diff --git a/.clang-format b/.clang-format index df053af05..7817490b8 100644 --- a/.clang-format +++ b/.clang-format @@ -11,6 +11,7 @@ AlignTrailingComments: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: Never AllowShortCaseLabelsOnASingleLine: false +AllowShortEnumsOnASingleLine: false AllowShortFunctionsOnASingleLine: None AllowShortIfStatementsOnASingleLine: Never AllowShortLoopsOnASingleLine: false @@ -20,24 +21,8 @@ AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: Yes BinPackArguments: true BinPackParameters: true -BraceWrapping: - AfterClass: true - AfterControlStatement: true - AfterEnum: true - AfterFunction: false - AfterNamespace: false - AfterObjCDeclaration: true - AfterStruct: true - AfterUnion: true - AfterCaseLabel: true - BeforeCatch: true - BeforeElse: true - IndentBraces: false - SplitEmptyFunction: true - SplitEmptyRecord: true - SplitEmptyNamespace: true BreakBeforeBinaryOperators: None -BreakBeforeBraces: Custom +BreakBeforeBraces: Attach BreakBeforeInheritanceComma: true BreakInheritanceList: BeforeColon BreakBeforeTernaryOperators: true diff --git a/AGENTS.md b/AGENTS.md index 155d33842..53a5d5538 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -87,12 +87,16 @@ branch or worktree when the existing checkout contains uncommitted changes. a top-level application source directory or split source headers into include/. Retain the current `app` CMake target and the `app`/`app_d` executable names. - Follow `.clang-format` and the repository formatting scripts with clang-format - 18. Keep function opening braces on the declaration line, expand short function - bodies, and use braces for control statements. + 18. Use attached opening braces for classes, structs, enums, unions, functions, + namespaces and control statements (`class example {`, `if (ready) {`). Keep + `} else {` and `} catch (...) {` together. Expand short function, enum and + control bodies, and use braces for control statements. - Group includes as system, third-party, then project headers. Keep required platform-header dependencies in a valid order. Separate include blocks, namespaces and adjacent definitions with the prescribed blank lines. - Run `CLANG_FORMAT=/path/to/clang-format bash scripts/format.sh --check`. +- Include first-party native tools in the same formatting scope as core, plugins, + examples and tests; do not leave the Entity exporter outside the check. - The formatter selects Git-tracked files. Stage intended new C++ files before running it, or format those paths explicitly. Run the complete check again after committing so newly tracked tests and headers cannot escape validation. diff --git a/benchmarks/database.cpp b/benchmarks/database.cpp index 0bae7f009..63d508b8b 100644 --- a/benchmarks/database.cpp +++ b/benchmarks/database.cpp @@ -42,8 +42,7 @@ using ark::detail::database_awaitable; using ark::detail::module_task; using ark::detail::module_task_group; -struct options -{ +struct options { std::string_view protocol{"redis"}; std::string_view mode{"callback"}; std::size_t concurrency{4}; @@ -60,8 +59,7 @@ struct options std::size_t number(std::string_view text, std::size_t minimum, std::size_t maximum) { std::size_t value{}; const auto parsed = std::from_chars(text.data(), text.data() + text.size(), value); - if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size() || value < minimum || value > maximum) - { + if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size() || value < minimum || value > maximum) { throw std::invalid_argument("Numeric argument is invalid or outside its documented bound"); } return value; @@ -69,66 +67,40 @@ std::size_t number(std::string_view text, std::size_t minimum, std::size_t maxim options parse(int argc, char** argv) { options result; - for (int index = 1; index < argc; index += 2) - { - if (index + 1 == argc) - { + for (int index = 1; index < argc; index += 2) { + if (index + 1 == argc) { throw std::invalid_argument("Each option requires a value; see --help"); } const std::string_view key(argv[index]), value(argv[index + 1]); - if (key == "--protocol") - { + if (key == "--protocol") { result.protocol = value; - } - else if (key == "--mode") - { + } else if (key == "--mode") { result.mode = value; - } - else if (key == "--concurrency") - { + } else if (key == "--concurrency") { result.concurrency = number(value, 1, 64); - } - else if (key == "--window") - { + } else if (key == "--window") { result.window = number(value, 1, 256); - } - else if (key == "--payload") - { + } else if (key == "--payload") { result.payload = number(value, 1, 65536); - } - else if (key == "--operations") - { + } else if (key == "--operations") { result.operations = number(value, 1, 1000000); - } - else if (key == "--warmup-operations") - { + } else if (key == "--warmup-operations") { result.warmup = number(value, 1, 100000); - } - else if (key == "--update-us") - { + } else if (key == "--update-us") { result.update_us = number(value, 0, 1000000); - } - else if (key == "--update-budget") - { + } else if (key == "--update-budget") { result.update_budget = number(value, 1, 4096); - } - else if (key == "--timeout-ms") - { + } else if (key == "--timeout-ms") { result.timeout_ms = number(value, 1, 30000); - } - else if (key == "--deadline-seconds") - { + } else if (key == "--deadline-seconds") { result.deadline_seconds = number(value, 1, 300); - } - else - { + } else { throw std::invalid_argument("Unknown option; credentials must be supplied through environment variables"); } } if ((result.protocol != "redis" && result.protocol != "mysql") || (result.mode != "callback" && result.mode != "coroutine") || result.concurrency > result.window || - result.operations < result.window || result.warmup < result.window) - { + result.operations < result.window || result.warmup < result.window) { throw std::invalid_argument( "Use redis|mysql, callback|coroutine and concurrency <= window <= warmup/operations"); } @@ -137,8 +109,7 @@ options parse(int argc, char** argv) { std::string environment(const char* name, bool allow_empty = false) { const auto* value = std::getenv(name); - if (!value || (!allow_empty && !*value)) - { + if (!value || (!allow_empty && !*value)) { throw std::invalid_argument(std::string("Required environment variable: ") + name); } return value; @@ -146,8 +117,7 @@ std::string environment(const char* name, bool allow_empty = false) { std::string binary_payload(std::size_t size) { std::string value(size, '\0'); - for (std::size_t index = 0; index < size; ++index) - { + for (std::size_t index = 0; index < size; ++index) { value[index] = static_cast(index % 256); } return value; @@ -156,8 +126,7 @@ std::string binary_payload(std::size_t size) { double cpu_seconds() { #if defined(_WIN32) FILETIME created{}, exited{}, kernel{}, user{}; - if (!GetProcessTimes(GetCurrentProcess(), &created, &exited, &kernel, &user)) - { + if (!GetProcessTimes(GetCurrentProcess(), &created, &exited, &kernel, &user)) { throw std::runtime_error("Cannot read process CPU time"); } const auto ticks = [](FILETIME value) { @@ -166,8 +135,7 @@ double cpu_seconds() { return static_cast(ticks(kernel) + ticks(user)) / 10000000.0; #else rusage usage{}; - if (getrusage(RUSAGE_SELF, &usage)) - { + if (getrusage(RUSAGE_SELF, &usage)) { throw std::runtime_error("Cannot read process CPU time"); } return static_cast(usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) + @@ -178,15 +146,13 @@ double cpu_seconds() { std::uint64_t peak_rss_bytes() { #if defined(_WIN32) PROCESS_MEMORY_COUNTERS memory{}; - if (!GetProcessMemoryInfo(GetCurrentProcess(), &memory, sizeof(memory))) - { + if (!GetProcessMemoryInfo(GetCurrentProcess(), &memory, sizeof(memory))) { throw std::runtime_error("Cannot read process resident memory"); } return memory.PeakWorkingSetSize; #else rusage usage{}; - if (getrusage(RUSAGE_SELF, &usage)) - { + if (getrusage(RUSAGE_SELF, &usage)) { throw std::runtime_error("Cannot read process resident memory"); } #if defined(__APPLE__) @@ -198,16 +164,14 @@ std::uint64_t peak_rss_bytes() { } double percentile(const std::vector& sorted, std::size_t percent) { - if (sorted.empty()) - { + if (sorted.empty()) { return 0; } const auto rank = (sorted.size() * percent + 99) / 100; return sorted[rank - 1]; } -struct errors -{ +struct errors { std::size_t native{}, exception{}, validation{}, admission{}, task{}, deadline{}; bool any() const { @@ -220,8 +184,7 @@ std::size_t input_budget(const options& config) { return config.window * (config.payload * 2 + 4096); } -struct redis_workload -{ +struct redis_workload { using result_type = arknet::redis::result; using service_type = ark::detail::redis_service; const std::string payload; @@ -231,12 +194,10 @@ struct redis_workload arknet::redis::pool_options pool; pool.connection.host = environment("ARK_DATABASE_REDIS_HOST"); pool.connection.port = std::to_string(number(environment("ARK_DATABASE_REDIS_PORT"), 1, 65535)); - if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) - { + if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) { pool.connection.username = user; } - if (const auto* password = std::getenv("ARK_DATABASE_REDIS_PASSWORD")) - { + if (const auto* password = std::getenv("ARK_DATABASE_REDIS_PASSWORD")) { pool.connection.password = password; } pool.max_connections = config.concurrency; @@ -255,12 +216,9 @@ struct redis_workload return service.start( {"ECHO", payload}, [completion = std::move(completion)](ark::detail::redis_service_result result) mutable { - if (auto* failure = std::get_if(&result)) - { + if (auto* failure = std::get_if(&result)) { completion(*failure, {}); - } - else - { + } else { completion({}, std::get(std::move(result))); } }, @@ -278,8 +236,7 @@ struct redis_workload }; #if defined(ARKNET_ENABLE_SSL) -struct mysql_workload -{ +struct mysql_workload { using result_type = ark::detail::mysql_service_reply; using service_type = ark::detail::mysql_service; const std::string payload; @@ -304,8 +261,7 @@ struct mysql_workload constexpr std::string_view digits = "0123456789abcdef"; std::string sql = "SELECT X'"; sql.reserve(payload.size() * 2 + 10); - for (const unsigned char byte : payload) - { + for (const unsigned char byte : payload) { sql += digits[byte >> 4]; sql += digits[byte & 15]; } @@ -323,12 +279,9 @@ struct mysql_workload return service.start_query( query, [completion = std::move(completion)](ark::detail::mysql_service_result result) mutable { - if (auto* failure = std::get_if(&result)) - { + if (auto* failure = std::get_if(&result)) { completion(*failure, {}); - } - else - { + } else { completion({}, std::get(std::move(result))); } }, @@ -340,8 +293,7 @@ struct mysql_workload } bool valid(const result_type& result) const { - if (result.result.columns.size() != 1 || result.result.rows.size() != 1 || result.result.rows[0].size() != 1) - { + if (result.result.columns.size() != 1 || result.result.rows.size() != 1 || result.result.rows[0].size() != 1) { return false; } const auto* value = std::get_if(&result.result.rows[0][0]); @@ -351,12 +303,10 @@ struct mysql_workload #endif template -class benchmark -{ +class benchmark { using result_type = typename Workload::result_type; - struct slot - { + struct slot { std::optional previous; clock_type::time_point submitted; bool active{}; @@ -375,8 +325,7 @@ class benchmark bool measured_{}, stopping_{}; bool begin(std::size_t index) { - if (stopping_ || errors_.any() || started_ == target_) - { + if (stopping_ || errors_.any() || started_ == target_) { return false; } ++started_; @@ -390,36 +339,26 @@ class benchmark auto& current = slots_[index]; // Timestamping and owning-result checks are identical in both modes. const auto delivered = clock_type::now(); - if (!current.active) - { + if (!current.active) { ++errors_.validation; return; } current.active = false; --active_; ++completed_; - if (measured_) - { + if (measured_) { latencies_.push_back(std::chrono::duration(delivered - current.submitted).count()); } - if (current.previous && !workload_.valid(*current.previous)) - { + if (current.previous && !workload_.valid(*current.previous)) { ++errors_.validation; } - if (failure) - { + if (failure) { ++errors_.exception; - } - else if (!workload_.success(result)) - { + } else if (!workload_.success(result)) { ++errors_.native; - } - else if (!workload_.valid(result)) - { + } else if (!workload_.valid(result)) { ++errors_.validation; - } - else - { + } else { ++successful_; current.previous = std::move(result); } @@ -428,54 +367,45 @@ class benchmark template std::uint64_t start(Handler handler) { const auto id = workload_.start(std::move(handler), std::chrono::milliseconds(config_.timeout_ms)); - if (!id) - { + if (!id) { ++errors_.admission; } return id; } void refill() { - for (std::size_t index = 0; index < slots_.size(); ++index) - { - if (!slots_[index].active && begin(index)) - { - try - { + for (std::size_t index = 0; index < slots_.size(); ++index) { + if (!slots_[index].active && begin(index)) { + try { start([this, index](std::exception_ptr error, result_type result) { receive(index, std::move(error), std::move(result)); }); + } catch (...) { + receive(index, std::current_exception(), {}); } - catch (...) - { receive(index, std::current_exception(), {}); } } } } module_task<> sequence(std::size_t index) { - while (begin(index)) - { - try - { + while (begin(index)) { + try { auto result = co_await bridge_.wait([this](auto completion) { return this->start(std::move(completion)); }, [this](std::uint64_t id) { workload_.service.cancel(id); }); receive(index, {}, std::move(result)); + } catch (...) { + receive(index, std::current_exception(), {}); } - catch (...) - { receive(index, std::current_exception(), {}); } } } void tick() { workload_.service.update(config_.update_budget); - if (config_.mode == "coroutine") - { + if (config_.mode == "coroutine") { bridge_.dispatch(config_.update_budget); tasks_.poll(config_.update_budget); - } - else if (!stopping_) - { + } else if (!stopping_) { // The service retires its reservation after returning from its // callback. Refill outside update(), without an extra request queue. refill(); @@ -483,34 +413,28 @@ class benchmark } void pause(clock_type::time_point& next) const { - if (config_.update_us) - { + if (config_.update_us) { next = std::max(next + std::chrono::microseconds(config_.update_us), clock_type::now()); std::this_thread::sleep_until(next); } } void cancel_and_drain() noexcept { - try - { + try { stopping_ = true; workload_.service.stop_accepting(); bridge_.stop_accepting(); tasks_.close(); workload_.service.cancel_all(); const auto deadline = clock_type::now() + std::chrono::milliseconds(config_.timeout_ms) + 10s; - while (active_ || tasks_.pending() || bridge_.pending()) - { + while (active_ || tasks_.pending() || bridge_.pending()) { tick(); - if (clock_type::now() >= deadline) - { + if (clock_type::now() >= deadline) { throw std::runtime_error("drain deadline"); } std::this_thread::sleep_for(100us); } - } - catch (...) - { + } catch (...) { // Never destroy suspended frames or report a fictitious drain. std::cerr << "Database benchmark failed to drain real terminal completions\n" << std::flush; std::_Exit(2); @@ -521,50 +445,37 @@ class benchmark started_ = completed_ = successful_ = 0; target_ = count; measured_ = measured; - try - { - if (config_.mode == "coroutine") - { - for (std::size_t index = 0; index < slots_.size(); ++index) - { + try { + if (config_.mode == "coroutine") { + for (std::size_t index = 0; index < slots_.size(); ++index) { if (!tasks_.start(sequence(index), [this](std::exception_ptr error) { - if (error) - { + if (error) { ++errors_.task; } - })) - { + })) { ++errors_.admission; break; } } - } - else - { + } else { refill(); } const auto deadline = clock_type::now() + std::chrono::seconds(config_.deadline_seconds); auto next = clock_type::now(); - while (active_ || tasks_.pending() || (!errors_.any() && completed_ < target_)) - { + while (active_ || tasks_.pending() || (!errors_.any() && completed_ < target_)) { tick(); - if (clock_type::now() >= deadline) - { + if (clock_type::now() >= deadline) { ++errors_.deadline; } - if (errors_.any()) - { + if (errors_.any()) { cancel_and_drain(); return; } - if (active_ || tasks_.pending() || completed_ < target_) - { + if (active_ || tasks_.pending() || completed_ < target_) { pause(next); } } - } - catch (...) - { + } catch (...) { ++errors_.exception; cancel_and_drain(); } @@ -588,8 +499,7 @@ class benchmark // the measured interval. Sorting, RSS inspection and shutdown follow it. const auto cpu_start = cpu_seconds(); const auto wall_start = clock_type::now(); - if (warmup_ok) - { + if (warmup_ok) { phase(config_.operations, true); } const double seconds = std::chrono::duration(clock_type::now() - wall_start).count(); @@ -600,8 +510,7 @@ class benchmark tasks_.close(); workload_.service.stop(); const auto diagnostics = workload_.service.diagnostics(); - if (diagnostics.cancellation_submission || diagnostics.lease_return || bridge_.cancellation_exception()) - { + if (diagnostics.cancellation_submission || diagnostics.lease_return || bridge_.cancellation_exception()) { ++errors_.exception; } const bool valid = @@ -642,20 +551,17 @@ class benchmark void self_test() { const auto bytes = binary_payload(513); if (bytes.size() != 513 || bytes[0] != '\0' || static_cast(bytes[255]) != 255 || - bytes[256] != '\0' || percentile({1, 2, 3, 4}, 50) != 2 || percentile({1, 2, 3, 4}, 99) != 4) - { + bytes[256] != '\0' || percentile({1, 2, 3, 4}, 50) != 2 || percentile({1, 2, 3, 4}, 99) != 4) { throw std::runtime_error("Binary payload or nearest-rank percentile self-test failed"); } const std::vector hundred = [] { std::vector result; - for (unsigned value = 1; value <= 100; ++value) - { + for (unsigned value = 1; value <= 100; ++value) { result.push_back(value); } return result; }(); - if (percentile(hundred, 50) != 50 || percentile(hundred, 99) != 99 || !peak_rss_bytes() || cpu_seconds() < 0) - { + if (percentile(hundred, 50) != 50 || percentile(hundred, 99) != 99 || !peak_rss_bytes() || cpu_seconds() < 0) { throw std::runtime_error("Resource/percentile self-test failed"); } std::cout << "Database benchmark local self-tests passed\n"; @@ -664,15 +570,12 @@ void self_test() { } // namespace int main(int argc, char** argv) { - try - { - if (argc == 2 && std::string_view(argv[1]) == "--self-test") - { + try { + if (argc == 2 && std::string_view(argv[1]) == "--self-test") { self_test(); return 0; } - if (argc == 2 && std::string_view(argv[1]) == "--help") - { + if (argc == 2 && std::string_view(argv[1]) == "--help") { std::cout << "ark_database_benchmark --protocol redis|mysql --mode callback|coroutine\n" " --concurrency 1..64 --window 1..256 --payload 1..65536\n" " --operations 1..1000000 --warmup-operations 1..100000\n" @@ -684,8 +587,7 @@ int main(int argc, char** argv) { return 0; } const auto config = parse(argc, argv); - if (config.protocol == "redis") - { + if (config.protocol == "redis") { return benchmark(config).run(); } #if defined(ARKNET_ENABLE_SSL) @@ -693,9 +595,7 @@ int main(int argc, char** argv) { #else throw std::invalid_argument("MySQL benchmark requires ARKNET_ENABLE_SSL=ON"); #endif - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { std::cerr << error.what() << '\n'; return 1; } diff --git a/benchmarks/entity_operations.cpp b/benchmarks/entity_operations.cpp index 46f326ada..2d528e506 100644 --- a/benchmarks/entity_operations.cpp +++ b/benchmarks/entity_operations.cpp @@ -18,8 +18,7 @@ namespace ark { -class entity_operations_benchmark -{ +class entity_operations_benchmark { public: entity_operations_benchmark(kernel_module& kernel, bool timed, std::ostream& output) : kernel_module_(&kernel) @@ -43,8 +42,7 @@ class entity_operations_benchmark void entity_operations_benchmark::query_string_test(const guid_t& guid, size_t count, const uint32_t index) { auto entity_ptr = kernel_module_->get_entity(guid); - if (nullptr == entity_ptr) - { + if (nullptr == entity_ptr) { return; } @@ -52,8 +50,7 @@ void entity_operations_benchmark::query_string_test(const guid_t& guid, size_t c // query string data with int key auto begin = now(); - for (size_t i = 0; i < count; i++) - { + for (size_t i = 0; i < count; i++) { auto& value = entity_ptr->get_string(entity_meta_player::name_index()); } auto end = now(); @@ -61,8 +58,7 @@ void entity_operations_benchmark::query_string_test(const guid_t& guid, size_t c // query string data with string key begin = now(); - for (size_t i = 0; i < count; i++) - { + for (size_t i = 0; i < count; i++) { auto& value = entity_ptr->get_string(entity_meta_player::name()); } end = now(); @@ -73,11 +69,9 @@ void entity_operations_benchmark::query_string_test(const guid_t& guid, size_t c // query string data with int key begin = now(); - for (size_t i = 0; i < count; i++) - { + for (size_t i = 0; i < count; i++) { auto obj_ptr = kernel_module_->get_entity(guid); - if (nullptr == obj_ptr) - { + if (nullptr == obj_ptr) { return; } @@ -88,11 +82,9 @@ void entity_operations_benchmark::query_string_test(const guid_t& guid, size_t c // query string data with string key begin = now(); - for (size_t i = 0; i < count; i++) - { + for (size_t i = 0; i < count; i++) { auto obj_ptr = kernel_module_->get_entity(guid); - if (nullptr == obj_ptr) - { + if (nullptr == obj_ptr) { return; } @@ -109,8 +101,7 @@ void entity_operations_benchmark::query_string_test(const guid_t& guid, size_t c void entity_operations_benchmark::query_int_test(const guid_t& guid, size_t count, const uint32_t index) { auto entity_ptr = kernel_module_->get_entity(guid); - if (nullptr == entity_ptr) - { + if (nullptr == entity_ptr) { return; } @@ -118,8 +109,7 @@ void entity_operations_benchmark::query_int_test(const guid_t& guid, size_t coun // query string data with int key auto begin = now(); - for (size_t i = 0; i < count; i++) - { + for (size_t i = 0; i < count; i++) { auto value = entity_ptr->get_int32(entity_meta_player::gender_index()); } auto end = now(); @@ -127,8 +117,7 @@ void entity_operations_benchmark::query_int_test(const guid_t& guid, size_t coun // query string data with string key begin = now(); - for (size_t i = 0; i < count; i++) - { + for (size_t i = 0; i < count; i++) { auto value = entity_ptr->get_int32(entity_meta_player::gender()); } end = now(); @@ -139,11 +128,9 @@ void entity_operations_benchmark::query_int_test(const guid_t& guid, size_t coun // query string data with int key begin = now(); - for (size_t i = 0; i < count; i++) - { + for (size_t i = 0; i < count; i++) { auto obj_ptr = kernel_module_->get_entity(guid); - if (nullptr == obj_ptr) - { + if (nullptr == obj_ptr) { return; } @@ -154,11 +141,9 @@ void entity_operations_benchmark::query_int_test(const guid_t& guid, size_t coun // query string data with string key begin = now(); - for (size_t i = 0; i < count; i++) - { + for (size_t i = 0; i < count; i++) { auto obj_ptr = kernel_module_->get_entity(guid); - if (nullptr == obj_ptr) - { + if (nullptr == obj_ptr) { return; } @@ -175,8 +160,7 @@ void entity_operations_benchmark::query_int_test(const guid_t& guid, size_t coun void entity_operations_benchmark::set_data_test(const guid_t& guid, size_t count, const uint32_t index) { auto entity_ptr = kernel_module_->get_entity(guid); - if (nullptr == entity_ptr) - { + if (nullptr == entity_ptr) { return; } @@ -184,8 +168,7 @@ void entity_operations_benchmark::set_data_test(const guid_t& guid, size_t count // set data with int key auto begin = now(); - for (size_t i = 0; i < count; i++) - { + for (size_t i = 0; i < count; i++) { entity_ptr->set_int32(entity_meta_player::gender_index(), 22); } auto end = now(); @@ -193,8 +176,7 @@ void entity_operations_benchmark::set_data_test(const guid_t& guid, size_t count // set data with string key begin = now(); - for (size_t i = 0; i < count; i++) - { + for (size_t i = 0; i < count; i++) { entity_ptr->set_int32(entity_meta_player::gender(), 22); } end = now(); @@ -205,11 +187,9 @@ void entity_operations_benchmark::set_data_test(const guid_t& guid, size_t count // set data with int key begin = now(); - for (size_t i = 0; i < count; i++) - { + for (size_t i = 0; i < count; i++) { auto obj_ptr = kernel_module_->get_entity(guid); - if (nullptr == obj_ptr) - { + if (nullptr == obj_ptr) { return; } @@ -220,11 +200,9 @@ void entity_operations_benchmark::set_data_test(const guid_t& guid, size_t count // set data with string key begin = now(); - for (size_t i = 0; i < count; i++) - { + for (size_t i = 0; i < count; i++) { auto obj_ptr = kernel_module_->get_entity(guid); - if (nullptr == obj_ptr) - { + if (nullptr == obj_ptr) { return; } @@ -242,23 +220,19 @@ void entity_operations_benchmark::set_data_test(const guid_t& guid, size_t count } // namespace ark int main(int argc, char* argv[]) { - if ((argc != 4 && argc != 5) || std::string(argv[1]) != "--plugin-dir") - { + if ((argc != 4 && argc != 5) || std::string(argv[1]) != "--plugin-dir") { std::cerr << "Usage: ark_entity_operations_benchmark --plugin-dir DIR --smoke | --iterations N" << std::endl; return 2; } const bool smoke = argc == 4 && std::string(argv[3]) == "--smoke"; std::size_t iterations = 8; - if (!smoke) - { - if (argc != 5 || std::string(argv[3]) != "--iterations") - { + if (!smoke) { + if (argc != 5 || std::string(argv[3]) != "--iterations") { return 2; } const std::string text = argv[4]; const auto result = std::from_chars(text.data(), text.data() + text.size(), iterations); - if (result.ec != std::errc{} || result.ptr != text.data() + text.size() || iterations == 0) - { + if (result.ec != std::errc{} || result.ptr != text.data() + text.size() || iterations == 0) { return 2; } } @@ -266,22 +240,20 @@ int main(int argc, char* argv[]) { ark::logger::init(&log); log.set_log_func([](spdlog::level::level_enum, const std::string& text) { std::cout << text << '\n'; }); ark::plugin_manager manager; - if (!manager.start(0, std::string(argv[2]) + "/", "conf/", {{"ark_kernel_plugin", ""}, {"ark_utility_plugin", ""}})) - { + if (!manager.start( + 0, std::string(argv[2]) + "/", "conf/", {{"ark_kernel_plugin", ""}, {"ark_utility_plugin", ""}})) { std::cerr << "Benchmark dependency startup failed: " << manager.get_startup_failure() << std::endl; std::_Exit(1); } auto* kernel = manager.find_module(); auto* maps = manager.find_module(); - if (!kernel || !maps || !maps->create_map(1)) - { + if (!kernel || !maps || !maps->create_map(1)) { std::_Exit(1); } auto player = kernel->create_entity( ark::null_guid, 1, 0, ark::entity_meta_player::self_name(), ark::null_int, ark::data_list_impl{}); if (!player || !player->set_string(ark::entity_meta_player::name(), "Xiaoming") || - !player->set_int32(ark::entity_meta_player::gender(), 1)) - { + !player->set_int32(ark::entity_meta_player::gender(), 1)) { std::_Exit(1); } std::ostringstream quiet; @@ -290,14 +262,12 @@ int main(int argc, char* argv[]) { workload.query_int_test(player->get_id(), iterations, 1); workload.set_data_test(player->get_id(), iterations, 1); if (player->get_string(ark::entity_meta_player::name_index()) != "Xiaoming" || - player->get_int32(ark::entity_meta_player::gender()) != 11) - { + player->get_int32(ark::entity_meta_player::gender()) != 11) { std::_Exit(1); } const auto id = player->get_id(); player.reset(); - if (!kernel->destroy_entity(id)) - { + if (!kernel->destroy_entity(id)) { std::_Exit(1); } const auto shutdown_deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); @@ -309,36 +279,30 @@ int main(int argc, char* argv[]) { // Do not unwind retained callbacks/DSOs or report timeout as success. std::_Exit(1); }; - try - { - while (!manager.stop_until(++tick, shutdown_deadline)) - { - if (const auto error = manager.get_shutdown_exception()) - { + try { + while (!manager.stop_until(++tick, shutdown_deadline)) { + if (const auto error = manager.get_shutdown_exception()) { std::rethrow_exception(error); } const auto state = manager.get_shutdown_state(); - if (state != ark::plugin_manager::shutdown_state::stopping || !manager.get_shutdown_failure().empty()) - { + if (state != ark::plugin_manager::shutdown_state::stopping || !manager.get_shutdown_failure().empty()) { fail_shutdown("terminal shutdown state"); } - if (std::chrono::steady_clock::now() >= shutdown_deadline) - { + if (std::chrono::steady_clock::now() >= shutdown_deadline) { fail_shutdown("cooperative deadline reached"); } // Startup used the synthetic timestamp zero. Keep its clock domain // while pumping accepted completions; never jump to wall-clock time. - if (!manager.update(++tick)) - { + if (!manager.update(++tick)) { fail_shutdown("owner update failed during drain"); } std::this_thread::yield(); } + } catch (const std::exception& error) { + fail_shutdown(error.what()); + } catch (...) { + fail_shutdown("nonstandard exception during drain"); } - catch (const std::exception& error) - { fail_shutdown(error.what()); } - catch (...) - { fail_shutdown("nonstandard exception during drain"); } std::cout << (smoke ? "Entity workload smoke passed: 8 iterations per loop; timing disabled" : "Entity workload completed") << std::endl; diff --git a/benchmarks/network_buffers.cpp b/benchmarks/network_buffers.cpp index 8426984d9..c8c48521e 100644 --- a/benchmarks/network_buffers.cpp +++ b/benchmarks/network_buffers.cpp @@ -36,8 +36,7 @@ std::size_t array_bytes{}; std::size_t object_allocations{}; std::size_t object_bytes{}; -struct benchmark_options -{ +struct benchmark_options { std::string_view mode{"framing"}; std::size_t sessions{10000}; std::size_t iterations{200000}; @@ -51,8 +50,7 @@ struct benchmark_options std::size_t parse_number(std::string_view text, bool allow_zero = false) { std::size_t value{}; const auto result = std::from_chars(text.data(), text.data() + text.size(), value); - if (result.ec != std::errc{} || result.ptr != text.data() + text.size() || (!allow_zero && value == 0)) - { + if (result.ec != std::errc{} || result.ptr != text.data() + text.size() || (!allow_zero && value == 0)) { throw std::invalid_argument(allow_zero ? "Expected a nonnegative integer" : "Expected a positive integer"); } return value; @@ -60,82 +58,57 @@ std::size_t parse_number(std::string_view text, bool allow_zero = false) { benchmark_options parse_options(int argc, char** argv) { benchmark_options options; - for (int i = 1; i < argc; i += 2) - { + for (int i = 1; i < argc; i += 2) { const std::string_view key(argv[i]); - if (i + 1 >= argc) - { + if (i + 1 >= argc) { throw std::invalid_argument("Each option requires a value"); } const std::string_view value(argv[i + 1]); - if (key == "--mode") - { + if (key == "--mode") { options.mode = value; - } - else if (key == "--sessions") - { + } else if (key == "--sessions") { options.sessions = parse_number(value); - } - else if (key == "--iterations") - { + } else if (key == "--iterations") { options.iterations = parse_number(value); - } - else if (key == "--warmup-iterations") - { + } else if (key == "--warmup-iterations") { options.warmup = parse_number(value, true); - } - else if (key == "--payload") - { + } else if (key == "--payload") { options.payload = parse_number(value); - } - else if (key == "--batch") - { + } else if (key == "--batch") { options.batch = parse_number(value); - } - else if (key == "--initial-buffer") - { + } else if (key == "--initial-buffer") { options.initial_buffer = parse_number(value); - } - else if (key == "--chunk") - { + } else if (key == "--chunk") { options.chunk = parse_number(value); - } - else - { + } else { throw std::invalid_argument("Unknown option: " + std::string(key)); } } - if ((options.mode != "sessions" && options.mode != "framing") || options.payload > ark::ark_msg_max_length) - { + if ((options.mode != "sessions" && options.mode != "framing") || options.payload > ark::ark_msg_max_length) { throw std::invalid_argument("Use --mode sessions|framing and payloads within ark_msg_max_length"); } - if (options.iterations > std::numeric_limits::max() / options.batch) - { + if (options.iterations > std::numeric_limits::max() / options.batch) { throw std::invalid_argument("The total message count exceeds the addressable range"); } return options; } void check(bool value) { - if (!value) - { + if (!value) { throw std::runtime_error("Frame content or message count mismatch"); } } void parse_frames(ark::tcp_client_session& session, std::string_view frame, std::string_view body, const benchmark_options& options, std::size_t iterations) { - for (std::size_t i = 0; i < iterations; ++i) - { - for (std::size_t pos = 0; pos < frame.size();) - { + for (std::size_t i = 0; i < iterations; ++i) { + for (std::size_t pos = 0; pos < frame.size();) { const auto count = std::min(options.chunk, frame.size() - pos); session.add_buffer(frame.data() + pos, count); check(session.parse_buffer_to_msg()); pos += count; } - for (std::size_t j = 0; j < options.batch; ++j) - { + for (std::size_t j = 0; j < options.batch; ++j) { ark::net_msg* message{}; check(session.pop_net_msg(message)); const bool valid = message->get_msg_id() == 7 && message->get_msg_length() == body.size() && @@ -151,8 +124,7 @@ void parse_frames(ark::tcp_client_session& session, std::string_view frame, std: double process_cpu_seconds() { #if defined(_WIN32) FILETIME created{}, exited{}, kernel{}, user{}; - if (!GetProcessTimes(GetCurrentProcess(), &created, &exited, &kernel, &user)) - { + if (!GetProcessTimes(GetCurrentProcess(), &created, &exited, &kernel, &user)) { throw std::runtime_error("Cannot read process CPU usage"); } const auto ticks = [](const FILETIME& value) { @@ -167,17 +139,13 @@ double process_cpu_seconds() { template std::unique_ptr make_session( const std::shared_ptr& header, ark::conv_id_t id, std::size_t capacity) { - if (!capacity) - { + if (!capacity) { return std::make_unique(header, id); } if constexpr (std::constructible_from, ark::conv_id_t, - std::nullptr_t, std::size_t>) - { + std::nullptr_t, std::size_t>) { return std::make_unique(header, id, nullptr, capacity); - } - else - { + } else { throw std::invalid_argument("This ark revision does not support --initial-buffer"); } } @@ -191,30 +159,24 @@ void run_benchmark(const benchmark_options& options) { header->serialize_to_string(frame); frame += body; const auto single = frame; - for (std::size_t i = 1; i < options.batch; ++i) - { + for (std::size_t i = 1; i < options.batch; ++i) { frame += single; } std::vector> sessions; sessions.reserve(options.mode == "sessions" ? options.sessions : 1); - if (options.mode == "framing") - { + if (options.mode == "framing") { sessions.push_back(make_session(header, 1, options.initial_buffer)); parse_frames(*sessions.front(), frame, body, options, options.warmup); } const auto cpu_start = process_cpu_seconds(); const auto start = std::chrono::steady_clock::now(); count_allocations = true; - if (options.mode == "sessions") - { - for (std::size_t i = 0; i < options.sessions; ++i) - { + if (options.mode == "sessions") { + for (std::size_t i = 0; i < options.sessions; ++i) { sessions.push_back(make_session(header, i + 1, options.initial_buffer)); } - } - else - { + } else { parse_frames(*sessions.front(), frame, body, options, options.iterations); } count_allocations = false; @@ -240,10 +202,8 @@ void run_benchmark(const benchmark_options& options) { // Count ordinary C++ requests; aligned allocations, queue-internal malloc calls // and socket buffers are outside these metrics. This program runs on one thread. void* operator new(std::size_t size) { - if (void* value = std::malloc(size == 0 ? 1 : size)) - { - if (count_allocations) - { + if (void* value = std::malloc(size == 0 ? 1 : size)) { + if (count_allocations) { ++object_allocations; object_bytes += size; } @@ -261,10 +221,8 @@ void operator delete(void* value, std::size_t) noexcept { } void* operator new[](std::size_t size) { - if (void* value = std::malloc(size == 0 ? 1 : size)) - { - if (count_allocations) - { + if (void* value = std::malloc(size == 0 ? 1 : size)) { + if (count_allocations) { ++array_allocations; array_bytes += size; } @@ -282,19 +240,15 @@ void operator delete[](void* value, std::size_t) noexcept { } int main(int argc, char** argv) { - try - { - if (argc == 2 && std::string_view(argv[1]) == "--help") - { + try { + if (argc == 2 && std::string_view(argv[1]) == "--help") { std::cout << "Usage: ark_network_buffer_benchmark --mode sessions|framing\n" " [--sessions N] [--iterations N] [--payload BYTES] [--chunk BYTES] [--batch N]\n" " [--warmup-iterations N] [--initial-buffer BYTES]\n"; return 0; } run_benchmark(parse_options(argc, argv)); - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { std::cerr << error.what() << '\n'; return 1; } diff --git a/examples/entity_operations/entity_operations_module.cpp b/examples/entity_operations/entity_operations_module.cpp index a9d593bfa..8d310dc84 100644 --- a/examples/entity_operations/entity_operations_module.cpp +++ b/examples/entity_operations/entity_operations_module.cpp @@ -142,8 +142,7 @@ void entity_operations_module::destroy_test() { ARK_LOG_DEBUG("DestroyTest Start..."); size_t count = 1; - for (size_t i = 0; i < count; i++) - { + for (size_t i = 0; i < count; i++) { auto entity_ptr = create_an_player_and_init(); kernel_module_->destroy_entity(entity_ptr->get_id()); } @@ -234,8 +233,7 @@ std::shared_ptr entity_operations_module::create_an_player_and_init ARK_ASSERT_RET_VAL(row_ptr != nullptr, nullptr); row_ptr->set_int64(col_guid, 1111); - if (!entity_ptr->find_custom_data("test")) - { + if (!entity_ptr->find_custom_data("test")) { entity_ptr->add_custom_int32("test", 111); } @@ -249,13 +247,11 @@ void entity_operations_module::custom_data_test(const guid_t& guid, size_t count std::cout << "----------[index] time [custom data] test start----------" << std::endl; auto entity_ptr = kernel_module_->get_entity(guid); - if (nullptr == entity_ptr) - { + if (nullptr == entity_ptr) { return; } - if (!entity_ptr->find_custom_data("test") && !entity_ptr->add_custom_int32("test", 0)) - { + if (!entity_ptr->find_custom_data("test") && !entity_ptr->add_custom_int32("test", 0)) { return; } @@ -271,8 +267,7 @@ int entity_operations_module::on_class_call_back_event( std::cout << "ClassName: " << class_name << " ID: " << self << " Event: " << (int)event << std::endl; - if (event == entity_event::entity_evt_data_finished) - { + if (event == entity_event::entity_evt_data_finished) { // } @@ -297,12 +292,9 @@ int entity_operations_module::on_table_call_back_event( const guid_t& self, const table_event_data& data, const ark::data& old_value, const ark::data& new_value) { std::cout << "---------- OnTableCallBackEvent start----------" << std::endl; - if (data.op_type == (size_t)table_op_type::table_add) - { + if (data.op_type == (size_t)table_op_type::table_add) { std::cout << "table name: " << data.table_name << " row : " << data.row << std::endl; - } - else - { + } else { std::cout << "table name: " << data.table_name << " row : " << data.row << " data index : " << data.data_index << " old value : " << old_value.to_string() << " new value : " << new_value.to_string() << std::endl; } diff --git a/examples/entity_operations/entity_operations_module.hpp b/examples/entity_operations/entity_operations_module.hpp index d563e0fb9..f8c639be3 100644 --- a/examples/entity_operations/entity_operations_module.hpp +++ b/examples/entity_operations/entity_operations_module.hpp @@ -26,8 +26,7 @@ namespace ark { -class entity_operations_module final : public module_base -{ +class entity_operations_module final : public module_base { public: explicit entity_operations_module() = default; diff --git a/examples/entity_operations/entity_operations_plugin.cpp b/examples/entity_operations/entity_operations_plugin.cpp index 8c0e656a5..362231d49 100644 --- a/examples/entity_operations/entity_operations_plugin.cpp +++ b/examples/entity_operations/entity_operations_plugin.cpp @@ -34,15 +34,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void entity_operations_plugin::install() { - if (!register_module(make_entity_operations_module(), module_update::disabled)) - { + if (!register_module(make_entity_operations_module(), module_update::disabled)) { throw std::runtime_error("entity_operations module registration rejected"); } } void entity_operations_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("entity_operations module unregistration rejected"); } } diff --git a/examples/entity_operations/entity_operations_plugin.hpp b/examples/entity_operations/entity_operations_plugin.hpp index 6268361e2..61dab2533 100644 --- a/examples/entity_operations/entity_operations_plugin.hpp +++ b/examples/entity_operations/entity_operations_plugin.hpp @@ -29,8 +29,7 @@ namespace ark { std::unique_ptr make_entity_operations_module(); -class entity_operations_plugin final : public plugin_base -{ +class entity_operations_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/examples/guest_room/guest_room_module.cpp b/examples/guest_room/guest_room_module.cpp index 4b1e013c3..d7697b51b 100644 --- a/examples/guest_room/guest_room_module.cpp +++ b/examples/guest_room/guest_room_module.cpp @@ -12,8 +12,7 @@ namespace ark::guest_room { void room_module::owner_thread() const { - if (std::this_thread::get_id() != owner_) - { + if (std::this_thread::get_id() != owner_) { throw std::logic_error("guest_room state accessed outside the launcher owner thread"); } } @@ -28,58 +27,47 @@ bool room_module::pre_update() { owner_thread(); auto* maps = find_module(); auto* network = find_module(); - if (maps == nullptr || network == nullptr || !maps->create_map(1)) - { + if (maps == nullptr || network == nullptr || !maps->create_map(1)) { return false; } const auto profile = kernel_->get_static_entity(1); - if (!profile || profile->get_class_name() != "GuestPlayer") - { + if (!profile || profile->get_class_name() != "GuestPlayer") { throw std::runtime_error("guest_room requires GuestPlayer Entity schema and configuration profile 1"); } auto probe = kernel_->create_entity(null_guid, 1, 0, "GuestPlayer", 1, data_list_impl()); - if (!probe) - { + if (!probe) { throw std::runtime_error("guest_room cannot create the configured GuestPlayer Entity"); } const std::vector fields{"name", "x", "y", "move_seq", "hp", "mp", "hp_max", "mp_max", "action_seq"}; - for (std::size_t offset = 0; offset < fields.size(); ++offset) - { + for (std::size_t offset = 0; offset < fields.size(); ++offset) { const auto index = static_cast(100 + offset); const auto type = offset == 0 ? data_type::dt_string : offset <= 2 ? data_type::dt_double : data_type::dt_uint32; - if (probe->get_index(fields[offset]) != index || probe->get_node_type(fields[offset]) != type) - { + if (probe->get_index(fields[offset]) != index || probe->get_node_type(fields[offset]) != type) { throw std::runtime_error("guest_room requires the declared GuestPlayer field: " + fields[offset]); } } - if (!kernel_->destroy_entity(probe->get_id())) - { + if (!kernel_->destroy_entity(probe->get_id())) { throw std::runtime_error("guest_room cannot retire its startup schema validation Entity"); } probe.reset(); if (profile->get_u_int32("hp_max") == 0 || profile->get_u_int32("mp_max") == 0 || profile->get_u_int32("hp") > profile->get_u_int32("hp_max") || profile->get_u_int32("mp") > profile->get_u_int32("mp_max") || profile->get_u_int32("move_seq") != 0 || - profile->get_u_int32("action_seq") != 0) - { + profile->get_u_int32("action_seq") != 0) { throw std::runtime_error( "guest_room profile 1 requires bounded HP/MP, positive maxima and zero initial sequences"); } - if (!network->create_server(60000, header(true), header(true))) - { + if (!network->create_server(60000, header(true), header(true))) { return false; } server_ = network->get_inter_net_server(); - if (server_ == nullptr) - { + if (server_ == nullptr) { return false; } - for (const auto id : {join, move, action, ping, unsupported}) - { - if (!server_->reg_msg_callback(id, this, &room_module::on_message)) - { + for (const auto id : {join, move, action, ping, unsupported}) { + if (!server_->reg_msg_callback(id, this, &room_module::on_message)) { return false; } } @@ -89,14 +77,12 @@ bool room_module::pre_update() { } void room_module::enqueue(peer& connection, msg_id_t id, const google::protobuf::MessageLite& body) { - if (connection.closing) - { + if (connection.closing) { return; } std::string text; if (body.ByteSizeLong() > max_body || !body.SerializeToString(&text) || connection.pending.size() >= 8 || - text.size() + 12 > 8 * (max_body + 12) - connection.pending_bytes) - { + text.size() + 12 > 8 * (max_body + 12) - connection.pending_bytes) { connection.closing = true; connection.pending.clear(); connection.pending_bytes = 0; @@ -114,12 +100,10 @@ void room_module::reject(peer& connection, const std::string& code, const std::s } void room_module::retire(peer& connection) { - if (!connection.player) - { + if (!connection.player) { return; } - if (connection.publisher) - { + if (connection.publisher) { removed_.emplace_back(connection.publisher->remove(), connection.binding); connection.publisher.reset(); } @@ -127,16 +111,13 @@ void room_module::retire(peer& connection) { } void room_module::release_player(peer& connection) { - for (auto& equipment : connection.equipment) - { - if (equipment) - { + for (auto& equipment : connection.equipment) { + if (equipment) { kernel_->destroy_entity(equipment->get_id()); equipment.reset(); } } - if (!connection.player) - { + if (!connection.player) { return; } kernel_->destroy_entity(connection.player->get_id()); @@ -148,23 +129,19 @@ void room_module::flush_room() { wire::room_delta changes; changes.set_room("lobby"); // Each active Entity is captured once at this explicit owner-thread flush. - for (auto& [session, connection] : peers_) - { - if (connection.closing) - { + for (auto& [session, connection] : peers_) { + if (connection.closing) { retire(connection); continue; } - if (!connection.player) - { + if (!connection.player) { continue; } const std::array equipment{connection.equipment[0]->get_id(), connection.equipment[1]->get_id()}; auto state = kernel_->capture_nested_snapshot(*connection.player, player_projection(connection.player->get_id(), equipment), player_limits().stream.snapshot); validate_player(state); - if (!connection.publisher) - { + if (!connection.publisher) { connection.binding = { player_schema, connection.player->get_id(), state.root.incarnation, 1, player_layout(equipment)}; entity_sync::nested_baseline initial{1, 1, std::move(state)}; @@ -174,33 +151,24 @@ void room_module::flush_room() { added.set_player_id(connection.player_id); encode_binding(connection.binding, *added.mutable_binding()); encode(initial, *added.mutable_state(), connection.binding); - } - else - { - if (const auto changed = connection.publisher->update(state)) - { + } else { + if (const auto changed = connection.publisher->update(state)) { encode(*changed, *changes.add_changed(), connection.binding); } } } - for (const auto& [removed, binding] : removed_) - { + for (const auto& [removed, binding] : removed_) { encode(*removed, *changes.add_changed(), binding); } - for (auto& [session, connection] : peers_) - { - if (!connection.player || connection.closing) - { + for (auto& [session, connection] : peers_) { + if (!connection.player || connection.closing) { continue; } - if (connection.needs_baseline) - { + if (connection.needs_baseline) { wire::room_baseline baseline; baseline.set_room("lobby"); - for (const auto& [other_session, other] : peers_) - { - if (other.player && !other.closing) - { + for (const auto& [other_session, other] : peers_) { + if (other.player && !other.closing) { auto& added = *baseline.add_players(); added.set_player_id(other.player_id); encode_binding(other.binding, *added.mutable_binding()); @@ -209,9 +177,7 @@ void room_module::flush_room() { } enqueue(connection, snapshot, baseline); connection.needs_baseline = false; - } - else if (changes.added_size() != 0 || changes.changed_size() != 0) - { + } else if (changes.added_size() != 0 || changes.changed_size() != 0) { enqueue(connection, delta, changes); } } @@ -219,27 +185,23 @@ void room_module::flush_room() { } void room_module::join_room(peer& connection, const wire::join_request& body) { - if (connection.player != nullptr) - { + if (connection.player != nullptr) { reject(connection, "already_joined", "This session already joined the lobby"); return; } - if (body.protocol_version() != protocol_version || !valid_name(body.name()) || body.room() != "lobby") - { + if (body.protocol_version() != protocol_version || !valid_name(body.name()) || body.room() != "lobby") { reject(connection, "invalid_message", "Expected the current protocol, lobby and a name of 1..64 UTF-8 bytes without controls"); return; } const auto count = std::count_if(peers_.begin(), peers_.end(), [](const auto& entry) { return entry.second.player != nullptr; }); - if (count >= 16) - { + if (count >= 16) { reject(connection, "room_full", "The lobby has 16 players"); return; } auto player = kernel_->create_entity(null_guid, 1, 0, "GuestPlayer", 1, data_list_impl()); - if (player == nullptr) - { + if (player == nullptr) { throw std::runtime_error("guest_room Kernel entity creation failed"); } // Typed setters report false for unchanged values; the schema was checked at startup. @@ -248,39 +210,31 @@ void room_module::join_room(peer& connection, const wire::join_request& body) { player->set_double("y", 100.0 + static_cast(((next_player_ - 1) / 8) % 2) * 200.0); connection.player_id = std::to_string(next_player_++); connection.player = std::move(player); - try - { + try { auto* inventory = connection.player->find_table(inventory_index); auto container = connection.player->find_container(equipment_index); - if (inventory == nullptr || !container) - { + if (inventory == nullptr || !container) { throw std::runtime_error("GuestPlayer requires inventory and equipment members"); } auto* potion = inventory->add_row(1); - if (potion == nullptr) - { + if (potion == nullptr) { throw std::runtime_error("Cannot initialize inventory row"); } potion->set_u_int32(1, 1); potion->set_u_int32(2, 2); - for (std::size_t i = 0; i < connection.equipment.size(); ++i) - { + for (std::size_t i = 0; i < connection.equipment.size(); ++i) { auto child = kernel_->create_entity(null_guid, 1, 0, "GuestEquipment", 0, data_list_impl()); - if (!child) - { + if (!child) { throw std::runtime_error("Cannot create equipment Entity"); } connection.equipment[i] = child; child->set_u_int32(1, 1001 + static_cast(i)); child->set_u_int32(2, 10 + 10 * static_cast(i)); } - if (!container->place(1, connection.equipment[0])) - { + if (!container->place(1, connection.equipment[0])) { throw std::runtime_error("Cannot equip initial item"); } - } - catch (...) - { + } catch (...) { release_player(connection); throw; } @@ -296,21 +250,18 @@ void room_module::join_room(peer& connection, const wire::join_request& body) { } void room_module::move_player(peer& connection, const wire::move_request& body) { - if (connection.player == nullptr) - { + if (connection.player == nullptr) { reject(connection, "not_joined", "Join the lobby before moving"); return; } const auto sequence = body.sequence(); const auto x = body.x(); const auto y = body.y(); - if (!std::isfinite(x) || !std::isfinite(y) || x < 0 || x > 960 || y < 0 || y > 540) - { + if (!std::isfinite(x) || !std::isfinite(y) || x < 0 || x > 960 || y < 0 || y > 540) { reject(connection, "invalid_message", "Coordinates must be within 0..960 and 0..540"); return; } - if (sequence <= connection.player->get_u_int32("move_seq")) - { + if (sequence <= connection.player->get_u_int32("move_seq")) { reject(connection, "stale_sequence", "Movement sequence must strictly increase from 1"); return; } @@ -328,107 +279,77 @@ void room_module::act_player(peer& connection, const wire::action_request& body) response.set_action_sequence(sequence); enqueue(connection, error, response); }; - if (connection.player == nullptr) - { + if (connection.player == nullptr) { fail("not_joined", "Join the lobby before using an attribute action"); return; } const auto kind = body.kind(); - if (sequence == 0 || kind < wire::action_damage || kind > wire::action_upgrade) - { + if (sequence == 0 || kind < wire::action_damage || kind > wire::action_upgrade) { fail("invalid_message", "Expected a positive sequence and a supported action"); return; } auto& player = *connection.player; - if (sequence <= player.get_u_int32("action_seq")) - { + if (sequence <= player.get_u_int32("action_seq")) { fail("stale_sequence", "Attribute action sequence must strictly increase from 1"); return; } auto hp = player.get_u_int32("hp"); auto mp = player.get_u_int32("mp"); - if (kind == wire::action_damage) - { + if (kind == wire::action_damage) { hp = hp > 15 ? hp - 15 : 0; - } - else if (kind == wire::action_skill) - { - if (mp < 20) - { + } else if (kind == wire::action_skill) { + if (mp < 20) { fail("insufficient_resource", "Skill requires at least 20 MP"); return; } mp -= 20; - } - else if (kind == wire::action_rest) - { + } else if (kind == wire::action_rest) { const auto hp_max = player.get_u_int32("hp_max"); const auto mp_max = player.get_u_int32("mp_max"); hp += std::min(std::uint32_t{20}, hp_max - hp); mp += std::min(std::uint32_t{20}, mp_max - mp); - } - else if (kind == wire::action_pickup || kind == wire::action_use_potion) - { + } else if (kind == wire::action_pickup || kind == wire::action_use_potion) { auto* inventory = player.find_table(inventory_index); auto* potion = inventory->find_row(1); - if (kind == wire::action_pickup) - { - if (potion && potion->get_u_int32(2) >= 99) - { + if (kind == wire::action_pickup) { + if (potion && potion->get_u_int32(2) >= 99) { fail("inventory_full", "Potion stack is full"); return; } - if (!potion) - { + if (!potion) { potion = inventory->add_row(1); - if (!potion) - { + if (!potion) { throw std::runtime_error("Cannot add potion row"); } potion->set_u_int32(1, 1); potion->set_u_int32(2, 1); - } - else - { + } else { potion->set_u_int32(2, potion->get_u_int32(2) + 1); } - } - else - { - if (!potion) - { + } else { + if (!potion) { fail("insufficient_resource", "No potion in inventory"); return; } const auto count = potion->get_u_int32(2); - if (count == 1) - { - if (!inventory->remove_row(1)) - { + if (count == 1) { + if (!inventory->remove_row(1)) { throw std::runtime_error("Cannot remove consumed potion row"); } - } - else - { + } else { potion->set_u_int32(2, count - 1); } hp += std::min(std::uint32_t{10}, player.get_u_int32("hp_max") - hp); } - } - else - { + } else { auto container = player.find_container(equipment_index); auto equipped = container->find(std::uint32_t{1}); - if (kind == wire::action_upgrade) - { + if (kind == wire::action_upgrade) { const auto power = equipped->get_u_int32(2); equipped->set_u_int32(2, std::min(std::uint32_t{100}, power + 1)); - } - else - { + } else { const auto next = equipped == connection.equipment[0] ? connection.equipment[1] : connection.equipment[0]; - if (!container->remove(std::uint32_t{1}) || !container->place(1, next)) - { + if (!container->remove(std::uint32_t{1}) || !container->place(1, next)) { throw std::runtime_error("Cannot replace equipment slot"); } } @@ -442,19 +363,16 @@ void room_module::act_player(peer& connection, const wire::action_request& body) room_module::peer* room_module::consume_message_budget(conv_id_t session) { owner_thread(); auto found = peers_.find(session); - if (found == peers_.end() || found->second.closing) - { + if (found == peers_.end() || found->second.closing) { return nullptr; } auto& connection = found->second; const auto now = std::chrono::steady_clock::now(); - if (now - connection.window >= std::chrono::seconds(1)) - { + if (now - connection.window >= std::chrono::seconds(1)) { connection.window = now; connection.messages = 0; } - if (++connection.messages > 32 || ++tick_messages_ > 64) - { + if (++connection.messages > 32 || ++tick_messages_ > 64) { connection.closing = true; return nullptr; } @@ -463,64 +381,46 @@ room_module::peer* room_module::consume_message_budget(conv_id_t session) { void room_module::on_message(const net_msg* message, conv_id_t session) { auto* admitted = consume_message_budget(session); - if (admitted == nullptr) - { + if (admitted == nullptr) { return; } auto& connection = *admitted; const auto parse = [&](auto& body) { return body.ParseFromArray(message->get_msg_data(), static_cast(message->get_msg_length())); }; - switch (message->get_msg_id()) - { - case join: - { + switch (message->get_msg_id()) { + case join: { wire::join_request body; - if (parse(body)) - { + if (parse(body)) { join_room(connection, body); - } - else - { + } else { connection.closing = true; } break; } - case move: - { + case move: { wire::move_request body; - if (parse(body)) - { + if (parse(body)) { move_player(connection, body); - } - else - { + } else { connection.closing = true; } break; } - case action: - { + case action: { wire::action_request body; - if (parse(body)) - { + if (parse(body)) { act_player(connection, body); - } - else - { + } else { connection.closing = true; } break; } - case ping: - { + case ping: { wire::heartbeat body; - if (parse(body)) - { + if (parse(body)) { enqueue(connection, pong, body); - } - else - { + } else { connection.closing = true; } break; @@ -533,26 +433,19 @@ void room_module::on_message(const net_msg* message, conv_id_t session) { void room_module::on_event(const net_event* event) { owner_thread(); - if (event->get_type() == net_event_type::connect) - { + if (event->get_type() == net_event_type::connect) { peers_.try_emplace(event->get_id()); - } - else if (event->get_type() == net_event_type::disconnect) - { + } else if (event->get_type() == net_event_type::disconnect) { const auto found = peers_.find(event->get_id()); - if (found != peers_.end()) - { - try - { retire(found->second); } - catch (const std::exception& exception) - { + if (found != peers_.end()) { + try { + retire(found->second); + } catch (const std::exception& exception) { ARK_LOG_ERROR("guest_room cannot publish removal: {}", exception.what()); - for (auto& [session, connection] : peers_) - { + for (auto& [session, connection] : peers_) { connection.closing = true; } - if (found->second.player) - { + if (found->second.player) { release_player(found->second); } } @@ -564,33 +457,27 @@ void room_module::on_event(const net_event* event) { bool room_module::update() { owner_thread(); tick_messages_ = 0; - try - { flush_room(); } - catch (const std::exception& exception) - { + try { + flush_room(); + } catch (const std::exception& exception) { ARK_LOG_ERROR("guest_room Entity flush failed: {}", exception.what()); - for (auto& [session, connection] : peers_) - { + for (auto& [session, connection] : peers_) { connection.closing = true; } } - for (auto& [session, connection] : peers_) - { - if (connection.closing) - { + for (auto& [session, connection] : peers_) { + if (connection.closing) { server_->get_net()->close_session(session); continue; } - while (!connection.pending.empty()) - { + while (!connection.pending.empty()) { auto pending = std::move(connection.pending.front()); connection.pending.pop_front(); connection.pending_bytes -= pending.body.size() + 12; header response; response.set_message_id(pending.id); response.set_message_length(static_cast(pending.body.size())); - if (!server_->get_net()->send_msg(&response, pending.body.data(), session)) - { + if (!server_->get_net()->send_msg(&response, pending.body.data(), session)) { connection.closing = true; connection.pending.clear(); connection.pending_bytes = 0; @@ -604,10 +491,8 @@ bool room_module::update() { bool room_module::pre_shut() { owner_thread(); - for (auto& [session, connection] : peers_) - { - if (connection.player != nullptr) - { + for (auto& [session, connection] : peers_) { + if (connection.player != nullptr) { release_player(connection); } } diff --git a/examples/guest_room/guest_room_module.hpp b/examples/guest_room/guest_room_module.hpp index 13eb19ab8..da4dbb249 100644 --- a/examples/guest_room/guest_room_module.hpp +++ b/examples/guest_room/guest_room_module.hpp @@ -18,8 +18,7 @@ namespace ark::guest_room { -class room_module final : public module_base -{ +class room_module final : public module_base { public: bool init() override; bool pre_update() override; @@ -27,14 +26,12 @@ class room_module final : public module_base player; std::string player_id; std::unique_ptr publisher; diff --git a/examples/guest_room/guest_room_plugin.cpp b/examples/guest_room/guest_room_plugin.cpp index 22873b30e..1a4d8e62c 100644 --- a/examples/guest_room/guest_room_plugin.cpp +++ b/examples/guest_room/guest_room_plugin.cpp @@ -16,15 +16,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void plugin::install() { - if (!register_module(std::make_unique(), module_update::enabled)) - { + if (!register_module(std::make_unique(), module_update::enabled)) { throw std::runtime_error("guest_room module registration rejected"); } } void plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("guest_room module unregistration rejected"); } } diff --git a/examples/guest_room/guest_room_plugin.hpp b/examples/guest_room/guest_room_plugin.hpp index aea120fb0..941eb72c2 100644 --- a/examples/guest_room/guest_room_plugin.hpp +++ b/examples/guest_room/guest_room_plugin.hpp @@ -5,8 +5,7 @@ namespace ark::guest_room { -class plugin final : public plugin_base -{ +class plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/examples/guest_room/guest_room_protocol.hpp b/examples/guest_room/guest_room_protocol.hpp index cde6c0e06..605a649a3 100644 --- a/examples/guest_room/guest_room_protocol.hpp +++ b/examples/guest_room/guest_room_protocol.hpp @@ -22,8 +22,7 @@ inline constexpr msg_id_t delta = 60009; inline constexpr std::uint32_t max_body = 8192; inline constexpr std::uint32_t protocol_version = 2; -class header final : public msg_header -{ +class header final : public msg_header { public: explicit header(bool client_requests_only = false) : client_requests_only_(client_requests_only) { @@ -38,13 +37,11 @@ class header final : public msg_header id_ = (std::uint16_t(bytes[4]) << 8) | bytes[5]; length_ = (std::uint32_t(bytes[8]) << 24) | (std::uint32_t(bytes[9]) << 16) | (std::uint32_t(bytes[10]) << 8) | bytes[11]; - if (std::memcmp(bytes, "ARK2", 4) != 0 || bytes[6] != 0 || bytes[7] != 0 || length_ > max_body) - { + if (std::memcmp(bytes, "ARK2", 4) != 0 || bytes[6] != 0 || bytes[7] != 0 || length_ > max_body) { // Net rejects this size before allocating a message or invoking callbacks. length_ = max_body + 1; } - if (client_requests_only_ && id_ != join && id_ != move && id_ != ping && id_ != action) - { + if (client_requests_only_ && id_ != join && id_ != move && id_ != ping && id_ != action) { // Keep unsupported/reserved IDs out of Net's own registration/heartbeat dispatch. id_ = unsupported; } @@ -55,8 +52,7 @@ class header final : public msg_header output.push_back(static_cast(id_ >> 8)); output.push_back(static_cast(id_)); output.append(2, '\0'); - for (int shift = 24; shift >= 0; shift -= 8) - { + for (int shift = 24; shift >= 0; shift -= 8) { output.push_back(static_cast(length_ >> shift)); } } @@ -96,55 +92,42 @@ class header final : public msg_header }; inline bool valid_name(const std::string& name) { - if (name.empty() || name.size() > 64) - { + if (name.empty() || name.size() > 64) { return false; } // Validate UTF-8 explicitly: protobuf bytes fields also use this rule for names. - for (std::size_t i = 0; i < name.size();) - { + for (std::size_t i = 0; i < name.size();) { const auto first = static_cast(name[i++]); std::uint32_t point = first; unsigned continuation = 0; std::uint32_t minimum = 0; - if (first >= 0xc2 && first <= 0xdf) - { + if (first >= 0xc2 && first <= 0xdf) { point = first & 0x1f; continuation = 1; minimum = 0x80; - } - else if (first >= 0xe0 && first <= 0xef) - { + } else if (first >= 0xe0 && first <= 0xef) { point = first & 0x0f; continuation = 2; minimum = 0x800; - } - else if (first >= 0xf0 && first <= 0xf4) - { + } else if (first >= 0xf0 && first <= 0xf4) { point = first & 0x07; continuation = 3; minimum = 0x10000; - } - else if (first >= 0x80) - { + } else if (first >= 0x80) { return false; } - if (continuation > name.size() - i) - { + if (continuation > name.size() - i) { return false; } - for (unsigned count = 0; count < continuation; ++count) - { + for (unsigned count = 0; count < continuation; ++count) { const auto byte = static_cast(name[i++]); - if ((byte & 0xc0) != 0x80) - { + if ((byte & 0xc0) != 0x80) { return false; } point = (point << 6) | (byte & 0x3f); } if (point < minimum || point > 0x10ffff || (point >= 0xd800 && point <= 0xdfff) || point < 0x20 || - (point >= 0x7f && point <= 0x9f)) - { + (point >= 0x7f && point <= 0x9f)) { return false; } } diff --git a/examples/guest_room/guest_room_wire.hpp b/examples/guest_room/guest_room_wire.hpp index 87f1f17ff..910abe374 100644 --- a/examples/guest_room/guest_room_wire.hpp +++ b/examples/guest_room/guest_room_wire.hpp @@ -26,16 +26,14 @@ inline entity_sync::nested_wire::limits player_limits() { inline guid_t decode_guid(std::uint64_t value) { if (value == 0 || value > static_cast(std::numeric_limits::max()) || - value > static_cast(std::numeric_limits::max())) - { + value > static_cast(std::numeric_limits::max())) { throw std::invalid_argument("Room Entity GUID must be positive and fit the native width"); } return static_cast(value); } inline std::uint64_t encode_identity(guid_t value) { - if (value <= 0 || value > std::numeric_limits::max()) - { + if (value <= 0 || value > std::numeric_limits::max()) { throw std::invalid_argument("Room Entity GUID must be positive and fit signed 64 bits"); } return static_cast(value); @@ -44,21 +42,18 @@ inline std::uint64_t encode_identity(guid_t value) { inline entity_sync::nested_entity_layout player_layout(const std::array& equipment) { using type = entity_sync::nested_scalar_type; entity_sync::nested_entity_layout layout{"GuestPlayer", {}, {}, {}}; - for (const auto index : player_fields) - { + for (const auto index : player_fields) { layout.fields.emplace(index, index == 100 ? type::bytes : index <= 102 ? type::real64 : type::uint32); } layout.tables.emplace( inventory_index, entity_sync::nested_table_layout{"InventoryItem", {{1, type::uint32}, {2, type::uint32}}}); auto& children = layout.containers[equipment_index]; - for (const auto id : equipment) - { + for (const auto id : equipment) { encode_identity(id); if (!children .emplace(id, entity_sync::nested_entity_layout{"GuestEquipment", {{1, type::uint32}, {2, type::uint32}}, {}, {}}) - .second) - { + .second) { throw std::invalid_argument("Duplicate equipment binding"); } } @@ -68,8 +63,7 @@ inline entity_sync::nested_entity_layout player_layout(const std::array& equipment) { entity_sync::nested_projection projection{player_schema, root, {"GuestPlayer", {player_fields.begin(), player_fields.end()}, {{inventory_index, {1, 2}}}, {}}}; - for (const auto id : equipment) - { + for (const auto id : equipment) { projection.root.containers[equipment_index].emplace( id, entity_sync::nested_entity_projection{"GuestEquipment", {1, 2}, {}, {}}); } @@ -77,21 +71,17 @@ inline entity_sync::nested_projection player_projection(guid_t root, const std:: } inline entity_sync::nested_stream_binding decode_binding(const wire::player_binding& input) { - if (input.equipment_ids_size() != 2 || input.incarnation() == 0 || input.generation() == 0) - { + if (input.equipment_ids_size() != 2 || input.incarnation() == 0 || input.generation() == 0) { throw std::invalid_argument("Missing fixed player instance binding"); } const auto root = decode_guid(input.entity_id()); std::array equipment{}; - for (std::size_t i = 0; i < equipment.size(); ++i) - { - if (input.equipment_ids(static_cast(i)) <= 0) - { + for (std::size_t i = 0; i < equipment.size(); ++i) { + if (input.equipment_ids(static_cast(i)) <= 0) { throw std::invalid_argument("Invalid equipment binding"); } equipment[i] = decode_guid(static_cast(input.equipment_ids(static_cast(i)))); - if (equipment[i] == root) - { + if (equipment[i] == root) { throw std::invalid_argument("Equipment aliases its root"); } } @@ -103,8 +93,7 @@ inline void encode_binding(const entity_sync::nested_stream_binding& input, wire staged.set_entity_id(encode_identity(input.root_id)); staged.set_incarnation(input.root_incarnation); staged.set_generation(input.generation); - for (const auto& [id, layout] : input.root.containers.at(equipment_index)) - { + for (const auto& [id, layout] : input.root.containers.at(equipment_index)) { staged.add_equipment_ids(static_cast(encode_identity(id))); } static_cast(decode_binding(staged)); @@ -115,17 +104,14 @@ inline void validate_player(const entity_sync::nested_snapshot& input) { const auto& root = input.root; const auto& fields = root.scalars.fields; if (input.schema_id != player_schema || root.scalars.class_name != "GuestPlayer" || - fields.size() != player_fields.size() || root.tables.size() != 1 || root.containers.size() != 1) - { + fields.size() != player_fields.size() || root.tables.size() != 1 || root.containers.size() != 1) { throw std::invalid_argument("Unsupported GuestPlayer projection"); } - for (const auto index : player_fields) - { + for (const auto index : player_fields) { const auto field = fields.find(index); if (field == fields.end() || (index == 100 ? !std::holds_alternative(field->second) : index <= 102 ? !std::holds_alternative(field->second) - : !std::holds_alternative(field->second))) - { + : !std::holds_alternative(field->second))) { throw std::invalid_argument("Wrong GuestPlayer field or type"); } } @@ -135,49 +121,40 @@ inline void validate_player(const entity_sync::nested_snapshot& input) { x > 960 || y < 0 || y > 540 || std::get(fields.at(106)) == 0 || std::get(fields.at(107)) == 0 || std::get(fields.at(104)) > std::get(fields.at(106)) || - std::get(fields.at(105)) > std::get(fields.at(107))) - { + std::get(fields.at(105)) > std::get(fields.at(107))) { throw std::invalid_argument("Invalid GuestPlayer public state"); } - if (!root.tables.contains(inventory_index) || !root.containers.contains(equipment_index)) - { + if (!root.tables.contains(inventory_index) || !root.containers.contains(equipment_index)) { throw std::invalid_argument("Missing demo inventory or equipment"); } const auto& inventory = root.tables.at(inventory_index); - if (inventory.class_name != "InventoryItem" || inventory.rows.size() > 1) - { + if (inventory.class_name != "InventoryItem" || inventory.rows.size() > 1) { throw std::invalid_argument("Invalid demo inventory"); } - for (const auto& [number, row] : inventory.rows) - { + for (const auto& [number, row] : inventory.rows) { if (row.fields.size() != 2 || !row.fields.contains(1) || !row.fields.contains(2) || !std::holds_alternative(row.fields.at(1)) || - !std::holds_alternative(row.fields.at(2))) - { + !std::holds_alternative(row.fields.at(2))) { throw std::invalid_argument("Wrong inventory column or type"); } if (number != 1 || std::get(row.fields.at(1)) != 1 || - std::get(row.fields.at(2)) == 0 || std::get(row.fields.at(2)) > 99) - { + std::get(row.fields.at(2)) == 0 || std::get(row.fields.at(2)) > 99) { throw std::invalid_argument("Invalid potion row"); } } const auto& slots = root.containers.at(equipment_index); - if (slots.size() != 1 || !slots.contains(1)) - { + if (slots.size() != 1 || !slots.contains(1)) { throw std::invalid_argument("Invalid demo equipment slot"); } const auto& child = slots.at(1); if (child.scalars.fields.size() != 2 || !child.scalars.fields.contains(1) || !child.scalars.fields.contains(2) || !std::holds_alternative(child.scalars.fields.at(1)) || - !std::holds_alternative(child.scalars.fields.at(2))) - { + !std::holds_alternative(child.scalars.fields.at(2))) { throw std::invalid_argument("Wrong equipment field or type"); } const auto item = std::get(child.scalars.fields.at(1)); if (child.scalars.class_name != "GuestEquipment" || (item != 1001 && item != 1002) || - std::get(child.scalars.fields.at(2)) > 100) - { + std::get(child.scalars.fields.at(2)) > 100) { throw std::invalid_argument("Invalid demo equipment attributes"); } } diff --git a/examples/http_client/http_client_sample_module.cpp b/examples/http_client/http_client_sample_module.cpp index af6b4cb05..8f1fe75e1 100644 --- a/examples/http_client/http_client_sample_module.cpp +++ b/examples/http_client/http_client_sample_module.cpp @@ -34,8 +34,7 @@ using namespace std; namespace ark { namespace { -class http_client_sample_module_impl final : public module_base -{ +class http_client_sample_module_impl final : public module_base { public: bool init() override; bool post_init() override; @@ -48,8 +47,7 @@ class http_client_sample_module_impl final : public module_base(); auto* etcd = find_module(); - if (!http_client_ || !etcd) - { + if (!http_client_ || !etcd) { return false; } etcd_client_ = diff --git a/examples/http_client/http_client_sample_module.hpp b/examples/http_client/http_client_sample_module.hpp index 8ff200545..30faeca83 100644 --- a/examples/http_client/http_client_sample_module.hpp +++ b/examples/http_client/http_client_sample_module.hpp @@ -24,8 +24,6 @@ namespace ark { -class http_client_sample_module : public module -{ -}; +class http_client_sample_module : public module {}; } // namespace ark diff --git a/examples/http_client/http_client_sample_plugin.cpp b/examples/http_client/http_client_sample_plugin.cpp index 8896d1131..e865b8f7a 100644 --- a/examples/http_client/http_client_sample_plugin.cpp +++ b/examples/http_client/http_client_sample_plugin.cpp @@ -34,15 +34,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void http_client_sample_plugin::install() { - if (!register_module(make_http_client_sample_module(), module_update::disabled)) - { + if (!register_module(make_http_client_sample_module(), module_update::disabled)) { throw std::runtime_error("http_client example module registration rejected"); } } void http_client_sample_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("http_client example module unregistration rejected"); } } diff --git a/examples/http_client/http_client_sample_plugin.hpp b/examples/http_client/http_client_sample_plugin.hpp index 1c3739654..fbb4071a2 100644 --- a/examples/http_client/http_client_sample_plugin.hpp +++ b/examples/http_client/http_client_sample_plugin.hpp @@ -29,8 +29,7 @@ namespace ark { std::unique_ptr make_http_client_sample_module(); -class http_client_sample_plugin final : public plugin_base -{ +class http_client_sample_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/examples/http_server/http_server_module.cpp b/examples/http_server/http_server_module.cpp index 58c6421f8..d7acf5176 100644 --- a/examples/http_server/http_server_module.cpp +++ b/examples/http_server/http_server_module.cpp @@ -25,8 +25,7 @@ namespace ark { namespace { -class http_server_sample_module_impl final : public module_base -{ +class http_server_sample_module_impl final : public module_base { public: bool init() override; bool post_init() override; diff --git a/examples/http_server/http_server_module.hpp b/examples/http_server/http_server_module.hpp index d3636100b..24bccddf9 100644 --- a/examples/http_server/http_server_module.hpp +++ b/examples/http_server/http_server_module.hpp @@ -24,8 +24,6 @@ namespace ark { -class http_server_sample_module : public module -{ -}; +class http_server_sample_module : public module {}; } // namespace ark diff --git a/examples/http_server/http_server_plugin.cpp b/examples/http_server/http_server_plugin.cpp index 439a70f6e..6781c4336 100644 --- a/examples/http_server/http_server_plugin.cpp +++ b/examples/http_server/http_server_plugin.cpp @@ -34,15 +34,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void http_server_plugin::install() { - if (!register_module(make_http_server_sample_module(), module_update::disabled)) - { + if (!register_module(make_http_server_sample_module(), module_update::disabled)) { throw std::runtime_error("http_server example module registration rejected"); } } void http_server_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("http_server example module unregistration rejected"); } } diff --git a/examples/http_server/http_server_plugin.hpp b/examples/http_server/http_server_plugin.hpp index 019f2ee71..c281f5c33 100644 --- a/examples/http_server/http_server_plugin.hpp +++ b/examples/http_server/http_server_plugin.hpp @@ -29,8 +29,7 @@ namespace ark { std::unique_ptr make_http_server_sample_module(); -class http_server_plugin final : public plugin_base -{ +class http_server_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/examples/module_lifecycle/module_lifecycle_module.hpp b/examples/module_lifecycle/module_lifecycle_module.hpp index f2921d576..bfbcba8db 100644 --- a/examples/module_lifecycle/module_lifecycle_module.hpp +++ b/examples/module_lifecycle/module_lifecycle_module.hpp @@ -25,8 +25,7 @@ namespace ark { -class module_lifecycle_module final : public module_base -{ +class module_lifecycle_module final : public module_base { public: explicit module_lifecycle_module() = default; diff --git a/examples/module_lifecycle/module_lifecycle_plugin.cpp b/examples/module_lifecycle/module_lifecycle_plugin.cpp index 45acfd358..b3b48da3a 100644 --- a/examples/module_lifecycle/module_lifecycle_plugin.cpp +++ b/examples/module_lifecycle/module_lifecycle_plugin.cpp @@ -34,15 +34,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void module_lifecycle_plugin::install() { - if (!register_module(make_module_lifecycle_module(), module_update::disabled)) - { + if (!register_module(make_module_lifecycle_module(), module_update::disabled)) { throw std::runtime_error("module_lifecycle module registration rejected"); } } void module_lifecycle_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("module_lifecycle module unregistration rejected"); } } diff --git a/examples/module_lifecycle/module_lifecycle_plugin.hpp b/examples/module_lifecycle/module_lifecycle_plugin.hpp index b74931875..880c55206 100755 --- a/examples/module_lifecycle/module_lifecycle_plugin.hpp +++ b/examples/module_lifecycle/module_lifecycle_plugin.hpp @@ -29,8 +29,7 @@ namespace ark { std::unique_ptr make_module_lifecycle_module(); -class module_lifecycle_plugin final : public plugin_base -{ +class module_lifecycle_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/examples/mysql_sample/mysql_sample_module.cpp b/examples/mysql_sample/mysql_sample_module.cpp index e96c0fe01..8f07d38d9 100644 --- a/examples/mysql_sample/mysql_sample_module.cpp +++ b/examples/mysql_sample/mysql_sample_module.cpp @@ -10,15 +10,13 @@ namespace { task<> run_mysql_sample(mysql_module& database) { auto reply = co_await database.query("primary", "SELECT 1"); - if (!reply) - { + if (!reply) { throw std::runtime_error(reply.result.status.message); } ARK_LOG_INFO("MySQL query completed: {} rows", reply.result.rows.size()); std::vector parameters{std::int64_t{42}}; auto prepared = co_await database.execute("primary", "SELECT ?", std::move(parameters)); - if (!prepared) - { + if (!prepared) { throw std::runtime_error(prepared.result.status.message); } } @@ -31,29 +29,23 @@ std::unique_ptr make_mysql_sample_module() { bool mysql_sample_module::init() { mysql_module_ptr_ = find_module(); - if (!mysql_module_ptr_) - { + if (!mysql_module_ptr_) { return false; } mysql_options options; - if (const auto* value = std::getenv("ARK_MYSQL_HOST")) - { + if (const auto* value = std::getenv("ARK_MYSQL_HOST")) { options.pool.connection.host = value; } - if (const auto* value = std::getenv("ARK_MYSQL_USER")) - { + if (const auto* value = std::getenv("ARK_MYSQL_USER")) { options.pool.connection.username = value; } - if (const auto* value = std::getenv("ARK_MYSQL_PASSWORD")) - { + if (const auto* value = std::getenv("ARK_MYSQL_PASSWORD")) { options.pool.connection.password = value; } - if (const auto* value = std::getenv("ARK_MYSQL_DATABASE")) - { + if (const auto* value = std::getenv("ARK_MYSQL_DATABASE")) { options.pool.connection.database = value; } - if (const auto* value = std::getenv("ARK_MYSQL_CA")) - { + if (const auto* value = std::getenv("ARK_MYSQL_CA")) { options.pool.connection.ca_file = value; } // Native TLS verification remains enabled. A password is never logged. @@ -63,8 +55,7 @@ bool mysql_sample_module::init() { bool mysql_sample_module::post_init() { auto& tasks = get_plugin_manager()->create_task_group(*this); return tasks.start(run_mysql_sample(*mysql_module_ptr_), [](std::exception_ptr error) { - if (error) - { + if (error) { ARK_LOG_ERROR("MySQL sample coroutine failed"); } }) != 0; diff --git a/examples/mysql_sample/mysql_sample_module.hpp b/examples/mysql_sample/mysql_sample_module.hpp index b76cd90c5..5139ee439 100644 --- a/examples/mysql_sample/mysql_sample_module.hpp +++ b/examples/mysql_sample/mysql_sample_module.hpp @@ -25,8 +25,7 @@ namespace ark { -class mysql_sample_module final : public module_base -{ +class mysql_sample_module final : public module_base { private: mysql_module* mysql_module_ptr_; diff --git a/examples/mysql_sample/mysql_sample_plugin.cpp b/examples/mysql_sample/mysql_sample_plugin.cpp index 58178fcd6..081cfd6db 100644 --- a/examples/mysql_sample/mysql_sample_plugin.cpp +++ b/examples/mysql_sample/mysql_sample_plugin.cpp @@ -34,15 +34,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void mysql_sample_plugin::install() { - if (!register_module(make_mysql_sample_module(), module_update::disabled)) - { + if (!register_module(make_mysql_sample_module(), module_update::disabled)) { throw std::runtime_error("mysql sample module registration rejected"); } } void mysql_sample_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("mysql sample module unregistration rejected"); } } diff --git a/examples/mysql_sample/mysql_sample_plugin.hpp b/examples/mysql_sample/mysql_sample_plugin.hpp index 4cf21e414..8b387d492 100644 --- a/examples/mysql_sample/mysql_sample_plugin.hpp +++ b/examples/mysql_sample/mysql_sample_plugin.hpp @@ -29,8 +29,7 @@ namespace ark { std::unique_ptr make_mysql_sample_module(); -class mysql_sample_plugin final : public plugin_base -{ +class mysql_sample_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/examples/physics_scene/physics_scene_module.cpp b/examples/physics_scene/physics_scene_module.cpp index a5756d4b4..bc22df759 100644 --- a/examples/physics_scene/physics_scene_module.cpp +++ b/examples/physics_scene/physics_scene_module.cpp @@ -103,8 +103,7 @@ void physics_scene_module::init_base() { void physics_scene_module::init_move() { ///random direction auto step_count = sizeof(move_step_values) / sizeof(int); - for (size_t i = 0; i < step_count; i++) - { + for (size_t i = 0; i < step_count; i++) { ///ray cast distances auto step = move_step_values[i]; init_move_step(step); @@ -116,8 +115,7 @@ void physics_scene_module::init_move_step(const int step) { sample_move_step.move_step = float(step); auto move_count = sizeof(move_count_values) / sizeof(int); - for (size_t i = 0; i < move_count; i++) - { + for (size_t i = 0; i < move_count; i++) { ///move counts of each actor auto one_move_count = move_count_values[i]; init_actor_direction(one_move_count, sample_move_step); @@ -129,8 +127,7 @@ void physics_scene_module::init_move_step(const int step) { void physics_scene_module::init_actor_direction(const int move_count, sample_move_step& sample_move_step) { sample_actor_direction actor_direction; actor_direction.move_count = move_count; - for (int i = 0; i < actor_count; i++) - { + for (int i = 0; i < actor_count; i++) { ///actor move directions physic3_d direction = random_move_direction(); actor_direction.direction_list.push_back(direction); @@ -142,30 +139,23 @@ void physics_scene_module::init_actor_direction(const int move_count, sample_mov void physics_scene_module::create_scene() { ///first scene for test auto& scene_list = physic_config_module_->get_physic_scene_list(); - for (auto& iter : scene_list) - { + for (auto& iter : scene_list) { sample_scene sample_scene; auto& scene_id = iter.first; - if (scene_id == "wfcy") - { + if (scene_id == "wfcy") { sample_scene.min_pos = physic3_d(-9372.780273, 700, -16475.042969); sample_scene.max_pos = physic3_d(12115.969727, 700, 9105.064453); - } - else if (scene_id == "fjcz") - { + } else if (scene_id == "fjcz") { sample_scene.min_pos = physic3_d(-6977.476563, 700, -4477.612305); sample_scene.max_pos = physic3_d(10624.397461, 700, 12644.917969); - } - else - { + } else { continue; } ///create a scene sample_scene.scene_obj_id = physic_module_->create_scene(scene_id); - if (sample_scene.scene_obj_id == null_guid) - { + if (sample_scene.scene_obj_id == null_guid) { ARK_ASSERT_RET_NONE("scene create failed"); exit(0); } @@ -176,15 +166,13 @@ void physics_scene_module::create_scene() { } void physics_scene_module::create_actor() { - for (auto& iter : sample_scene_list_) - { + for (auto& iter : sample_scene_list_) { auto& sample_scene = iter; auto scene_obj_id = sample_scene.scene_obj_id; //auto interval_x = (sample_scene.max_pos.x - sample_scene.min_pos.x) / ACTOR_X_COUNT; //auto interval_z = (sample_scene.max_pos.z - sample_scene.min_pos.z) / ACOTR_Z_COUNT; - for (int i = 0; i < actor_count; i++) - { + for (int i = 0; i < actor_count; i++) { //auto index_x = i / ACTOR_X_COUNT; //auto index_z = i % ACOTR_Z_COUNT; @@ -206,13 +194,10 @@ void physics_scene_module::create_actor() { auto actor = physic_module_->create_dynamic_box_actor(scene_obj_id, pos, box_size); #endif - if (actor != null_guid) - { + if (actor != null_guid) { sample_scene.actor_list.push_back(actor); ARK_LOG_INFO("actor index = {} created at position x = {} y = {} z= {}", i, pos.x, pos.y, pos.z); - } - else - { + } else { ARK_LOG_INFO("actor created faile index = ", i); exit(0); } @@ -229,19 +214,16 @@ void physics_scene_module::create_actor() { } void physics_scene_module::move_actor() { - for (auto& iter : sample_scene_list_) - { + for (auto& iter : sample_scene_list_) { auto& sample_scene = iter; move_actor(sample_scene); } } void physics_scene_module::move_actor(const sample_scene& scene) { - for (auto& iter_move : sample_move_list_) - { + for (auto& iter_move : sample_move_list_) { auto& move_step = iter_move.second; - for (auto& iter_actor_move : move_step.count_actor_move_list) - { + for (auto& iter_actor_move : move_step.count_actor_move_list) { auto& actor_move = iter_actor_move.second; move_actor(scene, actor_move, move_step.move_step); } @@ -269,14 +251,11 @@ void physics_scene_module::move_actor( int missed = 0; date_time now; - for (int i = 0; i < move_count; i++) - { - for (size_t j = 0; j < actor_count; j++) - { + for (int i = 0; i < move_count; i++) { + for (size_t j = 0; j < actor_count; j++) { auto actor = actor_list[j]; physic3_d pos; - if (!physic_module_->get_actor_position(actor, pos)) - { + if (!physic_module_->get_actor_position(actor, pos)) { ARK_LOG_ERROR("get actor position failed actor id = {}", actor); continue; } @@ -292,12 +271,10 @@ void physics_scene_module::move_actor( pos.z += (direction.z * distance); ///is out of range - if (scene.is_in_range(pos)) - { + if (scene.is_in_range(pos)) { physic_ray_hit ray_hit; auto result = physic_module_->ray_cast(scene_obj_id, origin, direction, distance, ray_hit); - if (result) - { + if (result) { pos = ray_hit.hit_pos; ///a new direction @@ -305,14 +282,10 @@ void physics_scene_module::move_actor( hit += 1; //LogRayCast(scene, hit, actor, rayHit.block.distance, rayHit.block.actor, pos); - } - else - { + } else { missed += 1; } - } - else - { + } else { ///reverse direction direction.x = -direction.x; direction.z = -direction.z; @@ -322,8 +295,7 @@ void physics_scene_module::move_actor( physic_ray_hit ray_hit; auto result = physic_module_->ray_cast(scene_obj_id, origin, direction, distance, ray_hit); - if (result) - { + if (result) { pos = ray_hit.hit_pos; ///a new direction @@ -331,16 +303,13 @@ void physics_scene_module::move_actor( hit += 1; //LogRayCast(scene, hit, actor, rayHit.block.distance, rayHit.block.actor, pos); - } - else - { + } else { missed += 1; } } auto result = physic_module_->update_actor(actor, pos); - if (!result) - { + if (!result) { ARK_LOG_INFO("actor move to origin failed"); } @@ -384,8 +353,7 @@ void physics_scene_module::log_ray_cast( void physics_scene_module::re_random_position(const sample_scene& scene) { auto& actor_list = scene.actor_list; - for (auto iter : actor_list) - { + for (auto iter : actor_list) { auto actor = iter; auto pos = random_position(scene); physic_module_->update_actor(actor, pos); @@ -396,8 +364,7 @@ physic3_d physics_scene_module::random_position(const sample_scene& scene) { physic3_d pos; float mul = 1.0F; - if (scene.scene_id == "wfcy") - { + if (scene.scene_id == "wfcy") { mul = 0.5F; } @@ -411,12 +378,10 @@ physic3_d physics_scene_module::random_position(const sample_scene& scene) { } void physics_scene_module::test_raycast() { - for (auto& iter : sample_scene_list_) - { + for (auto& iter : sample_scene_list_) { auto& sample_scene = iter; auto scene_obj_id = sample_scene.scene_obj_id; - if (sample_scene.scene_id == "wfcy") - { + if (sample_scene.scene_id == "wfcy") { //sample_scene.min_pos = AFPhysic3D(-9372.780273, 700, -16475.042969); //sample_scene.max_pos = AFPhysic3D(12115.969727, 700, 9105.064453); @@ -437,28 +402,22 @@ void physics_scene_module::test_raycast() { float ray_dist = 500; physic_ray_hit ray_hit; bool result = physic_module_->ray_cast(scene_obj_id, origin, direction, ray_dist, ray_hit); - if (result) - { + if (result) { auto hit_pos = ray_hit.hit_pos; std::cout << "ray cast distance = " << ray_dist << " hit pos = (" << hit_pos.x << ", " << hit_pos.y << ", " << hit_pos.z << ") hit distance = " << ray_hit.hit_distance << std::endl; - } - else - { + } else { std::cout << "ray cast distance = " << ray_dist << " did not hit " << std::endl; } ray_dist = 5; physic_ray_hit ray_hit2; result = physic_module_->ray_cast(scene_obj_id, origin, direction, ray_dist, ray_hit2); - if (result) - { + if (result) { auto hit_pos = ray_hit2.hit_pos; std::cout << "ray cast distance = " << ray_dist << " hit pos = (" << hit_pos.x << ", " << hit_pos.y << ", " << hit_pos.z << ") hit distance = " << ray_hit.hit_distance << std::endl; - } - else - { + } else { std::cout << "ray cast distance = " << ray_dist << " did not hit " << std::endl; } } diff --git a/examples/physics_scene/physics_scene_module.hpp b/examples/physics_scene/physics_scene_module.hpp index cbf3956e6..292cc0a86 100644 --- a/examples/physics_scene/physics_scene_module.hpp +++ b/examples/physics_scene/physics_scene_module.hpp @@ -29,33 +29,28 @@ namespace ark { using sample_actor_direction_list = std::vector; -struct sample_actor_direction -{ +struct sample_actor_direction { int move_count{0}; sample_actor_direction_list direction_list; }; using move_count_actor_direction_list = std::map; -struct sample_move_step -{ +struct sample_move_step { float move_step{0.0F}; move_count_actor_direction_list count_actor_move_list; }; using step_move_count_actor_move_list = std::map; -class sample_scene -{ +class sample_scene { public: bool is_in_range(const physic3_d& pos) const { - if (pos.x < min_pos.x || pos.z < min_pos.z) - { + if (pos.x < min_pos.x || pos.z < min_pos.z) { return false; } - if (pos.x > max_pos.x || pos.z > max_pos.z) - { + if (pos.x > max_pos.x || pos.z > max_pos.z) { return false; } @@ -70,8 +65,7 @@ class sample_scene std::vector actor_list; }; -class physics_scene_module final : public module -{ +class physics_scene_module final : public module { ARK_DECLARE_MODULE_FUNCTIONS public: explicit physics_scene_module() = default; diff --git a/examples/redis_sample/redis_sample_module.cpp b/examples/redis_sample/redis_sample_module.cpp index 9f1456c29..5cd193267 100644 --- a/examples/redis_sample/redis_sample_module.cpp +++ b/examples/redis_sample/redis_sample_module.cpp @@ -12,8 +12,7 @@ std::unique_ptr make_redis_sample_module() { bool redis_sample_module::init() { redis_module_ = find_module(); - if (!redis_module_) - { + if (!redis_module_) { return false; } tasks_ = &get_plugin_manager()->create_task_group(*this); @@ -25,25 +24,23 @@ bool redis_sample_module::init() { bool redis_sample_module::post_init() { return tasks_->start(run(), [](std::exception_ptr error) { - if (error) - { - try - { std::rethrow_exception(error); } - catch (const std::exception& failure) - { ARK_LOG_ERROR("Redis sample failed: {}", failure.what()); } + if (error) { + try { + std::rethrow_exception(error); + } catch (const std::exception& failure) { + ARK_LOG_ERROR("Redis sample failed: {}", failure.what()); + } } }) != 0; } task<> redis_sample_module::run() { auto written = co_await redis_module_->command("sample", {"SET", "test", "123"}); - if (!written) - { + if (!written) { throw std::runtime_error("Redis SET failed; inspect native error before retrying a write"); } auto read = co_await redis_module_->command("sample", {"GET", "test"}); - if (!read || read.replies.empty()) - { + if (!read || read.replies.empty()) { throw std::runtime_error("Redis GET failed"); } ARK_LOG_INFO("Redis GET succeeded, value={}", read.replies.front().text); diff --git a/examples/redis_sample/redis_sample_module.hpp b/examples/redis_sample/redis_sample_module.hpp index 44413c839..fd7d6cbdb 100644 --- a/examples/redis_sample/redis_sample_module.hpp +++ b/examples/redis_sample/redis_sample_module.hpp @@ -6,8 +6,7 @@ namespace ark { -class redis_sample_module final : public module_base -{ +class redis_sample_module final : public module_base { public: bool init() override; bool post_init() override; diff --git a/examples/redis_sample/redis_sample_plugin.cpp b/examples/redis_sample/redis_sample_plugin.cpp index d6c60b907..832511064 100644 --- a/examples/redis_sample/redis_sample_plugin.cpp +++ b/examples/redis_sample/redis_sample_plugin.cpp @@ -34,15 +34,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void redis_sample_plugin::install() { - if (!register_module(make_redis_sample_module(), module_update::disabled)) - { + if (!register_module(make_redis_sample_module(), module_update::disabled)) { throw std::runtime_error("redis sample module registration rejected"); } } void redis_sample_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("redis sample module unregistration rejected"); } } diff --git a/examples/redis_sample/redis_sample_plugin.hpp b/examples/redis_sample/redis_sample_plugin.hpp index 8575fecc3..c75ee16b6 100644 --- a/examples/redis_sample/redis_sample_plugin.hpp +++ b/examples/redis_sample/redis_sample_plugin.hpp @@ -29,8 +29,7 @@ namespace ark { std::unique_ptr make_redis_sample_module(); -class redis_sample_plugin final : public plugin_base -{ +class redis_sample_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/examples/task_group/main.cpp b/examples/task_group/main.cpp index 2f0f07c04..37756d40e 100644 --- a/examples/task_group/main.cpp +++ b/examples/task_group/main.cpp @@ -31,24 +31,20 @@ int main() { failure = std::move(error); completed = true; }); - if (id == 0) - { + if (id == 0) { return 1; } tasks.stop_accepting(); const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); - while (!tasks.closed() && std::chrono::steady_clock::now() < deadline) - { + while (!tasks.closed() && std::chrono::steady_clock::now() < deadline) { tasks.poll(8); } - if (!tasks.closed()) - { + if (!tasks.closed()) { // A sample failure guard, not an application drain/abandon policy. // Do not destroy an owner which still has suspended task frames. std::_Exit(2); } - if (failure || !completed || result != 42) - { + if (failure || !completed || result != 42) { return 1; } std::cout << "result=" << result << " completed=" << completed << '\n'; diff --git a/examples/timers/timers_module.hpp b/examples/timers/timers_module.hpp index 81db685ee..e7509083b 100644 --- a/examples/timers/timers_module.hpp +++ b/examples/timers/timers_module.hpp @@ -27,8 +27,7 @@ namespace ark { -class timers_module final : public module_base -{ +class timers_module final : public module_base { public: bool init() override; bool post_init() override; diff --git a/examples/timers/timers_plugin.cpp b/examples/timers/timers_plugin.cpp index 5a3877c8c..00774c0f6 100644 --- a/examples/timers/timers_plugin.cpp +++ b/examples/timers/timers_plugin.cpp @@ -34,15 +34,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void timers_plugin::install() { - if (!register_module(make_timers_module(), module_update::enabled)) - { + if (!register_module(make_timers_module(), module_update::enabled)) { throw std::runtime_error("timers module registration rejected"); } } void timers_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("timers module unregistration rejected"); } } diff --git a/examples/timers/timers_plugin.hpp b/examples/timers/timers_plugin.hpp index 32ab4fbfd..23a81ccb1 100755 --- a/examples/timers/timers_plugin.hpp +++ b/examples/timers/timers_plugin.hpp @@ -29,8 +29,7 @@ namespace ark { std::unique_ptr make_timers_module(); -class timers_plugin final : public plugin_base -{ +class timers_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/scripts/style_files.sh b/scripts/style_files.sh index 04e1c2a33..1c2dcc1fd 100644 --- a/scripts/style_files.sh +++ b/scripts/style_files.sh @@ -7,7 +7,7 @@ ark_style_root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P) ark_style_files() { git -C "$ark_style_root" ls-files -z --cached --others --exclude-standard -- \ - include src examples tests benchmarks resources/photon/proto | + include src examples tests benchmarks tools resources/photon/proto | while IFS= read -r -d '' style_file; do case "$style_file" in tests/catch.hpp|tests/network/doctest.h|\ diff --git a/src/application/main.cpp b/src/application/main.cpp index 13c4decfb..9298452b4 100644 --- a/src/application/main.cpp +++ b/src/application/main.cpp @@ -47,13 +47,11 @@ using namespace ark; #ifdef ARK_PLATFORM_WIN static bool utf16_text(const std::string& text, std::wstring& native) { const auto count = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.c_str(), -1, nullptr, 0); - if (count == 0) - { + if (count == 0) { return false; } native.resize(count); - if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.c_str(), -1, native.data(), count) == 0) - { + if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.c_str(), -1, native.data(), count) == 0) { return false; } native.resize(count - 1); @@ -66,8 +64,7 @@ std::thread g_cmd_thread; // mini-dump void create_dump_file(const std::string& dump_file_path_name, EXCEPTION_POINTERS* exception_ptr) { std::wstring native_path; - if (!utf16_text(dump_file_path_name, native_path)) - { + if (!utf16_text(dump_file_path_name, native_path)) { return; } HANDLE h_dump_file = @@ -99,8 +96,7 @@ long application_crash_handler(EXCEPTION_POINTERS* exception_ptr) { void disable_close_button() { HWND h_wnd = GetConsoleWindow(); - if (h_wnd) - { + if (h_wnd) { HMENU h_menu = GetSystemMenu(h_wnd, FALSE); EnableMenuItem(h_menu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND); } @@ -152,15 +148,13 @@ Copyright 2020 © X.D. NetWork Inc. #ifdef ARK_PLATFORM_WIN void create_back_thread() { auto thread_func = []() { - while (app_detail::requested_stop_reason() == 0) - { + while (app_detail::requested_stop_reason() == 0) { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); std::string s; std::cin >> s; string_utils::to_lower(s); - if (s == "exit") - { + if (s == "exit") { app_detail::request_stop(app_detail::command_stop_reason); } } @@ -220,26 +214,20 @@ bool parse_args(int argc, char* argv[], std::chrono::milliseconds& shutdown_time args::Options::Single); // start parse argument list - try - { parser.ParseCLI(argc, argv); } - catch (args::Help& h) - { + try { + parser.ParseCLI(argc, argv); + } catch (args::Help& h) { std::cout << parser << ", error = " << h.what() << std::endl; return false; - } - catch (args::ParseError& e) - { + } catch (args::ParseError& e) { std::cout << parser << ", error = " << e.what() << std::endl; return false; - } - catch (args::ValidationError& e) - { + } catch (args::ValidationError& e) { std::cout << parser << ", error = " << e.what() << std::endl; return false; } - if (log_conf) - { + if (log_conf) { std::cerr << "--log_conf/-l has been removed; move logger settings into [logging] in --app_conf" << std::endl; configuration_error = true; return false; @@ -248,20 +236,17 @@ bool parse_args(int argc, char* argv[], std::chrono::milliseconds& shutdown_time std::int64_t timeout_ms{}; const auto& value = shutdown_wait.Get(); const auto parsed = std::from_chars(value.data(), value.data() + value.size(), timeout_ms); - if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || timeout_ms < 0) - { + if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || timeout_ms < 0) { std::cout << "Shutdown timeout must be a non-negative integer in milliseconds within int64 range" << std::endl; return false; } shutdown_timeout = std::chrono::milliseconds(timeout_ms); // Set bus id - if (busid) - { + if (busid) { std::vector slices; string_utils::split(slices, busid.Get(), '.'); - if (slices.size() != 4) - { + if (slices.size() != 4) { std::cout << "Bus id is invalid, it likes 8.8.8.8" << std::endl; return false; } @@ -269,15 +254,12 @@ bool parse_args(int argc, char* argv[], std::chrono::milliseconds& shutdown_time bus_addr bus_addr; bus_addr.from_string(busid.Get()); plugin_manager::instance()->set_bus_id(bus_addr.bus_id); - } - else - { + } else { return false; } // Set app name - if (name) - { + if (name) { plugin_manager::instance()->set_app_name(name.Get()); std::string process_name = @@ -285,8 +267,7 @@ bool parse_args(int argc, char* argv[], std::chrono::milliseconds& shutdown_time // Set process name #ifdef ARK_PLATFORM_WIN std::wstring title; - if (!utf16_text(process_name, title)) - { + if (!utf16_text(process_name, title)) { std::cerr << "Application name could not be converted to UTF-16" << std::endl; configuration_error = true; return false; @@ -295,19 +276,14 @@ bool parse_args(int argc, char* argv[], std::chrono::milliseconds& shutdown_time #elif defined(ARK_PLATFORM_LINUX) // Do not need to change process name #endif - } - else - { + } else { return false; } // Set plugin file - if (app_conf) - { + if (app_conf) { plugin_manager::instance()->set_app_conf(app_conf.Get()); - } - else - { + } else { return false; } @@ -315,10 +291,9 @@ bool parse_args(int argc, char* argv[], std::chrono::milliseconds& shutdown_time } bool capture_update_exception(std::exception_ptr& error) noexcept { - try - { return plugin_manager::instance()->update(date_time::get_now_time()); } - catch (...) - { + try { + return plugin_manager::instance()->update(date_time::get_now_time()); + } catch (...) { error = std::current_exception(); return false; } @@ -326,14 +301,13 @@ bool capture_update_exception(std::exception_ptr& error) noexcept { bool main_loop(std::exception_ptr* error = nullptr) { #ifdef ARK_PLATFORM_WIN - __try - { + __try { // Catch C++ exceptions before the outer SEH filter sees them. The // shutdown owner rethrows only after this guarded frame returns. return error ? capture_update_exception(*error) : plugin_manager::instance()->update(date_time::get_now_time()); + } __except (application_crash_handler(GetExceptionInformation())) { + return false; } - __except (application_crash_handler(GetExceptionInformation())) - { return false; } #else return error ? capture_update_exception(*error) : plugin_manager::instance()->update(date_time::get_now_time()); #endif @@ -342,65 +316,54 @@ bool main_loop(std::exception_ptr* error = nullptr) { static int run_application(int argc, char* argv[]) { std::chrono::milliseconds shutdown_timeout{}; bool configuration_error = false; - if (!parse_args(argc, argv, shutdown_timeout, configuration_error)) - { + if (!parse_args(argc, argv, shutdown_timeout, configuration_error)) { std::cout << "Application parameter is invalid, please check it..." << std::endl; return configuration_error ? 1 : 0; } const auto& app_conf_path = plugin_manager::instance()->get_app_conf(); application_manifest manifest; - try - { manifest = load_application_manifest(app_conf_path); } - catch (const application_manifest_error& error) - { + try { + manifest = load_application_manifest(app_conf_path); + } catch (const application_manifest_error& error) { std::cerr << "Application manifest loading failed: " << error.what() << std::endl; return 1; } - try - { + try { const auto filename = ARK_FORMAT("{}_{}.log", plugin_manager::instance()->get_app_name(), misc::bus2_str(plugin_manager::instance()->get_bus_id())); logger::init(nullptr); - if (!logger::instance()->init_logger(manifest.logging, filename)) - { + if (!logger::instance()->init_logger(manifest.logging, filename)) { std::cerr << "Application logging initialization failed: logger already initialized" << std::endl; return 1; } - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { std::cerr << "Application logging initialization failed (" << app_conf_path << "): " << error.what() << std::endl; return 1; } print_logo(); - try - { + try { if (!plugin_manager::instance()->start( - date_time::get_now_time(), manifest.plugin_library_dir, manifest.plugin_config_dir, manifest.plugins)) - { + date_time::get_now_time(), manifest.plugin_library_dir, manifest.plugin_config_dir, manifest.plugins)) { app_detail::exit_startup_failure(*plugin_manager::instance(), "returned false"); } + } catch (const std::exception& error) { + app_detail::exit_startup_failure(*plugin_manager::instance(), error.what()); + } catch (...) { + app_detail::exit_startup_failure(*plugin_manager::instance(), "unknown exception"); } - catch (const std::exception& error) - { app_detail::exit_startup_failure(*plugin_manager::instance(), error.what()); } - catch (...) - { app_detail::exit_startup_failure(*plugin_manager::instance(), "unknown exception"); } #ifdef ARK_PLATFORM_WIN create_back_thread(); #endif - for (;; std::this_thread::sleep_for(std::chrono::milliseconds(1))) - { + for (;; std::this_thread::sleep_for(std::chrono::milliseconds(1))) { const auto stop_reason = app_detail::requested_stop_reason(); - if (stop_reason != 0) - { - if (stop_reason > 0) - { + if (stop_reason != 0) { + if (stop_reason > 0) { ARK_LOG_INFO("Server stop requested by signal {}", stop_reason); } break; @@ -416,33 +379,27 @@ static int run_application(int argc, char* argv[]) { const auto shutdown_started = std::chrono::steady_clock::now(); auto shutdown_deadline = std::chrono::steady_clock::time_point::max(); if (shutdown_timeout.count() > 0 && shutdown_timeout < std::chrono::duration_cast( - std::chrono::steady_clock::duration::max())) - { + std::chrono::steady_clock::duration::max())) { const auto delay = std::chrono::duration_cast(shutdown_timeout); - if (shutdown_started <= shutdown_deadline - delay) - { + if (shutdown_started <= shutdown_deadline - delay) { shutdown_deadline = shutdown_started + delay; } } bool shutdown_retained = false; bool shutdown_failure_reported = false; bool shutdown_update_error_reported = false; - for (;;) - { - if (!shutdown_retained) - { + for (;;) { + if (!shutdown_retained) { const auto stopped = shutdown_timeout.count() > 0 ? plugin_manager::instance()->stop_until(date_time::get_now_time(), shutdown_deadline) : plugin_manager::instance()->stop(date_time::get_now_time()); - if (stopped) - { + if (stopped) { break; } const auto state = plugin_manager::instance()->get_shutdown_state(); if (state == plugin_manager::shutdown_state::timed_out || - state == plugin_manager::shutdown_state::cleanup_timed_out) - { + state == plugin_manager::shutdown_state::cleanup_timed_out) { shutdown_retained = true; const auto elapsed = std::chrono::duration_cast( std::chrono::steady_clock::now() - shutdown_started); @@ -452,67 +409,48 @@ static int run_application(int argc, char* argv[]) { plugin_manager::instance()->get_shutdown_failure()); } } - if (plugin_manager::instance()->get_shutdown_state() == plugin_manager::shutdown_state::failed) - { - if (!shutdown_failure_reported) - { - try - { - if (const auto error = plugin_manager::instance()->get_shutdown_exception()) - { + if (plugin_manager::instance()->get_shutdown_state() == plugin_manager::shutdown_state::failed) { + if (!shutdown_failure_reported) { + try { + if (const auto error = plugin_manager::instance()->get_shutdown_exception()) { std::rethrow_exception(error); } ARK_LOG_ERROR("Shutdown failed at {}; process and resources are retained", plugin_manager::instance()->get_shutdown_failure()); - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { ARK_LOG_ERROR("Shutdown failed at {}: {}; process and resources are retained", plugin_manager::instance()->get_shutdown_failure(), error.what()); - } - catch (...) - { + } catch (...) { ARK_LOG_ERROR("Shutdown failed at {} with an unknown exception; process and resources are retained", plugin_manager::instance()->get_shutdown_failure()); } shutdown_failure_reported = true; } - } - else if (plugin_manager::instance()->get_shutdown_state() != plugin_manager::shutdown_state::cleanup_timed_out) - { - try - { + } else if (plugin_manager::instance()->get_shutdown_state() != + plugin_manager::shutdown_state::cleanup_timed_out) { + try { std::exception_ptr update_error; const auto updated = main_loop(&update_error); - if (update_error) - { + if (update_error) { std::rethrow_exception(update_error); } - if (!updated) - { + if (!updated) { shutdown_retained = true; - if (!shutdown_update_error_reported) - { + if (!shutdown_update_error_reported) { ARK_LOG_ERROR( "{}", "Shutdown update failed: update returned false; process and resources are retained"); shutdown_update_error_reported = true; } } - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { shutdown_retained = true; - if (!shutdown_update_error_reported) - { + if (!shutdown_update_error_reported) { ARK_LOG_ERROR("Shutdown update failed: {}; process and resources are retained", error.what()); shutdown_update_error_reported = true; } - } - catch (...) - { + } catch (...) { shutdown_retained = true; - if (!shutdown_update_error_reported) - { + if (!shutdown_update_error_reported) { ARK_LOG_ERROR( "{}", "Shutdown update failed with an unknown exception; process and resources are retained"); shutdown_update_error_reported = true; @@ -538,37 +476,30 @@ static int run_application(int argc, char* argv[]) { int wmain(int argc, wchar_t* argv[]) { std::vector arguments; std::vector utf8_argv; - try - { + try { arguments.reserve(argc); utf8_argv.reserve(argc + 1); - for (int index = 0; index < argc; ++index) - { + for (int index = 0; index < argc; ++index) { const auto count = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, argv[index], -1, nullptr, 0, nullptr, nullptr); - if (count == 0) - { + if (count == 0) { std::fputs("Application arguments contain invalid UTF-16\n", stderr); return 1; } std::string argument(count, '\0'); if (WideCharToMultiByte( - CP_UTF8, WC_ERR_INVALID_CHARS, argv[index], -1, argument.data(), count, nullptr, nullptr) == 0) - { + CP_UTF8, WC_ERR_INVALID_CHARS, argv[index], -1, argument.data(), count, nullptr, nullptr) == 0) { std::fputs("Application arguments could not be converted to UTF-8\n", stderr); return 1; } argument.resize(count - 1); arguments.push_back(std::move(argument)); } - for (auto& argument : arguments) - { + for (auto& argument : arguments) { utf8_argv.push_back(argument.data()); } utf8_argv.push_back(nullptr); - } - catch (const std::exception&) - { + } catch (const std::exception&) { std::fputs("Application arguments could not be prepared as UTF-8\n", stderr); return 1; } diff --git a/src/application/startup_failure.hpp b/src/application/startup_failure.hpp index 817f53e18..bcc770c07 100644 --- a/src/application/startup_failure.hpp +++ b/src/application/startup_failure.hpp @@ -19,24 +19,20 @@ namespace ark::app_detail { inline void write_native_stderr(std::string_view line) noexcept { std::size_t written{}; - while (written < line.size()) - { + while (written < line.size()) { #ifdef ARK_PLATFORM_WIN DWORD count{}; if (!WriteFile(GetStdHandle(STD_ERROR_HANDLE), line.data() + written, static_cast(line.size() - written), &count, nullptr) || - count == 0) - { + count == 0) { break; } #else const auto count = ::write(STDERR_FILENO, line.data() + written, line.size() - written); - if (count < 0 && errno == EINTR) - { + if (count < 0 && errno == EINTR) { continue; } - if (count <= 0) - { + if (count <= 0) { break; } #endif @@ -51,23 +47,19 @@ inline void write_startup_failure( char line[1024]; std::size_t size{}; const auto append = [&](std::string_view value) { - for (const char character : value) - { - if (size == sizeof(line) - 1) - { + for (const char character : value) { + if (size == sizeof(line) - 1) { break; } line[size++] = character; } }; append("Application startup failed"); - if (!phase.empty()) - { + if (!phase.empty()) { append(" at "); append(phase); } - if (!owner.empty()) - { + if (!owner.empty()) { append(": "); append(owner); } @@ -89,16 +81,12 @@ inline void write_startup_failure( // The manager already exists before start; no allocation, logger callback or // virtual name lookup is needed to preserve the primary failure diagnostic. const auto& call = manager.get_startup_call(); - if (call.result == startup_call_result::exception && !call.diagnostic_ready) - { + if (call.result == startup_call_result::exception && !call.diagnostic_ready) { write_startup_failure(call.phase.data(), detail, call.owner.data()); - } - else - { + } else { write_startup_failure(manager.get_startup_failure(), detail); } - switch (manager.cleanup_failed_startup()) - { + switch (manager.cleanup_failed_startup()) { case startup_cleanup_result::done: write_native_stderr("Startup failure cleanup: done\n"); break; diff --git a/src/config/application_manifest.cpp b/src/config/application_manifest.cpp index 8bdb94492..363fd16be 100644 --- a/src/config/application_manifest.cpp +++ b/src/config/application_manifest.cpp @@ -15,15 +15,12 @@ namespace { } void validate_keys(const toml::table& table, std::initializer_list allowed, const std::string& path) { - for (const auto& [key, value] : table) - { + for (const auto& [key, value] : table) { bool known = false; - for (const auto candidate : allowed) - { + for (const auto candidate : allowed) { known = known || key.str() == candidate; } - if (!known) - { + if (!known) { fail_at(path, "unknown manifest field", key.source()); } } @@ -32,25 +29,20 @@ void validate_keys(const toml::table& table, std::initializer_listas_string(); - if (value == nullptr) - { + if (value == nullptr) { fail_at(path, "manifest field must be a string", node->source()); } - if (value->get().find('\0') != std::string::npos) - { + if (value->get().find('\0') != std::string::npos) { fail_at(path, "manifest string contains NUL", node->source()); } - if (required && value->get().empty()) - { + if (required && value->get().empty()) { fail_at(path, "plugin name must not be empty", node->source()); } return value->get(); @@ -58,67 +50,48 @@ std::string read_string( logger_settings parse_logger( const toml::table& table, const std::string& path, logger_settings result, const std::string& prefix = "logging.") { - for (const auto& [key, node] : table) - { + for (const auto& [key, node] : table) { const auto field = prefix + std::string(key.str()); const auto invalid = [&](const char* reason) { throw application_manifest_error( path, field + " " + reason, node.source().begin.line, node.source().begin.column); }; - if (key == "loggers") - { + if (key == "loggers") { continue; } - if (key == "console" || key == "file") - { + if (key == "console" || key == "file") { const auto value = node.value(); - if (!node.is_boolean() || !value) - { + if (!node.is_boolean() || !value) { invalid("must be a boolean"); } (key == "console" ? result.console : result.file) = *value; - } - else if (key == "queue_count") - { + } else if (key == "queue_count") { const auto value = node.value(); - if (!node.is_integer() || !value || *value < 0 || *value > 65535) - { + if (!node.is_integer() || !value || *value < 0 || *value > 65535) { invalid("must be an integer between 0 and 65535"); } result.queue_count = static_cast(*value); - } - else if (key == "level" || key == "pattern" || key == "output_path") - { + } else if (key == "level" || key == "pattern" || key == "output_path") { const auto value = node.value(); - if (!value || value->empty() || value->find('\0') != std::string::npos) - { + if (!value || value->empty() || value->find('\0') != std::string::npos) { invalid("must be a non-empty string without NUL"); } - if (key == "level") - { + if (key == "level") { if (*value != "trace" && *value != "debug" && *value != "info" && *value != "warn" && - *value != "error" && *value != "critical" && *value != "off") - { + *value != "error" && *value != "critical" && *value != "off") { invalid("must be trace, debug, info, warn, error, critical or off"); } result.level = *value; - } - else if (key == "pattern") - { + } else if (key == "pattern") { result.pattern = *value; - } - else - { + } else { result.output_path = *value; } - } - else - { + } else { invalid("is unknown"); } } - if (!result.console && !result.file) - { + if (!result.console && !result.file) { fail_at(path, "logging requires console or file output", table.source()); } return result; @@ -126,32 +99,25 @@ logger_settings parse_logger( logging_settings parse_logging(const toml::node* node, const std::string& path) { logging_settings result; - if (node == nullptr) - { + if (node == nullptr) { return result; } const auto* table = node->as_table(); - if (table == nullptr) - { + if (table == nullptr) { fail_at(path, "logging must be a table", node->source()); } static_cast(result) = parse_logger(*table, path, result); - if (const auto* loggers = table->get("loggers")) - { + if (const auto* loggers = table->get("loggers")) { const auto* named = loggers->as_table(); - if (named == nullptr) - { + if (named == nullptr) { fail_at(path, "logging.loggers must be a table", loggers->source()); } - for (const auto& [key, entry] : *named) - { + for (const auto& [key, entry] : *named) { const auto* settings = entry.as_table(); - if (key.str().empty() || key.str().find('\0') != std::string_view::npos || settings == nullptr) - { + if (key.str().empty() || key.str().find('\0') != std::string_view::npos || settings == nullptr) { fail_at(path, "logging.loggers entries require a non-empty name and table", entry.source()); } - if (settings->contains("loggers")) - { + if (settings->contains("loggers")) { fail_at(path, "nested logging.loggers is invalid", settings->source()); } result.loggers.emplace(std::string(key.str()), @@ -165,13 +131,11 @@ application_manifest parse_toml(const std::string& path, std::string_view conten const auto document = config_detail::parse_toml(path, contents, "invalid TOML syntax or encoding"); validate_keys(document, {"application", "plugins", "logging"}, path); const auto* application_node = document.get("application"); - if (application_node == nullptr) - { + if (application_node == nullptr) { throw application_manifest_error(path, "missing application table", 1, 1); } const auto* application = application_node->as_table(); - if (application == nullptr) - { + if (application == nullptr) { fail_at(path, "application must be a table", application_node->source()); } validate_keys(*application, {"plugin_library_dir", "plugin_config_dir"}, path); @@ -180,27 +144,22 @@ application_manifest parse_toml(const std::string& path, std::string_view conten result.plugin_library_dir = read_string(*application, "plugin_library_dir", path); result.plugin_config_dir = read_string(*application, "plugin_config_dir", path); const auto* plugins_node = document.get("plugins"); - if (plugins_node == nullptr) - { + if (plugins_node == nullptr) { return result; } const auto* plugins = plugins_node->as_array(); - if (plugins == nullptr) - { + if (plugins == nullptr) { fail_at(path, "plugins must be an array of tables", plugins_node->source()); } - for (const auto& node : *plugins) - { + for (const auto& node : *plugins) { const auto* plugin = node.as_table(); - if (plugin == nullptr) - { + if (plugin == nullptr) { fail_at(path, "plugin entry must be a table", node.source()); } validate_keys(*plugin, {"name", "config"}, path); auto name = read_string(*plugin, "name", path, true); auto config = read_string(*plugin, "config", path); - if (!result.plugins.emplace(std::move(name), std::move(config)).second) - { + if (!result.plugins.emplace(std::move(name), std::move(config)).second) { fail_at(path, "duplicate plugin name", plugin->source()); } } @@ -230,18 +189,16 @@ std::size_t application_manifest_error::column() const noexcept { } application_manifest load_application_manifest(const std::string& path) { - if (!path.ends_with(".toml")) - { + if (!path.ends_with(".toml")) { throw application_manifest_error( path, "application manifest path must end in .toml; XML manifests are no longer supported"); } - try - { + try { const auto contents = config_detail::read_file(path, "manifest"); return parse_toml(path, contents); + } catch (const config_detail::read_error& error) { + throw application_manifest_error(path, error.reason, error.line, error.column); } - catch (const config_detail::read_error& error) - { throw application_manifest_error(path, error.reason, error.line, error.column); } } } // namespace ark diff --git a/src/config/application_manifest.hpp b/src/config/application_manifest.hpp index d3b72e6b3..b664c2929 100644 --- a/src/config/application_manifest.hpp +++ b/src/config/application_manifest.hpp @@ -9,8 +9,7 @@ namespace ark { // Standard-library-only settings shared by the reader and runtime logger. -struct logger_settings -{ +struct logger_settings { bool console{true}; bool file{false}; std::string level{"info"}; @@ -19,21 +18,18 @@ struct logger_settings std::size_t queue_count{0}; }; -struct logging_settings : logger_settings -{ +struct logging_settings : logger_settings { std::unordered_map loggers; }; -struct application_manifest -{ +struct application_manifest { std::string plugin_library_dir; std::string plugin_config_dir; std::unordered_map plugins; logging_settings logging; }; -class application_manifest_error : public std::runtime_error -{ +class application_manifest_error : public std::runtime_error { public: application_manifest_error( const std::string& path, const std::string& reason, std::size_t line = 0, std::size_t column = 0); diff --git a/src/config/configuration_reader.cpp b/src/config/configuration_reader.cpp index 86058d6cc..802a1f828 100644 --- a/src/config/configuration_reader.cpp +++ b/src/config/configuration_reader.cpp @@ -10,10 +10,8 @@ namespace ark::config_detail { std::string diagnostic_path(std::string_view path) { std::string result; - for (const auto character : path) - { - switch (character) - { + for (const auto character : path) { + switch (character) { case '\0': result += "\\0"; break; @@ -33,8 +31,7 @@ std::string diagnostic_path(std::string_view path) { std::string error_message(const std::string& path, const std::string& reason, std::size_t line, std::size_t column) { auto message = diagnostic_path(path); - if (line != 0) - { + if (line != 0) { message += ":" + std::to_string(line) + ":" + std::to_string(column); } return message + ": " + reason; @@ -47,15 +44,11 @@ std::string error_message(const std::string& path, const std::string& reason, st // Match the TOML parser's source positions: columns count code points, // and the optional UTF-8 BOM is not part of the first line. const std::size_t begin = contents.starts_with("\xef\xbb\xbf") ? 3 : 0; - for (std::size_t index = begin; index < offset && index < contents.size(); ++index) - { - if (contents[index] == '\n') - { + for (std::size_t index = begin; index < offset && index < contents.size(); ++index) { + if (contents[index] == '\n') { ++line; column = 1; - } - else if ((static_cast(contents[index]) & 0xc0u) != 0x80u) - { + } else if ((static_cast(contents[index]) & 0xc0u) != 0x80u) { ++column; } } @@ -70,43 +63,39 @@ read_error::read_error(const std::string& path, std::string reason, std::size_t } std::string read_file(const std::string& path, std::string_view kind) { - if (path.find('\0') != std::string::npos) - { + if (path.find('\0') != std::string::npos) { throw read_error(path, std::string(kind) + " path contains NUL"); } std::string contents; - try - { + try { const std::filesystem::path native_path(std::u8string(path.begin(), path.end())); - if (std::filesystem::is_directory(native_path)) - { + if (std::filesystem::is_directory(native_path)) { throw read_error(path, std::string(kind) + " path is a directory"); } std::ifstream input(native_path, std::ios::binary); input.exceptions(std::ios::badbit); - if (!input) - { + if (!input) { throw read_error(path, "could not open " + std::string(kind)); } contents.assign(std::istreambuf_iterator(input), std::istreambuf_iterator()); + } catch (const std::filesystem::filesystem_error&) { + throw read_error(path, "could not open " + std::string(kind) + " path"); + } catch (const std::ios_base::failure&) { + throw read_error(path, "could not read " + std::string(kind)); } - catch (const std::filesystem::filesystem_error&) - { throw read_error(path, "could not open " + std::string(kind) + " path"); } - catch (const std::ios_base::failure&) - { throw read_error(path, "could not read " + std::string(kind)); } const auto nul = contents.find('\0'); - if (nul != std::string::npos) - { + if (nul != std::string::npos) { fail_at(path, std::string(kind) + " contains NUL", contents, nul); } return contents; } toml::table parse_toml(const std::string& path, std::string_view contents, const std::string& reason) { - try - { return toml::parse(contents); } - catch (const toml::parse_error& error) - { throw read_error(path, reason, error.source().begin.line, error.source().begin.column); } + try { + return toml::parse(contents); + } catch (const toml::parse_error& error) { + throw read_error(path, reason, error.source().begin.line, error.source().begin.column); + } } toml::table read_toml(const std::string& path) { diff --git a/src/config/configuration_reader.hpp b/src/config/configuration_reader.hpp index 5364607f9..ab1c254fd 100644 --- a/src/config/configuration_reader.hpp +++ b/src/config/configuration_reader.hpp @@ -12,8 +12,7 @@ namespace ark::config_detail { // Private transport/parser diagnostics. Schema owners translate these when they // expose a more specific public exception, such as application_manifest_error. -class read_error : public std::runtime_error -{ +class read_error : public std::runtime_error { public: read_error(const std::string& path, std::string reason, std::size_t line = 0, std::size_t column = 0); diff --git a/src/core/app.hpp b/src/core/app.hpp index 8ebb8de80..0fa8b3f59 100644 --- a/src/core/app.hpp +++ b/src/core/app.hpp @@ -24,8 +24,7 @@ namespace ark { -enum class app_type : uint8_t -{ +enum class app_type : uint8_t { ark_app_default, // none ark_app_master, // master //cluster level start ark_app_router, // router, world & cluster middle layer diff --git a/src/core/array_pod.hpp b/src/core/array_pod.hpp index e813e9190..80f126e24 100644 --- a/src/core/array_pod.hpp +++ b/src/core/array_pod.hpp @@ -30,8 +30,7 @@ namespace ark { -class pod_array_allocator -{ +class pod_array_allocator { public: pod_array_allocator() = default; ~pod_array_allocator() = default; @@ -54,8 +53,7 @@ template -class pod_array -{ +class pod_array { public: using self_t = pod_array; @@ -68,13 +66,10 @@ class pod_array pod_array(const self_t& src) { size_ = src.size_; - if (size_ <= inline_capacity) - { + if (size_ <= inline_capacity) { data_ = inline_buffer_; capacity_ = inline_capacity; - } - else - { + } else { capacity_ = src.capacity_; data_ = allocate(capacity_); } @@ -83,8 +78,7 @@ class pod_array } ~pod_array() { - if (capacity_ > inline_capacity) - { + if (capacity_ > inline_capacity) { allocator_.free(data_, capacity_ * sizeof(element_type)); } } @@ -101,21 +95,17 @@ class pod_array element_type* tmp_data = src.data_; element_type tmp_stack[inline_capacity]; - if (tmp_capacity <= inline_capacity) - { + if (tmp_capacity <= inline_capacity) { memcpy(tmp_stack, src.inline_buffer_, tmp_size * sizeof(element_type)); } src.size_ = this->size_; src.capacity_ = this->capacity_; - if (this->capacity_ <= inline_capacity) - { + if (this->capacity_ <= inline_capacity) { memcpy(src.inline_buffer_, this->inline_buffer_, size_ * sizeof(element_type)); src.data_ = src.inline_buffer_; - } - else - { + } else { src.data_ = this->data_; } @@ -123,13 +113,10 @@ class pod_array this->size_ = tmp_size; this->capacity_ = tmp_capacity; - if (tmp_capacity <= inline_capacity) - { + if (tmp_capacity <= inline_capacity) { memcpy(this->inline_buffer_, tmp_stack, tmp_size * sizeof(element_type)); this->data_ = this->inline_buffer_; - } - else - { + } else { this->data_ = tmp_data; } @@ -151,8 +138,7 @@ class pod_array void push_back(const element_type& data) { const size_t new_size = incremented_size(); const element_type value = data; - if (new_size > capacity_) - { + if (new_size > capacity_) { reserve(grown_capacity(new_size)); } @@ -186,13 +172,11 @@ class pod_array } void reserve(size_t size) { - if (size > capacity_) - { + if (size > capacity_) { element_type* p = allocate(size); memcpy(p, data_, size_ * sizeof(element_type)); - if (capacity_ > inline_capacity) - { + if (capacity_ > inline_capacity) { allocator_.free(data_, capacity_ * sizeof(element_type)); } @@ -202,8 +186,7 @@ class pod_array } void resize(size_t size) { - if (size > capacity_) - { + if (size > capacity_) { reserve(grown_capacity(size)); } @@ -211,16 +194,14 @@ class pod_array } void resize(size_t size, const element_type& value) { - if (size <= size_) - { + if (size <= size_) { size_ = size; return; } const element_type saved_value = value; const size_t old_size = size_; resize(size); - for (size_t i = old_size; i < size; ++i) - { + for (size_t i = old_size; i < size; ++i) { data_[i] = saved_value; } } @@ -258,8 +239,7 @@ class pod_array size_t get_mem_usage() const { size_t size = sizeof(self_t); - if (capacity_ > size) - { + if (capacity_ > size) { size += capacity_ * sizeof(element_type); } @@ -272,15 +252,13 @@ class pod_array } static void check_capacity(size_t size) { - if (size > max_capacity()) - { + if (size > max_capacity()) { throw std::length_error("pod_array capacity exceeds addressable storage"); } } size_t incremented_size() const { - if (size_ == max_capacity()) - { + if (size_ == max_capacity()) { throw std::length_error("pod_array size exceeds addressable storage"); } return size_ + 1; @@ -295,8 +273,7 @@ class pod_array element_type* allocate(size_t size) { check_capacity(size); auto* result = static_cast(allocator_.alloc(size * sizeof(element_type))); - if (result == nullptr) - { + if (result == nullptr) { throw std::bad_alloc{}; } return result; diff --git a/src/core/buffer.hpp b/src/core/buffer.hpp index 7f3dd4a67..57adaf010 100644 --- a/src/core/buffer.hpp +++ b/src/core/buffer.hpp @@ -32,10 +32,8 @@ namespace ark { -class buffer final -{ - struct data_deleter - { +class buffer final { + struct data_deleter { void operator()(char* value) const noexcept { ARK_DELETE_ARRAY(char, value); } @@ -50,8 +48,7 @@ class buffer final public: explicit buffer(size_t buffer_size = 1024 * 512) { data_.reset(allocate_data(buffer_size)); - if (data_ != nullptr) - { + if (data_ != nullptr) { data_size_ = buffer_size; } } @@ -69,8 +66,7 @@ class buffer final } buffer& operator=(buffer&& other) noexcept { - if (this != &other) - { + if (this != &other) { data_ = std::move(other.data_); data_size_ = std::exchange(other.data_size_, 0); write_pos_ = std::exchange(other.write_pos_, 0); @@ -84,39 +80,31 @@ class buffer final } bool write(const char* data, size_t len) { - if (len == 0) - { + if (len == 0) { return true; } - if (data == nullptr) - { + if (data == nullptr) { return false; } owned_data snapshot; const std::less before; - if (data_ && !before(data, data_.get()) && before(data, data_.get() + data_size_)) - { + if (data_ && !before(data, data_.get()) && before(data, data_.get() + data_size_)) { const auto offset = static_cast(data - data_.get()); - if (len > data_size_ - offset) - { + if (len > data_size_ - offset) { return false; } - if (get_write_valid_count() < len) - { + if (get_write_valid_count() < len) { // Compaction can overwrite the source; growth releases its allocation. snapshot.reset(allocate_data(len)); - if (!snapshot) - { + if (!snapshot) { return false; } std::memcpy(snapshot.get(), data, len); data = snapshot.get(); } } - if (get_write_valid_count() < len) [[unlikely]] - { - if (!prepare_write(len)) - { + if (get_write_valid_count() < len) [[unlikely]] { + if (!prepare_write(len)) { return false; } } @@ -130,19 +118,15 @@ class buffer final } char* get_data() { - if (read_pos_ < data_size_) - { + if (read_pos_ < data_size_) { return data_.get() + read_pos_; - } - else - { + } else { return nullptr; } } void remove_data(size_t value) { - if (value <= get_length()) - { + if (value <= get_length()) { read_pos_ += value; } } @@ -150,8 +134,7 @@ class buffer final private: bool prepare_write(size_t len) { const size_t left_len = data_size_ - get_length(); - if (left_len >= len) - { + if (left_len >= len) { adjust_to_head(); return true; } @@ -161,15 +144,13 @@ class buffer final void adjust_to_head() { size_t len = 0; - if (read_pos_ <= 0) - { + if (read_pos_ <= 0) { return; } len = get_length(); - if (len > 0) - { + if (len > 0) { std::memmove(data_.get(), data_.get() + read_pos_, len); } @@ -189,8 +170,7 @@ class buffer final void add_write_pos(size_t value) { size_t temp = write_pos_ + value; - if (temp <= data_size_) - { + if (temp <= data_size_) { write_pos_ = temp; } } @@ -204,32 +184,26 @@ class buffer final } char* get_write_ptr() { - if (write_pos_ < data_size_) - { + if (write_pos_ < data_size_) { return data_.get() + write_pos_; - } - else - { + } else { return nullptr; } } bool grow(size_t len) { - if (len > std::numeric_limits::max() - data_size_) - { + if (len > std::numeric_limits::max() - data_size_) { throw std::length_error("Receive buffer size exceeds the addressable range"); } const size_t required = data_size_ + len; const size_t doubled = data_size_ <= std::numeric_limits::max() / 2 ? data_size_ * 2 : required; const size_t n = std::max(required, doubled); owned_data candidate(allocate_data(n)); - if (!candidate) - { + if (!candidate) { return false; } const size_t unread = get_length(); - if (unread > 0) - { + if (unread > 0) { std::memcpy(candidate.get(), data_.get() + read_pos_, unread); } data_ = std::move(candidate); diff --git a/src/core/bus.hpp b/src/core/bus.hpp index f2b4fdd7e..aa41788b7 100644 --- a/src/core/bus.hpp +++ b/src/core/bus.hpp @@ -29,8 +29,7 @@ namespace ark { // bus address, like IP address, 8.8.8.8 -class bus_addr -{ +class bus_addr { public: bus_id_t bus_id{0}; @@ -98,16 +97,14 @@ class bus_addr }; // bus relation, app connect other app with direct way or waiting sync message -class bus_relation -{ +class bus_relation { public: uint8_t app_type{std::underlying_type::type(ark::app_type::ark_app_default)}; uint8_t target_app_type{std::underlying_type::type(ark::app_type::ark_app_default)}; bool connection_type{false}; }; -class proc_config -{ +class proc_config { public: bus_id_t bus_id{0}; uint32_t max_connection{0}; @@ -117,8 +114,7 @@ class proc_config // to add other fields }; -class reg_center -{ +class reg_center { public: std::string ip{}; uint16_t port{8500}; @@ -127,8 +123,7 @@ class reg_center std::string check_timeout{"3s"}; }; -class app_config -{ +class app_config { public: ark::reg_center reg_center; // register center diff --git a/src/core/client_connect.hpp b/src/core/client_connect.hpp index e0d648d13..7b6372e53 100644 --- a/src/core/client_connect.hpp +++ b/src/core/client_connect.hpp @@ -25,8 +25,7 @@ namespace ark { -class client_connect -{ +class client_connect { public: using ret_type = std::pair; @@ -39,14 +38,12 @@ class client_connect ///user session manager ret_type add_session(const std::string& open_id, const conv_id_t& sesssion_id) { ret_type ret(false, 0U); - if (open_id.empty() || sesssion_id == 0) - { + if (open_id.empty() || sesssion_id == 0) { return ret; } auto iter_open_id = user_sesssion_list_.find(open_id); - if (iter_open_id != user_sesssion_list_.end()) - { + if (iter_open_id != user_sesssion_list_.end()) { ret.second = iter_open_id->second; remove_session(iter_open_id->second); } @@ -60,15 +57,13 @@ class client_connect bool remove_session(const conv_id_t& sesssion_id) { auto iter_session_id = sesssion_user_list_.find(sesssion_id); - if (iter_session_id == sesssion_user_list_.end()) - { + if (iter_session_id == sesssion_user_list_.end()) { return false; } auto& open_id = iter_session_id->second; auto iter_open_id = user_sesssion_list_.find(open_id); - if (iter_open_id != user_sesssion_list_.end()) - { + if (iter_open_id != user_sesssion_list_.end()) { user_sesssion_list_.erase(iter_open_id); } @@ -78,8 +73,7 @@ class client_connect const std::string& get_opend_id(const conv_id_t& sesssion_id) { auto iter_session_id = sesssion_user_list_.find(sesssion_id); - if (iter_session_id == sesssion_user_list_.end()) - { + if (iter_session_id == sesssion_user_list_.end()) { return null_str; } @@ -88,8 +82,7 @@ class client_connect conv_id_t get_session_id(const std::string& open_id) { auto iter_open_id = user_sesssion_list_.find(open_id); - if (iter_open_id == user_sesssion_list_.end()) - { + if (iter_open_id == user_sesssion_list_.end()) { return null_int64; } diff --git a/src/core/compress/lz4.hpp b/src/core/compress/lz4.hpp index bf2688b80..004e244bb 100644 --- a/src/core/compress/lz4.hpp +++ b/src/core/compress/lz4.hpp @@ -32,27 +32,23 @@ namespace ark { #define PRE_ALLOCATED_LZ4_BUFF_SIZE (1024 * 1024) -class lz4_compress -{ +class lz4_compress { public: static bool compress( IN const char* in_data, IN std::size_t in_size, IN int c_level, OUT std::string& compress_buff) { - if (in_size > static_cast((std::numeric_limits::max)())) - { + if (in_size > static_cast((std::numeric_limits::max)())) { return false; } const int source_size = static_cast(in_size); const int pre_buff_size = LZ4_compressBound(source_size); - if (pre_buff_size <= 0 || pre_buff_size >= PRE_ALLOCATED_LZ4_BUFF_SIZE) - { + if (pre_buff_size <= 0 || pre_buff_size >= PRE_ALLOCATED_LZ4_BUFF_SIZE) { return false; } std::vector pre_buffer(pre_buff_size); const int compressed_size = LZ4_compress_fast(in_data, pre_buffer.data(), source_size, pre_buff_size, c_level); - if (compressed_size <= 0) - { + if (compressed_size <= 0) { return false; } @@ -61,16 +57,14 @@ class lz4_compress } static bool decompress(IN const char* in_data, IN std::size_t in_size, OUT std::string& decompress_buff) { - if (in_size > static_cast((std::numeric_limits::max)())) - { + if (in_size > static_cast((std::numeric_limits::max)())) { return false; } std::vector pre_buffer(PRE_ALLOCATED_LZ4_BUFF_SIZE); int const decompressed_size = LZ4_decompress_safe( in_data, pre_buffer.data(), static_cast(in_size), static_cast(pre_buffer.size())); - if (decompressed_size <= 0) - { + if (decompressed_size <= 0) { return false; } diff --git a/src/core/compress/zlib.hpp b/src/core/compress/zlib.hpp index 570d2ec4f..36a81a28d 100644 --- a/src/core/compress/zlib.hpp +++ b/src/core/compress/zlib.hpp @@ -36,27 +36,23 @@ namespace ark { // compressBound() returns an upper bound on the compressed size after compress() or compress2() on sourceLen bytes. // It would be used before a compress() or compress2() call to allocate the destination buffer. -class zlib_compress final -{ +class zlib_compress final { public: static bool compress( IN const char* in_data, IN std::size_t in_size, IN uint8_t compress_level, OUT std::string& compress_buff) { - if (in_size >= PRE_ALLOCATED_ZLIB_BUFF_SIZE || in_size > (std::numeric_limits::max)()) - { + if (in_size >= PRE_ALLOCATED_ZLIB_BUFF_SIZE || in_size > (std::numeric_limits::max)()) { return false; } uLongf pre_buff_size = compressBound(static_cast(in_size)); // calc needed size - if (pre_buff_size >= PRE_ALLOCATED_ZLIB_BUFF_SIZE) - { + if (pre_buff_size >= PRE_ALLOCATED_ZLIB_BUFF_SIZE) { return false; } std::vector pre_buffer(pre_buff_size); int ret = compress2(pre_buffer.data(), &pre_buff_size, reinterpret_cast(in_data), static_cast(in_size), compress_level); - if (ret != Z_OK) - { + if (ret != Z_OK) { return false; } @@ -65,8 +61,7 @@ class zlib_compress final } static bool decompress(IN const char* in_data, IN std::size_t in_size, OUT std::string& decompress_buff) { - if (in_size > (std::numeric_limits::max)()) - { + if (in_size > (std::numeric_limits::max)()) { return false; } @@ -74,8 +69,7 @@ class zlib_compress final uLongf pre_buff_size = static_cast(pre_buffer.size()); uLong source_size = static_cast(in_size); int ret = uncompress2(pre_buffer.data(), &pre_buff_size, reinterpret_cast(in_data), &source_size); - if (ret != Z_OK) - { + if (ret != Z_OK) { return false; } diff --git a/src/core/compress/zstd.hpp b/src/core/compress/zstd.hpp index a85dffb48..ff2143429 100644 --- a/src/core/compress/zstd.hpp +++ b/src/core/compress/zstd.hpp @@ -45,11 +45,9 @@ namespace ark { * TODO: 3. add streaming compress for some situations. */ -class zstd_compress final -{ +class zstd_compress final { private: - struct resource_deleter - { + struct resource_deleter { void operator()(ZSTD_CCtx* value) const noexcept { ZSTD_freeCCtx(value); } @@ -71,8 +69,7 @@ class zstd_compress final } }; - struct dictionary - { + struct dictionary { std::unique_ptr compress; std::unique_ptr decompress; }; @@ -91,8 +88,7 @@ class zstd_compress final zstd_compress& operator=(zstd_compress&& other) noexcept { static_assert(noexcept(dictionaries_ = std::move(other.dictionaries_))); - if (this != &other) - { + if (this != &other) { compress_ctx_ = std::move(other.compress_ctx_); decompress_ctx_ = std::move(other.decompress_ctx_); dictionaries_ = std::move(other.dictionaries_); @@ -103,22 +99,19 @@ class zstd_compress final /// simple compress and decompress bool normal_compress( IN const char* in_data, IN std::size_t in_size, IN uint8_t compress_level, OUT std::string& compressed_buff) { - if (in_size >= PRE_ALLOCATED_ZSTD_BUFF_SIZE) - { + if (in_size >= PRE_ALLOCATED_ZSTD_BUFF_SIZE) { return false; } size_t const pre_buff_size = ZSTD_compressBound(in_size); // calc needed size - if (pre_buff_size >= PRE_ALLOCATED_ZSTD_BUFF_SIZE) - { + if (pre_buff_size >= PRE_ALLOCATED_ZSTD_BUFF_SIZE) { return false; } std::vector pre_buffer(pre_buff_size); std::size_t const compressed_size = ZSTD_compress(pre_buffer.data(), pre_buff_size, in_data, in_size, compress_level); - if (ZSTD_isError(compressed_size)) - { + if (ZSTD_isError(compressed_size)) { return false; } @@ -130,8 +123,7 @@ class zstd_compress final bool normal_decompress(IN const char* in_data, IN std::size_t in_size, OUT std::string& decompressed_buff) { unsigned long long const r_size = ZSTD_getFrameContentSize(in_data, in_size); if (r_size == ZSTD_CONTENTSIZE_ERROR || r_size == ZSTD_CONTENTSIZE_UNKNOWN || - r_size > PRE_ALLOCATED_ZSTD_BUFF_SIZE) - { + r_size > PRE_ALLOCATED_ZSTD_BUFF_SIZE) { return false; } @@ -139,8 +131,7 @@ class zstd_compress final size_t const decompressed_size = ZSTD_decompress(pre_buffer.data(), static_cast(r_size), in_data, in_size); // When zstd knows the content size, it will error if it doesn't match. - if (ZSTD_isError(decompressed_size) || decompressed_size != r_size) - { + if (ZSTD_isError(decompressed_size) || decompressed_size != r_size) { return false; } @@ -168,19 +159,16 @@ class zstd_compress final bool dict_compress( IN uint16_t dict_type, IN const char* in_data, IN std::size_t in_size, OUT std::string& compressed_buff) { - if (in_size >= PRE_ALLOCATED_ZSTD_BUFF_SIZE) - { + if (in_size >= PRE_ALLOCATED_ZSTD_BUFF_SIZE) { return false; } size_t const pre_buff_size = ZSTD_compressBound(in_size); - if (pre_buff_size >= PRE_ALLOCATED_ZSTD_BUFF_SIZE) - { + if (pre_buff_size >= PRE_ALLOCATED_ZSTD_BUFF_SIZE) { return false; } - if (compress_ctx_ == nullptr) - { + if (compress_ctx_ == nullptr) { compress_ctx_.reset(ZSTD_createCCtx()); } @@ -192,8 +180,7 @@ class zstd_compress final std::vector pre_buffer(pre_buff_size); std::size_t const compressed_size = ZSTD_compress_usingCDict( compress_ctx_.get(), pre_buffer.data(), pre_buff_size, in_data, in_size, iter->second.compress.get()); - if (ZSTD_isError(compressed_size)) - { + if (ZSTD_isError(compressed_size)) { return false; } @@ -205,8 +192,7 @@ class zstd_compress final IN uint16_t dict_type, IN const char* in_data, IN std::size_t in_size, OUT std::string& decompressed_buff) { unsigned long long const r_size = ZSTD_getFrameContentSize(in_data, in_size); if (r_size == ZSTD_CONTENTSIZE_ERROR || r_size == ZSTD_CONTENTSIZE_UNKNOWN || - r_size > PRE_ALLOCATED_ZSTD_BUFF_SIZE) - { + r_size > PRE_ALLOCATED_ZSTD_BUFF_SIZE) { return false; } @@ -216,13 +202,11 @@ class zstd_compress final unsigned const expected_dict_id = ZSTD_getDictID_fromDDict(iter->second.decompress.get()); unsigned const actual_dict_id = ZSTD_getDictID_fromFrame(in_data, in_size); - if (actual_dict_id != expected_dict_id) - { + if (actual_dict_id != expected_dict_id) { return false; } - if (decompress_ctx_ == nullptr) - { + if (decompress_ctx_ == nullptr) { decompress_ctx_.reset(ZSTD_createDCtx()); } @@ -232,8 +216,7 @@ class zstd_compress final std::size_t decompressed_size = ZSTD_decompress_usingDDict(decompress_ctx_.get(), pre_buffer.data(), static_cast(r_size), in_data, in_size, iter->second.decompress.get()); // When zstd knows the content size, it will error if it doesn't match. - if (ZSTD_isError(decompressed_size) || decompressed_size != r_size) - { + if (ZSTD_isError(decompressed_size) || decompressed_size != r_size) { return false; } @@ -247,8 +230,7 @@ class zstd_compress final /* * Define the returned error code from utility functions. */ - enum common_error_code - { + enum common_error_code { error_fsize = 1, error_fopen = 2, error_fclose = 3, @@ -269,8 +251,7 @@ class zstd_compress final */ static void* malloc_or_die(std::size_t size) { void* const buff = malloc(size); - if (buff) - { + if (buff) { return buff; } @@ -286,8 +267,7 @@ class zstd_compress final */ static size_t fsize_or_die(const char* filename) { struct stat st; - if (stat(filename, &st) != 0) - { + if (stat(filename, &st) != 0) { /* error */ perror(filename); exit(common_error_code::error_fsize); @@ -299,8 +279,7 @@ class zstd_compress final * 2. if off_t -> size_t type conversion results in discrepancy, * the file size is too large for type size_t. */ - if ((file_size < 0) || (file_size != (off_t)size)) - { + if ((file_size < 0) || (file_size != (off_t)size)) { fprintf(stderr, "%s : filesize too large \n", filename); exit(common_error_code::error_large_file); } @@ -316,8 +295,7 @@ class zstd_compress final */ static FILE* fopen_or_die(const char* filename, const char* instruction) { FILE* const in_file = fopen(filename, instruction); - if (in_file) - { + if (in_file) { return in_file; } /* error */ @@ -340,8 +318,7 @@ class zstd_compress final FILE* const in_file = fopen_or_die(file_name, "rb"); size_t const read_size = fread(buffer, 1, file_size, in_file); - if (read_size != (size_t)file_size) - { + if (read_size != (size_t)file_size) { fprintf(stderr, "fread: %s : %s \n", file_name, strerror(errno)); exit(common_error_code::error_fread); } diff --git a/src/core/container/array_map.hpp b/src/core/container/array_map.hpp index f75adc681..305d5ec9e 100644 --- a/src/core/container/array_map.hpp +++ b/src/core/container/array_map.hpp @@ -32,14 +32,16 @@ namespace ark { template -class is_buildin_type -{ +class is_buildin_type { public: - enum - { - yes = std::same_as || std::same_as || - std::same_as || std::same_as || - std::same_as || std::same_as, + enum { + yes = std::same_as < element_type, + uint16_t > || std::same_as < element_type, + uint32_t > || std::same_as < element_type, + uint64_t > || std::same_as < element_type, + int16_t > || std::same_as < element_type, + int32_t > || std::same_as < element_type, + int64_t >, no = !yes }; }; @@ -52,14 +54,11 @@ bool check_buildin_type(const element_type& t) { ////////////////////////////////////////////////////////////////////////// template -class array_map -{ -}; +class array_map {}; // partial template specialization for KEY=std::string template -class array_map -{ +class array_map { public: array_map() noexcept { } @@ -76,15 +75,11 @@ class array_map bool add_element(const std::string& name, node_type* data) { nodes_.push_back(data); - try - { - if (indices_.add(name.c_str(), nodes_.size() - 1)) - { + try { + if (indices_.add(name.c_str(), nodes_.size() - 1)) { return true; } - } - catch (...) - { + } catch (...) { nodes_.pop_back(); throw; } @@ -95,8 +90,7 @@ class array_map node_type* get_element(const std::string& name) { size_t index; - if (!indices_.get_data(name.c_str(), index)) - { + if (!indices_.get_data(name.c_str(), index)) { return nullptr; } @@ -145,8 +139,7 @@ class array_map protected: void release_all() { - for (size_t i = 0; i < get_count(); ++i) - { + for (size_t i = 0; i < get_count(); ++i) { nodes_[i] = nullptr; } diff --git a/src/core/container/bit_value.hpp b/src/core/container/bit_value.hpp index 5af37a295..6b663d2d6 100644 --- a/src/core/container/bit_value.hpp +++ b/src/core/container/bit_value.hpp @@ -24,11 +24,9 @@ namespace ark { // T just can be build-in type, like int uint16_t uint64_t template -class bit_value -{ +class bit_value { public: - enum bit_value_define - { + enum bit_value_define { error_value = 1, none_value = 0, have_value = 1, @@ -55,10 +53,8 @@ class bit_value } int get_first_no_value_index() { - for (int i = 0; i < get_bit_length(); ++i) - { - if ((value_ & (element_type(1) << i)) == none_value) - { + for (int i = 0; i < get_bit_length(); ++i) { + if ((value_ & (element_type(1) << i)) == none_value) { return i; } } @@ -67,8 +63,7 @@ class bit_value } element_type get_bit_value(const int n_index) { - if (n_index < 0 || n_index >= get_bit_length()) - { + if (n_index < 0 || n_index >= get_bit_length()) { return error_value; } @@ -76,8 +71,7 @@ class bit_value } void set_bit_value(const int n_index) { - if (n_index < 0 || n_index >= get_bit_length()) - { + if (n_index < 0 || n_index >= get_bit_length()) { return; } @@ -85,8 +79,7 @@ class bit_value } void clear_bit_value(const int n_index) { - if (n_index < 0 || n_index >= get_bit_length()) - { + if (n_index < 0 || n_index >= get_bit_length()) { return; } @@ -99,10 +92,8 @@ class bit_value //////////////////////////////////////////////////////////////////////////////////////// static int get_first_no_value_index(const element_type& n_value) { - for (int i = 0; i < get_bit_length(); ++i) - { - if ((n_value & (element_type(1) << i)) == none_value) - { + for (int i = 0; i < get_bit_length(); ++i) { + if ((n_value & (element_type(1) << i)) == none_value) { return i; } } @@ -111,8 +102,7 @@ class bit_value } static element_type get_bit_value(const element_type& n_value, const int n_index) { - if (n_index < 0 || n_index >= get_bit_length()) - { + if (n_index < 0 || n_index >= get_bit_length()) { return error_value; } @@ -120,8 +110,7 @@ class bit_value } static void set_bit_value(element_type& n_value, const int n_index) { - if (n_index < 0 || n_index >= get_bit_length()) - { + if (n_index < 0 || n_index >= get_bit_length()) { return; } @@ -129,8 +118,7 @@ class bit_value } static void clear_bit_value(element_type& n_value, const int n_index) { - if (n_index < 0 || n_index >= get_bit_length()) - { + if (n_index < 0 || n_index >= get_bit_length()) { return; } diff --git a/src/core/container/consistent_hash.hpp b/src/core/container/consistent_hash.hpp index 3c8f8fb6f..c31b1ce34 100644 --- a/src/core/container/consistent_hash.hpp +++ b/src/core/container/consistent_hash.hpp @@ -27,8 +27,7 @@ namespace ark { -class v_node -{ +class v_node { public: v_node(int server_id, const std::string& ip, std::size_t port, std::size_t id) : bus_id(server_id) @@ -56,8 +55,7 @@ class v_node template>> -class consistent_hashmap -{ +class consistent_hashmap { public: using size_type = typename hasher_type::result_type; using map_type = std::map, allocator_param_type>; @@ -77,8 +75,7 @@ class consistent_hashmap void insert(bus_id_t bus_id, const std::string& ip, uint16_t port) { v_node vnode(bus_id, ip, port, 0); - for (std::size_t i = 0; i < vnode_count_; ++i) - { + for (std::size_t i = 0; i < vnode_count_; ++i) { vnode.vnode_id = i; insert(vnode); } @@ -124,15 +121,13 @@ class consistent_hashmap } iterator find(size_type hash) { - if (nodes_.empty()) - { + if (nodes_.empty()) { return nodes_.end(); } iterator it = nodes_.lower_bound(hash); - if (it == nodes_.end()) - { + if (it == nodes_.end()) { it = nodes_.begin(); } @@ -149,8 +144,7 @@ class consistent_hashmap std::size_t vnode_count_{100}; // default virtual node count is 100 }; -class crc_hasher -{ +class crc_hasher { public: using result_type = uint32_t; @@ -164,8 +158,7 @@ class crc_hasher } }; -class murmur_hasher -{ +class murmur_hasher { public: using result_type = uint32_t; diff --git a/src/core/container/list.hpp b/src/core/container/list.hpp index 374d648e4..5d9b9b45c 100644 --- a/src/core/container/list.hpp +++ b/src/core/container/list.hpp @@ -25,8 +25,7 @@ namespace ark { template -class list -{ +class list { public: using list_type = std::list; using reference = element_type&; @@ -88,8 +87,7 @@ class list } bool get_value(const std::size_t index, reference value) { - if (index >= values_.size()) - { + if (index >= values_.size()) { return false; } diff --git a/src/core/container/lock_free_queue.hpp b/src/core/container/lock_free_queue.hpp index 21921db11..6b8baf290 100644 --- a/src/core/container/lock_free_queue.hpp +++ b/src/core/container/lock_free_queue.hpp @@ -27,8 +27,7 @@ namespace ark { template -class lock_free_queue -{ +class lock_free_queue { public: lock_free_queue() = default; ~lock_free_queue() = default; diff --git a/src/core/container/lru_map.hpp b/src/core/container/lru_map.hpp index e693e5a72..b18465f69 100644 --- a/src/core/container/lru_map.hpp +++ b/src/core/container/lru_map.hpp @@ -25,8 +25,7 @@ namespace ark { template -class lru_map -{ +class lru_map { public: using iterator = typename std::unordered_map::iterator; @@ -38,15 +37,13 @@ class lru_map : lru_map(other.capacity_) { // Prepare all container bookkeeping before copying entries. Rebuild each // link in its final list instead of temporarily borrowing source links. - for (auto it = other.kl_.rbegin(); it != other.kl_.rend(); ++it) - { + for (auto it = other.kl_.rbegin(); it != other.kl_.rend(); ++it) { insert(*it, other.kv_.at(*it)); } } lru_map& operator=(const lru_map& other) { - if (this != &other) - { + if (this != &other) { lru_map candidate(other); swap(candidate); } @@ -73,8 +70,7 @@ class lru_map iterator find(const key_type& key) { iterator it = kv_.find(key); - if (it != kv_.end() && kl_.front() != key) - { + if (it != kv_.end() && kl_.front() != key) { auto ki = ki_.find(key); kl_.splice(kl_.begin(), kl_, ki->second); // move key to the front ki->second = kl_.begin(); @@ -85,21 +81,16 @@ class lru_map // The key is not inserted if it already exists. void insert(const key_type& key, const mapped_type& value) { auto r = kv_.insert(std::make_pair(key, value)); - if (!r.second) - { + if (!r.second) { return; } - try - { + try { kl_.push_front(key); - try - { + try { const auto index = ki_.emplace(key, kl_.begin()).first; - try - { - if (kv_.size() > capacity_) - { + try { + if (kv_.size() > capacity_) { // Resolve both lookups before removing any existing entry. const auto oldest_value = kv_.find(kl_.back()); const auto oldest_index = ki_.find(kl_.back()); @@ -107,29 +98,22 @@ class lru_map kv_.erase(oldest_value); ki_.erase(oldest_index); } - } - catch (...) - { + } catch (...) { ki_.erase(index); throw; } - } - catch (...) - { + } catch (...) { kl_.pop_front(); throw; } - } - catch (...) - { + } catch (...) { kv_.erase(r.first); throw; } } void erase(iterator it) { - if (it != kv_.end()) - { + if (it != kv_.end()) { auto ki = ki_.find(it->first); kl_.erase(ki->second); ki_.erase(ki); diff --git a/src/core/container/map.hpp b/src/core/container/map.hpp index 80d028134..98fbc9b30 100644 --- a/src/core/container/map.hpp +++ b/src/core/container/map.hpp @@ -25,8 +25,7 @@ namespace ark { template -class object_map_base -{ +class object_map_base { public: using k_type = key_type; using v_type = mapped_type; @@ -62,8 +61,7 @@ class object_map_base } object_map_base& operator=(object_map_base&& other) noexcept(std::is_nothrow_move_assignable_v) { - if (this != &other) - { + if (this != &other) { clear(); nodes_ = std::move(other.nodes_); other.nodes_.clear(); @@ -89,8 +87,7 @@ class object_map_base // will delete allocated memory iterator erase(iterator it) { - if (it != nodes_.end()) - { + if (it != nodes_.end()) { delete_value(it->second); return nodes_.erase(it); } @@ -101,8 +98,7 @@ class object_map_base // will delete allocated memory bool erase(const k_type& key) { auto iter = nodes_.find(key); - if (iter == nodes_.end()) - { + if (iter == nodes_.end()) { return false; } @@ -142,8 +138,7 @@ class object_map_base // will delete allocated memory void clear() { - for (auto& iter : nodes_) - { + for (auto& iter : nodes_) { delete_value(iter.second); } @@ -152,8 +147,7 @@ class object_map_base v_type find_value(const k_type& key) { auto iter = find(key); - if (iter != end()) - { + if (iter != end()) { return iter->second; } @@ -166,8 +160,7 @@ class object_map_base v_type find_value(const k_type& key) const { auto iter = find(key); - if (iter != end()) - { + if (iter != end()) { return iter->second; } @@ -177,8 +170,7 @@ class object_map_base private: template void delete_value(stored_type& value) { - if constexpr (std::is_pointer_v) - { + if constexpr (std::is_pointer_v) { delete value; value = nullptr; } diff --git a/src/core/container/queue.hpp b/src/core/container/queue.hpp index 40b234c37..182d24efc 100644 --- a/src/core/container/queue.hpp +++ b/src/core/container/queue.hpp @@ -28,8 +28,7 @@ namespace ark { -class queue_lock : public noncopyable -{ +class queue_lock : public noncopyable { public: explicit queue_lock() { flag_.clear(); @@ -39,8 +38,7 @@ class queue_lock : public noncopyable } void lock() { - while (flag_.test_and_set(std::memory_order_acquire)) - { + while (flag_.test_and_set(std::memory_order_acquire)) { } } @@ -55,8 +53,7 @@ class queue_lock : public noncopyable using lock = queue_lock; template -class queue : public lock -{ +class queue : public lock { public: queue() { } @@ -72,8 +69,7 @@ class queue : public lock bool pop(element_type& object) { std::lock_guard guard(*this); - if (list_.empty()) - { + if (list_.empty()) { return false; } diff --git a/src/core/container/thread_safe_queue.hpp b/src/core/container/thread_safe_queue.hpp index a435d866b..1fae2aae9 100644 --- a/src/core/container/thread_safe_queue.hpp +++ b/src/core/container/thread_safe_queue.hpp @@ -8,8 +8,7 @@ namespace ark { template -class thread_safe_queue -{ +class thread_safe_queue { private: std::queue data_queue_; mutable std::mutex mutex_; @@ -29,8 +28,7 @@ class thread_safe_queue bool try_pop(element_type& value) { std::lock_guard guard(mutex_); - if (data_queue_.empty()) - { + if (data_queue_.empty()) { return false; } diff --git a/src/core/container/vector.hpp b/src/core/container/vector.hpp index 69d7389c2..b39c6fadf 100644 --- a/src/core/container/vector.hpp +++ b/src/core/container/vector.hpp @@ -31,15 +31,13 @@ namespace ark { template -class vector_value_type -{ +class vector_value_type { public: using value_type = std::conditional_t, element_type*>; }; template -class object_vector_base -{ +class object_vector_base { public: using value_type = typename vector_value_type::value_type; using vector_type = std::vector; @@ -71,8 +69,7 @@ class object_vector_base } object_vector_base& operator=(object_vector_base&& other) noexcept { - if (this != &other) - { + if (this != &other) { clear(); datas_ = std::move(other.datas_); other.datas_.clear(); @@ -93,10 +90,8 @@ class object_vector_base } void clear() { - if constexpr (!is_smart_ptr) - { - for (auto data : datas_) - { + if constexpr (!is_smart_ptr) { + for (auto data : datas_) { delete data; } } @@ -105,8 +100,7 @@ class object_vector_base } value_type at(std::size_t index) { - if (index >= size()) - { + if (index >= size()) { return nullptr; } @@ -119,8 +113,7 @@ class object_vector_base } void resize(std::size_t new_size) { - if (new_size <= size()) - { + if (new_size <= size()) { return; } @@ -130,10 +123,8 @@ class object_vector_base std::size_t first_empty() { std::size_t index = 0; auto size = this->size(); - for (; index < size; index++) - { - if (datas_[index] == nullptr) - { + for (; index < size; index++) { + if (datas_[index] == nullptr) { return index; } } @@ -143,8 +134,7 @@ class object_vector_base void erase(std::size_t index) { ARK_ASSERT_RET_NONE(index < size()); - if constexpr (!is_smart_ptr) - { + if constexpr (!is_smart_ptr) { delete datas_[index]; } datas_[index] = nullptr; @@ -156,20 +146,15 @@ class object_vector_base } void push_back(std::size_t index, value_type value) { - if (index < size()) - { - if constexpr (!is_smart_ptr) - { - if (datas_[index] != value) - { + if (index < size()) { + if constexpr (!is_smart_ptr) { + if (datas_[index] != value) { delete datas_[index]; datas_[index] = nullptr; } } datas_[index] = std::move(value); - } - else - { + } else { datas_.emplace_back(std::move(value)); } } diff --git a/src/core/core_def.hpp b/src/core/core_def.hpp index 7e18678d0..b776f9e28 100644 --- a/src/core/core_def.hpp +++ b/src/core/core_def.hpp @@ -25,8 +25,7 @@ namespace ark { -class core_allocator -{ +class core_allocator { public: core_allocator() = default; ~core_allocator() = default; @@ -308,8 +307,7 @@ inline static unsigned int get_hash_value_no_case(const char* name) { unsigned int hash = 0; - for (; *name; name++) - { + for (; *name; name++) { hash = hash * 131 + convert_to_lower[(unsigned char)(*name)]; } @@ -321,8 +319,7 @@ inline unsigned int get_hash_value(const char* name) { unsigned int hash = 0; - for (; *name; name++) - { + for (; *name; name++) { hash = hash * 131 + *name; } diff --git a/src/core/cron.hpp b/src/core/cron.hpp index fbf1aee76..604bf71d9 100644 --- a/src/core/cron.hpp +++ b/src/core/cron.hpp @@ -27,8 +27,7 @@ namespace ark { -class bad_cron_expression : public std::exception -{ +class bad_cron_expression : public std::exception { public: explicit bad_cron_expression(const std::string&& msg) : msg_(std::move(msg)) { @@ -64,8 +63,7 @@ inline std::tm scheduler_local_time(std::time_t time) { #else const bool converted = localtime_r(&time, &result) != nullptr; #endif - if (!converted) - { + if (!converted) { throw std::runtime_error("Cannot convert scheduler local time"); } return result; @@ -79,8 +77,7 @@ inline void add(std::tm& tm, std::chrono::system_clock::duration time) { tm = detail::scheduler_local_time(tm_adjusted); } -class cron -{ +class cron { public: using clock = std::chrono::system_clock; @@ -88,8 +85,7 @@ class cron std::istringstream iss(expression); std::vector tokens{std::istream_iterator{iss}, std::istream_iterator{}}; - if (tokens.size() != 5) - { + if (tokens.size() != 5) { throw bad_cron_expression("malformed cron string (must be 5 fields): " + expression); } @@ -108,19 +104,14 @@ class cron // it will always at least run the next minute next.tm_sec = 0; add(next, std::chrono::minutes(1)); - while (true) - { - if (month != -1 && next.tm_mon != month) - { + while (true) { + if (month != -1 && next.tm_mon != month) { // add a month // if this will bring us over a year, increment the year instead and reset the month - if (next.tm_mon + 1 > 11) - { + if (next.tm_mon + 1 > 11) { next.tm_mon = 0; next.tm_year++; - } - else - { + } else { next.tm_mon++; } @@ -130,31 +121,27 @@ class cron continue; } - if (day != -1 && next.tm_mday != day) - { + if (day != -1 && next.tm_mday != day) { add(next, std::chrono::hours(24)); next.tm_hour = 0; next.tm_min = 0; continue; } - if (day_of_week != -1 && next.tm_wday != day_of_week) - { + if (day_of_week != -1 && next.tm_wday != day_of_week) { add(next, std::chrono::hours(24)); next.tm_hour = 0; next.tm_min = 0; continue; } - if (hour != -1 && next.tm_hour != hour) - { + if (hour != -1 && next.tm_hour != hour) { add(next, std::chrono::hours(1)); next.tm_min = 0; continue; } - if (minute != -1 && next.tm_min != minute) - { + if (minute != -1 && next.tm_min != minute) { add(next, std::chrono::minutes(1)); continue; } @@ -176,32 +163,26 @@ class cron private: inline void verify_and_set(const std::string& token, const std::string& expression, int& field, const int lower_bound, const int upper_bound, const bool adjust = false) { - if (token == "*") - { + if (token == "*") { field = -1; - } - else - { - try - { field = std::stoi(token); } - catch (const std::invalid_argument&) - { throw bad_cron_expression("malformed cron string (`" + token + "` not an integer or *): " + expression); } - catch (const std::out_of_range&) - { + } else { + try { + field = std::stoi(token); + } catch (const std::invalid_argument&) { + throw bad_cron_expression("malformed cron string (`" + token + "` not an integer or *): " + expression); + } catch (const std::out_of_range&) { throw bad_cron_expression( "malformed cron string (`" + token + "` not convertable to int): " + expression); } - if (field < lower_bound || field > upper_bound) - { + if (field < lower_bound || field > upper_bound) { std::ostringstream oss; oss << "malformed cron string ('" << token << "' must be <= " << upper_bound << " and >= " << lower_bound << "): " << expression; throw bad_cron_expression(oss.str()); } - if (adjust) - { + if (adjust) { field--; } } diff --git a/src/core/crypto/xxtea.hpp b/src/core/crypto/xxtea.hpp index 7800b4529..4900d63ac 100644 --- a/src/core/crypto/xxtea.hpp +++ b/src/core/crypto/xxtea.hpp @@ -28,8 +28,7 @@ namespace ark { -class xxtea -{ +class xxtea { public: /** * Function: xxtea_encrypt @@ -42,8 +41,7 @@ class xxtea size_t out_len = 0; std::unique_ptr ret( xxtea_encrypt(data.c_str(), data.length(), key.c_str(), &out_len), &std::free); - if (ret == nullptr) - { + if (ret == nullptr) { return false; } @@ -62,8 +60,7 @@ class xxtea size_t out_len = 0; std::unique_ptr ret( xxtea_decrypt(data.c_str(), data.length(), key.c_str(), &out_len), &std::free); - if (ret == nullptr) - { + if (ret == nullptr) { return false; } @@ -83,8 +80,7 @@ class xxtea */ static void* xxtea_encrypt(const void* data, size_t len, const void* key, size_t* out_len) { if (data == nullptr || key == nullptr || out_len == nullptr || len == 0 || - len > (std::numeric_limits::max)()) - { + len > (std::numeric_limits::max)()) { return nullptr; } const auto fixed_key = normalize_key(key); @@ -103,8 +99,7 @@ class xxtea */ static void* xxtea_decrypt(const void* data, size_t len, const void* key, size_t* out_len) { if (data == nullptr || key == nullptr || out_len == nullptr || len == 0 || len % sizeof(uint32_t) != 0 || - len > (std::numeric_limits::max)()) - { + len > (std::numeric_limits::max)()) { return nullptr; } const auto fixed_key = normalize_key(key); @@ -123,8 +118,7 @@ class xxtea static std::array normalize_key(const void* key) { std::array result{}; const auto* bytes = static_cast(key); - for (size_t index = 0; index < result.size() && bytes[index] != 0; ++index) - { + for (size_t index = 0; index < result.size() && bytes[index] != 0; ++index) { result[index] = bytes[index]; } return result; @@ -136,33 +130,24 @@ class xxtea n = (((len & 3) == 0) ? (len >> 2) : ((len >> 2) + 1)); - if (inc_len) - { + if (inc_len) { out = (uint32_t*)calloc(n + 1, sizeof(uint32_t)); - if (!out) - { + if (!out) { return nullptr; } out[n] = (uint32_t)len; *out_len = n + 1; - } - else - { + } else { out = (uint32_t*)calloc(n, sizeof(uint32_t)); - if (!out) - { + if (!out) { return nullptr; } *out_len = n; } - if constexpr (std::endian::native == std::endian::little) - { + if constexpr (std::endian::native == std::endian::little) { std::memcpy(out, data, len); - } - else - { - for (size_t i = 0; i < len; ++i) - { + } else { + for (size_t i = 0; i < len; ++i) { out[i >> 2] |= static_cast(data[i]) << ((i & 3) << 3); } } @@ -177,12 +162,10 @@ class xxtea n = len << 2; - if (inc_len) - { + if (inc_len) { m = data[len - 1]; n -= 4; - if ((m < n - 3) || (m > n)) - { + if ((m < n - 3) || (m > n)) { return nullptr; } n = m; @@ -190,19 +173,14 @@ class xxtea out = (uint8_t*)malloc(n + 1); - if (out == nullptr) - { + if (out == nullptr) { return nullptr; } - if constexpr (std::endian::native == std::endian::little) - { + if constexpr (std::endian::native == std::endian::little) { std::memcpy(out, data, n); - } - else - { - for (size_t i = 0; i < n; ++i) - { + } else { + for (size_t i = 0; i < n; ++i) { out[i] = static_cast(data[i >> 2] >> ((i & 3) << 3)); } } @@ -217,18 +195,15 @@ class xxtea uint32_t n = (uint32_t)len - 1; uint32_t z = data[n], y, p, q = 6 + 52 / (n + 1), sum = 0, e; - if (n < 1) - { + if (n < 1) { return data; } - while (0 < q--) - { + while (0 < q--) { sum += delta; e = sum >> 2 & 3; - for (p = 0; p < n; p++) - { + for (p = 0; p < n; p++) { y = data[p + 1]; z = data[p] += mix(z, y, sum, p, e, std::span(key, 4)); } @@ -244,17 +219,14 @@ class xxtea uint32_t n = (uint32_t)len - 1; uint32_t z, y = data[0], p, q = 6 + 52 / (n + 1), sum = q * delta, e; - if (n < 1) - { + if (n < 1) { return data; } - while (sum != 0) - { + while (sum != 0) { e = sum >> 2 & 3; - for (p = n; p > 0; p--) - { + for (p = n; p > 0; p--) { z = data[p - 1]; y = data[p] -= mix(z, y, sum, p, e, std::span(key, 4)); } @@ -272,20 +244,17 @@ class xxtea uint32_t *data_array, *key_array; size_t data_len, key_len; - if (!len) - { + if (!len) { return nullptr; } data_array = xxtea_to_uint_array(data, len, 1, &data_len); - if (!data_array) - { + if (!data_array) { return nullptr; } key_array = xxtea_to_uint_array(key, 16, 0, &key_len); - if (!key_array) - { + if (!key_array) { free(data_array); return nullptr; } @@ -303,20 +272,17 @@ class xxtea uint32_t *data_array, *key_array; size_t data_len, key_len; - if (!len) - { + if (!len) { return nullptr; } data_array = xxtea_to_uint_array(data, len, 0, &data_len); - if (!data_array) - { + if (!data_array) { return nullptr; } key_array = xxtea_to_uint_array(key, 16, 0, &key_len); - if (!key_array) - { + if (!key_array) { free(data_array); return nullptr; } diff --git a/src/core/define.hpp b/src/core/define.hpp index 3f6a34310..8af96cf46 100644 --- a/src/core/define.hpp +++ b/src/core/define.hpp @@ -53,8 +53,7 @@ using id_type = uint32_t; using mask_type = std::bitset<16>; /// Table callback data -class table_event_data -{ +class table_event_data { public: table_event_data() = default; diff --git a/src/core/dynamic_library.hpp b/src/core/dynamic_library.hpp index 1d7705939..0c4fcf4cf 100644 --- a/src/core/dynamic_library.hpp +++ b/src/core/dynamic_library.hpp @@ -33,8 +33,7 @@ namespace detail { struct dynamic_library_test_access; } -class dynamic_library -{ +class dynamic_library { public: explicit dynamic_library(const std::string& lib_name) : name_(lib_name) { @@ -57,8 +56,7 @@ class dynamic_library #ifdef ARK_PLATFORM_WIN const auto result = load_windows_library(path + name_); lib_inst_ = result.first; - if (!lib_inst_) - { + if (!lib_inst_) { // Preserve the native failure after temporary path buffers retire. SetLastError(result.second); } @@ -89,28 +87,23 @@ class dynamic_library #ifdef ARK_PLATFORM_WIN static std::pair load_windows_library(const std::string& path) { const auto count = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, path.c_str(), -1, nullptr, 0); - if (count == 0) - { + if (count == 0) { return {nullptr, GetLastError()}; } std::wstring requested(count, L'\0'); - if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, path.c_str(), -1, requested.data(), count) == 0) - { + if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, path.c_str(), -1, requested.data(), count) == 0) { return {nullptr, GetLastError()}; } const auto capacity = GetFullPathNameW(requested.c_str(), 0, nullptr, nullptr); - if (capacity == 0) - { + if (capacity == 0) { return {nullptr, GetLastError()}; } std::wstring absolute(capacity, L'\0'); const auto length = GetFullPathNameW(requested.c_str(), capacity, absolute.data(), nullptr); - if (length == 0) - { + if (length == 0) { return {nullptr, GetLastError()}; } - if (length >= capacity) - { + if (length >= capacity) { return {nullptr, ERROR_INSUFFICIENT_BUFFER}; } absolute.resize(length); @@ -132,12 +125,10 @@ class dynamic_library template bool unload_with(close_type close) { - if (!lib_inst_) - { + if (!lib_inst_) { return true; } - if (!native_unload_succeeded(close(lib_inst_))) - { + if (!native_unload_succeeded(close(lib_inst_))) { return false; } lib_inst_ = nullptr; diff --git a/src/core/enum.hpp b/src/core/enum.hpp index d50512030..c4cc6fb6b 100644 --- a/src/core/enum.hpp +++ b/src/core/enum.hpp @@ -24,8 +24,7 @@ namespace ark { -enum class data_type : uint32_t -{ +enum class data_type : uint32_t { dt_empty, // unknown dt_boolean, // bool dt_int32, // int32 @@ -44,16 +43,14 @@ enum class data_type : uint32_t dt_userdata, // user data(char*) }; -enum class connection_type : uint32_t -{ +enum class connection_type : uint32_t { brt_unknown, // unknown brt_direct, // directly brt_wait_notify, // wait notify brt_record, // do not connect, but need record info }; -enum class entity_event : uint32_t -{ +enum class entity_event : uint32_t { entity_evt_none = 0, entity_evt_destroy, entity_evt_pre_destroy, @@ -66,8 +63,7 @@ enum class entity_event : uint32_t entity_evt_all_finished, // Call it by yourself when create entity finished }; -enum class data_op_type : uint16_t -{ +enum class data_op_type : uint16_t { dot_unknown = 0, dot_inc, // + dot_dec, // - @@ -88,8 +84,7 @@ enum class table_op_type : uint16_t // table operate type table_clear, // clear all rows }; -enum class data_mask : uint16_t -{ +enum class data_mask : uint16_t { pf_sync_view = 0, // send to others pf_sync_self = 1, // send to self pf_real_time = 2, // send real-time when changed @@ -100,8 +95,7 @@ enum class data_mask : uint16_t pf_log = 7, // log when changed }; -enum class container_op_type : uint32_t -{ +enum class container_op_type : uint32_t { op_create = 0, // new entity op_place = 1, // place another entity op_remove = 2, // remove en entity but do not destroy @@ -109,8 +103,7 @@ enum class container_op_type : uint32_t op_destroy = 4, // destroy an entity }; -enum class http_method : uint8_t -{ +enum class http_method : uint8_t { http_method_head, http_method_get, http_method_post, @@ -119,8 +112,7 @@ enum class http_method : uint8_t http_method_max }; -enum class compress_type : uint8_t -{ +enum class compress_type : uint8_t { compress_type_none, compress_type_zlib, compress_type_zstd diff --git a/src/core/error.hpp b/src/core/error.hpp index dbec24cc4..717e55b98 100644 --- a/src/core/error.hpp +++ b/src/core/error.hpp @@ -28,16 +28,14 @@ namespace ark { // will be used for internal errors class error_category : public std::error_category - , public singleton -{ + , public singleton { public: const char* name() const noexcept override { return "ark_error"; } std::string message(int err_val) const override { - switch (err_val) - { + switch (err_val) { case -1: return "first error"; case -2: diff --git a/src/core/error_code.hpp b/src/core/error_code.hpp index ab653f922..78707b291 100644 --- a/src/core/error_code.hpp +++ b/src/core/error_code.hpp @@ -24,8 +24,7 @@ namespace ark { -enum class error_code : std::uint32_t -{ +enum class error_code : std::uint32_t { success = 0, kcp_server_disconnect = 1000, // kcp server disconnect when dtor @@ -37,4 +36,4 @@ enum class error_code : std::uint32_t // will add error code logic_error_code_start = 10000, }; -} \ No newline at end of file +} // namespace ark \ No newline at end of file diff --git a/src/core/event_define.hpp b/src/core/event_define.hpp index 85fac9b46..f7f0c2475 100644 --- a/src/core/event_define.hpp +++ b/src/core/event_define.hpp @@ -22,10 +22,9 @@ namespace ark { -enum event_define -{ +enum event_define { ////////////////Has Self---logic////////////////////////////////////////////////////////// // arg[0]:object afed_on_client_leave_scene, }; -} +} // namespace ark diff --git a/src/core/guid128.hpp b/src/core/guid128.hpp index 5d6f5f3e8..706813474 100644 --- a/src/core/guid128.hpp +++ b/src/core/guid128.hpp @@ -27,8 +27,7 @@ namespace ark { -class guid_t128 -{ +class guid_t128 { public: std::uint64_t high; std::uint64_t low; @@ -66,8 +65,7 @@ class guid_t128 } guid_t128& operator=(const guid_t128& rhs) { - if (this != &rhs) - { + if (this != &rhs) { high = rhs.high; low = rhs.low; } @@ -83,8 +81,7 @@ class guid_t128 } bool operator<(const guid_t128& rhs) const { - if (this->high == rhs.high) - { + if (this->high == rhs.high) { return this->low < rhs.low; } @@ -97,8 +94,7 @@ class guid_t128 bool from_string(const std::string& str_id) { const auto separator = str_id.find('-'); - if (separator == std::string::npos || separator == 0 || separator + 1 == str_id.size()) - { + if (separator == std::string::npos || separator == 0 || separator + 1 == str_id.size()) { return false; } @@ -108,14 +104,12 @@ class guid_t128 std::uint64_t parsed_high; std::uint64_t parsed_low; const auto high_result = std::from_chars(begin, middle, parsed_high); - if (high_result.ec != std::errc{} || high_result.ptr != middle) - { + if (high_result.ec != std::errc{} || high_result.ptr != middle) { return false; } const auto low_result = std::from_chars(middle + 1, end, parsed_low); - if (low_result.ec != std::errc{} || low_result.ptr != end) - { + if (low_result.ec != std::errc{} || low_result.ptr != end) { return false; } diff --git a/src/core/hash/base64.hpp b/src/core/hash/base64.hpp index cb10855b0..25759d080 100644 --- a/src/core/hash/base64.hpp +++ b/src/core/hash/base64.hpp @@ -27,14 +27,12 @@ namespace ark { -class base64 -{ +class base64 { using base_enc_map_t = const unsigned char[64]; using base_dec_map_t = const unsigned char[128]; public: - enum class base64_mode_t - { + enum class base64_mode_t { // RFC 1421, RFC 2045, [RFC 3548](https://en.wikipedia.org/wiki/Base64#RFC_3548) // [RFC 4648](https://en.wikipedia.org/wiki/Base64#RFC_4648) en_bmt_standard = 0, @@ -161,16 +159,14 @@ class base64 int c1, c2, c3; unsigned char* p; - if (slen == 0) - { + if (slen == 0) { *olen = 0; return (0); } n = (slen + 2) / 3; - if (n > (BASE64_SIZE_T_MAX - 1) / 4) - { + if (n > (BASE64_SIZE_T_MAX - 1) / 4) { *olen = BASE64_SIZE_T_MAX; return -1; } @@ -178,25 +174,21 @@ class base64 n *= 4; // no padding - if (0 == padding_char) - { + if (0 == padding_char) { nopadding = slen % 3; - if (0 != nopadding) - { + if (0 != nopadding) { n -= 3 - nopadding; } } - if ((dlen < n + 1) || (NULL == dst)) - { + if ((dlen < n + 1) || (NULL == dst)) { *olen = n + 1; return -1; } n = (slen / 3) * 3; - for (i = 0, p = dst; i < n; i += 3) - { + for (i = 0, p = dst; i < n; i += 3) { c1 = *src++; c2 = *src++; c3 = *src++; @@ -207,25 +199,20 @@ class base64 *p++ = base64_enc_map[c3 & 0x3F]; } - if (i < slen) - { + if (i < slen) { c1 = *src++; c2 = ((i + 1) < slen) ? *src++ : 0; *p++ = base64_enc_map[(c1 >> 2) & 0x3F]; *p++ = base64_enc_map[(((c1 & 3) << 4) + (c2 >> 4)) & 0x3F]; - if ((i + 1) < slen) - { + if ((i + 1) < slen) { *p++ = base64_enc_map[((c2 & 15) << 2) & 0x3F]; - } - else if (padding_char) - { + } else if (padding_char) { *p++ = padding_char; } - if (padding_char) - { + if (padding_char) { *p++ = padding_char; } } @@ -246,8 +233,7 @@ class base64 reinterpret_cast(&dst[0]), dst.size(), &olen, src, slen, base64_enc_map, padding_char); assert(0 != ret || dst.size() == olen + 1); // pop back last zero - if (!dst.empty() && *dst.rbegin() == 0) - { + if (!dst.empty() && *dst.rbegin() == 0) { dst.resize(dst.size() - 1); } return ret; @@ -266,70 +252,56 @@ class base64 unsigned char* p; /* First pass: check for validity and get output length */ - for (i = n = j = 0; i < slen; i++) - { + for (i = n = j = 0; i < slen; i++) { /* Skip spaces before checking for EOL */ x = 0; - while (i < slen && (src[i] == ' ' || src[i] == '\t')) - { + while (i < slen && (src[i] == ' ' || src[i] == '\t')) { ++i; ++x; } /* Spaces at end of buffer are OK */ - if (i == slen) - { + if (i == slen) { break; } - if ((slen - i) >= 2 && src[i] == '\r' && src[i + 1] == '\n') - { + if ((slen - i) >= 2 && src[i] == '\r' && src[i + 1] == '\n') { continue; } - if (src[i] == '\n') - { + if (src[i] == '\n') { continue; } /* Space inside a line is an error */ - if (x != 0) - { + if (x != 0) { return -2; } - if (src[i] == padding_char) - { - if (++j > 2) - { + if (src[i] == padding_char) { + if (++j > 2) { return -2; } - } - else - { - if (src[i] > 127 || base64_dec_map[src[i]] == 127) - { + } else { + if (src[i] > 127 || base64_dec_map[src[i]] == 127) { return -2; } } - if (base64_dec_map[src[i]] < 64 && j != 0) - { + if (base64_dec_map[src[i]] < 64 && j != 0) { return -2; } n++; } - if (n == 0) - { + if (n == 0) { *olen = 0; return (0); } // no padding, add j to padding length - if (slen & 3) - { + if (slen & 3) { j += 4 - (slen & 3); n += 4 - (slen & 3); } @@ -341,47 +313,37 @@ class base64 n = (6 * (n >> 3)) + ((6 * (n & 0x7) + 7) >> 3); n -= j; - if (dst == NULL || dlen < n) - { + if (dst == NULL || dlen < n) { *olen = n; return -1; } - for (j = 3, n = x = 0, p = dst; i > 0; i--, src++) - { - if (*src == '\r' || *src == '\n' || *src == ' ' || *src == '\t') - { + for (j = 3, n = x = 0, p = dst; i > 0; i--, src++) { + if (*src == '\r' || *src == '\n' || *src == ' ' || *src == '\t') { continue; } j -= (*src == padding_char ? 1 : 0); x = (x << 6) | (base64_dec_map[*src] & 0x3F); - if (++n == 4) - { + if (++n == 4) { n = 0; - if (j > 0) - { + if (j > 0) { *p++ = (unsigned char)(x >> 16); } - if (j > 1) - { + if (j > 1) { *p++ = (unsigned char)(x >> 8); } - if (j > 2) - { + if (j > 2) { *p++ = (unsigned char)(x); } } } // no padding, the tail code - if (n == 2) - { + if (n == 2) { *p++ = (unsigned char)(x >> 4); - } - else if (n == 3) - { + } else if (n == 3) { *p++ = (unsigned char)(x >> 10); *p++ = (unsigned char)(x >> 2); } @@ -395,8 +357,7 @@ class base64 base_dec_map_t& base64_dec_map, unsigned char padding_char) { size_t olen = 0; - if (-2 == base64_decode_inner(NULL, 0, &olen, src, slen, base64_dec_map, padding_char)) - { + if (-2 == base64_decode_inner(NULL, 0, &olen, src, slen, base64_dec_map, padding_char)) { return -2; } @@ -435,8 +396,7 @@ class base64 18, 19, 20, 21, 22, 23, 24, 25, 127, 127, 127, 127, 63, 127, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 127, 127, 127, 127, 127}; - switch (mode) - { + switch (mode) { case base64_mode_t::en_bmt_standard: case base64_mode_t::en_bmt_utf7: return base64_dec_map_basic; @@ -468,8 +428,7 @@ class base64 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'}; - switch (mode) - { + switch (mode) { case base64_mode_t::en_bmt_standard: case base64_mode_t::en_bmt_utf7: return base64_enc_map_basic; @@ -486,8 +445,7 @@ class base64 } static inline unsigned char base64_get_padding_char(base64_mode_t mode) { - switch (mode) - { + switch (mode) { case base64_mode_t::en_bmt_standard: case base64_mode_t::en_bmt_url_filename_safe: return '='; diff --git a/src/core/hash/crc.hpp b/src/core/hash/crc.hpp index 872a177a0..b473fae78 100644 --- a/src/core/hash/crc.hpp +++ b/src/core/hash/crc.hpp @@ -28,8 +28,7 @@ namespace ark { -class crc -{ +class crc { public: static uint16_t crc16(const unsigned char* s, size_t l) { @@ -56,8 +55,7 @@ class crc 0x1ef0}; uint16_t init_val = 0; - for (size_t j = 0; j < l; ++j) - { + for (size_t j = 0; j < l; ++j) { unsigned char byte = s[j]; init_val = (init_val << 8) ^ crc16_table[((init_val >> 8) ^ (uint16_t)byte) & 0x00FF]; } @@ -326,8 +324,7 @@ class crc }; uint32_t init_val = 0; - for (size_t j = 0; j < l; ++j) - { + for (size_t j = 0; j < l; ++j) { unsigned char byte = s[j]; init_val = crc32_table[static_cast(init_val) ^ (uint32_t)byte] ^ (init_val >> 8); } @@ -596,8 +593,7 @@ class crc }; uint64_t init_val = 0; - for (size_t j = 0; j < l; ++j) - { + for (size_t j = 0; j < l; ++j) { unsigned char byte = s[j]; init_val = crc64_table[static_cast(init_val) ^ (uint64_t)byte] ^ (init_val >> 8); } diff --git a/src/core/hash/murmur_hash.hpp b/src/core/hash/murmur_hash.hpp index a7b793c17..fcf3c9ab3 100644 --- a/src/core/hash/murmur_hash.hpp +++ b/src/core/hash/murmur_hash.hpp @@ -30,8 +30,7 @@ namespace ark { -class murmur_hash -{ +class murmur_hash { public: static void murmur_hash3_x86_32(const void* key, int len, uint32_t seed, void* out) { murmur_hash3_x86_32_impl(key, len, seed, out); @@ -74,8 +73,7 @@ class murmur_hash const uint8_t* blocks = data + nblocks * 4; - for (int i = -nblocks; i; i++) - { + for (int i = -nblocks; i; i++) { uint32_t k1 = getblock(blocks, i); k1 *= c1; @@ -94,8 +92,7 @@ class murmur_hash uint32_t k1 = 0; - switch (len & 3) - { + switch (len & 3) { case 3: k1 ^= tail[2] << 16; case 2: @@ -140,8 +137,7 @@ class murmur_hash const uint8_t* blocks = data + nblocks * 16; - for (int i = -nblocks; i; i++) - { + for (int i = -nblocks; i; i++) { uint32_t k1 = getblock(blocks, i * 4 + 0); uint32_t k2 = getblock(blocks, i * 4 + 1); uint32_t k3 = getblock(blocks, i * 4 + 2); @@ -194,8 +190,7 @@ class murmur_hash uint32_t k3 = 0; uint32_t k4 = 0; - switch (len & 15) - { + switch (len & 15) { case 15: k4 ^= tail[14] << 16; case 14: @@ -294,8 +289,7 @@ class murmur_hash const uint8_t* blocks = data; - for (int i = 0; i < nblocks; i++) - { + for (int i = 0; i < nblocks; i++) { uint64_t k1 = getblock(blocks, i * 2 + 0); uint64_t k2 = getblock(blocks, i * 2 + 1); @@ -326,8 +320,7 @@ class murmur_hash uint64_t k1 = 0; uint64_t k2 = 0; - switch (len & 15) - { + switch (len & 15) { case 15: k2 ^= uint64_t(tail[14]) << 48; case 14: @@ -394,8 +387,7 @@ class murmur_hash h = 0 ^ len; const uint8_t* data = (const uint8_t*)key; - while (len >= 4) - { + while (len >= 4) { k = data[0]; k |= data[1] << 8; k |= data[2] << 16; @@ -412,8 +404,7 @@ class murmur_hash len -= 4; } - switch (len) - { + switch (len) { case 3: h ^= data[2] << 16; [[fallthrough]]; @@ -437,8 +428,7 @@ class murmur_hash static word_type byte_swap(word_type value) { static_assert(std::is_unsigned_v); word_type result = 0; - for (std::size_t byte = 0; byte < sizeof(word_type); ++byte) - { + for (std::size_t byte = 0; byte < sizeof(word_type); ++byte) { result = (result << 8) | (value & 0xff); value >>= 8; } @@ -453,8 +443,7 @@ class murmur_hash // Standard blocks are little endian; old MSVC blocks were byte-swapped // on a little-endian host. Legacy tails and output remain little endian. if constexpr ((legacy_msvc && std::endian::native == std::endian::little) || - (!legacy_msvc && std::endian::native == std::endian::big)) - { + (!legacy_msvc && std::endian::native == std::endian::big)) { value = byte_swap(value); } return value; @@ -462,8 +451,7 @@ class murmur_hash template static void store_word(void* out, word_type value) { - if constexpr (std::endian::native == std::endian::big) - { + if constexpr (std::endian::native == std::endian::big) { value = byte_swap(value); } std::memcpy(out, &value, sizeof(value)); @@ -471,8 +459,7 @@ class murmur_hash template static void store_words(void* out, const word_type (&words)[count]) { - for (std::size_t index = 0; index < count; ++index) - { + for (std::size_t index = 0; index < count; ++index) { store_word(static_cast(out) + index * sizeof(word_type), words[index]); } } diff --git a/src/core/lexical_cast.hpp b/src/core/lexical_cast.hpp index a7150d57a..a36177d0c 100644 --- a/src/core/lexical_cast.hpp +++ b/src/core/lexical_cast.hpp @@ -23,14 +23,11 @@ static const char* strue = "true"; static const char* sfalse = "false"; template -struct value_converter -{ -}; +struct value_converter {}; // to numeric template -struct value_converter -{ +struct value_converter { static uint8_t convert(const string& from) { return std::atoi(from.c_str()); } @@ -41,8 +38,7 @@ struct value_converter }; template -struct value_converter -{ +struct value_converter { static int16_t convert(const string& from) { return std::atoi(from.c_str()); } @@ -53,8 +49,7 @@ struct value_converter }; template -struct value_converter -{ +struct value_converter { static uint16_t convert(const string& from) { return std::atoi(from.c_str()); } @@ -65,8 +60,7 @@ struct value_converter }; template -struct value_converter -{ +struct value_converter { static int32_t convert(const string& from) { return std::atoi(from.c_str()); } @@ -77,8 +71,7 @@ struct value_converter }; template -struct value_converter -{ +struct value_converter { static uint32_t convert(const string& from) { return static_cast(std::strtoul(from.c_str(), nullptr, 10)); } @@ -89,8 +82,7 @@ struct value_converter }; template -struct value_converter -{ +struct value_converter { static long convert(const string& from) { return std::atol(from.c_str()); } @@ -101,8 +93,7 @@ struct value_converter }; template -struct value_converter -{ +struct value_converter { static long long convert(const string& from) { return std::atoll(from.c_str()); } @@ -113,8 +104,7 @@ struct value_converter }; template -struct value_converter -{ +struct value_converter { static uint64_t convert(const string& from) { return static_cast(std::strtoull(from.c_str(), nullptr, 10)); } @@ -125,8 +115,7 @@ struct value_converter }; template -struct value_converter -{ +struct value_converter { static double convert(const string& from) { return std::atof(from.c_str()); } @@ -137,8 +126,7 @@ struct value_converter }; template -struct value_converter -{ +struct value_converter { static float convert(const string& from) { return (float)std::atof(from.c_str()); } @@ -150,18 +138,15 @@ struct value_converter // to bool template -struct value_converter -{ +struct value_converter { static bool convert(from_type from) { return !!from; } }; static bool checkbool(const char* from, const size_t len, const char* s) { - for (size_t i = 0; i < len; i++) - { - if (from[i] != s[i]) - { + for (size_t i = 0; i < len; i++) { + if (from[i] != s[i]) { return false; } } @@ -173,28 +158,21 @@ static bool convert(const char* from) { size_t len = strlen(from); bool r = true; - if (len == 4) - { + if (len == 4) { //"true" r = checkbool(from, len, strue); - if (r) - { + if (r) { return true; } - } - else if (len == 5) - { + } else if (len == 5) { //"false" r = checkbool(from, len, sfalse); - if (r) - { + if (r) { return false; } - } - else - { + } else { // 数字转为bool int value = value_converter::convert(from); return (value > 0); @@ -204,40 +182,35 @@ static bool convert(const char* from) { } template<> -struct value_converter -{ +struct value_converter { static bool convert(const string& from) { return converter::convert(from.c_str()); } }; template<> -struct value_converter -{ +struct value_converter { static bool convert(const char* from) { return converter::convert(from); } }; template<> -struct value_converter -{ +struct value_converter { static bool convert(char* from) { return converter::convert(from); } }; template -struct value_converter -{ +struct value_converter { static bool convert(const char (&from)[extent]) { return converter::convert(from); } }; template -struct value_converter -{ +struct value_converter { static bool convert(const char (&from)[extent]) { return converter::convert(from); } @@ -245,8 +218,7 @@ struct value_converter // to string template -struct value_converter -{ +struct value_converter { static string convert(const from_type& from) { return std::to_string(from); } @@ -255,38 +227,33 @@ struct value_converter template to_type lexical_cast(const from_type& from) { - if constexpr (std::same_as) - { + if constexpr (std::same_as) { return from; - } - else - { + } else { return converter::value_converter::convert(from); } } template bool value_from_string(const std::string& input, value_type& value) { - try - { + try { value = lexical_cast(input); return true; + } catch (...) { + return false; } - catch (...) - { return false; } return false; } template bool value_to_string(const value_type& value, std::string& output) { - try - { + try { output = lexical_cast(value); return true; + } catch (...) { + return false; } - catch (...) - { return false; } return false; } diff --git a/src/core/lock/rw_lock.hpp b/src/core/lock/rw_lock.hpp index 0f0feeeff..82cdcff74 100644 --- a/src/core/lock/rw_lock.hpp +++ b/src/core/lock/rw_lock.hpp @@ -27,8 +27,7 @@ namespace ark { -class reader_writer_lock : public noncopyable -{ +class reader_writer_lock : public noncopyable { mutable std::shared_mutex mtx_; public: @@ -49,8 +48,7 @@ class reader_writer_lock : public noncopyable } }; -class scope_r_lock : public noncopyable -{ +class scope_r_lock : public noncopyable { public: explicit scope_r_lock(reader_writer_lock& lock) : rwlock_(lock) { @@ -65,8 +63,7 @@ class scope_r_lock : public noncopyable reader_writer_lock& rwlock_; }; -class scope_w_lock : public noncopyable -{ +class scope_w_lock : public noncopyable { public: explicit scope_w_lock(reader_writer_lock& lock) : rwlock_(lock) { diff --git a/src/core/lock/spin_lock.hpp b/src/core/lock/spin_lock.hpp index 122d2642a..5851dab98 100644 --- a/src/core/lock/spin_lock.hpp +++ b/src/core/lock/spin_lock.hpp @@ -24,8 +24,7 @@ namespace ark { -class spin_lock -{ +class spin_lock { public: spin_lock() : atomic_lock_(false) { diff --git a/src/core/logger.hpp b/src/core/logger.hpp index d777e6211..937a402a3 100644 --- a/src/core/logger.hpp +++ b/src/core/logger.hpp @@ -81,15 +81,13 @@ constexpr spdlog::source_loc log_source_location( #define ARK_LOG_OSS(name, content) logger::instance()->log_oss(spdlog::level::info, name, content) -enum class k_log_sink_type : uint8_t -{ +enum class k_log_sink_type : uint8_t { date_and_hour_sink = 0, // default, rotate by hour with specific date path size_step_sink, // rotate by file size, unused for now // others }; -class log_conf_data final -{ +class log_conf_data final { public: std::string output_path{"./binlog"}; k_log_sink_type sink_type{k_log_sink_type::date_and_hour_sink}; @@ -105,8 +103,7 @@ class log_conf_data final std::string pattern{}; }; -class log_conf final -{ +class log_conf final { shared_object_hashmap conf_datas_; public: @@ -120,8 +117,7 @@ class log_conf final } }; -class spdlogger final -{ +class spdlogger final { std::shared_ptr log_conf_{nullptr}; std::string log_name_{}; bool registered_{false}; @@ -135,8 +131,7 @@ class spdlogger final } ~spdlogger() { - if (registered_) - { + if (registered_) { spdlog::drop(log_name_); } } @@ -148,25 +143,20 @@ class spdlogger final log_name_ = identity.empty() ? file_path : identity + ":" + file_path; std::vector sinks_vec; - if (log_conf_->file) - { - switch (log_conf_->sink_type) - { - case k_log_sink_type::date_and_hour_sink: - { + if (log_conf_->file) { + switch (log_conf_->sink_type) { + case k_log_sink_type::date_and_hour_sink: { auto date_and_hour_sink = std::make_shared(detail::logging_filename(native_path)); sinks_vec.emplace_back(date_and_hour_sink); - } - break; + } break; default: ARK_ASSERT_BREAK(0); break; } } - if (log_conf_->consol) - { + if (log_conf_->consol) { #ifdef ARK_PLATFORM_WIN auto color_sink = std::make_shared(); #else @@ -175,14 +165,11 @@ class spdlogger final sinks_vec.push_back(color_sink); } - if (log_conf_->sink_queue_count > 0) - { + if (log_conf_->sink_queue_count > 0) { tp_ = std::make_shared(log_conf_->sink_queue_count, 1); logger_ = std::make_shared(log_name_, std::begin(sinks_vec), std::end(sinks_vec), tp_); - } - else - { + } else { logger_ = std::make_shared(log_name_, std::begin(sinks_vec), std::end(sinks_vec)); } @@ -201,8 +188,7 @@ class spdlogger final using log_functor = std::function; -class logger final : public singleton -{ +class logger final : public singleton { using logger_t = std::shared_ptr; // singleton @@ -230,8 +216,7 @@ class logger final : public singleton } static void init(logger* instance) { - if (instance == nullptr) - { + if (instance == nullptr) { singleton::instance(); return; } @@ -242,8 +227,7 @@ class logger final : public singleton // Public string paths and filenames are UTF-8 on every platform. bool init_logger(const logging_settings& settings, const std::string& log_filename) { - if (default_logger_ != nullptr) - { + if (default_logger_ != nullptr) { return false; } auto config = std::make_unique(); @@ -252,8 +236,7 @@ class logger final : public singleton value.pattern.find('\0') != std::string::npos || value.output_path.empty() || value.output_path.find('\0') != std::string::npos || (value.level != "trace" && value.level != "debug" && value.level != "info" && value.level != "warn" && - value.level != "error" && value.level != "critical" && value.level != "off")) - { + value.level != "error" && value.level != "critical" && value.level != "off")) { throw std::invalid_argument("invalid logging settings"); } auto result = std::make_shared(); @@ -266,15 +249,13 @@ class logger final : public singleton return result; }; config->set_conf_data("default", convert(settings)); - for (const auto& [name, value] : settings.loggers) - { + for (const auto& [name, value] : settings.loggers) { config->set_conf_data(name, convert(value)); } auto local = std::make_shared(config->get_conf_data("default")); local->init(log_filename, "default"); auto oss = local; - if (auto data = config->get_conf_data("oss")) - { + if (auto data = config->get_conf_data("oss")) { oss = std::make_shared(std::move(data)); oss->init(log_filename, "oss"); } @@ -287,15 +268,13 @@ class logger final : public singleton logger_t create_logger(bus_id_t id, std::string const& name, std::string const& filename) { auto iter = loggers_.find(id); - if (iter != loggers_.end()) - { + if (iter != loggers_.end()) { return iter->second; } // find log configuration auto log_conf_data = log_conf_->get_conf_data(name); - if (log_conf_data == nullptr) - { + if (log_conf_data == nullptr) { return nullptr; } @@ -308,8 +287,7 @@ class logger final : public singleton void remove_logger(bus_id_t id) { auto iter = loggers_.find(id); - if (iter == loggers_.end()) - { + if (iter == loggers_.end()) { return; } @@ -317,12 +295,9 @@ class logger final : public singleton } void set_log_func(log_functor&& func) { - if (func != nullptr) - { + if (func != nullptr) { log_func_ = func; - } - else - { + } else { auto func = std::bind_front(&logger::log, this); log_func_ = func; } @@ -352,8 +327,7 @@ class logger final : public singleton void* default_data[default_size] = {0}; auto stack_num = backtrace(default_data, default_size); auto stack_trace = backtrace_symbols(default_data, stack_num); - for (auto i = 0; i < stack_num; i++) - { + for (auto i = 0; i < stack_num; i++) { log(spdlog::level::err, stack_trace[i]); } free(stack_trace); diff --git a/src/core/macros.hpp b/src/core/macros.hpp index a1c0b359b..7d3268643 100644 --- a/src/core/macros.hpp +++ b/src/core/macros.hpp @@ -60,22 +60,17 @@ inline size_t strlcpy(char* dst, const char* src, size_t siz) { size_t n = siz; /* Copy as many bytes as will fit */ - if ((n != 0) && ((--n) != 0)) - { - do - { - if ((*d++ = *s++) == 0) - { + if ((n != 0) && ((--n) != 0)) { + do { + if ((*d++ = *s++) == 0) { break; } } while (--n != 0); } /* Not enough room in dst, add NUL and traverse rest of src */ - if (n == 0) - { - if (siz != 0) - { + if (n == 0) { + if (siz != 0) { *d = '\0'; /* NUL-terminate dst */ } @@ -96,10 +91,8 @@ inline size_t strlcpy(char* dst, const char* src, size_t siz) { #define ARK_STRICMP _stricmp #define ARK_STRNCPY strlcpy #define ARK_ASSERT(exp_, msg_, file_, func_) \ - do \ - { \ - if (!(exp_)) \ - { \ + do { \ + if (!(exp_)) { \ std::string error_message("Message:"); \ error_message += msg_ + std::string(" don't exist or some warning") + std::string("\n\nFile:") + \ std::string(file_) + std::string("\n Function:") + func_; \ @@ -133,8 +126,7 @@ typedef struct HINSTANCE__* library_instance; #define ARK_STRICMP strcasecmp #define ARK_STRNCPY strlcpy #define ARK_ASSERT(exp_, msg_, file_, func_) \ - do \ - { \ + do { \ if ((exp_)) \ break; \ assert(exp_); \ @@ -161,8 +153,7 @@ typedef struct HINSTANCE__* library_instance; #define ARK_STRICMP strcasecmp #define ARK_STRNCPY strlcpy #define ARK_ASSERT(exp_, msg_, file_, func_) \ - do \ - { \ + do { \ if ((exp_)) \ break; \ assert(exp_); \ @@ -222,8 +213,7 @@ typedef struct HINSTANCE__* library_instance; #endif #define ARK_ASSERT_RET_VAL(exp_, val) \ - do \ - { \ + do { \ if ((exp_)) \ break; \ assert(exp_); \ @@ -231,30 +221,26 @@ typedef struct HINSTANCE__* library_instance; } while (false) #define ARK_ASSERT_RET_VAL_NO_EFFECT(exp_, val) \ - do \ - { \ + do { \ if ((exp_)) \ break; \ return val; \ } while (false) #define ARK_ASSERT_BREAK(exp_) \ - if (!(exp_)) \ - { \ + if (!(exp_)) { \ assert(exp_); \ break; \ } #define ARK_ASSERT_CONTINUE(exp_) \ - if (!(exp_)) \ - { \ + if (!(exp_)) { \ assert(exp_); \ continue; \ } #define ARK_ASSERT_RET_NONE(exp_) \ - do \ - { \ + do { \ if ((exp_)) \ break; \ assert(exp_); \ @@ -262,8 +248,7 @@ typedef struct HINSTANCE__* library_instance; } while (false) #define ARK_ASSERT_NO_EFFECT(exp_) \ - do \ - { \ + do { \ if (exp_) \ break; \ assert(exp_); \ @@ -287,18 +272,15 @@ typedef struct HINSTANCE__* library_instance; #ifndef ARK_NEW_ARRAY_RET #define ARK_NEW_ARRAY_RET(element_type, size) \ - do \ - { \ + do { \ return new (std::nothrow) element_type[(size)]; \ } while (false); #endif // ARK_NEW_ARRAY_RET #ifndef ARK_DELETE #define ARK_DELETE(p) \ - do \ - { \ - if ((p) != nullptr) \ - { \ + do { \ + if ((p) != nullptr) { \ delete (p); \ (p) = nullptr; \ } \ @@ -307,10 +289,8 @@ typedef struct HINSTANCE__* library_instance; #ifndef ARK_DELETE_ARRAY #define ARK_DELETE_ARRAY(element_type, p) \ - do \ - { \ - if ((p) != nullptr) \ - { \ + do { \ + if ((p) != nullptr) { \ element_type* t_ptr = static_cast((p)); \ delete[] t_ptr; \ t_ptr = nullptr; \ @@ -331,8 +311,7 @@ typedef struct HINSTANCE__* library_instance; ////////////////////////////////////////////////////////////////////////// // Plugin macros #define ARK_DECLARE_PLUGIN(plugin_type) \ - class plugin_type final : public plugin \ - { \ + class plugin_type final : public plugin { \ public: \ int get_plugin_version() override { \ return 0; \ @@ -374,8 +353,7 @@ typedef struct HINSTANCE__* library_instance; std::string plugin_type::plugin_conf_ = ""; // init the plugin_conf in here cuz the duplicate symbol #define ARK_REGISTER_MODULE(module_type, implementation_type) \ - do \ - { \ + do { \ ARK_ASSERT_RET_NONE((std::is_base_of::value)); \ ARK_ASSERT_RET_NONE((std::is_base_of::value)); \ module* registered_module = ARK_NEW implementation_type(); \ @@ -384,8 +362,7 @@ typedef struct HINSTANCE__* library_instance; registered_module->set_name(GET_CLASS_NAME(module_type)); \ get_plugin_manager()->add_module(registered_module->get_name(), registered_module); \ modules_.insert(std::make_pair(registered_module->get_name(), registered_module)); \ - if (typeid(&module::update) != typeid(&implementation_type::update)) \ - { \ + if (typeid(&module::update) != typeid(&implementation_type::update)) { \ get_plugin_manager()->add_update_module(registered_module); \ } \ } while (0) diff --git a/src/core/math/vector3d.hpp b/src/core/math/vector3d.hpp index d0ce549a5..298a949f9 100644 --- a/src/core/math/vector3d.hpp +++ b/src/core/math/vector3d.hpp @@ -25,8 +25,7 @@ namespace ark { -class vector3d -{ +class vector3d { public: float x{0.0f}; float y{0.0f}; @@ -53,8 +52,7 @@ class vector3d } const vector3d& operator=(const vector3d& rhs) { - if (this != &rhs) - { + if (this != &rhs) { x = rhs.x; y = rhs.y; z = rhs.z; diff --git a/src/core/misc.hpp b/src/core/misc.hpp index 759d05d90..83ce72566 100644 --- a/src/core/misc.hpp +++ b/src/core/misc.hpp @@ -30,34 +30,28 @@ namespace ark { -class misc -{ +class misc { public: static uint32_t get_nearest2_n(uint32_t size) { - if (size == 0) - { + if (size == 0) { return 0; } - if (size <= 8) - { + if (size <= 8) { return 8; } - if (size > (1 << 16)) - { + if (size > (1 << 16)) { return 0; } - if ((size & (size - 1)) == 0) - { + if ((size & (size - 1)) == 0) { return size; } int count = 0; - while (size) - { + while (size) { size = size >> 1; ++count; } @@ -72,13 +66,10 @@ class misc template static bool from_string(const std::string& str_value, element_type& result) { - try - { + try { result = ARK_LEXICAL_CAST(str_value); return true; - } - catch (std::system_error& ex) - { + } catch (std::system_error& ex) { ARK_ASSERT_NO_EFFECT(0); return false; } @@ -88,13 +79,10 @@ class misc template static element_type from_string(const std::string& str_value) { - try - { + try { element_type result = ARK_LEXICAL_CAST(str_value); return result; - } - catch ([[maybe_unused]] std::system_error& ex) - { + } catch ([[maybe_unused]] std::system_error& ex) { ARK_ASSERT_NO_EFFECT(0); return element_type(); } @@ -113,10 +101,8 @@ class misc }; static int data_type_len = std::size(data_type_names); - for (int i = 0; i < data_type_len; ++i) - { - if (type_name == data_type_names[i]) - { + for (int i = 0; i < data_type_len; ++i) { + if (type_name == data_type_names[i]) { return data_type(i); } } @@ -126,8 +112,7 @@ class misc template static element_type operate(data_op_type op, const element_type& base, const element_type& delta) { - switch (op) - { + switch (op) { case data_op_type::dot_inc: base += delta; break; @@ -164,8 +149,7 @@ class misc static long pow_i(int d, int n) { int i; long m = 1; - for (i = 0; i < n; i++) - { + for (i = 0; i < n; i++) { m *= d; } @@ -173,20 +157,16 @@ class misc } static bool is_right_data(char c, int jz) { - if ((jz < 2) || (jz > 16)) - { + if ((jz < 2) || (jz > 16)) { return false; } char ch[] = "00112233445566778899aAbBcCdDeEfF"; int i = 0; - for (i = 0; i < jz; i++) - { - if (c == ch[i * 2]) - { + for (i = 0; i < jz; i++) { + if (c == ch[i * 2]) { return true; } - if (c == ch[i * 2 + 1]) - { + if (c == ch[i * 2 + 1]) { return true; } } @@ -198,15 +178,11 @@ class misc long int_value = 0; int bit_value = 0; int i; - for (i = 0; i < l; i++) - { - if (is_right_data(str_data[i], jz)) - { + for (i = 0; i < l; i++) { + if (is_right_data(str_data[i], jz)) { bit_value = to_hex_digit(str_data[i]); int_value = bit_value * pow_i(jz, l - i - 1) + int_value; - } - else - { + } else { return -1; } } @@ -217,14 +193,10 @@ class misc assert(is_right_data(c, 16)); int bit_value = 0; - if (isdigit(c)) - { + if (isdigit(c)) { bit_value = c - 0x30; - } - else - { - switch (c) - { + } else { + switch (c) { case 'a': case 'A': bit_value = 0x0a; @@ -296,17 +268,13 @@ class misc // Pre allocated memory rst_string.reserve(input.size() * 2); - for (size_t i = 0; i < input.size(); i++) - { + for (size_t i = 0; i < input.size(); i++) { //bool isAscIIChar = int8_t(_Str[i]) >= 0x0 && int8_t(_Str[i]) <= 0x7f; bool is_asc_ii_char = (static_cast(input[i]) <= 127); - if (is_asc_ii_char) - { + if (is_asc_ii_char) { // english characters rst_string.append(shift_map[size_t(input[i])]); - } - else - { + } else { // other characters rst_string.append(1, input[i]); } @@ -319,45 +287,33 @@ class misc ostrm << prefix; // hex - for (size_t i = 0; i < line.size(); i++) - { + for (size_t i = 0; i < line.size(); i++) { char hex_text[16] = ""; snprintf(hex_text, sizeof(hex_text), "%02X ", (unsigned char)(line[i])); ostrm << hex_text; - if (i == 7 || i == 15 || i == 23) - { + if (i == 7 || i == 15 || i == 23) { ostrm << ' '; } } // the space between hex and text - for (unsigned long spacer = line.size(); spacer < width; spacer++) - { + for (unsigned long spacer = line.size(); spacer < width; spacer++) { ostrm << " "; } - if (line.size() <= 8) - { + if (line.size() <= 8) { ostrm << " "; - } - else if (line.size() <= 16) - { + } else if (line.size() <= 16) { ostrm << " "; - } - else if (line.size() <= 24) - { + } else if (line.size() <= 24) { ostrm << " "; } ostrm << ": "; // text - for (size_t i = 0; i < line.size(); i++) - { - if (line[i] < 32) - { + for (size_t i = 0; i < line.size(); i++) { + if (line[i] < 32) { ostrm << '.'; - } - else - { + } else { ostrm << char(line[i]); } } @@ -371,15 +327,13 @@ class misc std::ostringstream ostrm; std::string str = input; - while (str.size() > width) - { + while (str.size() > width) { std::string line(str.c_str(), width); ostrm << hexdump_oneline(prefix, line, width); str = str.substr(width); } - if (str.size() > 0) - { + if (str.size() > 0) { ostrm << hexdump_oneline(prefix, str, width); } @@ -400,25 +354,17 @@ class misc // check if it's the standard format : "\(3F)" bool is_allowd_format = false; - if (src_str_len < 5) - { + if (src_str_len < 5) { is_allowd_format = false; - } - else if (p_src[0] != '\\' || p_src[1] != '(' || p_src[4] != ')') - { + } else if (p_src[0] != '\\' || p_src[1] != '(' || p_src[4] != ')') { is_allowd_format = false; - } - else if ((!is_hex_number(p_src[2])) || (!is_hex_number(p_src[3]))) - { + } else if ((!is_hex_number(p_src[2])) || (!is_hex_number(p_src[3]))) { is_allowd_format = false; - } - else - { + } else { is_allowd_format = true; } - if (is_allowd_format == false) - { + if (is_allowd_format == false) { // illegal format. //assert(false); // tag: do not assert @@ -438,8 +384,7 @@ class misc // pSrc is "\r" "\n" "\t" "\\" static int proc_shift_char_by_char(char& dst, const char* const p_src, int src_str_len) { // Check format. - if (src_str_len < 2) - { + if (src_str_len < 2) { // illegal format. //assert(false); // tag: do not assert @@ -449,8 +394,7 @@ class misc return 1; } - switch (p_src[1]) - { + switch (p_src[1]) { case 'r': dst = '\r'; return 2; @@ -476,8 +420,7 @@ class misc // return the pos that the iter moves. static int proc_shift_char(char& dst, const char* p_src, int src_str_len) { - switch (p_src[1]) - { + switch (p_src[1]) { case 'r': case 'n': case 't': @@ -502,15 +445,11 @@ class misc rst_string.reserve(c_style_string.size()); size_t c_style_str_index = 0; - while (c_style_str_index < c_style_string.size()) - { - if (c_style_string[c_style_str_index] != '\\') - { + while (c_style_str_index < c_style_string.size()) { + if (c_style_string[c_style_str_index] != '\\') { rst_string.append(1, c_style_string[c_style_str_index]); c_style_str_index++; - } - else - { + } else { char shift_char = 0; int c_style_str_left_len = c_style_string.size() - c_style_str_index; c_style_str_index += @@ -535,18 +474,15 @@ class misc // when len <= prefixLen // test_str(adfadf, 3) == adf - if (str.size() >= str_len) - { + if (str.size() >= str_len) { str.resize(str_len); return str; } // when len < 20 // test_str(adf, 13) == adfa:67890123 - if (str_len < 20) - { - for (size_t i = str.size() + 1; i <= str_len; ++i) - { + if (str_len < 20) { + for (size_t i = str.size() + 1; i <= str_len; ++i) { str.push_back(char(((i % 10) + 0x30))); } @@ -560,24 +496,20 @@ class misc str.resize(10, '='); // (20_56789)(30_56789) - while (str.size() + 10 <= str_len) - { + while (str.size() + 10 <= str_len) { const size_t new_len = str.size() + 10; std::ostringstream tmp_ostrm; tmp_ostrm << str << "(" << new_len << '_'; str = tmp_ostrm.str(); - for (size_t i = str.size() + 1; i < new_len; ++i) - { + for (size_t i = str.size() + 1; i < new_len; ++i) { str.push_back(char(((i % 10) + 0x30))); } str += ')'; } // 12345 - if (str.size() < str_len) - { - for (size_t i = str.size() + 1; i <= str_len; ++i) - { + if (str.size() < str_len) { + for (size_t i = str.size() + 1; i <= str_len; ++i) { char c = ((i % 10) + 0x30); str.push_back(c); } diff --git a/src/core/module.hpp b/src/core/module.hpp index c1a176757..3ab992330 100644 --- a/src/core/module.hpp +++ b/src/core/module.hpp @@ -30,8 +30,7 @@ namespace ark { class plugin_manager; -class module -{ +class module { public: module() = default; virtual ~module() = default; diff --git a/src/core/module_base.hpp b/src/core/module_base.hpp index 9f253c21f..24f160534 100644 --- a/src/core/module_base.hpp +++ b/src/core/module_base.hpp @@ -12,8 +12,7 @@ namespace ark { template interface_type, std::derived_from... provider_types> -class module_base : public interface_type -{ +class module_base : public interface_type { public: std::vector get_dependencies() const override { return {typeid(provider_types).name()...}; diff --git a/src/core/noncopyable.hpp b/src/core/noncopyable.hpp index 70c6f9b41..a677f4aaf 100755 --- a/src/core/noncopyable.hpp +++ b/src/core/noncopyable.hpp @@ -22,8 +22,7 @@ namespace ark { -class noncopyable -{ +class noncopyable { protected: noncopyable() = default; ~noncopyable() = default; diff --git a/src/core/pattern/singleton.hpp b/src/core/pattern/singleton.hpp index b82d8a185..d805340ce 100644 --- a/src/core/pattern/singleton.hpp +++ b/src/core/pattern/singleton.hpp @@ -27,8 +27,7 @@ namespace ark { template -class singleton : public noncopyable -{ +class singleton : public noncopyable { public: static element_type* instance() { // The C++ initialization guard serializes first access and retries if init throws. @@ -57,8 +56,7 @@ class singleton : public noncopyable private: static void init() { - if (!stopped_ && instance_ == nullptr) - { + if (!stopped_ && instance_ == nullptr) { owned_instance_ = ARK_NEW element_type(); instance_ = owned_instance_; } diff --git a/src/core/plugin.hpp b/src/core/plugin.hpp index a6f8c3eee..4fb1364f8 100755 --- a/src/core/plugin.hpp +++ b/src/core/plugin.hpp @@ -26,8 +26,7 @@ namespace ark { class plugin_manager; -class plugin -{ +class plugin { public: virtual ~plugin() = default; virtual int get_plugin_version() = 0; diff --git a/src/core/plugin_base.hpp b/src/core/plugin_base.hpp index 5a5ae84ad..d34b4870b 100644 --- a/src/core/plugin_base.hpp +++ b/src/core/plugin_base.hpp @@ -13,15 +13,13 @@ namespace ark { -enum class module_update -{ +enum class module_update { disabled, enabled }; template -class plugin_base : public plugin -{ +class plugin_base : public plugin { public: plugin_base() = default; plugin_base(const plugin_base&) = delete; @@ -60,33 +58,27 @@ class plugin_base : public plugin template interface_type> bool register_module(std::unique_ptr candidate, module_update update) { get_plugin_manager()->check_registration(); - if (!candidate) - { + if (!candidate) { return false; } const std::string name = typeid(interface_type).name(); candidate->set_plugin_manager(get_plugin_manager()); candidate->set_name(name); const auto [entry, inserted] = modules_.emplace(name, candidate.get()); - if (!inserted) - { + if (!inserted) { return false; } - try - { + try { if (!get_plugin_manager()->register_owned_module(name, *candidate, update == module_update::enabled, {this, [](void* owner, const std::string& key) { return static_cast(owner)->destroy_named_module(key); }, - lifetime_})) - { + lifetime_})) { modules_.erase(entry); return false; } - } - catch (...) - { + } catch (...) { modules_.erase(entry); throw; } @@ -103,8 +95,7 @@ class plugin_base : public plugin bool unregister_named_module(const std::string& name) { get_plugin_manager()->check_registry_mutation(); const auto entry = modules_.find(name); - if (entry == modules_.end() || !destroy_named_module(name)) - { + if (entry == modules_.end() || !destroy_named_module(name)) { return false; } modules_.erase(entry); @@ -114,19 +105,16 @@ class plugin_base : public plugin bool destroy_named_module(const std::string& name) { get_plugin_manager()->check_registry_mutation(); const auto entry = modules_.find(name); - if (entry == modules_.end()) - { + if (entry == modules_.end()) { return false; } // Keep a null entry until uninstall acknowledges this registration. // Existing explicit unregister calls still succeed exactly once. - if (!entry->second) - { + if (!entry->second) { return true; } std::unique_ptr retired_tasks; - if (!get_plugin_manager()->unregister_owned_module(entry->first, *entry->second, retired_tasks)) - { + if (!get_plugin_manager()->unregister_owned_module(entry->first, *entry->second, retired_tasks)) { return false; } auto* instance = std::exchange(entry->second, nullptr); diff --git a/src/core/plugin_manager.hpp b/src/core/plugin_manager.hpp index 19bf9a1b5..a62a5f0b7 100644 --- a/src/core/plugin_manager.hpp +++ b/src/core/plugin_manager.hpp @@ -54,19 +54,16 @@ struct plugin_manager_test_access; template class plugin_base; -class plugin_manager final : private noncopyable -{ +class plugin_manager final : private noncopyable { using startup_modules = std::vector>; - struct module_owner - { + struct module_owner { void* instance; bool (*destroy)(void*, const std::string&); std::weak_ptr lifetime; }; - enum class call_phase - { + enum class call_phase { idle, starting, installing, @@ -76,8 +73,7 @@ class plugin_manager final : private noncopyable startup_cleanup }; - class phase_guard - { + class phase_guard { public: phase_guard(plugin_manager& manager, call_phase phase) : manager_(manager) @@ -95,8 +91,7 @@ class plugin_manager final : private noncopyable }; public: - enum class shutdown_state - { + enum class shutdown_state { running, stopping, failed, @@ -110,16 +105,14 @@ class plugin_manager final : private noncopyable ~plugin_manager() { // Destruction cannot retire tasks or release code executing on this // stack. Keep the same visible contract as the task groups themselves. - if (owner_ != std::this_thread::get_id() || execution_active() || pending_tasks_unchecked()) - { + if (owner_ != std::this_thread::get_id() || execution_active() || pending_tasks_unchecked()) { std::terminate(); } } static auto instance() -> plugin_manager* { static plugin_manager* instance_ptr = nullptr; - if (instance_ptr == nullptr) - { + if (instance_ptr == nullptr) { instance_ptr = ARK_NEW plugin_manager(); } @@ -134,8 +127,7 @@ class plugin_manager final : private noncopyable const std::shared_ptr& context, startup_cleanup_action action) noexcept { if (owner_ != std::this_thread::get_id() || startup_finished_ || (phase_ != call_phase::idle && phase_ != call_phase::installing && phase_ != call_phase::starting) || - shutdown_state_ != shutdown_state::running || task_runtime_->get_executor().running_in_this_thread()) - { + shutdown_state_ != shutdown_state::running || task_runtime_->get_executor().running_in_this_thread()) { return false; } return startup_cleanup_.prepare(owner, code_owner, context, action); @@ -148,15 +140,13 @@ class plugin_manager final : private noncopyable // Call only after failed start() returned/unwound. No poll/cancel, normal // shutdown, deletion or DSO unload. Caller must still terminate with exit 1. startup_cleanup_result cleanup_failed_startup() noexcept { - if (owner_ != std::this_thread::get_id() || execution_active() || !startup_finished_ || startup_succeeded_) - { + if (owner_ != std::this_thread::get_id() || execution_active() || !startup_finished_ || startup_succeeded_) { return startup_cleanup_result::unsafe; } startup_cleanup_started_ = true; shutdown_state_ = shutdown_state::failed; phase_guard active(*this, call_phase::startup_cleanup); - for (const auto& [owner, tasks] : task_groups_) - { + for (const auto& [owner, tasks] : task_groups_) { tasks->stop_accepting(); } return startup_cleanup_.run(); @@ -165,20 +155,17 @@ class plugin_manager final : private noncopyable auto start(int64_t const timestamp, std::string const& lib_dir, std::string const& conf_dir, std::unordered_map const& plugins) -> bool { check_owner(); - if (execution_active() || startup_finished_ || shutdown_state_ != shutdown_state::running) - { + if (execution_active() || startup_finished_ || shutdown_state_ != shutdown_state::running) { throw std::logic_error("Plugin manager cannot start during a lifecycle call or after shutdown begins"); } phase_guard active(*this, call_phase::starting); - struct attempt_guard - { + struct attempt_guard { plugin_manager& manager; ~attempt_guard() { manager.startup_finished_ = true; - if (!manager.startup_succeeded_ && manager.startup_call_.result == startup_call_result::entered) - { + if (!manager.startup_succeeded_ && manager.startup_call_.result == startup_call_result::entered) { manager.startup_call_.result = startup_call_result::exception; } } @@ -192,20 +179,16 @@ class plugin_manager final : private noncopyable plugin_conf_dir_ = conf_dir; plugins_ = plugins; - if (!init()) - { + if (!init()) { return false; } - if (!post_init(lifecycle_order_)) - { + if (!post_init(lifecycle_order_)) { return false; } - if (!check_config(lifecycle_order_)) - { + if (!check_config(lifecycle_order_)) { return false; } - if (!pre_update(lifecycle_order_)) - { + if (!pre_update(lifecycle_order_)) { return false; } @@ -227,21 +210,18 @@ class plugin_manager final : private noncopyable auto update(const int64_t timestamp, std::size_t maximum_handlers = 64) -> bool { check_owner(); - if (execution_active()) - { + if (execution_active()) { throw std::logic_error("Plugin manager update does not permit reentrant lifecycle calls"); } if (shutdown_state_ == shutdown_state::failed || shutdown_state_ == shutdown_state::stopped || - shutdown_state_ == shutdown_state::cleanup_timed_out) - { + shutdown_state_ == shutdown_state::cleanup_timed_out) { return false; } phase_guard active(*this, call_phase::updating); timestamp_ = timestamp; // Just loop the modules which have update function. - for (const auto& iter : module_updates_) - { + for (const auto& iter : module_updates_) { module* module_ptr = iter.second; ARK_ASSERT_CONTINUE(module_ptr != nullptr); @@ -260,12 +240,10 @@ class plugin_manager final : private noncopyable task_group& create_task_group(module& owner, std::size_t maximum = 64) { check_owner(); - if (shutdown_state_ != shutdown_state::running || !registered_module(owner)) - { + if (shutdown_state_ != shutdown_state::running || !registered_module(owner)) { throw std::logic_error("Task group requires a registered module before shutdown begins"); } - if (task_groups_.contains(&owner)) - { + if (task_groups_.contains(&owner)) { throw std::logic_error("Module already owns a task group"); } auto tasks = std::make_unique(task_runtime_, maximum); @@ -277,8 +255,7 @@ class plugin_manager final : private noncopyable task_group& get_tasks(module& owner) const { check_owner(); const auto found = task_groups_.find(&owner); - if (!registered_module(owner) || found == task_groups_.end()) - { + if (!registered_module(owner) || found == task_groups_.end()) { throw std::logic_error("Module has no managed task group"); } return *found->second; @@ -336,13 +313,10 @@ class plugin_manager final : private noncopyable std::string runtime_plugin_name = GET_CLASS_NAME(plugin_type); startup_call_.enter(plugin_name, "constructor"); plugin* new_plugin{}; - try - { + try { new_plugin = ARK_NEW plugin_type(); startup_call_.result = startup_call_result::passed; - } - catch (...) - { + } catch (...) { startup_call_.result = startup_call_result::exception; throw; } @@ -357,15 +331,13 @@ class plugin_manager final : private noncopyable auto add_module(const std::string& module_name, module* module_ptr) -> bool { check_registration(); - if (!module_ptr || registered_module(*module_ptr)) - { + if (!module_ptr || registered_module(*module_ptr)) { return false; } ARK_ASSERT_RET_VAL(!module_name.empty(), false); ARK_ASSERT_RET_VAL(find_module(module_name) == nullptr, false); const auto inserted = module_instances_.insert(std::make_pair(module_name, module_ptr)).second; - if (inserted) - { + if (inserted) { lifecycle_order_valid_ = false; } return inserted; @@ -374,20 +346,17 @@ class plugin_manager final : private noncopyable void remove_module(const std::string& module_name) { check_registry_mutation(); auto iter = module_instances_.find(module_name); - if (iter == module_instances_.end()) - { + if (iter == module_instances_.end()) { return; } // A task owned by another module can still borrow this provider. // Retire every managed group before removing any provider object. - if (pending_tasks_unchecked()) - { + if (pending_tasks_unchecked()) { throw std::logic_error("Cannot remove modules while managed tasks are pending"); } const auto tasks = task_groups_.find(iter->second); - if (tasks != task_groups_.end()) - { + if (tasks != task_groups_.end()) { task_groups_.erase(tasks); } module_instances_.erase(iter); @@ -455,8 +424,7 @@ class plugin_manager final : private noncopyable const auto destroy = [](ark::plugin* value) { ARK_DELETE(value); }; std::unique_ptr candidate(plugin, destroy); check_registration(); - if (!candidate) - { + if (!candidate) { startup_failure_ = "allocate_plugin: " + plugin_name; return; } @@ -476,13 +444,10 @@ class plugin_manager final : private noncopyable // Retain the existing process-exit policy once user installation begins. candidate.release(); startup_call_.enter(plugin_name, "install"); - try - { + try { plugin->install(); startup_call_.result = startup_call_result::passed; - } - catch (...) - { + } catch (...) { startup_call_.result = startup_call_result::exception; throw; } @@ -492,8 +457,7 @@ class plugin_manager final : private noncopyable void unregister_plugin(const std::string& plugin_name) { check_registry_mutation(); - if (pending_tasks_unchecked()) - { + if (pending_tasks_unchecked()) { throw std::logic_error("Cannot uninstall plugins with pending managed tasks"); } ARK_ASSERT_RET_NONE(!plugin_name.empty()); @@ -508,12 +472,9 @@ class plugin_manager final : private noncopyable auto find_plugin(const std::string& plugin_name) -> plugin* { auto iter = plugin_instances_.find(plugin_name); - if (iter != plugin_instances_.end()) - { + if (iter != plugin_instances_.end()) { return iter->second; - } - else - { + } else { return nullptr; } } @@ -523,12 +484,9 @@ class plugin_manager final : private noncopyable auto find_plugin() -> plugin* { auto plugin_name = GET_CLASS_NAME(plugin_type); auto iter = plugin_instances_.find(plugin_name); - if (iter != plugin_instances_.end()) - { + if (iter != plugin_instances_.end()) { return iter->second; - } - else - { + } else { return nullptr; } } @@ -543,33 +501,26 @@ class plugin_manager final : private noncopyable // registry insertion and declaration order. Duplicate edges count once. std::map pending; std::map> consumers; - for (const auto& [name, instance] : module_instances_) - { + for (const auto& [name, instance] : module_instances_) { pending.emplace(name, 0); } - for (auto& [name, count] : pending) - { + for (auto& [name, count] : pending) { const bool startup = std::string_view(phase) == "dependencies"; - if (startup) - { + if (startup) { startup_call_.enter(name, phase); } failure = std::string(phase) + ": " + name; - if (startup) - { + if (startup) { startup_call_.diagnostic_ready = true; } auto dependencies = module_instances_.at(name)->get_dependencies(); - if (startup) - { + if (startup) { startup_call_.result = startup_call_result::passed; } std::sort(dependencies.begin(), dependencies.end()); dependencies.erase(std::unique(dependencies.begin(), dependencies.end()), dependencies.end()); - for (const auto& provider : dependencies) - { - if (!pending.contains(provider)) - { + for (const auto& provider : dependencies) { + if (!pending.contains(provider)) { failure += " requires missing module '" + provider + "'"; return false; } @@ -578,36 +529,28 @@ class plugin_manager final : private noncopyable } } std::set ready; - for (const auto& [name, count] : pending) - { - if (count == 0) - { + for (const auto& [name, count] : pending) { + if (count == 0) { ready.insert(name); } } - while (!ready.empty()) - { + while (!ready.empty()) { auto name = *ready.begin(); ready.erase(ready.begin()); order.emplace_back(name, module_instances_.at(name)); - for (const auto& consumer : consumers[name]) - { - if (--pending.at(consumer) == 0) - { + for (const auto& consumer : consumers[name]) { + if (--pending.at(consumer) == 0) { ready.insert(consumer); } } } - if (order.size() != pending.size()) - { + if (order.size() != pending.size()) { failure = std::string(phase) + (std::string(phase) == "dependencies" ? ": cycle prevents startup; blocked modules: " : ": cycle prevents shutdown; blocked modules: "); bool first = true; - for (const auto& [name, count] : pending) - { - if (count != 0) - { + for (const auto& [name, count] : pending) { + if (count != 0) { failure += (first ? "" : ", ") + name; first = false; } @@ -620,16 +563,13 @@ class plugin_manager final : private noncopyable bool call_startup(module& instance, const std::string& name, std::string_view phase, bool (module::*hook)()) { startup_call_.enter(name, phase); - try - { + try { startup_failure_ = std::string(phase) + ": " + name; startup_call_.diagnostic_ready = true; const bool result = (instance.*hook)(); startup_call_.result = result ? startup_call_result::passed : startup_call_result::returned_false; return result; - } - catch (...) - { + } catch (...) { startup_call_.result = startup_call_result::exception; throw; } @@ -637,14 +577,12 @@ class plugin_manager final : private noncopyable auto init() -> bool { // load plugin dynamic libraries - for (auto const& iter : plugins_) - { + for (auto const& iter : plugins_) { phase_guard installing(*this, call_phase::installing); startup_call_.enter(iter.first, "load_plugin"); startup_failure_ = "load_plugin: " + iter.first; startup_call_.diagnostic_ready = true; - if (!load_plugin_library(iter.first)) - { + if (!load_plugin_library(iter.first)) { startup_call_.result = startup_call_result::returned_false; return false; } @@ -654,8 +592,7 @@ class plugin_manager final : private noncopyable startup_call_.enter("", "dependencies"); // Count construction propagates MSVC Debug iterator-proxy allocation failures. startup_modules order(0); - if (!order_modules(order, startup_failure_, "dependencies")) - { + if (!order_modules(order, startup_failure_, "dependencies")) { startup_call_.result = startup_call_result::returned_false; return false; } @@ -664,12 +601,10 @@ class plugin_manager final : private noncopyable lifecycle_order_valid_ = true; // Initialize providers before their declared consumers in every phase. - for (const auto& [name, module_ptr] : lifecycle_order_) - { + for (const auto& [name, module_ptr] : lifecycle_order_) { ARK_ASSERT_CONTINUE(module_ptr != nullptr); - if (!call_startup(*module_ptr, name, "init", &module::init)) - { + if (!call_startup(*module_ptr, name, "init", &module::init)) { return false; } } @@ -679,12 +614,10 @@ class plugin_manager final : private noncopyable } auto post_init(const startup_modules& order) -> bool { - for (const auto& [name, module_ptr] : order) - { + for (const auto& [name, module_ptr] : order) { ARK_ASSERT_CONTINUE(module_ptr != nullptr); - if (!call_startup(*module_ptr, name, "post_init", &module::post_init)) - { + if (!call_startup(*module_ptr, name, "post_init", &module::post_init)) { return false; } } @@ -694,12 +627,10 @@ class plugin_manager final : private noncopyable } auto check_config(const startup_modules& order) -> bool { - for (const auto& [name, module_ptr] : order) - { + for (const auto& [name, module_ptr] : order) { ARK_ASSERT_CONTINUE(module_ptr != nullptr); - if (!call_startup(*module_ptr, name, "check_config", &module::check_config)) - { + if (!call_startup(*module_ptr, name, "check_config", &module::check_config)) { return false; } } @@ -709,12 +640,10 @@ class plugin_manager final : private noncopyable } auto pre_update(const startup_modules& order) -> bool { - for (const auto& [name, module_ptr] : order) - { + for (const auto& [name, module_ptr] : order) { ARK_ASSERT_CONTINUE(module_ptr != nullptr); - if (!call_startup(*module_ptr, name, "pre_update", &module::pre_update)) - { + if (!call_startup(*module_ptr, name, "pre_update", &module::pre_update)) { return false; } } @@ -725,23 +654,19 @@ class plugin_manager final : private noncopyable auto ready_to_shut() -> bool { bool ready = true; - for (auto const& iter : module_instances_) - { + for (auto const& iter : module_instances_) { const module* module_ptr = iter.second; ARK_ASSERT_CONTINUE(module_ptr != nullptr); shutdown_failure_ = "ready_to_shut: " + iter.first; - if (shutdown_deadline_expired()) - { + if (shutdown_deadline_expired()) { return false; } const auto module_ready = module_ptr->ready_to_shut(); - if (shutdown_deadline_expired()) - { + if (shutdown_deadline_expired()) { return false; } - if (!module_ready) - { + if (!module_ready) { ready = false; } } @@ -759,14 +684,12 @@ class plugin_manager final : private noncopyable ARK_ASSERT_RET_VAL(library != nullptr, false); bool load_ret = library->load(plugin_library_dir_); - if (load_ret) - { + if (load_ret) { auto* loaded_library = library.get(); plugin_libs_.insert(std::make_pair(plugin_name, loaded_library)); library.release(); auto func = reinterpret_cast(loaded_library->get_symbol("DllEntryPlugin")); - if (func == nullptr) - { + if (func == nullptr) { ARK_LOG_ERROR("Shared library[{}] has no DllEntryPlugin entrypoint", loaded_library->get_name()); // Keep an already loaded handle until process exit. Static // initializers may have started work before symbol validation. @@ -776,9 +699,7 @@ class plugin_manager final : private noncopyable // The void entrypoint cannot return a nullable allocation failure. return !startup_failure_.starts_with("allocate_plugin: "); - } - else - { + } else { #ifdef ARK_PLATFORM_WIN auto error = GetLastError(); #else @@ -812,86 +733,67 @@ class plugin_manager final : private noncopyable std::optional deadline = std::nullopt) -> bool { check_owner(); timestamp_ = timestamp; - if (shutdown_state_ == shutdown_state::stopped) - { + if (shutdown_state_ == shutdown_state::stopped) { return true; } if (shutdown_state_ == shutdown_state::failed || shutdown_state_ == shutdown_state::timed_out || - shutdown_state_ == shutdown_state::cleanup_timed_out) - { + shutdown_state_ == shutdown_state::cleanup_timed_out) { return false; } - if (deadline && (!shutdown_deadline_ || *deadline < *shutdown_deadline_)) - { + if (deadline && (!shutdown_deadline_ || *deadline < *shutdown_deadline_)) { shutdown_deadline_ = deadline; } - if (shutdown_state_ == shutdown_state::running) - { + if (shutdown_state_ == shutdown_state::running) { shutdown_state_ = shutdown_state::stopping; - for (const auto& [owner, tasks] : task_groups_) - { + for (const auto& [owner, tasks] : task_groups_) { tasks->stop_accepting(); } } // A completion removes its task before invoking user code. Never tear // down a module from that code's own active stack, even at zero tasks. - if (execution_active()) - { + if (execution_active()) { return false; } - try - { + try { phase_guard active(*this, call_phase::tearing_down); - if (!lifecycle_order_valid_) - { + if (!lifecycle_order_valid_) { startup_modules order(0); - if (!order_modules(order, shutdown_failure_, "shutdown")) - { + if (!order_modules(order, shutdown_failure_, "shutdown")) { shutdown_state_ = shutdown_state::failed; return false; } lifecycle_order_ = std::move(order); lifecycle_order_valid_ = true; } - if (!shutdown_cancellation_requested_) - { + if (!shutdown_cancellation_requested_) { shutdown_cancellation_requested_ = true; shutdown_failure_ = "cancel_tasks"; - for (const auto& [owner, tasks] : task_groups_) - { + for (const auto& [owner, tasks] : task_groups_) { tasks->close(); } } - if (pending_tasks_unchecked()) - { + if (pending_tasks_unchecked()) { shutdown_failure_.clear(); - if (shutdown_deadline_expired()) - { + if (shutdown_deadline_expired()) { shutdown_failure_ = "managed_tasks"; } return false; } - if (!ready_to_shut()) - { + if (!ready_to_shut()) { return false; } // Readiness may be empty, or its final return may reach the limit. shutdown_failure_ = "ready_to_shut"; - if (shutdown_deadline_expired()) - { + if (shutdown_deadline_expired()) { return false; } - if (!shut(unload)) - { - if (shutdown_state_ != shutdown_state::cleanup_timed_out) - { + if (!shut(unload)) { + if (shutdown_state_ != shutdown_state::cleanup_timed_out) { shutdown_state_ = shutdown_state::failed; } return false; } - } - catch (...) - { + } catch (...) { shutdown_exception_ = std::current_exception(); shutdown_state_ = shutdown_state::failed; return false; @@ -901,8 +803,7 @@ class plugin_manager final : private noncopyable } bool shutdown_deadline_expired(bool cleanup_started = false) { - if (!shutdown_deadline_ || std::chrono::steady_clock::now() < *shutdown_deadline_) - { + if (!shutdown_deadline_ || std::chrono::steady_clock::now() < *shutdown_deadline_) { return false; } shutdown_state_ = cleanup_started ? shutdown_state::cleanup_timed_out : shutdown_state::timed_out; @@ -913,57 +814,46 @@ class plugin_manager final : private noncopyable auto shut(unload_type unload) -> bool { // Stop callback sources while every receiver object is still alive. // A provider must not deliver a new callback to a destroyed consumer. - for (auto iter = lifecycle_order_.rbegin(); iter != lifecycle_order_.rend(); ++iter) - { + for (auto iter = lifecycle_order_.rbegin(); iter != lifecycle_order_.rend(); ++iter) { const auto& [name, module_ptr] = *iter; shutdown_failure_ = "pre_shut: " + name; - if (!module_ptr->pre_shut() || shutdown_deadline_expired(true)) - { + if (!module_ptr->pre_shut() || shutdown_deadline_expired(true)) { return false; } } // Providers remain available through consumer shut hooks/destructors. - for (auto iter = lifecycle_order_.rbegin(); iter != lifecycle_order_.rend(); ++iter) - { + for (auto iter = lifecycle_order_.rbegin(); iter != lifecycle_order_.rend(); ++iter) { const auto& [name, module_ptr] = *iter; shutdown_failure_ = "shut: " + name; - if (!module_ptr->shut() || shutdown_deadline_expired(true)) - { + if (!module_ptr->shut() || shutdown_deadline_expired(true)) { return false; } const auto owner = module_owners_.find(name); - if (owner != module_owners_.end() && !owner->second.lifetime.expired()) - { + if (owner != module_owners_.end() && !owner->second.lifetime.expired()) { const auto release = owner->second; phase_guard releasing(*this, call_phase::uninstalling); shutdown_failure_ = "destroy: " + name; - if (!release.destroy(release.instance, name) || shutdown_deadline_expired(true)) - { + if (!release.destroy(release.instance, name) || shutdown_deadline_expired(true)) { return false; } } } phase_guard uninstalling(*this, call_phase::uninstalling); - for (auto& it : plugins_) - { + for (auto& it : plugins_) { shutdown_failure_ = "uninstall: " + it.first; - if (!unload_plugin_library(it.first) || shutdown_deadline_expired(true)) - { + if (!unload_plugin_library(it.first) || shutdown_deadline_expired(true)) { return false; } } - for (auto& iter : plugin_libs_) - { + for (auto& iter : plugin_libs_) { shutdown_failure_ = "unload: " + iter.first; - if (!unload(*iter.second)) - { + if (!unload(*iter.second)) { return false; } ARK_DELETE(iter.second); - if (shutdown_deadline_expired(true)) - { + if (shutdown_deadline_expired(true)) { return false; } } @@ -978,21 +868,16 @@ class plugin_manager final : private noncopyable // Publish only registry bookkeeping; no user callbacks or lifecycle rollback. bool register_owned_module(const std::string& name, module& instance, bool update, module_owner owner) { check_registration(); - if (module_instances_.contains(name) || module_updates_.contains(name) || registered_module(instance)) - { + if (module_instances_.contains(name) || module_updates_.contains(name) || registered_module(instance)) { return false; } const auto entry = module_instances_.emplace(name, &instance).first; - try - { + try { module_owners_.emplace(name, owner); - if (update) - { + if (update) { module_updates_.emplace(name, &instance); } - } - catch (...) - { + } catch (...) { module_owners_.erase(name); module_instances_.erase(entry); throw; @@ -1007,35 +892,30 @@ class plugin_manager final : private noncopyable const auto entry = module_instances_.find(name); const auto update = module_updates_.find(name); if (entry == module_instances_.end() || entry->second != &expected || - (update != module_updates_.end() && update->second != &expected)) - { + (update != module_updates_.end() && update->second != &expected)) { return false; } - if (pending_tasks_unchecked()) - { + if (pending_tasks_unchecked()) { throw std::logic_error("Cannot remove modules while managed tasks are pending"); } // A module may retain a direct task_group reference for its destructor. // Remove registry lookup now, but keep the facade alive through delete. const auto tasks = task_groups_.find(&expected); - if (tasks != task_groups_.end()) - { + if (tasks != task_groups_.end()) { retired_tasks = std::move(tasks->second); task_groups_.erase(tasks); } module_instances_.erase(entry); module_owners_.erase(name); lifecycle_order_valid_ = false; - if (update != module_updates_.end()) - { + if (update != module_updates_.end()) { module_updates_.erase(update); } return true; } void check_owner() const { - if (owner_ != std::this_thread::get_id()) - { + if (owner_ != std::this_thread::get_id()) { throw std::logic_error("Plugin manager requires its constructing thread"); } } @@ -1048,25 +928,21 @@ class plugin_manager final : private noncopyable check_owner(); if (startup_cleanup_started_ || (phase_ != call_phase::idle && phase_ != call_phase::installing && phase_ != call_phase::uninstalling) || - task_runtime_->get_executor().running_in_this_thread()) - { + task_runtime_->get_executor().running_in_this_thread()) { throw std::logic_error("Cannot mutate the module registry during update or shutdown hooks"); } } void check_registration() const { check_registry_mutation(); - if (shutdown_state_ != shutdown_state::running) - { + if (shutdown_state_ != shutdown_state::running) { throw std::logic_error("Cannot register modules or plugins after shutdown begins"); } } bool registered_module(const module& owner) const { - for (const auto& [name, instance] : module_instances_) - { - if (instance == &owner) - { + for (const auto& [name, instance] : module_instances_) { + if (instance == &owner) { return true; } } @@ -1075,8 +951,7 @@ class plugin_manager final : private noncopyable std::size_t pending_tasks_unchecked() const { std::size_t count{}; - for (const auto& [owner, tasks] : task_groups_) - { + for (const auto& [owner, tasks] : task_groups_) { count += tasks->pending(); } return count; diff --git a/src/core/random/random_generator.hpp b/src/core/random/random_generator.hpp index fe8ffa4ad..33098a824 100644 --- a/src/core/random/random_generator.hpp +++ b/src/core/random/random_generator.hpp @@ -24,8 +24,7 @@ namespace ark { -class random_generator -{ +class random_generator { public: random_generator() : seed_(0) @@ -71,8 +70,7 @@ class random_generator get_count_++; // reset - if (get_count_ >= (std::numeric_limits::max() - 1)) - { + if (get_count_ >= (std::numeric_limits::max() - 1)) { get_count_ = 0; } @@ -82,8 +80,7 @@ class random_generator //-------------------------------------------------------------------- // generate a random number which ranges in [0, max_range - 1] uint32_t random(uint32_t max_range) { - if (max_range == 0) - { + if (max_range == 0) { return 0; } @@ -95,19 +92,15 @@ class random_generator uint32_t min = 0; uint32_t max = 0; - if (min_range <= max_range) - { + if (min_range <= max_range) { min = min_range; max = max_range; - } - else - { + } else { min = max_range; max = min_range; } - if (min == max) - { + if (min == max) { return max; } @@ -116,12 +109,9 @@ class random_generator // generate a random number which ranges in [min_range, max_range - 1] int random(int min_range, int max_range) { - if (min_range == max_range) - { + if (min_range == max_range) { return min_range; - } - else if (min_range > max_range) - { + } else if (min_range > max_range) { std::swap(min_range, max_range); // int iMinSwap = min_range; // min_range = max_range; diff --git a/src/core/random/random_xoshiro.hpp b/src/core/random/random_xoshiro.hpp index 5492bbc45..26600addb 100644 --- a/src/core/random/random_xoshiro.hpp +++ b/src/core/random/random_xoshiro.hpp @@ -43,8 +43,7 @@ namespace ark { * @note not support for xoroshiro64** xoroshiro64* xoroshiro512** xoroshiro512* xoroshiro1024** xoroshiro1024* */ template -class xoshinro_engine -{ +class xoshinro_engine { public: typedef uint_type result_type; typedef result_type seed_type[4]; @@ -57,12 +56,9 @@ class xoshinro_engine } result_type next_init() { - if constexpr (is_plus) - { + if constexpr (is_plus) { return xoshinro_seed_[0] + xoshinro_seed_[3]; - } - else - { + } else { return rotl(xoshinro_seed_[iidx] * 5, 7) * 9; } } @@ -88,12 +84,9 @@ class xoshinro_engine result_type s1 = 0; result_type s2 = 0; result_type s3 = 0; - for (size_t i = 0; i < sizeof(jump) / sizeof(jump[0]); i++) - { - for (size_t b = 0; b < sizeof(result_type) * 8; b++) - { - if (jump[i] & result_type(1) << b) - { + for (size_t i = 0; i < sizeof(jump) / sizeof(jump[0]); i++) { + for (size_t b = 0; b < sizeof(result_type) * 8; b++) { + if (jump[i] & result_type(1) << b) { s0 ^= xoshinro_seed_[0]; s1 ^= xoshinro_seed_[1]; s2 ^= xoshinro_seed_[2]; @@ -132,8 +125,7 @@ class xoshinro_engine xoshinro_seed_[3] = 0; // just like in Lua 5.4 - for (int i = 0; i < 16; ++i) - { + for (int i = 0; i < 16; ++i) { next(); } } @@ -141,22 +133,17 @@ class xoshinro_engine template void init_seed(it& first, it last) { it begin = first; - for (int i = 0; i < 4; ++i) - { - if (begin != last) - { + for (int i = 0; i < 4; ++i) { + if (begin != last) { xoshinro_seed_[i] = *begin; ++begin; - } - else - { + } else { xoshinro_seed_[i] = 0; } } // just like in Lua 5.4 - for (int i = 0; i < 16; ++i) - { + for (int i = 0; i < 16; ++i) { next(); } } @@ -175,8 +162,7 @@ class xoshinro_engine }; template -class xoshinro_engine_128 : public xoshinro_engine -{ +class xoshinro_engine_128 : public xoshinro_engine { public: typedef xoshinro_engine base_type; typedef typename base_type::result_type result_type; @@ -202,8 +188,7 @@ class xoshinro_engine_128 : public xoshinro_engine }; template -class xoshinro_engine_256 : public xoshinro_engine -{ +class xoshinro_engine_256 : public xoshinro_engine { public: typedef xoshinro_engine base_type; typedef typename base_type::result_type result_type; @@ -246,8 +231,7 @@ class xoshinro_engine_256 : public xoshinro_engine * @see https://en.cppreference.com/w/cpp/algorithm/random_shuffle */ template -class random_manager_wrapper -{ +class random_manager_wrapper { public: typedef engine_type core_type; typedef typename core_type::result_type result_type; @@ -315,8 +299,7 @@ class random_manager_wrapper */ template output_type random_between(output_type lowest, output_type highest) { - if (highest <= lowest) - { + if (highest <= lowest) { return lowest; } result_type res = (*this)(); @@ -343,12 +326,9 @@ class random_manager_wrapper * @return the random number */ inline result_type operator()(result_type mod) noexcept { - if (0 == mod) - { + if (0 == mod) { return random(); - } - else - { + } else { return random() % mod; } } diff --git a/src/core/socket_func.hpp b/src/core/socket_func.hpp index e6ce531a9..ba6a5f3ae 100644 --- a/src/core/socket_func.hpp +++ b/src/core/socket_func.hpp @@ -47,8 +47,7 @@ namespace ark { static std::atomic_bool winsock_initialized = false; #endif -enum class proto_type -{ +enum class proto_type { unknown, tcp, udp, @@ -59,11 +58,9 @@ enum class proto_type zk, }; -class endpoint final -{ +class endpoint final { public: - class socket final - { + class socket final { public: static std::string make_url(const std::string& protocol, const std::string& hostname, const uint16_t& port) { std::string domain = protocol + "://" + hostname + ":" + std::to_string(port); @@ -83,10 +80,8 @@ class endpoint final }; static int n = std::size(proto_type_s); - for (int i = 0; i < n; ++i) - { - if (ARK_STRICMP(s.c_str(), proto_type_s[i]) == 0) - { + for (int i = 0; i < n; ++i) { + if (ARK_STRICMP(s.c_str(), proto_type_s[i]) == 0) { return proto_type(i); } } @@ -107,8 +102,7 @@ class endpoint final }; static int n = std::size(proto_type_s); - if ((int)proto >= n) - { + if ((int)proto >= n) { return proto_type_s[0]; } @@ -116,8 +110,7 @@ class endpoint final } }; - struct ext_t - { + struct ext_t { proto_type proto; std::string ip; uint16_t port; @@ -157,8 +150,7 @@ class endpoint final } static endpoint from_string(std::string const& url, std::error_code& ec) { - if (url.empty()) - { + if (url.empty()) { ec = error_category::make_error_code(-1); return endpoint(); } @@ -166,8 +158,7 @@ class endpoint final static std::regex re("((.*)://)?([^:/]+)(:(\\d+))?(/.*)?"); std::smatch result; bool ok = std::regex_match(url, result, re); - if (!ok) - { + if (!ok) { ec = error_category::make_error_code(-2); return endpoint(); } @@ -183,8 +174,7 @@ class endpoint final std::string to_string() const { std::string url; - if (proto() != proto_type::unknown) - { + if (proto() != proto_type::unknown) { url += socket::proto2str(proto()) + "://"; } diff --git a/src/core/spdlog/sinks/date_and_hour_file_sink.h b/src/core/spdlog/sinks/date_and_hour_file_sink.h index 5405ea301..e2d66c47c 100644 --- a/src/core/spdlog/sinks/date_and_hour_file_sink.h +++ b/src/core/spdlog/sinks/date_and_hour_file_sink.h @@ -27,8 +27,7 @@ namespace sinks { /* * Default generator of daily log file names. */ -struct default_date_and_hour_file_name_calculator -{ +struct default_date_and_hour_file_name_calculator { // // return file pre-dir and name and its extension: // @@ -49,8 +48,7 @@ struct default_date_and_hour_file_name_calculator const auto basename = fname.substr(basename_index); const auto ext_index = basename.rfind('.'); - if (ext_index == filename_t::npos || ext_index == 0 || ext_index == basename.size() - 1) - { + if (ext_index == filename_t::npos || ext_index == 0 || ext_index == basename.size() - 1) { return std::make_tuple(directory, basename, filename_t{}); } @@ -76,8 +74,7 @@ struct default_date_and_hour_file_name_calculator * Target path is Date/filename_hour.ext */ template -class date_and_hour_file_sink final : public base_sink -{ +class date_and_hour_file_sink final : public base_sink { public: // create daily file sink which rotates on given time date_and_hour_file_sink(filename_t base_filename, bool truncate = false) @@ -96,8 +93,7 @@ class date_and_hour_file_sink final : public base_sink auto time = msg.time; #endif bool should_rotate = time >= rotation_tp_; - if (should_rotate) - { + if (should_rotate) { auto filename = file_name_calculator_type::calc_filename(base_filename_); file_helper_.open(filename, truncate_); rotation_tp_ = next_rotation_tp(); diff --git a/src/core/spdlog/sinks/native_file.hpp b/src/core/spdlog/sinks/native_file.hpp index a7cd39c42..68fe031d1 100644 --- a/src/core/spdlog/sinks/native_file.hpp +++ b/src/core/spdlog/sinks/native_file.hpp @@ -40,34 +40,28 @@ inline spdlog::filename_t logging_filename(const std::filesystem::path& value) { // Framework sinks use native filesystem paths without changing spdlog's // filename_t or the ABI of an independently built spdlog dependency. -class logging_file -{ +class logging_file { public: void open(const spdlog::filename_t& filename, bool truncate = false) { close(); filename_ = logging_native_path(filename); - for (int attempt = 0; attempt < 5; ++attempt) - { + for (int attempt = 0; attempt < 5; ++attempt) { std::error_code ignored; - if (!filename_.parent_path().empty()) - { + if (!filename_.parent_path().empty()) { std::filesystem::create_directories(filename_.parent_path(), ignored); } - if (truncate) - { + if (truncate) { // Keep writes in append mode, including after truncation, as // external tools may rotate or truncate the open log file. std::ofstream truncated(filename_, std::ios::binary | std::ios::trunc); - if (!truncated) - { + if (!truncated) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); continue; } } stream_.clear(); stream_.open(filename_, std::ios::binary | std::ios::app); - if (stream_) - { + if (stream_) { return; } std::this_thread::sleep_for(std::chrono::milliseconds(10)); @@ -76,49 +70,42 @@ class logging_file } void reopen(bool truncate) { - if (filename_.empty()) - { + if (filename_.empty()) { spdlog::throw_spdlog_ex("Failed re opening file - was not opened before"); } open(logging_filename(filename_), truncate); } void close() { - if (stream_.is_open()) - { + if (stream_.is_open()) { stream_.close(); } } void flush() { stream_.flush(); - if (!stream_) - { + if (!stream_) { fail("Failed flush to file "); } } void write(const spdlog::memory_buf_t& buffer) { - if (!stream_.is_open()) - { + if (!stream_.is_open()) { return; } stream_.write(buffer.data(), static_cast(buffer.size())); - if (!stream_) - { + if (!stream_) { fail("Failed writing to file "); } } std::size_t size() { - if (!stream_.is_open()) - { + if (!stream_.is_open()) { fail("Cannot use size() on closed file "); } stream_.seekp(0, std::ios::end); const auto position = stream_.tellp(); - if (position == std::streampos(-1)) - { + if (position == std::streampos(-1)) { fail("Failed sizing file "); } return static_cast(position); diff --git a/src/core/spdlog/sinks/rotating_file_with_date_sink-inl.h b/src/core/spdlog/sinks/rotating_file_with_date_sink-inl.h index 3e8a3a2f5..4d7d62300 100644 --- a/src/core/spdlog/sinks/rotating_file_with_date_sink-inl.h +++ b/src/core/spdlog/sinks/rotating_file_with_date_sink-inl.h @@ -53,15 +53,13 @@ rotating_file_with_date_sink::split_by_dir_and_extenstion(const spdl auto ext_index = fname.rfind('.'); // no valid extension found - return whole path and empty string as extension - if (ext_index == filename_t::npos || ext_index == 0 || ext_index == fname.size() - 1) - { + if (ext_index == filename_t::npos || ext_index == 0 || ext_index == fname.size() - 1) { return std::make_tuple(spdlog::filename_t(), fname, spdlog::filename_t()); } // treat cases like "/etc/rc.d/somelogfile or "/abc/.hiddenfile" auto folder_index = fname.find_last_of(details::os::folder_seps_filename); - if (folder_index != fname.npos && folder_index >= ext_index - 1) - { + if (folder_index != fname.npos && folder_index >= ext_index - 1) { return std::make_tuple(fname.substr(0, folder_index), fname.substr(folder_index + 1), spdlog::filename_t()); } @@ -82,12 +80,9 @@ SPDLOG_INLINE filename_t rotating_file_with_date_sink::calc_filename spdlog::details::os::folder_seps_filename[0], tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, spdlog::details::os::folder_seps_filename[0]); - if (index != 0u) - { + if (index != 0u) { return fmt::format(SPDLOG_FILENAME_T("{}{}.{}{}"), dir_path, basename, index, ext); - } - else - { + } else { return fmt::format(SPDLOG_FILENAME_T("{}{}{}"), dir_path, basename, ext); } } @@ -97,8 +92,7 @@ SPDLOG_INLINE void rotating_file_with_date_sink::sink_it_(const deta memory_buf_t formatted; base_sink::formatter_->format(msg, formatted); current_size_ += formatted.size(); - if (current_size_ > max_size_) - { + if (current_size_ > max_size_) { rotate(); current_size_ = formatted.size(); } @@ -119,24 +113,20 @@ template void rotating_file_with_date_sink::rotate() { using details::os::filename_to_str; file_helper_.close(); - for (auto i = max_files_; i > 0; --i) - { + for (auto i = max_files_; i > 0; --i) { filename_t src = calc_filename(base_filename_, i - 1); std::error_code error; - if (!std::filesystem::exists(ark::detail::logging_native_path(src), error)) - { + if (!std::filesystem::exists(ark::detail::logging_native_path(src), error)) { continue; } filename_t target = calc_filename(base_filename_, i); - if (!rename_file(src, target)) - { + if (!rename_file(src, target)) { // if failed try again after a small delay. // this is a workaround to a windows issue, where very high rotation // rates can cause the rename to fail with permission denied (because of antivirus?). details::os::sleep_for_millis(100); - if (!rename_file(src, target)) - { + if (!rename_file(src, target)) { file_helper_.reopen(true); // truncate the log file anyway to prevent it to grow beyond its limit! current_size_ = 0; throw spdlog_ex( diff --git a/src/core/spdlog/sinks/rotating_file_with_date_sink.h b/src/core/spdlog/sinks/rotating_file_with_date_sink.h index 4cffd6a48..7d6d77aee 100644 --- a/src/core/spdlog/sinks/rotating_file_with_date_sink.h +++ b/src/core/spdlog/sinks/rotating_file_with_date_sink.h @@ -24,8 +24,7 @@ namespace sinks { // Rotating file sink based on size // template -class rotating_file_with_date_sink final : public base_sink -{ +class rotating_file_with_date_sink final : public base_sink { public: rotating_file_with_date_sink(filename_t base_filename, std::size_t max_size, std::size_t max_files); static std::tuple split_by_dir_and_extenstion(const spdlog::filename_t& fname); diff --git a/src/core/startup_cleanup.hpp b/src/core/startup_cleanup.hpp index 08b06a2e1..4adc40d36 100644 --- a/src/core/startup_cleanup.hpp +++ b/src/core/startup_cleanup.hpp @@ -9,8 +9,7 @@ namespace ark { -enum class startup_cleanup_result -{ +enum class startup_cleanup_result { not_run, done, unsafe, @@ -21,8 +20,7 @@ using startup_cleanup_action = startup_cleanup_result (*)(void*); inline constexpr std::size_t startup_cleanup_capacity = 16; -enum class startup_call_result -{ +enum class startup_call_result { not_entered, entered, passed, @@ -32,8 +30,7 @@ enum class startup_call_result // The most recent call, not a full object/resource inventory. Storage and // recording never allocate; resource ownership belongs to the separate capsule. -struct startup_call_record -{ +struct startup_call_record { std::array owner{}; std::array phase{}; startup_call_result result{startup_call_result::not_entered}; @@ -51,8 +48,7 @@ struct startup_call_record template static void copy(std::array& target, std::string_view value) noexcept { const auto count = value.size() < size - 1 ? value.size() : size - 1; - for (std::size_t index{}; index < count; ++index) - { + for (std::size_t index{}; index < count; ++index) { target[index] = value[index]; } target[count] = '\0'; @@ -63,19 +59,16 @@ namespace detail { // Preallocated independent owners, enrolled before acquisition. Failure cleanup // retains every capsule and its DSO deleter code until the launcher's exit. -class startup_cleanup_registry -{ +class startup_cleanup_registry { public: bool prepare(std::string_view owner, std::string_view code_owner, const std::shared_ptr& context, startup_cleanup_action action) noexcept { - if (entered_ || count_ == entries_.size() || !valid_key(owner) || !valid_key(code_owner) || !context || !action) - { + if (entered_ || count_ == entries_.size() || !valid_key(owner) || !valid_key(code_owner) || !context || + !action) { return false; } - for (std::size_t index{}; index < count_; ++index) - { - if (owner == entries_[index].owner.data()) - { + for (std::size_t index{}; index < count_; ++index) { + if (owner == entries_[index].owner.data()) { return false; } } @@ -89,27 +82,22 @@ class startup_cleanup_registry } startup_cleanup_result run() noexcept { - if (entered_) - { + if (entered_) { return result_; } entered_ = true; - for (std::size_t index = count_; index > 0; --index) - { + for (std::size_t index = count_; index > 0; --index) { auto& entry = entries_[index - 1]; - try - { + try { result_ = entry.action(entry.context.get()); if (result_ != startup_cleanup_result::done && result_ != startup_cleanup_result::unsafe && - result_ != startup_cleanup_result::failed) - { + result_ != startup_cleanup_result::failed) { result_ = startup_cleanup_result::failed; } + } catch (...) { + result_ = startup_cleanup_result::failed; } - catch (...) - { result_ = startup_cleanup_result::failed; } - if (result_ != startup_cleanup_result::done) - { + if (result_ != startup_cleanup_result::done) { // An incomplete newer resource can still borrow an older one. // Do not release older owners or retry any action after failure. break; @@ -120,16 +108,14 @@ class startup_cleanup_registry void disarm() noexcept { entered_ = true; - for (std::size_t index{}; index < count_; ++index) - { + for (std::size_t index{}; index < count_; ++index) { entries_[index].action = nullptr; entries_[index].context.reset(); } } private: - struct entry - { + struct entry { std::array owner{}; std::array code_owner{}; std::shared_ptr context; @@ -141,8 +127,7 @@ class startup_cleanup_registry } static void copy(std::array& target, std::string_view value) noexcept { - for (std::size_t index{}; index < value.size(); ++index) - { + for (std::size_t index{}; index < value.size(); ++index) { target[index] = value[index]; } } diff --git a/src/core/string.hpp b/src/core/string.hpp index 8139e167a..b47abd594 100644 --- a/src/core/string.hpp +++ b/src/core/string.hpp @@ -25,13 +25,10 @@ namespace ark { template -class char_traits -{ -}; +class char_traits {}; template<> -class char_traits -{ +class char_traits { public: static size_t length(const char* value) { return strlen(value); @@ -56,8 +53,7 @@ class char_traits static size_t find(const char* dst, const char* find, size_t begin = 0) { const char* pos = strstr(&dst[begin], find); - if (pos == nullptr) - { + if (pos == nullptr) { return -1; } @@ -71,8 +67,7 @@ class char_traits ////////////////////////////////////////////////////////////////////////// -class string_allocator -{ +class string_allocator { public: string_allocator() { } @@ -95,8 +90,7 @@ class string_allocator template, typename allocator_type = string_allocator> -class small_string -{ +class small_string { using self_type = small_string; public: @@ -108,8 +102,7 @@ class small_string } ~small_string() { - if (capacity_ > inline_capacity) - { + if (capacity_ > inline_capacity) { allocator_.free(data_, capacity_ * sizeof(char_type)); } } @@ -145,34 +138,27 @@ class small_string char_type* tmp_data = src.data_; char_type tmp_stack[inline_capacity]; - if (tmp_capacity <= inline_capacity) - { + if (tmp_capacity <= inline_capacity) { traits_type::copy(tmp_stack, src.inline_buffer_, tmp_size + 1); } src.size_ = this->size_; src.capacity_ = this->capacity_; - if (this->capacity_ <= inline_capacity) - { + if (this->capacity_ <= inline_capacity) { traits_type::copy(src.inline_buffer_, this->inline_buffer_, this->size_ + 1); src.data_ = src.inline_buffer_; - } - else - { + } else { src.data_ = this->data_; } this->size_ = tmp_size; this->capacity_ = tmp_capacity; - if (tmp_capacity <= inline_capacity) - { + if (tmp_capacity <= inline_capacity) { traits_type::copy(this->inline_buffer_, tmp_stack, tmp_size + 1); this->data_ = this->inline_buffer_; - } - else - { + } else { data_ = tmp_data; } @@ -180,8 +166,7 @@ class small_string } self_type& operator=(const self_type& src) { - if (this != &src) - { + if (this != &src) { inner_assign(src.c_str(), src.length()); } @@ -234,8 +219,7 @@ class small_string } void clear() { - if (data_ != inline_buffer_) - { + if (data_ != inline_buffer_) { allocator_.free(data_, capacity_ * sizeof(char_type)); } @@ -274,10 +258,8 @@ class small_string } size_t find_last_of(char_type value) { - for (int i = int(size_ - 1); i >= 0; --i) - { - if (data_[i] == value) - { + for (int i = int(size_ - 1); i >= 0; --i) { + if (data_[i] == value) { return i; } } @@ -296,8 +278,7 @@ class small_string size_t get_mem_usage() const { size_t size = sizeof(self_type); - if (capacity_ > inline_capacity) - { + if (capacity_ > inline_capacity) { size += capacity_ * sizeof(char_type); } @@ -308,13 +289,10 @@ class small_string void init(const char_type* src, size_t len) { size_ = len; - if (size_ < inline_capacity) - { + if (size_ < inline_capacity) { capacity_ = inline_capacity; data_ = inline_buffer_; - } - else - { + } else { capacity_ = (size_ + 1) * 2; data_ = (char_type*)allocator_.alloc(capacity_ * sizeof(char_type)); } @@ -326,13 +304,10 @@ class small_string void init_with_two(const char_type* value1, size_t size1, const char_type* value2, size_t size2) { size_ = size1 + size2; - if (size_ < inline_capacity) - { + if (size_ < inline_capacity) { capacity_ = inline_capacity; data_ = inline_buffer_; - } - else - { + } else { capacity_ = (size_ + 1) * 2; data_ = (char_type*)allocator_.alloc(capacity_ * sizeof(char_type)); } @@ -343,14 +318,11 @@ class small_string } self_type& inner_assign(const char_type* src, size_t len) { - if (len < capacity_) - { + if (len < capacity_) { traits_type::copy(data_, src, len); traits_type::put(data_ + len, 0); size_ = len; - } - else - { + } else { self_type tmp(src, len); this->swap(tmp); } @@ -361,14 +333,11 @@ class small_string self_type& inner_append(const char_type* src, size_t len) { const size_t new_size = this->size_ + len; - if (new_size < capacity_) - { + if (new_size < capacity_) { traits_type::copy(data_ + size_, src, len); traits_type::put(data_ + size_ + len, 0); size_ = new_size; - } - else - { + } else { self_type tmp(this->c_str(), this->length(), src, len); this->swap(tmp); } @@ -387,13 +356,10 @@ typedef small_string, core_allocator> data_node_name typedef small_string, core_allocator> data_table_name; template -class hash -{ -}; +class hash {}; template<> -class hash -{ +class hash { public: size_t operator()(data_node_name const& pro) const { const char* value = pro.c_str(); diff --git a/src/core/string_pod.hpp b/src/core/string_pod.hpp index 22fdff934..25b0494a6 100644 --- a/src/core/string_pod.hpp +++ b/src/core/string_pod.hpp @@ -28,13 +28,10 @@ namespace ark { template -class string_traits -{ -}; +class string_traits {}; template<> -class string_traits -{ +class string_traits { public: static size_t hash(const char* value) { return get_hash_value(value); @@ -54,13 +51,10 @@ class string_traits }; template -class string_traits_no_case : public string_traits -{ -}; +class string_traits_no_case : public string_traits {}; template<> -class string_traits_no_case : public string_traits -{ +class string_traits_no_case : public string_traits { public: static size_t hash(const char* value) { return get_hash_value_no_case(value); @@ -72,16 +66,14 @@ class string_traits_no_case : public string_traits }; ////////////////////////////////////////////////////////////////////////// -class pod_string_allocator -{ +class pod_string_allocator { public: pod_string_allocator() = default; ~pod_string_allocator() = default; void* alloc(size_t size) { void* result = allocate_bytes(size); - if (result == nullptr) - { + if (result == nullptr) { throw std::bad_alloc{}; } return result; @@ -102,8 +94,7 @@ class pod_string_allocator }; template -class pod_string_node -{ +class pod_string_node { public: pod_string_node* next; size_t hash; @@ -120,8 +111,7 @@ class pod_string; template, typename allocator_type = pod_string_allocator> -class pod_string_iterator -{ +class pod_string_iterator { private: using hash_t = pod_string; using node_t = pod_string_node; @@ -137,12 +127,9 @@ class pod_string_iterator pod_string_iterator& operator++() { node_t* next = node_->next; - if (next != nullptr) - { + if (next != nullptr) { node_ = next; - } - else - { + } else { node_ = self_->to_next(node_); } @@ -181,8 +168,7 @@ class pod_string_iterator }; template -class pod_string -{ +class pod_string { private: using hash_t = pod_string; using node_t = pod_string_node; @@ -195,13 +181,10 @@ class pod_string : size_(size) { count_ = 0; - if (size > 0) - { + if (size > 0) { buckets_ = (node_t**)allocator_.alloc(sizeof(node_t*) * size); memset(buckets_, 0, sizeof(node_t*) * size); - } - else - { + } else { buckets_ = NULL; } } @@ -211,28 +194,22 @@ class pod_string count_ = 0; size_ = size; - if (size > 0) - { + if (size > 0) { buckets_ = (node_t**)allocator_.alloc(sizeof(node_t*) * size); memset(buckets_, 0, sizeof(node_t*) * size); - for (size_t i = 0; i < size; ++i) - { + for (size_t i = 0; i < size; ++i) { node_t* p = src.buckets_[i]; - while (p) - { - if (!add(p->name, p->data)) - { + while (p) { + if (!add(p->name, p->data)) { ARK_ASSERT(0, "Add fail ", __FILE__, __FUNCTION__); } p = p->next; } } - } - else - { + } else { buckets_ = NULL; } } @@ -240,8 +217,7 @@ class pod_string ~pod_string() { clear(); - if (buckets_) - { + if (buckets_) { allocator_.free(buckets_, sizeof(node_t*) * size_); } } @@ -261,12 +237,10 @@ class pod_string } void clear() { - for (size_t i = 0; i < size_; ++i) - { + for (size_t i = 0; i < size_; ++i) { node_t* p = buckets_[i]; - while (p) - { + while (p) { node_t* next = p->next; delete_node(p); p = next; @@ -283,8 +257,7 @@ class pod_string bool set(const element_type* name, const mapped_type& data) { node_t* node = find_node(name); - if (node == nullptr) - { + if (node == nullptr) { return add(name, data); } @@ -295,8 +268,7 @@ class pod_string bool add(const element_type* name, const mapped_type& data) { assert(name != nullptr); - if (count_ == size_) - { + if (count_ == size_) { expand(); } @@ -316,8 +288,7 @@ class pod_string bool add(const element_type* name, const mapped_type& data, element_type*& p_name) { assert(name != nullptr); - if (count_ == size_) - { + if (count_ == size_) { expand(); } @@ -339,8 +310,7 @@ class pod_string bool remove(const element_type* name) { assert(name != nullptr); - if (size_ == 0) - { + if (size_ == 0) { return false; } @@ -348,10 +318,8 @@ class pod_string size_t bucket = get_bucket(hash); node_t* p = buckets_[bucket]; - while (p) - { - if ((p->hash == hash) && traits_type::equal(p->name, name)) - { + while (p) { + if ((p->hash == hash) && traits_type::equal(p->name, name)) { erase_node(bucket, p); delete_node(p); --count_; @@ -367,8 +335,7 @@ class pod_string bool remove_data(const element_type* name, const mapped_type& data) { assert(name != nullptr); - if (size_ == 0) - { + if (size_ == 0) { return false; } @@ -376,10 +343,8 @@ class pod_string size_t bucket = get_bucket(hash); node_t* p = buckets_[bucket]; - while (p) - { - if ((p->hash == hash) && traits_type::equal(p->name, name) && (p->data == data)) - { + while (p) { + if ((p->hash == hash) && traits_type::equal(p->name, name) && (p->data == data)) { erase_node(bucket, p); delete_node(p); --count_; @@ -407,8 +372,7 @@ class pod_string bool get_data(const element_type* name, mapped_type& data) const { node_t* p = find_node(name); - if (p == nullptr) - { + if (p == nullptr) { return false; } @@ -417,10 +381,8 @@ class pod_string } iterator begin() { - for (size_t i = 0; i < size_; ++i) - { - if (buckets_[i]) - { + for (size_t i = 0; i < size_; ++i) { + if (buckets_[i]) { return iterator(this, buckets_[i]); } } @@ -433,10 +395,8 @@ class pod_string } const_iterator begin() const { - for (size_t i = 0; i < size_; ++i) - { - if (buckets_[i]) - { + for (size_t i = 0; i < size_; ++i) { + if (buckets_[i]) { return const_iterator(this, buckets_[i]); } } @@ -462,12 +422,10 @@ class pod_string size_t get_mem_usage() const { size_t size = sizeof(hash_t); - for (size_t i = 0; i < size_; ++i) - { + for (size_t i = 0; i < size_; ++i) { node_t* p = buckets_[i]; - while (p) - { + while (p) { size += sizeof(node_t) + traits_type::length(p->name) * sizeof(element_type); p = p->next; } @@ -500,16 +458,13 @@ class pod_string node_t* node = buckets_[bucket]; - if (node == p) - { + if (node == p) { buckets_[bucket] = p->next; return; } - while (node) - { - if (node->next == p) - { + while (node) { + if (node->next == p) { node->next = p->next; return; } @@ -521,8 +476,7 @@ class pod_string node_t* find_node(const element_type* name) const { assert(name != nullptr); - if (0 == size_) - { + if (0 == size_) { return nullptr; } @@ -530,10 +484,8 @@ class pod_string size_t bucket = get_bucket(hash); node_t* node = buckets_[bucket]; - while (node) - { - if ((node->hash == hash) && traits_type::equal(node->name, name)) - { + while (node) { + if ((node->hash == hash) && traits_type::equal(node->name, name)) { return node; } @@ -548,14 +500,11 @@ class pod_string node_t** new_buckets = (node_t**)allocator_.alloc(sizeof(node_t*) * new_size); memset(new_buckets, 0, sizeof(node_t*) * new_size); - for (size_t i = 0; i < size_; ++i) - { - if (nullptr != buckets_) - { + for (size_t i = 0; i < size_; ++i) { + if (nullptr != buckets_) { node_t* p = buckets_[i]; - while (p) - { + while (p) { node_t* next = p->next; size_t bucket = size_t(p->hash) % new_size; @@ -566,8 +515,7 @@ class pod_string } } - if (buckets_) - { + if (buckets_) { allocator_.free(buckets_, sizeof(node_t*) * size_); } @@ -578,10 +526,8 @@ class pod_string node_t* to_next(node_t* node) const { assert(node != nullptr); - for (size_t i = get_bucket(node->hash) + 1; i < size_; ++i) - { - if (buckets_[i]) - { + for (size_t i = get_bucket(node->hash) + 1; i < size_; ++i) { + if (buckets_[i]) { return buckets_[i]; } } diff --git a/src/core/string_utils.hpp b/src/core/string_utils.hpp index ed0178c1b..7513b953e 100644 --- a/src/core/string_utils.hpp +++ b/src/core/string_utils.hpp @@ -53,8 +53,7 @@ inline void dbg(const std::pair& x, std::string& fs) { template void dbg(const element_type& beg, const element_type& end, char c1, char c2, std::string& fs) { - if (beg == end) - { + if (beg == end) { //fs << c1 << c2; fs = ARK_FORMAT("{}{}{}", fs, c1, c2); return; @@ -62,8 +61,7 @@ void dbg(const element_type& beg, const element_type& end, char c1, char c2, std //fs << c1; fs = ARK_FORMAT("{}{}", fs, c1); - for (element_type it = beg; it != end; ++it) - { + for (element_type it = beg; it != end; ++it) { dbg(*it, fs); //fs << ','; fs = ARK_FORMAT("{}{}", fs, ','); @@ -74,8 +72,7 @@ void dbg(const element_type& beg, const element_type& end, char c1, char c2, std } // namespace detail -class string_utils -{ +class string_utils { public: // split("x y z", ' '); -> [ "x", "y", "z" ] // split("|x|y|", '|'); -> [ "", "x", "y" ] @@ -86,18 +83,15 @@ class string_utils const char* from = s; const char* end = s + strlen(s); - while ((p = static_cast(memchr(from, c, end - from)))) - { + while ((p = static_cast(memchr(from, c, end - from)))) { v.emplace_back(std::string_view(from, p - from)); from = p + 1; - if (v.size() == max_split) - { + if (v.size() == max_split) { break; } } - if (from < end) - { + if (from < end) { v.emplace_back(std::string_view(from)); } } @@ -107,18 +101,15 @@ class string_utils const char* from = s.data(); const char* end = from + s.size(); - while ((p = static_cast(memchr(from, c, end - from)))) - { + while ((p = static_cast(memchr(from, c, end - from)))) { v.emplace_back(std::string_view(from, p - from)); from = p + 1; - if (v.size() == max_split) - { + if (v.size() == max_split) { break; } } - if (from < end) - { + if (from < end) { v.emplace_back(std::string_view(from, end - from)); } } @@ -129,27 +120,22 @@ class string_utils size_t n = strlen(c); // An empty delimiter cannot advance the input cursor. - if (n == 0) - { - if (*s != '\0') - { + if (n == 0) { + if (*s != '\0') { v.emplace_back(s); } return; } - while ((p = strstr(from, c))) - { + while ((p = strstr(from, c))) { v.emplace_back(std::string(from, p - from)); from = p + n; - if (v.size() == max_split) - { + if (v.size() == max_split) { break; } } - if (from < s + strlen(s)) - { + if (from < s + strlen(s)) { v.emplace_back(std::string_view(from)); } } @@ -165,27 +151,23 @@ class string_utils const char* p; const char* from = s; size_t n = strlen(sub); - if (n == 0) - { + if (n == 0) { return s; } size_t m = strlen(to); std::string x; - while ((p = strstr(from, sub))) - { + while ((p = strstr(from, sub))) { x.append(from, p - from); x.append(to, m); from = p + n; - if (--max_replace == 0) - { + if (--max_replace == 0) { break; } } - if (from < s + strlen(s)) - { + if (from < s + strlen(s)) { x.append(from); } @@ -194,14 +176,12 @@ class string_utils static inline auto replace( const std::string& s, const char* sub, const char* to, uint32_t max_replace = 0) -> std::string { - if (*sub == '\0') - { + if (*sub == '\0') { return s; } const char* from = s.c_str(); const char* p = strstr(from, sub); - if (p == nullptr) - { + if (p == nullptr) { return s; } @@ -210,18 +190,15 @@ class string_utils std::string x; x.reserve(s.size()); - do - { + do { x.append(from, p - from).append(to, m); from = p + n; - if (--max_replace == 0) - { + if (--max_replace == 0) { break; } } while ((p = strstr(from, sub))); - if (from < s.data() + s.size()) - { + if (from < s.data() + s.size()) { x.append(from); } @@ -232,45 +209,34 @@ class string_utils // strip("abxxa", "ab", 'l') -> "xxa" strip left only. // strip("abxxa", "ab", 'r') -> "abxx" strip right only. static inline auto strip(const char* s, const char* c = " \t\r\n", char d = 'b') -> std::string { - if (!*s) - { + if (!*s) { return std::string(); } std::array bs = {0}; - while (*c) - { + while (*c) { bs[static_cast(*c++)] = 1; } - if (d == 'l' || d == 'L') - { - while (bs[static_cast(*s)]) - { + if (d == 'l' || d == 'L') { + while (bs[static_cast(*s)]) { ++s; } return std::string(s); - } - else if (d == 'r' || d == 'R') - { + } else if (d == 'r' || d == 'R') { const char* e = s + strlen(s); - while (e > s && bs[static_cast(e[-1])]) - { + while (e > s && bs[static_cast(e[-1])]) { --e; } return std::string(s, e - s); - } - else - { - while (bs[static_cast(*s)]) - { + } else { + while (bs[static_cast(*s)]) { ++s; } const char* e = s + strlen(s); - while (e > s && bs[static_cast(e[-1])]) - { + while (e > s && bs[static_cast(e[-1])]) { --e; } @@ -279,38 +245,28 @@ class string_utils } static inline auto strip(const char* s, char c, char d = 'b') -> std::string { - if (!*s) - { + if (!*s) { return std::string(); } - if (d == 'l' || d == 'L') - { - while (*s == c) - { + if (d == 'l' || d == 'L') { + while (*s == c) { ++s; } return std::string(s); - } - else if (d == 'r' || d == 'R') - { + } else if (d == 'r' || d == 'R') { const char* e = s + strlen(s); - while (e > s && e[-1] == c) - { + while (e > s && e[-1] == c) { --e; } return std::string(s, e - s); - } - else - { - while (*s == c) - { + } else { + while (*s == c) { ++s; } const char* e = s + strlen(s); - while (e > s && e[-1] == c) - { + while (e > s && e[-1] == c) { --e; } return std::string(s, e - s); @@ -318,48 +274,36 @@ class string_utils } static inline auto strip(const std::string& s, const char* c = " \t\r\n", char d = 'b') -> std::string { - if (s.empty()) - { + if (s.empty()) { return std::string(); } std::array bs = {0}; - while (*c) - { + while (*c) { bs[static_cast(*c++)] = 1; } - if (d == 'l' || d == 'L') - { + if (d == 'l' || d == 'L') { size_t b = 0; - while (b < s.size() && bs[static_cast(s[b])]) - { + while (b < s.size() && bs[static_cast(s[b])]) { ++b; } return b == 0 ? s : s.substr(b); - } - else if (d == 'r' || d == 'R') - { + } else if (d == 'r' || d == 'R') { size_t e = s.size(); - while (e > 0 && bs[static_cast(s[e - 1])]) - { + while (e > 0 && bs[static_cast(s[e - 1])]) { --e; } return e == s.size() ? s : s.substr(0, e); - } - else - { + } else { size_t b = 0, e = s.size(); - while (b < s.size() && bs[static_cast(s[b])]) - { + while (b < s.size() && bs[static_cast(s[b])]) { ++b; } - if (b == s.size()) - { + if (b == s.size()) { return std::string(); } - while (e > 0 && bs[static_cast(s[e - 1])]) - { + while (e > 0 && bs[static_cast(s[e - 1])]) { --e; } return (e - b == s.size()) ? s : s.substr(b, e - b); @@ -367,42 +311,31 @@ class string_utils } static inline auto strip(const std::string& s, char c, char d = 'b') -> std::string { - if (s.empty()) - { + if (s.empty()) { return std::string(); } - if (d == 'l' || d == 'L') - { + if (d == 'l' || d == 'L') { size_t b = 0; - while (b < s.size() && s[b] == c) - { + while (b < s.size() && s[b] == c) { ++b; } return b == 0 ? s : s.substr(b); - } - else if (d == 'r' || d == 'R') - { + } else if (d == 'r' || d == 'R') { size_t e = s.size(); - while (e > 0 && s[e - 1] == c) - { + while (e > 0 && s[e - 1] == c) { --e; } return e == s.size() ? s : s.substr(0, e); - } - else - { + } else { size_t b = 0, e = s.size(); - while (b < s.size() && s[b] == c) - { + while (b < s.size() && s[b] == c) { ++b; } - if (b == s.size()) - { + if (b == s.size()) { return std::string(); } - while (e > 0 && s[e - 1] == c) - { + while (e > 0 && s[e - 1] == c) { --e; } return (e - b == s.size()) ? s : s.substr(b, e - b); @@ -410,49 +343,37 @@ class string_utils } static inline auto strip(const std::string& s, const std::string& c, char d = 'b') -> std::string { - if (s.empty()) - { + if (s.empty()) { return std::string(); } std::array bs = {0}; - for (char i : c) - { + for (char i : c) { bs[static_cast(i)] = 1; } - if (d == 'l' || d == 'L') - { + if (d == 'l' || d == 'L') { size_t b = 0; - while (b < s.size() && bs[static_cast(s[b])]) - { + while (b < s.size() && bs[static_cast(s[b])]) { ++b; } return b == 0 ? s : s.substr(b); - } - else if (d == 'r' || d == 'R') - { + } else if (d == 'r' || d == 'R') { size_t e = s.size(); - while (e > 0 && bs[static_cast(s[e - 1])]) - { + while (e > 0 && bs[static_cast(s[e - 1])]) { --e; } return e == s.size() ? s : s.substr(0, e); - } - else - { + } else { size_t b = 0, e = s.size(); - while (b < s.size() && bs[static_cast(s[b])]) - { + while (b < s.size() && bs[static_cast(s[b])]) { ++b; } - if (b == s.size()) - { + if (b == s.size()) { return std::string(); } - while (e > 0 && bs[static_cast(s[e - 1])]) - { + while (e > 0 && bs[static_cast(s[e - 1])]) { --e; } return (e - b == s.size()) ? s : s.substr(b, e - b); diff --git a/src/core/task.hpp b/src/core/task.hpp index 480f0c38f..444e12b34 100644 --- a/src/core/task.hpp +++ b/src/core/task.hpp @@ -25,17 +25,14 @@ using task = asio::awaitable; // the group or the business state referenced by its tasks. Destruction with // pending tasks (or on a different thread) terminates; it does not detach tasks, // block, poll recursively, or destroy suspended coroutine frames. -class task_group -{ - struct task_record - { +class task_group { + struct task_record { asio::cancellation_signal cancellation; std::function completion; bool cancel_requested{}; }; - struct state - { + struct state { std::shared_ptr runtime; const std::thread::id owner = std::this_thread::get_id(); std::unordered_map> tasks; @@ -46,15 +43,13 @@ class task_group state(std::shared_ptr execution, std::size_t limit) : runtime(std::move(execution)) , maximum(limit) { - if (!runtime || !maximum) - { + if (!runtime || !maximum) { throw std::invalid_argument("Module task group requires a runtime and positive task limit"); } } void check_owner() const { - if (owner != std::this_thread::get_id()) - { + if (owner != std::this_thread::get_id()) { throw std::logic_error("Module task group requires its constructing thread"); } } @@ -74,8 +69,7 @@ class task_group task_group& operator=(task_group&&) = delete; ~task_group() { - if (state_->owner != std::this_thread::get_id() || !state_->tasks.empty()) - { + if (state_->owner != std::this_thread::get_id() || !state_->tasks.empty()) { std::terminate(); } } @@ -85,20 +79,17 @@ class task_group task_id start(task<> task, completion_handler completion = {}) { auto shared = state_; shared->check_owner(); - if (!shared->accepting || shared->tasks.size() == shared->maximum) - { + if (!shared->accepting || shared->tasks.size() == shared->maximum) { return 0; } - if (shared->next_id == std::numeric_limits::max()) - { + if (shared->next_id == std::numeric_limits::max()) { throw std::overflow_error("Module task identifiers exhausted"); } auto record = std::make_shared(); record->completion = std::move(completion); const auto id = shared->next_id++; shared->tasks.emplace(id, record); - try - { + try { asio::co_spawn(shared->runtime->get_executor(), std::move(task), asio::bind_cancellation_slot( record->cancellation.slot(), [shared, record, id](std::exception_ptr error) mutable { @@ -107,14 +98,11 @@ class task_group // completion may destroy the public group facade. shared->tasks.erase(id); auto handler = std::move(record->completion); - if (handler) - { + if (handler) { handler(std::move(error)); } })); - } - catch (...) - { + } catch (...) { shared->tasks.erase(id); throw; } @@ -125,13 +113,11 @@ class task_group auto shared = state_; shared->check_owner(); const auto found = shared->tasks.find(id); - if (found == shared->tasks.end()) - { + if (found == shared->tasks.end()) { return false; } auto record = found->second; - if (!record->cancel_requested) - { + if (!record->cancel_requested) { record->cancel_requested = true; record->cancellation.emit(asio::cancellation_type::terminal); } @@ -143,19 +129,15 @@ class task_group shared->check_owner(); // Emission may synchronously execute an operation's cancellation hook. // Do not retain an iterator across that external code. - while (true) - { + while (true) { std::shared_ptr next; - for (const auto& [id, record] : shared->tasks) - { - if (!record->cancel_requested) - { + for (const auto& [id, record] : shared->tasks) { + if (!record->cancel_requested) { next = record; break; } } - if (!next) - { + if (!next) { return; } next->cancel_requested = true; diff --git a/src/core/time/date_time.hpp b/src/core/time/date_time.hpp index 21c58c882..ebc1bd636 100644 --- a/src/core/time/date_time.hpp +++ b/src/core/time/date_time.hpp @@ -25,8 +25,7 @@ namespace ark { -class timespan -{ +class timespan { public: using time_diff = int64_t; @@ -63,8 +62,7 @@ class timespan } timespan& operator=(const timespan& timespan) { - if (this != ×pan) - { + if (this != ×pan) { this->span_ = timespan.span_; } return *this; @@ -217,11 +215,9 @@ class timespan //////////////////////////////////////////////////////////////////////// -class date_time -{ +class date_time { public: - enum months - { + enum months { january = 1, february, march, @@ -236,8 +232,7 @@ class date_time december }; - enum days_of_week - { + enum days_of_week { sunday = 0, monday, tuesday, @@ -289,8 +284,7 @@ class date_time ~date_time() = default; date_time& operator=(const date_time& other) { - if (this != &other) - { + if (this != &other) { ts_ = other.ts_; } @@ -461,8 +455,7 @@ class date_time // find the first firstDayOfWeek. int base_day = 1; - while (date_time(get_year(), 1, base_day).get_day_of_week() != first_day_of_week) - { + while (date_time(get_year(), 1, base_day).get_day_of_week() != first_day_of_week) { ++base_day; } @@ -474,12 +467,9 @@ class date_time int day = get_day_of_year(); day++; int offs = base_day <= 4 ? 0 : 1; //weekofYear of baseDay - if (day < base_day) - { + if (day < base_day) { return offs; - } - else - { + } else { return (day - base_day) / 7 + 1 + offs; } } @@ -494,12 +484,9 @@ class date_time // 0 = Sunday, 1 = Monday, ..., 6 = Saturday). int get_day_of_week(int first_day_of_week = monday) const { std::tm tm = get_utc_time(); - if (first_day_of_week == monday) - { + if (first_day_of_week == monday) { return ((tm.tm_wday == 0) ? 7 : tm.tm_wday); - } - else - { + } else { return tm.tm_wday; } } @@ -521,16 +508,11 @@ class date_time int gethour_ampm() const { int hour = get_hour(); - if (hour < 1) - { + if (hour < 1) { return 12; - } - else if (hour > 12) - { + } else if (hour > 12) { return hour - 12; - } - else - { + } else { return hour; } } @@ -590,13 +572,11 @@ class date_time } bool same_week(time_val time) { - if (!same_year(time)) - { + if (!same_year(time)) { return false; } - if (same_day(time)) - { + if (same_day(time)) { return true; } @@ -627,19 +607,15 @@ class date_time static int get_days_of_month(int year, int month) { ARK_ASSERT_NO_EFFECT(month >= 1 && month <= 12); - if (month < 1 || month > 12) - { + if (month < 1 || month > 12) { return -1; } static int days_of_month_table[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - if (month == 2 && is_leap_year(year)) - { + if (month == 2 && is_leap_year(year)) { return 29; - } - else - { + } else { return days_of_month_table[month]; } } diff --git a/src/core/time/timer.hpp b/src/core/time/timer.hpp index 0fa9d2fd2..60d719d2b 100644 --- a/src/core/time/timer.hpp +++ b/src/core/time/timer.hpp @@ -36,8 +36,7 @@ const uint32_t tv_size = 1 << tv_bits; // 256 slots each time_vec const uint32_t tv_mask = tv_size - 1; const uint32_t tv_num = 6; // 6 levels -class time_wheel_data -{ +class time_wheel_data { public: uint64_t idx{0}; uint32_t count{0}; // =0 means forever @@ -49,17 +48,14 @@ class time_wheel_data guid_t entity_id{null_guid}; }; -class time_wheel_vec -{ +class time_wheel_vec { public: int index{0}; std::vector> vec; }; -class time_wheel_manager -{ - struct timer_deleter - { +class time_wheel_manager { + struct timer_deleter { template void operator()(T* value) const noexcept { ARK_DELETE(value); @@ -84,16 +80,14 @@ class time_wheel_manager std::array tw_vecs{}; timer_storage.reserve(free_timer_size); - for (uint32_t i = 0; i < free_timer_size; ++i) - { + for (uint32_t i = 0; i < free_timer_size; ++i) { timer_owner data(ARK_NEW time_wheel_data()); ARK_ASSERT_RET_NONE(data != nullptr); free_timers.push_back(data.get()); timer_storage.push_back(std::move(data)); } - for (uint32_t i = 0; i < tv_num; ++i) - { + for (uint32_t i = 0; i < tv_num; ++i) { timer_vec_owner tv(ARK_NEW time_wheel_vec()); ARK_ASSERT_RET_NONE(tv != nullptr); init_timer_vec(tv.get(), tv_size); @@ -116,10 +110,8 @@ class time_wheel_manager bool has_retained_callbacks() const noexcept { // Active IDs omit completed timers and additions interrupted by a // container exception. Only the owning pool covers every callback. - for (const auto& timer : timer_storage_) - { - if (timer->callback) - { + for (const auto& timer : timer_storage_) { + if (timer->callback) { return true; } } @@ -127,8 +119,7 @@ class time_wheel_manager } void update(int64_t now_time) { - if (tw_vecs_[0]) - { + if (tw_vecs_[0]) { update_timer(now_time); } } @@ -136,8 +127,7 @@ class time_wheel_manager void shut() { timers_.clear(); free_timers_.clear(); - for (auto& tv : tw_vecs_) - { + for (auto& tv : tw_vecs_) { tv.reset(); } timer_storage_.clear(); @@ -163,8 +153,7 @@ class time_wheel_manager bool remove_timer(uint64_t idx) { auto iter = timers_.find(idx); - if (iter == timers_.end()) - { + if (iter == timers_.end()) { return false; } @@ -179,23 +168,19 @@ class time_wheel_manager void init_timer_vec(time_wheel_vec* tv, int32_t size) { tv->index = 0; tv->vec.resize(size); - for (int i = 0; i < size; ++i) - { + for (int i = 0; i < size; ++i) { tv->vec[i] = std::list(); } } time_wheel_data* get_free_timer() { time_wheel_data* timer = nullptr; - if (free_timers_.empty()) - { + if (free_timers_.empty()) { timer_owner data(ARK_NEW time_wheel_data); ARK_ASSERT_RET_VAL(data != nullptr, nullptr); timer = data.get(); timer_storage_.push_back(std::move(data)); - } - else - { + } else { timer = free_timers_.front(); free_timers_.pop_front(); } @@ -210,15 +195,13 @@ class time_wheel_manager void update_timer(int64_t now_time) { uint64_t passed_slot = (now_time - last_update_time_) / timer_precision; - if (passed_slot == 0) - { + if (passed_slot == 0) { return; } last_update_time_ += passed_slot * timer_precision; - for (uint64_t i = 0; i < passed_slot; ++i) - { + for (uint64_t i = 0; i < passed_slot; ++i) { update_slot_timer(); } } @@ -226,8 +209,7 @@ class time_wheel_manager void add_timer_internal(time_wheel_data* timer_data) { uint64_t expires = timer_data->expires; int64_t idx = expires - now_slot_; - if (idx <= 0) - { + if (idx <= 0) { time_wheel_vec* tv = tw_vecs_[0].get(); tv->vec[tv->index].push_back(timer_data); return; @@ -235,11 +217,9 @@ class time_wheel_manager uint32_t index = 0; uint64_t max_tv_num = 0; - for (uint32_t i = 0; i < tv_num; ++i) - { + for (uint32_t i = 0; i < tv_num; ++i) { max_tv_num = ((uint64_t)1 << ((i + 1) * tv_bits)); - if ((uint64_t)idx < max_tv_num) - { + if ((uint64_t)idx < max_tv_num) { index = ((expires >> (i * tv_bits)) & tv_mask); tw_vecs_[i]->vec[index].push_back(timer_data); return; @@ -250,23 +230,19 @@ class time_wheel_manager } void update_slot_timer() { - if (tw_vecs_[0]->index == 0) - { + if (tw_vecs_[0]->index == 0) { uint32_t n = 1; - do - { + do { carry_timers(tw_vecs_[n].get()); } while (tw_vecs_[n]->index == 1 && (++n < tv_num)); } int32_t index = tw_vecs_[0]->index; - while (!tw_vecs_[0]->vec[index].empty()) - { + while (!tw_vecs_[0]->vec[index].empty()) { time_wheel_data* timer = tw_vecs_[0]->vec[index].front(); tw_vecs_[0]->vec[index].pop_front(); - if (timer->callback == nullptr) - { + if (timer->callback == nullptr) { add_to_free_timer(timer); continue; } @@ -275,21 +251,17 @@ class time_wheel_manager (timer->callback)(timer->idx, timer->entity_id); // forever timer - if (timer->count == 0 && timer->interval > 0) - { + if (timer->count == 0 && timer->interval > 0) { timer->expires = static_cast(now_slot_) + timer->interval; add_timer_internal(timer); continue; } timer->count--; - if (timer->count > 0 && timer->interval > 0) - { + if (timer->count > 0 && timer->interval > 0) { timer->expires = static_cast(now_slot_) + timer->interval; add_timer_internal(timer); - } - else - { + } else { timers_.erase(timer->idx); add_to_free_timer(timer); } @@ -301,8 +273,7 @@ class time_wheel_manager void carry_timers(time_wheel_vec* tv) { int32_t index = tv->index; - while (!tv->vec[index].empty()) - { + while (!tv->vec[index].empty()) { time_wheel_data* timer = tv->vec[index].front(); add_timer_internal(timer); tv->vec[index].pop_front(); diff --git a/src/core/uid_generator.hpp b/src/core/uid_generator.hpp index 4bdbaa10c..9c86bc80b 100644 --- a/src/core/uid_generator.hpp +++ b/src/core/uid_generator.hpp @@ -31,8 +31,7 @@ namespace ark { #if defined(ARK_USE_GUID_32) -class uid_generator -{ +class uid_generator { guid_t last_sequence_{1000}; public: @@ -48,8 +47,7 @@ class uid_generator protected: guid_t next_id() { - if (last_sequence_ >= pow(2, 22)) - { + if (last_sequence_ >= pow(2, 22)) { last_sequence_ = 1000; } @@ -57,8 +55,7 @@ class uid_generator } }; -class uid_generator_thread_safe : public uid_generator -{ +class uid_generator_thread_safe : public uid_generator { public: guid_t get_uid() override { std::lock_guard lock(mutex_); @@ -75,8 +72,7 @@ class uid_generator_thread_safe : public uid_generator #else -class bits_allocator -{ +class bits_allocator { public: static const int total_bits = 1 << 6; @@ -87,8 +83,7 @@ class bits_allocator , sequence_bits_{seq_bits} { constexpr int payload_bits = total_bits - 1; if (ts_bits < 0 || ts_bits > payload_bits || worker_bits < 0 || worker_bits > payload_bits - ts_bits || - seq_bits < 0 || seq_bits != payload_bits - ts_bits - worker_bits) - { + seq_bits < 0 || seq_bits != payload_bits - ts_bits - worker_bits) { throw std::invalid_argument("UID field widths must be nonnegative and total 63 bits"); } @@ -102,8 +97,7 @@ class bits_allocator constexpr int64_t alloc(int64_t delta_seconds, int64_t worker_id, int64_t seq) { if (delta_seconds < 0 || delta_seconds > max_delta_seconds_ || worker_id < 0 || worker_id > max_worker_id_ || - seq < 0 || seq > max_sequence_) - { + seq < 0 || seq > max_sequence_) { throw std::out_of_range("UID field value exceeds its allocated width"); } return static_cast((static_cast(delta_seconds) << timestamp_shift_) | @@ -167,8 +161,7 @@ static constexpr int64_t uid_epoch = 1542643200L; // 2018/11/20 00:00:00 // TODO:remove sign and use uint64_t // then seq_bits is 12 bits, mean 2048/s -class uid_generator -{ +class uid_generator { public: uid_generator() { @@ -203,16 +196,12 @@ class uid_generator int64_t cur_second = get_current_second(); ARK_ASSERT_RET_VAL(cur_second >= last_second_, 0); - if (cur_second == last_second_) - { + if (cur_second == last_second_) { sequence_ = (sequence_ + 1) & bits_alloc_->get_max_sequence(); - if (sequence_ == 0) - { + if (sequence_ == 0) { cur_second = get_next_second(last_second_); } - } - else - { + } else { sequence_ = 0; } @@ -229,8 +218,7 @@ class uid_generator int64_t get_next_second(int64_t last_ts) { int64_t ts = get_current_second(); - while (ts <= last_ts) - { + while (ts <= last_ts) { ts = get_current_second(); } @@ -244,8 +232,7 @@ class uid_generator std::unique_ptr bits_alloc_{nullptr}; }; -class uid_generator_thread_safe : public uid_generator -{ +class uid_generator_thread_safe : public uid_generator { public: int64_t get_uid(const int64_t worker_id) override { std::lock_guard lock(mutex_); diff --git a/src/plugins/bus/bus_configuration.hpp b/src/plugins/bus/bus_configuration.hpp index 5293aef5e..29b1c5555 100644 --- a/src/plugins/bus/bus_configuration.hpp +++ b/src/plugins/bus/bus_configuration.hpp @@ -18,8 +18,7 @@ namespace ark::bus_config_detail { inline std::string string( const toml::table& table, const std::string& path, std::string_view key, bool allow_empty = false) { const auto value = table[key].value(); - if (!value || (!allow_empty && value->empty()) || value->find('\0') != std::string::npos) - { + if (!value || (!allow_empty && value->empty()) || value->find('\0') != std::string::npos) { plugin_config_detail::fail(path, key, allow_empty ? "expected a string without NUL bytes" : "expected a nonempty string without NUL bytes"); } @@ -28,8 +27,7 @@ inline std::string string( inline const toml::array& array(const toml::table& table, const std::string& path, std::string_view key) { const auto* value = table[key].as_array(); - if (!value || (!value->empty() && !value->is_array_of_tables())) - { + if (!value || (!value->empty() && !value->is_array_of_tables())) { plugin_config_detail::fail(path, key, "expected an array of tables"); } return *value; @@ -38,15 +36,13 @@ inline const toml::array& array(const toml::table& table, const std::string& pat inline bus_id_t bus_id(const std::string& value, const std::string& path) { std::uint32_t id = 0; std::size_t begin = 0; - for (unsigned component = 0; component < 4; ++component) - { + for (unsigned component = 0; component < 4; ++component) { const auto end = value.find('.', begin); const auto limit = end == std::string::npos ? value.size() : end; unsigned number = 0; const auto result = std::from_chars(value.data() + begin, value.data() + limit, number); if (result.ec != std::errc{} || result.ptr != value.data() + limit || number > 255 || - (component < 3) != (end != std::string::npos)) - { + (component < 3) != (end != std::string::npos)) { plugin_config_detail::fail(path, "bus_id", "expected four decimal components in 0..255"); } id = (id << 8) | number; @@ -62,32 +58,27 @@ inline endpoint parse_endpoint(const std::string& value, const std::string& path ep.set_ip(""); ep.set_port(0); ep.set_path(""); - if (value.empty()) - { + if (value.empty()) { return ep; // An empty endpoint keeps the corresponding listener disabled. } static const std::regex pattern(R"(([^:/]+)://(\[[^\]]+\]|[^:/[:space:]\[\]]+):([0-9]+)(/[^[:space:]]*)?)"); std::smatch match; - if (!std::regex_match(value, match, pattern)) - { + if (!std::regex_match(value, match, pattern)) { plugin_config_detail::fail(path, key, "expected protocol://host:port or an empty string"); } unsigned port = 0; const auto port_text = match[3].str(); const auto result = std::from_chars(port_text.data(), port_text.data() + port_text.size(), port); const auto protocol = endpoint::socket::str2proto(match[1].str()); - if (result.ec != std::errc{} || port > 65535 || protocol == proto_type::unknown) - { + if (result.ec != std::errc{} || port > 65535 || protocol == proto_type::unknown) { plugin_config_detail::fail(path, key, "unsupported protocol or port outside 0..65535"); } auto host = match[2].str(); - if (host.front() == '[') - { + if (host.front() == '[') { host = host.substr(1, host.size() - 2); asio::error_code error; static_cast(asio::ip::make_address_v6(host, error)); - if (error) - { + if (error) { plugin_config_detail::fail(path, key, "expected a valid bracketed IPv6 literal"); } } @@ -110,44 +101,37 @@ inline app_config load(const std::string& path, bus_id_t self_bus_id) { config.self_proc.server_ep = parse_endpoint("", path, "server_endpoint"); config.self_proc.intranet_ep = parse_endpoint("", path, "intranet_endpoint"); std::size_t index = 0; - for (const auto& node : array(table, path, "applications")) - { + for (const auto& node : array(table, path, "applications")) { const auto location = path + ": bus.applications[" + std::to_string(index++) + "]"; const auto& app = *node.as_table(); check_keys(app, location, "application", {"name", "type"}); const auto name = string(app, location, "name"); const auto type = static_cast(integer(app, location, "type", 1, 254)); - if (!config.name2types.insert({name, type}).second) - { + if (!config.name2types.insert({name, type}).second) { fail(location, "name", "duplicate application name: " + name); } - if (!config.type2names.insert({type, name}).second) - { + if (!config.type2names.insert({type, name}).second) { fail(location, "type", "duplicate application type"); } } index = 0; - for (const auto& node : array(table, path, "relations")) - { + for (const auto& node : array(table, path, "relations")) { const auto location = path + ": bus.relations[" + std::to_string(index++) + "]"; const auto& relation = *node.as_table(); check_keys(relation, location, "relation", {"source", "target"}); const auto source = config.name2types.find(string(relation, location, "source")); const auto target = config.name2types.find(string(relation, location, "target")); - if (source == config.name2types.end() || target == config.name2types.end()) - { + if (source == config.name2types.end() || target == config.name2types.end()) { fail(location, "source/target", "expected configured application names"); } auto& targets = config.connection_relations[source->second]; - if (std::find(targets.begin(), targets.end(), target->second) != targets.end()) - { + if (std::find(targets.begin(), targets.end(), target->second) != targets.end()) { fail(location, "source/target", "duplicate directed relation"); } targets.push_back(target->second); } const auto* registry = table["registry"].as_table(); - if (!registry) - { + if (!registry) { fail(path, "bus.registry", "required table is missing"); } const auto registry_path = path + ": bus.registry"; @@ -160,16 +144,14 @@ inline app_config load(const std::string& path, bus_id_t self_bus_id) { config.reg_center.check_timeout = string(*registry, registry_path, "check_timeout"); index = 0; std::set process_ids; - for (const auto& node : array(table, path, "processes")) - { + for (const auto& node : array(table, path, "processes")) { const auto location = path + ": bus.processes[" + std::to_string(index++) + "]"; const auto& process = *node.as_table(); check_keys(process, location, "process", {"bus_id", "server_endpoint", "intranet_endpoint", "max_connections", "threads"}); proc_config proc; proc.bus_id = bus_id(string(process, location, "bus_id"), location); - if (!process_ids.insert(proc.bus_id).second) - { + if (!process_ids.insert(proc.bus_id).second) { fail(location, "bus_id", "duplicate process Bus ID"); } proc.max_connection = @@ -179,15 +161,12 @@ inline app_config load(const std::string& path, bus_id_t self_bus_id) { parse_endpoint(string(process, location, "server_endpoint", true), location, "server_endpoint"); proc.intranet_ep = parse_endpoint(string(process, location, "intranet_endpoint", true), location, "intranet_endpoint"); - if (proc.bus_id == self_bus_id) - { + if (proc.bus_id == self_bus_id) { #ifdef ARK_DOCKER_ALPINE proc.intranet_ep.set_ip(getenv("MY_POD_IP")); #endif config.self_proc = proc; - } - else - { + } else { config.other_proc_list.insert({proc.bus_id, proc}); } } diff --git a/src/plugins/bus/bus_module.hpp b/src/plugins/bus/bus_module.hpp index 9aadf9716..e48d11d64 100755 --- a/src/plugins/bus/bus_module.hpp +++ b/src/plugins/bus/bus_module.hpp @@ -27,8 +27,7 @@ namespace ark { -class bus_module : public module -{ +class bus_module : public module { public: // get the app whole name, like app-bus_id virtual const std::string get_app_whole_name(bus_id_t bus_id) = 0; diff --git a/src/plugins/bus/bus_module_impl.cpp b/src/plugins/bus/bus_module_impl.cpp index 972dfe4d1..7e73faf90 100644 --- a/src/plugins/bus/bus_module_impl.cpp +++ b/src/plugins/bus/bus_module_impl.cpp @@ -28,8 +28,7 @@ namespace ark { -class bus_module_impl final : public module_base -{ +class bus_module_impl final : public module_base { public: bool init() override; @@ -133,8 +132,7 @@ int bus_module_impl::combine_bus_id(const app_type app_type, const uint8_t inst_ bool bus_module_impl::get_target_bus_relations(std::vector& target_list) { bus_addr bus_addr(get_self_bus_id()); auto iter = app_config_.connection_relations.find(static_cast(bus_addr.app_type)); - if (iter != app_config_.connection_relations.end()) - { + if (iter != app_config_.connection_relations.end()) { target_list = iter->second; } @@ -143,8 +141,7 @@ bool bus_module_impl::get_target_bus_relations(std::vector& target_lis bool bus_module_impl::get_other_proc(bus_id_t bus_id, proc_config& proc) const { auto iter = app_config_.other_proc_list.find(bus_id); - if (iter == app_config_.other_proc_list.end()) - { + if (iter == app_config_.other_proc_list.end()) { return false; } @@ -153,12 +150,10 @@ bool bus_module_impl::get_other_proc(bus_id_t bus_id, proc_config& proc) const { } int bus_module_impl::get_other_proc(const app_type app_type, std::vector& proc_list) const { - for (auto& iter : app_config_.other_proc_list) - { + for (auto& iter : app_config_.other_proc_list) { auto& proc = iter.second; bus_addr bus_id(proc.bus_id); - if (static_cast(bus_id.app_type) != app_type) - { + if (static_cast(bus_id.app_type) != app_type) { continue; } diff --git a/src/plugins/bus/bus_plugin.cpp b/src/plugins/bus/bus_plugin.cpp index bcbf17bed..99a8e96df 100644 --- a/src/plugins/bus/bus_plugin.cpp +++ b/src/plugins/bus/bus_plugin.cpp @@ -35,23 +35,19 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void bus_plugin::install() { - if (!register_module(detail::make_bus_module(), module_update::disabled)) - { + if (!register_module(detail::make_bus_module(), module_update::disabled)) { throw std::runtime_error("bus module registration rejected"); } - if (!register_module(detail::make_msg_module(), module_update::disabled)) - { + if (!register_module(detail::make_msg_module(), module_update::disabled)) { throw std::runtime_error("bus message module registration rejected"); } } void bus_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("bus message module unregistration rejected"); } - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("bus module unregistration rejected"); } } diff --git a/src/plugins/bus/bus_plugin.hpp b/src/plugins/bus/bus_plugin.hpp index 1c3fdf9b0..3fc777087 100755 --- a/src/plugins/bus/bus_plugin.hpp +++ b/src/plugins/bus/bus_plugin.hpp @@ -29,8 +29,7 @@ namespace ark { class msg_module; -class bus_plugin final : public plugin_base -{ +class bus_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/plugins/bus/msg_module.hpp b/src/plugins/bus/msg_module.hpp index 721192ca2..94e0df046 100644 --- a/src/plugins/bus/msg_module.hpp +++ b/src/plugins/bus/msg_module.hpp @@ -31,8 +31,7 @@ namespace ark { -class msg_module : public module -{ +class msg_module : public module { public: virtual bool send_def_cs_msg_by_app_type( const app_type app_type, const msg_id_t msg_id, const google::protobuf::Message& msg) = 0; @@ -56,8 +55,7 @@ class msg_module : public module } static bool decode_protobuf(const net_msg* msg, google::protobuf::Message& protobuf_msg, guid_t& actor_id) { - if (!protobuf_msg.ParseFromString(std::string(msg->get_msg_data(), msg->get_msg_length()))) - { + if (!protobuf_msg.ParseFromString(std::string(msg->get_msg_data(), msg->get_msg_length()))) { return false; } diff --git a/src/plugins/bus/msg_module_impl.cpp b/src/plugins/bus/msg_module_impl.cpp index fbf6f14e9..01b25aa14 100644 --- a/src/plugins/bus/msg_module_impl.cpp +++ b/src/plugins/bus/msg_module_impl.cpp @@ -28,8 +28,7 @@ namespace ark { -class msg_module_impl final : public module_base -{ +class msg_module_impl final : public module_base { public: bool init() override; @@ -84,8 +83,7 @@ bool msg_module_impl::send_msg_by_app_type( const app_type app_type, msg_header* header, const google::protobuf::Message& msg) { /// firstly find net client service auto client_service_ptr = net_service_manager_module_->get_client_service(app_type); - if (client_service_ptr == nullptr) - { + if (client_service_ptr == nullptr) { ARK_LOG_ERROR("net client service not be found, src_bus={} app_type={} msg_id={} actor_id={}", bus_module_->get_self_bus_id(), (uint8_t)app_type, header->message_id(), header->actor_id()); return false; @@ -95,8 +93,7 @@ bool msg_module_impl::send_msg_by_app_type( auto busid = bus_module_->get_self_bus_id(); auto connection_info_ptr = client_service_ptr->get_suitable_connect(misc::to_string(busid)); - if (connection_info_ptr == nullptr) - { + if (connection_info_ptr == nullptr) { ARK_LOG_ERROR("connection info not be found, src_bus={} app_type={} msg_id={} actor_id={}", busid, (uint8_t)app_type, header->message_id(), header->actor_id()); return false; @@ -123,8 +120,7 @@ bool msg_module_impl::send_msg_by_bus_id( bool msg_module_impl::send_to_client( conv_id_t session_id, msg_id_t msg_id, const google::protobuf::Message& msg, const guid_t& guid) { std::string msg_data; - if (!msg.SerializeToString(&msg_data)) - { + if (!msg.SerializeToString(&msg_data)) { ARK_LOG_ERROR("msg serializing failed, src_bus={} target_bus={} msg_id={} actor_id={}", msg_id, guid); return false; } @@ -135,8 +131,7 @@ bool msg_module_impl::send_to_client( bool msg_module_impl::send_to_client(conv_id_t session_id, msg_id_t msg_id, const std::string& msg_data, bool compressed /* = false*/, const guid_t& guid) { auto net_service_ptr = net_service_manager_module_->get_inter_net_server(); - if (net_service_ptr == nullptr) - { + if (net_service_ptr == nullptr) { ARK_LOG_ERROR("net service is null, src_bus={} session id ={} msg_id={} actor_id={}", bus_module_->get_self_bus_id(), session_id, msg_id, guid); return false; @@ -152,8 +147,7 @@ bool msg_module_impl::send_to_client(conv_id_t session_id, msg_id_t msg_id, cons bool msg_module_impl::send_to_intra( conv_id_t session_id, msg_id_t msg_id, const google::protobuf::Message& msg, const guid_t& guid) { auto net_service_ptr = net_service_manager_module_->get_intra_net_server(); - if (net_service_ptr == nullptr) - { + if (net_service_ptr == nullptr) { ARK_LOG_ERROR("net service is null, src_bus={} session id ={} msg_id={} actor_id={}", bus_module_->get_self_bus_id(), session_id, msg_id, guid); return false; @@ -171,8 +165,7 @@ bool msg_module_impl::send_to_intra( bool msg_module_impl::send_msg(std::shared_ptr& net_ptr, msg_header* header, const google::protobuf::Message& msg, const conv_id_t session_id) { std::string msg_data; - if (!msg.SerializeToString(&msg_data)) - { + if (!msg.SerializeToString(&msg_data)) { ARK_LOG_ERROR("msg serializing failed, src_bus={} target_bus={} msg_id={} actor_id={}", header->source_bus_id(), header->dest_bus_id(), header->message_id(), header->actor_id()); return false; @@ -183,16 +176,14 @@ bool msg_module_impl::send_msg(std::shared_ptr& net_ptr, msg_header* header bool msg_module_impl::send_msg( std::shared_ptr& net_ptr, msg_header* header, const std::string& msg_data, const conv_id_t session_id) { - if (net_ptr == nullptr) - { + if (net_ptr == nullptr) { ARK_LOG_ERROR("net is invalid, src_bus={} target_bus={} msg_id={} actor_id={}", header->source_bus_id(), header->dest_bus_id(), header->message_id(), header->actor_id()); return false; } auto conv_id = session_id; - if (conv_id == 0) - { + if (conv_id == 0) { conv_id = net_service_manager_module_->get_session_id(header->dest_bus_id()); } diff --git a/src/plugins/consul/consul_module.hpp b/src/plugins/consul/consul_module.hpp index 6ea3b17f4..ca643831c 100644 --- a/src/plugins/consul/consul_module.hpp +++ b/src/plugins/consul/consul_module.hpp @@ -9,8 +9,7 @@ namespace ark { -class consul_module : public module -{ +class consul_module : public module { public: // Set register center url(You should call this function first) // virtual void SetRegisterCenter(const std::string& center_ip, const uint16_t center_port) = 0; diff --git a/src/plugins/consul/consul_module_impl.cpp b/src/plugins/consul/consul_module_impl.cpp index 65f8f07fb..4c2c0efb2 100644 --- a/src/plugins/consul/consul_module_impl.cpp +++ b/src/plugins/consul/consul_module_impl.cpp @@ -46,8 +46,7 @@ bool consul_module_impl::load_config() { std::future> consul_module_impl::register_service(const consul::service_data& service) { std::string body; - if (!google::protobuf::util::MessageToJsonString(service, &body).ok()) - { + if (!google::protobuf::util::MessageToJsonString(service, &body).ok()) { return failed_request(); } const std::string content_type = "application/json"; @@ -56,8 +55,7 @@ std::future> consul_module_impl::register_service(c } std::future> consul_module_impl::deregister_service(const std::string& service_id) { - if (service_id.empty()) - { + if (service_id.empty()) { return failed_request(); } @@ -66,8 +64,7 @@ std::future> consul_module_impl::deregister_service } std::future> consul_module_impl::get_key_value(const std::string& key) { - if (key.empty()) - { + if (key.empty()) { return failed_request(); } @@ -77,8 +74,7 @@ std::future> consul_module_impl::get_key_value(cons std::future> consul_module_impl::set_key_value( const std::string& key, const std::string& value) { - if (key.empty()) - { + if (key.empty()) { return failed_request(); } @@ -87,8 +83,7 @@ std::future> consul_module_impl::set_key_value( } std::future> consul_module_impl::del_key_value(const std::string& key) { - if (key.empty()) - { + if (key.empty()) { return failed_request(); } @@ -98,8 +93,7 @@ std::future> consul_module_impl::del_key_value(cons std::future> consul_module_impl::get_health_services( const std::string& service_name, const std::string& tag_filter) { - if (service_name.empty()) - { + if (service_name.empty()) { return failed_request(); } diff --git a/src/plugins/consul/consul_module_impl.hpp b/src/plugins/consul/consul_module_impl.hpp index be2adec8c..af0584165 100644 --- a/src/plugins/consul/consul_module_impl.hpp +++ b/src/plugins/consul/consul_module_impl.hpp @@ -6,8 +6,7 @@ namespace ark { -class consul_module_impl final : public module_base -{ +class consul_module_impl final : public module_base { public: bool init() override; diff --git a/src/plugins/consul/consul_plugin.cpp b/src/plugins/consul/consul_plugin.cpp index c6feb77ce..f69f1591e 100644 --- a/src/plugins/consul/consul_plugin.cpp +++ b/src/plugins/consul/consul_plugin.cpp @@ -15,15 +15,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void consul_plugin::install() { - if (!register_module(detail::make_consul_module(), module_update::disabled)) - { + if (!register_module(detail::make_consul_module(), module_update::disabled)) { throw std::runtime_error("Consul module registration rejected"); } } void consul_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("Consul module unregistration rejected"); } } diff --git a/src/plugins/consul/consul_plugin.hpp b/src/plugins/consul/consul_plugin.hpp index 2aadec022..d6dc37b3e 100755 --- a/src/plugins/consul/consul_plugin.hpp +++ b/src/plugins/consul/consul_plugin.hpp @@ -4,8 +4,7 @@ namespace ark { -class consul_plugin final : public plugin_base -{ +class consul_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/plugins/detail/database_awaitable.hpp b/src/plugins/detail/database_awaitable.hpp index 83f84ea98..04a5dca17 100644 --- a/src/plugins/detail/database_awaitable.hpp +++ b/src/plugins/detail/database_awaitable.hpp @@ -40,13 +40,11 @@ inline bool is_database_executor(const asio::any_io_executor& candidate, arknet: // must outlive accepted operations. Destroy only on the owner after pending()==0. // stop_accepting() prevents new starts, but never suppresses accepted terminals. template -class database_awaitable -{ +class database_awaitable { static_assert(std::is_nothrow_move_constructible_v); static_assert(std::is_nothrow_default_constructible_v); - struct operation - { + struct operation { std::size_t index{}; std::uint64_t native_id{}; bool published{}; @@ -64,8 +62,7 @@ class database_awaitable }; template - struct typed_operation final : operation - { + struct typed_operation final : operation { std::optional handler; cancel_type cancel_native; asio::cancellation_slot slot; @@ -90,8 +87,7 @@ class database_awaitable } }; - struct state : std::enable_shared_from_this - { + struct state : std::enable_shared_from_this { std::shared_ptr runtime; const std::thread::id owner = std::this_thread::get_id(); mutable std::mutex mutex; @@ -106,15 +102,13 @@ class database_awaitable state(std::shared_ptr execution, std::size_t maximum) : runtime(std::move(execution)) , slots(maximum) { - if (!runtime || !maximum) - { + if (!runtime || !maximum) { throw std::invalid_argument("Database awaitable requires a runtime and positive operation limit"); } } void check_owner() const { - if (std::this_thread::get_id() != owner) - { + if (std::this_thread::get_id() != owner) { throw std::logic_error("Database awaitable requires its constructing thread"); } } @@ -122,14 +116,11 @@ class database_awaitable void admit(const std::shared_ptr& pending) { check_owner(); std::lock_guard lock(mutex); - if (!accepting) - { + if (!accepting) { throw std::logic_error("Database awaitable is not accepting operations"); } - for (std::size_t index = 0; index < slots.size(); ++index) - { - if (!slots[index]) - { + for (std::size_t index = 0; index < slots.size(); ++index) { + if (!slots[index]) { pending->index = index; slots[index] = pending; ++count; @@ -142,12 +133,10 @@ class database_awaitable void check_admission() const { check_owner(); std::lock_guard lock(mutex); - if (!accepting) - { + if (!accepting) { throw std::logic_error("Database awaitable is not accepting operations"); } - if (count == slots.size()) - { + if (count == slots.size()) { throw std::length_error("Database awaitable operation limit reached"); } } @@ -156,19 +145,15 @@ class database_awaitable // allocated before start; completion itself allocates no delivery node. void complete(const std::shared_ptr& pending, std::exception_ptr error, result_type result) { std::lock_guard lock(mutex); - if (pending->retired || pending->ready) - { + if (pending->retired || pending->ready) { return; } pending->exception = std::move(error); pending->response.emplace(std::move(result)); pending->ready = true; - if (tail) - { + if (tail) { tail->next = pending; - } - else - { + } else { head = pending; } tail = pending; @@ -179,19 +164,16 @@ class database_awaitable std::uint64_t id{}; { std::lock_guard lock(mutex); - if (pending->retired || pending->ready) - { + if (pending->retired || pending->ready) { return; } pending->cancel_requested = true; - if (pending->published && pending->native_id && !pending->cancel_forwarded) - { + if (pending->published && pending->native_id && !pending->cancel_forwarded) { id = pending->native_id; pending->cancel_forwarded = true; } } - if (id) - { + if (id) { // Native cancellation is a request, not a synthetic terminal. // Keep the record until the native service returns its result. forward_cancel(pending, id); @@ -199,15 +181,13 @@ class database_awaitable } void forward_cancel(const std::shared_ptr& pending, std::uint64_t id) noexcept { - try - { pending->cancel(id); } - catch (...) - { + try { + pending->cancel(id); + } catch (...) { // The request is already accepted. A failed cancellation // submission is a separate diagnostic, never its terminal. // This state is read/written only by the owner thread. - if (!cancel_exception) - { + if (!cancel_exception) { cancel_exception = std::current_exception(); } } @@ -221,13 +201,11 @@ class database_awaitable pending->native_id = id; pending->published = true; cancel = pending->cancel_requested && !pending->ready && !pending->retired && id; - if (cancel) - { + if (cancel) { pending->cancel_forwarded = true; } } - if (cancel) - { + if (cancel) { forward_cancel(pending, id); } } @@ -235,8 +213,7 @@ class database_awaitable void drain(std::size_t maximum) { check_owner(); - struct scheduled_guard - { + struct scheduled_guard { state& shared; ~scheduled_guard() { @@ -245,19 +222,16 @@ class database_awaitable } } guard{*this}; - for (std::size_t completed = 0; completed < maximum; ++completed) - { + for (std::size_t completed = 0; completed < maximum; ++completed) { std::shared_ptr pending; { std::lock_guard lock(mutex); - if (!head) - { + if (!head) { break; } pending = std::move(head); head = std::move(pending->next); - if (!head) - { + if (!head) { tail.reset(); } pending->retired = true; @@ -276,18 +250,14 @@ class database_awaitable check_owner(); { std::lock_guard lock(mutex); - if (scheduled || !head || !maximum) - { + if (scheduled || !head || !maximum) { return false; } scheduled = true; } - try - { + try { post(runtime->get_executor(), [shared = this->shared_from_this(), maximum] { shared->drain(maximum); }); - } - catch (...) - { + } catch (...) { std::lock_guard lock(mutex); scheduled = false; throw; @@ -305,8 +275,7 @@ class database_awaitable database_awaitable& operator=(const database_awaitable&) = delete; ~database_awaitable() { - if (state_->owner != std::this_thread::get_id() || pending()) - { + if (state_->owner != std::this_thread::get_id() || pending()) { std::terminate(); } } @@ -361,8 +330,7 @@ class database_awaitable template static module_task await_result(std::shared_ptr shared, start_type start, cancel_type cancel) { const auto executor = co_await asio::this_coro::executor; - if (!is_database_executor(executor, *shared->runtime)) - { + if (!is_database_executor(executor, *shared->runtime)) { throw std::logic_error("Database awaitable must run on its manual runtime executor"); } // Reject before use_awaitable transfers ownership of the Asio coroutine @@ -374,38 +342,30 @@ class database_awaitable static_assert(std::is_nothrow_move_constructible_v); std::shared_ptr> pending; std::uint64_t id{}; - try - { + try { // Allocation precedes the noexcept moves of handler/cancel. // If it fails, handler still owns the Asio coroutine thread. pending = std::make_shared>(std::move(handler), std::move(cancel)); - } - catch (...) - { + } catch (...) { // No native operation or delivery record was accepted. We are // already on the required manual executor; propagate through // Asio rather than dropping its detached coroutine thread. handler(std::current_exception(), result_type{}); return; } - try - { shared->admit(pending); } - catch (...) - { + try { + shared->admit(pending); + } catch (...) { pending->deliver(std::current_exception(), result_type{}); return; } - try - { - if (pending->slot.is_connected()) - { + try { + if (pending->slot.is_connected()) { pending->slot.assign( [shared, weak = std::weak_ptr(pending)](asio::cancellation_type type) { - if (type != asio::cancellation_type::none) - { - if (auto operation = weak.lock()) - { + if (type != asio::cancellation_type::none) { + if (auto operation = weak.lock()) { shared->request_cancel(operation); } } @@ -414,9 +374,7 @@ class database_awaitable id = start([shared, pending](std::exception_ptr error, result_type result) { shared->complete(pending, std::move(error), std::move(result)); }); - } - catch (...) - { + } catch (...) { shared->complete(pending, std::current_exception(), result_type{}); return; } diff --git a/src/plugins/detail/database_completion_queue.hpp b/src/plugins/detail/database_completion_queue.hpp index 13395ad43..8574a4d30 100644 --- a/src/plugins/detail/database_completion_queue.hpp +++ b/src/plugins/detail/database_completion_queue.hpp @@ -17,15 +17,13 @@ namespace ark::detail { // Private completion storage reserved before an operation is submitted. // Public methods except complete() belong to the constructing/module thread. template -class completion_queue -{ +class completion_queue { static_assert(std::is_nothrow_move_constructible_v); public: using callback = std::function; - struct record - { + struct record { std::size_t index{}; std::size_t input_bytes{}; callback completion; @@ -40,8 +38,7 @@ class completion_queue : owner_(std::this_thread::get_id()) , slots_(max_operations) , max_input_bytes_(max_input_bytes) { - if (!max_operations || !max_input_bytes) - { + if (!max_operations || !max_input_bytes) { throw std::invalid_argument("Database completion limits must be positive"); } } @@ -52,14 +49,11 @@ class completion_queue operation->input_bytes = input_bytes; operation->completion = std::move(handler); std::lock_guard lock(mutex_); - if (!accepting_ || input_bytes > max_input_bytes_ - retained_input_bytes_) - { + if (!accepting_ || input_bytes > max_input_bytes_ - retained_input_bytes_) { return {}; } - for (std::size_t index = 0; index < slots_.size(); ++index) - { - if (!slots_[index]) - { + for (std::size_t index = 0; index < slots_.size(); ++index) { + if (!slots_[index]) { operation->index = index; slots_[index] = operation; retained_input_bytes_ += input_bytes; @@ -72,18 +66,14 @@ class completion_queue // The response is moved into pre-reserved storage; no queue-node allocation. void complete(const ticket& operation, result_type response) { std::lock_guard lock(mutex_); - if (!dispatch_enabled_ || !contains(operation) || operation->ready) - { + if (!dispatch_enabled_ || !contains(operation) || operation->ready) { return; } operation->response.emplace(std::move(response)); operation->ready = true; - if (tail_) - { + if (tail_) { tail_->next = operation; - } - else - { + } else { head_ = operation; } tail_ = operation; @@ -94,8 +84,7 @@ class completion_queue check_owner(); { std::lock_guard lock(mutex_); - if (contains(operation)) - { + if (contains(operation)) { retained_input_bytes_ -= operation->input_bytes; slots_[operation->index].reset(); } @@ -106,8 +95,7 @@ class completion_queue std::size_t dispatch(std::size_t maximum = 64) { check_owner(); - struct dispatch_guard - { + struct dispatch_guard { std::size_t& depth; explicit dispatch_guard(std::size_t& active) noexcept @@ -121,32 +109,25 @@ class completion_queue } guard(dispatch_depth_); std::size_t dispatched{}; - while (dispatched < maximum) - { + while (dispatched < maximum) { ticket operation; { std::lock_guard lock(mutex_); - if (!dispatch_enabled_ || !head_) - { + if (!dispatch_enabled_ || !head_) { break; } operation = std::move(head_); head_ = std::move(operation->next); - if (!head_) - { + if (!head_) { tail_.reset(); } } auto handler = std::move(operation->completion); - try - { - if (handler) - { + try { + if (handler) { handler(std::move(*operation->response)); } - } - catch (...) - { + } catch (...) { handler = {}; operation->response.reset(); finish(operation); @@ -165,10 +146,8 @@ class completion_queue bool quiescent() const { check_owner(); std::lock_guard lock(mutex_); - for (const auto& operation : slots_) - { - if (operation) - { + for (const auto& operation : slots_) { + if (operation) { return false; } } @@ -195,10 +174,8 @@ class completion_queue tail_.reset(); retained_input_bytes_ = 0; } - for (auto& operation : retired) - { - if (operation) - { + for (auto& operation : retired) { + if (operation) { operation->completion = {}; operation->next.reset(); } @@ -207,8 +184,7 @@ class completion_queue private: void check_owner() const { - if (std::this_thread::get_id() != owner_) - { + if (std::this_thread::get_id() != owner_) { throw std::logic_error("Database service must be used on its module thread"); } } @@ -219,8 +195,7 @@ class completion_queue void finish(const ticket& operation) { std::lock_guard lock(mutex_); - if (contains(operation)) - { + if (contains(operation)) { retained_input_bytes_ -= operation->input_bytes; slots_[operation->index].reset(); } diff --git a/src/plugins/detail/database_request_control.hpp b/src/plugins/detail/database_request_control.hpp index 36bd35601..cac685b44 100644 --- a/src/plugins/detail/database_request_control.hpp +++ b/src/plugins/detail/database_request_control.hpp @@ -10,47 +10,40 @@ namespace ark::detail { // At most two retained diagnostics per private service. Neither overrides an // execution result nor claims that native resource cleanup has completed. -struct database_service_diagnostics -{ +struct database_service_diagnostics { std::exception_ptr cancellation_submission; std::exception_ptr lease_return; }; // Native completion is allowed to run inline, before its request ID is returned. // Only state is protected here: callers invoke native methods after unlocking. -class database_request_control -{ +class database_request_control { public: - enum class stage - { + enum class stage { idle, acquire, command, finished }; - struct submission - { + struct submission { std::uint64_t epoch{}; stage target{stage::idle}; }; - struct cancellation - { + struct cancellation { stage target; std::uint64_t id; }; - struct cancel_result - { + struct cancel_result { bool active{}; std::optional native; }; submission begin(stage target) { std::lock_guard lock(mutex_); - if (target_ == stage::finished) - { + if (target_ == stage::finished) { return {epoch_, target_}; } target_ = target; @@ -60,8 +53,7 @@ class database_request_control std::optional publish(submission operation, std::uint64_t id) { std::lock_guard lock(mutex_); - if (!matches(operation)) - { + if (!matches(operation)) { return {}; } id_ = id; @@ -70,8 +62,7 @@ class database_request_control bool complete(submission operation) { std::lock_guard lock(mutex_); - if (!matches(operation)) - { + if (!matches(operation)) { return false; } target_ = stage::idle; @@ -82,8 +73,7 @@ class database_request_control cancel_result cancel() { std::lock_guard lock(mutex_); - if (target_ == stage::finished) - { + if (target_ == stage::finished) { return {}; } cancelled_ = true; @@ -97,8 +87,7 @@ class database_request_control bool finish() { std::lock_guard lock(mutex_); - if (target_ == stage::finished) - { + if (target_ == stage::finished) { return false; } target_ = stage::finished; @@ -113,8 +102,7 @@ class database_request_control } std::optional cancellation_locked() const { - if (cancelled_ && id_ && (target_ == stage::acquire || target_ == stage::command)) - { + if (cancelled_ && id_ && (target_ == stage::acquire || target_ == stage::command)) { return cancellation{target_, id_}; } return {}; diff --git a/src/plugins/detail/database_service_activity.hpp b/src/plugins/detail/database_service_activity.hpp index 87bd1d433..3370617e0 100644 --- a/src/plugins/detail/database_service_activity.hpp +++ b/src/plugins/detail/database_service_activity.hpp @@ -8,13 +8,11 @@ namespace ark::detail { // Owner-thread activity outlives a facade that its own callback may destroy. -struct database_service_activity -{ +struct database_service_activity { std::size_t depth{}; bool native_retired{}; - class guard - { + class guard { public: explicit guard(std::shared_ptr state) noexcept : state_(std::move(state)) { diff --git a/src/plugins/detail/plugin_configuration.hpp b/src/plugins/detail/plugin_configuration.hpp index 112a4f8a4..4d18329b3 100644 --- a/src/plugins/detail/plugin_configuration.hpp +++ b/src/plugins/detail/plugin_configuration.hpp @@ -19,10 +19,8 @@ namespace ark::plugin_config_detail { inline void check_keys(const toml::table& table, const std::string& path, std::string_view section, std::initializer_list allowed) { - for (const auto& [key, value] : table) - { - if (std::ranges::find(allowed, key.str()) == allowed.end()) - { + for (const auto& [key, value] : table) { + if (std::ranges::find(allowed, key.str()) == allowed.end()) { fail(path, std::string(section) + "." + std::string(key.str()), "unknown setting"); } } @@ -31,8 +29,7 @@ inline void check_keys(const toml::table& table, const std::string& path, std::s inline toml::table read(const std::string& path, std::string_view section) { auto document = config_detail::read_toml(path); check_keys(document, path, "root", {section}); - if (!document[section].is_table()) - { + if (!document[section].is_table()) { fail(path, section, "required table is missing"); } return document; @@ -40,8 +37,7 @@ inline toml::table read(const std::string& path, std::string_view section) { inline std::string host(const toml::table& table, const std::string& path) { const auto value = table["host"].value(); - if (!value || value->empty() || value->find('\0') != std::string::npos) - { + if (!value || value->empty() || value->find('\0') != std::string::npos) { fail(path, "host", "expected a nonempty string without NUL"); } return *value; @@ -50,15 +46,13 @@ inline std::string host(const toml::table& table, const std::string& path) { inline std::uint32_t integer(const toml::table& table, const std::string& path, std::string_view key, std::int64_t minimum, std::int64_t maximum) { const auto value = table[key].value(); - if (!value || !table[key].is_integer() || *value < minimum || *value > maximum) - { + if (!value || !table[key].is_integer() || *value < minimum || *value > maximum) { fail(path, key, "expected an integer from " + std::to_string(minimum) + " to " + std::to_string(maximum)); } return static_cast(*value); } -struct http_configuration -{ +struct http_configuration { std::string host; std::uint32_t port; std::uint32_t threads; @@ -71,8 +65,7 @@ inline http_configuration load_http(const std::string& path) { return {host(table, path), integer(table, path, "port", 0, 65535), integer(table, path, "threads", 1, 255)}; } -struct consul_configuration -{ +struct consul_configuration { std::string host; std::uint32_t port; }; diff --git a/src/plugins/etcd_client/etcd_client.hpp b/src/plugins/etcd_client/etcd_client.hpp index 32f6bf581..db0aab58f 100644 --- a/src/plugins/etcd_client/etcd_client.hpp +++ b/src/plugins/etcd_client/etcd_client.hpp @@ -5,8 +5,7 @@ namespace ark { -class etcd_client -{ +class etcd_client { public: virtual ~etcd_client() = default; diff --git a/src/plugins/etcd_client/etcd_client_impl.cpp b/src/plugins/etcd_client/etcd_client_impl.cpp index 94cbf5c42..8eb6b81e7 100644 --- a/src/plugins/etcd_client/etcd_client_impl.cpp +++ b/src/plugins/etcd_client/etcd_client_impl.cpp @@ -33,15 +33,11 @@ etcd_client_impl::etcd_client_impl( , connect_timeout_(connect_timeout) , io_timeout_(io_timeout) { std::vector host_svc; - for (const auto& ep : endpoints) - { + for (const auto& ep : endpoints) { string_utils::split(host_svc, ep, ':'); - if (host_svc.size() == 2) - { + if (host_svc.size() == 2) { endpoints_.emplace_back(std::make_pair(std::move(host_svc[0]), std::move(host_svc[1]))); - } - else - { + } else { ARK_LOG_WARN("Invalid endpoint: {}", ep); } host_svc.clear(); @@ -59,23 +55,18 @@ void etcd_client_impl::post(std::function)> cb const auto& ep = endpoints_[ep_idx]; http_client_->post( [this, cb = std::move(cb), &api, body, ep_idx, tried_cnt](std::pair rsp) mutable { - if (rsp.first) - { + if (rsp.first) { cb(std::move(rsp)); selected_endpoint_index_ = ep_idx; return; } - if (tried_cnt < endpoints_.size()) - { - if (++ep_idx >= endpoints_.size()) - { + if (tried_cnt < endpoints_.size()) { + if (++ep_idx >= endpoints_.size()) { ep_idx %= endpoints_.size(); } post(std::move(cb), api, std::move(body), ep_idx, tried_cnt + 1); - } - else - { + } else { cb(std::move(rsp)); } }, @@ -85,45 +76,31 @@ void etcd_client_impl::post(std::function)> cb void etcd_client_impl::grant(std::function)> cb, int ttl) { post( [cb = std::move(cb)](std::pair rsp) { - if (rsp.first) - { + if (rsp.first) { std::pair cb_rsp; auto j = nlohmann::json::parse(rsp.second); - if (auto it = j.find("ID"); it != j.end()) - { - if (it->is_string()) - { + if (auto it = j.find("ID"); it != j.end()) { + if (it->is_string()) { cb_rsp.first = std::stoll(it->get()); - } - else - { + } else { cb_rsp.first = -1; cb_rsp.second = "Unknown error"; } - } - else if (it = j.find("error"); it != j.end()) - { + } else if (it = j.find("error"); it != j.end()) { cb_rsp.first = -1; - if (it->is_string()) - { + if (it->is_string()) { cb_rsp.second = it->get(); - } - else - { + } else { cb_rsp.second = "Unknown error"; } - } - else - { + } else { cb_rsp.first = -1; cb_rsp.second = "Unknown error"; } cb(cb_rsp); - } - else - { + } else { cb(std::make_pair(static_cast(-1), rsp.second)); } }, diff --git a/src/plugins/etcd_client/etcd_client_impl.hpp b/src/plugins/etcd_client/etcd_client_impl.hpp index 57dc4abe6..4fc179a88 100644 --- a/src/plugins/etcd_client/etcd_client_impl.hpp +++ b/src/plugins/etcd_client/etcd_client_impl.hpp @@ -9,8 +9,7 @@ namespace ark { /** * AFCEtcdClient is NOT thread-safe, please create an AFCEtcdClient object per thread, or use a lock mechanism. */ -class etcd_client_impl final : public etcd_client -{ +class etcd_client_impl final : public etcd_client { public: /** * Constructor diff --git a/src/plugins/etcd_client/etcd_client_module.hpp b/src/plugins/etcd_client/etcd_client_module.hpp index 3a5ebb7f3..acd12af41 100644 --- a/src/plugins/etcd_client/etcd_client_module.hpp +++ b/src/plugins/etcd_client/etcd_client_module.hpp @@ -5,8 +5,7 @@ namespace ark { -class etcd_client_module : public module -{ +class etcd_client_module : public module { public: virtual std::shared_ptr create_etcd_client( std::vector endpoints, int io_timeout = 5, int connect_timeout = 2) = 0; diff --git a/src/plugins/etcd_client/etcd_client_module_impl.hpp b/src/plugins/etcd_client/etcd_client_module_impl.hpp index 8296b0aed..29128e0b8 100644 --- a/src/plugins/etcd_client/etcd_client_module_impl.hpp +++ b/src/plugins/etcd_client/etcd_client_module_impl.hpp @@ -6,8 +6,7 @@ namespace ark { -class etcd_client_module_impl final : public module_base -{ +class etcd_client_module_impl final : public module_base { public: bool init() override; diff --git a/src/plugins/etcd_client/etcd_client_plugin.cpp b/src/plugins/etcd_client/etcd_client_plugin.cpp index ac6ccaef3..3fbfb3d03 100644 --- a/src/plugins/etcd_client/etcd_client_plugin.cpp +++ b/src/plugins/etcd_client/etcd_client_plugin.cpp @@ -15,15 +15,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void etcd_client_plugin::install() { - if (!register_module(detail::make_etcd_client_module(), module_update::disabled)) - { + if (!register_module(detail::make_etcd_client_module(), module_update::disabled)) { throw std::runtime_error("Etcd Client module registration rejected"); } } void etcd_client_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("Etcd Client module unregistration rejected"); } } diff --git a/src/plugins/etcd_client/etcd_client_plugin.hpp b/src/plugins/etcd_client/etcd_client_plugin.hpp index 684317dbb..27ec1b10c 100755 --- a/src/plugins/etcd_client/etcd_client_plugin.hpp +++ b/src/plugins/etcd_client/etcd_client_plugin.hpp @@ -4,8 +4,7 @@ namespace ark { -class etcd_client_plugin final : public plugin_base -{ +class etcd_client_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/plugins/http/http_plugin.cpp b/src/plugins/http/http_plugin.cpp index 2b35c3a3f..401214680 100644 --- a/src/plugins/http/http_plugin.cpp +++ b/src/plugins/http/http_plugin.cpp @@ -34,15 +34,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void http_plugin::install() { - if (!register_module(detail::make_http_server_module(get_plugin_manager()), module_update::disabled)) - { + if (!register_module(detail::make_http_server_module(get_plugin_manager()), module_update::disabled)) { throw std::runtime_error("HTTP server module registration rejected"); } } void http_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("HTTP server module unregistration rejected"); } } diff --git a/src/plugins/http/http_plugin.hpp b/src/plugins/http/http_plugin.hpp index d61676615..3fb9353e2 100644 --- a/src/plugins/http/http_plugin.hpp +++ b/src/plugins/http/http_plugin.hpp @@ -27,8 +27,7 @@ namespace ark { -class http_plugin final : public plugin_base -{ +class http_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/plugins/http/http_server_module.hpp b/src/plugins/http/http_server_module.hpp index a5c9dbb98..97f703e4e 100644 --- a/src/plugins/http/http_server_module.hpp +++ b/src/plugins/http/http_server_module.hpp @@ -31,8 +31,7 @@ namespace ark { -class http_server_module : public module -{ +class http_server_module : public module { public: virtual arknet::http_router& get_router() = 0; virtual bool start_server() = 0; diff --git a/src/plugins/http/http_server_module_impl.cpp b/src/plugins/http/http_server_module_impl.cpp index 30791de56..1114121f7 100644 --- a/src/plugins/http/http_server_module_impl.cpp +++ b/src/plugins/http/http_server_module_impl.cpp @@ -35,8 +35,7 @@ namespace ark { -class http_server_module_impl final : public module_base -{ +class http_server_module_impl final : public module_base { friend struct http_server_startup_test_access; public: @@ -81,8 +80,7 @@ bool reserve_endpoint(const std::string& key) { } void release_endpoint(std::string& key) { - if (key.empty()) - { + if (key.empty()) { return; } std::lock_guard lock(http_endpoint_mutex); @@ -90,8 +88,7 @@ void release_endpoint(std::string& key) { key.clear(); } -class endpoint_reservation final -{ +class endpoint_reservation final { public: explicit endpoint_reservation(std::string key) : key_(std::move(key)) @@ -99,8 +96,7 @@ class endpoint_reservation final } ~endpoint_reservation() { - if (reserved_) - { + if (reserved_) { release_endpoint(key_); } } @@ -124,23 +120,19 @@ class endpoint_reservation final } // namespace -struct http_server_module_impl::callback_state -{ - struct request_lease - { +struct http_server_module_impl::callback_state { + struct request_lease { explicit request_lease(std::shared_ptr owner) : owner_(std::move(owner)) { std::lock_guard lock(owner_->mutex); - if (!owner_->closing) - { + if (!owner_->closing) { ++owner_->pending; acquired = true; } } ~request_lease() { - if (acquired) - { + if (acquired) { std::lock_guard lock(owner_->mutex); --owner_->pending; } @@ -163,12 +155,10 @@ struct http_server_module_impl::callback_state arknet::http_router router; }; -struct http_server_module_impl::state -{ +struct http_server_module_impl::state { std::shared_ptr callbacks = std::make_shared(); - struct native_owner - { + struct native_owner { std::unique_ptr server; std::string listen_key; std::unique_ptr next; @@ -181,15 +171,12 @@ struct http_server_module_impl::state std::lock_guard lock(callbacks->mutex); // Even a stopped or never-started native endpoint can allocate in its // destructor. Its existence is not proof of safe retirement here. - for (auto* owner = owners.get(); owner; owner = owner->next.get()) - { - if (owner->server) - { + for (auto* owner = owners.get(); owner; owner = owner->next.get()) { + if (owner->server) { return startup_cleanup_result::unsafe; } } - if (callbacks->exposed || callbacks->pending != 0) - { + if (callbacks->exposed || callbacks->pending != 0) { return startup_cleanup_result::unsafe; } callbacks->sealed = true; @@ -198,20 +185,17 @@ struct http_server_module_impl::state } }; -struct http_server_module_impl::startup_capsule -{ +struct http_server_module_impl::startup_capsule { std::shared_ptr resource; }; http_server_module_impl::http_server_module_impl(plugin_manager* manager) : state_(std::make_shared()) { - if (manager) - { + if (manager) { auto capsule = std::make_shared(startup_capsule{state_}); if (!manager->prepare_startup_cleanup("HTTPServer", "ark_http_plugin", capsule, [](void* context) { return static_cast(context)->resource->cleanup_failed_startup(); - })) - { + })) { throw std::runtime_error("HTTP server startup ownership enrollment rejected"); } startup_owner_ = capsule; @@ -221,8 +205,7 @@ http_server_module_impl::http_server_module_impl(plugin_manager* manager) http_server_module_impl::~http_server_module_impl() { // Failed registration/startup leaves the complete owner with the host. // Successful startup disarms enrollment and restores ordinary destruction. - if (startup_owner_.expired()) - { + if (startup_owner_.expired()) { pre_shut(); } } @@ -255,10 +238,8 @@ bool http_server_module_impl::pre_shut() { std::lock_guard lock(state_->callbacks->mutex); state_->callbacks->closing = true; } - for (auto* owner = state_->owners.get(); owner; owner = owner->next.get()) - { - if (owner->server) - { + for (auto* owner = state_->owners.get(); owner; owner = owner->next.get()) { + if (owner->server) { owner->server->stop(); owner->server.reset(); } @@ -279,28 +260,23 @@ bool http_server_module_impl::start_server( std::string const& ip /* = "0.0.0.0"*/, uint16_t port /* = 8080 */, uint8_t thread_num /* = 1*/) { { std::lock_guard lock(state_->callbacks->mutex); - if (state_->callbacks->sealed) - { + if (state_->callbacks->sealed) { return false; } - if (state_->callbacks->closing) - { - if (state_->active || state_->callbacks->pending != 0) - { + if (state_->callbacks->closing) { + if (state_->active || state_->callbacks->pending != 0) { return false; } // An explicit restart after pre_shut uses the caller's new router. state_->callbacks->closing = false; } } - if (state_->active) - { + if (state_->active) { return false; } auto candidate = std::make_unique(); endpoint_reservation reservation(port == 0 ? std::string{} : endpoint_key(ip, port)); - if (!reservation.is_reserved()) - { + if (!reservation.is_reserved()) { return false; } candidate->next = std::move(state_->owners); @@ -313,8 +289,7 @@ bool http_server_module_impl::start_server( owner.server->bind_recv([callbacks = state_->callbacks]( std::shared_ptr& session, arknet::http_route_request& request) { auto lease = std::make_shared(callbacks); - if (!lease->acquired) - { + if (!lease->acquired) { session->stop(); return; } @@ -322,16 +297,14 @@ bool http_server_module_impl::start_server( response.set(arknet::http::field::server, "ARK"); session->async_send(std::move(response), [lease](const arknet::error_code&, std::size_t) {}); }); - if (!owner.server->start(ip, port)) - { + if (!owner.server->start(ip, port)) { // Preserve the existing ordinary start-false stop and endpoint reuse. // If native stop throws, the complete attempt stays enrolled. Retain // even stopped native allocations rather than invoking their destructors // while an allocation failure may still be active. owner.server->stop(); release_endpoint(owner.listen_key); - if (startup_owner_.expired()) - { + if (startup_owner_.expired()) { // Standalone use and completed startup retain the original ordinary // destruction path; failed attempts must not accumulate forever. owner.server.reset(); diff --git a/src/plugins/kafka/kafka.hpp b/src/plugins/kafka/kafka.hpp index c34b21878..59a4058b5 100644 --- a/src/plugins/kafka/kafka.hpp +++ b/src/plugins/kafka/kafka.hpp @@ -17,8 +17,7 @@ namespace { inline void set_config(RdKafka::Conf* conf, const std::string& key, const std::string& value) { std::string error; - if (conf->set(key, value, error) == RdKafka::Conf::CONF_OK) - { + if (conf->set(key, value, error) == RdKafka::Conf::CONF_OK) { return; } throw std::runtime_error("Failed to set '" + key + "' to '" + value + "'! err=" + error); @@ -26,8 +25,7 @@ inline void set_config(RdKafka::Conf* conf, const std::string& key, const std::s inline void set_config(RdKafka::Conf* conf, const std::string& key, RdKafka::EventCb* cb_obj) { std::string error; - if (conf->set(key, cb_obj, error) == RdKafka::Conf::CONF_OK) - { + if (conf->set(key, cb_obj, error) == RdKafka::Conf::CONF_OK) { return; } throw std::runtime_error("Failed to set '" + key + "'! err=" + error); @@ -35,8 +33,7 @@ inline void set_config(RdKafka::Conf* conf, const std::string& key, RdKafka::Eve inline void set_config(RdKafka::Conf* conf, const std::string& key, RdKafka::OffsetCommitCb* cb_obj) { std::string error; - if (conf->set(key, cb_obj, error) == RdKafka::Conf::CONF_OK) - { + if (conf->set(key, cb_obj, error) == RdKafka::Conf::CONF_OK) { return; } throw std::runtime_error("Failed to set '" + key + "'! err=" + error); @@ -44,8 +41,7 @@ inline void set_config(RdKafka::Conf* conf, const std::string& key, RdKafka::Off inline void set_config(RdKafka::Conf* conf, const std::string& key, RdKafka::DeliveryReportCb* cb_obj) { std::string error; - if (conf->set(key, cb_obj, error) == RdKafka::Conf::CONF_OK) - { + if (conf->set(key, cb_obj, error) == RdKafka::Conf::CONF_OK) { return; } throw std::runtime_error("Failed to set '" + key + "'! err=" + error); @@ -56,8 +52,7 @@ inline void set_config(RdKafka::Conf* conf, const std::string& key, RdKafka::Del /** * @brief RdKafka::KafkaConsumer的简单封装 */ -class kafka_consumer -{ +class kafka_consumer { public: using message = RdKafka::Message; @@ -70,8 +65,7 @@ class kafka_consumer */ kafka_consumer(const std::string& brokers, const std::string& group_id, const std::string& topics, RdKafka::OffsetCommitCb* offset_cb = nullptr, RdKafka::EventCb* evcb = nullptr) { - if (brokers.empty() || group_id.empty() || topics.empty()) - { + if (brokers.empty() || group_id.empty() || topics.empty()) { throw std::runtime_error("Invalid parameters!"); } @@ -83,27 +77,23 @@ class kafka_consumer set_config(conf, "auto.offset.reset", "smallest"); set_config(conf, "enable.auto.commit", "false"); set_config(conf, "enable.auto.offset.store", "false"); - if (evcb) - { + if (evcb) { set_config(conf, "event_cb", evcb); } - if (offset_cb) - { + if (offset_cb) { set_config(conf, "offset_commit_cb", offset_cb); } std::string error; std::unique_ptr consumer(RdKafka::KafkaConsumer::create(conf, error)); - if (!consumer) - { + if (!consumer) { throw std::runtime_error("Failed to create consumer! err=" + error); } std::vector all_topics; string_utils::split(all_topics, topics, ','); auto err = consumer->subscribe(all_topics); - if (err) - { + if (err) { throw std::runtime_error("Failed to subscribe to '" + topics + "'! err=" + RdKafka::err2str(err)); } @@ -142,8 +132,7 @@ class kafka_consumer /** * @brief RdKafka::Producer的简单封装 */ -class kafka_producer -{ +class kafka_producer { public: /** * @brief 构造函数 @@ -156,26 +145,22 @@ class kafka_producer std::unique_ptr conf_for_auto_del(conf); // for auto delete when throwing exception set_config(conf, "metadata.broker.list", brokers); - if (event_cb != nullptr) - { + if (event_cb != nullptr) { set_config(conf, "event_cb", event_cb); } - if (delivery_report_cb != nullptr) - { + if (delivery_report_cb != nullptr) { set_config(conf, "dr_cb", delivery_report_cb); } std::string error; auto tmp_producer = RdKafka::Producer::create(conf, error); - if (!tmp_producer) - { + if (!tmp_producer) { throw std::runtime_error("Failed to create producer! err=" + error); } std::unique_ptr producer(tmp_producer); // for auto delete when throwing exception topic_ = RdKafka::Topic::create(tmp_producer, topic, nullptr, error); - if (topic_ == nullptr) - { + if (topic_ == nullptr) { throw std::runtime_error("Failed to create topic! topic=" + topic + " error=" + error); } @@ -216,8 +201,7 @@ class kafka_producer producer_->produce(topic_, RdKafka::Topic::PARTITION_UA, RdKafka::Producer::RK_MSG_COPY, const_cast(payload.data()), payload.size(), nullptr, &err); - while (err == static_cast(-12345)) - { + while (err == static_cast(-12345)) { poll(1000); } @@ -245,8 +229,7 @@ class kafka_producer /** * @brief KafkaProducer对象池,线程安全。 */ -class kafka_producer_pool : private noncopyable -{ +class kafka_producer_pool : private noncopyable { public: /** * @brief 构造Oracle操作对象 @@ -263,8 +246,7 @@ class kafka_producer_pool : private noncopyable } ~kafka_producer_pool() { - for (auto cli : pooled_producers_) - { + for (auto cli : pooled_producers_) { delete cli; } } @@ -274,8 +256,7 @@ class kafka_producer_pool : private noncopyable */ kafka_producer* get() { lock_.lock(); - if (!pooled_producers_.empty()) - { + if (!pooled_producers_.empty()) { auto cli = pooled_producers_.front(); pooled_producers_.pop_front(); lock_.unlock(); @@ -283,10 +264,10 @@ class kafka_producer_pool : private noncopyable } lock_.unlock(); - try - { return new kafka_producer(brokers_, topic_, delivery_report_cb_, event_cb_); } - catch (...) - {} + try { + return new kafka_producer(brokers_, topic_, delivery_report_cb_, event_cb_); + } catch (...) { + } return nullptr; } @@ -296,13 +277,10 @@ class kafka_producer_pool : private noncopyable */ void put(kafka_producer* producer) { lock_.lock(); - if (pooled_producers_.size() < max_pooled_producers_) - { + if (pooled_producers_.size() < max_pooled_producers_) { pooled_producers_.emplace_back(producer); lock_.unlock(); - } - else - { + } else { lock_.unlock(); delete producer; } diff --git a/src/plugins/kafka/kafka_module.hpp b/src/plugins/kafka/kafka_module.hpp index b5293ab1d..4b0c71c1d 100644 --- a/src/plugins/kafka/kafka_module.hpp +++ b/src/plugins/kafka/kafka_module.hpp @@ -4,8 +4,7 @@ namespace ark { -class kafka_module : public module -{ +class kafka_module : public module { public: // single producer virtual bool init_producer(std::string const& brokers, std::string const& topic) = 0; diff --git a/src/plugins/kafka/kafka_module_impl.cpp b/src/plugins/kafka/kafka_module_impl.cpp index ee2e13227..e337d2be8 100644 --- a/src/plugins/kafka/kafka_module_impl.cpp +++ b/src/plugins/kafka/kafka_module_impl.cpp @@ -14,8 +14,7 @@ bool kafka_module_impl::init() { } bool kafka_module_impl::update() { - for (size_t i = 0; i < producers_.get_count(); ++i) - { + for (size_t i = 0; i < producers_.get_count(); ++i) { producers_[i]->poll(); } @@ -23,14 +22,12 @@ bool kafka_module_impl::update() { } bool kafka_module_impl::init_producer(std::string const& brokers, std::string const& topic) { - if (topic.empty() || brokers.empty()) - { + if (topic.empty() || brokers.empty()) { return false; } auto* found = producers_.get_element(topic); - if (found != nullptr) - { + if (found != nullptr) { return false; } @@ -41,8 +38,7 @@ bool kafka_module_impl::init_producer(std::string const& brokers, std::string co int kafka_module_impl::produce(std::string const& topic, std::string const& payload, void* user_data) { auto* producer = producers_.get_element(topic); - if (producer == nullptr) - { + if (producer == nullptr) { return false; } @@ -52,8 +48,7 @@ int kafka_module_impl::produce(std::string const& topic, std::string const& payl void kafka_module_impl::dr_cb(RdKafka::Message& msg) { //auto task = reinterpret_cast(msg.msg_opaque()); auto err = msg.err(); - if (err != RdKafka::ERR_NO_ERROR) - { + if (err != RdKafka::ERR_NO_ERROR) { // errStr_ = RdKafka::err2str(err); // LOG(WARNING) << "Push msg failed, retry later! msgID=" << task->MsgID << " offset=" << task->Offset // << " infocode=" << task->Infocode << " err=" << errStr_; @@ -65,8 +60,7 @@ void kafka_module_impl::dr_cb(RdKafka::Message& msg) { } void kafka_module_impl::event_cb(RdKafka::Event& event) { - switch (event.type()) - { + switch (event.type()) { case RdKafka::Event::EVENT_ERROR: ARK_LOG_WARN("Kafka error! err=[{}]:{} msg={}", static_cast(event.err()), RdKafka::err2str(event.err()), event.str()); diff --git a/src/plugins/kafka/kafka_module_impl.hpp b/src/plugins/kafka/kafka_module_impl.hpp index 83cbb5fc0..bc177ce1f 100644 --- a/src/plugins/kafka/kafka_module_impl.hpp +++ b/src/plugins/kafka/kafka_module_impl.hpp @@ -10,8 +10,7 @@ namespace ark { class kafka_module_impl : public module_base , public RdKafka::DeliveryReportCb - , public RdKafka::EventCb -{ + , public RdKafka::EventCb { public: bool init() override; bool update() override; diff --git a/src/plugins/kafka/kafka_plugin.cpp b/src/plugins/kafka/kafka_plugin.cpp index 37a6ea18a..a3a637a7f 100644 --- a/src/plugins/kafka/kafka_plugin.cpp +++ b/src/plugins/kafka/kafka_plugin.cpp @@ -15,15 +15,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void kafka_plugin::install() { - if (!register_module(detail::make_kafka_module(), module_update::enabled)) - { + if (!register_module(detail::make_kafka_module(), module_update::enabled)) { throw std::runtime_error("Kafka module registration rejected"); } } void kafka_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("Kafka module unregistration rejected"); } } diff --git a/src/plugins/kafka/kafka_plugin.hpp b/src/plugins/kafka/kafka_plugin.hpp index db562c284..c68803379 100644 --- a/src/plugins/kafka/kafka_plugin.hpp +++ b/src/plugins/kafka/kafka_plugin.hpp @@ -4,8 +4,7 @@ namespace ark { -class kafka_plugin final : public plugin_base -{ +class kafka_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/plugins/kernel/class_call_back_manager.cpp b/src/plugins/kernel/class_call_back_manager.cpp index aec61e572..fb9f610d2 100644 --- a/src/plugins/kernel/class_call_back_manager.cpp +++ b/src/plugins/kernel/class_call_back_manager.cpp @@ -24,8 +24,7 @@ namespace ark { namespace { -struct delayed_sync_dispatch -{ +struct delayed_sync_dispatch { class_call_back_manager::delay_sync_data_list pending; const guid_t* current{}; bool retired{}; @@ -49,14 +48,11 @@ bool class_call_back_manager::add_class_call_back(class_event_functor&& cb, cons bool class_call_back_manager::add_data_call_back( const uint32_t index, data_node_event_functor&& cb, const int32_t prio) { auto iter = data_call_backs_list_.find(index); - if (iter == data_call_backs_list_.end()) - { + if (iter == data_call_backs_list_.end()) { node_call_backs call_backs; call_backs.insert(std::make_pair(prio, std::move(cb))); data_call_backs_list_.insert(std::make_pair(index, call_backs)); - } - else - { + } else { iter->second.insert(std::make_pair(prio, std::move(cb))); } @@ -66,15 +62,12 @@ bool class_call_back_manager::add_data_call_back( bool class_call_back_manager::add_table_call_back( const uint32_t index, data_table_event_functor&& cb, const int32_t prio) { auto iter = table_call_backs_list_.find(index); - if (iter == table_call_backs_list_.end()) - { + if (iter == table_call_backs_list_.end()) { table_call_backs call_backs; call_backs.insert(std::make_pair(prio, std::move(cb))); table_call_backs_list_.insert(std::make_pair(index, call_backs)); - } - else - { + } else { iter->second.insert(std::make_pair(prio, std::move(cb))); } @@ -84,15 +77,12 @@ bool class_call_back_manager::add_table_call_back( bool class_call_back_manager::add_container_call_back( const uint32_t index, container_event_functor&& cb, const int32_t prio) { auto iter = container_call_backs_list_.find(index); - if (iter == container_call_backs_list_.end()) - { + if (iter == container_call_backs_list_.end()) { container_call_backs call_backs; call_backs.insert(std::make_pair(prio, std::move(cb))); container_call_backs_list_.insert(std::make_pair(index, call_backs)); - } - else - { + } else { iter->second.insert(std::make_pair(prio, std::move(cb))); } @@ -116,8 +106,7 @@ bool class_call_back_manager::add_move_event(move_event_functor&& cb, const int3 bool class_call_back_manager::on_class_event( const guid_t& id, const std::string& class_name, const entity_event class_event, const data_list& value_list) { - for (auto& iter : class_events_) - { + for (auto& iter : class_events_) { iter.second(id, class_name, class_event, value_list); } @@ -130,30 +119,23 @@ bool class_call_back_manager::on_node_call_back( auto& name = node_ptr->get_name(); // sync call back - if (node_ptr->have_mask(data_mask::pf_real_time)) - { - for (auto& iter : node_sync_call_back_list_) - { + if (node_ptr->have_mask(data_mask::pf_real_time)) { + for (auto& iter : node_sync_call_back_list_) { auto mask_value = iter.first; - if (!node_ptr->have_mask(mask_value)) - { + if (!node_ptr->have_mask(mask_value)) { continue; } iter.second(self, index, mask_value, new_data); } - } - else - { + } else { update_delay_node_list(self, node_ptr); } // common call back auto iter_call_backs = data_call_backs_list_.find(index); - if (iter_call_backs != data_call_backs_list_.end()) - { - for (auto& iter : iter_call_backs->second) - { + if (iter_call_backs != data_call_backs_list_.end()) { + for (auto& iter : iter_call_backs->second) { iter.second(self, name, index, old_data, new_data); } } @@ -164,31 +146,24 @@ bool class_call_back_manager::on_node_call_back( bool class_call_back_manager::on_table_call_back(const guid_t& self, const mask_type mask, node* node_ptr, const table_event_data& event_data, const data& old_data, const data& new_data) { // sync call back - if (mask.test((size_t)data_mask::pf_real_time)) - { - for (auto& iter : table_sync_call_back_list_) - { + if (mask.test((size_t)data_mask::pf_real_time)) { + for (auto& iter : table_sync_call_back_list_) { auto mask_value = iter.first; - if (!mask.test((size_t)mask_value)) - { + if (!mask.test((size_t)mask_value)) { continue; } iter.second(self, event_data, mask_value, new_data); } - } - else - { + } else { update_delay_table_list( self, mask, event_data.table_index, event_data.row, (table_op_type)event_data.op_type, node_ptr); } // common call back auto iter_call_backs = table_call_backs_list_.find(event_data.table_index); - if (iter_call_backs != table_call_backs_list_.end()) - { - for (auto& iter : iter_call_backs->second) - { + if (iter_call_backs != table_call_backs_list_.end()) { + for (auto& iter : iter_call_backs->second) { iter.second(self, event_data, old_data, new_data); } } @@ -200,29 +175,22 @@ bool class_call_back_manager::on_container_call_back(const guid_t& self, const u const container_op_type op_type, uint32_t src_index, uint32_t dest_index, std::shared_ptr src_entity /* = nullptr*/) { // sync call back - if (mask.test((size_t)data_mask::pf_real_time)) - { - for (auto& iter : container_sync_call_backs_list_) - { + if (mask.test((size_t)data_mask::pf_real_time)) { + for (auto& iter : container_sync_call_backs_list_) { auto mask_value = iter.first; - if (!mask.test((size_t)mask_value)) - { + if (!mask.test((size_t)mask_value)) { continue; } iter.second(self, index, mask_value, op_type, src_index, dest_index); } - } - else - { + } else { update_delay_container_list(self, index, mask, op_type, src_index, dest_index, src_entity); } auto iter_call_backs = container_call_backs_list_.find(index); - if (iter_call_backs != container_call_backs_list_.end()) - { - for (auto& iter : iter_call_backs->second) - { + if (iter_call_backs != container_call_backs_list_.end()) { + for (auto& iter : iter_call_backs->second) { iter.second(self, index, op_type, src_index, dest_index); } } @@ -231,8 +199,7 @@ bool class_call_back_manager::on_container_call_back(const guid_t& self, const u } bool class_call_back_manager::on_leave_scene_event(const guid_t& self, const int map_id, const int map_inst_id) { - for (auto& iter : leave_scene_events_) - { + for (auto& iter : leave_scene_events_) { iter.second(self, map_id, map_inst_id); } @@ -240,8 +207,7 @@ bool class_call_back_manager::on_leave_scene_event(const guid_t& self, const int } bool class_call_back_manager::on_enter_scene_event(const guid_t& self, const int map_id, const int map_inst_id) { - for (auto& iter : enter_scene_events_) - { + for (auto& iter : enter_scene_events_) { iter.second(self, map_id, map_inst_id); } @@ -249,8 +215,7 @@ bool class_call_back_manager::on_enter_scene_event(const guid_t& self, const int } bool class_call_back_manager::on_move_event(const guid_t& self, const vector3d& old_pos, const vector3d& new_pos) { - for (auto& iter : move_events_) - { + for (auto& iter : move_events_) { iter.second(self, old_pos, new_pos); } @@ -275,13 +240,11 @@ void class_call_back_manager::add_delay_sync_call_back(const data_mask mask_valu } bool class_call_back_manager::on_delay_sync() { - if (active_delay_sync) - { + if (active_delay_sync) { return false; } - struct flush_guard - { + struct flush_guard { ~flush_guard() { active_delay_sync = nullptr; } @@ -293,24 +256,20 @@ bool class_call_back_manager::on_delay_sync() { dispatch.pending.swap(delay_sync_data_list_); active_delay_sync = &dispatch; flush_guard guard; - while (!dispatch.pending.empty()) - { + while (!dispatch.pending.empty()) { // Extract the current entity before invoking user code. Retirement can // then erase any later entity without invalidating our traversal. auto entry = dispatch.pending.extract(dispatch.pending.begin()); auto& guid = entry.key(); dispatch.current = &guid; dispatch.retired = false; - for (auto& iter_data : entry.mapped()) - { - if (dispatch.retired) - { + for (auto& iter_data : entry.mapped()) { + if (dispatch.retired) { break; } auto mask_value = iter_data.first; auto iter_call_back = delay_sync_call_back_list_.find(mask_value); - if (iter_call_back == delay_sync_call_back_list_.end()) - { + if (iter_call_back == delay_sync_call_back_list_.end()) { continue; } @@ -324,11 +283,9 @@ bool class_call_back_manager::on_delay_sync() { void class_call_back_manager::retire_delay_sync(const guid_t& self) { delay_sync_data_list_.erase(self); - if (active_delay_sync) - { + if (active_delay_sync) { active_delay_sync->pending.erase(self); - if (active_delay_sync->current && *active_delay_sync->current == self) - { + if (active_delay_sync->current && *active_delay_sync->current == self) { active_delay_sync->retired = true; } } @@ -336,8 +293,7 @@ void class_call_back_manager::retire_delay_sync(const guid_t& self) { class_call_back_manager::delay_sync_mask_data& class_call_back_manager::get_delay_sync_mask_data(const guid_t& self) { auto iter_data = delay_sync_data_list_.find(self); - if (iter_data == delay_sync_data_list_.end()) - { + if (iter_data == delay_sync_data_list_.end()) { delay_sync_mask_data mask_data_map; iter_data = delay_sync_data_list_.insert(std::make_pair(self, mask_data_map)).first; } @@ -348,16 +304,14 @@ class_call_back_manager::delay_sync_mask_data& class_call_back_manager::get_dela delay_sync_table& class_call_back_manager::get_delay_sync_mask_table( delay_sync_mask_data& mask_data_map, const data_mask mask_value, uint32_t index) { auto iter_mask_data = mask_data_map.find(mask_value); - if (iter_mask_data == mask_data_map.end()) - { + if (iter_mask_data == mask_data_map.end()) { delay_sync_data data; iter_mask_data = mask_data_map.insert(std::make_pair(mask_value, data)).first; } auto& table_list = iter_mask_data->second.table_list; auto iter_table = table_list.find(index); - if (iter_table == table_list.end()) - { + if (iter_table == table_list.end()) { delay_sync_table table; iter_table = table_list.insert(std::make_pair(index, table)).first; } @@ -368,16 +322,14 @@ delay_sync_table& class_call_back_manager::get_delay_sync_mask_table( delay_sync_container& class_call_back_manager::get_delay_sync_mask_container( delay_sync_mask_data& mask_data_map, const data_mask mask_value, uint32_t index) { auto iter_mask_data = mask_data_map.find(mask_value); - if (iter_mask_data == mask_data_map.end()) - { + if (iter_mask_data == mask_data_map.end()) { delay_sync_data data; iter_mask_data = mask_data_map.insert(std::make_pair(mask_value, data)).first; } auto& contaier_list = iter_mask_data->second.container_list; auto iter_container = contaier_list.find(index); - if (iter_container == contaier_list.end()) - { + if (iter_container == contaier_list.end()) { delay_sync_container container; iter_container = contaier_list.insert(std::make_pair(index, container)).first; } @@ -388,23 +340,18 @@ delay_sync_container& class_call_back_manager::get_delay_sync_mask_container( void class_call_back_manager::update_delay_node_list(const guid_t& self, node* node_ptr) { // update node list auto& mask_data_map = get_delay_sync_mask_data(self); - for (auto& iter : delay_sync_call_back_list_) - { + for (auto& iter : delay_sync_call_back_list_) { auto mask_value = iter.first; - if (!node_ptr->have_mask(mask_value)) - { + if (!node_ptr->have_mask(mask_value)) { continue; } auto iter_mask_data = mask_data_map.find(mask_value); - if (iter_mask_data == mask_data_map.end()) - { + if (iter_mask_data == mask_data_map.end()) { delay_sync_data data; data.node_list.insert(node_ptr); mask_data_map.insert(std::make_pair(mask_value, data)); - } - else - { + } else { iter_mask_data->second.node_list.insert(node_ptr); } } @@ -413,33 +360,22 @@ void class_call_back_manager::update_delay_node_list(const guid_t& self, node* n void class_call_back_manager::update_delay_table_list(const guid_t& self, const mask_type mask, const uint32_t table_index, const uint32_t row_index, table_op_type op_type, node* node_ptr) { auto& mask_data_map = get_delay_sync_mask_data(self); - for (auto& iter : delay_sync_call_back_list_) - { + for (auto& iter : delay_sync_call_back_list_) { auto mask_value = iter.first; - if (!mask.test((size_t)mask_value)) - { + if (!mask.test((size_t)mask_value)) { continue; } auto& table = get_delay_sync_mask_table(mask_data_map, mask_value, table_index); - if (op_type == table_op_type::table_add) - { + if (op_type == table_op_type::table_add) { on_table_add(table, row_index); - } - else if (op_type == table_op_type::table_delete) - { + } else if (op_type == table_op_type::table_delete) { on_table_delete(table, row_index); - } - else if (op_type == table_op_type::table_update) - { + } else if (op_type == table_op_type::table_update) { on_table_row_update(table, row_index, node_ptr); - } - else if (op_type == table_op_type::table_swap) - { + } else if (op_type == table_op_type::table_swap) { // todo : for now there is no operation swap - } - else if (op_type == table_op_type::table_clear) - { + } else if (op_type == table_op_type::table_clear) { on_table_clear(table); } } @@ -450,29 +386,20 @@ void class_call_back_manager::update_delay_container_list(const guid_t& self, co std::shared_ptr src_entity = nullptr) { // update container list auto& mask_data_map = get_delay_sync_mask_data(self); - for (auto& iter : delay_sync_call_back_list_) - { + for (auto& iter : delay_sync_call_back_list_) { auto mask_value = iter.first; - if (!mask.test((size_t)mask_value)) - { + if (!mask.test((size_t)mask_value)) { continue; } auto& container = get_delay_sync_mask_container(mask_data_map, mask_value, index); - if (op_type == container_op_type::op_place) - { + if (op_type == container_op_type::op_place) { on_container_place(container, src_index); - } - else if (op_type == container_op_type::op_remove) - { + } else if (op_type == container_op_type::op_remove) { on_container_remove(container, src_index); - } - else if (op_type == container_op_type::op_destroy) - { + } else if (op_type == container_op_type::op_destroy) { on_container_destroy(container, src_index, src_entity); - } - else if (op_type == container_op_type::op_swap) - { + } else if (op_type == container_op_type::op_swap) { on_container_swap(container, src_index, dest_index); } } @@ -480,28 +407,22 @@ void class_call_back_manager::update_delay_container_list(const guid_t& self, co void class_call_back_manager::on_table_add(delay_sync_table& table, const int row) { auto iter = table.row_list.find(row); - if (iter == table.row_list.end()) - { + if (iter == table.row_list.end()) { delay_sync_row row_data(row); table.row_list.insert(std::make_pair(row, row_data)); - } - else - { + } else { iter->second.node_list.clear(); } } void class_call_back_manager::on_table_delete(delay_sync_table& table, const int row) { auto iter = table.row_list.find(row); - if (iter == table.row_list.end()) - { + if (iter == table.row_list.end()) { delay_sync_row row_data(row); row_data.need_clear = true; table.row_list.insert(std::make_pair(row, row_data)); - } - else - { + } else { iter->second.need_clear = true; iter->second.node_list.clear(); } @@ -509,14 +430,11 @@ void class_call_back_manager::on_table_delete(delay_sync_table& table, const int void class_call_back_manager::on_table_row_update(delay_sync_table& table, const int row, node* node_ptr) { auto iter = table.row_list.find(row); - if (iter == table.row_list.end()) - { + if (iter == table.row_list.end()) { delay_sync_row row_data(row); row_data.node_list.insert(node_ptr); table.row_list.insert(std::make_pair(row, row_data)); - } - else - { + } else { iter->second.node_list.insert(node_ptr); } } @@ -536,8 +454,7 @@ void class_call_back_manager::on_container_remove(delay_sync_container& containe void class_call_back_manager::on_container_destroy( delay_sync_container& container, uint32_t index, std::shared_ptr src_entity) { - if (src_entity->is_sent()) - { + if (src_entity->is_sent()) { container.destroy_list.insert(index); } diff --git a/src/plugins/kernel/class_call_back_manager.hpp b/src/plugins/kernel/class_call_back_manager.hpp index 3f98a3ecf..fe2b51d0c 100644 --- a/src/plugins/kernel/class_call_back_manager.hpp +++ b/src/plugins/kernel/class_call_back_manager.hpp @@ -31,8 +31,7 @@ namespace ark { -struct delay_sync_row -{ +struct delay_sync_row { delay_sync_row(const uint32_t row) : row(row) { } @@ -42,20 +41,17 @@ struct delay_sync_row std::set node_list; }; -struct delay_sync_table -{ +struct delay_sync_table { bool need_clear{false}; std::map row_list; }; -struct delay_sync_container -{ +struct delay_sync_container { std::set index_list; std::set destroy_list; }; -struct delay_sync_data -{ +struct delay_sync_data { // node list std::set node_list; @@ -66,8 +62,7 @@ struct delay_sync_data std::map container_list; }; -class class_call_back_manager final -{ +class class_call_back_manager final { public: // delay sync data using delay_sync_mask_data = std::map; diff --git a/src/plugins/kernel/class_meta.cpp b/src/plugins/kernel/class_meta.cpp index 96e4dbd7a..ee7e3f330 100644 --- a/src/plugins/kernel/class_meta.cpp +++ b/src/plugins/kernel/class_meta.cpp @@ -125,8 +125,7 @@ std::shared_ptr class_meta::get_class_call_back_manager uint32_t class_meta::get_index(const std::string& name) const { auto iter = name_index_list_.find(name); - if (iter == name_index_list_.end()) - { + if (iter == name_index_list_.end()) { return null_int; } diff --git a/src/plugins/kernel/class_meta.hpp b/src/plugins/kernel/class_meta.hpp index 9101f7fc9..ea0509234 100644 --- a/src/plugins/kernel/class_meta.hpp +++ b/src/plugins/kernel/class_meta.hpp @@ -34,8 +34,7 @@ namespace ark { class table_meta; -class class_meta final -{ +class class_meta final { public: using name_index_list = std::unordered_map; using data_meta_list = shared_object_map; diff --git a/src/plugins/kernel/class_meta_manager.hpp b/src/plugins/kernel/class_meta_manager.hpp index ff8b65516..d7e47818b 100644 --- a/src/plugins/kernel/class_meta_manager.hpp +++ b/src/plugins/kernel/class_meta_manager.hpp @@ -26,8 +26,7 @@ namespace ark { -class class_meta_manager final -{ +class class_meta_manager final { public: using class_meta_list = shared_object_hashmap; @@ -69,15 +68,13 @@ class class_meta_manager final } bool after_loaded() { - for (auto iter_class_meta : class_meta_list_) - { + for (auto iter_class_meta : class_meta_list_) { auto meta = iter_class_meta.second; ARK_ASSERT_RET_VAL(meta != nullptr, false); // init table col meta auto& table_meta_list = meta->get_table_meta_list(); - for (auto iter : table_meta_list) - { + for (auto iter : table_meta_list) { auto table_meta_ptr = iter.second; ARK_ASSERT_RET_VAL(table_meta_ptr != nullptr, false); @@ -96,8 +93,7 @@ class class_meta_manager final std::shared_ptr create_meta(class_meta_list& class_meta_list, const std::string& name) { // return if found auto iter = class_meta_list.find(name); - if (iter != class_meta_list.end()) - { + if (iter != class_meta_list.end()) { return iter->second; } diff --git a/src/plugins/kernel/class_meta_module.hpp b/src/plugins/kernel/class_meta_module.hpp index 6804c42c3..914766157 100644 --- a/src/plugins/kernel/class_meta_module.hpp +++ b/src/plugins/kernel/class_meta_module.hpp @@ -28,8 +28,7 @@ namespace ark { -class class_meta_module : public module -{ +class class_meta_module : public module { public: virtual bool load() = 0; diff --git a/src/plugins/kernel/class_meta_module_impl.cpp b/src/plugins/kernel/class_meta_module_impl.cpp index fc1872edd..334faa807 100644 --- a/src/plugins/kernel/class_meta_module_impl.cpp +++ b/src/plugins/kernel/class_meta_module_impl.cpp @@ -27,16 +27,12 @@ namespace ark { bool class_meta_module_impl::init() { class_meta_manager_ = ARK_NEW class_meta_manager; - try - { - if (!load()) - { + try { + if (!load()) { ARK_DELETE(class_meta_manager_); return false; } - } - catch (...) - { + } catch (...) { ARK_DELETE(class_meta_manager_); throw; } diff --git a/src/plugins/kernel/class_meta_module_impl.hpp b/src/plugins/kernel/class_meta_module_impl.hpp index dd0a99011..6ef3b9a0b 100644 --- a/src/plugins/kernel/class_meta_module_impl.hpp +++ b/src/plugins/kernel/class_meta_module_impl.hpp @@ -28,8 +28,7 @@ namespace ark { -class class_meta_module_impl final : public module_base -{ +class class_meta_module_impl final : public module_base { public: class_meta_module_impl() = default; ~class_meta_module_impl() override = default; diff --git a/src/plugins/kernel/component.hpp b/src/plugins/kernel/component.hpp index c5ff95419..24dc909dc 100644 --- a/src/plugins/kernel/component.hpp +++ b/src/plugins/kernel/component.hpp @@ -27,8 +27,7 @@ namespace ark { -class component : public module -{ +class component : public module { public: component() = delete; @@ -43,14 +42,11 @@ class component : public module std::shared_ptr create_new_instance() { std::shared_ptr component_ptr = create_new_instance(); - if (nullptr != component_ptr) - { - if constexpr (std::is_base_of_v) - { + if (nullptr != component_ptr) { + if constexpr (std::is_base_of_v) { std::shared_ptr value_ptr = std::dynamic_pointer_cast(component_ptr); - if (nullptr != value_ptr) - { + if (nullptr != value_ptr) { return value_ptr; } } diff --git a/src/plugins/kernel/config_module.hpp b/src/plugins/kernel/config_module.hpp index 4c8c42c45..08963bf58 100644 --- a/src/plugins/kernel/config_module.hpp +++ b/src/plugins/kernel/config_module.hpp @@ -26,8 +26,7 @@ namespace ark { -class config_module : public module -{ +class config_module : public module { public: virtual bool load() = 0; virtual bool save() = 0; diff --git a/src/plugins/kernel/config_module_impl.cpp b/src/plugins/kernel/config_module_impl.cpp index 2abae4772..d5bef3172 100644 --- a/src/plugins/kernel/config_module_impl.cpp +++ b/src/plugins/kernel/config_module_impl.cpp @@ -42,18 +42,15 @@ bool config_module_impl::shut() { } bool config_module_impl::load() { - if (loaded_) - { + if (loaded_) { return false; } auto& class_meta_list = class_meta_module_->get_static_meta_list(); - for (auto iter : class_meta_list) - { + for (auto iter : class_meta_list) { auto class_meta = iter.second; const auto& config = class_meta->get_json_config(); - if (!config) - { + if (!config) { throw entity_json::error( detail::entity_json_file(), "/configs", "configuration metadata has no validated JSON rows"); } diff --git a/src/plugins/kernel/config_module_impl.hpp b/src/plugins/kernel/config_module_impl.hpp index 5a91ab9f4..1a62feae8 100644 --- a/src/plugins/kernel/config_module_impl.hpp +++ b/src/plugins/kernel/config_module_impl.hpp @@ -26,8 +26,7 @@ namespace ark { -class config_module_impl final : public module_base -{ +class config_module_impl final : public module_base { public: bool init() override; bool post_init() override; diff --git a/src/plugins/kernel/container.hpp b/src/plugins/kernel/container.hpp index 55c92db3c..5212d8eee 100644 --- a/src/plugins/kernel/container.hpp +++ b/src/plugins/kernel/container.hpp @@ -29,8 +29,7 @@ namespace ark { class entity; -class container -{ +class container { public: virtual ~container() = default; diff --git a/src/plugins/kernel/container_impl.cpp b/src/plugins/kernel/container_impl.cpp index 08ed8209e..8e9d865bc 100644 --- a/src/plugins/kernel/container_impl.cpp +++ b/src/plugins/kernel/container_impl.cpp @@ -42,8 +42,7 @@ uint32_t container_impl::get_index() const { uint32_t container_impl::first() { iter_ = entity_data_list_.begin(); - if (entity_data_list_.end() == iter_) - { + if (entity_data_list_.end() == iter_) { return null_int; } @@ -51,14 +50,12 @@ uint32_t container_impl::first() { } uint32_t container_impl::next() { - if (entity_data_list_.end() == iter_) - { + if (entity_data_list_.end() == iter_) { return null_int; } ++iter_; - if (entity_data_list_.end() == iter_) - { + if (entity_data_list_.end() == iter_) { return null_int; } @@ -70,10 +67,8 @@ std::shared_ptr container_impl::find(uint32_t index) const { } uint32_t container_impl::find(const guid_t& id) const { - for (auto iter : entity_data_list_) - { - if (id == iter.second->get_id()) - { + for (auto iter : entity_data_list_) { + if (id == iter.second->get_id()) { return iter.first; } } @@ -100,20 +95,17 @@ bool container_impl::place(std::shared_ptr entity_ptr) { bool container_impl::place(uint32_t index, std::shared_ptr entity_ptr) { // class should be same - if (!entity_ptr || !container_meta_ || entity_ptr->get_class_name() != container_meta_->get_class_name()) - { + if (!entity_ptr || !container_meta_ || entity_ptr->get_class_name() != container_meta_->get_class_name()) { return false; } auto iter = entity_data_list_.find(index); - if (iter != entity_data_list_.end()) - { + if (iter != entity_data_list_.end()) { // has exist other entity return false; } - if (!place_entity(index, entity_ptr)) - { + if (!place_entity(index, entity_ptr)) { return false; } @@ -125,8 +117,7 @@ bool container_impl::swap(const uint32_t src_index, const uint32_t dest_index) { ARK_ASSERT_RET_VAL(src_index > 0u && dest_index > 0u && src_index != dest_index, false); auto iter_src = entity_data_list_.find(src_index); - if (iter_src == entity_data_list_.end()) - { + if (iter_src == entity_data_list_.end()) { // fail if source do not exist return false; } @@ -135,18 +126,14 @@ bool container_impl::swap(const uint32_t src_index, const uint32_t dest_index) { ARK_ASSERT_RET_VAL(src_entity_ptr != nullptr, false); auto iter_dest = entity_data_list_.find(dest_index); - if (iter_dest == entity_data_list_.end()) - { + if (iter_dest == entity_data_list_.end()) { entity_data_list_.erase(src_index); - if (!place_entity(dest_index, src_entity_ptr)) - { + if (!place_entity(dest_index, src_entity_ptr)) { return false; } on_container_swap(src_index, dest_index); - } - else - { + } else { // exchange auto dest_entity_ptr = iter_dest->second; iter_src->second = dest_entity_ptr; @@ -167,48 +154,38 @@ bool container_impl::swap(const guid_t& src_entity, const guid_t& dest_entity) { bool container_impl::swap( std::shared_ptr src_container_ptr, const uint32_t src_index, const uint32_t dest_index) { - if (src_container_ptr == nullptr || src_index == 0 || dest_index == 0) - { + if (src_container_ptr == nullptr || src_index == 0 || dest_index == 0) { return false; } auto src_entity_ptr = src_container_ptr->find(src_index); - if (src_entity_ptr == nullptr) - { + if (src_entity_ptr == nullptr) { return false; } // class should be same - if (!container_meta_ || src_entity_ptr->get_class_name() != container_meta_->get_class_name()) - { + if (!container_meta_ || src_entity_ptr->get_class_name() != container_meta_->get_class_name()) { return false; } - if (!src_container_ptr->remove(src_index)) - { + if (!src_container_ptr->remove(src_index)) { return false; } auto iter_dest = entity_data_list_.find(dest_index); - if (iter_dest == entity_data_list_.end()) - { - if (!place_entity(dest_index, src_entity_ptr)) - { + if (iter_dest == entity_data_list_.end()) { + if (!place_entity(dest_index, src_entity_ptr)) { return false; } on_container_place(dest_index, src_entity_ptr); - } - else - { + } else { auto dest_src_entity_ptr = iter_dest->second; - if (!remove(dest_index)) - { + if (!remove(dest_index)) { return false; } - if (!src_container_ptr->place(src_index, dest_src_entity_ptr) || !place_entity(dest_index, src_entity_ptr)) - { + if (!src_container_ptr->place(src_index, dest_src_entity_ptr) || !place_entity(dest_index, src_entity_ptr)) { return false; } @@ -220,8 +197,7 @@ bool container_impl::swap( bool container_impl::swap( std::shared_ptr src_container_ptr, const guid_t& src_entity, const guid_t& dest_entity) { - if (src_container_ptr == nullptr) - { + if (src_container_ptr == nullptr) { return false; } @@ -233,8 +209,7 @@ bool container_impl::swap( bool container_impl::remove(const uint32_t index) { auto entity_ptr = entity_data_list_.find_value(index); - if (nullptr == entity_ptr) - { + if (nullptr == entity_ptr) { return false; } @@ -251,8 +226,7 @@ bool container_impl::remove(const guid_t& id) { bool container_impl::destroy(const uint32_t index) { auto entity_ptr = entity_data_list_.find_value(index); - if (nullptr == entity_ptr) - { + if (nullptr == entity_ptr) { return false; } @@ -268,18 +242,13 @@ bool container_impl::destroy(const guid_t& id) { } uint32_t container_impl::select_index() const { - if (entity_data_list_.size() == current_index_) - { + if (entity_data_list_.size() == current_index_) { return current_index_ + 1; - } - else - { + } else { // index starts from 1 uint32_t index = 1u; - for (auto iter : entity_data_list_) - { - if (iter.first != index) - { + for (auto iter : entity_data_list_) { + if (iter.first != index) { break; } @@ -291,13 +260,11 @@ uint32_t container_impl::select_index() const { } bool container_impl::place_entity(const uint32_t index, std::shared_ptr entity_ptr) { - if (!entity_data_list_.insert(index, entity_ptr).second) - { + if (!entity_data_list_.insert(index, entity_ptr).second) { return false; } - if (current_index_ < index) - { + if (current_index_ < index) { current_index_ = index; } diff --git a/src/plugins/kernel/container_impl.hpp b/src/plugins/kernel/container_impl.hpp index 7c800a6b3..90679dd01 100644 --- a/src/plugins/kernel/container_impl.hpp +++ b/src/plugins/kernel/container_impl.hpp @@ -32,8 +32,7 @@ class snapshot_access; class container_impl final : public container - , public std::enable_shared_from_this -{ + , public std::enable_shared_from_this { public: using entity_data_list = shared_object_map; diff --git a/src/plugins/kernel/container_manager.hpp b/src/plugins/kernel/container_manager.hpp index 9cdc9b096..2b224b1ef 100644 --- a/src/plugins/kernel/container_manager.hpp +++ b/src/plugins/kernel/container_manager.hpp @@ -25,8 +25,7 @@ namespace ark { -class container_manager -{ +class container_manager { public: using container_list = shared_object_map; diff --git a/src/plugins/kernel/container_manager_impl.cpp b/src/plugins/kernel/container_manager_impl.cpp index 9121a730d..db0278702 100644 --- a/src/plugins/kernel/container_manager_impl.cpp +++ b/src/plugins/kernel/container_manager_impl.cpp @@ -31,8 +31,7 @@ std::shared_ptr container_manager_impl::create_container( std::shared_ptr class_meta_ptr, const uint32_t index, const guid_t& parent_id) { // return if found auto container_ptr = find_container(index); - if (nullptr != container_ptr) - { + if (nullptr != container_ptr) { return container_ptr; } diff --git a/src/plugins/kernel/container_manager_impl.hpp b/src/plugins/kernel/container_manager_impl.hpp index 3fa713fc7..d20c100f1 100644 --- a/src/plugins/kernel/container_manager_impl.hpp +++ b/src/plugins/kernel/container_manager_impl.hpp @@ -25,8 +25,7 @@ namespace ark { -class container_manager_impl final : public container_manager -{ +class container_manager_impl final : public container_manager { private: // container container_list container_data_; diff --git a/src/plugins/kernel/container_meta.hpp b/src/plugins/kernel/container_meta.hpp index a37e32019..bd8434015 100644 --- a/src/plugins/kernel/container_meta.hpp +++ b/src/plugins/kernel/container_meta.hpp @@ -22,8 +22,7 @@ namespace ark { -class container_meta final -{ +class container_meta final { private: // container name std::string name_{null_str}; diff --git a/src/plugins/kernel/data.hpp b/src/plugins/kernel/data.hpp index 301314e75..b20e2eeb9 100644 --- a/src/plugins/kernel/data.hpp +++ b/src/plugins/kernel/data.hpp @@ -31,8 +31,7 @@ namespace ark { -class data -{ +class data { public: data& operator=(const data& rhs) = delete; @@ -45,8 +44,7 @@ class data } inline static size_t get_raw_user_data_size(size_t size) { - if (size > std::numeric_limits::max() - sizeof(size_t)) - { + if (size > std::numeric_limits::max() - sizeof(size_t)) { throw std::length_error("Kernel user data size exceeds its header storage"); } return sizeof(size_t) + size; @@ -58,14 +56,12 @@ class data } bool equal(const data& src) { - if (this->get_type() != src.get_type()) - { + if (this->get_type() != src.get_type()) { return false; } bool success = false; - switch (this->get_type()) - { + switch (this->get_type()) { case data_type::dt_boolean: success = (get_bool() == src.get_bool()); break; @@ -111,8 +107,7 @@ class data } bool equal(const bool value) { - if (this->get_type() != data_type::dt_boolean) - { + if (this->get_type() != data_type::dt_boolean) { return false; } @@ -120,8 +115,7 @@ class data } bool equal(const int value) { - if (this->get_type() != data_type::dt_int32) - { + if (this->get_type() != data_type::dt_int32) { return false; } @@ -129,8 +123,7 @@ class data } bool equal(const int64_t value) { - if (this->get_type() != data_type::dt_int64) - { + if (this->get_type() != data_type::dt_int64) { return false; } @@ -138,8 +131,7 @@ class data } bool equal(const float value) { - if (this->get_type() != data_type::dt_float) - { + if (this->get_type() != data_type::dt_float) { return false; } @@ -147,8 +139,7 @@ class data } bool equal(const double value) { - if (this->get_type() != data_type::dt_double) - { + if (this->get_type() != data_type::dt_double) { return false; } @@ -156,8 +147,7 @@ class data } bool equal(const char* value) { - if (this->get_type() != data_type::dt_string) - { + if (this->get_type() != data_type::dt_string) { return false; } @@ -166,8 +156,7 @@ class data } bool equal(const void* value) { - if (this->get_type() != data_type::dt_pointer) - { + if (this->get_type() != data_type::dt_pointer) { return false; } diff --git a/src/plugins/kernel/data_impl.hpp b/src/plugins/kernel/data_impl.hpp index b677f2b65..2d5dd47f4 100644 --- a/src/plugins/kernel/data_impl.hpp +++ b/src/plugins/kernel/data_impl.hpp @@ -32,8 +32,7 @@ namespace ark { -class data_alloc_new_type -{ +class data_alloc_new_type { public: void* alloc(size_t size) { ARK_NEW_ARRAY_RET(char, size); @@ -49,8 +48,7 @@ class data_alloc_new_type }; template -class data_base final : public data -{ +class data_base final : public data { public: using self_t = data_base; @@ -70,8 +68,7 @@ class data_base final : public data data_base(const self_t& src) { this->type_ = src.type_; - switch (this->type_) - { + switch (this->type_) { case data_type::dt_boolean: bool_value_ = src.bool_value_; break; @@ -114,8 +111,7 @@ class data_base final : public data explicit data_base(const data& src) { this->type_ = src.get_type(); - switch (this->type_) - { + switch (this->type_) { case data_type::dt_boolean: bool_value_ = src.get_bool(); break; @@ -156,16 +152,14 @@ class data_base final : public data } bool from(const node* data_ptr) override { - if (data_ptr == nullptr) - { + if (data_ptr == nullptr) { return false; } self_t replacement; replacement.type_ = data_ptr->get_type(); - switch (replacement.type_) - { + switch (replacement.type_) { case data_type::dt_boolean: replacement.bool_value_ = data_ptr->get_bool(); break; @@ -285,31 +279,24 @@ class data_base final : public data char tmp_buffer[buffer_size] = {0}; bool tmp_use_buffer = (tmp_type == data_type::dt_string) && (this->string_value_ == this->inline_buffer_); - if (tmp_use_buffer) - { + if (tmp_use_buffer) { memcpy(tmp_buffer, this->inline_buffer_, buffer_size); } - if ((src.type_ == data_type::dt_string) && (src.string_value_ == src.inline_buffer_)) - { + if ((src.type_ == data_type::dt_string) && (src.string_value_ == src.inline_buffer_)) { memcpy(this->inline_buffer_, src.inline_buffer_, buffer_size); string_value_ = inline_buffer_; - } - else - { + } else { this->int64_value_ = src.int64_value_; allocated_length_ = src.allocated_length_; } this->type_ = src.type_; - if (tmp_use_buffer) - { + if (tmp_use_buffer) { memcpy(src.inline_buffer_, tmp_buffer, buffer_size); src.string_value_ = src.inline_buffer_; - } - else - { + } else { src.int64_value_ = tmp_value; src.allocated_length_ = tmp_alloc_len; } @@ -325,8 +312,7 @@ class data_base final : public data } void set_default_value(data_type type) override { - switch (type) - { + switch (type) { case data_type::dt_boolean: set_bool(null_boolean); break; @@ -358,8 +344,7 @@ class data_base final : public data } bool is_null_value() const override { - switch (get_type()) - { + switch (get_type()) { case data_type::dt_boolean: return bool_value_ == null_boolean; break; @@ -400,8 +385,7 @@ class data_base final : public data int get_int() const override { #if defined(ARK_USE_GUID_32) - if (type_ == data_type::dt_guid) - { + if (type_ == data_type::dt_guid) { return int_value_; } #endif @@ -411,8 +395,7 @@ class data_base final : public data int64_t get_int64() const override { #if !defined(ARK_USE_GUID_32) - if (type_ == data_type::dt_guid) - { + if (type_ == data_type::dt_guid) { return int64_value_; } #endif @@ -453,8 +436,7 @@ class data_base final : public data const void* get_user_data(size_t& size) const override { assert(type_ == data_type::dt_userdata); - if (type_ != data_type::dt_userdata) - { + if (type_ != data_type::dt_userdata) { size = 0; return nullptr; } @@ -545,24 +527,17 @@ class data_base final : public data size_t get_mem_usage() const override { size_t size = sizeof(self_t); - switch (type_) - { - case data_type::dt_string: - { - if (string_value_ != nullptr) - { + switch (type_) { + case data_type::dt_string: { + if (string_value_ != nullptr) { size += strlen(string_value_) + 1; } - } - break; - case data_type::dt_userdata: - { - if (user_data_ != nullptr) - { + } break; + case data_type::dt_userdata: { + if (user_data_ != nullptr) { size += data::get_user_data_size(user_data_); } - } - break; + } break; default: break; } @@ -571,8 +546,7 @@ class data_base final : public data } std::string to_string() const override { - switch (get_type()) - { + switch (get_type()) { case data_type::dt_boolean: return std::to_string(this->bool_value_); break; @@ -606,26 +580,19 @@ class data_base final : public data } void release() { - switch (type_) - { - case data_type::dt_string: - { - if (string_value_ != inline_buffer_) - { + switch (type_) { + case data_type::dt_string: { + if (string_value_ != inline_buffer_) { allocator_.free(string_value_, allocated_length_); string_value_ = nullptr; } - } - break; - case data_type::dt_userdata: - { - if (user_data_ != nullptr) - { + } break; + case data_type::dt_userdata: { + if (user_data_ != nullptr) { allocator_.free(user_data_, allocated_length_); user_data_ = nullptr; } - } - break; + } break; default: break; } @@ -634,24 +601,19 @@ class data_base final : public data protected: void inner_set_string(const char* value) { const size_t length = strlen(value); - if (length >= std::numeric_limits::max() && length >= buffer_size) - { + if (length >= std::numeric_limits::max() && length >= buffer_size) { throw std::length_error("Kernel string exceeds its storage length"); } const size_t value_size = length + 1; char* p = nullptr; - if (value_size > buffer_size) - { + if (value_size > buffer_size) { p = (char*)allocator_.alloc(value_size); - if (p == nullptr) - { + if (p == nullptr) { throw std::bad_alloc{}; } allocated_length_ = (uint32_t)value_size; - } - else - { + } else { p = inline_buffer_; } @@ -661,14 +623,12 @@ class data_base final : public data void inner_set_user_data(const void* data, size_t size) { constexpr size_t maximum = std::numeric_limits::max(); - if (size > maximum - sizeof(size_t)) - { + if (size > maximum - sizeof(size_t)) { throw std::length_error("Kernel user data exceeds its storage length"); } const size_t value_size = get_raw_user_data_size(size); char* p = (char*)allocator_.alloc(value_size); - if (p == nullptr) - { + if (p == nullptr) { throw std::bad_alloc{}; } init_raw_user_data(p, data, size); @@ -689,9 +649,7 @@ class data_base final : public data } private: - struct guid_tag - { - }; + struct guid_tag {}; data_base(guid_tag, const guid_t& value) : type_(data_type::dt_guid) @@ -720,8 +678,7 @@ class data_base final : public data data_type type_; // This union size is 8 bytes - union - { + union { bool bool_value_; int int_value_; uint32_t uint32_value_; @@ -735,8 +692,7 @@ class data_base final : public data }; // buffer - union - { + union { uint32_t allocated_length_{0}; char inline_buffer_[buffer_size]; }; diff --git a/src/plugins/kernel/data_list.hpp b/src/plugins/kernel/data_list.hpp index 598f79a7c..772ce66cd 100644 --- a/src/plugins/kernel/data_list.hpp +++ b/src/plugins/kernel/data_list.hpp @@ -27,8 +27,7 @@ namespace ark { -class data_list -{ +class data_list { public: virtual bool concat(const data_list& src) = 0; virtual bool split(const std::string& src, const std::string& split) = 0; @@ -81,18 +80,15 @@ class data_list int index = 0; - for (auto v : values) - { - if (v == data_type::dt_empty) - { + for (auto v : values) { + if (v == data_type::dt_empty) { success = false; return success; } data_type var_type = get_type(index); - if (var_type != v) - { + if (var_type != v) { success = false; break; } @@ -104,13 +100,11 @@ class data_list } bool to_afi_data(size_t index, data& source_data) const { - if (get_type(index) != source_data.get_type()) - { + if (get_type(index) != source_data.get_type()) { return false; } - switch (source_data.get_type()) - { + switch (source_data.get_type()) { case data_type::dt_boolean: source_data.set_bool(get_bool(index)); break; @@ -138,13 +132,11 @@ class data_list } bool equal(size_t index, const data& source_data) const { - if (get_type(index) != source_data.get_type()) - { + if (get_type(index) != source_data.get_type()) { return false; } - switch (source_data.get_type()) - { + switch (source_data.get_type()) { case data_type::dt_boolean: return source_data.get_bool() == get_bool(index); break; diff --git a/src/plugins/kernel/data_list_impl.hpp b/src/plugins/kernel/data_list_impl.hpp index 6e7a6e8b4..46c003496 100644 --- a/src/plugins/kernel/data_list_impl.hpp +++ b/src/plugins/kernel/data_list_impl.hpp @@ -31,8 +31,7 @@ namespace ark { -class data_list_alloc -{ +class data_list_alloc { public: void* alloc(size_t size) { ARK_NEW_ARRAY_RET(char, size); @@ -48,17 +47,14 @@ class data_list_alloc }; template -class base_data_list final : public data_list -{ +class base_data_list final : public data_list { private: using self_t = base_data_list; - struct dynamic_data_t - { + struct dynamic_data_t { data_type type; - union - { + union { bool bool_value; int int_value; uint32_t uint32_value; @@ -93,30 +89,24 @@ class base_data_list final : public data_list int begin = 0; int end = 0; - for (int i = 0; i < length; i++) - { - if (source[i] == separator) - { + for (int i = 0; i < length; i++) { + if (source[i] == separator) { end = i; - if (!add_string(&source[begin], end - begin)) - { + if (!add_string(&source[begin], end - begin)) { ARK_ASSERT_NO_EFFECT(0); } - if (i + 1 < length) - { + if (i + 1 < length) { begin = i + 1; } } } - if (end < length) - { + if (end < length) { end = length; - if (!add_string(&source[begin], end - begin)) - { + if (!add_string(&source[begin], end - begin)) { ARK_ASSERT_NO_EFFECT(0); } } @@ -138,8 +128,7 @@ class base_data_list final : public data_list } self_t operator=(const self_t& src) { - if (this == &src) - { + if (this == &src) { return *this; } release(); @@ -157,13 +146,11 @@ class base_data_list final : public data_list } void release() { - if (data_capacity_ > data_size) - { + if (data_capacity_ > data_size) { allocator_.free(data_, data_capacity_ * sizeof(dynamic_data_t)); } - if (buffer_capacity_ > buffer_size) - { + if (buffer_capacity_ > buffer_size) { allocator_.free(buffer_, buffer_capacity_ * sizeof(char)); } } @@ -177,8 +164,7 @@ class base_data_list final : public data_list clear(); std::string tmp(src); - if (tmp.empty()) - { + if (tmp.empty()) { return true; } @@ -187,11 +173,9 @@ class base_data_list final : public data_list tmp += tmp_split; std::string::size_type size = tmp.length(); - for (std::string::size_type i = 0; i < size; ++i) - { + for (std::string::size_type i = 0; i < size; ++i) { pos = int(tmp.find(tmp_split, i)); - if (pos < size) - { + if (pos < size) { std::string sub = tmp.substr(i, pos - i); add_string(sub.c_str()); @@ -208,15 +192,13 @@ class base_data_list final : public data_list } bool append(const data_list& src, size_t start, size_t count) override { - if (start >= src.get_count()) - { + if (start >= src.get_count()) { return false; } size_t end = start + count; - if (end > src.get_count()) - { + if (end > src.get_count()) { return false; } @@ -238,8 +220,7 @@ class base_data_list final : public data_list } data_type get_type(size_t index) const override { - if (index >= data_size_) - { + if (index >= data_size_) { return data_type::dt_empty; } @@ -299,8 +280,7 @@ class base_data_list final : public data_list bool add_string(const char* value) override { assert(value != nullptr); const size_t length = strlen(value); - if (length == std::numeric_limits::max()) - { + if (length == std::numeric_limits::max()) { throw std::length_error("Kernel data list string exceeds its storage length"); } const size_t value_size = length + 1; @@ -318,16 +298,14 @@ class base_data_list final : public data_list } virtual bool add_string(const char* value, const int length) { - if (length <= 0) - { + if (length <= 0) { return false; } assert(value != nullptr); size_t value_size = strlen(value); - if (value_size > (size_t)length) - { + if (value_size > (size_t)length) { value_size = (size_t)length; } @@ -375,299 +353,227 @@ class base_data_list final : public data_list // get data bool get_bool(size_t index) const override { - if (index > data_size_) - { + if (index > data_size_) { return null_boolean; } - if (data_[index].type == data_type::dt_boolean) - { + if (data_[index].type == data_type::dt_boolean) { return data_[index].bool_value; - } - else - { + } else { return null_boolean; } } int get_int(size_t index) const override { - if (index > data_size_) - { + if (index > data_size_) { return null_int; } - if (data_[index].type == data_type::dt_int32) - { + if (data_[index].type == data_type::dt_int32) { return data_[index].int_value; - } - else - { + } else { return null_int; } } int64_t int64(size_t index) const override { - if (index > data_size_) - { + if (index > data_size_) { return null_int64; } - if (data_[index].type == data_type::dt_int64) - { + if (data_[index].type == data_type::dt_int64) { return data_[index].int64_value; - } - else - { + } else { return null_int64; } } uint32_t u_int(size_t index) const override { - if (index > data_size_) - { + if (index > data_size_) { return null_int; } - if (data_[index].type == data_type::dt_uint32) - { + if (data_[index].type == data_type::dt_uint32) { return data_[index].uint32_value; - } - else - { + } else { return null_int; } } uint64_t u_int64(size_t index) const override { - if (index > data_size_) - { + if (index > data_size_) { return null_int64; } - if (data_[index].type == data_type::dt_uint64) - { + if (data_[index].type == data_type::dt_uint64) { return data_[index].uint64_value; - } - else - { + } else { return null_int64; } } float get_float(size_t index) const override { - if (index > data_size_) - { + if (index > data_size_) { return null_float; } - if (data_[index].type == data_type::dt_float) - { + if (data_[index].type == data_type::dt_float) { return data_[index].float_value; - } - else - { + } else { return null_float; } } double get_double(size_t index) const override { - if (index > data_size_) - { + if (index > data_size_) { return null_double; } - if (data_[index].type == data_type::dt_double) - { + if (data_[index].type == data_type::dt_double) { return data_[index].double_value; - } - else - { + } else { return null_double; } } const char* string(size_t index) const override { - if (index > data_size_) - { + if (index > data_size_) { return null_str.c_str(); } - if (data_[index].type == data_type::dt_string) - { + if (data_[index].type == data_type::dt_string) { return buffer_ + data_[index].string_offset; - } - else - { + } else { return null_str.c_str(); } } void* pointer(size_t index) const override { - if (index > data_size_) - { + if (index > data_size_) { return nullptr; } - if (data_[index].type == data_type::dt_pointer) - { + if (data_[index].type == data_type::dt_pointer) { return data_[index].pointer_value; - } - else - { + } else { return nullptr; } } const void* user_data(size_t index, size_t& size) const override { - if (index > data_size_) - { + if (index > data_size_) { size = 0; return nullptr; } - if (data_[index].type == data_type::dt_userdata) - { + if (data_[index].type == data_type::dt_userdata) { char* p = buffer_ + data_[index].user_data_offset; size = data::get_user_data_size(p); return data::get_user_data(p); - } - else - { + } else { size = 0; return nullptr; } } void* raw_user_data(size_t index) const override { - if (index > data_size_) - { + if (index > data_size_) { return nullptr; } - if (data_[index].type == data_type::dt_userdata) - { + if (data_[index].type == data_type::dt_userdata) { return buffer_ + data_[index].user_data_offset; - } - else - { + } else { return nullptr; } } virtual bool set_bool(size_t index, bool value) { - if (index >= data_size_) - { + if (index >= data_size_) { return false; } - if (data_[index].type != data_type::dt_boolean) - { + if (data_[index].type != data_type::dt_boolean) { return false; - } - else - { + } else { data_[index].bool_value = value; return true; } } virtual bool set_int(size_t index, int value) { - if (index >= data_size_) - { + if (index >= data_size_) { return false; } - if (data_[index].type != data_type::dt_int32) - { + if (data_[index].type != data_type::dt_int32) { return false; - } - else - { + } else { data_[index].int_value = value; return true; } } virtual bool set_int64(size_t index, int64_t value) { - if (index >= data_size_) - { + if (index >= data_size_) { return false; } - if (data_[index].type != data_type::dt_int64) - { + if (data_[index].type != data_type::dt_int64) { return false; - } - else - { + } else { data_[index].int64_value = value; return true; } } virtual bool set_u_int(size_t index, uint32_t value) { - if (index >= data_size_) - { + if (index >= data_size_) { return false; } - if (data_[index].type != data_type::dt_uint32) - { + if (data_[index].type != data_type::dt_uint32) { return false; - } - else - { + } else { data_[index].uint32_value = value; return true; } } virtual bool set_u_int64(size_t index, uint64_t value) { - if (index >= data_size_) - { + if (index >= data_size_) { return false; } - if (data_[index].type != data_type::dt_uint64) - { + if (data_[index].type != data_type::dt_uint64) { return false; - } - else - { + } else { data_[index].uint64_value = value; return true; } } virtual bool set_float(size_t index, float value) { - if (index >= data_size_) - { + if (index >= data_size_) { return false; } - if (data_[index].type != data_type::dt_float) - { + if (data_[index].type != data_type::dt_float) { return false; - } - else - { + } else { data_[index].float_value = value; return true; } } virtual bool set_double(size_t index, double value) { - if (index >= data_size_) - { + if (index >= data_size_) { return false; } - if (data_[index].type != data_type::dt_double) - { + if (data_[index].type != data_type::dt_double) { return false; - } - else - { + } else { data_[index].double_value = value; return true; } @@ -676,26 +582,22 @@ class base_data_list final : public data_list virtual bool set_string(size_t index, const char* value) { assert(value != nullptr); - if (index >= data_size_) - { + if (index >= data_size_) { return false; } - if (data_[index].type != data_type::dt_string) - { + if (data_[index].type != data_type::dt_string) { return false; } char* p = buffer_ + data_[index].string_offset; const size_t length = strlen(value); - if (length == std::numeric_limits::max()) - { + if (length == std::numeric_limits::max()) { throw std::length_error("Kernel data list string exceeds its storage length"); } const size_t size1 = length + 1; - if (size1 <= (strlen(p) + 1)) - { + if (size1 <= (strlen(p) + 1)) { ARK_STRNCPY(p, value, size1); return true; } @@ -709,31 +611,25 @@ class base_data_list final : public data_list } virtual bool set_pointer(size_t index, void* value) { - if (index >= data_size_) - { + if (index >= data_size_) { return false; } - if (data_[index].type != data_type::dt_pointer) - { + if (data_[index].type != data_type::dt_pointer) { return false; - } - else - { + } else { data_[index].pointer_value = value; return true; } } const std::string to_string(size_t index) override { - if (index > data_size_) - { + if (index > data_size_) { return null_str; } std::string data; - switch (data_[index].type) - { + switch (data_[index].type) { case data_type::dt_boolean: data = std::to_string(data_[index].bool_value); break; @@ -773,13 +669,11 @@ class base_data_list final : public data_list size_t get_mem_usage() const override { size_t size = sizeof(self_t); - if (data_capacity_ > data_size) - { + if (data_capacity_ > data_size) { size += sizeof(dynamic_data_t) * data_capacity_; } - if (buffer_capacity_ > buffer_size) - { + if (buffer_capacity_ > buffer_size) { size += sizeof(char) * buffer_capacity_; } @@ -788,23 +682,19 @@ class base_data_list final : public data_list protected: void reserve_dynamic_data() { - if (data_size_ >= data_capacity_) - { + if (data_size_ >= data_capacity_) { constexpr size_t maximum = std::numeric_limits::max() / sizeof(dynamic_data_t); - if (data_capacity_ > maximum / 2) - { + if (data_capacity_ > maximum / 2) { throw std::length_error("Kernel data list exceeds its index storage"); } size_t new_size = data_capacity_ * 2; dynamic_data_t* p = (dynamic_data_t*)allocator_.alloc(new_size * sizeof(dynamic_data_t)); - if (p == nullptr) - { + if (p == nullptr) { throw std::bad_alloc{}; } memcpy(p, data_, data_size_ * sizeof(dynamic_data_t)); - if (data_capacity_ > data_size) - { + if (data_capacity_ > data_size) { allocator_.free(data_, data_capacity_ * sizeof(dynamic_data_t)); } @@ -820,24 +710,19 @@ class base_data_list final : public data_list size_t buffer_capacity_for(size_t need_size) const { constexpr size_t maximum = std::numeric_limits::max(); - if (need_size > maximum - buffer_size_) - { + if (need_size > maximum - buffer_size_) { throw std::length_error("Kernel data list exceeds its buffer storage"); } const size_t new_used = buffer_size_ + need_size; - if (new_used <= buffer_capacity_) - { + if (new_used <= buffer_capacity_) { return buffer_capacity_; } - if (buffer_capacity_ > maximum / 2) - { + if (buffer_capacity_ > maximum / 2) { throw std::length_error("Kernel data list buffer growth exceeds its storage length"); } size_t new_size = buffer_capacity_ * 2; - if (new_used > new_size) - { - if (new_used > maximum / 2) - { + if (new_used > new_size) { + if (new_used > maximum / 2) { throw std::length_error("Kernel data list buffer growth exceeds its storage length"); } new_size = new_used * 2; @@ -848,17 +733,14 @@ class base_data_list final : public data_list char* add_buffer(size_t need_size) { const size_t new_size = buffer_capacity_for(need_size); const size_t new_used = buffer_size_ + need_size; - if (new_size > buffer_capacity_) - { + if (new_size > buffer_capacity_) { char* p = (char*)allocator_.alloc(new_size); - if (p == nullptr) - { + if (p == nullptr) { throw std::bad_alloc{}; } memcpy(p, buffer_, buffer_size_); - if (buffer_capacity_ > buffer_size) - { + if (buffer_capacity_ > buffer_size) { allocator_.free(buffer_, buffer_capacity_); } @@ -874,8 +756,7 @@ class base_data_list final : public data_list void inner_append(const data& data) { bool success(false); - switch (data.get_type()) - { + switch (data.get_type()) { case data_type::dt_boolean: success = add_bool(data.get_bool()); break; @@ -903,13 +784,11 @@ class base_data_list final : public data_list case data_type::dt_pointer: success = add_pointer(data.get_pointer()); break; - case data_type::dt_userdata: - { + case data_type::dt_userdata: { size_t size; const void* data_ptr = data.get_user_data(size); success = add_user_data(data_ptr, size); - } - break; + } break; default: ARK_ASSERT_NO_EFFECT(0); break; @@ -921,10 +800,8 @@ class base_data_list final : public data_list bool inner_append(const data_list& src, size_t start, size_t end) { bool success(false); - for (size_t i = start; i < end; ++i) - { - switch (src.get_type(i)) - { + for (size_t i = start; i < end; ++i) { + switch (src.get_type(i)) { case data_type::dt_boolean: success = add_bool(src.get_bool(i)); break; @@ -952,13 +829,11 @@ class base_data_list final : public data_list case data_type::dt_pointer: success = add_pointer(src.pointer(i)); break; - case data_type::dt_userdata: - { + case data_type::dt_userdata: { size_t size; const void* data_ptr = src.user_data(i, size); success = add_user_data(data_ptr, size); - } - break; + } break; default: ARK_ASSERT_NO_EFFECT(0); break; diff --git a/src/plugins/kernel/detail/entity_json_runtime.hpp b/src/plugins/kernel/detail/entity_json_runtime.hpp index 8be7a08ac..dd362dede 100644 --- a/src/plugins/kernel/detail/entity_json_runtime.hpp +++ b/src/plugins/kernel/detail/entity_json_runtime.hpp @@ -19,8 +19,7 @@ inline std::string entity_json_file() { inline data_type entity_json_type(entity_json::value_type type) { using type_t = entity_json::value_type; - switch (type) - { + switch (type) { case type_t::boolean: return data_type::dt_boolean; case type_t::int32: @@ -44,11 +43,9 @@ inline data_type entity_json_type(entity_json::value_type type) { } inline void entity_json_fields(const entity_json::class_definition& schema, const std::shared_ptr& meta) { - for (const auto& field : schema.fields) - { + for (const auto& field : schema.fields) { const auto member = meta->create_data_meta(field.name, field.index); - if (!member) - { + if (!member) { throw entity_json::error(entity_json_file(), "/classes/" + schema.name, "could not create field metadata"); } member->set_type(entity_json_type(field.type)); @@ -57,23 +54,19 @@ inline void entity_json_fields(const entity_json::class_definition& schema, cons } inline void load_entity_json_metadata(class_meta_manager& manager, const entity_json::document& document) { - for (const auto& schema : document.classes) - { + for (const auto& schema : document.classes) { const auto meta = manager.create_meta(schema.name); entity_json_fields(schema, meta); - for (const auto& table : schema.tables) - { + for (const auto& table : schema.tables) { const auto member = meta->create_table_meta(table.name, table.index); member->set_type_name(table.class_name); member->set_mask(table.mask); } - for (const auto& container : schema.containers) - { + for (const auto& container : schema.containers) { meta->create_container_meta(container.name, container.index, container.class_name, container.mask); } } - for (std::size_t i = 0; const auto& config : document.configs) - { + for (std::size_t i = 0; const auto& config : document.configs) { const auto schema = std::find_if(document.classes.begin(), document.classes.end(), [&](const auto& schema) { return schema.name == config.class_name; }); const auto meta = manager.create_static_meta(config.class_name); @@ -81,15 +74,13 @@ inline void load_entity_json_metadata(class_meta_manager& manager, const entity_ meta->set_json_config( std::make_shared(config), "/configs/" + std::to_string(i++)); } - if (!manager.after_loaded()) - { + if (!manager.after_loaded()) { throw entity_json::error(entity_json_file(), "/classes", "could not resolve table metadata"); } } inline void assign_entity_json(node& node, const entity_json::value& value, const std::string& pointer) { - switch (node.get_type()) - { + switch (node.get_type()) { case data_type::dt_boolean: node.set_bool(std::get(value)); break; @@ -114,13 +105,11 @@ inline void assign_entity_json(node& node, const entity_json::value& value, cons case data_type::dt_string: node.set_string(std::get(value)); break; - case data_type::dt_guid: - { + case data_type::dt_guid: { const auto& text = std::get(value); guid_t guid{}; const auto parsed = std::from_chars(text.data(), text.data() + text.size(), guid); - if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size()) - { + if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size()) { throw entity_json::error(entity_json_file(), pointer, "GUID exceeds the configured runtime width"); } node.set_object(guid); @@ -133,16 +122,13 @@ inline void assign_entity_json(node& node, const entity_json::value& value, cons inline void load_entity_json_config(static_entity_manager& manager, const std::shared_ptr& meta, const entity_json::config_definition& config) { - for (std::size_t j = 0; const auto& row : config.rows) - { + for (std::size_t j = 0; const auto& row : config.rows) { const auto pointer = meta->get_json_config_pointer() + "/rows/" + std::to_string(j++); const auto nodes = std::make_shared(meta); - for (const auto& [name, value] : row) - { + for (const auto& [name, value] : row) { const auto index = meta->get_index(name); const auto field = meta->find_data_meta(index); - if (!field) - { + if (!field) { throw entity_json::error( entity_json_file(), pointer + "/" + name, "selected schema changed during startup"); } @@ -150,8 +136,7 @@ inline void load_entity_json_config(static_entity_manager& manager, const std::s assign_entity_json(*node, value, pointer + "/" + name); } const auto id = static_cast(std::get(row.at("id"))); - if (!manager.create_static_entity(meta, nodes, id)) - { + if (!manager.create_static_entity(meta, nodes, id)) { throw entity_json::error( entity_json_file(), pointer + "/id", "could not create static configuration entity"); } diff --git a/src/plugins/kernel/detail/incarnation.hpp b/src/plugins/kernel/detail/incarnation.hpp index c946a48ea..6e13a614b 100644 --- a/src/plugins/kernel/detail/incarnation.hpp +++ b/src/plugins/kernel/detail/incarnation.hpp @@ -12,14 +12,11 @@ namespace ark::detail { // durable identity service. Never wrap or recycle an allocated incarnation. inline std::uint64_t next_incarnation(std::atomic& counter) { auto previous = counter.load(std::memory_order_relaxed); - for (;;) - { - if (previous == std::numeric_limits::max()) - { + for (;;) { + if (previous == std::numeric_limits::max()) { throw std::overflow_error("Entity incarnation exhausted; start a new implementation lifetime"); } - if (counter.compare_exchange_weak(previous, previous + 1, std::memory_order_relaxed)) - { + if (counter.compare_exchange_weak(previous, previous + 1, std::memory_order_relaxed)) { return previous + 1; } } diff --git a/src/plugins/kernel/entity.hpp b/src/plugins/kernel/entity.hpp index 19e9d2df0..3ee36ef14 100644 --- a/src/plugins/kernel/entity.hpp +++ b/src/plugins/kernel/entity.hpp @@ -30,8 +30,7 @@ namespace ark { class container; -class entity -{ +class entity { public: virtual ~entity() = default; diff --git a/src/plugins/kernel/entity_impl.cpp b/src/plugins/kernel/entity_impl.cpp index b418804a4..13c2e79c3 100644 --- a/src/plugins/kernel/entity_impl.cpp +++ b/src/plugins/kernel/entity_impl.cpp @@ -197,8 +197,7 @@ int32_t entity_impl::get_map_entity_id() const { bool entity_impl::switch_scene(const int32_t map_id, const int32_t map_inst_id, const vector3d& pos) { ARK_ASSERT_RET_VAL(callback_manager_ != nullptr && opt_charactor_ != nullptr, false); - if (opt_charactor_->map_id == map_id && opt_charactor_->map_entity_id == map_inst_id) - { + if (opt_charactor_->map_id == map_id && opt_charactor_->map_entity_id == map_inst_id) { return false; } @@ -246,8 +245,7 @@ float entity_impl::get_orient() const { bool entity_impl::set_position(const vector3d& position, const float orient) { ARK_ASSERT_RET_VAL(callback_manager_ != nullptr && opt_charactor_ != nullptr, false); - if (opt_charactor_->pos == position && opt_charactor_->orient == orient) - { + if (opt_charactor_->pos == position && opt_charactor_->orient == orient) { return false; } @@ -265,8 +263,7 @@ bool entity_impl::set_position(const float x, const float y, const float z, cons ARK_ASSERT_RET_VAL(callback_manager_ != nullptr && opt_charactor_ != nullptr, false); if (opt_charactor_->pos.x == x && opt_charactor_->pos.y == y && opt_charactor_->pos.z == z && - opt_charactor_->orient == orient) - { + opt_charactor_->orient == orient) { return false; } @@ -557,8 +554,7 @@ std::shared_ptr entity_impl::find_container(const uint32_t index) { ARK_ASSERT_RET_VAL(container_manager_ptr != nullptr, nullptr); auto container_ptr = container_manager_ptr->find_container(index); - if (container_ptr == nullptr) - { + if (container_ptr == nullptr) { // create a new container container_ptr = container_manager_ptr->create_container(class_meta_, index, guid_); } @@ -578,8 +574,7 @@ table* entity_impl::find_table(const std::string& name) { table* entity_impl::find_table(const uint32_t index) { auto table_ptr = table_manager_->find_table(index); - if (nullptr == table_ptr) - { + if (nullptr == table_ptr) { auto func = std::bind_front(&entity_impl::on_table_call_back, this); table_ptr = table_manager_->create_table(index, std::move(func)); } @@ -634,8 +629,7 @@ bool entity_impl::add_custom_bool(const std::string& name, bool value) { ARK_ASSERT_RET_VAL(data_ptr != nullptr, false); data_ptr->set_bool(value); - if (!custom_data_list_.insert(name, data_ptr.get()).second) - { + if (!custom_data_list_.insert(name, data_ptr.get()).second) { return false; } @@ -651,8 +645,7 @@ bool entity_impl::add_custom_int32(const std::string& name, const int32_t value) ARK_ASSERT_RET_VAL(data_ptr != nullptr, false); data_ptr->set_int(value); - if (!custom_data_list_.insert(name, data_ptr.get()).second) - { + if (!custom_data_list_.insert(name, data_ptr.get()).second) { return false; } @@ -668,8 +661,7 @@ bool entity_impl::add_custom_u_int32(const std::string& name, const uint32_t val ARK_ASSERT_RET_VAL(data_ptr != nullptr, false); data_ptr->set_u_int(value); - if (!custom_data_list_.insert(name, data_ptr.get()).second) - { + if (!custom_data_list_.insert(name, data_ptr.get()).second) { return false; } @@ -685,8 +677,7 @@ bool entity_impl::add_custom_int64(const std::string& name, const int64_t value) ARK_ASSERT_RET_VAL(data_ptr != nullptr, false); data_ptr->set_int64(value); - if (!custom_data_list_.insert(name, data_ptr.get()).second) - { + if (!custom_data_list_.insert(name, data_ptr.get()).second) { return false; } @@ -702,8 +693,7 @@ bool entity_impl::add_custom_float(const std::string& name, const float value) { ARK_ASSERT_RET_VAL(data_ptr != nullptr, false); data_ptr->set_float(value); - if (!custom_data_list_.insert(name, data_ptr.get()).second) - { + if (!custom_data_list_.insert(name, data_ptr.get()).second) { return false; } @@ -719,8 +709,7 @@ bool entity_impl::add_custom_double(const std::string& name, const double value) ARK_ASSERT_RET_VAL(data_ptr != nullptr, false); data_ptr->set_double(value); - if (!custom_data_list_.insert(name, data_ptr.get()).second) - { + if (!custom_data_list_.insert(name, data_ptr.get()).second) { return false; } @@ -736,8 +725,7 @@ bool entity_impl::add_custom_string(const std::string& name, const std::string& ARK_ASSERT_RET_VAL(data_ptr != nullptr, false); data_ptr->set_string(value.c_str()); - if (!custom_data_list_.insert(name, data_ptr.get()).second) - { + if (!custom_data_list_.insert(name, data_ptr.get()).second) { return false; } @@ -777,8 +765,7 @@ bool entity_impl::set_custom_int32(const std::string& name, const int32_t value) bool entity_impl::set_custom_u_int32(const std::string& name, const uint32_t value) { auto* data_ptr = custom_data_list_.find_value(name); - if (data_ptr == nullptr || data_ptr->get_type() != data_type::dt_uint32) - { + if (data_ptr == nullptr || data_ptr->get_type() != data_type::dt_uint32) { return false; } diff --git a/src/plugins/kernel/entity_impl.hpp b/src/plugins/kernel/entity_impl.hpp index f0cf81c02..9b0a887c2 100644 --- a/src/plugins/kernel/entity_impl.hpp +++ b/src/plugins/kernel/entity_impl.hpp @@ -40,8 +40,7 @@ namespace entity_sync { class snapshot_access; } -class entity_opt_charactor -{ +class entity_opt_charactor { public: entity_opt_charactor(const int32_t map_id, const int32_t map_entity_id) : map_id(map_id) @@ -65,8 +64,7 @@ class entity_opt_charactor std::shared_ptr containers{nullptr}; }; -class entity_impl final : public entity -{ +class entity_impl final : public entity { private: friend class kernel_module_impl; friend class entity_sync::snapshot_access; diff --git a/src/plugins/kernel/entity_json.cpp b/src/plugins/kernel/entity_json.cpp index b1fa258b2..0d7e7b8a2 100644 --- a/src/plugins/kernel/entity_json.cpp +++ b/src/plugins/kernel/entity_json.cpp @@ -23,18 +23,12 @@ using json = nlohmann::json; std::string escaped(std::string_view text) { std::string result; - for (const auto character : text) - { - if (character == '~') - { + for (const auto character : text) { + if (character == '~') { result += "~0"; - } - else if (character == '/') - { + } else if (character == '/') { result += "~1"; - } - else - { + } else { result += character; } } @@ -43,14 +37,11 @@ std::string escaped(std::string_view text) { void keys(const json& input, std::initializer_list allowed, std::string_view source, const std::string& pointer) { - if (!input.is_object()) - { + if (!input.is_object()) { fail(source, pointer, "expected an object"); } - for (auto entry = input.begin(); entry != input.end(); ++entry) - { - if (std::find(allowed.begin(), allowed.end(), entry.key()) == allowed.end()) - { + for (auto entry = input.begin(); entry != input.end(); ++entry) { + if (std::find(allowed.begin(), allowed.end(), entry.key()) == allowed.end()) { fail(source, pointer + "/" + escaped(entry.key()), "unknown key"); } } @@ -58,29 +49,25 @@ void keys(const json& input, std::initializer_list allowed, st const json& required(const json& input, std::string_view key, std::string_view source, const std::string& pointer) { const auto found = input.find(std::string(key)); - if (found == input.end()) - { + if (found == input.end()) { fail(source, pointer + "/" + std::string(key), "required value is missing"); } return *found; } const json& array(const json& input, std::string_view source, const std::string& pointer) { - if (!input.is_array()) - { + if (!input.is_array()) { fail(source, pointer, "expected an array"); } return input; } std::string text(const json& input, std::string_view source, const std::string& pointer, bool empty = false) { - if (!input.is_string()) - { + if (!input.is_string()) { fail(source, pointer, "expected a string"); } auto result = input.get(); - if ((!empty && result.empty()) || result.find('\0') != std::string::npos) - { + if ((!empty && result.empty()) || result.find('\0') != std::string::npos) { fail(source, pointer, "expected a nonempty string without NUL bytes"); } return result; @@ -89,13 +76,11 @@ std::string text(const json& input, std::string_view source, const std::string& std::uint64_t unsigned_integer( const json& input, std::uint64_t maximum, std::string_view source, const std::string& pointer) { if (!input.is_number_integer() || - (input.is_number_integer() && !input.is_number_unsigned() && input.get() < 0)) - { + (input.is_number_integer() && !input.is_number_unsigned() && input.get() < 0)) { fail(source, pointer, "expected an unsigned integer"); } const auto number = input.get(); - if (number > maximum) - { + if (number > maximum) { fail(source, pointer, "integer is outside the declared range"); } return number; @@ -103,28 +88,23 @@ std::uint64_t unsigned_integer( std::int64_t signed_integer(const json& input, std::int64_t minimum, std::int64_t maximum, std::string_view source, const std::string& pointer) { - if (!input.is_number_integer()) - { + if (!input.is_number_integer()) { fail(source, pointer, "expected an integer"); } - if (input.is_number_unsigned() && input.get() > static_cast(maximum)) - { + if (input.is_number_unsigned() && input.get() > static_cast(maximum)) { fail(source, pointer, "integer is outside the declared range"); } const auto number = input.get(); - if (number < minimum || number > maximum) - { + if (number < minimum || number > maximum) { fail(source, pointer, "integer is outside the declared range"); } return number; } value scalar(const json& input, value_type type, std::string_view source, const std::string& pointer) { - switch (type) - { + switch (type) { case value_type::boolean: - if (!input.is_boolean()) - { + if (!input.is_boolean()) { fail(source, pointer, "expected a boolean"); } return input.get(); @@ -137,31 +117,26 @@ value scalar(const json& input, value_type type, std::string_view source, const case value_type::uint64: return unsigned_integer(input, UINT64_MAX, source, pointer); case value_type::float32: - case value_type::float64: - { - if (!input.is_number()) - { + case value_type::float64: { + if (!input.is_number()) { fail(source, pointer, "expected a finite number"); } const auto number = input.get(); if (!std::isfinite(number) || (type == value_type::float32 && (std::abs(number) > std::numeric_limits::max() || - (number != 0 && static_cast(number) == 0)))) - { + (number != 0 && static_cast(number) == 0)))) { fail(source, pointer, "number is outside the declared finite range"); } return type == value_type::float32 ? static_cast(static_cast(number)) : number; } case value_type::string: return text(input, source, pointer, true); - case value_type::guid: - { + case value_type::guid: { const auto result = text(input, source, pointer); std::int64_t number = 0; const auto converted = std::from_chars(result.data(), result.data() + result.size(), number); if (converted.ec != std::errc{} || converted.ptr != result.data() + result.size() || - std::to_string(number) != result) - { + std::to_string(number) != result) { fail(source, pointer, "expected a canonical signed 64-bit decimal GUID string"); } return result; @@ -172,18 +147,15 @@ value scalar(const json& input, value_type type, std::string_view source, const std::bitset<16> mask(const json& input, std::string_view source, const std::string& pointer) { std::bitset<16> result; - for (std::size_t i = 0; const auto& item : array(input, source, pointer)) - { + for (std::size_t i = 0; const auto& item : array(input, source, pointer)) { const auto location = pointer + "/" + std::to_string(i++); const auto name = text(item, source, location); const auto found = std::find(mask_names.begin(), mask_names.end(), name); - if (found == mask_names.end()) - { + if (found == mask_names.end()) { fail(source, location, "unknown mask name"); } const auto bit = static_cast(found - mask_names.begin()); - if (result.test(bit)) - { + if (result.test(bit)) { fail(source, location, "duplicate mask name"); } result.set(bit); @@ -197,31 +169,25 @@ void declaration(const json& input, std::string& name, std::uint32_t& index, std name = text(required(input, "name", source, pointer), source, pointer + "/name"); index = static_cast( unsigned_integer(required(input, "index", source, pointer), UINT32_MAX, source, pointer + "/index")); - if (index == 0) - { + if (index == 0) { fail(source, pointer + "/index", "field indices start at one"); } - if (!names.insert(name).second) - { + if (!names.insert(name).second) { fail(source, pointer + "/name", "duplicate member name"); } - if (!indices.insert(index).second) - { + if (!indices.insert(index).second) { fail(source, pointer + "/index", "duplicate member index"); } - if (input.contains("mask")) - { + if (input.contains("mask")) { flags = mask(input["mask"], source, pointer + "/mask"); } - if (input.contains("description")) - { + if (input.contains("description")) { description = text(input["description"], source, pointer + "/description", true); } } json strict_json(std::string_view input, std::string_view source) { - struct level - { + struct level { std::string path; std::string key; std::size_t next{0}; @@ -231,59 +197,45 @@ json strict_json(std::string_view input, std::string_view source) { std::vector levels; const auto child = [&levels]() { - if (levels.empty()) - { + if (levels.empty()) { return std::string{}; } auto& parent = levels.back(); return parent.path + "/" + (parent.object ? escaped(parent.key) : std::to_string(parent.next++)); }; - try - { + try { return json::parse(input.begin(), input.end(), [&](int depth, json::parse_event_t event, json& parsed) { - if (depth > 64) - { + if (depth > 64) { fail(source, levels.empty() ? "/" : levels.back().path, "JSON nesting exceeds 64 levels"); } - if (event == json::parse_event_t::object_start || event == json::parse_event_t::array_start) - { + if (event == json::parse_event_t::object_start || event == json::parse_event_t::array_start) { levels.push_back({child(), {}, 0, event == json::parse_event_t::object_start, {}}); - } - else if (event == json::parse_event_t::object_end || event == json::parse_event_t::array_end) - { + } else if (event == json::parse_event_t::object_end || event == json::parse_event_t::array_end) { levels.pop_back(); - } - else if (event == json::parse_event_t::key) - { + } else if (event == json::parse_event_t::key) { auto& current = levels.back(); current.key = parsed.get(); - if (!current.keys.insert(current.key).second) - { + if (!current.keys.insert(current.key).second) { fail(source, current.path + "/" + escaped(current.key), "duplicate object key"); } - } - else if (event == json::parse_event_t::value && !levels.empty() && !levels.back().object) - { + } else if (event == json::parse_event_t::value && !levels.empty() && !levels.back().object) { ++levels.back().next; } return true; }); + } catch (const json::exception& exception) { + fail(source, "/", std::string("invalid JSON: ") + exception.what()); } - catch (const json::exception& exception) - { fail(source, "/", std::string("invalid JSON: ") + exception.what()); } } json encode(const document& input) { const auto encode_mask = [](const std::bitset<16>& flags) { - if ((flags >> mask_names.size()).any()) - { + if ((flags >> mask_names.size()).any()) { throw std::invalid_argument("unsupported mask bits"); } json output = json::array(); - for (std::size_t i = 0; i < mask_names.size(); ++i) - { - if (flags.test(i)) - { + for (std::size_t i = 0; i < mask_names.size(); ++i) { + if (flags.test(i)) { output.push_back(mask_names[i]); } } @@ -291,31 +243,25 @@ json encode(const document& input) { }; json output{ {"format", "ark.entity-schema"}, {"version", 1}, {"classes", json::array()}, {"configs", json::array()}}; - for (const auto& definition : input.classes) - { + for (const auto& definition : input.classes) { json item{{"name", definition.name}, {"fields", json::array()}, {"tables", json::array()}, {"containers", json::array()}}; - if (!definition.description.empty()) - { + if (!definition.description.empty()) { item["description"] = definition.description; } - for (const auto& member : definition.fields) - { + for (const auto& member : definition.fields) { json field{{"name", member.name}, {"index", member.index}, {"type", type_name(member.type)}, {"mask", encode_mask(member.mask)}}; - if (!member.description.empty()) - { + if (!member.description.empty()) { field["description"] = member.description; } item["fields"].push_back(std::move(field)); } const auto relations = [&](const std::vector& members, const char* key) { - for (const auto& member : members) - { + for (const auto& member : members) { json relation{{"name", member.name}, {"index", member.index}, {"class", member.class_name}, {"mask", encode_mask(member.mask)}}; - if (!member.description.empty()) - { + if (!member.description.empty()) { relation["description"] = member.description; } item[key].push_back(std::move(relation)); @@ -325,14 +271,11 @@ json encode(const document& input) { relations(definition.containers, "containers"); output["classes"].push_back(std::move(item)); } - for (const auto& definition : input.configs) - { + for (const auto& definition : input.configs) { json rows = json::array(); - for (const auto& values : definition.rows) - { + for (const auto& values : definition.rows) { json row = json::object(); - for (const auto& [name, scalar] : values) - { + for (const auto& [name, scalar] : values) { row[name] = std::visit([](const auto& value) -> json { return value; }, scalar); } rows.push_back(std::move(row)); @@ -358,8 +301,7 @@ const std::string& error::pointer() const noexcept { } std::string_view type_name(value_type type) { - switch (type) - { + switch (type) { case value_type::boolean: return "bool"; case value_type::int32: @@ -384,10 +326,8 @@ std::string_view type_name(value_type type) { value_type parse_type(std::string_view name, std::string_view source, std::string_view pointer) { for (const auto type : {value_type::boolean, value_type::int32, value_type::uint32, value_type::int64, - value_type::uint64, value_type::float32, value_type::float64, value_type::string, value_type::guid}) - { - if (name == type_name(type)) - { + value_type::uint64, value_type::float32, value_type::float64, value_type::string, value_type::guid}) { + if (name == type_name(type)) { return type; } } @@ -397,35 +337,30 @@ value_type parse_type(std::string_view name, std::string_view source, std::strin document parse(std::string_view text_input, std::string_view source) { const auto input = strict_json(text_input, source); keys(input, {"format", "version", "classes", "configs"}, source, ""); - if (required(input, "format", source, "") != "ark.entity-schema") - { + if (required(input, "format", source, "") != "ark.entity-schema") { fail(source, "/format", "expected ark.entity-schema"); } - if (unsigned_integer(required(input, "version", source, ""), UINT32_MAX, source, "/version") != 1) - { + if (unsigned_integer(required(input, "version", source, ""), UINT32_MAX, source, "/version") != 1) { fail(source, "/version", "unsupported format version"); } document result; std::map class_names; - for (std::size_t i = 0; const auto& definition : array(required(input, "classes", source, ""), source, "/classes")) - { + for (std::size_t i = 0; + const auto& definition : array(required(input, "classes", source, ""), source, "/classes")) { const auto pointer = "/classes/" + std::to_string(i++); keys(definition, {"name", "fields", "tables", "containers", "description"}, source, pointer); class_definition item; item.name = text(required(definition, "name", source, pointer), source, pointer + "/name"); - if (!class_names.emplace(item.name, result.classes.size()).second) - { + if (!class_names.emplace(item.name, result.classes.size()).second) { fail(source, pointer + "/name", "duplicate class name"); } - if (definition.contains("description")) - { + if (definition.contains("description")) { item.description = text(definition["description"], source, pointer + "/description", true); } std::set member_names; std::set indices; for (std::size_t j = 0; - const auto& member : array(required(definition, "fields", source, pointer), source, pointer + "/fields")) - { + const auto& member : array(required(definition, "fields", source, pointer), source, pointer + "/fields")) { const auto location = pointer + "/fields/" + std::to_string(j++); keys(member, {"name", "index", "type", "mask", "description"}, source, location); field field; @@ -437,8 +372,7 @@ document parse(std::string_view text_input, std::string_view source) { } const auto relations = [&](const char* key, std::vector& members) { for (std::size_t j = 0; - const auto& member : array(required(definition, key, source, pointer), source, pointer + "/" + key)) - { + const auto& member : array(required(definition, key, source, pointer), source, pointer + "/" + key)) { const auto location = pointer + "/" + key + "/" + std::to_string(j++); keys(member, {"name", "index", "class", "mask", "description"}, source, location); relation relation; @@ -452,23 +386,18 @@ document parse(std::string_view text_input, std::string_view source) { relations("containers", item.containers); result.classes.push_back(std::move(item)); } - for (std::size_t i = 0; const auto& definition : result.classes) - { - for (const auto* kind : {"tables", "containers"}) - { + for (std::size_t i = 0; const auto& definition : result.classes) { + for (const auto* kind : {"tables", "containers"}) { const auto& relations = std::string_view(kind) == "tables" ? definition.tables : definition.containers; - for (std::size_t j = 0; const auto& relation : relations) - { + for (std::size_t j = 0; const auto& relation : relations) { const auto pointer = "/classes/" + std::to_string(i) + "/" + kind + "/" + std::to_string(j++) + "/class"; const auto found = class_names.find(relation.class_name); - if (found == class_names.end()) - { + if (found == class_names.end()) { fail(source, pointer, "referenced class does not exist"); } const auto& target = result.classes[found->second]; - if (std::string_view(kind) == "tables" && (!target.tables.empty() || !target.containers.empty())) - { + if (std::string_view(kind) == "tables" && (!target.tables.empty() || !target.containers.empty())) { fail(source, pointer, "table columns must reference a scalar-only class"); } } @@ -477,53 +406,44 @@ document parse(std::string_view text_input, std::string_view source) { } std::set config_classes; std::set ids; - for (std::size_t i = 0; const auto& definition : array(required(input, "configs", source, ""), source, "/configs")) - { + for (std::size_t i = 0; + const auto& definition : array(required(input, "configs", source, ""), source, "/configs")) { const auto pointer = "/configs/" + std::to_string(i++); keys(definition, {"class", "rows"}, source, pointer); config_definition config; config.class_name = text(required(definition, "class", source, pointer), source, pointer + "/class"); const auto found = class_names.find(config.class_name); - if (found == class_names.end()) - { + if (found == class_names.end()) { fail(source, pointer + "/class", "configuration class does not exist"); } - if (!config_classes.insert(config.class_name).second) - { + if (!config_classes.insert(config.class_name).second) { fail(source, pointer + "/class", "duplicate configuration class"); } const auto& schema = result.classes[found->second]; const auto id_field = std::find_if( schema.fields.begin(), schema.fields.end(), [](const auto& field) { return field.name == "id"; }); - if (id_field == schema.fields.end() || id_field->type != value_type::uint32) - { + if (id_field == schema.fields.end() || id_field->type != value_type::uint32) { fail(source, pointer, "configuration requires a uint32 id field"); } for (std::size_t j = 0; - const auto& values : array(required(definition, "rows", source, pointer), source, pointer + "/rows")) - { + const auto& values : array(required(definition, "rows", source, pointer), source, pointer + "/rows")) { const auto location = pointer + "/rows/" + std::to_string(j++); - if (!values.is_object()) - { + if (!values.is_object()) { fail(source, location, "expected a row object"); } - for (auto member = values.begin(); member != values.end(); ++member) - { + for (auto member = values.begin(); member != values.end(); ++member) { if (std::none_of(schema.fields.begin(), schema.fields.end(), - [&](const auto& field) { return field.name == member.key(); })) - { + [&](const auto& field) { return field.name == member.key(); })) { fail(source, location + "/" + escaped(member.key()), "unknown configuration field"); } } row output; - for (const auto& member : schema.fields) - { + for (const auto& member : schema.fields) { output.emplace(member.name, scalar(required(values, member.name, source, location), member.type, source, location + "/" + escaped(member.name))); } const auto id = static_cast(std::get(output.at("id"))); - if (id == 0 || !ids.insert(id).second) - { + if (id == 0 || !ids.insert(id).second) { fail(source, location + "/id", "configuration id must be positive and globally unique"); } config.rows.push_back(std::move(output)); @@ -534,31 +454,29 @@ document parse(std::string_view text_input, std::string_view source) { } document load(const std::string& path) { - if (path.empty() || path.find('\0') != std::string::npos) - { + if (path.empty() || path.find('\0') != std::string::npos) { fail(path, "/", "expected a nonempty input path without NUL bytes"); } std::ifstream stream(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary); - if (!stream) - { + if (!stream) { fail(path, "/", "could not open JSON input"); } std::ostringstream contents; contents << stream.rdbuf(); - if (stream.bad()) - { + if (stream.bad()) { fail(path, "/", "could not read JSON input"); } return parse(contents.str(), path); } void validate(const document& input, std::string_view source) { - try - { static_cast(parse(encode(input).dump(), source)); } - catch (const error&) - { throw; } - catch (const std::exception& exception) - { fail(source, "/", exception.what()); } + try { + static_cast(parse(encode(input).dump(), source)); + } catch (const error&) { + throw; + } catch (const std::exception& exception) { + fail(source, "/", exception.what()); + } } std::string serialize(const document& input) { diff --git a/src/plugins/kernel/entity_json.hpp b/src/plugins/kernel/entity_json.hpp index a6a446d4b..b36adc699 100644 --- a/src/plugins/kernel/entity_json.hpp +++ b/src/plugins/kernel/entity_json.hpp @@ -16,8 +16,7 @@ namespace ark::entity_json { inline constexpr std::array mask_names = { "sync_view", "sync_self", "real_time", "save", "sync_team", "sync_guild", "sync_map", "log"}; -enum class value_type -{ +enum class value_type { boolean, int32, uint32, @@ -32,8 +31,7 @@ enum class value_type // Integers retain their signedness and full width. GUIDs use canonical decimal strings. using value = std::variant; -struct field -{ +struct field { std::string name; std::uint32_t index{0}; value_type type{value_type::int32}; @@ -41,8 +39,7 @@ struct field std::string description; }; -struct relation -{ +struct relation { std::string name; std::uint32_t index{0}; std::string class_name; @@ -50,8 +47,7 @@ struct relation std::string description; }; -struct class_definition -{ +struct class_definition { std::string name; std::vector fields; std::vector tables; @@ -61,20 +57,17 @@ struct class_definition using row = std::map; -struct config_definition -{ +struct config_definition { std::string class_name; std::vector rows; }; -struct document -{ +struct document { std::vector classes; std::vector configs; }; -class error : public std::runtime_error -{ +class error : public std::runtime_error { public: error(std::string source, std::string pointer, std::string reason); const std::string& source() const noexcept; diff --git a/src/plugins/kernel/entity_nested_snapshot.hpp b/src/plugins/kernel/entity_nested_snapshot.hpp index d41976227..a523d46a8 100644 --- a/src/plugins/kernel/entity_nested_snapshot.hpp +++ b/src/plugins/kernel/entity_nested_snapshot.hpp @@ -13,37 +13,32 @@ namespace ark::entity_sync { // Explicit authorization input. A table selection covers its rows; container // children require individual GUID bindings and their own member selections. -struct nested_entity_projection -{ +struct nested_entity_projection { std::string class_name; std::vector fields; std::map> tables; std::map> containers; }; -struct nested_projection -{ +struct nested_projection { std::string schema_id; guid_t root_id{}; nested_entity_projection root; }; -struct nested_row_snapshot -{ +struct nested_row_snapshot { std::uint64_t incarnation{}; std::map fields; bool operator==(const nested_row_snapshot&) const = default; }; -struct nested_table_snapshot -{ +struct nested_table_snapshot { std::string class_name; std::map rows; bool operator==(const nested_table_snapshot&) const = default; }; -struct nested_entity_snapshot -{ +struct nested_entity_snapshot { std::uint64_t incarnation{}; scalar_snapshot scalars; std::map tables; @@ -52,15 +47,13 @@ struct nested_entity_snapshot bool operator==(const nested_entity_snapshot&) const = default; }; -struct nested_snapshot -{ +struct nested_snapshot { std::string schema_id; nested_entity_snapshot root; bool operator==(const nested_snapshot&) const = default; }; -struct nested_snapshot_limits -{ +struct nested_snapshot_limits { // Root depth is zero. Entity count also bounds inspected container entries. std::size_t max_depth{8}; std::size_t max_entities{1024}; diff --git a/src/plugins/kernel/entity_snapshot.cpp b/src/plugins/kernel/entity_snapshot.cpp index ee403a1ea..b6e7a59ef 100644 --- a/src/plugins/kernel/entity_snapshot.cpp +++ b/src/plugins/kernel/entity_snapshot.cpp @@ -12,8 +12,7 @@ namespace ark::entity_sync { // The public entity interface exposes only materialized node types. This // private bridge reads selected schema entries without materializing any nodes. -class snapshot_access -{ +class snapshot_access { public: static const class_meta* schema(const entity_impl& source) { return source.class_meta_.get(); @@ -32,8 +31,7 @@ class snapshot_access } static const container* find_container(const entity_impl& source, std::uint32_t index) { - if (!source.opt_charactor_ || !source.opt_charactor_->containers) - { + if (!source.opt_charactor_ || !source.opt_charactor_->containers) { return nullptr; } return source.opt_charactor_->containers->get_container_list().find_value(index).get(); @@ -58,27 +56,23 @@ class snapshot_access namespace { -struct selected_field -{ +struct selected_field { data_type type; const node* value; }; void add_string_bytes(std::size_t bytes, std::size_t& total, const snapshot_limits& limits) { - if (bytes > limits.max_string_bytes - total) - { + if (bytes > limits.max_string_bytes - total) { throw std::length_error("scalar snapshot string byte limit exceeded"); } total += bytes; } void validate_field(const selected_field& field, std::size_t& string_bytes, const snapshot_limits& limits) { - if (field.value && field.value->get_type() != field.type) - { + if (field.value && field.value->get_type() != field.type) { throw std::invalid_argument("scalar snapshot node type does not match schema"); } - switch (field.type) - { + switch (field.type) { case data_type::dt_boolean: case data_type::dt_int32: case data_type::dt_uint32: @@ -87,20 +81,17 @@ void validate_field(const selected_field& field, std::size_t& string_bytes, cons case data_type::dt_guid: break; case data_type::dt_float: - if (field.value && !std::isfinite(field.value->get_float())) - { + if (field.value && !std::isfinite(field.value->get_float())) { throw std::invalid_argument("scalar snapshot requires finite float values"); } break; case data_type::dt_double: - if (field.value && !std::isfinite(field.value->get_double())) - { + if (field.value && !std::isfinite(field.value->get_double())) { throw std::invalid_argument("scalar snapshot requires finite double values"); } break; case data_type::dt_string: - if (field.value) - { + if (field.value) { add_string_bytes(field.value->get_string().size(), string_bytes, limits); } break; @@ -110,8 +101,7 @@ void validate_field(const selected_field& field, std::size_t& string_bytes, cons } scalar_value copy_field(const selected_field& field) { - switch (field.type) - { + switch (field.type) { case data_type::dt_boolean: return field.value ? field.value->get_bool() : false; case data_type::dt_int32: @@ -139,39 +129,32 @@ scalar_value copy_field(const selected_field& field) { static scalar_snapshot capture_selected_scalars( const entity& source, std::span allowed_indices, const snapshot_limits& limits) { - if (allowed_indices.size() > limits.max_fields) - { + if (allowed_indices.size() > limits.max_fields) { throw std::length_error("scalar snapshot field limit exceeded"); } const auto* implementation = dynamic_cast(&source); - if (!implementation) - { + if (!implementation) { throw std::invalid_argument("scalar snapshots require the framework entity_impl"); } const auto* schema = snapshot_access::schema(*implementation); - if (!schema) - { + if (!schema) { throw std::invalid_argument("scalar snapshot entity has no schema"); } std::size_t string_bytes = 0; add_string_bytes(schema->get_name().size(), string_bytes, limits); std::map selected; - for (const auto index : allowed_indices) - { - if (index == 0) - { + for (const auto index : allowed_indices) { + if (index == 0) { throw std::invalid_argument("scalar snapshot field indices must be nonzero"); } const auto meta = schema->find_data_meta(index); - if (!meta) - { + if (!meta) { throw std::invalid_argument("scalar snapshot field index is not declared"); } const auto [position, inserted] = selected.emplace( index, selected_field{meta->get_type(), snapshot_access::find_node(*implementation, index)}); - if (!inserted) - { + if (!inserted) { throw std::invalid_argument("scalar snapshot field indices must be unique"); } validate_field(position->second, string_bytes, limits); @@ -179,8 +162,7 @@ static scalar_snapshot capture_selected_scalars( // Validate every selection and cumulative text limit before copying strings. scalar_snapshot result{source.get_id(), schema->get_name(), {}}; - for (const auto& [index, field] : selected) - { + for (const auto& [index, field] : selected) { result.fields.emplace(index, copy_field(field)); } return result; @@ -189,15 +171,13 @@ static scalar_snapshot capture_selected_scalars( namespace { void consume(std::size_t count, std::size_t& remaining) { - if (count > remaining) - { + if (count > remaining) { throw std::length_error("Nested snapshot limit exceeded"); } remaining -= count; } -struct nested_budget -{ +struct nested_budget { explicit nested_budget(const nested_snapshot_limits& input) : limits(input) , entities(input.max_entities) @@ -215,10 +195,8 @@ struct nested_budget void validate_indices(const std::vector& indices, nested_budget& budget) { consume(indices.size(), budget.fields); std::set unique; - for (const auto index : indices) - { - if (index == 0 || !unique.insert(index).second) - { + for (const auto index : indices) { + if (index == 0 || !unique.insert(index).second) { throw std::invalid_argument("Nested projection indices must be nonzero and unique"); } } @@ -226,37 +204,29 @@ void validate_indices(const std::vector& indices, nested_budget& // Bound authorization input as well as output, including currently absent children. void validate_projection(const nested_entity_projection& projection, std::size_t depth, nested_budget& budget) { - if (depth > budget.limits.max_depth) - { + if (depth > budget.limits.max_depth) { throw std::length_error("Nested projection depth limit exceeded"); } - if (projection.class_name.empty()) - { + if (projection.class_name.empty()) { throw std::invalid_argument("Nested projection class binding is missing"); } consume(1, budget.entities); consume(projection.class_name.size(), budget.strings); validate_indices(projection.fields, budget); consume(projection.tables.size(), budget.fields); - for (const auto& [index, columns] : projection.tables) - { - if (index == 0) - { + for (const auto& [index, columns] : projection.tables) { + if (index == 0) { throw std::invalid_argument("Nested table index must be nonzero"); } validate_indices(columns, budget); } consume(projection.containers.size(), budget.fields); - for (const auto& [index, children] : projection.containers) - { - if (index == 0) - { + for (const auto& [index, children] : projection.containers) { + if (index == 0) { throw std::invalid_argument("Nested container index must be nonzero"); } - for (const auto& [id, child] : children) - { - if (id == null_guid) - { + for (const auto& [id, child] : children) { + if (id == null_guid) { throw std::invalid_argument("Nested child authorization requires a GUID binding"); } validate_projection(child, depth + 1, budget); @@ -267,11 +237,9 @@ void validate_projection(const nested_entity_projection& projection, std::size_t std::map selected_columns( const class_meta& schema, const std::vector& columns) { std::map selected; - for (const auto index : columns) - { + for (const auto index : columns) { const auto meta = schema.find_data_meta(index); - if (!meta) - { + if (!meta) { throw std::invalid_argument("Nested column index is not declared in the row class"); } std::size_t bytes = 0; @@ -284,23 +252,20 @@ std::map selected_columns( nested_row_snapshot capture_row( const row& source, const std::map& columns, nested_budget& budget) { const auto* implementation = dynamic_cast(&source); - if (!implementation || snapshot_access::incarnation(*implementation) == 0) - { + if (!implementation || snapshot_access::incarnation(*implementation) == 0) { throw std::invalid_argument("Nested snapshots require a published framework row"); } consume(columns.size(), budget.fields); std::map selected; std::size_t bytes = 0; - for (const auto& [index, type] : columns) - { + for (const auto& [index, type] : columns) { selected_field field{type, snapshot_access::find_node(*implementation, index)}; validate_field(field, bytes, {columns.size(), budget.strings}); selected.emplace(index, field); } consume(bytes, budget.strings); nested_row_snapshot result{snapshot_access::incarnation(*implementation), {}}; - for (const auto& [index, field] : selected) - { + for (const auto& [index, field] : selected) { result.fields.emplace(index, copy_field(field)); } return result; @@ -308,16 +273,14 @@ nested_row_snapshot capture_row( nested_entity_snapshot capture_nested_entity( const entity& source, const nested_entity_projection& projection, std::size_t depth, nested_budget& budget) { - if (depth > budget.limits.max_depth) - { + if (depth > budget.limits.max_depth) { throw std::length_error("Nested snapshot depth limit exceeded"); } consume(1, budget.entities); const auto* implementation = dynamic_cast(&source); const auto* schema = implementation ? snapshot_access::schema(*implementation) : nullptr; if (!schema || source.get_id() == null_guid || schema->get_name() != projection.class_name || - !budget.identities.insert(source.get_id()).second) - { + !budget.identities.insert(source.get_id()).second) { throw std::invalid_argument("Nested entity binding is invalid, repeated or cyclic"); } consume(projection.fields.size(), budget.fields); @@ -325,37 +288,29 @@ nested_entity_snapshot capture_nested_entity( consume(projection.containers.size(), budget.fields); auto scalars = capture_selected_scalars(source, projection.fields, {projection.fields.size(), budget.strings}); consume(scalars.class_name.size(), budget.strings); - for (const auto& [index, value] : scalars.fields) - { - if (const auto text = std::get_if(&value)) - { + for (const auto& [index, value] : scalars.fields) { + if (const auto text = std::get_if(&value)) { consume(text->size(), budget.strings); } } nested_entity_snapshot result{snapshot_access::incarnation(*implementation), std::move(scalars), {}, {}}; - for (const auto& [index, columns] : projection.tables) - { + for (const auto& [index, columns] : projection.tables) { const auto meta = schema->find_table_meta(index); const auto row_schema = meta ? meta->get_class_meta() : nullptr; - if (!row_schema || row_schema->get_name().empty()) - { + if (!row_schema || row_schema->get_name().empty()) { throw std::invalid_argument("Nested table index or row class is not declared"); } const auto selected = selected_columns(*row_schema, columns); consume(row_schema->get_name().size(), budget.strings); nested_table_snapshot table_state{row_schema->get_name(), {}}; - if (const auto* table = snapshot_access::find_table(*implementation, index)) - { + if (const auto* table = snapshot_access::find_table(*implementation, index)) { const auto* actual = dynamic_cast(table); - if (!actual) - { + if (!actual) { throw std::invalid_argument("Nested snapshots require a framework table"); } consume(snapshot_access::rows(*actual).size(), budget.rows); - for (const auto& [number, row] : snapshot_access::rows(*actual)) - { - if (!row || number == 0 || row->get_row() != number) - { + for (const auto& [number, row] : snapshot_access::rows(*actual)) { + if (!row || number == 0 || row->get_row() != number) { throw std::invalid_argument("Nested row binding is invalid"); } table_state.rows.emplace(number, capture_row(*row, selected, budget)); @@ -363,49 +318,38 @@ nested_entity_snapshot capture_nested_entity( } result.tables.emplace(index, std::move(table_state)); } - for (const auto& [index, allowed_children] : projection.containers) - { + for (const auto& [index, allowed_children] : projection.containers) { const auto meta = schema->find_container_meta(index); - if (!meta || meta->get_class_name().empty()) - { + if (!meta || meta->get_class_name().empty()) { throw std::invalid_argument("Nested container index or child class is not declared"); } - for (const auto& [id, child_projection] : allowed_children) - { - if (child_projection.class_name != meta->get_class_name()) - { + for (const auto& [id, child_projection] : allowed_children) { + if (child_projection.class_name != meta->get_class_name()) { throw std::invalid_argument("Nested child class does not match its container schema"); } } auto& children = result.containers[index]; - if (allowed_children.empty()) - { + if (allowed_children.empty()) { continue; } const auto* container = snapshot_access::find_container(*implementation, index); - if (!container) - { + if (!container) { continue; } const auto* actual = dynamic_cast(container); - if (!actual) - { + if (!actual) { throw std::invalid_argument("Nested snapshots require a framework container"); } consume(snapshot_access::children(*actual).size(), budget.inspected_children); - for (const auto& [slot, child] : snapshot_access::children(*actual)) - { - if (!child) - { + for (const auto& [slot, child] : snapshot_access::children(*actual)) { + if (!child) { throw std::invalid_argument("Nested container has a null child"); } const auto allowed = allowed_children.find(child->get_id()); - if (allowed == allowed_children.end()) - { + if (allowed == allowed_children.end()) { continue; } - if (slot == 0 || child->get_parent_container().get() != container) - { + if (slot == 0 || child->get_parent_container().get() != container) { throw std::invalid_argument("Nested child relationship is invalid"); } children.emplace(slot, capture_nested_entity(*child, allowed->second, depth + 1, budget)); @@ -416,8 +360,7 @@ nested_entity_snapshot capture_nested_entity( nested_snapshot capture_selected_nested( const entity& source, const nested_projection& projection, const nested_snapshot_limits& limits) { - if (projection.schema_id.empty() || projection.root_id == null_guid || projection.root_id != source.get_id()) - { + if (projection.schema_id.empty() || projection.root_id == null_guid || projection.root_id != source.get_id()) { throw std::invalid_argument("Nested capture requires an explicit schema and authorized root binding"); } nested_budget authorization(limits); diff --git a/src/plugins/kernel/entity_snapshot.hpp b/src/plugins/kernel/entity_snapshot.hpp index abc6d8531..e88fa6130 100644 --- a/src/plugins/kernel/entity_snapshot.hpp +++ b/src/plugins/kernel/entity_snapshot.hpp @@ -12,8 +12,7 @@ namespace ark::entity_sync { -struct guid_value -{ +struct guid_value { guid_t value{}; bool operator==(const guid_value&) const = default; }; @@ -21,16 +20,14 @@ struct guid_value using scalar_value = std::variant; -struct scalar_snapshot -{ +struct scalar_snapshot { guid_t entity_id{}; std::string class_name; std::map fields; bool operator==(const scalar_snapshot&) const = default; }; -struct snapshot_limits -{ +struct snapshot_limits { std::size_t max_fields{1024}; // Combined class-name and selected string-field bytes, including embedded NULs. std::size_t max_string_bytes{1024 * 1024}; @@ -43,8 +40,7 @@ namespace detail { // even a deleted copy/move constructor is supported. The factory must return a // prvalue, and the adapter must be consumed synchronously within its captures. template -struct direct_value -{ +struct direct_value { factory_type create; using value_type = std::invoke_result_t; @@ -72,8 +68,7 @@ inline scalar_value copy_scalar_value(const scalar_value& input) { inline std::map copy_scalar_fields(const std::map& input) { std::map result; - for (const auto& [index, item] : input) - { + for (const auto& [index, item] : input) { result.emplace_hint(result.end(), index, direct_value{[&] { return copy_scalar_value(item); }}); } return result; diff --git a/src/plugins/kernel/entity_stream.hpp b/src/plugins/kernel/entity_stream.hpp index a8377d44d..1107aeac9 100644 --- a/src/plugins/kernel/entity_stream.hpp +++ b/src/plugins/kernel/entity_stream.hpp @@ -17,16 +17,14 @@ namespace ark::entity_sync { // In-process value envelopes, not a serialized message format or transport API. -struct scalar_baseline -{ +struct scalar_baseline { std::string schema_id; std::uint64_t generation{}; std::uint64_t revision{}; scalar_snapshot snapshot; }; -struct scalar_delta -{ +struct scalar_delta { std::string schema_id; std::uint64_t generation{}; std::uint64_t required_revision{}; @@ -37,8 +35,7 @@ struct scalar_delta bool removed{false}; }; -enum class scalar_apply_result -{ +enum class scalar_apply_result { applied, duplicate, rejected @@ -55,35 +52,26 @@ inline void swap_scalar_snapshots(scalar_snapshot& left, scalar_snapshot& right) inline void validate_scalar_state(guid_t id, const std::string& name, const std::map& fields, const snapshot_limits& limits) { - if (id == guid_t{} || name.empty()) - { + if (id == guid_t{} || name.empty()) { throw std::invalid_argument("Scalar state requires an entity ID and class"); } - if (fields.size() > limits.max_fields || name.size() > limits.max_string_bytes) - { + if (fields.size() > limits.max_fields || name.size() > limits.max_string_bytes) { throw std::length_error("Scalar state exceeds snapshot limits"); } auto remaining = limits.max_string_bytes - name.size(); - for (const auto& [index, value] : fields) - { - if (index == 0 || value.valueless_by_exception()) - { + for (const auto& [index, value] : fields) { + if (index == 0 || value.valueless_by_exception()) { throw std::invalid_argument("Invalid scalar field"); } std::visit( [&](const auto& item) { using type = std::decay_t; - if constexpr (std::is_floating_point_v) - { - if (!std::isfinite(item)) - { + if constexpr (std::is_floating_point_v) { + if (!std::isfinite(item)) { throw std::invalid_argument("Non-finite scalar field"); } - } - else if constexpr (std::is_same_v) - { - if (item.size() > remaining) - { + } else if constexpr (std::is_same_v) { + if (item.size() > remaining) { throw std::length_error("Scalar strings exceed snapshot limits"); } remaining -= item.size(); @@ -94,12 +82,10 @@ inline void validate_scalar_state(guid_t id, const std::string& name, } inline void validate_scalar_schema(const std::string& schema, const snapshot_limits& limits) { - if (schema.empty()) - { + if (schema.empty()) { throw std::invalid_argument("A scalar stream requires an application schema ID"); } - if (schema.size() > limits.max_string_bytes) - { + if (schema.size() > limits.max_string_bytes) { throw std::length_error("Scalar schema ID exceeds snapshot limits"); } } @@ -109,8 +95,7 @@ inline void validate_scalar_schema(const std::string& schema, const snapshot_lim // Owner-thread state differ. Returning a delta does not acknowledge network delivery. // Call update once at the application's explicit flush point. A changed selection // or schema requires a new publisher/generation and a new baseline. -class scalar_publisher final -{ +class scalar_publisher final { public: explicit scalar_publisher(const scalar_baseline& initial, snapshot_limits limits = {}) : limits_(limits) @@ -127,25 +112,20 @@ class scalar_publisher final require_active(); detail::validate_scalar_state(next.entity_id, next.class_name, next.fields, limits_); if (next.entity_id != current_.snapshot.entity_id || next.class_name != current_.snapshot.class_name || - next.fields.size() != current_.snapshot.fields.size()) - { + next.fields.size() != current_.snapshot.fields.size()) { throw std::invalid_argument("Scalar identity or selection changed; establish a new baseline"); } auto delta = envelope(); - for (const auto& [index, value] : next.fields) - { + for (const auto& [index, value] : next.fields) { const auto before = current_.snapshot.fields.find(index); - if (before == current_.snapshot.fields.end() || before->second.index() != value.index()) - { + if (before == current_.snapshot.fields.end() || before->second.index() != value.index()) { throw std::invalid_argument("Scalar field selection or type changed"); } - if (before->second != value) - { + if (before->second != value) { delta.fields.emplace(index, detail::direct_value{[&] { return detail::copy_scalar_value(value); }}); } } - if (delta.fields.empty()) - { + if (delta.fields.empty()) { return {}; } advance(delta); @@ -172,8 +152,7 @@ class scalar_publisher final detail::validate_scalar_schema(initial.schema_id, limits); detail::validate_scalar_state( initial.snapshot.entity_id, initial.snapshot.class_name, initial.snapshot.fields, limits); - if (initial.generation == 0 || initial.revision == 0) - { + if (initial.generation == 0 || initial.revision == 0) { throw std::invalid_argument("Scalar generation and revision must be positive"); } return { @@ -188,8 +167,7 @@ class scalar_publisher final } void require_active() const { - if (removed_) - { + if (removed_) { throw std::logic_error("Scalar entity was removed; establish a new generation"); } } @@ -200,8 +178,7 @@ class scalar_publisher final } void advance(scalar_delta& delta) const { - if (current_.revision == std::numeric_limits::max()) - { + if (current_.revision == std::numeric_limits::max()) { throw std::overflow_error("Scalar revision exhausted; establish a new generation"); } delta.revision = current_.revision + 1; @@ -214,8 +191,7 @@ class scalar_publisher final // Validates in-process envelopes for an explicitly bound root. It is not a wire // decoder, schema-definition validator or authorization/session mechanism. -class scalar_replica final -{ +class scalar_replica final { public: scalar_replica(std::string schema, guid_t id, std::string class_name, snapshot_limits limits = {}) : schema_(std::move(schema)) @@ -227,26 +203,22 @@ class scalar_replica final } scalar_apply_result apply(const scalar_baseline& input) { - try - { + try { detail::validate_scalar_schema(input.schema_id, limits_); detail::validate_scalar_state( input.snapshot.entity_id, input.snapshot.class_name, input.snapshot.fields, limits_); + } catch (const std::invalid_argument&) { + return reject(); + } catch (const std::length_error&) { + return reject(); } - catch (const std::invalid_argument&) - { return reject(); } - catch (const std::length_error&) - { return reject(); } if (input.schema_id != schema_ || input.snapshot.entity_id != id_ || input.snapshot.class_name != class_name_ || - input.generation == 0 || input.revision == 0 || input.generation < generation_) - { + input.generation == 0 || input.revision == 0 || input.generation < generation_) { return reject(); } - if (input.generation == generation_) - { + if (input.generation == generation_) { if (valid_ && - (input.revision < revision_ || (input.revision == revision_ && state_ && *state_ == input.snapshot))) - { + (input.revision < revision_ || (input.revision == revision_ && state_ && *state_ == input.snapshot))) { return scalar_apply_result::duplicate; } return reject(); @@ -261,60 +233,49 @@ class scalar_replica final } scalar_apply_result apply(const scalar_delta& input) { - try - { detail::validate_scalar_state(input.entity_id, input.class_name, input.fields, limits_); } - catch (const std::invalid_argument&) - { return reject(); } - catch (const std::length_error&) - { return reject(); } + try { + detail::validate_scalar_state(input.entity_id, input.class_name, input.fields, limits_); + } catch (const std::invalid_argument&) { + return reject(); + } catch (const std::length_error&) { + return reject(); + } if (!valid_ || input.schema_id != schema_ || input.entity_id != id_ || input.class_name != class_name_ || input.generation != generation_ || input.required_revision == 0 || input.required_revision == std::numeric_limits::max() || input.revision != input.required_revision + 1 || (input.removed && !input.fields.empty()) || - (!input.removed && input.fields.empty())) - { + (!input.removed && input.fields.empty())) { return reject(); } - if (input.revision <= revision_) - { + if (input.revision <= revision_) { return scalar_apply_result::duplicate; } - if (input.required_revision != revision_ || !state_) - { + if (input.required_revision != revision_ || !state_) { return reject(); } - if (input.removed) - { + if (input.removed) { state_.reset(); - } - else - { - for (const auto& [index, value] : input.fields) - { + } else { + for (const auto& [index, value] : input.fields) { const auto old = state_->fields.find(index); - if (old == state_->fields.end() || old->second.index() != value.index()) - { + if (old == state_->fields.end() || old->second.index() != value.index()) { return reject(); } } // Validate the merged text budget before allocating a state copy. auto remaining = limits_.max_string_bytes - class_name_.size(); - for (const auto& [index, old] : state_->fields) - { + for (const auto& [index, old] : state_->fields) { const auto changed = input.fields.find(index); const auto& value = changed == input.fields.end() ? old : changed->second; - if (const auto text = std::get_if(&value)) - { - if (text->size() > remaining) - { + if (const auto text = std::get_if(&value)) { + if (text->size() > remaining) { return reject(); } remaining -= text->size(); } } auto replacement = detail::copy_scalar_snapshot(*state_); - for (const auto& [index, value] : input.fields) - { + for (const auto& [index, value] : input.fields) { replacement.fields.at(index) = detail::copy_scalar_value(value); } auto immutable = std::make_shared(detail::direct_value{[&] { diff --git a/src/plugins/kernel/event_manager.hpp b/src/plugins/kernel/event_manager.hpp index 7868ee9aa..d613f0fe6 100644 --- a/src/plugins/kernel/event_manager.hpp +++ b/src/plugins/kernel/event_manager.hpp @@ -28,8 +28,7 @@ namespace ark { -class event_manager -{ +class event_manager { public: virtual void update() = 0; diff --git a/src/plugins/kernel/event_manager_impl.hpp b/src/plugins/kernel/event_manager_impl.hpp index f80d3e8f2..d76c0f09d 100644 --- a/src/plugins/kernel/event_manager_impl.hpp +++ b/src/plugins/kernel/event_manager_impl.hpp @@ -28,8 +28,7 @@ namespace ark { -class event_manager_impl final : public event_manager -{ +class event_manager_impl final : public event_manager { public: event_manager_impl() = delete; @@ -38,8 +37,7 @@ class event_manager_impl final : public event_manager } void update() override { - for (auto iter : need_remove_events_) - { + for (auto iter : need_remove_events_) { event_callbacks_.erase(iter); } @@ -48,14 +46,11 @@ class event_manager_impl final : public event_manager bool add_event_call_back(const int event_id, event_process_functor&& cb) override { auto event_info_ptr = event_callbacks_.find_value(event_id); - if (event_info_ptr == nullptr) - { + if (event_info_ptr == nullptr) { auto event_info = std::make_shared>(); event_info->emplace_back(cb); return event_callbacks_.insert(event_id, event_info).second; - } - else - { + } else { event_info_ptr->emplace_back(cb); return true; } @@ -68,13 +63,11 @@ class event_manager_impl final : public event_manager bool do_event(const int event_id, const data_list& args) override { auto event_info = event_callbacks_.find_value(event_id); - if (event_info == nullptr) - { + if (event_info == nullptr) { return false; } - for (auto iter : *event_info) - { + for (auto iter : *event_info) { iter(self_, event_id, args); } diff --git a/src/plugins/kernel/kernel_module.hpp b/src/plugins/kernel/kernel_module.hpp index 3948b5d40..eb623cb7e 100644 --- a/src/plugins/kernel/kernel_module.hpp +++ b/src/plugins/kernel/kernel_module.hpp @@ -33,8 +33,7 @@ namespace ark { -class kernel_module : public module -{ +class kernel_module : public module { public: template bool add_common_class_event(base_type* base_ptr, diff --git a/src/plugins/kernel/kernel_module_impl.cpp b/src/plugins/kernel/kernel_module_impl.cpp index 763731790..3c768cb0f 100644 --- a/src/plugins/kernel/kernel_module_impl.cpp +++ b/src/plugins/kernel/kernel_module_impl.cpp @@ -64,21 +64,17 @@ bool kernel_module_impl::post_init() { bool kernel_module_impl::update() { cur_exec_object_ = null_guid; - if (!delete_list_.empty()) - { - for (auto it : delete_list_) - { + if (!delete_list_.empty()) { + for (auto it : delete_list_) { destroy_entity(it); } delete_list_.clear(); } - for (auto& iter : objects_) - { + for (auto& iter : objects_) { auto entity_ptr = iter.second; - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { continue; } @@ -96,30 +92,25 @@ bool kernel_module_impl::pre_shut() { bool kernel_module_impl::copy_data( std::shared_ptr entity_ptr, std::shared_ptr static_entity_ptr) { - if (entity_ptr == nullptr || nullptr == static_entity_ptr) - { + if (entity_ptr == nullptr || nullptr == static_entity_ptr) { return false; } // static node manager must be not empty auto static_node_manager_ptr = get_node_manager(static_entity_ptr); - if (static_node_manager_ptr == nullptr || static_node_manager_ptr->is_empty()) - { + if (static_node_manager_ptr == nullptr || static_node_manager_ptr->is_empty()) { return false; } auto node_manager_ptr = get_node_manager(entity_ptr); - if (node_manager_ptr == nullptr) - { + if (node_manager_ptr == nullptr) { return false; } // Fill absent nodes without overwriting explicit initialization arguments. auto& data_list = static_node_manager_ptr->get_data_list(); - for (auto& iter : data_list) - { - if (node_manager_ptr->get_node(iter.first) == nullptr) - { + for (auto& iter : data_list) { + if (node_manager_ptr->get_node(iter.first) == nullptr) { node_manager_ptr->create_data(iter.second); } } @@ -132,37 +123,31 @@ std::shared_ptr kernel_module_impl::create_entity(const guid_t& self, co guid_t object_id = self; auto map_info_ptr = map_module_->get_map_info(map_id); - if (map_info_ptr == nullptr) - { + if (map_info_ptr == nullptr) { ARK_LOG_ERROR("There is no scene, scene = {}", map_id); return nullptr; } - if (!map_info_ptr->exist_instance(map_instance_id)) - { + if (!map_info_ptr->exist_instance(map_instance_id)) { ARK_LOG_ERROR("There is no group, scene = {} group = {}", map_id, map_instance_id); return nullptr; } auto class_meta_ptr = class_meta_module_->find_meta(class_name); - if (nullptr == class_meta_ptr) - { + if (nullptr == class_meta_ptr) { ARK_LOG_ERROR("There is no class meta, name = {}", class_name); return nullptr; } std::shared_ptr static_entity_ptr = nullptr; - if (config_id > 0) - { + if (config_id > 0) { static_entity_ptr = get_static_entity(config_id); - if (nullptr == static_entity_ptr) - { + if (nullptr == static_entity_ptr) { ARK_LOG_ERROR("There is no config, config_id = {}", config_id); return nullptr; } - if (static_entity_ptr->get_class_name() != class_name) - { + if (static_entity_ptr->get_class_name() != class_name) { ARK_LOG_ERROR("Config class does not match entity class, config_id = {}", config_id); return nullptr; } @@ -170,20 +155,17 @@ std::shared_ptr kernel_module_impl::create_entity(const guid_t& self, co // check args num size_t arg_count = args.get_count(); - if (arg_count % 2 != 0) - { + if (arg_count % 2 != 0) { ARK_LOG_ERROR("Args count is wrong, count = {}", arg_count); return nullptr; } - if (object_id == null_guid) - { + if (object_id == null_guid) { object_id = guid_module_->create_guid(); } // Check if the entity exists - if (get_entity(object_id) != nullptr) - { + if (get_entity(object_id) != nullptr) { ARK_LOG_ERROR("The entity has existed, id = {}", object_id); return nullptr; } @@ -193,8 +175,7 @@ std::shared_ptr kernel_module_impl::create_entity(const guid_t& self, co objects_.insert(object_id, entity_ptr); - if (class_name == entity_meta_player::self_name()) - { + if (class_name == entity_meta_player::self_name()) { map_info_ptr->add_entity_to_instance(map_instance_id, object_id, true); } //else if (class_name == AFEntityMetaPlayer::self_name()) // to do : npc type for now we do not have @@ -219,38 +200,32 @@ std::shared_ptr kernel_module_impl::create_entity(const guid_t& self, co std::shared_ptr kernel_module_impl::create_container_entity( const guid_t& self, const uint32_t container_index, const std::string& class_name, const id_type config_id) { auto entity_ptr = get_entity(self); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { ARK_LOG_ERROR("There is no object, object = {}", self); return nullptr; } auto container_ptr = entity_ptr->find_container(container_index); - if (container_ptr == nullptr) - { + if (container_ptr == nullptr) { ARK_LOG_ERROR("There is no container, container = {}", container_index); return nullptr; } auto class_meta_ptr = class_meta_module_->find_meta(class_name); - if (nullptr == class_meta_ptr) - { + if (nullptr == class_meta_ptr) { ARK_LOG_ERROR("There is no class meta, name = {}", class_name); return nullptr; } std::shared_ptr static_entity_ptr = nullptr; - if (config_id > 0) - { + if (config_id > 0) { static_entity_ptr = get_static_entity(config_id); - if (nullptr == static_entity_ptr) - { + if (nullptr == static_entity_ptr) { ARK_LOG_ERROR("There is no config, config_id = {}", config_id); return nullptr; } - if (static_entity_ptr->get_class_name() != class_name) - { + if (static_entity_ptr->get_class_name() != class_name) { ARK_LOG_ERROR("Config class does not match entity class, config_id = {}", config_id); return nullptr; } @@ -258,15 +233,13 @@ std::shared_ptr kernel_module_impl::create_container_entity( auto map_id = entity_ptr->get_map_id(); auto map_info_ptr = map_module_->get_map_info(map_id); - if (map_info_ptr == nullptr) - { + if (map_info_ptr == nullptr) { ARK_LOG_ERROR("There is no scene, scene = {}", map_id); return nullptr; } auto map_instance_id = entity_ptr->get_map_entity_id(); - if (!map_info_ptr->exist_instance(map_instance_id)) - { + if (!map_info_ptr->exist_instance(map_instance_id)) { ARK_LOG_ERROR("There is no group, scene = {} group = {}", map_id, map_instance_id); return nullptr; } @@ -274,8 +247,7 @@ std::shared_ptr kernel_module_impl::create_container_entity( guid_t object_id = guid_module_->create_guid(); // Check if the entity exists - if (get_entity(object_id) != nullptr) - { + if (get_entity(object_id) != nullptr) { ARK_LOG_ERROR("The entity has existed, id = {}", object_id); return nullptr; } @@ -310,11 +282,9 @@ std::shared_ptr kernel_module_impl::get_entity(const guid_t& self) { } bool kernel_module_impl::destroy_all() { - for (auto& iter : objects_) - { + for (auto& iter : objects_) { auto& entity_ptr = iter.second; - if (entity_ptr->get_parent_container() != nullptr) - { + if (entity_ptr->get_parent_container() != nullptr) { continue; } @@ -328,26 +298,21 @@ bool kernel_module_impl::destroy_all() { } bool kernel_module_impl::destroy_entity(const guid_t& self) { - if (self == cur_exec_object_ && self != null_guid) - { + if (self == cur_exec_object_ && self != null_guid) { return destroy_self(self); } auto entity_ptr = get_entity(self); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { ARK_LOG_ERROR("Cannot find this object, self={}", null_guid); return false; } auto parent_container_ptr = entity_ptr->get_parent_container(); - if (parent_container_ptr) - { + if (parent_container_ptr) { // use container to destroy its entity return parent_container_ptr->destroy(self); - } - else - { + } else { return inner_destroy_entity(entity_ptr); } } @@ -358,8 +323,7 @@ bool kernel_module_impl::destroy_self(const guid_t& self) { } bool kernel_module_impl::inner_destroy_entity(std::shared_ptr entity_ptr) { - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { ARK_LOG_ERROR("Cannot find this object, self={}", null_guid); return false; } @@ -369,8 +333,7 @@ bool kernel_module_impl::inner_destroy_entity(std::shared_ptr entity_ptr int32_t inst_id = entity_ptr->get_map_entity_id(); std::shared_ptr map_info_ptr = map_module_->get_map_info(map_id); - if (map_info_ptr != nullptr) - { + if (map_info_ptr != nullptr) { const std::string& class_name = entity_ptr->get_class_name(); map_info_ptr->remove_entity_from_instance( @@ -384,9 +347,7 @@ bool kernel_module_impl::inner_destroy_entity(std::shared_ptr entity_ptr // queued under the surviving parent and remain available for delivery. class_call_back_manager::retire_delay_sync(self); return objects_.erase(self); - } - else - { + } else { ARK_LOG_ERROR("Cannot find this map, object_id={} map={} inst={}", self, map_id, inst_id); return false; } @@ -413,8 +374,7 @@ bool kernel_module_impl::add_node_call_back( ARK_ASSERT_RET_VAL(class_meta_ptr != nullptr, false); auto index = class_meta_ptr->get_index(name); - if (index == 0) - { + if (index == 0) { return false; } @@ -429,8 +389,7 @@ bool kernel_module_impl::add_table_call_back( ARK_ASSERT_RET_VAL(class_meta_ptr != nullptr, false); auto index = class_meta_ptr->get_index(name); - if (index == 0) - { + if (index == 0) { return false; } @@ -488,18 +447,14 @@ bool kernel_module_impl::add_container_call_back( } bool kernel_module_impl::add_common_container_call_back(container_event_functor&& cb, const int32_t prio) { - for (const auto& entry : class_meta_module_->get_meta_list()) - { + for (const auto& entry : class_meta_module_->get_meta_list()) { const auto& meta = entry.second; - if (!meta) - { + if (!meta) { continue; } - for (const auto& container : meta->get_container_meta_list()) - { + for (const auto& container : meta->get_container_meta_list()) { auto callback = cb; - if (!add_container_call_back(meta->get_name(), container.first, std::move(callback), prio)) - { + if (!add_container_call_back(meta->get_name(), container.first, std::move(callback), prio)) { return false; } } @@ -510,11 +465,9 @@ bool kernel_module_impl::add_common_container_call_back(container_event_functor& bool kernel_module_impl::add_common_class_event(class_event_functor&& cb, const int32_t prio) { auto& class_meta_list = class_meta_module_->get_meta_list(); - for (auto& iter : class_meta_list) - { + for (auto& iter : class_meta_list) { auto class_meta_ptr = iter.second; - if (nullptr == class_meta_ptr) - { + if (nullptr == class_meta_ptr) { continue; } @@ -594,8 +547,7 @@ int kernel_module_impl::on_sync_node( const guid_t& self, const uint32_t index, const data_mask mask_value, const data& data) { // find parent entity auto entity_ptr = get_entity(self); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { ARK_LOG_ERROR("sync node failed entity do no exist, self={}", self); return -1; } @@ -605,25 +557,21 @@ int kernel_module_impl::on_sync_node( auto protobuf_entity = protobuf_data.mutable_data(); auto parent_container_ptr = entity_ptr->get_parent_container(); - if (parent_container_ptr != nullptr) - { + if (parent_container_ptr != nullptr) { if (!try_add_container_protobuf_entity( - parent_container_ptr, self, *protobuf_data.mutable_data(), entity_id, protobuf_entity)) - { + parent_container_ptr, self, *protobuf_data.mutable_data(), entity_id, protobuf_entity)) { ARK_LOG_ERROR("sync node failed container entity do no exist, self={}", self); return -1; } } - if (!node_to_protobuf_data(index, data, protobuf_entity)) - { + if (!node_to_protobuf_data(index, data, protobuf_entity)) { ARK_LOG_ERROR("node to pb failed, self={}, index={}", self, index); return -1; } protobuf_data.set_id(entity_id); - if (send_sync_msg(entity_id, mask_value, protobuf_data) < 0) - { + if (send_sync_msg(entity_id, mask_value, protobuf_data) < 0) { ARK_LOG_ERROR("send sync msg failed, self={}, index={}", entity_id, index); return -1; } @@ -634,26 +582,19 @@ int kernel_module_impl::on_sync_node( int kernel_module_impl::on_sync_table( const guid_t& self, const table_event_data& event, const data_mask mask_value, const data& data) { table_op_type op_type = static_cast(event.op_type); - switch (op_type) - { - case table_op_type::table_add: - { + switch (op_type) { + case table_op_type::table_add: { on_sync_table_add(self, event, mask_value); - } - break; - case table_op_type::table_delete: - { + } break; + case table_op_type::table_delete: { on_sync_table_delete(self, event, mask_value); - } - break; + } break; case table_op_type::table_swap: // do not have yet break; - case table_op_type::table_update: - { + case table_op_type::table_update: { on_sync_table_update(self, event, mask_value, data); - } - break; + } break; case table_op_type::table_coverage: // will do something break; @@ -666,28 +607,19 @@ int kernel_module_impl::on_sync_table( int kernel_module_impl::on_sync_container(const guid_t& self, const uint32_t index, const data_mask mask, const container_op_type op_type, uint32_t src_index, uint32_t dest_index) { - switch (op_type) - { - case container_op_type::op_place: - { + switch (op_type) { + case container_op_type::op_place: { on_sync_container_place(self, index, mask, src_index); - } - break; - case container_op_type::op_remove: - { + } break; + case container_op_type::op_remove: { on_sync_container_remove(self, index, mask, src_index); - } - break; - case container_op_type::op_destroy: - { + } break; + case container_op_type::op_destroy: { on_sync_container_destroy(self, index, mask, src_index); - } - break; - case container_op_type::op_swap: - { + } break; + case container_op_type::op_swap: { on_sync_container_swap(self, index, mask, src_index, dest_index); - } - break; + } break; default: break; } @@ -696,15 +628,13 @@ int kernel_module_impl::on_sync_container(const guid_t& self, const uint32_t ind int kernel_module_impl::on_delay_sync_data( const guid_t& self, const data_mask mask_value, const delay_sync_data& data) { - if (data.node_list.empty() && data.table_list.empty() && data.container_list.empty()) - { + if (data.node_list.empty() && data.table_list.empty() && data.container_list.empty()) { return 0; } // find parent entity auto entity_ptr = get_entity(self); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { ARK_LOG_ERROR("sync delay data failed entity do no exist, self={}", self); return -1; } @@ -714,37 +644,31 @@ int kernel_module_impl::on_delay_sync_data( auto protobuf_entity = protobuf_data.mutable_data(); auto parent_container_ptr = entity_ptr->get_parent_container(); - if (parent_container_ptr != nullptr) - { + if (parent_container_ptr != nullptr) { if (!try_add_container_protobuf_entity( - parent_container_ptr, self, *protobuf_data.mutable_data(), entity_id, protobuf_entity)) - { + parent_container_ptr, self, *protobuf_data.mutable_data(), entity_id, protobuf_entity)) { ARK_LOG_ERROR("sync delay data failed container entity do no exist, self={}", self); return -1; } } // node to pb - for (auto& iter : data.node_list) - { + for (auto& iter : data.node_list) { auto node_ptr = iter; - if (!node_to_protobuf_data(node_ptr, protobuf_entity)) - { + if (!node_to_protobuf_data(node_ptr, protobuf_entity)) { continue; } } // table to pb - for (auto& iter : data.table_list) - { + for (auto& iter : data.table_list) { auto table_index = iter.first; auto& table = iter.second; delay_table_to_protobuf(table, table_index, protobuf_data, *protobuf_entity); } // container to pb - for (auto& iter : data.container_list) - { + for (auto& iter : data.container_list) { auto container_index = iter.first; auto& container = iter.second; delay_container_to_protobuf(entity_ptr, container, container_index, protobuf_data); @@ -752,8 +676,7 @@ int kernel_module_impl::on_delay_sync_data( protobuf_data.set_id(entity_id); - if (send_sync_msg(entity_id, mask_value, protobuf_data) < 0) - { + if (send_sync_msg(entity_id, mask_value, protobuf_data) < 0) { ARK_LOG_ERROR("send sync msg failed, self={}", self); return -1; } @@ -765,22 +688,19 @@ int kernel_module_impl::on_sync_table_add( const guid_t& self, const table_event_data& event, const data_mask mask_value) { // find parent entity auto entity_ptr = get_entity(self); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { ARK_LOG_ERROR("sync table failed entity do no exist, self={}", self); return -1; } auto table_ptr = entity_ptr->find_table(event.table_index); - if (nullptr == table_ptr) - { + if (nullptr == table_ptr) { ARK_LOG_ERROR("sync table failed table do no exist, self={}, table={}", self, event.table_name); return -1; } auto row_ptr = table_ptr->find_row(event.row); - if (nullptr == row_ptr) - { + if (nullptr == row_ptr) { ARK_LOG_ERROR( "sync table failed table row do no exist, self={}, table={}, row={}", self, event.table_name, event.row); return -1; @@ -791,19 +711,16 @@ int kernel_module_impl::on_sync_table_add( auto protobuf_entity = protobuf_data.mutable_data(); auto parent_container_ptr = entity_ptr->get_parent_container(); - if (parent_container_ptr != nullptr) - { + if (parent_container_ptr != nullptr) { if (!try_add_container_protobuf_entity( - parent_container_ptr, self, *protobuf_data.mutable_data(), entity_id, protobuf_entity)) - { + parent_container_ptr, self, *protobuf_data.mutable_data(), entity_id, protobuf_entity)) { ARK_LOG_ERROR("sync node failed container entity do no exist, self={}", self); return -1; } } ark::protobuf::protobuf_entity_data protobuf_row; - if (!row_to_protobuf_data(row_ptr, event.row, &protobuf_row)) - { + if (!row_to_protobuf_data(row_ptr, event.row, &protobuf_row)) { ARK_LOG_ERROR( "sync table failed table row do no exist, self={}, table={}, row={}", self, event.table_name, event.row); return -1; @@ -823,8 +740,7 @@ int kernel_module_impl::on_sync_table_delete( const guid_t& self, const table_event_data& event, const data_mask mask_value) { // find parent entity auto entity_ptr = get_entity(self); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { ARK_LOG_ERROR("sync table failed entity do no exist, self={}", self); return -1; } @@ -834,11 +750,9 @@ int kernel_module_impl::on_sync_table_delete( auto protobuf_entity = protobuf_data.mutable_data(); auto parent_container_ptr = entity_ptr->get_parent_container(); - if (parent_container_ptr != nullptr) - { + if (parent_container_ptr != nullptr) { if (!try_add_container_protobuf_entity( - parent_container_ptr, self, *protobuf_data.mutable_data(), entity_id, protobuf_entity)) - { + parent_container_ptr, self, *protobuf_data.mutable_data(), entity_id, protobuf_entity)) { ARK_LOG_ERROR("sync node failed container entity do no exist, self={}", self); return -1; } @@ -857,8 +771,7 @@ int kernel_module_impl::on_sync_table_update( const guid_t& self, const table_event_data& event, const data_mask mask_value, const data& data) { // find parent entity auto entity_ptr = get_entity(self); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { ARK_LOG_ERROR("sync table failed entity do no exist, self={}", self); return -1; } @@ -868,19 +781,16 @@ int kernel_module_impl::on_sync_table_update( auto protobuf_entity = protobuf_data.mutable_data(); auto parent_container_ptr = entity_ptr->get_parent_container(); - if (parent_container_ptr != nullptr) - { + if (parent_container_ptr != nullptr) { if (!try_add_container_protobuf_entity( - parent_container_ptr, self, *protobuf_data.mutable_data(), entity_id, protobuf_entity)) - { + parent_container_ptr, self, *protobuf_data.mutable_data(), entity_id, protobuf_entity)) { ARK_LOG_ERROR("sync node failed container entity do no exist, self={}", self); return -1; } } ark::protobuf::protobuf_entity_data protobuf_row; - if (!node_to_protobuf_data(event.data_index, data, &protobuf_row)) - { + if (!node_to_protobuf_data(event.data_index, data, &protobuf_row)) { ARK_LOG_ERROR( "sync table failed table node do no exist, self={}, table={}, row={}", self, event.table_name, event.row); return -1; @@ -899,29 +809,25 @@ int kernel_module_impl::on_sync_container_place( const guid_t& self, const uint32_t index, const data_mask mask, uint32_t src_index) { // find parent entity auto entity_ptr = get_entity(self); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { ARK_LOG_ERROR("sync container failed entity do no exist, self={}", self); return -1; } auto container_ptr = entity_ptr->find_container(index); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { ARK_LOG_ERROR("sync container failed container do no exist, self={}, container={}", self, index); return -1; } auto container_entity_ptr = container_ptr->find(src_index); - if (container_entity_ptr == nullptr) - { + if (container_entity_ptr == nullptr) { ARK_LOG_ERROR("sync container failed container entity do no exist, self={}, container={}, entity={}", self, index, src_index); return -1; } - if (container_entity_ptr->is_sent()) - { + if (container_entity_ptr->is_sent()) { ark::protobuf::protobuf_container_place protobuf_data; protobuf_data.set_id(self); protobuf_data.set_index(index); @@ -929,12 +835,9 @@ int kernel_module_impl::on_sync_container_place( protobuf_data.set_entity_id(container_entity_ptr->get_id()); send_sync_msg(self, mask, protobuf_data); - } - else - { + } else { ark::protobuf::protobuf_container_create protobuf_data; - if (!entity_to_protobuf_data(container_entity_ptr, protobuf_data.mutable_data())) - { + if (!entity_to_protobuf_data(container_entity_ptr, protobuf_data.mutable_data())) { ARK_LOG_ERROR("sync container failed container entity to pb failed, self={}, container={}, entity={}", self, index, src_index); return -1; @@ -954,8 +857,7 @@ int kernel_module_impl::on_sync_container_remove( const guid_t& self, const uint32_t index, const data_mask mask, uint32_t src_index) { // find parent entity auto entity_ptr = get_entity(self); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { ARK_LOG_ERROR("sync container failed entity do no exist, self={}", self); return -1; } @@ -974,8 +876,7 @@ int kernel_module_impl::on_sync_container_destroy( const guid_t& self, const uint32_t index, const data_mask mask, uint32_t src_index) { // find parent entity auto entity_ptr = get_entity(self); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { ARK_LOG_ERROR("sync container failed entity do no exist, self={}", self); return -1; } @@ -994,8 +895,7 @@ int kernel_module_impl::on_sync_container_swap( const guid_t& self, const uint32_t index, const data_mask mask, uint32_t src_index, uint32_t dest_index) { // find parent entity auto entity_ptr = get_entity(self); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { ARK_LOG_ERROR("sync container failed entity do no exist, self={}", self); return -1; } @@ -1015,34 +915,28 @@ bool kernel_module_impl::delay_table_to_protobuf(const delay_sync_table& table, ark::protobuf::protobuf_delay_entity& data, ark::protobuf::protobuf_entity_data& protobuf_entity) { ark::protobuf::protobuf_table protobuf_table; ark::protobuf::delay_clear_row clear_row_list; - for (auto& iter : table.row_list) - { + for (auto& iter : table.row_list) { ark::protobuf::protobuf_entity_data protobuf_row; auto row_index = iter.first; auto& row_data = iter.second; - for (auto& iter_row : row_data.node_list) - { + for (auto& iter_row : row_data.node_list) { auto node_ptr = iter_row; - if (node_to_protobuf_data(node_ptr, &protobuf_row)) - { + if (node_to_protobuf_data(node_ptr, &protobuf_row)) { protobuf_table.mutable_datas_value()->insert({row_index, protobuf_row}); } } - if (row_data.need_clear) - { + if (row_data.need_clear) { clear_row_list.add_row_list(row_index); } } - if (table.need_clear) - { + if (table.need_clear) { data.add_clear_tables(index); } - if (clear_row_list.row_list_size() > 0) - { + if (clear_row_list.row_list_size() > 0) { data.mutable_clear_rows()->insert({index, clear_row_list}); } @@ -1055,29 +949,21 @@ bool kernel_module_impl::delay_container_to_protobuf(std::shared_ptr ent const delay_sync_container& container, const uint32_t index, ark::protobuf::protobuf_delay_entity& data) { ark::protobuf::delay_container protobuf_delay_container; ark::protobuf::protobuf_container protobuf_conatiner; - for (auto& iter : container.index_list) - { + for (auto& iter : container.index_list) { auto entity_index = iter; auto container_ptr = entity_ptr->find_container(index); - if (container_ptr == nullptr) - { + if (container_ptr == nullptr) { continue; } auto container_entity_ptr = container_ptr->find(entity_index); - if (container_entity_ptr == nullptr) - { + if (container_entity_ptr == nullptr) { protobuf_delay_container.mutable_entity_list()->insert({entity_index, null_guid}); - } - else if (entity_ptr->is_sent()) - { + } else if (entity_ptr->is_sent()) { protobuf_delay_container.mutable_entity_list()->insert({entity_index, container_entity_ptr->get_id()}); - } - else - { + } else { ark::protobuf::protobuf_entity protobuf_container_entity; - if (!entity_to_protobuf_data(container_entity_ptr, &protobuf_container_entity)) - { + if (!entity_to_protobuf_data(container_entity_ptr, &protobuf_container_entity)) { continue; } @@ -1085,15 +971,13 @@ bool kernel_module_impl::delay_container_to_protobuf(std::shared_ptr ent } } - if (protobuf_conatiner.datas_value_size() > 0) - { + if (protobuf_conatiner.datas_value_size() > 0) { data.mutable_data()->mutable_datas_container()->insert({index, protobuf_conatiner}); } data.mutable_container_entity()->insert({index, protobuf_delay_container}); ark::protobuf::delay_container protobuf_destroy_entity; - for (auto& iter : container.destroy_list) - { + for (auto& iter : container.destroy_list) { auto entity_index = iter; protobuf_destroy_entity.mutable_entity_list()->insert({entity_index, null_guid}); } @@ -1108,15 +992,13 @@ bool kernel_module_impl::try_add_container_protobuf_entity(std::shared_ptrget_parent_id(); auto parent_entity_ptr = get_entity(parent_id); - if (parent_entity_ptr == nullptr) - { + if (parent_entity_ptr == nullptr) { ARK_LOG_ERROR("parent entity do no exist, parent={}", parent_id); return false; } auto self_index = container_ptr->find(self); - if (self_index == 0) - { + if (self_index == 0) { ARK_LOG_ERROR("entity is not in container, self={}", self); return false; } @@ -1124,8 +1006,7 @@ bool kernel_module_impl::try_add_container_protobuf_entity(std::shared_ptrinsert({container_ptr->get_index(), protobuf_container}); - if (!result_container.second) - { + if (!result_container.second) { ARK_LOG_ERROR("entity insert container failed, self={} container index = {}", self, container_ptr->get_index()); return false; } @@ -1133,8 +1014,7 @@ bool kernel_module_impl::try_add_container_protobuf_entity(std::shared_ptrinsert({self_index, protobuf_entity}); - if (!result_entity.second) - { + if (!result_entity.second) { ARK_LOG_ERROR("container insert entity failed, self={} container index = {}", self, container_ptr->get_index()); return false; } @@ -1147,8 +1027,7 @@ bool kernel_module_impl::try_add_container_protobuf_entity(std::shared_ptrget_inst_entity_list(map_id, inst_id, map_inst_entity_list); - for (size_t i = 0; i < map_inst_entity_list.get_count(); i++) - { + for (size_t i = 0; i < map_inst_entity_list.get_count(); i++) { auto view_entity_ptr = get_entity(map_inst_entity_list.int64(i)); - if (view_entity_ptr == nullptr) - { + if (view_entity_ptr == nullptr) { continue; } const std::string& obj_class_name = view_entity_ptr->get_class_name(); - if (entity_meta_player::self_name() == obj_class_name) - { + if (entity_meta_player::self_name() == obj_class_name) { send_to_self(view_entity_ptr->get_id(), msg); } } @@ -1218,8 +1093,7 @@ bool kernel_module_impl::log_self_info(const guid_t& id) { int kernel_module_impl::log_object_data(const guid_t& guid) { auto entity = get_entity(guid); - if (entity == nullptr) - { + if (entity == nullptr) { return -1; } @@ -1230,11 +1104,9 @@ int kernel_module_impl::log_object_data(const guid_t& guid) { ARK_ASSERT_RET_VAL(table_manager_ptr != nullptr, -1); auto& node_list = node_manager_ptr->get_data_list(); - for (auto& iter : node_list) - { + for (auto& iter : node_list) { auto data_ptr = iter.second; - if (!data_ptr) - { + if (!data_ptr) { continue; } @@ -1242,28 +1114,22 @@ int kernel_module_impl::log_object_data(const guid_t& guid) { } auto& table_list = table_manager_ptr->get_table_list(); - for (auto& iter : table_list) - { + for (auto& iter : table_list) { auto table_ptr = iter.second; - if (!table_ptr) - { + if (!table_ptr) { continue; } - for (auto row_ptr = table_ptr->first(); row_ptr != nullptr; row_ptr = table_ptr->next()) - { + for (auto row_ptr = table_ptr->first(); row_ptr != nullptr; row_ptr = table_ptr->next()) { auto row_node_manager_ptr = get_node_manager(row_ptr); - if (!row_node_manager_ptr) - { + if (!row_node_manager_ptr) { continue; } auto& row_data_list = row_node_manager_ptr->get_data_list(); - for (auto& iter_row : row_data_list) - { + for (auto& iter_row : row_data_list) { auto node_ptr = iter_row.second; - if (!node_ptr) - { + if (!node_ptr) { continue; } @@ -1278,27 +1144,22 @@ int kernel_module_impl::log_object_data(const guid_t& guid) { bool kernel_module_impl::log_info(const guid_t& id) { std::shared_ptr entity_ptr = get_entity(id); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { ARK_LOG_ERROR("Cannot find entity, id = {}", id); return false; } - if (map_module_->is_in_map_instance(id)) - { + if (map_module_->is_in_map_instance(id)) { int map_id = entity_ptr->get_map_id(); ARK_LOG_INFO("----------child object list-------- , id = {} mapid = {}", id, map_id); data_list_impl entity_list; int online_count = map_module_->get_map_online_list(map_id, entity_list); - for (int i = 0; i < online_count; ++i) - { + for (int i = 0; i < online_count; ++i) { guid_t target_entity_id = entity_list.int64(i); ARK_LOG_INFO("id = {} mapid = {}", target_entity_id, map_id); } - } - else - { + } else { ARK_LOG_INFO("---------print object start--------, id = {}", id); ARK_LOG_INFO("---------print object end--------, id = {}", id); } @@ -1333,16 +1194,13 @@ bool kernel_module_impl::entity_to_db_data( // node to db auto& node_list = node_manager_ptr->get_data_list(); - for (auto& iter : node_list) - { + for (auto& iter : node_list) { auto node_ptr = iter.second; - if (!node_ptr) - { + if (!node_ptr) { continue; } - if (!node_ptr->have_mask(data_mask::pf_save)) - { + if (!node_ptr->have_mask(data_mask::pf_save)) { continue; } @@ -1351,22 +1209,18 @@ bool kernel_module_impl::entity_to_db_data( // table to db auto& table_list = table_manager_ptr->get_table_list(); - for (auto& iter : table_list) - { + for (auto& iter : table_list) { auto table_ptr = iter.second; - if (!table_ptr) - { + if (!table_ptr) { continue; } - if (!table_ptr->have_mask(data_mask::pf_save)) - { + if (!table_ptr->have_mask(data_mask::pf_save)) { continue; } ark::protobuf::protobuf_db_table protobuf_table; - if (!table_to_db_data(table_ptr, protobuf_table)) - { + if (!table_to_db_data(table_ptr, protobuf_table)) { continue; } @@ -1375,34 +1229,28 @@ bool kernel_module_impl::entity_to_db_data( // container to db auto& container_list = container_manager_ptr->get_container_list(); - for (auto& iter : container_list) - { + for (auto& iter : container_list) { auto container_ptr = iter.second; - if (!container_ptr) - { + if (!container_ptr) { continue; } ark::protobuf::protobuf_db_container protobuf_container; - for (auto index = container_ptr->first(); index > 0; index = container_ptr->next()) - { + for (auto index = container_ptr->first(); index > 0; index = container_ptr->next()) { auto sub_entity_ptr = container_ptr->find(index); - if (!sub_entity_ptr) - { + if (!sub_entity_ptr) { continue; } ark::protobuf::protobuf_db_entity protobuf_container_entity; - if (!entity_to_db_data(sub_entity_ptr, protobuf_container_entity)) - { + if (!entity_to_db_data(sub_entity_ptr, protobuf_container_entity)) { continue; } protobuf_container.mutable_datas_value()->insert({index, protobuf_container_entity}); } - if (protobuf_container.datas_value_size() > 0) - { + if (protobuf_container.datas_value_size() > 0) { protobuf_data.mutable_data()->mutable_datas_entity()->insert( {container_ptr->get_name(), protobuf_container}); } @@ -1414,16 +1262,14 @@ bool kernel_module_impl::entity_to_db_data( std::shared_ptr kernel_module_impl::create_entity(const ark::protobuf::protobuf_db_entity& protobuf_data) { auto entity_id = protobuf_data.id(); auto entity_ptr = get_entity(entity_id); - if (entity_ptr != nullptr) - { + if (entity_ptr != nullptr) { ARK_LOG_ERROR("entity already exists, object = {}", entity_id); return nullptr; } const std::string& class_name = protobuf_data.class_name(); auto class_meta_ptr = class_meta_module_->find_meta(class_name); - if (nullptr == class_meta_ptr) - { + if (nullptr == class_meta_ptr) { ARK_LOG_ERROR("There is no class meta, name = {}", class_name); return nullptr; } @@ -1431,8 +1277,7 @@ std::shared_ptr kernel_module_impl::create_entity(const ark::protobuf::p auto map_id = protobuf_data.map_id(); auto map_inst_id = protobuf_data.map_inst_id(); auto map_info_ptr = map_module_->get_map_info(map_id); - if (map_info_ptr == nullptr) - { + if (map_info_ptr == nullptr) { ARK_LOG_ERROR("There is no scene, scene = {}", map_id); return nullptr; } @@ -1443,8 +1288,7 @@ std::shared_ptr kernel_module_impl::create_entity(const ark::protobuf::p objects_.insert(entity_id, entity_ptr); - if (class_name == entity_meta_player::self_name()) - { + if (class_name == entity_meta_player::self_name()) { map_info_ptr->add_entity_to_instance(map_inst_id, entity_id, true); } //else if (class_name == AFEntityMetaPlayer::self_name()) // to do : npc type for now we do not have @@ -1456,24 +1300,20 @@ std::shared_ptr kernel_module_impl::create_entity(const ark::protobuf::p // node data auto node_manager_ptr = entity_impl_ptr->get_node_manager(); - if (nullptr != node_manager_ptr) - { + if (nullptr != node_manager_ptr) { db_data_to_node(node_manager_ptr, protobuf_db_entity_data); } // table data auto table_manager_ptr = entity_impl_ptr->get_table_manager(); - if (nullptr != table_manager_ptr) - { - for (auto& iter : protobuf_db_entity_data.datas_table()) - { + if (nullptr != table_manager_ptr) { + for (auto& iter : protobuf_db_entity_data.datas_table()) { db_data_to_table(entity_ptr, iter.first, iter.second); } } // container data - for (auto& iter : protobuf_db_entity_data.datas_entity()) - { + for (auto& iter : protobuf_db_entity_data.datas_entity()) { db_data_to_container(entity_ptr, iter.first, iter.second); } @@ -1497,11 +1337,9 @@ bool kernel_module_impl::send_custom_message(const guid_t& target, const uint32_ custom_message.set_message_id(msg_id); size_t count = args.get_count(); - for (size_t i = 0; i < count; i++) - { + for (size_t i = 0; i < count; i++) { auto data_type = args.get_type(i); - switch (data_type) - { + switch (data_type) { case ark::data_type::dt_boolean: custom_message.add_data_list()->set_bool_value(args.get_bool(i)); break; @@ -1545,24 +1383,20 @@ bool kernel_module_impl::db_data_to_table(std::shared_ptr entity_ptr, co auto table_impl_ptr = dynamic_cast(table_ptr); ARK_ASSERT_RET_VAL(table_impl_ptr != nullptr, false); - for (auto& iter : protobuf_table.datas_value()) - { + for (auto& iter : protobuf_table.datas_value()) { auto row_index = iter.first; - if (row_index == null_int) - { + if (row_index == null_int) { continue; } auto& protobuf_db_entity_data = iter.second; auto row_ptr = table_impl_ptr->create_row(row_index, data_list_impl()); - if (row_ptr == nullptr) - { + if (row_ptr == nullptr) { continue; } auto node_manager_ptr = get_node_manager(row_ptr); - if (node_manager_ptr == nullptr) - { + if (node_manager_ptr == nullptr) { continue; } @@ -1575,22 +1409,18 @@ bool kernel_module_impl::db_data_to_table(std::shared_ptr entity_ptr, co bool kernel_module_impl::db_data_to_container(std::shared_ptr entity_ptr, const std::string& name, const ark::protobuf::protobuf_db_container& protobuf_data) { auto container_ptr = entity_ptr->find_container(name); - if (nullptr == container_ptr) - { + if (nullptr == container_ptr) { return false; } auto container_impl_ptr = std::dynamic_pointer_cast(container_ptr); - if (nullptr == container_impl_ptr) - { + if (nullptr == container_impl_ptr) { return false; } - for (auto& iter : protobuf_data.datas_value()) - { + for (auto& iter : protobuf_data.datas_value()) { auto container_entity_ptr = create_entity(iter.second); - if (nullptr == container_entity_ptr) - { + if (nullptr == container_entity_ptr) { continue; } @@ -1602,8 +1432,7 @@ bool kernel_module_impl::db_data_to_container(std::shared_ptr entity_ptr int kernel_module_impl::on_container_call_back(const guid_t& self, const uint32_t index, const container_op_type op_type, const uint32_t src_index, const uint32_t dest_index) { - if (op_type == container_op_type::op_destroy) - { + if (op_type == container_op_type::op_destroy) { // destroy entity auto entity_ptr = get_entity(self); ARK_ASSERT_RET_VAL(entity_ptr != nullptr, 0); @@ -1623,11 +1452,9 @@ int kernel_module_impl::on_container_call_back(const guid_t& self, const uint32_ bool kernel_module_impl::db_data_to_node(std::shared_ptr node_manager_ptr, const ark::protobuf::protobuf_db_entity_data& protobuf_db_entity_data) { //bool data - for (auto& iter : protobuf_db_entity_data.datas_bool()) - { + for (auto& iter : protobuf_db_entity_data.datas_bool()) { auto node_ptr = node_manager_ptr->create_data(iter.first); - if (node_ptr == nullptr) - { + if (node_ptr == nullptr) { continue; } @@ -1635,11 +1462,9 @@ bool kernel_module_impl::db_data_to_node(std::shared_ptr node_mana } //int32 data - for (auto& iter : protobuf_db_entity_data.datas_int32()) - { + for (auto& iter : protobuf_db_entity_data.datas_int32()) { auto node_ptr = node_manager_ptr->create_data(iter.first); - if (node_ptr == nullptr) - { + if (node_ptr == nullptr) { continue; } @@ -1647,11 +1472,9 @@ bool kernel_module_impl::db_data_to_node(std::shared_ptr node_mana } //uint32 data - for (auto& iter : protobuf_db_entity_data.datas_uint32()) - { + for (auto& iter : protobuf_db_entity_data.datas_uint32()) { auto node_ptr = node_manager_ptr->create_data(iter.first); - if (node_ptr == nullptr) - { + if (node_ptr == nullptr) { continue; } @@ -1659,11 +1482,9 @@ bool kernel_module_impl::db_data_to_node(std::shared_ptr node_mana } //int64 data - for (auto& iter : protobuf_db_entity_data.datas_int64()) - { + for (auto& iter : protobuf_db_entity_data.datas_int64()) { auto node_ptr = node_manager_ptr->create_data(iter.first); - if (node_ptr == nullptr) - { + if (node_ptr == nullptr) { continue; } @@ -1671,11 +1492,9 @@ bool kernel_module_impl::db_data_to_node(std::shared_ptr node_mana } //uint64 data - for (auto& iter : protobuf_db_entity_data.datas_uint64()) - { + for (auto& iter : protobuf_db_entity_data.datas_uint64()) { auto node_ptr = node_manager_ptr->create_data(iter.first); - if (node_ptr == nullptr) - { + if (node_ptr == nullptr) { continue; } @@ -1683,11 +1502,9 @@ bool kernel_module_impl::db_data_to_node(std::shared_ptr node_mana } //float data - for (auto& iter : protobuf_db_entity_data.datas_float()) - { + for (auto& iter : protobuf_db_entity_data.datas_float()) { auto node_ptr = node_manager_ptr->create_data(iter.first); - if (node_ptr == nullptr) - { + if (node_ptr == nullptr) { continue; } @@ -1695,11 +1512,9 @@ bool kernel_module_impl::db_data_to_node(std::shared_ptr node_mana } //double data - for (auto& iter : protobuf_db_entity_data.datas_double()) - { + for (auto& iter : protobuf_db_entity_data.datas_double()) { auto node_ptr = node_manager_ptr->create_data(iter.first); - if (node_ptr == nullptr) - { + if (node_ptr == nullptr) { continue; } @@ -1707,11 +1522,9 @@ bool kernel_module_impl::db_data_to_node(std::shared_ptr node_mana } //string data - for (auto& iter : protobuf_db_entity_data.datas_string()) - { + for (auto& iter : protobuf_db_entity_data.datas_string()) { auto node_ptr = node_manager_ptr->create_data(iter.first); - if (node_ptr == nullptr) - { + if (node_ptr == nullptr) { continue; } @@ -1726,8 +1539,7 @@ bool kernel_module_impl::node_to_db_data(node* node_ptr, ark::protobuf::protobuf ARK_ASSERT_RET_VAL(node_ptr != nullptr, false); auto& name = node_ptr->get_name(); - switch (node_ptr->get_type()) - { + switch (node_ptr->get_type()) { case data_type::dt_boolean: protobuf_data.mutable_datas_bool()->insert({name, node_ptr->get_bool()}); break; @@ -1763,19 +1575,16 @@ bool kernel_module_impl::node_to_db_data(node* node_ptr, ark::protobuf::protobuf bool kernel_module_impl::table_to_db_data(table* table_ptr, ark::protobuf::protobuf_db_table& protobuf_data) { ARK_ASSERT_RET_VAL(table_ptr != nullptr, false); - for (auto row_ptr = table_ptr->first(); row_ptr != nullptr; row_ptr = table_ptr->next()) - { + for (auto row_ptr = table_ptr->first(); row_ptr != nullptr; row_ptr = table_ptr->next()) { auto node_manager_ptr = get_node_manager(row_ptr); - if (!node_manager_ptr) - { + if (!node_manager_ptr) { continue; } ark::protobuf::protobuf_db_entity_data row_data; auto& data_list = node_manager_ptr->get_data_list(); - for (auto& iter : data_list) - { + for (auto& iter : data_list) { node_to_db_data(iter.second, row_data); } @@ -1790,8 +1599,7 @@ bool kernel_module_impl::node_to_protobuf_data(node* node_ptr, ark::protobuf::pr ARK_ASSERT_RET_VAL(node_ptr != nullptr && protobuf_data != nullptr, false); auto index = node_ptr->get_index(); - switch (node_ptr->get_type()) - { + switch (node_ptr->get_type()) { case data_type::dt_boolean: protobuf_data->mutable_datas_bool()->insert({index, node_ptr->get_bool()}); break; @@ -1828,8 +1636,7 @@ bool kernel_module_impl::node_to_protobuf_data( const uint32_t index, const data& data, ark::protobuf::protobuf_entity_data* protobuf_data) { ARK_ASSERT_RET_VAL(index > 0 && protobuf_data != nullptr, false); - switch (data.get_type()) - { + switch (data.get_type()) { case data_type::dt_boolean: protobuf_data->mutable_datas_bool()->insert({index, data.get_bool()}); break; @@ -1866,11 +1673,9 @@ bool kernel_module_impl::table_to_protobuf_data( table* table_ptr, const uint32_t index, ark::protobuf::protobuf_table* protobuf_data) { ARK_ASSERT_RET_VAL(table_ptr != nullptr && index > 0 && protobuf_data != nullptr, false); - for (row* row_ptr = table_ptr->first(); row_ptr != nullptr; row_ptr = table_ptr->next()) - { + for (row* row_ptr = table_ptr->first(); row_ptr != nullptr; row_ptr = table_ptr->next()) { ark::protobuf::protobuf_entity_data row_data; - if (!row_to_protobuf_data(row_ptr, row_ptr->get_row(), &row_data)) - { + if (!row_to_protobuf_data(row_ptr, row_ptr->get_row(), &row_data)) { continue; } @@ -1884,17 +1689,14 @@ bool kernel_module_impl::container_to_protobuf_data( std::shared_ptr container_ptr, ark::protobuf::protobuf_container* protobuf_data) { ARK_ASSERT_RET_VAL(container_ptr != nullptr && protobuf_data != nullptr, false); - for (auto index = container_ptr->first(); index > 0; index = container_ptr->next()) - { + for (auto index = container_ptr->first(); index > 0; index = container_ptr->next()) { auto entity_ptr = container_ptr->find(index); - if (nullptr == entity_ptr) - { + if (nullptr == entity_ptr) { continue; } ark::protobuf::protobuf_entity protobuf_entity; - if (!entity_to_protobuf_data(entity_ptr, &protobuf_entity)) - { + if (!entity_to_protobuf_data(entity_ptr, &protobuf_entity)) { continue; } @@ -1909,14 +1711,12 @@ bool kernel_module_impl::row_to_protobuf_data( ARK_ASSERT_RET_VAL(row_ptr != nullptr && index > 0 && protobuf_data != nullptr, false); auto node_manager_ptr = get_node_manager(row_ptr); - if (!node_manager_ptr) - { + if (!node_manager_ptr) { return false; } auto& data_list = node_manager_ptr->get_data_list(); - for (auto& iter : data_list) - { + for (auto& iter : data_list) { node_to_protobuf_data(iter.second, protobuf_data); } @@ -1928,8 +1728,7 @@ bool kernel_module_impl::table_row_data_to_protobuf_data(const uint32_t index, u ARK_ASSERT_RET_VAL(index > 0 && row > 0 && col > 0 && protobuf_data != nullptr, false); ark::protobuf::protobuf_entity_data row_data; - if (!node_to_protobuf_data(col, data, &row_data)) - { + if (!node_to_protobuf_data(col, data, &row_data)) { return false; } @@ -1979,26 +1778,21 @@ bool kernel_module_impl::entity_container_to_protobuf_data( ARK_ASSERT_RET_VAL(container_manager_ptr != nullptr, false); auto& container_list = container_manager_ptr->get_container_list(); - for (auto& iter : container_list) - { + for (auto& iter : container_list) { auto container_ptr = iter.second; - if (!container_ptr) - { + if (!container_ptr) { continue; } - if (!mask.none()) - { + if (!mask.none()) { auto result = (container_ptr->get_mask() & mask); - if (!result.any()) - { + if (!result.any()) { continue; } } ark::protobuf::protobuf_container protobuf_container; - if (!container_to_protobuf_data(container_ptr, &protobuf_container)) - { + if (!container_to_protobuf_data(container_ptr, &protobuf_container)) { continue; } @@ -2017,19 +1811,15 @@ bool kernel_module_impl::entity_node_to_protobuf_data(std::shared_ptr en ARK_ASSERT_RET_VAL(node_manager_ptr != nullptr, false); auto& data_list = node_manager_ptr->get_data_list(); - for (auto& iter : data_list) - { + for (auto& iter : data_list) { auto node_ptr = iter.second; - if (!node_ptr) - { + if (!node_ptr) { continue; } - if (!mask.none()) - { + if (!mask.none()) { auto result = (node_ptr->get_mask() & mask); - if (!result.any()) - { + if (!result.any()) { continue; } } @@ -2048,19 +1838,15 @@ bool kernel_module_impl::entity_table_to_protobuf_data(std::shared_ptr e ARK_ASSERT_RET_VAL(table_manager_ptr != nullptr, false); auto& data_list = table_manager_ptr->get_table_list(); - for (auto& iter : data_list) - { + for (auto& iter : data_list) { auto table_ptr = iter.second; - if (!table_ptr) - { + if (!table_ptr) { continue; } - if (!mask.none()) - { + if (!mask.none()) { auto result = (table_ptr->get_mask() & mask); - if (!result.any()) - { + if (!result.any()) { continue; } } @@ -2068,8 +1854,7 @@ bool kernel_module_impl::entity_table_to_protobuf_data(std::shared_ptr e const auto index = table_ptr->get_index(); ark::protobuf::protobuf_table table_data; - if (!table_to_protobuf_data(table_ptr, index, &table_data)) - { + if (!table_to_protobuf_data(table_ptr, index, &table_data)) { continue; } @@ -2082,14 +1867,12 @@ bool kernel_module_impl::entity_table_to_protobuf_data(std::shared_ptr e // -----------get entity manager-------------- std::shared_ptr kernel_module_impl::get_node_manager( std::shared_ptr static_entity_ptr) const { - if (static_entity_ptr == nullptr) - { + if (static_entity_ptr == nullptr) { return nullptr; } auto static_entity_impl_ptr = std::dynamic_pointer_cast(static_entity_ptr); - if (static_entity_impl_ptr == nullptr) - { + if (static_entity_impl_ptr == nullptr) { return nullptr; } @@ -2097,14 +1880,12 @@ std::shared_ptr kernel_module_impl::get_node_manager( } std::shared_ptr kernel_module_impl::get_node_manager(std::shared_ptr entity_ptr) const { - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { return nullptr; } auto entity_impl_ptr = std::dynamic_pointer_cast(entity_ptr); - if (entity_impl_ptr == nullptr) - { + if (entity_impl_ptr == nullptr) { return nullptr; } @@ -2112,14 +1893,12 @@ std::shared_ptr kernel_module_impl::get_node_manager(std::shared_p } std::shared_ptr kernel_module_impl::get_node_manager(row* row_ptr) const { - if (row_ptr == nullptr) - { + if (row_ptr == nullptr) { return nullptr; } auto row_impl_ptr = dynamic_cast(row_ptr); - if (row_impl_ptr == nullptr) - { + if (row_impl_ptr == nullptr) { return nullptr; } @@ -2127,14 +1906,12 @@ std::shared_ptr kernel_module_impl::get_node_manager(row* row_ptr) } std::shared_ptr kernel_module_impl::get_table_manager(std::shared_ptr entity_ptr) const { - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { return nullptr; } auto entity_impl_ptr = std::dynamic_pointer_cast(entity_ptr); - if (entity_impl_ptr == nullptr) - { + if (entity_impl_ptr == nullptr) { return nullptr; } @@ -2142,14 +1919,12 @@ std::shared_ptr kernel_module_impl::get_table_manager(std::shared } std::shared_ptr kernel_module_impl::get_container_manager(std::shared_ptr entity_ptr) const { - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { return nullptr; } auto entity_impl_ptr = std::dynamic_pointer_cast(entity_ptr); - if (entity_impl_ptr == nullptr) - { + if (entity_impl_ptr == nullptr) { return nullptr; } @@ -2157,14 +1932,12 @@ std::shared_ptr kernel_module_impl::get_container_manager(std } std::shared_ptr kernel_module_impl::get_event_manager(std::shared_ptr entity_ptr) const { - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { return nullptr; } auto entity_impl_ptr = std::dynamic_pointer_cast(entity_ptr); - if (entity_impl_ptr == nullptr) - { + if (entity_impl_ptr == nullptr) { return nullptr; } diff --git a/src/plugins/kernel/kernel_module_impl.hpp b/src/plugins/kernel/kernel_module_impl.hpp index 98a80f054..260452056 100644 --- a/src/plugins/kernel/kernel_module_impl.hpp +++ b/src/plugins/kernel/kernel_module_impl.hpp @@ -37,8 +37,7 @@ namespace ark { -class kernel_module_impl final : public module_base -{ +class kernel_module_impl final : public module_base { public: explicit kernel_module_impl(); ~kernel_module_impl() override; diff --git a/src/plugins/kernel/kernel_plugin.cpp b/src/plugins/kernel/kernel_plugin.cpp index 6efbe7c0c..673009ea0 100644 --- a/src/plugins/kernel/kernel_plugin.cpp +++ b/src/plugins/kernel/kernel_plugin.cpp @@ -35,39 +35,31 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void kernel_plugin::install() { - if (!register_module(detail::make_class_meta_module(), module_update::disabled)) - { + if (!register_module(detail::make_class_meta_module(), module_update::disabled)) { throw std::runtime_error("kernel class_meta_module registration rejected"); } - if (!register_module(detail::make_config_module(), module_update::disabled)) - { + if (!register_module(detail::make_config_module(), module_update::disabled)) { throw std::runtime_error("kernel config_module registration rejected"); } - if (!register_module(detail::make_kernel_module(), module_update::enabled)) - { + if (!register_module(detail::make_kernel_module(), module_update::enabled)) { throw std::runtime_error("kernel kernel_module registration rejected"); } - if (!register_module(detail::make_map_module(), module_update::disabled)) - { + if (!register_module(detail::make_map_module(), module_update::disabled)) { throw std::runtime_error("kernel map_module registration rejected"); } } void kernel_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("kernel map_module unregistration rejected"); } - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("kernel kernel_module unregistration rejected"); } - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("kernel config_module unregistration rejected"); } - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("kernel class_meta_module unregistration rejected"); } } diff --git a/src/plugins/kernel/kernel_plugin.hpp b/src/plugins/kernel/kernel_plugin.hpp index 936477555..3bd204f84 100644 --- a/src/plugins/kernel/kernel_plugin.hpp +++ b/src/plugins/kernel/kernel_plugin.hpp @@ -24,8 +24,7 @@ namespace ark { -class kernel_plugin final : public plugin_base -{ +class kernel_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/plugins/kernel/map_module.hpp b/src/plugins/kernel/map_module.hpp index e58647820..57286cb06 100644 --- a/src/plugins/kernel/map_module.hpp +++ b/src/plugins/kernel/map_module.hpp @@ -29,8 +29,7 @@ namespace ark { // Map instance -class map_instance -{ +class map_instance { public: explicit map_instance(int inst_id) : inst_id(inst_id) { @@ -42,8 +41,7 @@ class map_instance }; // All instance in this map -class map_info -{ +class map_info { public: map_info() = default; @@ -84,18 +82,12 @@ class map_info bool add_entity_to_instance(const int inst_id, const guid_t& entity_id, bool is_player) { std::shared_ptr info_ptr = map_instances_.find_value(inst_id); - if (info_ptr == nullptr) - { + if (info_ptr == nullptr) { return false; - } - else - { - if (is_player) - { + } else { + if (is_player) { return info_ptr->player_entities.insert(entity_id, nullptr).second; // TODO:Map.second mean nothing - } - else - { + } else { return info_ptr->other_entities.insert(entity_id, nullptr).second; // TODO:Map.second mean nothing } } @@ -103,18 +95,12 @@ class map_info bool remove_entity_from_instance(const int inst_id, const guid_t& entity_id, bool is_player) { std::shared_ptr info_ptr = map_instances_.find_value(inst_id); - if (nullptr == info_ptr) - { + if (nullptr == info_ptr) { return false; - } - else - { - if (is_player) - { + } else { + if (is_player) { return info_ptr->player_entities.erase(entity_id); - } - else - { + } else { return info_ptr->other_entities.erase(entity_id); } } @@ -127,8 +113,7 @@ class map_info shared_object_map map_instances_; }; -class map_module : public module -{ +class map_module : public module { public: virtual std::shared_ptr get_map_info(const int map_id) = 0; diff --git a/src/plugins/kernel/map_module_impl.cpp b/src/plugins/kernel/map_module_impl.cpp index 6af313424..bc025078f 100644 --- a/src/plugins/kernel/map_module_impl.cpp +++ b/src/plugins/kernel/map_module_impl.cpp @@ -43,12 +43,9 @@ std::shared_ptr map_module_impl::get_map_info(const int map_id) { bool map_module_impl::is_in_map_instance(const guid_t& self) { auto entity_ptr = kernel_module_->get_entity(self); - if (entity_ptr != nullptr) - { + if (entity_ptr != nullptr) { return (entity_ptr->get_int32(entity_meta_base_entity::map_inst_id()) < 0); - } - else - { + } else { ARK_LOG_ERROR("Cannot find entity, id = {}", self); return false; } @@ -62,8 +59,7 @@ bool map_module_impl::exist_map(const int map_id) { bool map_module_impl::switch_map(const guid_t& self, const int target_map, const int target_inst, const vector3d& pos, const float orient, const data_list& args) { auto entity_ptr = kernel_module_->get_entity(self); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { ARK_LOG_ERROR("Cannot find entity, id = {}", self); return false; } @@ -74,20 +70,17 @@ bool map_module_impl::switch_map(const guid_t& self, const int target_map, const std::shared_ptr old_map_info_ptr = map_infos_.find_value(old_map); std::shared_ptr new_map_info_ptr = map_infos_.find_value(target_map); - if (nullptr == old_map_info_ptr) - { + if (nullptr == old_map_info_ptr) { ARK_LOG_ERROR("cannot find this map, id={}", old_map); return false; } - if (nullptr == new_map_info_ptr) - { + if (nullptr == new_map_info_ptr) { ARK_LOG_ERROR("cannot tind this map, id = {}", target_map); return false; } - if (!new_map_info_ptr->exist_instance(target_inst)) - { + if (!new_map_info_ptr->exist_instance(target_inst)) { ARK_LOG_ERROR("Cannot find this map instance, map={} inst={}", target_map, target_inst); return false; } @@ -112,14 +105,12 @@ bool map_module_impl::switch_map(const guid_t& self, const int target_map, const bool map_module_impl::create_map(const int map_id) { auto map_info_ptr = map_infos_.find_value(map_id); - if (map_info_ptr != nullptr) - { + if (map_info_ptr != nullptr) { return false; } map_info_ptr = std::make_shared(); - if (map_info_ptr == nullptr) - { + if (map_info_ptr == nullptr) { return false; } @@ -127,8 +118,7 @@ bool map_module_impl::create_map(const int map_id) { // create group 0 auto map_inst_ptr = std::make_shared(0); - if (nullptr == map_inst_ptr) - { + if (nullptr == map_inst_ptr) { return false; } @@ -143,12 +133,10 @@ bool map_module_impl::destroy_map(const int map_id) { int map_module_impl::get_online_count() { int online_count = 0; - for (auto iter : map_infos_) - { + for (auto iter : map_infos_) { auto map_info_ptr = iter.second; auto& all_instances = map_info_ptr->get_all_instance(); - for (auto it : all_instances) - { + for (auto it : all_instances) { online_count += it.second->player_entities.size(); } } @@ -166,14 +154,12 @@ int map_module_impl::get_map_online_count(const int map_id) { int online_count = 0; auto map_info_ptr = map_infos_.find_value(map_id); - if (map_info_ptr == nullptr) - { + if (map_info_ptr == nullptr) { return online_count; } auto all_instances = map_info_ptr->get_all_instance(); - for (auto iter : all_instances) - { + for (auto iter : all_instances) { online_count += iter.second->player_entities.size(); } @@ -184,14 +170,12 @@ int map_module_impl::get_map_online_count(const int map_id, const int map_instan int online_count = 0; auto map_info_ptr = map_infos_.find_value(map_id); - if (map_info_ptr == nullptr) - { + if (map_info_ptr == nullptr) { return online_count; } auto map_inst_ptr = map_info_ptr->get_instance(map_instance_id); - if (map_inst_ptr == nullptr) - { + if (map_inst_ptr == nullptr) { return online_count; } @@ -201,17 +185,14 @@ int map_module_impl::get_map_online_count(const int map_id, const int map_instan int map_module_impl::get_map_online_list(const int map_id, data_list& list) { auto map_info_ptr = map_infos_.find_value(map_id); - if (map_info_ptr == nullptr) - { + if (map_info_ptr == nullptr) { return 0; } auto all_instances = map_info_ptr->get_all_instance(); - for (auto iter : all_instances) - { + for (auto iter : all_instances) { auto map_instance_ptr = iter.second; - for (auto it : map_instance_ptr->player_entities) - { + for (auto it : map_instance_ptr->player_entities) { list.add_int64(it.first); } } @@ -221,21 +202,18 @@ int map_module_impl::get_map_online_list(const int map_id, data_list& list) { int map_module_impl::create_map_instance(const int map_id) { auto map_info_ptr = map_infos_.find_value(map_id); - if (map_info_ptr == nullptr) - { + if (map_info_ptr == nullptr) { return -1; } int new_inst_id = map_info_ptr->create_instance_id(); - if (map_info_ptr->exist_instance(new_inst_id)) - { + if (map_info_ptr->exist_instance(new_inst_id)) { return -1; } auto map_instance_ptr = std::make_shared(new_inst_id); - if (map_instance_ptr == nullptr) - { + if (map_instance_ptr == nullptr) { return -1; } @@ -245,26 +223,21 @@ int map_module_impl::create_map_instance(const int map_id) { bool map_module_impl::release_map_instance(const int map_id, const int inst_id) { auto map_info_ptr = map_infos_.find_value(map_id); - if (nullptr == map_info_ptr) - { + if (nullptr == map_info_ptr) { return false; } - if (!map_info_ptr->exist_instance(inst_id)) - { + if (!map_info_ptr->exist_instance(inst_id)) { return false; } data_list_impl list_object; - if (get_inst_entity_list(map_id, inst_id, list_object)) - { - for (size_t i = 0; i < list_object.get_count(); ++i) - { + if (get_inst_entity_list(map_id, inst_id, list_object)) { + for (size_t i = 0; i < list_object.get_count(); ++i) { guid_t ident = list_object.int64(i); - if (!kernel_module_->destroy_entity(ident)) - { + if (!kernel_module_->destroy_entity(ident)) { ARK_LOG_ERROR("Destory entity failed, id = {}, please check", ident); } } @@ -277,8 +250,7 @@ bool map_module_impl::release_map_instance(const int map_id, const int inst_id) bool map_module_impl::exit_map_instance(const int map_id, const int inst_id) { auto map_info_ptr = map_infos_.find_value(map_id); - if (map_info_ptr == nullptr) - { + if (map_info_ptr == nullptr) { return false; } @@ -288,24 +260,20 @@ bool map_module_impl::exit_map_instance(const int map_id, const int inst_id) { bool map_module_impl::get_inst_entity_list(const int map_id, const int inst_id, data_list& list) { auto map_info_ptr = map_infos_.find_value(map_id); - if (map_info_ptr == nullptr) - { + if (map_info_ptr == nullptr) { return false; } auto map_instance_ptr = map_info_ptr->get_instance(inst_id); - if (map_instance_ptr == nullptr) - { + if (map_instance_ptr == nullptr) { return false; } - for (auto iter : map_instance_ptr->player_entities) - { + for (auto iter : map_instance_ptr->player_entities) { list.add_int64(iter.first); } - for (auto iter : map_instance_ptr->other_entities) - { + for (auto iter : map_instance_ptr->other_entities) { list.add_int64(iter.first); } @@ -317,23 +285,19 @@ int map_module_impl::get_entity_by_data_node( data_list_impl var_object_list; get_map_online_list(map_id, var_object_list); size_t entity_count = var_object_list.get_count(); - for (size_t i = 0; i < entity_count; ++i) - { + for (size_t i = 0; i < entity_count; ++i) { guid_t ident = var_object_list.int64(i); auto entity_ptr = kernel_module_->get_entity(ident); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { continue; } data_impl data; - if (!entity_ptr->get_node(name, data)) - { + if (!entity_ptr->get_node(name, data)) { continue; } - if (value_args.equal(0, data)) - { + if (value_args.equal(0, data)) { list.add_int64(ident); } } diff --git a/src/plugins/kernel/map_module_impl.hpp b/src/plugins/kernel/map_module_impl.hpp index 026de14ba..85bd9bd3b 100644 --- a/src/plugins/kernel/map_module_impl.hpp +++ b/src/plugins/kernel/map_module_impl.hpp @@ -27,8 +27,7 @@ namespace ark { -class map_module_impl final : public module_base -{ +class map_module_impl final : public module_base { public: bool init() override; bool shut() override; diff --git a/src/plugins/kernel/nested_stream.hpp b/src/plugins/kernel/nested_stream.hpp index 07e6ec7b3..0aa3b1cbd 100644 --- a/src/plugins/kernel/nested_stream.hpp +++ b/src/plugins/kernel/nested_stream.hpp @@ -21,8 +21,7 @@ namespace ark::entity_sync { // Local type names only; neither these ordinals nor variant indices are a wire ABI. -enum class nested_scalar_type -{ +enum class nested_scalar_type { boolean, int32, uint32, @@ -36,23 +35,20 @@ enum class nested_scalar_type static_assert(std::variant_size_v == 9); using nested_field_layout = std::map; -struct nested_table_layout -{ +struct nested_table_layout { std::string class_name; nested_field_layout columns; }; // Trusted application schema/projection, supplied before any remote baseline. -struct nested_entity_layout -{ +struct nested_entity_layout { std::string class_name; nested_field_layout fields; std::map tables; std::map> containers; }; -struct nested_stream_binding -{ +struct nested_stream_binding { std::string schema_id; guid_t root_id{}; std::uint64_t root_incarnation{}; @@ -60,8 +56,7 @@ struct nested_stream_binding nested_entity_layout root; }; -struct nested_baseline -{ +struct nested_baseline { std::uint64_t generation{}; std::uint64_t revision{}; nested_snapshot snapshot; @@ -69,8 +64,7 @@ struct nested_baseline // required=0: complete add; incarnation=0: remove; equal incarnations: // sparse column patch; newer incarnation: complete replacement of that row. -struct nested_row_delta -{ +struct nested_row_delta { std::uint64_t required_incarnation{}; std::uint64_t incarnation{}; std::map fields; @@ -78,8 +72,7 @@ struct nested_row_delta struct nested_container_delta; -struct nested_entity_delta -{ +struct nested_entity_delta { guid_t entity_id{}; std::uint64_t incarnation{}; std::map fields; @@ -87,16 +80,14 @@ struct nested_entity_delta std::map containers; }; -struct nested_container_delta -{ +struct nested_container_delta { // Structural changes replace the container's final authorized membership. bool replace{false}; std::map slots; std::map changed; }; -struct nested_delta -{ +struct nested_delta { std::string schema_id; std::uint64_t generation{}; std::uint64_t required_revision{}; @@ -108,8 +99,7 @@ struct nested_delta static_assert(std::is_nothrow_move_constructible_v>); static_assert(std::is_nothrow_move_constructible_v>); -struct nested_stream_limits -{ +struct nested_stream_limits { nested_snapshot_limits snapshot; std::size_t max_patch_operations{65536}; std::size_t max_patch_values{65536}; @@ -118,8 +108,7 @@ struct nested_stream_limits std::size_t max_lifetime_entries{132096}; }; -enum class nested_apply_result -{ +enum class nested_apply_result { applied, duplicate, rejected @@ -132,8 +121,7 @@ inline nested_entity_snapshot copy_entity(const nested_entity_snapshot& input); inline std::map copy_children( const std::map& input) { std::map result; - for (const auto& [slot, child] : input) - { + for (const auto& [slot, child] : input) { result.emplace_hint(result.end(), slot, detail::direct_value{[&] { return copy_entity(child); }}); } return result; @@ -141,11 +129,9 @@ inline std::map copy_children( inline nested_entity_snapshot copy_entity(const nested_entity_snapshot& input) { std::map tables; - for (const auto& [index, table] : input.tables) - { + for (const auto& [index, table] : input.tables) { std::map rows; - for (const auto& [number, row] : table.rows) - { + for (const auto& [number, row] : table.rows) { rows.emplace_hint( rows.end(), number, nested_row_snapshot{row.incarnation, detail::copy_scalar_fields(row.fields)}); } @@ -153,8 +139,7 @@ inline nested_entity_snapshot copy_entity(const nested_entity_snapshot& input) { detail::direct_value{[&] { return nested_table_snapshot{table.class_name, std::move(rows)}; }}); } std::map> containers; - for (const auto& [index, children] : input.containers) - { + for (const auto& [index, children] : input.containers) { containers.emplace_hint(containers.end(), index, copy_children(children)); } // A named owning result could move its strings when optional NRVO is absent. @@ -175,15 +160,13 @@ inline nested_snapshot take_snapshot(nested_snapshot& input) { } inline void require(bool condition) { - if (!condition) - { + if (!condition) { throw std::invalid_argument("Invalid nested stream binding, state or operation"); } } inline void consume(std::size_t count, std::size_t& remaining) { - if (count > remaining) - { + if (count > remaining) { throw std::length_error("Nested stream limit exceeded"); } remaining -= count; @@ -194,12 +177,9 @@ inline void value(const scalar_value& input, nested_scalar_type expected, std::s std::visit( [&](const auto& item) { using type = std::decay_t; - if constexpr (std::is_floating_point_v) - { + if constexpr (std::is_floating_point_v) { require(std::isfinite(item)); - } - else if constexpr (std::is_same_v) - { + } else if constexpr (std::is_same_v) { consume(item.size(), bytes); } }, @@ -210,16 +190,14 @@ inline void fields(const std::map& input, const nes std::size_t& count, std::size_t& bytes) { require(!complete || input.size() == layout.size()); consume(input.size(), count); - for (const auto& [index, item] : input) - { + for (const auto& [index, item] : input) { const auto expected = layout.find(index); require(expected != layout.end()); value(item, expected->second, bytes); } } -struct state_budget -{ +struct state_budget { explicit state_budget(const nested_snapshot_limits& input) : limits(input) , entities(input.max_entities) @@ -233,8 +211,7 @@ struct state_budget std::set seen; }; -struct schema_member -{ +struct schema_member { unsigned kind; nested_scalar_type type{}; std::string_view reference; @@ -245,13 +222,11 @@ using schema_registry = std::map, sch inline void member(schema_registry& registry, std::string_view owner, std::uint32_t index, schema_member next) { require(index != 0); const auto [position, added] = registry.emplace(std::make_pair(owner, index), next); - if (!added) - { + if (!added) { auto& old = position->second; require(old.kind == next.kind && (old.kind != 0 || old.type == next.type)); require(old.reference.empty() || next.reference.empty() || old.reference == next.reference); - if (old.reference.empty()) - { + if (old.reference.empty()) { old.reference = next.reference; } } @@ -260,8 +235,7 @@ inline void member(schema_registry& registry, std::string_view owner, std::uint3 inline void field_layout( const nested_field_layout& input, std::string_view owner, state_budget& budget, schema_registry& registry) { consume(input.size(), budget.fields); - for (const auto& [index, type] : input) - { + for (const auto& [index, type] : input) { require(static_cast(type) <= static_cast(nested_scalar_type::guid)); member(registry, owner, index, {0, type, {}}); } @@ -269,8 +243,7 @@ inline void field_layout( inline void layout( const nested_entity_layout& input, std::size_t depth, state_budget& budget, schema_registry& registry) { - if (depth > budget.limits.max_depth) - { + if (depth > budget.limits.max_depth) { throw std::length_error("Nested binding depth exceeded"); } require(!input.class_name.empty()); @@ -278,19 +251,16 @@ inline void layout( consume(input.class_name.size(), budget.strings); field_layout(input.fields, input.class_name, budget, registry); consume(input.tables.size(), budget.fields); - for (const auto& [index, table] : input.tables) - { + for (const auto& [index, table] : input.tables) { require(!table.class_name.empty()); member(registry, input.class_name, index, {1, {}, table.class_name}); consume(table.class_name.size(), budget.strings); field_layout(table.columns, table.class_name, budget, registry); } consume(input.containers.size(), budget.fields); - for (const auto& [index, children] : input.containers) - { + for (const auto& [index, children] : input.containers) { member(registry, input.class_name, index, {2, {}, {}}); - for (const auto& [id, child] : children) - { + for (const auto& [id, child] : children) { require(id != guid_t{}); member(registry, input.class_name, index, {2, {}, child.class_name}); layout(child, depth + 1, budget, registry); @@ -308,8 +278,7 @@ inline void binding(const nested_stream_binding& input, const nested_stream_limi inline void entity( const nested_entity_snapshot& input, const nested_entity_layout& trusted, std::size_t depth, state_budget& budget) { - if (depth > budget.limits.max_depth) - { + if (depth > budget.limits.max_depth) { throw std::length_error("Nested state depth exceeded"); } consume(1, budget.entities); @@ -319,26 +288,22 @@ inline void entity( fields(input.scalars.fields, trusted.fields, true, budget.fields, budget.strings); require(input.tables.size() == trusted.tables.size() && input.containers.size() == trusted.containers.size()); consume(input.tables.size(), budget.fields); - for (const auto& [index, table] : input.tables) - { + for (const auto& [index, table] : input.tables) { const auto expected = trusted.tables.find(index); require(expected != trusted.tables.end() && table.class_name == expected->second.class_name); consume(table.class_name.size(), budget.strings); consume(table.rows.size(), budget.rows); std::set incarnations; - for (const auto& [number, row] : table.rows) - { + for (const auto& [number, row] : table.rows) { require(number && row.incarnation && incarnations.insert(row.incarnation).second); fields(row.fields, expected->second.columns, true, budget.fields, budget.strings); } } consume(input.containers.size(), budget.fields); - for (const auto& [index, children] : input.containers) - { + for (const auto& [index, children] : input.containers) { const auto allowed = trusted.containers.find(index); require(allowed != trusted.containers.end()); - for (const auto& [slot, child] : children) - { + for (const auto& [slot, child] : children) { const auto selected = allowed->second.find(child.scalars.entity_id); require(slot && selected != allowed->second.end()); entity(child, selected->second, depth + 1, budget); @@ -355,20 +320,17 @@ inline void snapshot( entity(input.root, trusted.root, 0, budget); } -struct table_lifetime -{ +struct table_lifetime { std::uint64_t watermark{}; std::map rows; }; -struct entity_lifetime -{ +struct entity_lifetime { std::uint64_t incarnation; std::string class_name; }; -struct lifetime_history -{ +struct lifetime_history { std::map entities; std::map, table_lifetime> tables; std::size_t entries{}; @@ -381,8 +343,7 @@ struct lifetime_history }; inline void history_entry(lifetime_history& history, std::size_t limit) { - if (history.entries >= limit) - { + if (history.entries >= limit) { throw std::length_error("Nested lifetime history exceeded"); } ++history.entries; @@ -391,50 +352,39 @@ inline void history_entry(lifetime_history& history, std::size_t limit) { inline void remember(const nested_entity_snapshot& input, lifetime_history& history, std::size_t limit) { const auto id = input.scalars.entity_id; auto known = history.entities.find(id); - if (known == history.entities.end()) - { + if (known == history.entities.end()) { history_entry(history, limit); history.entities.emplace( id, detail::direct_value{[&] { return entity_lifetime{input.incarnation, input.scalars.class_name}; }}); - } - else - { + } else { require(input.incarnation >= known->second.incarnation); - if (input.incarnation == known->second.incarnation) - { + if (input.incarnation == known->second.incarnation) { require(input.scalars.class_name == known->second.class_name); - } - else - { + } else { for (auto position = history.tables.lower_bound({id, 0, 0}); - position != history.tables.end() && std::get<0>(position->first) == id;) - { + position != history.tables.end() && std::get<0>(position->first) == id;) { history.entries -= 1 + position->second.rows.size(); position = history.tables.erase(position); } known->second = {input.incarnation, input.scalars.class_name}; } } - for (const auto& [index, table] : input.tables) - { + for (const auto& [index, table] : input.tables) { const auto key = std::make_tuple(id, input.incarnation, index); auto previous = history.tables.find(key); - if (previous == history.tables.end()) - { + if (previous == history.tables.end()) { history_entry(history, limit); previous = history.tables.emplace(key, table_lifetime{}).first; } auto& old = previous->second; const auto without_rows = history.entries - old.rows.size(); require(without_rows <= limit); - if (table.rows.size() > limit - without_rows) - { + if (table.rows.size() > limit - without_rows) { throw std::length_error("Nested row history exceeded"); } auto watermark = old.watermark; std::map rows; - for (const auto& [number, row] : table.rows) - { + for (const auto& [number, row] : table.rows) { const auto before = old.rows.find(number); require((before != old.rows.end() && before->second == row.incarnation) || row.incarnation > old.watermark); watermark = std::max(watermark, row.incarnation); @@ -444,17 +394,14 @@ inline void remember(const nested_entity_snapshot& input, lifetime_history& hist old.watermark = watermark; history.entries = without_rows + old.rows.size(); } - for (const auto& [index, children] : input.containers) - { - for (const auto& [slot, child] : children) - { + for (const auto& [index, children] : input.containers) { + for (const auto& [slot, child] : children) { remember(child, history, limit); } } } -struct patch_budget -{ +struct patch_budget { explicit patch_budget(const nested_stream_limits& limits) : operations(limits.max_patch_operations) , values(limits.max_patch_values) @@ -466,8 +413,7 @@ struct patch_budget inline void count_values(const std::map& values, patch_budget& budget) { consume(values.size(), budget.values); - for (const auto& [index, item] : values) - { + for (const auto& [index, item] : values) { require(!item.valueless_by_exception()); value(item, static_cast(item.index()), budget.strings); } @@ -478,20 +424,16 @@ inline void count_entity(const nested_entity_snapshot& input, patch_budget& budg consume(input.scalars.class_name.size(), budget.strings); count_values(input.scalars.fields, budget); consume(input.tables.size(), budget.operations); - for (const auto& [index, table] : input.tables) - { + for (const auto& [index, table] : input.tables) { consume(table.class_name.size(), budget.strings); consume(table.rows.size(), budget.operations); - for (const auto& [number, row] : table.rows) - { + for (const auto& [number, row] : table.rows) { count_values(row.fields, budget); } } consume(input.containers.size(), budget.operations); - for (const auto& [index, children] : input.containers) - { - for (const auto& [slot, child] : children) - { + for (const auto& [index, children] : input.containers) { + for (const auto& [slot, child] : children) { count_entity(child, budget); } } @@ -504,11 +446,9 @@ inline bool empty(const nested_entity_delta& input) { inline void patch_fields(const std::map& before, const std::map& next, std::map& output, patch_budget& budget) { - for (const auto& [index, item] : next) - { + for (const auto& [index, item] : next) { const auto old = before.find(index); - if (old == before.end() || old->second != item) - { + if (old == before.end() || old->second != item) { consume(1, budget.values); value(item, static_cast(item.index()), budget.strings); output.emplace(index, detail::direct_value{[&] { return detail::copy_scalar_value(item); }}); @@ -518,16 +458,13 @@ inline void patch_fields(const std::map& before, inline bool same_membership(const std::map& before, const std::map& next) { - if (before.size() != next.size()) - { + if (before.size() != next.size()) { return false; } auto left = before.begin(); - for (const auto& [slot, child] : next) - { + for (const auto& [slot, child] : next) { if (left->first != slot || left->second.scalars.entity_id != child.scalars.entity_id || - left->second.incarnation != child.incarnation) - { + left->second.incarnation != child.incarnation) { return false; } ++left; @@ -540,72 +477,55 @@ inline nested_entity_delta difference( consume(1, budget.operations); nested_entity_delta result{next.scalars.entity_id, next.incarnation, {}, {}, {}}; patch_fields(before.scalars.fields, next.scalars.fields, result.fields, budget); - for (const auto& [index, table] : next.tables) - { + for (const auto& [index, table] : next.tables) { const auto& old = before.tables.at(index); std::map changes; - for (const auto& [number, row] : old.rows) - { - if (!table.rows.contains(number)) - { + for (const auto& [number, row] : old.rows) { + if (!table.rows.contains(number)) { consume(1, budget.operations); changes.emplace(number, nested_row_delta{row.incarnation, 0, {}}); } } - for (const auto& [number, row] : table.rows) - { + for (const auto& [number, row] : table.rows) { const auto previous = old.rows.find(number); - if (previous == old.rows.end() || previous->second.incarnation != row.incarnation) - { + if (previous == old.rows.end() || previous->second.incarnation != row.incarnation) { consume(1, budget.operations); count_values(row.fields, budget); changes.emplace(number, nested_row_delta{previous == old.rows.end() ? 0 : previous->second.incarnation, row.incarnation, detail::copy_scalar_fields(row.fields)}); - } - else - { + } else { nested_row_delta update{row.incarnation, row.incarnation, {}}; patch_fields(previous->second.fields, row.fields, update.fields, budget); - if (!update.fields.empty()) - { + if (!update.fields.empty()) { consume(1, budget.operations); changes.emplace(number, std::move(update)); } } } - if (!changes.empty()) - { + if (!changes.empty()) { consume(1, budget.operations); result.tables.emplace(index, std::move(changes)); } } - for (const auto& [index, children] : next.containers) - { + for (const auto& [index, children] : next.containers) { const auto& old = before.containers.at(index); nested_container_delta update; - if (!same_membership(old, children)) - { + if (!same_membership(old, children)) { consume(1, budget.operations); - for (const auto& [slot, child] : children) - { + for (const auto& [slot, child] : children) { count_entity(child, budget); } update.replace = true; update.slots = copy_children(children); result.containers.emplace(index, std::move(update)); - } - else - { - for (const auto& [slot, child] : children) - { - if (!(child == old.at(slot))) - { + } else { + for (const auto& [slot, child] : children) { + if (!(child == old.at(slot))) { auto delta = difference(old.at(slot), child, budget); update.changed.emplace(slot, std::move(delta)); } } - if (!update.changed.empty()) - { + if (!update.changed.empty()) { consume(1, budget.operations); result.containers.emplace(index, std::move(update)); } @@ -616,28 +536,22 @@ inline nested_entity_delta difference( inline void validate_patch(const nested_entity_delta& input, const nested_entity_layout& trusted, std::size_t depth, patch_budget& budget, state_budget& replacements) { - if (depth > replacements.limits.max_depth) - { + if (depth > replacements.limits.max_depth) { throw std::length_error("Nested patch depth exceeded"); } consume(1, budget.operations); require(input.entity_id != guid_t{} && input.incarnation && replacements.seen.insert(input.entity_id).second); fields(input.fields, trusted.fields, false, budget.values, budget.strings); consume(input.tables.size(), budget.operations); - for (const auto& [index, rows] : input.tables) - { + for (const auto& [index, rows] : input.tables) { const auto expected = trusted.tables.find(index); require(expected != trusted.tables.end() && !rows.empty()); consume(rows.size(), budget.operations); - for (const auto& [number, row] : rows) - { + for (const auto& [number, row] : rows) { require(number && (row.required_incarnation || row.incarnation)); - if (!row.incarnation) - { + if (!row.incarnation) { require(row.fields.empty()); - } - else - { + } else { const bool complete = row.incarnation != row.required_incarnation; require(complete ? row.incarnation > row.required_incarnation : !row.fields.empty()); fields(row.fields, expected->second.columns, complete, budget.values, budget.strings); @@ -645,26 +559,20 @@ inline void validate_patch(const nested_entity_delta& input, const nested_entity } } consume(input.containers.size(), budget.operations); - for (const auto& [index, update] : input.containers) - { + for (const auto& [index, update] : input.containers) { const auto allowed = trusted.containers.find(index); require(allowed != trusted.containers.end()); - if (update.replace) - { + if (update.replace) { require(update.changed.empty()); - for (const auto& [slot, child] : update.slots) - { + for (const auto& [slot, child] : update.slots) { const auto selection = allowed->second.find(child.scalars.entity_id); require(slot && selection != allowed->second.end()); entity(child, selection->second, depth + 1, replacements); count_entity(child, budget); } - } - else - { + } else { require(update.slots.empty() && !update.changed.empty()); - for (const auto& [slot, child] : update.changed) - { + for (const auto& [slot, child] : update.changed) { const auto selection = allowed->second.find(child.entity_id); require(slot && selection != allowed->second.end() && !empty(child)); validate_patch(child, selection->second, depth + 1, budget, replacements); @@ -687,48 +595,34 @@ inline void delta(const nested_delta& input, const nested_stream_binding& truste inline void apply_patch(nested_entity_snapshot& candidate, const nested_entity_delta& patch) { require(candidate.scalars.entity_id == patch.entity_id && candidate.incarnation == patch.incarnation); - for (const auto& [index, value] : patch.fields) - { + for (const auto& [index, value] : patch.fields) { candidate.scalars.fields.at(index) = detail::copy_scalar_value(value); } - for (const auto& [index, rows] : patch.tables) - { + for (const auto& [index, rows] : patch.tables) { auto& table = candidate.tables.at(index); - for (const auto& [number, change] : rows) - { + for (const auto& [number, change] : rows) { const auto old = table.rows.find(number); require(change.required_incarnation ? old != table.rows.end() && old->second.incarnation == change.required_incarnation : old == table.rows.end()); - if (!change.incarnation) - { + if (!change.incarnation) { table.rows.erase(old); - } - else if (change.incarnation != change.required_incarnation) - { + } else if (change.incarnation != change.required_incarnation) { table.rows.insert_or_assign( number, nested_row_snapshot{change.incarnation, detail::copy_scalar_fields(change.fields)}); - } - else - { - for (const auto& [column, value] : change.fields) - { + } else { + for (const auto& [column, value] : change.fields) { old->second.fields.at(column) = detail::copy_scalar_value(value); } } } } - for (const auto& [index, change] : patch.containers) - { + for (const auto& [index, change] : patch.containers) { auto& children = candidate.containers.at(index); - if (change.replace) - { + if (change.replace) { children = copy_children(change.slots); - } - else - { - for (const auto& [slot, child] : change.changed) - { + } else { + for (const auto& [slot, child] : change.changed) { const auto previous = children.find(slot); require(previous != children.end()); apply_patch(previous->second, child); @@ -740,8 +634,7 @@ inline void apply_patch(nested_entity_snapshot& candidate, const nested_entity_d } // namespace nested_detail // Single owner thread. Returned immutable publications do not acknowledge delivery. -class nested_publisher final -{ +class nested_publisher final { public: nested_publisher( const nested_stream_binding& trusted, const nested_baseline& initial, nested_stream_limits limits = {}) @@ -762,8 +655,7 @@ class nested_publisher final std::shared_ptr update(const nested_snapshot& next) { active(); nested_detail::snapshot(next, binding_, limits_); - if (next == current_->snapshot) - { + if (next == current_->snapshot) { return {}; } advance(); @@ -812,15 +704,13 @@ class nested_publisher final } void active() const { - if (removed_) - { + if (removed_) { throw std::logic_error("Nested root was removed; bind a new stream"); } } void advance() const { - if (current_->revision == std::numeric_limits::max()) - { + if (current_->revision == std::numeric_limits::max()) { throw std::overflow_error("Nested revision exhausted"); } } @@ -832,8 +722,7 @@ class nested_publisher final bool removed_{false}; }; -class nested_replica final -{ +class nested_replica final { public: explicit nested_replica(const nested_stream_binding& trusted, nested_stream_limits limits = {}) : limits_(limits) @@ -841,18 +730,15 @@ class nested_replica final } nested_apply_result apply(const nested_baseline& input) { - if (failed_) - { + if (failed_) { return nested_apply_result::rejected; } - try - { + try { nested_detail::require(input.generation == binding_.generation && input.revision); nested_detail::snapshot(input.snapshot, binding_, limits_); - if (installed_) - { - if (input.revision < revision_ || (input.revision == revision_ && state_ && *state_ == input.snapshot)) - { + if (installed_) { + if (input.revision < revision_ || + (input.revision == revision_ && state_ && *state_ == input.snapshot)) { return nested_apply_result::duplicate; } return reject(); @@ -866,29 +752,25 @@ class nested_replica final revision_ = input.revision; installed_ = true; return nested_apply_result::applied; + } catch (const std::invalid_argument&) { + return reject(); + } catch (const std::length_error&) { + return reject(); } - catch (const std::invalid_argument&) - { return reject(); } - catch (const std::length_error&) - { return reject(); } } nested_apply_result apply(const nested_delta& input) { - if (failed_) - { + if (failed_) { return nested_apply_result::rejected; } - try - { + try { nested_detail::delta(input, binding_, limits_); nested_detail::require(installed_); - if (input.revision <= revision_) - { + if (input.revision <= revision_) { return nested_apply_result::duplicate; } nested_detail::require(state_ && input.required_revision == revision_); - if (input.removed) - { + if (input.removed) { state_.reset(); revision_ = input.revision; return nested_apply_result::applied; @@ -904,13 +786,13 @@ class nested_replica final history_.swap(history); revision_ = input.revision; return nested_apply_result::applied; + } catch (const std::invalid_argument&) { + return reject(); + } catch (const std::length_error&) { + return reject(); + } catch (const std::out_of_range&) { + return reject(); } - catch (const std::invalid_argument&) - { return reject(); } - catch (const std::length_error&) - { return reject(); } - catch (const std::out_of_range&) - { return reject(); } } bool valid() const noexcept { diff --git a/src/plugins/kernel/nested_wire.hpp b/src/plugins/kernel/nested_wire.hpp index 5930fd420..c97d24164 100644 --- a/src/plugins/kernel/nested_wire.hpp +++ b/src/plugins/kernel/nested_wire.hpp @@ -35,8 +35,7 @@ namespace ark::entity_sync::nested_wire { namespace proto = protobuf::entity_sync; -struct limits -{ +struct limits { nested_stream_limits stream; // Independent of native state/patch budgets and transport pending budgets. std::size_t max_message_bytes{4 * 1024 * 1024}; @@ -48,10 +47,8 @@ namespace detail { template inline std::int64_t encode_guid(guid_type input) { - if constexpr (std::numeric_limits::digits > std::numeric_limits::digits) - { - if (input < std::numeric_limits::min() || input > std::numeric_limits::max()) - { + if constexpr (std::numeric_limits::digits > std::numeric_limits::digits) { + if (input < std::numeric_limits::min() || input > std::numeric_limits::max()) { throw std::invalid_argument("Nested GUID exceeds signed 64-bit wire width"); } } @@ -59,8 +56,7 @@ inline std::int64_t encode_guid(guid_type input) { } inline guid_t decode_guid(std::int64_t input) { - if (input < std::numeric_limits::min() || input > std::numeric_limits::max()) - { + if (input < std::numeric_limits::min() || input > std::numeric_limits::max()) { throw std::invalid_argument("Nested GUID exceeds native width"); } return static_cast(input); @@ -69,28 +65,23 @@ inline guid_t decode_guid(std::int64_t input) { inline void check_limits(const limits& budget) { if (!budget.max_message_bytes || budget.max_message_bytes > static_cast(std::numeric_limits::max()) || - budget.max_recursion_depth <= 0) - { + budget.max_recursion_depth <= 0) { throw std::invalid_argument("Invalid nested wire byte or recursion limit"); } } inline void check_unknown( const google::protobuf::UnknownFieldSet& input, int depth, const limits& budget, std::size_t& records) { - if (depth > budget.max_recursion_depth) - { + if (depth > budget.max_recursion_depth) { throw std::length_error("Nested wire unknown-group recursion limit exceeded"); } - for (int index = 0; index < input.field_count(); ++index) - { - if (!records) - { + for (int index = 0; index < input.field_count(); ++index) { + if (!records) { throw std::length_error("Nested wire record limit exceeded"); } --records; const auto& field = input.field(index); - if (field.type() == google::protobuf::UnknownField::TYPE_GROUP) - { + if (field.type() == google::protobuf::UnknownField::TYPE_GROUP) { check_unknown(field.group(), depth + 1, budget, records); } } @@ -100,8 +91,7 @@ inline void check_unknown( // size or constructing native maps. Unknown fields remain forward compatible; // their size and any unknown groups still obey the independent wire budgets. inline void check_depth(const google::protobuf::Message& input, int depth, const limits& budget, std::size_t& records) { - if (depth > budget.max_recursion_depth || !records) - { + if (depth > budget.max_recursion_depth || !records) { throw std::length_error("Nested wire recursion or record limit exceeded"); } --records; @@ -109,22 +99,16 @@ inline void check_depth(const google::protobuf::Message& input, int depth, const check_unknown(reflection->GetUnknownFields(input), depth, budget, records); std::vector fields; reflection->ListFields(input, &fields); - for (const auto* field : fields) - { - if (field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) - { + for (const auto* field : fields) { + if (field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) { continue; } - if (field->is_repeated()) - { + if (field->is_repeated()) { const auto count = reflection->FieldSize(input, field); - for (int index = 0; index < count; ++index) - { + for (int index = 0; index < count; ++index) { check_depth(reflection->GetRepeatedMessage(input, field, index), depth + 1, budget, records); } - } - else - { + } else { check_depth(reflection->GetMessage(input, field), depth + 1, budget, records); } } @@ -135,8 +119,7 @@ inline void check_message(const google::protobuf::Message& input, const limits& // Each nested record needs at least a tag and a length byte on the wire. auto records = budget.max_message_bytes; check_depth(input, 0, budget, records); - if (input.ByteSizeLong() > budget.max_message_bytes) - { + if (input.ByteSizeLong() > budget.max_message_bytes) { throw std::length_error("Nested wire message byte limit exceeded"); } } @@ -156,47 +139,29 @@ inline void validate(const nested_delta& input, const nested_stream_binding& tru inline void encode_fields(const std::map& input, google::protobuf::RepeatedPtrField& output) { - for (const auto& [index, value] : input) - { + for (const auto& [index, value] : input) { auto& field = *output.Add(); field.set_index(index); std::visit( [&](const auto& item) { using type = std::decay_t; - if constexpr (std::is_same_v) - { + if constexpr (std::is_same_v) { field.set_bool_value(item); - } - else if constexpr (std::is_same_v) - { + } else if constexpr (std::is_same_v) { field.set_int32_value(item); - } - else if constexpr (std::is_same_v) - { + } else if constexpr (std::is_same_v) { field.set_uint32_value(item); - } - else if constexpr (std::is_same_v) - { + } else if constexpr (std::is_same_v) { field.set_int64_value(item); - } - else if constexpr (std::is_same_v) - { + } else if constexpr (std::is_same_v) { field.set_uint64_value(item); - } - else if constexpr (std::is_same_v) - { + } else if constexpr (std::is_same_v) { field.set_float_value(item); - } - else if constexpr (std::is_same_v) - { + } else if constexpr (std::is_same_v) { field.set_double_value(item); - } - else if constexpr (std::is_same_v) - { + } else if constexpr (std::is_same_v) { field.set_string_value(item); - } - else if constexpr (std::is_same_v) - { + } else if constexpr (std::is_same_v) { field.set_guid_value(encode_guid(item.value)); } }, @@ -205,8 +170,7 @@ inline void encode_fields(const std::map& input, } inline scalar_value decode_field(const proto::scalar_field& input) { - switch (input.value_case()) - { + switch (input.value_case()) { case proto::scalar_field::kBoolValue: return input.bool_value(); case proto::scalar_field::kInt32Value: @@ -233,8 +197,7 @@ inline scalar_value decode_field(const proto::scalar_field& input) { inline std::map decode_fields( const google::protobuf::RepeatedPtrField& input) { std::map output; - for (const auto& field : input) - { + for (const auto& field : input) { nested_detail::require( field.index() && output.emplace(field.index(), entity_sync::detail::direct_value{[&] { return decode_field(field); }}) @@ -248,25 +211,21 @@ inline void encode_entity(const nested_entity_snapshot& input, proto::entity_sna output.set_incarnation(input.incarnation); output.set_class_name(input.scalars.class_name); encode_fields(input.scalars.fields, *output.mutable_fields()); - for (const auto& [index, table] : input.tables) - { + for (const auto& [index, table] : input.tables) { auto& result = *output.add_tables(); result.set_index(index); result.set_class_name(table.class_name); - for (const auto& [number, row] : table.rows) - { + for (const auto& [number, row] : table.rows) { auto& record = *result.add_rows(); record.set_number(number); record.set_incarnation(row.incarnation); encode_fields(row.fields, *record.mutable_fields()); } } - for (const auto& [index, children] : input.containers) - { + for (const auto& [index, children] : input.containers) { auto& result = *output.add_containers(); result.set_index(index); - for (const auto& [slot, child] : children) - { + for (const auto& [slot, child] : children) { auto& record = *result.add_slots(); record.set_slot(slot); encode_entity(child, *record.mutable_state()); @@ -276,11 +235,9 @@ inline void encode_entity(const nested_entity_snapshot& input, proto::entity_sna inline nested_entity_snapshot decode_entity(const proto::entity_snapshot& input) { std::map tables; - for (const auto& table : input.tables()) - { + for (const auto& table : input.tables()) { std::map rows; - for (const auto& row : table.rows()) - { + for (const auto& row : table.rows()) { nested_detail::require(row.number() && rows.emplace(row.number(), entity_sync::detail::direct_value{[&] { return nested_row_snapshot{ row.incarnation(), decode_fields(row.fields())}; @@ -295,11 +252,9 @@ inline nested_entity_snapshot decode_entity(const proto::entity_snapshot& input) .second); } std::map> containers; - for (const auto& container : input.containers()) - { + for (const auto& container : input.containers()) { std::map children; - for (const auto& slot : container.slots()) - { + for (const auto& slot : container.slots()) { nested_detail::require(slot.slot() && slot.has_state() && children .emplace(slot.slot(), entity_sync::detail::direct_value{[&] { @@ -317,12 +272,10 @@ inline void encode_change(const nested_entity_delta& input, proto::entity_delta& output.set_entity_id(encode_guid(input.entity_id)); output.set_incarnation(input.incarnation); encode_fields(input.fields, *output.mutable_fields()); - for (const auto& [index, rows] : input.tables) - { + for (const auto& [index, rows] : input.tables) { auto& result = *output.add_tables(); result.set_index(index); - for (const auto& [number, row] : rows) - { + for (const auto& [number, row] : rows) { auto& record = *result.add_rows(); record.set_number(number); record.set_required_incarnation(row.required_incarnation); @@ -330,25 +283,19 @@ inline void encode_change(const nested_entity_delta& input, proto::entity_delta& encode_fields(row.fields, *record.mutable_fields()); } } - for (const auto& [index, change] : input.containers) - { + for (const auto& [index, change] : input.containers) { auto& result = *output.add_containers(); result.set_index(index); - if (change.replace) - { + if (change.replace) { auto& replacement = *result.mutable_replacement(); - for (const auto& [slot, child] : change.slots) - { + for (const auto& [slot, child] : change.slots) { auto& record = *replacement.add_slots(); record.set_slot(slot); encode_entity(child, *record.mutable_state()); } - } - else - { + } else { auto& patch = *result.mutable_patch(); - for (const auto& [slot, child] : change.changed) - { + for (const auto& [slot, child] : change.changed) { auto& record = *patch.add_changed(); record.set_slot(slot); encode_change(child, *record.mutable_change()); @@ -359,11 +306,9 @@ inline void encode_change(const nested_entity_delta& input, proto::entity_delta& inline nested_entity_delta decode_change(const proto::entity_delta& input) { std::map> tables; - for (const auto& table : input.tables()) - { + for (const auto& table : input.tables()) { std::map rows; - for (const auto& row : table.rows()) - { + for (const auto& row : table.rows()) { nested_detail::require(row.number() && rows.emplace(row.number(), entity_sync::detail::direct_value{[&] { return nested_row_delta{row.required_incarnation(), row.incarnation(), decode_fields(row.fields())}; @@ -373,14 +318,11 @@ inline nested_entity_delta decode_change(const proto::entity_delta& input) { nested_detail::require(table.index() && tables.emplace(table.index(), std::move(rows)).second); } std::map containers; - for (const auto& container : input.containers()) - { + for (const auto& container : input.containers()) { nested_container_delta change; - if (container.has_replacement()) - { + if (container.has_replacement()) { change.replace = true; - for (const auto& slot : container.replacement().slots()) - { + for (const auto& slot : container.replacement().slots()) { nested_detail::require(slot.slot() && slot.has_state() && change.slots .emplace(slot.slot(), entity_sync::detail::direct_value{[&] { @@ -388,12 +330,9 @@ inline nested_entity_delta decode_change(const proto::entity_delta& input) { }}) .second); } - } - else - { + } else { nested_detail::require(container.has_patch()); - for (const auto& slot : container.patch().changed()) - { + for (const auto& slot : container.patch().changed()) { nested_detail::require(slot.slot() && slot.has_change() && change.changed .emplace(slot.slot(), entity_sync::detail::direct_value{[&] { @@ -411,16 +350,14 @@ inline nested_entity_delta decode_change(const proto::entity_delta& input) { template inline void parse(std::string_view input, message_type& output, const limits& budget) { check_limits(budget); - if (input.size() > budget.max_message_bytes) - { + if (input.size() > budget.max_message_bytes) { throw std::length_error("Nested wire message byte limit exceeded"); } google::protobuf::io::CodedInputStream stream( reinterpret_cast(input.data()), static_cast(input.size())); stream.SetTotalBytesLimit(static_cast(budget.max_message_bytes)); stream.SetRecursionLimit(budget.max_recursion_depth); - if (!output.ParseFromCodedStream(&stream) || !stream.ConsumedEntireMessage()) - { + if (!output.ParseFromCodedStream(&stream) || !stream.ConsumedEntireMessage()) { throw std::invalid_argument("Malformed or excessively nested Entity message"); } } @@ -494,8 +431,7 @@ inline std::string encode( message_type message; encode(input, message, trusted, budget); std::string output; - if (!message.SerializeToString(&output)) - { + if (!message.SerializeToString(&output)) { throw std::invalid_argument("Cannot serialize nested Entity message"); } return output; diff --git a/src/plugins/kernel/node.hpp b/src/plugins/kernel/node.hpp index 2f3e1d5af..aeebbf00c 100644 --- a/src/plugins/kernel/node.hpp +++ b/src/plugins/kernel/node.hpp @@ -25,8 +25,7 @@ namespace ark { -class node -{ +class node { public: virtual ~node() = default; diff --git a/src/plugins/kernel/node_impl.hpp b/src/plugins/kernel/node_impl.hpp index 33373755f..646816736 100644 --- a/src/plugins/kernel/node_impl.hpp +++ b/src/plugins/kernel/node_impl.hpp @@ -62,8 +62,7 @@ private: std::shared_ptr data_meta_{nullptr}; // data int32_t -class node_int32 final : public node -{ +class node_int32 final : public node { public: explicit node_int32(std::shared_ptr data_meta_ptr) { data_meta_ = data_meta_ptr; @@ -125,8 +124,7 @@ class node_int32 final : public node }; // data uint32_t -class node_u_int32 final : public node -{ +class node_u_int32 final : public node { public: explicit node_u_int32(std::shared_ptr data_meta_ptr) { data_meta_ = data_meta_ptr; @@ -188,8 +186,7 @@ class node_u_int32 final : public node }; // data string -class node_string final : public node -{ +class node_string final : public node { public: explicit node_string(std::shared_ptr data_meta_ptr) { data_meta_ = data_meta_ptr; @@ -251,8 +248,7 @@ class node_string final : public node }; // data bool -class node_bool final : public node -{ +class node_bool final : public node { public: explicit node_bool(std::shared_ptr data_meta_ptr) { data_meta_ = data_meta_ptr; @@ -314,8 +310,7 @@ class node_bool final : public node }; // data int64 -class node_int64 final : public node -{ +class node_int64 final : public node { public: explicit node_int64(std::shared_ptr data_meta_ptr) { data_meta_ = data_meta_ptr; @@ -377,8 +372,7 @@ class node_int64 final : public node }; // data uint64 -class node_u_int64 final : public node -{ +class node_u_int64 final : public node { public: explicit node_u_int64(std::shared_ptr data_meta_ptr) { data_meta_ = data_meta_ptr; @@ -440,8 +434,7 @@ class node_u_int64 final : public node }; // data float -class node_float final : public node -{ +class node_float final : public node { public: explicit node_float(std::shared_ptr data_meta_ptr) { data_meta_ = data_meta_ptr; @@ -503,8 +496,7 @@ class node_float final : public node }; // data double -class node_double final : public node -{ +class node_double final : public node { public: explicit node_double(std::shared_ptr data_meta_ptr) { data_meta_ = data_meta_ptr; @@ -566,8 +558,7 @@ class node_double final : public node }; // data object -class node_guid final : public node -{ +class node_guid final : public node { public: explicit node_guid(std::shared_ptr data_meta_ptr) { data_meta_ = data_meta_ptr; @@ -633,8 +624,7 @@ static node* create_data_by_meta(std::shared_ptr data_meta_ptr) { ARK_ASSERT_RET_VAL(data_meta_ptr != nullptr, nullptr); node* data_ptr = nullptr; - switch (data_meta_ptr->get_type()) - { + switch (data_meta_ptr->get_type()) { case ark::data_type::dt_boolean: data_ptr = ARK_NEW node_bool(data_meta_ptr); break; diff --git a/src/plugins/kernel/node_manager.cpp b/src/plugins/kernel/node_manager.cpp index 27178d720..8f8bac249 100644 --- a/src/plugins/kernel/node_manager.cpp +++ b/src/plugins/kernel/node_manager.cpp @@ -27,8 +27,7 @@ namespace ark { namespace { -struct unpublished_node_deleter -{ +struct unpublished_node_deleter { void operator()(node* pointer) const noexcept { ARK_DELETE(pointer); } @@ -54,84 +53,58 @@ void node_manager::init_data(const data_list& args) { size_t count = args.get_count(); ARK_ASSERT_RET_NONE(count % 2 == 0); - for (size_t i = 0; i < count; i += 2) - { + for (size_t i = 0; i < count; i += 2) { auto data_type = args.get_type(i); auto index = args.u_int(i + 1); - switch (data_type) - { - case ark::data_type::dt_boolean: - { + switch (data_type) { + case ark::data_type::dt_boolean: { node* node_ptr = find_data(index); - if (node_ptr != nullptr) - { + if (node_ptr != nullptr) { node_ptr->set_bool(args.get_bool(i)); } - } - break; - case ark::data_type::dt_int32: - { + } break; + case ark::data_type::dt_int32: { node* node_ptr = find_data(index); - if (node_ptr != nullptr) - { + if (node_ptr != nullptr) { node_ptr->set_int32(args.get_int(i)); } - } - break; - case ark::data_type::dt_uint32: - { + } break; + case ark::data_type::dt_uint32: { node* node_ptr = find_data(index); - if (node_ptr != nullptr) - { + if (node_ptr != nullptr) { node_ptr->set_u_int32(args.u_int(i)); } - } - break; - case ark::data_type::dt_int64: - { + } break; + case ark::data_type::dt_int64: { node* node_ptr = find_data(index); - if (node_ptr != nullptr) - { + if (node_ptr != nullptr) { node_ptr->set_int64(args.int64(i)); } - } - break; - case ark::data_type::dt_uint64: - { + } break; + case ark::data_type::dt_uint64: { node* node_ptr = find_data(index); - if (node_ptr != nullptr) - { + if (node_ptr != nullptr) { node_ptr->set_u_int64(args.u_int64(i)); } - } - break; - case ark::data_type::dt_float: - { + } break; + case ark::data_type::dt_float: { node* node_ptr = find_data(index); - if (node_ptr != nullptr) - { + if (node_ptr != nullptr) { node_ptr->set_float(args.get_float(i)); } - } - break; - case ark::data_type::dt_double: - { + } break; + case ark::data_type::dt_double: { node* node_ptr = find_data(index); - if (node_ptr != nullptr) - { + if (node_ptr != nullptr) { node_ptr->set_double(args.get_double(i)); } - } - break; - case ark::data_type::dt_string: - { + } break; + case ark::data_type::dt_string: { node* node_ptr = find_data(index); - if (node_ptr != nullptr) - { + if (node_ptr != nullptr) { node_ptr->set_string(args.string(i)); } - } - break; + } break; default: break; } @@ -154,8 +127,7 @@ node* node_manager::create_data(std::shared_ptr data_meta_ptr) { scoped_node data_ptr(create_data_by_meta(data_meta_ptr)); ARK_ASSERT_RET_VAL(data_ptr != nullptr, nullptr); - if (!data_list_.insert(index, data_ptr.get()).second) - { + if (!data_list_.insert(index, data_ptr.get()).second) { return nullptr; } @@ -171,8 +143,7 @@ bool node_manager::create_data(node* data_ptr) { new_data_ptr->copy_from(data_ptr); - if (!data_list_.insert(new_data_ptr->get_index(), new_data_ptr.get()).second) - { + if (!data_list_.insert(new_data_ptr->get_index(), new_data_ptr.get()).second) { return false; } @@ -419,15 +390,13 @@ bool node_manager::set_bool(const uint32_t index, bool value) { ARK_ASSERT_RET_VAL(data_type == data_type::dt_boolean, false); auto old_value = data_ptr->get_bool(); - if (old_value == value) - { + if (old_value == value) { return false; } data_ptr->set_bool(value); - if (func_) - { + if (func_) { // data callbacks func_(data_ptr, data_impl(data_type, old_value), data_impl(data_type, value)); } @@ -443,15 +412,13 @@ bool node_manager::set_int32(const uint32_t index, const int32_t value) { ARK_ASSERT_RET_VAL(data_type == data_type::dt_int32, false); auto old_value = data_ptr->get_int32(); - if (old_value == value) - { + if (old_value == value) { return false; } data_ptr->set_int32(value); - if (func_) - { + if (func_) { // data callbacks func_(data_ptr, data_impl(data_type, old_value), data_impl(data_type, value)); } @@ -467,15 +434,13 @@ bool node_manager::set_u_int32(const uint32_t index, const uint32_t value) { ARK_ASSERT_RET_VAL(data_type == data_type::dt_uint32, false); auto old_value = data_ptr->get_u_int32(); - if (old_value == value) - { + if (old_value == value) { return false; } data_ptr->set_u_int32(value); - if (func_) - { + if (func_) { // data callbacks func_(data_ptr, data_impl(data_type, old_value), data_impl(data_type, value)); } @@ -491,15 +456,13 @@ bool node_manager::set_int64(const uint32_t index, const int64_t value) { ARK_ASSERT_RET_VAL(data_type == data_type::dt_int64, false); auto old_value = data_ptr->get_int64(); - if (old_value == value) - { + if (old_value == value) { return false; } data_ptr->set_int64(value); - if (func_) - { + if (func_) { // data callbacks func_(data_ptr, data_impl(data_type, old_value), data_impl(data_type, value)); } @@ -515,15 +478,13 @@ bool node_manager::set_u_int64(const uint32_t index, const uint64_t value) { ARK_ASSERT_RET_VAL(data_type == data_type::dt_uint64, false); auto old_value = data_ptr->get_u_int64(); - if (old_value == value) - { + if (old_value == value) { return false; } data_ptr->set_u_int64(value); - if (func_) - { + if (func_) { // data callbacks func_(data_ptr, data_impl(data_type, old_value), data_impl(data_type, value)); } @@ -539,15 +500,13 @@ bool node_manager::set_float(const uint32_t index, const float value) { ARK_ASSERT_RET_VAL(data_type == data_type::dt_float, false); auto old_value = data_ptr->get_float(); - if (old_value == value) - { + if (old_value == value) { return false; } data_ptr->set_float(value); - if (func_) - { + if (func_) { // data callbacks func_(data_ptr, data_impl(data_type, old_value), data_impl(data_type, value)); } @@ -563,15 +522,13 @@ bool node_manager::set_double(const uint32_t index, const double value) { ARK_ASSERT_RET_VAL(data_type == data_type::dt_double, false); auto old_value = data_ptr->get_double(); - if (old_value == value) - { + if (old_value == value) { return false; } data_ptr->set_double(value); - if (func_) - { + if (func_) { // data callbacks func_(data_ptr, data_impl(data_type, old_value), data_impl(data_type, value)); } @@ -587,15 +544,13 @@ bool node_manager::set_string(const uint32_t index, const std::string& value) { ARK_ASSERT_RET_VAL(data_type == data_type::dt_string, false); auto old_value = data_ptr->get_string(); - if (old_value == value) - { + if (old_value == value) { return false; } data_ptr->set_string(value); - if (func_) - { + if (func_) { // data callbacks func_(data_ptr, data_impl(data_type, old_value.c_str()), data_impl(data_type, value.c_str())); } @@ -612,15 +567,13 @@ bool node_manager::set_w_string(const uint32_t index, const std::wstring& value) ARK_ASSERT_RET_VAL(data_type == data_type::dt_wstring, false); auto old_value = data_ptr->get_w_string(); - if (old_value == value) - { + if (old_value == value) { return false; } data_ptr->set_w_string(value); - if (func_) - { + if (func_) { // data callbacks func_(data_ptr, data_impl(data_type, old_value.c_str()), data_impl(data_type, value.c_str())); } @@ -637,15 +590,13 @@ bool node_manager::set_guid(const uint32_t index, const guid_t& value) { ARK_ASSERT_RET_VAL(data_type == data_type::dt_guid, false); auto old_value = data_ptr->get_object(); - if (old_value == value) - { + if (old_value == value) { return false; } data_ptr->set_object(value); - if (func_) - { + if (func_) { // data callbacks func_(data_ptr, data_impl::from_guid(old_value), data_impl::from_guid(value)); } @@ -666,16 +617,14 @@ uint32_t node_manager::get_index(const std::string& name) const { node* node_manager::find_data(const uint32_t index) { auto data_ptr = data_list_.find_value(index); - if (nullptr == data_ptr) - { + if (nullptr == data_ptr) { auto data_meta_ptr = class_meta_->find_data_meta(index); ARK_ASSERT_RET_VAL(data_meta_ptr != nullptr, nullptr); scoped_node candidate(create_data_by_meta(data_meta_ptr)); ARK_ASSERT_RET_VAL(candidate != nullptr, nullptr); - if (!data_list_.insert(index, candidate.get()).second) - { + if (!data_list_.insert(index, candidate.get()).second) { return nullptr; } data_ptr = candidate.release(); diff --git a/src/plugins/kernel/node_manager.hpp b/src/plugins/kernel/node_manager.hpp index d85cedb95..18bcf8261 100644 --- a/src/plugins/kernel/node_manager.hpp +++ b/src/plugins/kernel/node_manager.hpp @@ -26,8 +26,7 @@ namespace ark { -class node_manager final -{ +class node_manager final { public: using node_map = object_map; using node_manager_functor = std::function; diff --git a/src/plugins/kernel/node_meta.hpp b/src/plugins/kernel/node_meta.hpp index f7a2e7ab8..9404dde37 100644 --- a/src/plugins/kernel/node_meta.hpp +++ b/src/plugins/kernel/node_meta.hpp @@ -26,8 +26,7 @@ namespace ark { -class node_meta final -{ +class node_meta final { public: node_meta() = delete; diff --git a/src/plugins/kernel/row.cpp b/src/plugins/kernel/row.cpp index b25157618..cfc5e2ec5 100644 --- a/src/plugins/kernel/row.cpp +++ b/src/plugins/kernel/row.cpp @@ -289,8 +289,7 @@ std::shared_ptr row_impl::get_node_manager() const { } int row_impl::on_node_call_back(node* node_ptr, const data& old_data, const data& new_data) { - if (func_) - { + if (func_) { func_(row_, node_ptr, old_data, new_data); } diff --git a/src/plugins/kernel/row.hpp b/src/plugins/kernel/row.hpp index cc7872c34..0622ce4e2 100644 --- a/src/plugins/kernel/row.hpp +++ b/src/plugins/kernel/row.hpp @@ -34,8 +34,7 @@ namespace entity_sync { class snapshot_access; } -class row_impl final : public row -{ +class row_impl final : public row { private: friend class kernel_module_impl; friend class table_impl; diff --git a/src/plugins/kernel/static_entity.hpp b/src/plugins/kernel/static_entity.hpp index fe1d025e7..764bb903c 100644 --- a/src/plugins/kernel/static_entity.hpp +++ b/src/plugins/kernel/static_entity.hpp @@ -26,8 +26,7 @@ namespace ark { -class static_entity -{ +class static_entity { public: virtual ~static_entity() = default; diff --git a/src/plugins/kernel/static_entity_impl.hpp b/src/plugins/kernel/static_entity_impl.hpp index 173c7e720..916961d58 100644 --- a/src/plugins/kernel/static_entity_impl.hpp +++ b/src/plugins/kernel/static_entity_impl.hpp @@ -26,8 +26,7 @@ namespace ark { -class static_entity_impl final : public static_entity -{ +class static_entity_impl final : public static_entity { public: using table_list = object_map; diff --git a/src/plugins/kernel/static_entity_manager.hpp b/src/plugins/kernel/static_entity_manager.hpp index 4e92d162b..32206c99e 100644 --- a/src/plugins/kernel/static_entity_manager.hpp +++ b/src/plugins/kernel/static_entity_manager.hpp @@ -25,8 +25,7 @@ namespace ark { -class static_entity_manager final -{ +class static_entity_manager final { public: using static_object_list = shared_object_map; @@ -43,8 +42,7 @@ class static_entity_manager final // create new class auto object_ptr = std::make_shared(class_meta_ptr, node_manager_ptr, config_id); - if (!static_object_list_.insert(config_id, object_ptr).second) - { + if (!static_object_list_.insert(config_id, object_ptr).second) { return nullptr; } diff --git a/src/plugins/kernel/table.hpp b/src/plugins/kernel/table.hpp index 46c0f9797..44512fd59 100644 --- a/src/plugins/kernel/table.hpp +++ b/src/plugins/kernel/table.hpp @@ -25,8 +25,7 @@ namespace ark { -class row -{ +class row { public: virtual ~row() = default; @@ -80,8 +79,7 @@ class row virtual bool set_guid(const std::string& name, const guid_t& value) = 0; }; -class table -{ +class table { public: virtual ~table() = default; diff --git a/src/plugins/kernel/table_impl.cpp b/src/plugins/kernel/table_impl.cpp index 28e135cd2..8623827ac 100644 --- a/src/plugins/kernel/table_impl.cpp +++ b/src/plugins/kernel/table_impl.cpp @@ -104,8 +104,7 @@ row* table_impl::add_row(uint32_t row, const data_list& args) { ARK_ASSERT_RET_VAL(args.get_count() % 2 == 0, nullptr); ark::row* row_data = nullptr; - if (row == 0) - { + if (row == 0) { row = select_row(); } @@ -142,13 +141,11 @@ void table_impl::clear() { // find uint32_t table_impl::find_int32(const uint32_t index, const int32_t value) const { - for (auto iter : data_) - { + for (auto iter : data_) { auto row_data = iter.second; ARK_ASSERT_RET_VAL(row_data != nullptr, 0u); - if (row_data->get_int32(index) == value) - { + if (row_data->get_int32(index) == value) { return iter.first; } } @@ -157,13 +154,11 @@ uint32_t table_impl::find_int32(const uint32_t index, const int32_t value) const } uint32_t table_impl::find_int64(const uint32_t index, const int64_t value) const { - for (auto iter : data_) - { + for (auto iter : data_) { auto row_data = iter.second; ARK_ASSERT_RET_VAL(row_data != nullptr, 0u); - if (row_data->get_int64(index) == value) - { + if (row_data->get_int64(index) == value) { return iter.first; } } @@ -172,13 +167,11 @@ uint32_t table_impl::find_int64(const uint32_t index, const int64_t value) const } uint32_t table_impl::find_bool(const uint32_t index, bool value) const { - for (auto iter : data_) - { + for (auto iter : data_) { auto row_data = iter.second; ARK_ASSERT_RET_VAL(row_data != nullptr, 0u); - if (row_data->get_bool(index) == value) - { + if (row_data->get_bool(index) == value) { return iter.first; } } @@ -187,13 +180,11 @@ uint32_t table_impl::find_bool(const uint32_t index, bool value) const { } uint32_t table_impl::find_float(const uint32_t index, float value) const { - for (auto iter : data_) - { + for (auto iter : data_) { auto row_data = iter.second; ARK_ASSERT_RET_VAL(row_data != nullptr, 0u); - if (row_data->get_float(index) == value) - { + if (row_data->get_float(index) == value) { return iter.first; } } @@ -202,13 +193,11 @@ uint32_t table_impl::find_float(const uint32_t index, float value) const { } uint32_t table_impl::find_double(const uint32_t index, double value) const { - for (auto iter : data_) - { + for (auto iter : data_) { auto row_data = iter.second; ARK_ASSERT_RET_VAL(row_data != nullptr, 0u); - if (row_data->get_double(index) == value) - { + if (row_data->get_double(index) == value) { return iter.first; } } @@ -217,13 +206,11 @@ uint32_t table_impl::find_double(const uint32_t index, double value) const { } uint32_t table_impl::find_string(const uint32_t index, const std::string& value) const { - for (auto iter : data_) - { + for (auto iter : data_) { auto row_data = iter.second; ARK_ASSERT_RET_VAL(row_data != nullptr, 0u); - if (row_data->get_string(index) == value) - { + if (row_data->get_string(index) == value) { return iter.first; } } @@ -232,13 +219,11 @@ uint32_t table_impl::find_string(const uint32_t index, const std::string& value) } uint32_t table_impl::find_w_string(const uint32_t index, const std::wstring& value) const { - for (auto iter : data_) - { + for (auto iter : data_) { auto row_data = iter.second; ARK_ASSERT_RET_VAL(row_data != nullptr, 0u); - if (row_data->get_w_string(index) == value) - { + if (row_data->get_w_string(index) == value) { return iter.first; } } @@ -247,13 +232,11 @@ uint32_t table_impl::find_w_string(const uint32_t index, const std::wstring& val } uint32_t table_impl::find_guid(const uint32_t index, const guid_t& value) const { - for (auto iter : data_) - { + for (auto iter : data_) { auto row_data = iter.second; ARK_ASSERT_RET_VAL(row_data != nullptr, 0u); - if (row_data->get_guid(index) == value) - { + if (row_data->get_guid(index) == value) { return iter.first; } } @@ -290,18 +273,13 @@ uint32_t table_impl::get_index(const std::string& name) const { } uint32_t table_impl::select_row() const { - if (data_.size() == current_row_) - { + if (data_.size() == current_row_) { return current_row_ + 1; - } - else - { + } else { // row starts from 1 uint32_t row = 1u; - for (auto iter : data_) - { - if (iter.first != row) - { + for (auto iter : data_) { + if (iter.first != row) { break; } @@ -356,28 +334,24 @@ row* table_impl::create_row(uint32_t row, const data_list& args) { auto func = std::bind_front(&table_impl::on_row_changed, this); - if (last_incarnation_ == std::numeric_limits::max()) - { + if (last_incarnation_ == std::numeric_limits::max()) { throw std::overflow_error("Table row incarnation exhausted"); } const auto delete_row = [](row_impl* value) { ARK_DELETE(value); }; std::unique_ptr row_ptr( ARK_NEW row_impl(class_meta_ptr, row, args, std::move(func)), delete_row); - if (row_ptr == nullptr) - { + if (row_ptr == nullptr) { return nullptr; } - if (!data_.insert(row, row_ptr.get()).second) - { + if (!data_.insert(row, row_ptr.get()).second) { return nullptr; } // No throwing work between successful insertion and identity publication. row_ptr->incarnation_ = ++last_incarnation_; auto* published_row = row_ptr.release(); - if (current_row_ < row) - { + if (current_row_ < row) { current_row_ = row; } diff --git a/src/plugins/kernel/table_impl.hpp b/src/plugins/kernel/table_impl.hpp index 61a733bec..8eba2283d 100644 --- a/src/plugins/kernel/table_impl.hpp +++ b/src/plugins/kernel/table_impl.hpp @@ -32,8 +32,7 @@ namespace entity_sync { class snapshot_access; } -class table_impl final : public table -{ +class table_impl final : public table { public: using table_data = object_map; using table_callback_functor = diff --git a/src/plugins/kernel/table_manager.hpp b/src/plugins/kernel/table_manager.hpp index a4707256f..feba67620 100644 --- a/src/plugins/kernel/table_manager.hpp +++ b/src/plugins/kernel/table_manager.hpp @@ -26,8 +26,7 @@ namespace ark { -class table_manager final -{ +class table_manager final { public: using table_list = object_map; @@ -58,8 +57,7 @@ class table_manager final table_ptr = ARK_NEW table_impl(table_meta_ptr, std::move(func)); ARK_ASSERT_RET_VAL(table_ptr != nullptr, nullptr); - if (!table_list_.insert(index, table_ptr).second) - { + if (!table_list_.insert(index, table_ptr).second) { ARK_DELETE(table_ptr); return nullptr; } diff --git a/src/plugins/kernel/table_meta.hpp b/src/plugins/kernel/table_meta.hpp index 1395f7d52..5d4083049 100644 --- a/src/plugins/kernel/table_meta.hpp +++ b/src/plugins/kernel/table_meta.hpp @@ -30,8 +30,7 @@ namespace ark { class class_meta; -class table_meta final -{ +class table_meta final { public: using col_meta_list = shared_object_map; diff --git a/src/plugins/mysql/detail/mysql_awaitable.hpp b/src/plugins/mysql/detail/mysql_awaitable.hpp index 00cddfab4..6f6793b9e 100644 --- a/src/plugins/mysql/detail/mysql_awaitable.hpp +++ b/src/plugins/mysql/detail/mysql_awaitable.hpp @@ -26,12 +26,9 @@ module_task mysql_query(service_type& service, database_awa return service.start_query( std::move(sql), [completion = std::move(completion)](mysql_service_result result) mutable { - if (auto* error = std::get_if(&result)) - { + if (auto* error = std::get_if(&result)) { completion(*error, {}); - } - else - { + } else { completion({}, std::get(std::move(result))); } }, @@ -48,12 +45,9 @@ module_task mysql_execute(service_type& service, database_a return service.start_execute( std::move(sql), std::move(parameters), [completion = std::move(completion)](mysql_service_result result) mutable { - if (auto* error = std::get_if(&result)) - { + if (auto* error = std::get_if(&result)) { completion(*error, {}); - } - else - { + } else { completion({}, std::get(std::move(result))); } }, diff --git a/src/plugins/mysql/detail/mysql_service.hpp b/src/plugins/mysql/detail/mysql_service.hpp index 721ea29b2..64f50cf5a 100644 --- a/src/plugins/mysql/detail/mysql_service.hpp +++ b/src/plugins/mysql/detail/mysql_service.hpp @@ -28,8 +28,7 @@ namespace ark::detail { // Internal bridge; the published plugin API remains unchanged. // Keep execution and statement cleanup outcomes separate: // a failed close must not turn a successful write into a failed/replayed write. -struct mysql_service_reply -{ +struct mysql_service_reply { arknet::mysql::query_result result; std::optional statement_close; std::exception_ptr statement_close_exception; @@ -37,22 +36,19 @@ struct mysql_service_reply using mysql_service_result = std::variant; -class mysql_service -{ +class mysql_service { using queue_type = completion_queue; using control_type = database_request_control; struct operation; - struct request_registry - { + struct request_registry { std::mutex mutex; std::unordered_map> active; std::uint64_t next_id{1}; database_service_diagnostics diagnostics; }; - struct operation : std::enable_shared_from_this - { + struct operation : std::enable_shared_from_this { control_type control; std::weak_ptr registry; std::uint64_t id{}; @@ -69,25 +65,17 @@ class mysql_service bool prepared{}; void forward_cancel(std::optional cancellation) { - if (cancellation) - { - try - { - if (cancellation->target == control_type::stage::acquire) - { + if (cancellation) { + try { + if (cancellation->target == control_type::stage::acquire) { pool->cancel(cancellation->id); - } - else - { + } else { lease.cancel(cancellation->id); } - } - catch (...) - { + } catch (...) { // A failed cancellation post cannot turn an accepted write // into a known failure. Its real completion/deadline remains. - if (auto requests = registry.lock()) - { + if (auto requests = registry.lock()) { std::lock_guard lock(requests->mutex); requests->diagnostics.cancellation_submission = std::current_exception(); } @@ -102,29 +90,21 @@ class mysql_service } void erase_request() { - if (auto requests = registry.lock()) - { + if (auto requests = registry.lock()) { std::lock_guard lock(requests->mutex); requests->active.erase(id); } } void return_lease(bool discard = false) { - try - { - if (discard) - { + try { + if (discard) { lease.discard(); - } - else - { + } else { lease.release(); } - } - catch (...) - { - if (auto requests = registry.lock()) - { + } catch (...) { + if (auto requests = registry.lock()) { std::lock_guard lock(requests->mutex); requests->diagnostics.lease_return = std::current_exception(); } @@ -134,8 +114,7 @@ class mysql_service std::optional remaining_options() const { const auto remaining = std::chrono::duration_cast(deadline - std::chrono::steady_clock::now()); - if (remaining <= std::chrono::milliseconds::zero()) - { + if (remaining <= std::chrono::milliseconds::zero()) { return std::nullopt; } auto options = limits; @@ -144,8 +123,7 @@ class mysql_service } void finish() { - if (!control.finish()) - { + if (!control.finish()) { return; } return_lease(); @@ -154,8 +132,7 @@ class mysql_service } void fail(std::exception_ptr failure) { - if (!control.finish()) - { + if (!control.finish()) { return; } return_lease(true); @@ -165,8 +142,7 @@ class mysql_service void close_statement() { const auto options = remaining_options(); - if (!options || !lease) - { + if (!options || !lease) { arknet::mysql::connection_result cleanup; cleanup.code = options ? arknet::mysql::connection_errc::not_connected : arknet::mysql::connection_errc::timeout; @@ -175,28 +151,23 @@ class mysql_service finish(); return; } - try - { + try { const auto submission = control.begin(control_type::stage::command); const auto native_id = lease.async_close( statement, [self = shared_from_this(), submission](arknet::mysql::connection_result result) mutable { - if (!self->control.complete(submission)) - { + if (!self->control.complete(submission)) { return; } self->reply.statement_close.emplace(std::move(result)); - if (!bool(*self->reply.statement_close)) - { + if (!bool(*self->reply.statement_close)) { self->return_lease(true); } self->finish(); }, *options); forward_cancel(control.publish(submission, native_id)); - } - catch (...) - { + } catch (...) { reply.statement_close_exception = std::current_exception(); return_lease(true); finish(); @@ -204,15 +175,13 @@ class mysql_service } void execute() { - if (control.cancelled()) - { + if (control.cancelled()) { reply.result.status.code = arknet::mysql::connection_errc::cancelled; close_statement(); return; } const auto options = remaining_options(); - if (!options) - { + if (!options) { reply.result.status.code = arknet::mysql::connection_errc::timeout; close_statement(); return; @@ -221,8 +190,7 @@ class mysql_service const auto native_id = lease.async_execute( statement, std::move(parameters), [self = shared_from_this(), submission](arknet::mysql::query_result result) mutable { - if (!self->control.complete(submission)) - { + if (!self->control.complete(submission)) { return; } self->reply.result = std::move(result); @@ -233,65 +201,56 @@ class mysql_service } void acquired(arknet::mysql::pool::acquire_result result) { - if (!result) - { + if (!result) { reply.result.status = std::move(result.status); // A successful acquisition status is insufficient if the // lease became unavailable before this callback used it. - if (reply.result.status.code == arknet::mysql::connection_errc::none) - { + if (reply.result.status.code == arknet::mysql::connection_errc::none) { reply.result.status.code = arknet::mysql::connection_errc::not_connected; } finish(); return; } lease = std::move(result.connection); - if (control.cancelled()) - { + if (control.cancelled()) { reply.result.status.code = arknet::mysql::connection_errc::cancelled; finish(); return; } const auto options = remaining_options(); - if (!options) - { + if (!options) { reply.result.status.code = arknet::mysql::connection_errc::timeout; finish(); return; } - if (prepared) - { + if (prepared) { const auto submission = control.begin(control_type::stage::command); const auto native_id = lease.async_prepare( std::move(sql), [self = shared_from_this(), submission](arknet::mysql::prepare_result result) mutable { - if (!self->control.complete(submission)) - { + if (!self->control.complete(submission)) { return; } - if (!result) - { + if (!result) { self->reply.result.status = std::move(result.status); self->finish(); return; } self->statement = std::move(result.statement); - try - { self->execute(); } - catch (...) - { self->fail(std::current_exception()); } + try { + self->execute(); + } catch (...) { + self->fail(std::current_exception()); + } }, *options); forward_cancel(control.publish(submission, native_id)); - } - else - { + } else { const auto submission = control.begin(control_type::stage::command); const auto native_id = lease.async_query( std::move(sql), [self = shared_from_this(), submission](arknet::mysql::query_result result) mutable { - if (!self->control.complete(submission)) - { + if (!self->control.complete(submission)) { return; } self->reply.result = std::move(result); @@ -349,8 +308,7 @@ class mysql_service { std::lock_guard lock(requests_->mutex); const auto found = requests_->active.find(id); - if (found != requests_->active.end()) - { + if (found != requests_->active.end()) { pending = found->second.lock(); } } @@ -384,16 +342,13 @@ class mysql_service { std::lock_guard lock(requests_->mutex); pending.reserve(requests_->active.size()); - for (const auto& [id, weak] : requests_->active) - { - if (auto request = weak.lock()) - { + for (const auto& [id, weak] : requests_->active) { + if (auto request = weak.lock()) { pending.push_back(std::move(request)); } } } - for (const auto& request : pending) - { + for (const auto& request : pending) { request->cancel(); } } @@ -457,19 +412,16 @@ class mysql_service template bool retire_native(finalizer_type finalizer) { check_owner(); - if (!logically_drained()) - { + if (!logically_drained()) { return false; } auto activity = activity_; auto pool = pool_; - if (activity->native_retired) - { + if (activity->native_retired) { return true; } database_service_activity::guard active(activity); - if (!finalizer(*pool)) - { + if (!finalizer(*pool)) { return false; } activity->native_retired = true; @@ -477,8 +429,7 @@ class mysql_service } void check_owner() const { - if (std::this_thread::get_id() != owner_) - { + if (std::this_thread::get_id() != owner_) { throw std::logic_error("Database service must be used on its module thread"); } } @@ -491,37 +442,30 @@ class mysql_service auto handler = std::make_shared(std::move(completion)); mysql_service_result rejected; request_id id{}; - if (!arknet::detail::checked_deadline(std::chrono::steady_clock::now(), timeout)) - { + if (!arknet::detail::checked_deadline(std::chrono::steady_clock::now(), timeout)) { std::get(rejected).result.status.code = arknet::mysql::connection_errc::invalid_options; - } - else - { - try - { + } else { + try { id = submit( std::move(sql), std::move(parameters), [handler](mysql_service_result result) { - if (*handler) - { + if (*handler) { (*handler)(std::move(result)); } }, timeout, prepared); - if (id) - { + if (id) { return id; } std::get(rejected).result.status.code = accepting_ ? arknet::mysql::connection_errc::queue_full : arknet::mysql::connection_errc::not_connected; + } catch (...) { + rejected = std::current_exception(); } - catch (...) - { rejected = std::current_exception(); } } - if (*handler) - { + if (*handler) { (*handler)(std::move(rejected)); } return 0; @@ -533,38 +477,31 @@ class mysql_service database_service_activity::guard active(activity_); auto completion = std::move(incoming); const auto deadline = arknet::detail::checked_deadline(std::chrono::steady_clock::now(), timeout); - if (!deadline) - { + if (!deadline) { throw std::invalid_argument("Database operation timeout is not representable"); } std::size_t bytes = sql.capacity(); if (parameters.capacity() > - (std::numeric_limits::max() - bytes) / sizeof(arknet::mysql::field_value)) - { + (std::numeric_limits::max() - bytes) / sizeof(arknet::mysql::field_value)) { return false; } bytes += parameters.capacity() * sizeof(arknet::mysql::field_value); - for (const auto& value : parameters) - { - if (const auto* text = std::get_if(&value)) - { - if (text->capacity() > std::numeric_limits::max() - bytes) - { + for (const auto& value : parameters) { + if (const auto* text = std::get_if(&value)) { + if (text->capacity() > std::numeric_limits::max() - bytes) { return false; } bytes += text->capacity(); } } auto ticket = completions_->admit(bytes, std::move(completion)); - if (!ticket) - { + if (!ticket) { return 0; } auto queue = completions_; auto requests = requests_; std::shared_ptr pending; - try - { + try { pending = std::make_shared(); pending->queue = queue; pending->registry = requests; @@ -577,16 +514,14 @@ class mysql_service pending->prepared = prepared; { std::lock_guard lock(requests->mutex); - if (!requests->next_id) - { + if (!requests->next_id) { throw std::overflow_error("Database request IDs exhausted"); } pending->id = requests->next_id++; requests->active.emplace(pending->id, pending); } const auto options = pending->remaining_options(); - if (!options) - { + if (!options) { pending->reply.result.status.code = arknet::mysql::connection_errc::timeout; pending->finish(); return pending->id; @@ -594,22 +529,19 @@ class mysql_service const auto submission = pending->control.begin(control_type::stage::acquire); const auto native_id = pending->pool->async_acquire( [pending, submission](arknet::mysql::pool::acquire_result acquired) mutable { - if (!pending->control.complete(submission)) - { + if (!pending->control.complete(submission)) { return; } - try - { pending->acquired(std::move(acquired)); } - catch (...) - { pending->fail(std::current_exception()); } + try { + pending->acquired(std::move(acquired)); + } catch (...) { + pending->fail(std::current_exception()); + } }, options->timeout); pending->forward_cancel(pending->control.publish(submission, native_id)); - } - catch (...) - { - if (pending) - { + } catch (...) { + if (pending) { pending->control.finish(); pending->erase_request(); } diff --git a/src/plugins/mysql/detail/mysql_transaction.hpp b/src/plugins/mysql/detail/mysql_transaction.hpp index 132f35ab3..951a4b6c2 100644 --- a/src/plugins/mysql/detail/mysql_transaction.hpp +++ b/src/plugins/mysql/detail/mysql_transaction.hpp @@ -28,8 +28,7 @@ namespace ark::detail { -enum class mysql_transaction_outcome -{ +enum class mysql_transaction_outcome { not_started, active, committed, @@ -37,20 +36,17 @@ enum class mysql_transaction_outcome unconfirmed }; -struct mysql_transaction_options -{ +struct mysql_transaction_options { std::chrono::milliseconds timeout; std::chrono::milliseconds cleanup_timeout; }; -struct mysql_transaction_limits -{ +struct mysql_transaction_limits { std::size_t max_transactions; std::size_t max_input_bytes; }; -struct mysql_transaction_snapshot -{ +struct mysql_transaction_snapshot { mysql_transaction_outcome outcome{mysql_transaction_outcome::not_started}; std::optional rollback_code; bool rollback_outcome_unknown{}; @@ -66,8 +62,7 @@ struct mysql_transaction_owner; // Private move-only handle. Destruction requests abandonment; it does not wait // for, or claim completion of, an asynchronous rollback. -class mysql_transaction -{ +class mysql_transaction { public: using callback = std::function; using request_id = std::uint64_t; @@ -98,8 +93,7 @@ class mysql_transaction std::shared_ptr state_; }; -struct mysql_transaction_reply -{ +struct mysql_transaction_reply { arknet::mysql::query_result result; std::optional statement_close; std::exception_ptr statement_close_exception; @@ -115,8 +109,7 @@ struct mysql_transaction_reply } }; -enum class mysql_transaction_phase -{ +enum class mysql_transaction_phase { acquiring, beginning, idle, @@ -130,8 +123,7 @@ enum class mysql_transaction_phase terminal }; -struct mysql_transaction_state -{ +struct mysql_transaction_state { using event = std::variant; using queue_type = completion_queue; @@ -165,10 +157,8 @@ struct mysql_transaction_state // The IO callback never touches the shared lease or invokes user code. void publish(std::uint64_t expected, event response) { std::lock_guard lock(event_mutex); - if (retired || epoch != expected || completed) - { - if (auto* acquired = std::get_if(&response)) - { + if (retired || epoch != expected || completed) { + if (auto* acquired = std::get_if(&response)) { acquired->connection.discard(); } return; @@ -177,8 +167,7 @@ struct mysql_transaction_state } }; -struct mysql_transaction_owner : std::enable_shared_from_this -{ +struct mysql_transaction_owner : std::enable_shared_from_this { using state_type = mysql_transaction_state; using phase_type = mysql_transaction_phase; using callback = mysql_transaction::callback; @@ -186,8 +175,7 @@ struct mysql_transaction_owner : std::enable_shared_from_this state; std::shared_ptr> input; std::size_t bytes{}; @@ -201,8 +189,7 @@ struct mysql_transaction_owner : std::enable_shared_from_this pool, mysql_transaction_limits limits, arknet::mysql::query_options query_limits) : mysql_transaction_owner(limits, query_limits) { - if (!pool) - { + if (!pool) { throw std::invalid_argument("MySQL transaction service requires an existing pool"); } this->pool = std::move(pool); @@ -217,15 +204,13 @@ struct mysql_transaction_owner : std::enable_shared_from_this& state, std::size_t bytes, callback completion) { - if (bytes > max_input_bytes - retained_input->load()) - { + if (bytes > max_input_bytes - retained_input->load()) { return false; } - if (!next_id) - { + if (!next_id) { throw std::overflow_error("MySQL transaction request IDs exhausted"); } auto reservation = std::make_shared(); @@ -250,13 +233,11 @@ struct mysql_transaction_owner : std::enable_shared_from_thisfetch_add(bytes); auto delivery = queue->admit( bytes, [reservation, completion = std::move(completion)](mysql_transaction_reply result) mutable { - if (completion) - { + if (completion) { completion(std::move(result)); } }); - if (!delivery) - { + if (!delivery) { return false; } state->delivery = std::move(delivery); @@ -269,18 +250,14 @@ struct mysql_transaction_owner : std::enable_shared_from_this(); @@ -290,21 +267,17 @@ struct mysql_transaction_owner : std::enable_shared_from_thisbegin_delivery = true; auto handler = std::make_shared(std::move(completion)); if (!reserve(state, 0, [handler](auto reply) { - if (*handler) - { + if (*handler) { (*handler)(std::move(reply)); } - })) - { + })) { return reject(std::move(*handler), arknet::mysql::connection_errc::queue_full); } slot = state; const auto expected = ++state->epoch; - try - { + try { const auto remaining = std::chrono::duration_cast(*deadline - clock::now()); - if (remaining <= std::chrono::milliseconds::zero()) - { + if (remaining <= std::chrono::milliseconds::zero()) { arknet::mysql::pool::acquire_result expired; expired.status.code = arknet::mysql::connection_errc::timeout; state->publish(expected, std::move(expired)); @@ -314,9 +287,9 @@ struct mysql_transaction_owner : std::enable_shared_from_thispublish(expected, std::move(result)); }, remaining); + } catch (...) { + state->publish(expected, std::current_exception()); } - catch (...) - { state->publish(expected, std::current_exception()); } return state->logical_id; } return reject(std::move(completion), arknet::mysql::connection_errc::queue_full); @@ -326,32 +299,25 @@ struct mysql_transaction_owner : std::enable_shared_from_this parameters = {}) { check_owner(); database_service_activity::guard active(activity); - if (state->retired || state->phase == phase_type::terminal) - { + if (state->retired || state->phase == phase_type::terminal) { return reject(std::move(completion), arknet::mysql::connection_errc::not_connected); } - if (state->phase != phase_type::idle) - { + if (state->phase != phase_type::idle) { return reject(std::move(completion), arknet::mysql::connection_errc::already_started); } - if (state->abandoned || clock::now() >= state->deadline) - { + if (state->abandoned || clock::now() >= state->deadline) { state->abandoned = true; return reject(std::move(completion), arknet::mysql::connection_errc::timeout); } std::size_t bytes = sql.capacity(); if (parameters.capacity() > - (std::numeric_limits::max() - bytes) / sizeof(arknet::mysql::field_value)) - { + (std::numeric_limits::max() - bytes) / sizeof(arknet::mysql::field_value)) { return reject(std::move(completion), arknet::mysql::connection_errc::queue_full); } bytes += parameters.capacity() * sizeof(arknet::mysql::field_value); - for (const auto& value : parameters) - { - if (const auto* text = std::get_if(&value)) - { - if (text->capacity() > std::numeric_limits::max() - bytes) - { + for (const auto& value : parameters) { + if (const auto* text = std::get_if(&value)) { + if (text->capacity() > std::numeric_limits::max() - bytes) { return reject(std::move(completion), arknet::mysql::connection_errc::queue_full); } bytes += text->capacity(); @@ -359,12 +325,10 @@ struct mysql_transaction_owner : std::enable_shared_from_this(std::move(completion)); if (!reserve(state, bytes, [handler](auto reply) { - if (*handler) - { + if (*handler) { (*handler)(std::move(reply)); } - })) - { + })) { return reject(std::move(*handler), arknet::mysql::connection_errc::queue_full); } state->reply = {}; @@ -383,67 +347,54 @@ struct mysql_transaction_owner : std::enable_shared_from_thiscleanup_deadline : state->deadline; options.timeout = std::chrono::duration_cast(deadline - clock::now()); - if (options.timeout <= std::chrono::milliseconds::zero()) - { - if (phase == phase_type::closing_statement) - { + if (options.timeout <= std::chrono::milliseconds::zero()) { + if (phase == phase_type::closing_statement) { arknet::mysql::connection_result expired; expired.code = arknet::mysql::connection_errc::timeout; state->publish(expected, std::move(expired)); - } - else - { + } else { arknet::mysql::query_result expired; expired.status.code = arknet::mysql::connection_errc::timeout; state->publish(expected, std::move(expired)); } return; } - try - { - if (phase == phase_type::preparing) - { + try { + if (phase == phase_type::preparing) { state->native_id = state->lease.async_prepare( std::move(sql), [state, expected]( arknet::mysql::prepare_result result) { state->publish(expected, std::move(result)); }, options); - } - else if (phase == phase_type::executing) - { + } else if (phase == phase_type::executing) { state->native_id = state->lease.async_execute( state->statement, std::move(state->parameters), [state, expected]( arknet::mysql::query_result result) { state->publish(expected, std::move(result)); }, options); - } - else if (phase == phase_type::closing_statement) - { + } else if (phase == phase_type::closing_statement) { state->native_id = state->lease.async_close( state->statement, [state, expected]( arknet::mysql::connection_result result) { state->publish(expected, std::move(result)); }, options); - } - else - { + } else { state->native_id = state->lease.async_query( std::move(sql), [state, expected]( arknet::mysql::query_result result) { state->publish(expected, std::move(result)); }, options); } + } catch (...) { + state->publish(expected, std::current_exception()); } - catch (...) - { state->publish(expected, std::current_exception()); } } bool cancel(const std::shared_ptr& state, request_id id) { check_owner(); if (!id || id != state->logical_id || state->phase == phase_type::idle || state->phase == phase_type::terminal || state->phase == phase_type::cleanup || - state->cancellation_requested) - { + state->cancellation_requested) { return false; } bool native_completed{}; @@ -451,8 +402,7 @@ struct mysql_transaction_owner : std::enable_shared_from_thisevent_mutex); native_completed = state->completed.has_value(); if (native_completed && state->phase != phase_type::preparing && state->phase != phase_type::executing && - state->phase != phase_type::closing_statement) - { + state->phase != phase_type::closing_statement) { return false; } } @@ -460,41 +410,32 @@ struct mysql_transaction_owner : std::enable_shared_from_thiscancellation_requested = true; // A prepared step is not terminal when one native stage completes. // Cancel its pending owner transition without cancelling a stale ID. - if (native_completed) - { + if (native_completed) { return true; } - try - { - if (state->phase == phase_type::acquiring) - { + try { + if (state->phase == phase_type::acquiring) { pool->cancel(state->native_id); - } - else - { + } else { state->lease.cancel(state->native_id); } + } catch (...) { + state->status.cancellation_exception = std::current_exception(); } - catch (...) - { state->status.cancellation_exception = std::current_exception(); } return true; } void release(const std::shared_ptr& state, bool discard) { state->status.discard_requested = discard; - try - { - if (discard) - { + try { + if (discard) { state->lease.discard(); - } - else - { + } else { state->lease.release(); } + } catch (...) { + state->status.lease_return_exception = std::current_exception(); } - catch (...) - { state->status.lease_return_exception = std::current_exception(); } state->phase = phase_type::terminal; state->statement = {}; std::vector{}.swap(state->parameters); @@ -503,11 +444,9 @@ struct mysql_transaction_owner : std::enable_shared_from_this& state) { state->statement = {}; std::vector{}.swap(state->parameters); - if (state->delivery) - { + if (state->delivery) { state->reply.transaction_status = state->status; - if (state->begin_delivery && state->status.outcome == mysql_transaction_outcome::active) - { + if (state->begin_delivery && state->status.outcome == mysql_transaction_outcome::active) { state->reply.transaction.emplace(mysql_transaction(state)); } queue->complete(std::exchange(state->delivery, {}), std::move(state->reply)); @@ -516,12 +455,10 @@ struct mysql_transaction_owner : std::enable_shared_from_this& state) { state->abort_requested = true; - if (!state->cleanup_deadline) - { + if (!state->cleanup_deadline) { state->cleanup_deadline = arknet::detail::checked_deadline(clock::now(), state->cleanup_timeout); } - if (!state->lease || !state->cleanup_deadline) - { + if (!state->lease || !state->cleanup_deadline) { state->status.outcome = mysql_transaction_outcome::unconfirmed; release(state, true); deliver(state); @@ -533,8 +470,7 @@ struct mysql_transaction_owner : std::enable_shared_from_this& state) { // An uncertain command cannot be replayed or followed by cleanup SQL. // Discarding its connection also disposes of its server-side statement. - if (state->reply.result.status.outcome_unknown) - { + if (state->reply.result.status.outcome_unknown) { state->status.outcome = mysql_transaction_outcome::unconfirmed; release(state, true); deliver(state); @@ -545,10 +481,8 @@ struct mysql_transaction_owner : std::enable_shared_from_this& state, state_type::event response) { state->native_id = 0; - if (auto* prepared = std::get_if(&response)) - { - if (!*prepared) - { + if (auto* prepared = std::get_if(&response)) { + if (!*prepared) { arknet::mysql::query_result failed; failed.status = std::move(prepared->status); state->phase = phase_type::query; @@ -556,42 +490,32 @@ struct mysql_transaction_owner : std::enable_shared_from_thisstatement = std::move(prepared->statement); - if (state->abort_requested || state->abandoned || clock::now() >= state->deadline) - { + if (state->abort_requested || state->abandoned || clock::now() >= state->deadline) { state->reply.result.status.code = state->abort_requested || state->abandoned ? arknet::mysql::connection_errc::cancelled : arknet::mysql::connection_errc::timeout; close_statement(state); - } - else - { + } else { issue(state, {}, phase_type::executing); } return; } - if (auto* closed = std::get_if(&response)) - { + if (auto* closed = std::get_if(&response)) { state->reply.statement_close.emplace(std::move(*closed)); - if (!*state->reply.statement_close) - { + if (!*state->reply.statement_close) { state->status.outcome = mysql_transaction_outcome::unconfirmed; release(state, true); deliver(state); - } - else - { + } else { state->phase = phase_type::query; advance(state, std::move(state->reply.result)); } return; } - if (auto* acquired = std::get_if(&response)) - { - if (!*acquired) - { + if (auto* acquired = std::get_if(&response)) { + if (!*acquired) { state->reply.result.status = std::move(acquired->status); - if (state->reply.result.status.code == arknet::mysql::connection_errc::none) - { + if (state->reply.result.status.code == arknet::mysql::connection_errc::none) { state->reply.result.status.code = arknet::mysql::connection_errc::not_connected; } release(state, true); @@ -599,8 +523,7 @@ struct mysql_transaction_owner : std::enable_shared_from_thislease = std::move(acquired->connection); - if (state->abort_requested || state->abandoned || clock::now() >= state->deadline) - { + if (state->abort_requested || state->abandoned || clock::now() >= state->deadline) { state->reply.result.status.code = state->abort_requested ? arknet::mysql::connection_errc::cancelled : arknet::mysql::connection_errc::timeout; release(state, false); @@ -611,18 +534,12 @@ struct mysql_transaction_owner : std::enable_shared_from_thisphase == phase_type::cleanup; - if (auto* error = std::get_if(&response)) - { - if (state->phase == phase_type::closing_statement) - { + if (auto* error = std::get_if(&response)) { + if (state->phase == phase_type::closing_statement) { state->reply.statement_close_exception = *error; - } - else if (cleaning) - { + } else if (cleaning) { state->status.cleanup_exception = *error; - } - else - { + } else { state->reply.initiation_exception = *error; } state->status.outcome = state->phase == phase_type::acquiring ? mysql_transaction_outcome::not_started @@ -632,16 +549,14 @@ struct mysql_transaction_owner : std::enable_shared_from_this(std::move(response)); - if (state->phase == phase_type::executing) - { + if (state->phase == phase_type::executing) { state->reply.result = std::move(result); close_statement(state); return; } // SERVER_STATUS_IN_TRANS is bit 0 in MySQL OK/EOF status flags. const bool in_transaction = (result.status_flags & 1u) != 0; - if (cleaning) - { + if (cleaning) { state->status.outcome = result && !in_transaction ? mysql_transaction_outcome::rolled_back : mysql_transaction_outcome::unconfirmed; state->status.rollback_code = result.status.code; @@ -652,51 +567,40 @@ struct mysql_transaction_owner : std::enable_shared_from_thisreply.result = std::move(result); - if (state->phase == phase_type::beginning && state->reply.result && in_transaction) - { + if (state->phase == phase_type::beginning && state->reply.result && in_transaction) { state->status.outcome = mysql_transaction_outcome::active; - if (state->abort_requested || state->abandoned || clock::now() >= state->deadline) - { + if (state->abort_requested || state->abandoned || clock::now() >= state->deadline) { cleanup(state); - } - else - { + } else { state->phase = phase_type::idle; deliver(state); } return; } - if (state->phase == phase_type::committing && state->reply.result && !in_transaction) - { + if (state->phase == phase_type::committing && state->reply.result && !in_transaction) { state->status.outcome = mysql_transaction_outcome::committed; release(state, false); deliver(state); return; } - if (state->phase == phase_type::rolling_back) - { + if (state->phase == phase_type::rolling_back) { state->status.outcome = state->reply.result && !in_transaction ? mysql_transaction_outcome::rolled_back : mysql_transaction_outcome::unconfirmed; release(state, state->status.outcome != mysql_transaction_outcome::rolled_back); deliver(state); return; } - if (state->phase == phase_type::query && state->reply.result && in_transaction) - { - if (state->abort_requested || state->abandoned || clock::now() >= state->deadline) - { + if (state->phase == phase_type::query && state->reply.result && in_transaction) { + if (state->abort_requested || state->abandoned || clock::now() >= state->deadline) { cleanup(state); - } - else - { + } else { state->phase = phase_type::idle; deliver(state); } return; } if (!state->reply.result && !state->reply.result.status.outcome_unknown && state->lease && - state->phase != phase_type::beginning) - { + state->phase != phase_type::beginning) { cleanup(state); return; } @@ -709,12 +613,10 @@ struct mysql_transaction_owner : std::enable_shared_from_thisphase == phase_type::terminal) - { + if (!state || state->phase == phase_type::terminal) { continue; } std::optional response; @@ -722,29 +624,23 @@ struct mysql_transaction_owner : std::enable_shared_from_thisevent_mutex); response.swap(state->completed); } - if (response) - { + if (response) { advance(state, std::move(*response)); - } - else if (state->phase == phase_type::idle && (state->abandoned || clock::now() >= state->deadline)) - { + } else if (state->phase == phase_type::idle && (state->abandoned || clock::now() >= state->deadline)) { cleanup(state); } // In-flight native calls already own their remaining deadline. // Cancelling them here would race timeout into a user cancellation. - else if (state->phase != phase_type::idle && state->phase != phase_type::cleanup && state->abandoned) - { + else if (state->phase != phase_type::idle && state->phase != phase_type::cleanup && state->abandoned) { cancel(state, state->logical_id); } } const auto dispatched = queue->dispatch(maximum); const auto reaped = std::min(maximum, states.size()); - for (std::size_t index = 0; index < reaped; ++index) - { + for (std::size_t index = 0; index < reaped; ++index) { auto& state = states[reap_cursor]; reap_cursor = (reap_cursor + 1) % states.size(); - if (state && state->phase == phase_type::terminal && state->deliveries == 0) - { + if (state && state->phase == phase_type::terminal && state->deliveries == 0) { state.reset(); } } @@ -766,8 +662,7 @@ struct mysql_transaction_owner : std::enable_shared_from_thisdepth != 0 || !queue->quiescent()) - { + if (closed || activity->depth != 0 || !queue->quiescent()) { return false; } return std::none_of(states.begin(), states.end(), [](const auto& state) { return bool(state); }); @@ -778,13 +673,10 @@ struct mysql_transaction_owner : std::enable_shared_from_thisretired = true; - if (state->phase != phase_type::terminal) - { + if (state->phase != phase_type::terminal) { state->status.outcome = mysql_transaction_outcome::unconfirmed; release(state, true); } @@ -810,8 +702,7 @@ struct mysql_transaction_owner : std::enable_shared_from_thisabandoned = true; } } inline std::shared_ptr mysql_transaction::lock_owner() const { - if (state_ && std::this_thread::get_id() != state_->thread) - { + if (state_ && std::this_thread::get_id() != state_->thread) { throw std::logic_error("MySQL transaction handles must be used on their module thread"); } return state_ ? state_->owner.lock() : nullptr; } inline mysql_transaction::request_id mysql_transaction::start_query(std::string sql, callback completion) { - if (auto owner = lock_owner()) - { + if (auto owner = lock_owner()) { return owner->submit(state_, std::move(sql), mysql_transaction_phase::query, std::move(completion)); } return mysql_transaction_owner::reject(std::move(completion), arknet::mysql::connection_errc::not_connected); @@ -847,8 +735,7 @@ inline mysql_transaction::request_id mysql_transaction::start_query(std::string inline mysql_transaction::request_id mysql_transaction::start_execute( std::string sql, std::vector parameters, callback completion) { - if (auto owner = lock_owner()) - { + if (auto owner = lock_owner()) { return owner->submit( state_, std::move(sql), mysql_transaction_phase::preparing, std::move(completion), std::move(parameters)); } @@ -856,8 +743,7 @@ inline mysql_transaction::request_id mysql_transaction::start_execute( } inline mysql_transaction::request_id mysql_transaction::start_commit(callback completion) { - if (auto owner = lock_owner()) - { + if (auto owner = lock_owner()) { return owner->submit( state_, "COMMIT AND NO CHAIN NO RELEASE", mysql_transaction_phase::committing, std::move(completion)); } @@ -865,8 +751,7 @@ inline mysql_transaction::request_id mysql_transaction::start_commit(callback co } inline mysql_transaction::request_id mysql_transaction::start_rollback(callback completion) { - if (auto owner = lock_owner()) - { + if (auto owner = lock_owner()) { return owner->submit( state_, "ROLLBACK AND NO CHAIN NO RELEASE", mysql_transaction_phase::rolling_back, std::move(completion)); } @@ -874,16 +759,14 @@ inline mysql_transaction::request_id mysql_transaction::start_rollback(callback } inline bool mysql_transaction::cancel(request_id id) { - if (auto owner = lock_owner()) - { + if (auto owner = lock_owner()) { return owner->cancel(state_, id); } return false; } inline mysql_transaction_snapshot mysql_transaction::snapshot() const { - if (auto owner = lock_owner()) - { + if (auto owner = lock_owner()) { owner->check_owner(); } return state_ ? state_->status : mysql_transaction_snapshot{}; @@ -891,8 +774,7 @@ inline mysql_transaction_snapshot mysql_transaction::snapshot() const { // Development-only owner of transaction admission and delivery. The caller // supplies an existing native pool; no new pool or worker is created here. -class mysql_transaction_service -{ +class mysql_transaction_service { public: using callback = mysql_transaction::callback; using request_id = mysql_transaction::request_id; @@ -903,9 +785,7 @@ class mysql_transaction_service } // Internal connection-construction channel. Bind before publishing or starting work. - struct prepared_t - { - }; + struct prepared_t {}; mysql_transaction_service( prepared_t, mysql_transaction_limits limits, arknet::mysql::query_options query_limits = {}) @@ -946,10 +826,8 @@ class mysql_transaction_service bool cancel(request_id id) { owner_->check_owner(); - for (const auto& state : owner_->states) - { - if (state && state->logical_id == id) - { + for (const auto& state : owner_->states) { + if (state && state->logical_id == id) { return owner_->cancel(state, id); } } @@ -964,8 +842,7 @@ class mysql_transaction_service std::size_t active() const { owner_->check_owner(); std::size_t count{}; - for (const auto& state : owner_->states) - { + for (const auto& state : owner_->states) { count += bool(state); } return count; diff --git a/src/plugins/mysql/mysql_module.cpp b/src/plugins/mysql/mysql_module.cpp index efc3d03d9..f6761efee 100644 --- a/src/plugins/mysql/mysql_module.cpp +++ b/src/plugins/mysql/mysql_module.cpp @@ -13,8 +13,7 @@ namespace ark { -class mysql_module_impl final : public module_base -{ +class mysql_module_impl final : public module_base { public: mysql_module_impl(); ~mysql_module_impl() override; @@ -40,10 +39,8 @@ class mysql_module_impl final : public module_base std::shared_ptr state_; }; -struct mysql_module_impl::state -{ - struct connection - { +struct mysql_module_impl::state { + struct connection { std::optional queries; detail::mysql_transaction_service transactions; detail::database_awaitable query_bridge; @@ -65,8 +62,7 @@ struct mysql_module_impl::state } }; - struct transaction - { + struct transaction { std::shared_ptr owner; detail::mysql_transaction handle; bool busy{}; @@ -77,14 +73,12 @@ struct mysql_module_impl::state } }; - struct operation_guard - { + struct operation_guard { transaction& value; explicit operation_guard(transaction& item) : value(item) { - if (value.busy) - { + if (value.busy) { throw std::logic_error("A transaction already has an active operation"); } value.busy = true; @@ -103,16 +97,14 @@ struct mysql_module_impl::state bool closed{}; void check_owner() const { - if (owner != std::this_thread::get_id()) - { + if (owner != std::this_thread::get_id()) { throw std::logic_error("MySQL module requires its framework thread"); } } void check_open() const { check_owner(); - if (closed) - { + if (closed) { throw std::logic_error("MySQL module is retiring"); } } @@ -120,8 +112,7 @@ struct mysql_module_impl::state std::shared_ptr find(const std::string& name) const { check_open(); const auto found = connections.find(name); - if (found == connections.end()) - { + if (found == connections.end()) { throw std::invalid_argument("Unknown MySQL connection name"); } return found->second; @@ -130,8 +121,7 @@ struct mysql_module_impl::state std::shared_ptr find(mysql_transaction_id id) const { check_open(); const auto found = transactions.find(id); - if (!id || found == transactions.end()) - { + if (!id || found == transactions.end()) { throw std::invalid_argument("Unknown MySQL transaction"); } return found->second; @@ -166,16 +156,14 @@ struct mysql_module_impl::state static task run_begin( std::shared_ptr shared, std::shared_ptr node, mysql_transaction_options options) { shared->check_open(); - if (shared->next_id == std::numeric_limits::max()) - { + if (shared->next_id == std::numeric_limits::max()) { throw std::overflow_error("MySQL transaction identifiers exhausted"); } const auto id = shared->next_id++; auto reply = co_await detail::mysql_transaction_begin(node->transactions, node->transaction_bridge, detail::mysql_transaction_options{options.timeout, options.cleanup_timeout}); mysql_transaction_id admitted{}; - if (reply.transaction) - { + if (reply.transaction) { // Allocation failure abandons the handle through its normal deadline // cleanup. No private transaction object escapes the plugin module. auto entry = std::make_shared(node, std::move(*reply.transaction)); @@ -184,8 +172,7 @@ struct mysql_module_impl::state } co_return adapt(std::move(reply), admitted); } - enum class step - { + enum class step { query, execute, commit, @@ -199,8 +186,7 @@ struct mysql_module_impl::state operation_guard active(*entry); auto& bridge = entry->owner->transaction_bridge; detail::mysql_transaction_reply reply; - switch (action) - { + switch (action) { case step::query: reply = co_await detail::mysql_transaction_query(entry->handle, bridge, std::move(sql)); break; @@ -227,8 +213,7 @@ mysql_module_impl::~mysql_module_impl() = default; bool mysql_module_impl::init() { state_->check_open(); - if (!get_plugin_manager()) - { + if (!get_plugin_manager()) { return false; } state_->runtime = get_plugin_manager()->get_task_runtime(); @@ -238,32 +223,25 @@ bool mysql_module_impl::init() { bool mysql_module_impl::configure(std::string name, mysql_options options) { auto shared = state_; shared->check_open(); - if (!get_plugin_manager() || shared->connections.contains(name)) - { + if (!get_plugin_manager() || shared->connections.contains(name)) { return false; } - if (name.empty() || !options.max_operations || !options.max_transactions || !options.max_input_bytes) - { + if (name.empty() || !options.max_operations || !options.max_transactions || !options.max_input_bytes) { throw std::invalid_argument("MySQL requires a connection name and positive limits"); } - if (get_plugin_manager()->get_shutdown_state() != plugin_manager::shutdown_state::running) - { + if (get_plugin_manager()->get_shutdown_state() != plugin_manager::shutdown_state::running) { return false; } shared->runtime = get_plugin_manager()->get_task_runtime(); // Allocate the destination node and buckets before starting native IO. auto [entry, inserted] = shared->connections.try_emplace(std::move(name), nullptr); - if (!inserted) - { + if (!inserted) { return false; } - try - { + try { auto node = std::make_shared(std::move(options), shared->runtime); entry->second = std::move(node); - } - catch (...) - { + } catch (...) { // This unpublished entry is still empty; preserve same-name retry. shared->connections.erase(entry); throw; @@ -274,22 +252,17 @@ bool mysql_module_impl::configure(std::string name, mysql_options options) { bool mysql_module_impl::update() { auto shared = state_; shared->check_owner(); - for (const auto& [name, node] : shared->connections) - { + for (const auto& [name, node] : shared->connections) { node->queries->update(); node->transactions.update(); node->query_bridge.dispatch(); node->transaction_bridge.dispatch(); } - for (auto iter = shared->transactions.begin(); iter != shared->transactions.end();) - { + for (auto iter = shared->transactions.begin(); iter != shared->transactions.end();) { const auto& entry = iter->second; - if (!entry->busy && entry->handle.snapshot().outcome != detail::mysql_transaction_outcome::active) - { + if (!entry->busy && entry->handle.snapshot().outcome != detail::mysql_transaction_outcome::active) { iter = shared->transactions.erase(iter); - } - else - { + } else { ++iter; } } @@ -298,10 +271,8 @@ bool mysql_module_impl::update() { bool mysql_module_impl::ready_to_shut() const { state_->check_owner(); - for (const auto& [name, node] : state_->connections) - { - if (!node->quiescent()) - { + for (const auto& [name, node] : state_->connections) { + if (!node->quiescent()) { return false; } } @@ -311,23 +282,19 @@ bool mysql_module_impl::ready_to_shut() const { bool mysql_module_impl::pre_shut() { auto shared = state_; shared->check_owner(); - if (!ready_to_shut()) - { + if (!ready_to_shut()) { return false; } shared->closed = true; - for (const auto& [name, node] : shared->connections) - { + for (const auto& [name, node] : shared->connections) { node->query_bridge.stop_accepting(); node->transaction_bridge.stop_accepting(); node->queries->stop_accepting(); node->transactions.stop_accepting(); } - for (const auto& [name, node] : shared->connections) - { + for (const auto& [name, node] : shared->connections) { if (!node->transactions.logically_drained() || !node->queries->logically_drained() || - !node->queries->retire_native()) - { + !node->queries->retire_native()) { return false; } } @@ -337,14 +304,11 @@ bool mysql_module_impl::pre_shut() { bool mysql_module_impl::shut() { auto shared = state_; shared->check_owner(); - if (!shared->closed) - { + if (!shared->closed) { return false; } - for (const auto& [name, node] : shared->connections) - { - if (!node->queries->native_retired()) - { + for (const auto& [name, node] : shared->connections) { + if (!node->queries->native_retired()) { return false; } } diff --git a/src/plugins/mysql/mysql_module.hpp b/src/plugins/mysql/mysql_module.hpp index 439fa9833..ab1e11f28 100644 --- a/src/plugins/mysql/mysql_module.hpp +++ b/src/plugins/mysql/mysql_module.hpp @@ -16,8 +16,7 @@ namespace ark { -struct mysql_options -{ +struct mysql_options { arknet::mysql::pool_options pool; arknet::mysql::query_options queries; std::size_t max_operations{64}; @@ -25,8 +24,7 @@ struct mysql_options std::size_t max_transactions{16}; }; -struct mysql_reply -{ +struct mysql_reply { arknet::mysql::query_result result; std::optional statement_close; std::exception_ptr statement_close_exception; @@ -36,8 +34,7 @@ struct mysql_reply } }; -enum class mysql_transaction_outcome -{ +enum class mysql_transaction_outcome { not_started, active, committed, @@ -45,8 +42,7 @@ enum class mysql_transaction_outcome unconfirmed }; -struct mysql_transaction_options -{ +struct mysql_transaction_options { std::chrono::milliseconds timeout{5000}; std::chrono::milliseconds cleanup_timeout{1000}; }; @@ -55,8 +51,7 @@ struct mysql_transaction_options // An unused transaction rolls back at its original deadline, never auto-commits. using mysql_transaction_id = std::uint64_t; -struct mysql_transaction_status -{ +struct mysql_transaction_status { mysql_transaction_outcome outcome{mysql_transaction_outcome::not_started}; std::optional rollback_code; bool rollback_outcome_unknown{}; @@ -66,8 +61,7 @@ struct mysql_transaction_status bool discard_requested{}; }; -struct mysql_transaction_reply -{ +struct mysql_transaction_reply { arknet::mysql::query_result result; std::optional statement_close; std::exception_ptr statement_close_exception; @@ -85,8 +79,7 @@ struct mysql_transaction_reply // groups: completion resumes on the shared business executor during update(). // Inputs and native results own storage. Local admission/C++ failures throw; // server/transport failures remain in the native result. -class mysql_module : public module -{ +class mysql_module : public module { public: virtual bool configure(std::string name, mysql_options options) = 0; virtual task query( diff --git a/src/plugins/mysql/mysql_plugin.cpp b/src/plugins/mysql/mysql_plugin.cpp index c767310d1..52b2c1118 100644 --- a/src/plugins/mysql/mysql_plugin.cpp +++ b/src/plugins/mysql/mysql_plugin.cpp @@ -34,15 +34,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void mysql_plugin::install() { - if (!register_module(detail::make_mysql_module(), module_update::enabled)) - { + if (!register_module(detail::make_mysql_module(), module_update::enabled)) { throw std::runtime_error("mysql module registration rejected"); } } void mysql_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("mysql module unregistration rejected"); } } diff --git a/src/plugins/mysql/mysql_plugin.hpp b/src/plugins/mysql/mysql_plugin.hpp index c480544ec..bd4c63ec9 100644 --- a/src/plugins/mysql/mysql_plugin.hpp +++ b/src/plugins/mysql/mysql_plugin.hpp @@ -27,8 +27,7 @@ namespace ark { -class mysql_plugin final : public plugin_base -{ +class mysql_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/plugins/net/http_client_module.hpp b/src/plugins/net/http_client_module.hpp index 4cdbdace0..f850e3acd 100644 --- a/src/plugins/net/http_client_module.hpp +++ b/src/plugins/net/http_client_module.hpp @@ -34,8 +34,7 @@ namespace ark { -class http_client_module : public module -{ +class http_client_module : public module { public: virtual std::future> async_request(arknet::http::verb method, const std::string& host, const uint16_t port, const std::string& url, const std::map* url_params = nullptr, diff --git a/src/plugins/net/http_client_module_impl.cpp b/src/plugins/net/http_client_module_impl.cpp index 2707707bb..1b4ef2a83 100644 --- a/src/plugins/net/http_client_module_impl.cpp +++ b/src/plugins/net/http_client_module_impl.cpp @@ -33,8 +33,7 @@ namespace ark { -class http_client_module_impl final : public module_base -{ +class http_client_module_impl final : public module_base { friend struct http_client_startup_test_access; public: @@ -112,16 +111,12 @@ using http_callback = std::function; std::string encode_parameter(const std::string& text) { constexpr char hex[] = "0123456789ABCDEF"; std::string encoded; - for (unsigned char character : text) - { + for (unsigned char character : text) { if ((character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') || (character >= '0' && character <= '9') || character == '-' || character == '_' || character == '.' || - character == '~') - { + character == '~') { encoded += static_cast(character); - } - else - { + } else { encoded += '%'; encoded += hex[character >> 4]; encoded += hex[character & 15]; @@ -134,12 +129,9 @@ arknet::http_request::request_type make_request(arknet::http::verb method, const const std::map* params, const std::vector* cookies, const std::string* body, const std::string* content_type) { std::string url = target.empty() ? "/" : target; - if (params) - { - for (const auto& [key, value] : *params) - { - if (url.back() != '?' && url.back() != '&') - { + if (params) { + for (const auto& [key, value] : *params) { + if (url.back() != '?' && url.back() != '&') { url += url.find('?') == std::string::npos ? '?' : '&'; } url += encode_parameter(key) + "=" + encode_parameter(value); @@ -147,37 +139,30 @@ arknet::http_request::request_type make_request(arknet::http::verb method, const } arknet::http_request::request_type request(method, url, 11); request.set(arknet::http::field::user_agent, "ARK"); - if (cookies) - { + if (cookies) { std::string cookie; - for (const auto& value : *cookies) - { - if (!cookie.empty()) - { + for (const auto& value : *cookies) { + if (!cookie.empty()) { cookie += "; "; } cookie += value; } request.set(arknet::http::field::cookie, cookie); } - if (body) - { + if (body) { request.body() = *body; } - if (content_type) - { + if (content_type) { request.set(arknet::http::field::content_type, *content_type); } return request; } http_result make_result(arknet::error_code error, arknet::http_request::response_type response) { - if (error) - { + if (error) { return {false, error.message()}; } - if (response.result() != arknet::http::status::ok) - { + if (response.result() != arknet::http::status::ok) { return {false, std::string(response.reason())}; } return {true, std::move(response.body())}; @@ -185,10 +170,8 @@ http_result make_result(arknet::error_code error, arknet::http_request::response } // namespace -struct http_client_module_impl::state : std::enable_shared_from_this -{ - struct callback - { +struct http_client_module_impl::state : std::enable_shared_from_this { + struct callback { http_callback function; http_result result; }; @@ -210,8 +193,7 @@ struct http_client_module_impl::state : std::enable_shared_from_this options.io_timeout = std::chrono::seconds(io_timeout); options.connect_timeout = std::chrono::seconds(connect_timeout); std::unique_lock lock(mutex); - if (stopped) - { + if (stopped) { lock.unlock(); completion(make_result(asio::error::operation_aborted, {})); return; @@ -236,14 +218,12 @@ struct http_client_module_impl::state : std::enable_shared_from_this } startup_cleanup_result cleanup_failed_startup() { - if (runtime.running_in_threads()) - { + if (runtime.running_in_threads()) { return startup_cleanup_result::unsafe; } { std::lock_guard lock(mutex); - if (!requests.empty() || !finished.empty() || active_callbacks != 0) - { + if (!requests.empty() || !finished.empty() || active_callbacks != 0) { return startup_cleanup_result::unsafe; } stopped = true; @@ -260,8 +240,7 @@ struct http_client_module_impl::state : std::enable_shared_from_this { std::lock_guard lock(mutex); stopped = true; - for (const auto& [id, operation] : requests) - { + for (const auto& [id, operation] : requests) { operation->cancel(); } } @@ -269,8 +248,7 @@ struct http_client_module_impl::state : std::enable_shared_from_this } }; -struct http_client_module_impl::startup_capsule -{ +struct http_client_module_impl::startup_capsule { explicit startup_capsule(std::shared_ptr resource) : resource(std::move(resource)) { } @@ -282,19 +260,16 @@ http_client_module_impl::http_client_module_impl(plugin_manager* manager) : state_(std::make_shared()) { // Keep complete state and its deleter alive even if construction or a later // install/startup hook fails. Enrollment precedes native worker acquisition. - if (manager) - { + if (manager) { auto capsule = std::make_shared(state_); if (!manager->prepare_startup_cleanup("NetHttpClient", "ark_net_plugin", capsule, [](void* context) { return static_cast(context)->resource->cleanup_failed_startup(); - })) - { + })) { throw std::runtime_error("Net HTTP startup cleanup enrollment rejected"); } startup_owner_ = capsule; } - if (!state_->runtime.start()) - { + if (!state_->runtime.start()) { throw arknet::system_error(arknet::get_last_error()); } } @@ -303,8 +278,7 @@ http_client_module_impl::~http_client_module_impl() { // Failed construction/registration must reach the failure runner without // closing native IO from candidate unwinding. Successful startup disarms // the capsule, restoring ordinary ownership and destructor cleanup. - if (startup_owner_.expired()) - { + if (startup_owner_.expired()) { pre_shut(); } } @@ -327,13 +301,11 @@ bool http_client_module_impl::update() { std::lock_guard lock(shared->mutex); remaining = shared->finished.size(); } - while (remaining--) - { + while (remaining--) { state::callback callback; { std::lock_guard lock(shared->mutex); - if (shared->finished.empty()) - { + if (shared->finished.empty()) { break; } callback = std::move(shared->finished.front()); @@ -341,8 +313,7 @@ bool http_client_module_impl::update() { ++shared->active_callbacks; } - struct delivery_guard - { + struct delivery_guard { state& shared; state::callback& callback; @@ -353,8 +324,7 @@ bool http_client_module_impl::update() { } } delivery{*shared, callback}; - if (callback.function) - { + if (callback.function) { callback.function(std::move(callback.result)); } } diff --git a/src/plugins/net/http_server.hpp b/src/plugins/net/http_server.hpp index d4ee97dee..5560718e9 100644 --- a/src/plugins/net/http_server.hpp +++ b/src/plugins/net/http_server.hpp @@ -6,8 +6,7 @@ namespace ark { -class http_server -{ +class http_server { private: std::shared_ptr server_; diff --git a/src/plugins/net/net.hpp b/src/plugins/net/net.hpp index 1a172b195..fc04618f9 100644 --- a/src/plugins/net/net.hpp +++ b/src/plugins/net/net.hpp @@ -36,8 +36,7 @@ using net_msg_functor = std::function; using net_msg_session_functor = std::function; using net_event_functor = std::function; -class net -{ +class net { public: virtual ~net() = default; @@ -65,8 +64,7 @@ class net // Configure before start_client/start_server. Existing sessions keep their capacity. bool set_initial_receive_buffer_size(size_t bytes) { - if (bytes == 0 || is_working()) - { + if (bytes == 0 || is_working()) { return false; } initial_receive_buffer_size_ = bytes; diff --git a/src/plugins/net/net_client_service.hpp b/src/plugins/net/net_client_service.hpp index 27398f41c..aba9c6cb0 100644 --- a/src/plugins/net/net_client_service.hpp +++ b/src/plugins/net/net_client_service.hpp @@ -30,11 +30,9 @@ namespace ark { -class connection_data -{ +class connection_data { public: - enum connect_state - { + enum connect_state { disconnect, connecting, connected, @@ -50,8 +48,7 @@ class connection_data int64_t last_active_time{0}; }; -class net_client_service : public noncopyable -{ +class net_client_service : public noncopyable { public: virtual ~net_client_service() = default; diff --git a/src/plugins/net/net_client_service_impl.cpp b/src/plugins/net/net_client_service_impl.cpp index 6539807d1..fb9d2f2d7 100644 --- a/src/plugins/net/net_client_service_impl.cpp +++ b/src/plugins/net/net_client_service_impl.cpp @@ -42,10 +42,8 @@ net_client_service_impl::~net_client_service_impl() { void net_client_service_impl::shutdown() { closed_ = true; callback_lifetime_.reset(); - for (const auto& [bus, connection] : real_connections_) - { - if (connection->net_client) - { + for (const auto& [bus, connection] : real_connections_) { + if (connection->net_client) { connection->net_client->shutdown(); connection->net_client.reset(); } @@ -61,8 +59,7 @@ void net_client_service_impl::shutdown() { bool net_client_service_impl::start_client( std::shared_ptr head, bus_id_t target_bus_id, const endpoint& endpoint) { - if (closed_) - { + if (closed_) { return false; } connection_data data; @@ -75,8 +72,7 @@ bool net_client_service_impl::start_client( } void net_client_service_impl::update() { - if (closed_) - { + if (closed_) { return; } process_add_connection(); @@ -84,12 +80,9 @@ void net_client_service_impl::update() { } bool net_client_service_impl::reg_msg_callback(msg_id_t msg_id, const net_msg_functor&& cb) { - if (net_msg_callbacks_.find(msg_id) != net_msg_callbacks_.end()) - { + if (net_msg_callbacks_.find(msg_id) != net_msg_callbacks_.end()) { return false; - } - else - { + } else { net_msg_callbacks_.insert(std::make_pair(msg_id, std::forward(cb))); return true; } @@ -106,39 +99,28 @@ bool net_client_service_impl::reg_net_event_callback(const net_event_functor&& c } void net_client_service_impl::process_update() { - for (auto iter : real_connections_) - { + for (auto iter : real_connections_) { auto connection_data = iter.second; - if (connection_data->net_client == nullptr) - { + if (connection_data->net_client == nullptr) { continue; } - switch (connection_data->net_state) - { - case connection_data::disconnect: - { + switch (connection_data->net_state) { + case connection_data::disconnect: { connection_data->net_state = connection_data::reconnect; connection_data->net_client->shutdown(); - } - break; - case connection_data::connecting: - { + } break; + case connection_data::connecting: { connection_data->net_client->update(); - } - break; - case connection_data::connected: - { + } break; + case connection_data::connected: { connection_data->net_client->update(); keep_alive(connection_data); - } - break; - case connection_data::reconnect: - { + } break; + case connection_data::reconnect: { // RECONNECT 30s/time - if ((connection_data->last_active_time + 30 * timespan::second_ms) >= plugin_manager_->get_now_time()) - { + if ((connection_data->last_active_time + 30 * timespan::second_ms) >= plugin_manager_->get_now_time()) { break; } @@ -149,16 +131,12 @@ void net_client_service_impl::process_update() { // based on protocol to create a new client bool ret = connection_data->net_client->start_client(connection_data->head, connection_data->server_bus_id, connection_data->remote_endpoint.get_ip(), connection_data->remote_endpoint.get_port()); - if (!ret) - { + if (!ret) { connection_data->net_state = connection_data::reconnect; - } - else - { + } else { connection_data->net_state = connection_data::connecting; } - } - break; + } break; default: break; } @@ -168,27 +146,20 @@ void net_client_service_impl::process_update() { std::shared_ptr net_client_service_impl::create_net(const proto_type proto) { const std::weak_ptr lifetime = callback_lifetime_; const net_msg_functor message_callback = [this, lifetime](const net_msg* message, conv_id_t session) { - if (const auto alive = lifetime.lock()) - { + if (const auto alive = lifetime.lock()) { on_net_msg(message, session); } }; const net_event_functor event_callback = [this, lifetime](const net_event* event) { - if (const auto alive = lifetime.lock()) - { + if (const auto alive = lifetime.lock()) { on_net_event(event); } }; - if (proto == proto_type::tcp) - { + if (proto == proto_type::tcp) { return std::make_shared(message_callback, event_callback); - } - else if (proto == proto_type::udp) - { + } else if (proto == proto_type::udp) { return std::make_shared(message_callback, event_callback); - } - else if (proto == proto_type::ws) - { + } else if (proto == proto_type::ws) { // will add web-socket client } @@ -199,11 +170,9 @@ std::shared_ptr net_client_service_impl::create_net(const proto_type proto) void net_client_service_impl::log_server_info() { log_server_info("This is a client, begin to print Server Info----------------------------------"); - for (auto iter : real_connections_) - { + for (auto iter : real_connections_) { auto connection_data = iter.second; - if (connection_data != nullptr) - { + if (connection_data != nullptr) { std::string info = ARK_FORMAT("TargetBusID={} State={} url={}", connection_data->server_bus_id, static_cast(connection_data->net_state), connection_data->remote_endpoint.to_string()); log_server_info(info); @@ -214,8 +183,7 @@ void net_client_service_impl::log_server_info() { } void net_client_service_impl::keep_alive(std::shared_ptr server_data_ptr) { - if ((server_data_ptr->last_active_time + 5000) > plugin_manager_->get_now_time()) - { + if ((server_data_ptr->last_active_time + 5000) > plugin_manager_->get_now_time()) { return; } @@ -234,12 +202,9 @@ bool net_client_service_impl::add_server_node(std::shared_ptr d bool net_client_service_impl::get_server_node(const std::string& hash_key, v_node& vnode) { auto iter = consistent_hashmap_.find(hash_key); - if (iter == consistent_hashmap_.end()) - { + if (iter == consistent_hashmap_.end()) { return false; - } - else - { + } else { vnode = iter->second; return true; } @@ -256,8 +221,7 @@ int net_client_service_impl::on_connect(const net_event* event) { auto connection_info = get_connection_info(event->get_bus_id()); - if (connection_info != nullptr) - { + if (connection_info != nullptr) { add_server_node(connection_info); connection_info->net_state = connection_data::connected; @@ -277,8 +241,7 @@ int net_client_service_impl::on_disconnect(const net_event* event) { std::shared_ptr connection_info = get_connection_info(event->get_bus_id()); - if (connection_info != nullptr) - { + if (connection_info != nullptr) { remove_server_node(connection_info); connection_info->net_state = connection_data::disconnect; connection_info->last_active_time = plugin_manager_->get_now_time(); @@ -290,13 +253,11 @@ int net_client_service_impl::on_disconnect(const net_event* event) { } void net_client_service_impl::process_add_connection() { - for (auto& iter : tmp_connections_) - { + for (auto& iter : tmp_connections_) { const connection_data& pending_connection = iter; std::shared_ptr target_connection_data = real_connections_.find_value(pending_connection.server_bus_id); - if (target_connection_data != nullptr) - { + if (target_connection_data != nullptr) { continue; } // add new server @@ -310,12 +271,9 @@ void net_client_service_impl::process_add_connection() { int ret = target_connection_data->net_client->start_client(target_connection_data->head, target_connection_data->server_bus_id, target_connection_data->remote_endpoint.get_ip(), target_connection_data->remote_endpoint.get_port()); - if (!ret) - { + if (!ret) { target_connection_data->net_state = connection_data::reconnect; - } - else - { + } else { target_connection_data->net_state = connection_data::connecting; } @@ -330,20 +288,16 @@ void net_client_service_impl::on_net_msg(const net_msg* msg, conv_id_t session_i auto it = net_msg_callbacks_.find(msg->get_msg_id()); - if (it != net_msg_callbacks_.end()) - { + if (it != net_msg_callbacks_.end()) { (it->second)(msg, session_id); - } - else - { + } else { ARK_LOG_ERROR("Invalid message, id = {}", msg->get_msg_id()); // TODO:forward to other server process } } void net_client_service_impl::on_net_event(const net_event* event) { - switch (event->get_type()) - { + switch (event->get_type()) { case net_event_type::connect: on_connect(event); break; @@ -354,8 +308,7 @@ void net_client_service_impl::on_net_event(const net_event* event) { break; } - for (const auto& it : net_event_callbacks_) - { + for (const auto& it : net_event_callbacks_) { (it)(event); } } @@ -366,8 +319,7 @@ std::shared_ptr net_client_service_impl::get_connection_info(bu std::shared_ptr net_client_service_impl::get_suitable_connect(const std::string& key) { static v_node vnode(0, null_str, 0, 0); - if (!get_server_node(key, vnode)) - { + if (!get_server_node(key, vnode)) { return nullptr; } @@ -384,8 +336,7 @@ void net_client_service_impl::remove_account_bus_id(const std::string& account) int net_client_service_impl::get_account_bus_id(const std::string& account) { auto iter = account_bus_map_.find(account); - if (iter == account_bus_map_.end()) - { + if (iter == account_bus_map_.end()) { return -1; } @@ -402,8 +353,7 @@ void net_client_service_impl::remove_actor_bus_id(const guid_t& actor) { int net_client_service_impl::get_actor_bus_id(const guid_t& actor) { auto iter = actor_bus_map_.find(actor); - if (iter == actor_bus_map_.end()) - { + if (iter == actor_bus_map_.end()) { return -1; } @@ -413,8 +363,7 @@ int net_client_service_impl::get_actor_bus_id(const guid_t& actor) { void net_client_service_impl::reg_to_server(const msg_header& head, bus_id_t target_bus_id) { auto bus_id = bus_module_->get_self_bus_id(); auto net_ptr = net_service_manager_->get_net_connection_bus(bus_id, target_bus_id); - if (!net_ptr) - { + if (!net_ptr) { return; } diff --git a/src/plugins/net/net_client_service_impl.hpp b/src/plugins/net/net_client_service_impl.hpp index 9b94a06a4..f000155cd 100644 --- a/src/plugins/net/net_client_service_impl.hpp +++ b/src/plugins/net/net_client_service_impl.hpp @@ -30,11 +30,9 @@ namespace ark { -class net_client_service_impl final : public net_client_service -{ +class net_client_service_impl final : public net_client_service { public: - enum constant_definitions - { + enum constant_definitions { default_weight = 255, }; diff --git a/src/plugins/net/net_define.hpp b/src/plugins/net/net_define.hpp index 3ed4d4e9b..bcf80e13e 100644 --- a/src/plugins/net/net_define.hpp +++ b/src/plugins/net/net_define.hpp @@ -56,8 +56,7 @@ static constexpr int ark_kcp_update_interval_time = 10; // 10 ms static constexpr int ark_kcp_resend_connect_msg_interval = 3000; // milliseconds static constexpr int ark_kcp_connect_timeout_time = 60000; // milliseconds -enum class net_event_type : uint8_t -{ +enum class net_event_type : uint8_t { none = 0, connect, disconnect, @@ -66,8 +65,7 @@ enum class net_event_type : uint8_t lag_notify, }; -enum class kcp_protocal_type : uint8_t -{ +enum class kcp_protocal_type : uint8_t { none = 0, syn, // connect ack, // connected @@ -75,8 +73,7 @@ enum class kcp_protocal_type : uint8_t msg, // msg }; -enum class kcp_connect_status : uint8_t -{ +enum class kcp_connect_status : uint8_t { status_none = 0, status_connecting, status_connected, diff --git a/src/plugins/net/net_event.hpp b/src/plugins/net/net_event.hpp index cc958aef2..36e27f7e7 100644 --- a/src/plugins/net/net_event.hpp +++ b/src/plugins/net/net_event.hpp @@ -27,8 +27,7 @@ namespace ark { -class net_event final -{ +class net_event final { net_event_type type_{net_event_type::none}; conv_id_t id_{0}; std::string ip_{}; diff --git a/src/plugins/net/net_msg.hpp b/src/plugins/net/net_msg.hpp index d58d2cf38..e169ad536 100644 --- a/src/plugins/net/net_msg.hpp +++ b/src/plugins/net/net_msg.hpp @@ -37,8 +37,7 @@ namespace ark { /** * @brief 协议头部接口类,通过它支持任意类型协议头部格式 */ -class msg_header -{ +class msg_header { public: virtual ~msg_header() { } @@ -105,8 +104,7 @@ class msg_header }; // CS通信默认包头 -class s_msg_header : public msg_header -{ +class s_msg_header : public msg_header { public: // 返回包头大小 virtual uint32_t header_length() const override { @@ -162,8 +160,7 @@ class s_msg_header : public msg_header private: #pragma pack(push, 1) - struct header_impl - { + struct header_impl { msg_id_t id{0}; // Msg id uint32_t length{0}; // Msg length(without header length) uint8_t compress{0}; // Msg data compressed @@ -176,8 +173,7 @@ class s_msg_header : public msg_header }; // SS通信默认包头 -class ss_msg_header : public msg_header -{ +class ss_msg_header : public msg_header { public: // 返回包头大小 virtual uint32_t header_length() const override { @@ -255,8 +251,7 @@ class ss_msg_header : public msg_header private: #pragma pack(push, 1) - struct header_impl - { + struct header_impl { msg_id_t id{0}; // Msg id uint32_t length{0}; // Msg length(without header length) uint8_t compress{0}; // Msg data compressed @@ -271,8 +266,7 @@ class ss_msg_header : public msg_header header_impl header_; }; -class net_msg final : private noncopyable -{ +class net_msg final : private noncopyable { protected: net_msg(msg_header* head) : head_(head) { @@ -291,21 +285,18 @@ class net_msg final : private noncopyable // Consumes head, including when allocation fails. static net_msg* alloc_msg(msg_header* head) { std::unique_ptr owner(head); - if (!owner) - { + if (!owner) { return nullptr; } - try - { + try { auto* msg = new (std::nothrow) net_msg(head); - if (msg != nullptr) - { + if (msg != nullptr) { owner.release(); } return msg; + } catch (const std::bad_alloc&) { + return nullptr; } - catch (const std::bad_alloc&) - { return nullptr; } } static void release(net_msg*& msg) { @@ -314,23 +305,18 @@ class net_msg final : private noncopyable } void copy_data(const char* data, const uint32_t len) { - if (data == nullptr && len != 0) - { + if (data == nullptr && len != 0) { throw std::invalid_argument("net_msg body is null"); } - if (len > capacity_) - { + if (len > capacity_) { auto replacement = allocate_data(len); std::memcpy(replacement.get(), data, len); head_->set_message_length(len); delete[] msg_data_; msg_data_ = replacement.release(); capacity_ = len; - } - else - { - if (len != 0) - { + } else { + if (len != 0) { std::memmove(msg_data_, data, len); } head_->set_message_length(len); @@ -338,27 +324,22 @@ class net_msg final : private noncopyable } void copy_from(net_msg* msg) { - if (msg == nullptr) - { + if (msg == nullptr) { throw std::invalid_argument("net_msg source is null"); } - if (msg == this) - { + if (msg == this) { return; } const auto length = msg->get_msg_length(); - if (length > msg->capacity_) - { + if (length > msg->capacity_) { throw std::length_error("net_msg source body exceeds its allocation"); } std::unique_ptr head(msg->head_->clone()); - if (!head) - { + if (!head) { throw std::bad_alloc{}; } auto data = allocate_data(length); - if (length != 0) - { + if (length != 0) { std::memcpy(data.get(), msg->msg_data_, length); } delete head_; @@ -397,21 +378,17 @@ class net_msg final : private noncopyable } void set_msg_length(uint32_t value) { - if (value > capacity_) - { + if (value > capacity_) { auto data = allocate_data(value); const auto preserved = std::min(get_msg_length(), capacity_); - if (preserved != 0) - { + if (preserved != 0) { std::memcpy(data.get(), msg_data_, preserved); } head_->set_message_length(value); delete[] msg_data_; msg_data_ = data.release(); capacity_ = value; - } - else - { + } else { head_->set_message_length(value); } } diff --git a/src/plugins/net/net_plugin.cpp b/src/plugins/net/net_plugin.cpp index 744885232..203794286 100644 --- a/src/plugins/net/net_plugin.cpp +++ b/src/plugins/net/net_plugin.cpp @@ -35,23 +35,19 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void net_plugin::install() { - if (!register_module(detail::make_http_client_module(get_plugin_manager()), module_update::enabled)) - { + if (!register_module(detail::make_http_client_module(get_plugin_manager()), module_update::enabled)) { throw std::runtime_error("net HTTP client module registration rejected"); } - if (!register_module(detail::make_net_service_manager_module(), module_update::enabled)) - { + if (!register_module(detail::make_net_service_manager_module(), module_update::enabled)) { throw std::runtime_error("net service manager module registration rejected"); } } void net_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("net service manager module unregistration rejected"); } - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("net HTTP client module unregistration rejected"); } } diff --git a/src/plugins/net/net_plugin.hpp b/src/plugins/net/net_plugin.hpp index 156ac8cb2..ce0c8d4eb 100755 --- a/src/plugins/net/net_plugin.hpp +++ b/src/plugins/net/net_plugin.hpp @@ -27,8 +27,7 @@ namespace ark { -class net_plugin final : public plugin_base -{ +class net_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/plugins/net/net_server_service.hpp b/src/plugins/net/net_server_service.hpp index 9fbe83082..fefc59bdc 100644 --- a/src/plugins/net/net_server_service.hpp +++ b/src/plugins/net/net_server_service.hpp @@ -50,8 +50,7 @@ namespace ark { // std::string account_{}; //}; -class net_server_service -{ +class net_server_service { public: virtual ~net_server_service() = default; diff --git a/src/plugins/net/net_server_service_impl.cpp b/src/plugins/net/net_server_service_impl.cpp index a9a63e4b9..6aa03a2fa 100644 --- a/src/plugins/net/net_server_service_impl.cpp +++ b/src/plugins/net/net_server_service_impl.cpp @@ -38,8 +38,7 @@ net_server_service_impl::~net_server_service_impl() { void net_server_service_impl::shutdown() { closed_ = true; callback_lifetime_.reset(); - if (network_) - { + if (network_) { network_->shutdown(); network_.reset(); } @@ -53,45 +52,35 @@ void net_server_service_impl::shutdown() { bool net_server_service_impl::start(std::shared_ptr head, bus_id_t bus_id, const endpoint& ep, uint8_t thread_count, uint32_t max_connection, const size_t silent_timeout) { - if (closed_) - { + if (closed_) { return false; } const std::weak_ptr lifetime = callback_lifetime_; const net_msg_functor message_callback = [this, lifetime](const net_msg* message, conv_id_t session) { - if (const auto alive = lifetime.lock()) - { + if (const auto alive = lifetime.lock()) { on_net_msg(message, session); } }; const net_event_functor event_callback = [this, lifetime](const net_event* event) { - if (const auto alive = lifetime.lock()) - { + if (const auto alive = lifetime.lock()) { on_net_event(event); } }; bool ret = false; - if (ep.proto() == proto_type::tcp) - { + if (ep.proto() == proto_type::tcp) { network_ = std::make_shared(message_callback, event_callback); ret = network_->start_server( head, bus_id, ep.get_ip(), ep.get_port(), thread_count, max_connection, silent_timeout); //AFINetServerService::RegMsgCallback( // ark::protobuf::e_ss_msg_id_server_report, this, &AFCNetServerService::OnClientRegister); - } - else if (ep.proto() == proto_type::udp) - { + } else if (ep.proto() == proto_type::udp) { network_ = std::make_shared(message_callback, event_callback); ret = network_->start_server( head, bus_id, ep.get_ip(), ep.get_port(), thread_count, max_connection, silent_timeout); - } - else if (ep.proto() == proto_type::ws) - { + } else if (ep.proto() == proto_type::ws) { // will add websocket server - } - else - { + } else { // other protocols will be supported return false; } @@ -100,8 +89,7 @@ bool net_server_service_impl::start(std::shared_ptr head, bus_ } bool net_server_service_impl::update() { - if (closed_) - { + if (closed_) { return true; } ARK_ASSERT_RET_VAL(network_ != nullptr, false); @@ -117,12 +105,9 @@ std::shared_ptr net_server_service_impl::get_net() { } bool net_server_service_impl::reg_msg_callback(msg_id_t msg_id, net_msg_functor&& cb) { - if (net_msg_callbacks_.find(msg_id) != net_msg_callbacks_.end()) - { + if (net_msg_callbacks_.find(msg_id) != net_msg_callbacks_.end()) { return false; - } - else - { + } else { net_msg_callbacks_.insert(std::make_pair(msg_id, std::forward(cb))); return true; } @@ -144,8 +129,7 @@ bool net_server_service_impl::reg_reg_server_call_back(net_msg_session_functor&& } void net_server_service_impl::set_timeout_interval(const int32_t interval) { - if (interval <= 0) - { + if (interval <= 0) { return; } @@ -156,8 +140,7 @@ void net_server_service_impl::on_net_msg(const net_msg* msg, conv_id_t session_i ARK_LOG_DEBUG("[msg][recv] msg id = {} session id = {}", msg->get_msg_id(), session_id); auto msg_id = msg->get_msg_id(); - if (msg_id == ark::protobuf::e_ss_msg_id_reg_to_server) - { + if (msg_id == ark::protobuf::e_ss_msg_id_reg_to_server) { reg_server_call_back_(msg, session_id); net_service_manager_->remove_net_connection_bus(msg->get_src_bus()); @@ -166,25 +149,19 @@ void net_server_service_impl::on_net_msg(const net_msg* msg, conv_id_t session_i remove_connection(msg->get_src_bus()); add_connection(msg->get_src_bus(), session_id); return; - } - else if (msg_id == ark::protobuf::e_ss_msg_id_heart_beat) - { + } else if (msg_id == ark::protobuf::e_ss_msg_id_heart_beat) { update_connection(msg->get_src_bus()); return; } - if (msg->get_src_bus() == 0) - { + if (msg->get_src_bus() == 0) { update_client_connection(session_id); } auto it = net_msg_callbacks_.find(msg_id); - if (it != net_msg_callbacks_.end()) - { + if (it != net_msg_callbacks_.end()) { (it->second)(msg, session_id); - } - else - { + } else { // TODO:forward to other server process ARK_LOG_ERROR("Invalid message, id = {}", msg_id); @@ -197,8 +174,7 @@ void net_server_service_impl::on_net_msg(const net_msg* msg, conv_id_t session_i } void net_server_service_impl::on_net_event(const net_event* event) { - switch (event->get_type()) - { + switch (event->get_type()) { case net_event_type::connect: ARK_LOG_INFO("Connected server = {} succenssfully, ip = {}, session_id = {}", bus_addr(event->get_bus_id()).to_string(), event->get_ip(), event->get_id()); @@ -215,8 +191,7 @@ void net_server_service_impl::on_net_event(const net_event* event) { break; } - for (const auto& it : net_event_callbacks_) - { + for (const auto& it : net_event_callbacks_) { (it)(event); } } @@ -225,8 +200,7 @@ void net_server_service_impl::on_disconnect_net_event(const net_event* event) { ARK_LOG_INFO("TimeOut Disconnected server = {} succenssfully, ip = {}, session_id = {}", bus_addr(event->get_bus_id()).to_string(), event->get_ip(), event->get_id()); - for (const auto& it : net_event_callbacks_) - { + for (const auto& it : net_event_callbacks_) { (it)(event); } } @@ -272,11 +246,9 @@ void net_server_service_impl::process_client_connection() { ///check connection auto now = date_time::get_now_time(); - for (auto& iter : client_connection_list_) - { + for (auto& iter : client_connection_list_) { auto& connection = iter.second; - if (connection.last_active_time + client_timeout_interval_ < now) - { + if (connection.last_active_time + client_timeout_interval_ < now) { /// close session close_list.push_back(iter.first); network_->close_session(iter.first); @@ -289,8 +261,7 @@ void net_server_service_impl::process_client_connection() { } } - for (auto iter : close_list) - { + for (auto iter : close_list) { remove_client_connection(iter); } } @@ -309,8 +280,7 @@ void net_server_service_impl::add_connection(bus_id_t bus_id, conv_id_t session_ void net_server_service_impl::update_connection(bus_id_t bus_id) { auto connection = connection_list_.find_value(bus_id); - if (!connection) - { + if (!connection) { return; } @@ -324,14 +294,11 @@ void net_server_service_impl::remove_connection(bus_id_t bus_id) { void net_server_service_impl::update_client_connection(conv_id_t session_id) { auto iter = client_connection_list_.find(session_id); - if (iter == client_connection_list_.end()) - { + if (iter == client_connection_list_.end()) { auto connection = ark::connection(0, session_id, date_time::get_now_time(), ark::connection::connect_state::connected); client_connection_list_.insert(std::make_pair(session_id, connection)); - } - else - { + } else { iter->second.last_active_time = date_time::get_now_time(); } } diff --git a/src/plugins/net/net_server_service_impl.hpp b/src/plugins/net/net_server_service_impl.hpp index 9d01f38c0..03e7da02e 100644 --- a/src/plugins/net/net_server_service_impl.hpp +++ b/src/plugins/net/net_server_service_impl.hpp @@ -28,11 +28,9 @@ namespace ark { -class connection -{ +class connection { public: - enum class connect_state : uint8_t - { + enum class connect_state : uint8_t { disconnect = 0, connecting, connected, @@ -54,8 +52,7 @@ class connection connect_state state{connect_state::disconnect}; }; -class net_server_service_impl final : public net_server_service -{ +class net_server_service_impl final : public net_server_service { public: explicit net_server_service_impl(plugin_manager* p); @@ -93,8 +90,7 @@ class net_server_service_impl final : public net_server_service inline void remove_client_connection(conv_id_t session_id) { auto iter = client_connection_list_.find(session_id); - if (iter == client_connection_list_.end()) - { + if (iter == client_connection_list_.end()) { return; } diff --git a/src/plugins/net/net_service_manager_module.hpp b/src/plugins/net/net_service_manager_module.hpp index 49136f898..73c9849d5 100644 --- a/src/plugins/net/net_service_manager_module.hpp +++ b/src/plugins/net/net_service_manager_module.hpp @@ -26,8 +26,7 @@ namespace ark { -class net_service_manager_module : public module -{ +class net_service_manager_module : public module { public: // server-side net service virtual bool create_server(const size_t silent_timeout = std::chrono::milliseconds(ark_net_heart_time).count(), diff --git a/src/plugins/net/net_service_manager_module_impl.cpp b/src/plugins/net/net_service_manager_module_impl.cpp index b10e0f6e9..cff9cf7c1 100644 --- a/src/plugins/net/net_service_manager_module_impl.cpp +++ b/src/plugins/net/net_service_manager_module_impl.cpp @@ -37,8 +37,7 @@ namespace ark { -class net_service_manager_module_impl final : public module_base -{ +class net_service_manager_module_impl final : public module_base { public: bool init() override; bool post_init() override; @@ -85,8 +84,7 @@ class net_service_manager_module_impl final : public module_base service; bool published{}; }; @@ -135,16 +133,13 @@ void net_service_manager_module_impl::start_configured_clients() { std::vector types; bus_module_->get_target_bus_relations(types); std::set queued; - for (const auto type : types) - { + for (const auto type : types) { std::vector processes; bus_module_->get_other_proc(type, processes); - for (const auto* process : processes) - { + for (const auto* process : processes) { bus_addr target(process->bus_id); if (target.bus_id == self.bus_id || target.channel_id != self.channel_id || - target.zone_id != self.zone_id || !queued.insert(target.bus_id).second) - { + target.zone_id != self.zone_id || !queued.insert(target.bus_id).second) { continue; } const auto& ep = process->intranet_ep; @@ -152,15 +147,13 @@ void net_service_manager_module_impl::start_configured_clients() { const auto address = asio::ip::make_address(ep.get_ip(), address_error); if ((ep.proto() != proto_type::tcp && ep.proto() != proto_type::udp) || ep.get_ip().empty() || ep.get_ip() == "*" || (!address_error && address.is_unspecified()) || ep.get_port() == 0 || - !ep.get_path().empty()) - { + !ep.get_path().empty()) { throw std::runtime_error( "static Bus target " + target.to_string() + ": intranet_endpoint requires a dialable TCP/UDP host and nonzero port without a path; " "wildcard bind addresses cannot be advertised"); } - if (!create_client_service(target, ep.proto(), ep.get_ip(), ep.get_port())) - { + if (!create_client_service(target, ep.proto(), ep.get_ip(), ep.get_port())) { throw std::runtime_error("could not queue static Bus target " + target.to_string()); } } @@ -245,27 +238,21 @@ void net_service_manager_module_impl::health_check(uint64_t timer_id, const guid } bool net_service_manager_module_impl::update() { - for (const auto& [bus, entry] : server_services_) - { - if (entry.published) - { + for (const auto& [bus, entry] : server_services_) { + if (entry.published) { entry.service->update(); } } - for (const auto& [bus, entry] : intra_services_) - { - if (entry.published) - { + for (const auto& [bus, entry] : intra_services_) { + if (entry.published) { entry.service->update(); } } - for (auto iter : client_services_) - { + for (auto iter : client_services_) { auto data_ptr = iter.second; - if (data_ptr != nullptr) - { + if (data_ptr != nullptr) { data_ptr->update(); } } @@ -276,20 +263,16 @@ bool net_service_manager_module_impl::update() { bool net_service_manager_module_impl::pre_shut() { // Retire callbacks while their consumers and resource providers are still alive. const auto timer_id = std::exchange(health_timer_id_, 0); - if (timer_id != 0 && timer_module_) - { + if (timer_id != 0 && timer_module_) { timer_module_->remove_timer(timer_id); } - for (const auto& [bus, entry] : server_services_) - { + for (const auto& [bus, entry] : server_services_) { entry.service->shutdown(); } - for (const auto& [bus, entry] : intra_services_) - { + for (const auto& [bus, entry] : intra_services_) { entry.service->shutdown(); } - for (const auto& [type, service] : client_services_) - { + for (const auto& [type, service] : client_services_) { service->shutdown(); } net_bus_relations_.clear(); @@ -315,24 +298,21 @@ bool net_service_manager_module_impl::create_server( auto func = [this, &self_proc, silent_timeout]( const endpoint& ep, shared_ptr header, server_service& server_service) { const auto bus_id = bus_module_->get_self_bus_id(); - if (server_service.contains(bus_id)) - { + if (server_service.contains(bus_id)) { return false; } auto server_ptr = std::make_shared(get_plugin_manager()); auto server_interface_ptr = static_pointer_cast(server_ptr); server_interface_ptr->reg_reg_server_call_back(this, &net_service_manager_module_impl::on_reg_server_call_back); const auto [entry, inserted] = server_service.emplace(bus_id, listener{server_ptr}); - if (!inserted) - { + if (!inserted) { return false; } // start itself may throw after its native workers start. Keep the entire // unpublished receiver and transport in this installed module on unwind. const bool ret = server_ptr->start( header, self_proc.bus_id, ep, self_proc.thread_num, self_proc.max_connection, silent_timeout); - if (ret) - { + if (ret) { entry->second.published = true; ARK_LOG_INFO("Start net server successful, url = {}", ep.to_string()); return true; @@ -346,12 +326,10 @@ bool net_service_manager_module_impl::create_server( return false; }; - if (!self_proc.server_ep.get_ip().empty()) - { + if (!self_proc.server_ep.get_ip().empty()) { // create inter server auto result = func(self_proc.server_ep, cs_req_head, server_services_); - if (!result) - { + if (!result) { ARK_LOG_ERROR("Cannot start inter server net, url = {}", self_proc.server_ep.to_string()); // promise.SetValue(std::make_pair(false, std::string())); // return promise.GetFuture(); @@ -360,21 +338,16 @@ bool net_service_manager_module_impl::create_server( } auto& intra_ep = self_proc.intranet_ep; - if (intra_ep.get_port() == self_proc.server_ep.get_port()) - { + if (intra_ep.get_port() == self_proc.server_ep.get_port()) { ARK_LOG_ERROR("Cannot start intra server net, has the same port with server, url = {}", intra_ep.to_string()); // promise.SetValue(std::make_pair(false, std::string())); // return promise.GetFuture(); return false; - } - else - { - if (!intra_ep.get_ip().empty()) - { + } else { + if (!intra_ep.get_ip().empty()) { // create intra server auto result = func(intra_ep, ss_req_head, intra_services_); - if (!result) - { + if (!result) { ARK_LOG_ERROR("Cannot start intra server net, url = {}", intra_ep.to_string()); // promise.SetValue(std::make_pair(false, std::string())); // return promise.GetFuture(); @@ -399,8 +372,7 @@ std::shared_ptr net_service_manager_module_impl::get_intra_n } bool net_service_manager_module_impl::add_net_connection_bus(bus_id_t target_bus_id, std::shared_ptr net_ptr) { - if (/*target_bus_id <= 0 || */ net_ptr == nullptr) - { + if (/*target_bus_id <= 0 || */ net_ptr == nullptr) { return false; } @@ -480,8 +452,7 @@ bool net_service_manager_module_impl::create_client_service(const bus_addr& bus_ const std::string& ip, uint16_t port, std::shared_ptr head) { app_type app_type = static_cast(bus_addr.app_type); auto client_ptr = client_services_.find_value(app_type); - if (client_ptr == nullptr) - { + if (client_ptr == nullptr) { client_ptr = std::make_shared(get_plugin_manager()); client_services_.insert(app_type, client_ptr); } @@ -492,8 +463,7 @@ bool net_service_manager_module_impl::create_client_service(const bus_addr& bus_ target_ep.set_port(port); bool ret = client_ptr->start_client(head, bus_addr.bus_id, target_ep); - if (!ret) - { + if (!ret) { ARK_LOG_ERROR("start net client failed, self_bus_id={} target_url={}", bus_module_->get_self_bus_name(), target_ep.to_string()); return ret; @@ -506,8 +476,7 @@ bool net_service_manager_module_impl::create_client_service(const bus_addr& bus_ conv_id_t net_service_manager_module_impl::get_session_id(bus_id_t target_bus_id) { auto iter = bus_session_list_.find(target_bus_id); - if (iter == bus_session_list_.end()) - { + if (iter == bus_session_list_.end()) { return 0; } @@ -515,10 +484,8 @@ conv_id_t net_service_manager_module_impl::get_session_id(bus_id_t target_bus_id } bool net_service_manager_module_impl::remove_session_id(conv_id_t session_id) { - for (auto& iter : bus_session_list_) - { - if (iter.second == session_id) - { + for (auto& iter : bus_session_list_) { + if (iter.second == session_id) { bus_session_list_.erase(iter.first); break; } @@ -534,8 +501,7 @@ bool net_service_manager_module_impl::check_connected_target_server(const bus_ad std::shared_ptr net_service_manager_module_impl::get_target_client_connection( const bus_addr& bus_addr) { auto client_service = client_services_.find_value(static_cast(bus_addr.app_type)); - if (client_service == nullptr) - { + if (client_service == nullptr) { return nullptr; } @@ -545,12 +511,9 @@ std::shared_ptr net_service_manager_module_impl::get_target_cli void net_service_manager_module_impl::on_reg_server_call_back(const net_msg* msg, conv_id_t session_id) { // msg->GetSrcBus() means client msg bus id auto iter = bus_session_list_.find(msg->get_src_bus()); - if (iter == bus_session_list_.end()) - { + if (iter == bus_session_list_.end()) { bus_session_list_.insert(std::make_pair(msg->get_src_bus(), session_id)); - } - else - { + } else { iter->second = session_id; } } diff --git a/src/plugins/net/net_session.hpp b/src/plugins/net/net_session.hpp index e98965f32..c4f3b6ce5 100644 --- a/src/plugins/net/net_session.hpp +++ b/src/plugins/net/net_session.hpp @@ -42,8 +42,7 @@ namespace ark { template -class net_session : public noncopyable -{ +class net_session : public noncopyable { public: explicit net_session(std::shared_ptr req_head, conv_id_t session_id, const session_ptr_type session_ptr = nullptr, @@ -60,34 +59,28 @@ class net_session : public noncopyable void release_queue_data() { net_event* event = nullptr; - while (pop_net_event(event)) - { + while (pop_net_event(event)) { net_event::release(event); } net_msg* msg = nullptr; - while (pop_net_msg(msg)) - { + while (pop_net_msg(msg)) { net_msg::release(msg); } } const session_ptr_type get_session() { - if constexpr (is_session) - { + if constexpr (is_session) { ARK_ASSERT_RET_VAL(session_ != nullptr, nullptr); return session_; - } - else - { + } else { ARK_ASSERT_NO_EFFECT(0); return nullptr; } } int add_buffer(const char* data, size_t len) { - if (!buffer_.write(data, len)) - { + if (!buffer_.write(data, len)) { return -1; } const auto length = std::min(buffer_.get_length(), static_cast(std::numeric_limits::max())); @@ -99,14 +92,12 @@ class net_session : public noncopyable } size_t remove_buffer(size_t len) { - if (len > buffer_.get_length()) - { + if (len > buffer_.get_length()) { return 0; } buffer_.remove_data(len); - if (len > 0) - { + if (len > 0) { pending_header_.reset(); } return buffer_.get_length(); @@ -163,55 +154,45 @@ class net_session : public noncopyable bool parse_buffer_to_msg() { size_t pos = 0; const size_t head_len = get_head_len(); - if (head_len == 0) - { + if (head_len == 0) { return false; } - while (get_buffer_len() - pos >= head_len) - { + while (get_buffer_len() - pos >= head_len) { auto msg_head = std::move(pending_header_); - if (msg_head == nullptr) - { + if (msg_head == nullptr) { msg_head.reset(req_header_->create()); - if (!msg_head) - { + if (!msg_head) { return false; } msg_head->parse_from_array(get_buffer() + pos); } const size_t msg_len = msg_head->message_length(); - if (!req_header_->accepts_body_size(msg_len)) - { + if (!req_header_->accepts_body_size(msg_len)) { return false; } - if (get_buffer_len() - pos - head_len < msg_len) - { + if (get_buffer_len() - pos - head_len < msg_len) { pending_header_ = std::move(msg_head); break; } net_msg* msg = net_msg::alloc_msg(msg_head.release()); - if (msg == nullptr) - { + if (msg == nullptr) { return false; } pos += head_len; - if (msg_len > 0) - { + if (msg_len > 0) { msg->copy_data(get_buffer() + pos, msg_len); pos += msg_len; } - if (!add_net_msg(msg)) - { + if (!add_net_msg(msg)) { net_msg::release(msg); return false; } } // remove [0, pos] buffers - if (pos > 0) - { + if (pos > 0) { remove_buffer(pos); } return true; diff --git a/src/plugins/net/rudp_client.cpp b/src/plugins/net/rudp_client.cpp index 749cb3eb3..0c7ad4884 100644 --- a/src/plugins/net/rudp_client.cpp +++ b/src/plugins/net/rudp_client.cpp @@ -32,8 +32,7 @@ rudp_client::~rudp_client() { bool rudp_client::start_client( std::shared_ptr head, bus_id_t dst_bus_id, const std::string& host, uint16_t port) { - if (!head) - { + if (!head) { return false; } shutdown(); @@ -51,20 +50,16 @@ bool rudp_client::start_client( ->bind_connect([weak, head, initial_buffer_size] { const auto ec = arknet::get_last_error(); auto self = weak.lock(); - if (!self) - { + if (!self) { return; } - if (ec) - { + if (ec) { ARK_LOG_INFO("Client(RUDP) connect server failed, error={} errno={}, server_addr={} " "server_port={},local_addr={} local_port={}", ec.message(), ec.value(), self->client_->remote_address(), self->client_->remote_port(), self->client_->local_address(), self->client_->local_port()); return; - } - else - { + } else { ARK_LOG_INFO( "Client(RUDP) connect server success, server_addr={} server_port={} local_addr={} local_port={}", self->client_->remote_address(), self->client_->remote_port(), self->client_->local_address(), @@ -84,8 +79,7 @@ bool rudp_client::start_client( self->session_ = std::make_shared(head, cur_session_id, nullptr, initial_buffer_size); self->sessions_.push_back(self->session_); - if (!self->session_->add_net_event(net_connect_event)) - { + if (!self->session_->add_net_event(net_connect_event)) { net_event::release(net_connect_event); } } @@ -93,8 +87,7 @@ bool rudp_client::start_client( .bind_disconnect([weak] { const auto ec = arknet::get_last_error(); auto self = weak.lock(); - if (!self) - { + if (!self) { return; } ARK_LOG_INFO("Client(RUDP) disconnect server, error={} errno={} remote_addr={} remote_port={} " @@ -105,8 +98,7 @@ bool rudp_client::start_client( auto session_id = self->client_->get_user_data(); scope_w_lock guard(self->rw_lock_); - if (!self->session_ || self->session_->get_session_id() != session_id || self->session_->need_remove()) - { + if (!self->session_ || self->session_->get_session_id() != session_id || self->session_->need_remove()) { return; } net_event* net_disconnect_event = net_event::alloc_event(); @@ -114,16 +106,14 @@ bool rudp_client::start_client( net_disconnect_event->set_type(net_event_type::disconnect); net_disconnect_event->set_bus_id(self->dst_bus_id_); net_disconnect_event->set_ip(self->client_->remote_address()); - if (!self->session_->add_net_event(net_disconnect_event)) - { + if (!self->session_->add_net_event(net_disconnect_event)) { net_event::release(net_disconnect_event); } self->session_->need_remove(true); }) .bind_recv([weak](std::string_view s) { auto self = weak.lock(); - if (!self) - { + if (!self) { return; } rdp_client_session_ptr session; @@ -131,10 +121,8 @@ bool rudp_client::start_client( scope_r_lock guard(self->rw_lock_); session = self->session_; } - if (session && !session->need_remove()) - { - if (session->add_buffer(s.data(), s.length()) < 0 || !session->parse_buffer_to_msg()) - { + if (session && !session->need_remove()) { + if (session->add_buffer(s.data(), s.length()) < 0 || !session->parse_buffer_to_msg()) { self->client_->stop(); } } @@ -151,17 +139,14 @@ void rudp_client::update() { scope_r_lock guard(rw_lock_); sessions.assign(sessions_.begin(), sessions_.end()); } - for (const auto& session : sessions) - { + for (const auto& session : sessions) { const auto disconnected = session->need_remove(); update_net_event(session); const auto drained = update_net_msg(session); - if (disconnected && drained) - { + if (disconnected && drained) { scope_w_lock guard(rw_lock_); sessions_.erase(std::remove(sessions_.begin(), sessions_.end(), session), sessions_.end()); - if (session_ == session) - { + if (session_ == session) { session_.reset(); } } @@ -170,8 +155,7 @@ void rudp_client::update() { void rudp_client::update_net_event(const rdp_client_session_ptr& session) { net_event* event{nullptr}; - while (session->pop_net_event(event)) - { + while (session->pop_net_event(event)) { net_event_cb_(event); net_event::release(event); } @@ -180,14 +164,12 @@ void rudp_client::update_net_event(const rdp_client_session_ptr& session) { bool rudp_client::update_net_msg(const rdp_client_session_ptr& session) { net_msg* msg{nullptr}; int msg_count = 0; - while (session->pop_net_msg(msg)) - { + while (session->pop_net_msg(msg)) { net_msg_cb_(msg, session->get_session_id()); net_msg::release(msg); ++msg_count; - if (msg_count >= ark_process_net_msg_count_once) - { + if (msg_count >= ark_process_net_msg_count_once) { return false; } } @@ -195,48 +177,41 @@ bool rudp_client::update_net_msg(const rdp_client_session_ptr& session) { } void rudp_client::shutdown() { - if (client_) - { + if (client_) { client_->stop(); } set_working(false); } bool rudp_client::send_msg(msg_header* head, const char* msg_data, conv_id_t session_id) { - if (!head || !msg_data || !head->accepts_body_size(head->message_length()) || !client_) - { + if (!head || !msg_data || !head->accepts_body_size(head->message_length()) || !client_) { return false; } std::string buffer; head->serialize_to_string(buffer); const auto message_length = head->message_length(); - if (buffer.empty() || !head->accepts_body_size(message_length)) - { + if (buffer.empty() || !head->accepts_body_size(message_length)) { return false; } buffer.append(msg_data, message_length); scope_r_lock guard(rw_lock_); const auto session = session_; - if (!session || session->need_remove() || (session_id != 0 && session_id != session->get_session_id())) - { + if (!session || session->need_remove() || (session_id != 0 && session_id != session->get_session_id())) { return false; } return client_->async_send(std::move(buffer), [weak = std::weak_ptr(client_), id = session->get_session_id()](arknet::error_code ec, size_t) { - if (!ec) - { + if (!ec) { return; } ARK_LOG_ERROR("Client(RUDP) send failed, session={} error={} errno={}", id, ec.message(), ec.value()); - if (auto client = weak.lock(); client && client->is_started()) - { + if (auto client = weak.lock(); client && client->is_started()) { // Check the session on its executor so an old send cannot stop a reconnected client. client->post([weak, id] { - if (auto current = weak.lock(); current && current->get_user_data() == id) - { + if (auto current = weak.lock(); current && current->get_user_data() == id) { current->stop(); } }); @@ -245,13 +220,12 @@ bool rudp_client::send_msg(msg_header* head, const char* msg_data, conv_id_t ses } void rudp_client::close_session(conv_id_t session_id) { - if (!client_) - { + if (!client_) { return; } client_->post([weak = std::weak_ptr(client_), session_id] { - if (auto client = weak.lock(); client && (session_id == 0 || client->get_user_data() == session_id)) - { + if (auto client = weak.lock(); + client && (session_id == 0 || client->get_user_data() == session_id)) { client->stop(); } }); diff --git a/src/plugins/net/rudp_server.cpp b/src/plugins/net/rudp_server.cpp index d19e4bf8f..71c319add 100644 --- a/src/plugins/net/rudp_server.cpp +++ b/src/plugins/net/rudp_server.cpp @@ -12,8 +12,7 @@ rudp_server::~rudp_server() { bool rudp_server::start_server(std::shared_ptr head, bus_id_t bus_id, const std::string& host, uint16_t port, uint8_t thread_num, uint32_t max_client, const size_t silent_timeout) { - if (!head || !max_client) - { + if (!head || !max_client) { return false; } shutdown(); @@ -30,16 +29,12 @@ bool rudp_server::start_server(std::shared_ptr head, bus_id_t ->bind_start([weak] { const auto ec = arknet::get_last_error(); auto self = weak.lock(); - if (!self) - { + if (!self) { return; } - if (ec) - { + if (ec) { ARK_LOG_INFO("Server(RUDP) start failed, error={}, errno={}", ec.message(), ec.value()); - } - else - { + } else { ARK_LOG_INFO("Server(RUDP) start success, listen_addr={} listen_port={}", self->server_->listen_address(), self->server_->listen_port()); } @@ -49,13 +44,10 @@ bool rudp_server::start_server(std::shared_ptr head, bus_id_t ARK_LOG_INFO("Server(RUDP) stop, error={}, errno={}", ec.message(), ec.value()); }) .bind_handshake([](std::shared_ptr& session_ptr, arknet::error_code ec) { - if (ec) - { + if (ec) { ARK_LOG_INFO("Client(RUDP) handshake failed, remote_addr={} remote_port={} error={} errno={}", session_ptr->remote_address(), session_ptr->remote_port(), ec.message(), ec.value()); - } - else - { + } else { ARK_LOG_INFO("Client(RUDP) handshake success, remote_addr={} remote_port={}", session_ptr->remote_address(), session_ptr->remote_port()); } @@ -63,8 +55,7 @@ bool rudp_server::start_server(std::shared_ptr head, bus_id_t .bind_connect( [weak, head, initial_buffer_size, silent_timeout](std::shared_ptr& session_ptr) { auto self = weak.lock(); - if (!self) - { + if (!self) { session_ptr->stop(); return; } @@ -83,15 +74,11 @@ bool rudp_server::start_server(std::shared_ptr head, bus_id_t net_connect_event->set_ip(session_ptr->remote_address()); udp_session_ptr session = std::make_shared(head, cur_session_id, session_ptr, initial_buffer_size); - if (self->add_net_session(session)) - { - if (!session->add_net_event(net_connect_event)) - { + if (self->add_net_session(session)) { + if (!session->add_net_event(net_connect_event)) { net_event::release(net_connect_event); } - } - else - { + } else { net_event::release(net_connect_event); session_ptr->stop(); } @@ -99,8 +86,7 @@ bool rudp_server::start_server(std::shared_ptr head, bus_id_t .bind_disconnect([weak](std::shared_ptr& session_ptr) { const auto ec = arknet::get_last_error(); auto self = weak.lock(); - if (!self) - { + if (!self) { return; } ARK_LOG_INFO("Client(RUDP) disconnected, remote_addr={} remote_port={} error={}", @@ -108,8 +94,7 @@ bool rudp_server::start_server(std::shared_ptr head, bus_id_t auto session_id = session_ptr->get_user_data(); auto session = self->get_net_session(session_id); - if (!session || session->need_remove()) - { + if (!session || session->need_remove()) { return; } @@ -118,23 +103,19 @@ bool rudp_server::start_server(std::shared_ptr head, bus_id_t net_disconnect_event->set_type(net_event_type::disconnect); net_disconnect_event->set_bus_id(self->bus_id_); net_disconnect_event->set_ip(session_ptr->remote_address()); - if (!session->add_net_event(net_disconnect_event)) - { + if (!session->add_net_event(net_disconnect_event)) { net_event::release(net_disconnect_event); } session->need_remove(true); }) .bind_recv([weak](std::shared_ptr& session_ptr, std::string_view s) { auto self = weak.lock(); - if (!self) - { + if (!self) { return; } auto session = self->get_net_session(session_ptr->get_user_data()); - if (session && !session->need_remove()) - { - if (session->add_buffer(s.data(), s.length()) < 0 || !session->parse_buffer_to_msg()) - { + if (session && !session->need_remove()) { + if (session->add_buffer(s.data(), s.length()) < 0 || !session->parse_buffer_to_msg()) { session_ptr->stop(); } } @@ -153,18 +134,15 @@ void rudp_server::update_net_session() { std::vector sessions; { scope_r_lock guard(rw_lock_); - for (auto& iter : sessions_) - { + for (auto& iter : sessions_) { sessions.push_back(iter.second); } } - for (auto& session : sessions) - { + for (auto& session : sessions) { const auto disconnected = session->need_remove(); update_net_event(session); const auto drained = update_net_msg(session); - if (disconnected && drained) - { + if (disconnected && drained) { scope_w_lock guard(rw_lock_); close_session(session); } @@ -175,8 +153,7 @@ void rudp_server::update_net_event(const udp_session_ptr& session) { ARK_ASSERT_RET_NONE(session != nullptr); net_event* event{nullptr}; - while (session->pop_net_event(event)) - { + while (session->pop_net_event(event)) { net_event_cb_(event); net_event::release(event); } @@ -185,14 +162,12 @@ void rudp_server::update_net_event(const udp_session_ptr& session) { bool rudp_server::update_net_msg(const udp_session_ptr& session) { net_msg* msg{nullptr}; int msg_count = 0; - while (session->pop_net_msg(msg)) - { + while (session->pop_net_msg(msg)) { net_msg_cb_(msg, session->get_session_id()); net_msg::release(msg); ++msg_count; - if (msg_count >= ark_process_net_msg_count_once) - { + if (msg_count >= ark_process_net_msg_count_once) { return false; } } @@ -200,8 +175,7 @@ bool rudp_server::update_net_msg(const udp_session_ptr& session) { } void rudp_server::shutdown() { - if (server_) - { + if (server_) { server_->stop(); } set_working(false); @@ -220,8 +194,7 @@ udp_session_ptr rudp_server::get_net_session(conv_id_t session_id) { void rudp_server::close_session(conv_id_t session_id) { auto session = get_net_session(session_id); - if (session == nullptr) - { + if (session == nullptr) { return; } @@ -230,8 +203,7 @@ void rudp_server::close_session(conv_id_t session_id) { std::string rudp_server::get_ip(const conv_id_t session_id) { auto session = get_net_session(session_id); - if (session == nullptr) - { + if (session == nullptr) { return null_str; } @@ -244,16 +216,14 @@ void rudp_server::close_session(udp_session_ptr& session) { } bool rudp_server::send_msg(msg_header* head, const char* msg_data, conv_id_t session_id) { - if (!head || !msg_data || !head->accepts_body_size(head->message_length())) - { + if (!head || !msg_data || !head->accepts_body_size(head->message_length())) { return false; } std::string buffer; head->serialize_to_string(buffer); const auto message_length = head->message_length(); - if (buffer.empty() || !head->accepts_body_size(message_length)) - { + if (buffer.empty() || !head->accepts_body_size(message_length)) { return false; } @@ -263,38 +233,33 @@ bool rudp_server::send_msg(msg_header* head, const char* msg_data, conv_id_t ses bool rudp_server::send_msg(const char* msg, size_t msg_len, conv_id_t session_id) { auto session = get_net_session(session_id); - if (session == nullptr || session->need_remove()) - { + if (session == nullptr || session->need_remove()) { return false; } auto transport = session->get_session(); return transport->async_send(msg, msg_len, [weak = std::weak_ptr(transport), session_id](arknet::error_code ec, size_t) { - if (!ec) - { + if (!ec) { return; } ARK_LOG_ERROR( "Server(RUDP) send failed, session={} error={} errno={}", session_id, ec.message(), ec.value()); - if (auto current = weak.lock()) - { + if (auto current = weak.lock()) { current->stop(); } }); } void rudp_server::broadcast_msg(msg_header* head, const char* msg_data) { - if (!head || !msg_data || !head->accepts_body_size(head->message_length())) - { + if (!head || !msg_data || !head->accepts_body_size(head->message_length())) { return; } std::string buffer; head->serialize_to_string(buffer); const auto message_length = head->message_length(); - if (buffer.empty() || !head->accepts_body_size(message_length)) - { + if (buffer.empty() || !head->accepts_body_size(message_length)) { return; } @@ -306,16 +271,13 @@ void rudp_server::send_msg_to_all(const char* msg, size_t msg_len) { std::vector session_ids; { scope_r_lock guard(rw_lock_); - for (const auto& [id, session] : sessions_) - { - if (!session->need_remove()) - { + for (const auto& [id, session] : sessions_) { + if (!session->need_remove()) { session_ids.push_back(id); } } } - for (auto id : session_ids) - { + for (auto id : session_ids) { send_msg(msg, msg_len, id); } } diff --git a/src/plugins/net/rudp_server.hpp b/src/plugins/net/rudp_server.hpp index bb778dc0f..f981f29ed 100644 --- a/src/plugins/net/rudp_server.hpp +++ b/src/plugins/net/rudp_server.hpp @@ -15,8 +15,7 @@ namespace ark { class rudp_server final : public net , public std::enable_shared_from_this - , private noncopyable -{ + , private noncopyable { friend struct net_listener_startup_test_access; net_event_functor net_event_cb_; diff --git a/src/plugins/net/tcp_client.cpp b/src/plugins/net/tcp_client.cpp index 042f36afa..fe5337886 100644 --- a/src/plugins/net/tcp_client.cpp +++ b/src/plugins/net/tcp_client.cpp @@ -36,8 +36,7 @@ void tcp_client::update() { bool tcp_client::start_client( std::shared_ptr head, bus_id_t dst_bus_id, const std::string& host, uint16_t port) { ARK_ASSERT_RET_VAL(head != nullptr, false); - if (client_ != nullptr) - { + if (client_ != nullptr) { shutdown(); } client_ = std::make_shared(arknet::detail::tcp_frame_size, ark_tcp_recv_buffer_size); @@ -49,28 +48,23 @@ bool tcp_client::start_client( client_->set_connect_timeout(ark_connect_timeout); client_ ->bind_init([weak] { - if (auto self = weak.lock()) - { + if (auto self = weak.lock()) { self->client_->set_no_delay(true); } }) .bind_connect([weak, head, initial_buffer_size] { const auto ec = arknet::get_last_error(); const auto self = weak.lock(); - if (self == nullptr) - { + if (self == nullptr) { return; } - if (ec) - { + if (ec) { ARK_LOG_INFO("Client(TCP) connect server failed, error={} errno={}, server_addr={} server_port={} " "local_addr={} local_port={}", ec.message(), ec.value(), self->client_->remote_address(), self->client_->remote_port(), self->client_->local_address(), self->client_->local_port()); return; - } - else - { + } else { ARK_LOG_INFO("Client(TCP) connect success, server_addr={} server_port={} local_addr={} local_port={}", self->client_->remote_address(), self->client_->remote_port(), self->client_->local_address(), self->client_->local_port()); @@ -92,14 +86,12 @@ bool tcp_client::start_client( // net event & session scope { scope_w_lock guard(self->rw_lock_); - if (self->session_ != nullptr) - { + if (self->session_ != nullptr) { self->retired_sessions_.push_back(self->session_); } self->session_ = std::make_shared(head, cur_session_id, nullptr, initial_buffer_size); - if (!self->session_->add_net_event(net_connect_event)) - { + if (!self->session_->add_net_event(net_connect_event)) { net_event::release(net_connect_event); } } @@ -107,8 +99,7 @@ bool tcp_client::start_client( .bind_disconnect([weak] { const auto ec = arknet::get_last_error(); const auto self = weak.lock(); - if (self == nullptr) - { + if (self == nullptr) { return; } ARK_LOG_INFO( @@ -120,8 +111,7 @@ bool tcp_client::start_client( scope_w_lock guard(self->rw_lock_); if (self->session_ == nullptr || self->session_->get_session_id() != session_id || - self->session_->need_remove()) - { + self->session_->need_remove()) { return; } @@ -133,28 +123,24 @@ bool tcp_client::start_client( net_disconnect_event->set_ip(self->client_->remote_address()); self->session_->need_remove(true); - if (!self->session_->add_net_event(net_disconnect_event)) - { + if (!self->session_->add_net_event(net_disconnect_event)) { net_event::release(net_disconnect_event); } }) .bind_recv([weak](std::string_view s) { const auto self = weak.lock(); - if (self == nullptr) - { + if (self == nullptr) { return; } bool parsed = false; { scope_r_lock guard(self->rw_lock_); - if (self->session_ == nullptr || self->session_->need_remove()) - { + if (self->session_ == nullptr || self->session_->need_remove()) { return; } parsed = self->session_->add_buffer(s.data(), s.length()) >= 0 && self->session_->parse_buffer_to_msg(); } - if (!parsed) - { + if (!parsed) { self->client_->stop(); } }); @@ -166,8 +152,7 @@ bool tcp_client::start_client( } void tcp_client::shutdown() { - if (client_ != nullptr) - { + if (client_ != nullptr) { client_->stop(); } set_working(false); @@ -178,13 +163,11 @@ void tcp_client::update_net_session() { { scope_w_lock guard(rw_lock_); sessions.swap(retired_sessions_); - if (session_ != nullptr) - { + if (session_ != nullptr) { sessions.push_back(session_); } } - for (const auto& session : sessions) - { + for (const auto& session : sessions) { update_net_event(session); update_net_msg(session); } @@ -194,8 +177,7 @@ void tcp_client::update_net_event(const tcp_client_session_ptr& session) { ARK_ASSERT_RET_NONE(session != nullptr); net_event* event(nullptr); - while (session->pop_net_event(event)) - { + while (session->pop_net_event(event)) { net_event_cb_(event); net_event::release(event); } @@ -206,14 +188,12 @@ void tcp_client::update_net_msg(const tcp_client_session_ptr& session) { net_msg* msg(nullptr); int msg_count = 0; - while (session->pop_net_msg(msg)) - { + while (session->pop_net_msg(msg)) { net_msg_cb_(msg, session->get_session_id()); net_msg::release(msg); ++msg_count; - if (msg_count >= ark_process_net_msg_count_once && !session->need_remove()) - { + if (msg_count >= ark_process_net_msg_count_once && !session->need_remove()) { break; } } @@ -225,16 +205,14 @@ bool tcp_client::send_msg(msg_header* head, const char* msg_data, conv_id_t sess std::string buffer; head->serialize_to_string(buffer); const auto message_length = head->message_length(); - if (buffer.empty() || !head->accepts_body_size(message_length)) - { + if (buffer.empty() || !head->accepts_body_size(message_length)) { return false; } buffer.append(msg_data, message_length); scope_r_lock guard(rw_lock_); if (client_ == nullptr || session_ == nullptr || session_->need_remove() || - (session_id != 0 && session_->get_session_id() != session_id)) - { + (session_id != 0 && session_->get_session_id() != session_id)) { return false; } return client_->async_send(std::move(buffer)); @@ -249,8 +227,7 @@ void tcp_client::close_session(conv_id_t session_id) { { scope_r_lock guard(rw_lock_); if (client_ == nullptr || session_ == nullptr || session_->need_remove() || - session_->get_session_id() != session_id) - { + session_->get_session_id() != session_id) { return; } session_id = session_->get_session_id(); @@ -258,8 +235,7 @@ void tcp_client::close_session(conv_id_t session_id) { } client->post([weak = std::weak_ptr(client), session_id] { if (const auto current = weak.lock(); - current != nullptr && current->is_started() && current->get_user_data() == session_id) - { + current != nullptr && current->is_started() && current->get_user_data() == session_id) { current->stop(); } }); diff --git a/src/plugins/net/tcp_client.hpp b/src/plugins/net/tcp_client.hpp index 5ed5c07e2..a1921a6ab 100644 --- a/src/plugins/net/tcp_client.hpp +++ b/src/plugins/net/tcp_client.hpp @@ -35,8 +35,7 @@ namespace ark { class tcp_client final : public net , public noncopyable - , public std::enable_shared_from_this -{ + , public std::enable_shared_from_this { public: tcp_client(net_msg_functor message_callback, net_event_functor event_callback) : net_msg_cb_(std::move(message_callback)) diff --git a/src/plugins/net/tcp_server.cpp b/src/plugins/net/tcp_server.cpp index 5638fff5e..fc6bb2ecd 100644 --- a/src/plugins/net/tcp_server.cpp +++ b/src/plugins/net/tcp_server.cpp @@ -39,8 +39,7 @@ void tcp_server::update() { bool tcp_server::start_server(std::shared_ptr head, bus_id_t bus_id, const std::string& host, uint16_t port, uint8_t thread_num, uint32_t max_client, const size_t silent_timeout) { ARK_ASSERT_RET_VAL(head != nullptr, false); - if (server_ != nullptr) - { + if (server_ != nullptr) { shutdown(); } server_ = std::make_shared( @@ -53,16 +52,12 @@ bool tcp_server::start_server(std::shared_ptr head, bus_id_t b ->bind_start([weak] { const auto ec = arknet::get_last_error(); const auto self = weak.lock(); - if (self == nullptr) - { + if (self == nullptr) { return; } - if (ec) - { + if (ec) { ARK_LOG_INFO("Server(TCP) start failed, error={}, errno={}", ec.message(), ec.value()); - } - else - { + } else { ARK_LOG_INFO("Server(TCP) start success, listen_addr={} listen_port={}", self->server_->listen_address(), self->server_->listen_port()); } @@ -77,8 +72,7 @@ bool tcp_server::start_server(std::shared_ptr head, bus_id_t b }) .bind_connect([weak, head, initial_buffer_size, max_client](std::shared_ptr& session_ptr) { const auto self = weak.lock(); - if (self == nullptr) - { + if (self == nullptr) { session_ptr->stop(); return; } @@ -90,37 +84,32 @@ bool tcp_server::start_server(std::shared_ptr head, bus_id_t b bool admitted = false; { scope_w_lock guard(self->rw_lock_); - if (max_client == 0 || self->active_session_count_ < max_client) - { + if (max_client == 0 || self->active_session_count_ < max_client) { session_ptr->set_user_data(cur_session_id); tcp_session_ptr session = std::make_shared(head, cur_session_id, session_ptr, initial_buffer_size); admitted = self->add_net_session(session); - if (admitted) - { + if (admitted) { ++self->active_session_count_; net_event* net_connect_event = net_event::alloc_event(); net_connect_event->set_id(cur_session_id); net_connect_event->set_type(net_event_type::connect); net_connect_event->set_bus_id(self->bus_id_); net_connect_event->set_ip(session_ptr->remote_address()); - if (!session->add_net_event(net_connect_event)) - { + if (!session->add_net_event(net_connect_event)) { net_event::release(net_connect_event); } } } } - if (!admitted) - { + if (!admitted) { session_ptr->stop(); } }) .bind_disconnect([weak](std::shared_ptr& session_ptr) { const auto ec = arknet::get_last_error(); const auto self = weak.lock(); - if (self == nullptr) - { + if (self == nullptr) { return; } ARK_LOG_INFO("Client(TCP) disconnected, client_addr={} client_port={} error={}, errno={}", @@ -130,8 +119,7 @@ bool tcp_server::start_server(std::shared_ptr head, bus_id_t b scope_w_lock guard(self->rw_lock_); tcp_session_ptr session = self->get_net_session(session_id); - if (session == nullptr || session->need_remove()) - { + if (session == nullptr || session->need_remove()) { return; } @@ -142,15 +130,13 @@ bool tcp_server::start_server(std::shared_ptr head, bus_id_t b net_disconnect_event->set_ip(session_ptr->remote_address()); session->need_remove(true); --self->active_session_count_; - if (!session->add_net_event(net_disconnect_event)) - { + if (!session->add_net_event(net_disconnect_event)) { net_event::release(net_disconnect_event); } }) .bind_recv([weak](std::shared_ptr& session_ptr, std::string_view s) { const auto self = weak.lock(); - if (self == nullptr) - { + if (self == nullptr) { return; } auto session_id = session_ptr->get_user_data(); @@ -160,15 +146,13 @@ bool tcp_server::start_server(std::shared_ptr head, bus_id_t b { scope_r_lock guard(self->rw_lock_); const tcp_session_ptr session = self->get_net_session(session_id); - if (session == nullptr || session->need_remove()) - { + if (session == nullptr || session->need_remove()) { return; } parsed = session->add_buffer(s.data(), s.length()) >= 0 && session->parse_buffer_to_msg(); } - if (!parsed) - { + if (!parsed) { session_ptr->stop(); } }); @@ -183,18 +167,15 @@ void tcp_server::update_net_session() { { scope_r_lock guard(rw_lock_); sessions.reserve(sessions_.size()); - for (const auto& iter : sessions_) - { + for (const auto& iter : sessions_) { sessions.push_back(iter.second); } } - for (auto& session : sessions) - { + for (auto& session : sessions) { ARK_ASSERT_CONTINUE(session != nullptr); const bool disconnected = update_net_event(session); update_net_msg(session); - if (disconnected) - { + if (disconnected) { scope_w_lock guard(rw_lock_); close_session(session); } @@ -206,8 +187,7 @@ bool tcp_server::update_net_event(const tcp_session_ptr& session) { bool disconnected = false; net_event* event{nullptr}; - while (session->pop_net_event(event)) - { + while (session->pop_net_event(event)) { disconnected = disconnected || event->get_type() == net_event_type::disconnect; net_event_cb_(event); net_event::release(event); @@ -220,22 +200,19 @@ void tcp_server::update_net_msg(const tcp_session_ptr& session) { net_msg* msg{nullptr}; int msg_count = 0; - while (session->pop_net_msg(msg)) - { + while (session->pop_net_msg(msg)) { net_msg_cb_(msg, session->get_session_id()); net_msg::release(msg); ++msg_count; - if (msg_count >= ark_process_net_msg_count_once && !session->need_remove()) - { + if (msg_count >= ark_process_net_msg_count_once && !session->need_remove()) { break; } } } void tcp_server::shutdown() { - if (server_ != nullptr) - { + if (server_ != nullptr) { server_->stop(); } set_working(false); @@ -244,8 +221,7 @@ void tcp_server::shutdown() { std::string tcp_server::get_ip(const conv_id_t session_id) { scope_r_lock guard(rw_lock_); auto session = get_net_session(session_id); - if (session == nullptr) - { + if (session == nullptr) { return null_str; } @@ -269,8 +245,7 @@ void tcp_server::close_session(conv_id_t session_id) { scope_r_lock guard(rw_lock_); session = get_net_session(session_id); } - if (session != nullptr) - { + if (session != nullptr) { session->get_session()->stop(); } } @@ -279,13 +254,11 @@ void tcp_server::close_all_session() { std::vector sessions; { scope_r_lock guard(rw_lock_); - for (const auto& entry : sessions_) - { + for (const auto& entry : sessions_) { sessions.push_back(entry.second); } } - for (const auto& session : sessions) - { + for (const auto& session : sessions) { session->get_session()->stop(); } } @@ -298,8 +271,7 @@ tcp_session_ptr tcp_server::get_net_session(conv_id_t session_id) { bool tcp_server::send_msg(const char* msg, size_t msg_len, conv_id_t session_id) { scope_r_lock guard(rw_lock_); auto session = get_net_session(session_id); - if (session == nullptr || session->need_remove()) - { + if (session == nullptr || session->need_remove()) { return false; } @@ -308,11 +280,9 @@ bool tcp_server::send_msg(const char* msg, size_t msg_len, conv_id_t session_id) void tcp_server::send_msg_to_all_client(const char* msg, size_t msg_len) { scope_r_lock guard(rw_lock_); - for (const auto& it : sessions_) - { + for (const auto& it : sessions_) { auto& session = it.second; - if (session != nullptr && !session->need_remove()) - { + if (session != nullptr && !session->need_remove()) { session->get_session()->async_send(msg, msg_len); } } @@ -320,23 +290,20 @@ void tcp_server::send_msg_to_all_client(const char* msg, size_t msg_len) { bool tcp_server::send_msg(msg_header* head, const char* msg_data, conv_id_t session_id) { ARK_ASSERT_RET_VAL(head != nullptr && msg_data != nullptr, false); - if (!head->accepts_body_size(head->message_length())) - { + if (!head->accepts_body_size(head->message_length())) { return false; } scope_r_lock guard(rw_lock_); auto session = get_net_session(session_id); - if (session == nullptr || session->need_remove()) - { + if (session == nullptr || session->need_remove()) { return false; } std::string buffer; head->serialize_to_string(buffer); const auto message_length = head->message_length(); - if (buffer.empty() || !head->accepts_body_size(message_length)) - { + if (buffer.empty() || !head->accepts_body_size(message_length)) { return false; } @@ -346,16 +313,14 @@ bool tcp_server::send_msg(msg_header* head, const char* msg_data, conv_id_t sess void tcp_server::broadcast_msg(msg_header* head, const char* msg_data) { ARK_ASSERT_RET_NONE(head != nullptr && msg_data != nullptr); - if (!head->accepts_body_size(head->message_length())) - { + if (!head->accepts_body_size(head->message_length())) { return; } std::string buffer; head->serialize_to_string(buffer); const auto message_length = head->message_length(); - if (buffer.empty() || !head->accepts_body_size(message_length)) - { + if (buffer.empty() || !head->accepts_body_size(message_length)) { return; } buffer.append(msg_data, message_length); diff --git a/src/plugins/net/tcp_server.hpp b/src/plugins/net/tcp_server.hpp index 817a43d9b..bccaa0740 100644 --- a/src/plugins/net/tcp_server.hpp +++ b/src/plugins/net/tcp_server.hpp @@ -36,8 +36,7 @@ namespace ark { class tcp_server final : public net , public noncopyable - , public std::enable_shared_from_this -{ + , public std::enable_shared_from_this { public: tcp_server(net_msg_functor message_callback, net_event_functor event_callback) : net_msg_cb_(std::move(message_callback)) diff --git a/src/plugins/net/websocket_client.cpp b/src/plugins/net/websocket_client.cpp index a1ec48057..278c75da9 100644 --- a/src/plugins/net/websocket_client.cpp +++ b/src/plugins/net/websocket_client.cpp @@ -32,8 +32,7 @@ websocket_client::~websocket_client() { bool websocket_client::start_client( std::shared_ptr head, bus_id_t dst_bus_id, const std::string& host, uint16_t port) { ARK_ASSERT_RET_VAL(head != nullptr, false); - if (client_ != nullptr) - { + if (client_ != nullptr) { shutdown(); } client_ = std::make_shared(arknet::detail::tcp_frame_size, ark_tcp_recv_buffer_size); @@ -45,28 +44,23 @@ bool websocket_client::start_client( client_->set_connect_timeout(ark_connect_timeout); client_ ->bind_init([weak] { - if (auto self = weak.lock()) - { + if (auto self = weak.lock()) { self->client_->set_no_delay(true); } }) .bind_connect([weak, head, initial_buffer_size] { const auto ec = arknet::get_last_error(); const auto self = weak.lock(); - if (self == nullptr) - { + if (self == nullptr) { return; } - if (ec) - { + if (ec) { ARK_LOG_INFO("Client(WS) connect server failed, error={} errno={}, server_addr={} " "server_port={},local_addr={} local_port={}", ec.message(), ec.value(), self->client_->remote_address(), self->client_->remote_port(), self->client_->local_address(), self->client_->local_port()); return; - } - else - { + } else { ARK_LOG_INFO( "Client(WS) connect server success, server_addr={} server_port={} local_addr={} local_port={}", self->client_->remote_address(), self->client_->remote_port(), self->client_->local_address(), @@ -90,14 +84,12 @@ bool websocket_client::start_client( // net event & session scope { scope_w_lock guard(self->rw_lock_); - if (self->client_session_ptr_ != nullptr) - { + if (self->client_session_ptr_ != nullptr) { self->retired_sessions_.push_back(self->client_session_ptr_); } self->client_session_ptr_ = std::make_shared(head, cur_session_id, nullptr, initial_buffer_size); - if (!self->client_session_ptr_->add_net_event(net_connect_event)) - { + if (!self->client_session_ptr_->add_net_event(net_connect_event)) { net_event::release(net_connect_event); } } @@ -105,8 +97,7 @@ bool websocket_client::start_client( .bind_disconnect([weak] { const auto ec = arknet::get_last_error(); const auto self = weak.lock(); - if (self == nullptr) - { + if (self == nullptr) { return; } ARK_LOG_INFO("Client(WS) disconnect server, error={} errno={} remote_addr={} remote_port={} local_addr={} " @@ -118,8 +109,7 @@ bool websocket_client::start_client( scope_w_lock guard(self->rw_lock_); if (self->client_session_ptr_ == nullptr || self->client_session_ptr_->get_session_id() != session_id || - self->client_session_ptr_->need_remove()) - { + self->client_session_ptr_->need_remove()) { return; } @@ -132,29 +122,25 @@ bool websocket_client::start_client( // TODO: will add port self->client_session_ptr_->need_remove(true); - if (!self->client_session_ptr_->add_net_event(net_disconnect_event)) - { + if (!self->client_session_ptr_->add_net_event(net_disconnect_event)) { net_event::release(net_disconnect_event); } }) .bind_recv([weak](std::string_view s) { const auto self = weak.lock(); - if (self == nullptr) - { + if (self == nullptr) { return; } bool parsed = false; { scope_r_lock guard(self->rw_lock_); - if (self->client_session_ptr_ == nullptr || self->client_session_ptr_->need_remove()) - { + if (self->client_session_ptr_ == nullptr || self->client_session_ptr_->need_remove()) { return; } parsed = self->client_session_ptr_->add_buffer(s.data(), s.length()) >= 0 && self->client_session_ptr_->parse_buffer_to_msg(); } - if (!parsed) - { + if (!parsed) { self->client_->stop(); } }); @@ -166,8 +152,7 @@ bool websocket_client::start_client( } void websocket_client::shutdown() { - if (client_ != nullptr) - { + if (client_ != nullptr) { client_->stop(); } set_working(false); @@ -178,13 +163,11 @@ void websocket_client::update() { { scope_w_lock guard(rw_lock_); sessions.swap(retired_sessions_); - if (client_session_ptr_ != nullptr) - { + if (client_session_ptr_ != nullptr) { sessions.push_back(client_session_ptr_); } } - for (const auto& session : sessions) - { + for (const auto& session : sessions) { update_net_event(session); update_net_msg(session); } @@ -194,8 +177,7 @@ void websocket_client::update_net_event(const ws_client_session_ptr& session) { ARK_ASSERT_RET_NONE(session != nullptr); net_event* event{nullptr}; - while (session->pop_net_event(event)) - { + while (session->pop_net_event(event)) { net_event_cb_(event); net_event::release(event); } @@ -206,14 +188,12 @@ void websocket_client::update_net_msg(const ws_client_session_ptr& session) { net_msg* msg{nullptr}; int msg_count = 0; - while (session->pop_net_msg(msg)) - { + while (session->pop_net_msg(msg)) { net_msg_cb_(msg, session->get_session_id()); net_msg::release(msg); ++msg_count; - if (msg_count >= ark_process_net_msg_count_once && !session->need_remove()) - { + if (msg_count >= ark_process_net_msg_count_once && !session->need_remove()) { break; } } @@ -225,16 +205,14 @@ bool websocket_client::send_msg(msg_header* head, const char* msg_data, conv_id_ std::string buffer; head->serialize_to_string(buffer); const auto message_length = head->message_length(); - if (buffer.empty() || !head->accepts_body_size(message_length)) - { + if (buffer.empty() || !head->accepts_body_size(message_length)) { return false; } buffer.append(msg_data, message_length); scope_r_lock guard(rw_lock_); if (client_ == nullptr || client_session_ptr_ == nullptr || client_session_ptr_->need_remove() || - (session_id != 0 && client_session_ptr_->get_session_id() != session_id)) - { + (session_id != 0 && client_session_ptr_->get_session_id() != session_id)) { return false; } return client_->async_send(std::move(buffer)); @@ -249,8 +227,7 @@ void websocket_client::close_session(conv_id_t session_id) { { scope_r_lock guard(rw_lock_); if (client_ == nullptr || client_session_ptr_ == nullptr || client_session_ptr_->need_remove() || - client_session_ptr_->get_session_id() != session_id) - { + client_session_ptr_->get_session_id() != session_id) { return; } session_id = client_session_ptr_->get_session_id(); @@ -258,8 +235,7 @@ void websocket_client::close_session(conv_id_t session_id) { } client->post([weak = std::weak_ptr(client), session_id] { if (const auto current = weak.lock(); - current != nullptr && current->is_started() && current->get_user_data() == session_id) - { + current != nullptr && current->is_started() && current->get_user_data() == session_id) { current->stop(); } }); diff --git a/src/plugins/net/websocket_client.hpp b/src/plugins/net/websocket_client.hpp index 7c13a0e03..5c742090d 100644 --- a/src/plugins/net/websocket_client.hpp +++ b/src/plugins/net/websocket_client.hpp @@ -35,8 +35,7 @@ namespace ark { class websocket_client final : public net , public noncopyable - , public std::enable_shared_from_this -{ + , public std::enable_shared_from_this { public: template websocket_client(base_type* base_type_ptr, void (base_type::*handle_recv)(net_msg const*, conv_id_t const&), diff --git a/src/plugins/net/websocket_server.cpp b/src/plugins/net/websocket_server.cpp index 36005ae2b..f07808336 100644 --- a/src/plugins/net/websocket_server.cpp +++ b/src/plugins/net/websocket_server.cpp @@ -39,8 +39,7 @@ void websocket_server::update() { bool websocket_server::start_server(std::shared_ptr head, bus_id_t bus_id, const std::string& host, uint16_t port, uint8_t thread_num, uint32_t max_client, const size_t silent_timeout) { ARK_ASSERT_RET_VAL(head != nullptr, false); - if (server_ != nullptr) - { + if (server_ != nullptr) { shutdown(); } server_ = std::make_shared( @@ -53,16 +52,12 @@ bool websocket_server::start_server(std::shared_ptr head, bus_ ->bind_start([weak] { const auto ec = arknet::get_last_error(); const auto self = weak.lock(); - if (self == nullptr) - { + if (self == nullptr) { return; } - if (ec) - { + if (ec) { ARK_LOG_INFO("Server(WS) start failed, error={} errno={}", ec.message(), ec.value()); - } - else - { + } else { ARK_LOG_INFO("Server(WS) start success, listen_addr={} listen_port={}", self->server_->listen_address(), self->server_->listen_port()); } @@ -77,8 +72,7 @@ bool websocket_server::start_server(std::shared_ptr head, bus_ }) .bind_connect([weak, head, initial_buffer_size, max_client](std::shared_ptr& session_ptr) { const auto self = weak.lock(); - if (self == nullptr) - { + if (self == nullptr) { session_ptr->stop(); return; } @@ -91,37 +85,32 @@ bool websocket_server::start_server(std::shared_ptr head, bus_ bool admitted = false; { scope_w_lock guard(self->rw_lock_); - if (max_client == 0 || self->active_session_count_ < max_client) - { + if (max_client == 0 || self->active_session_count_ < max_client) { session_ptr->set_user_data(cur_session_id); ws_session_ptr session = std::make_shared(head, cur_session_id, session_ptr, initial_buffer_size); admitted = self->add_net_session(session); - if (admitted) - { + if (admitted) { ++self->active_session_count_; net_event* net_connect_event = net_event::alloc_event(); net_connect_event->set_id(cur_session_id); net_connect_event->set_type(net_event_type::connect); net_connect_event->set_bus_id(self->bus_id_); net_connect_event->set_ip(session_ptr->remote_address()); - if (!session->add_net_event(net_connect_event)) - { + if (!session->add_net_event(net_connect_event)) { net_event::release(net_connect_event); } } } } - if (!admitted) - { + if (!admitted) { session_ptr->stop(); } }) .bind_disconnect([weak](std::shared_ptr& session_ptr) { const auto ec = arknet::get_last_error(); const auto self = weak.lock(); - if (self == nullptr) - { + if (self == nullptr) { return; } ARK_LOG_INFO("Client(WS) disconnected, client_addr={} client_port={} error={}", @@ -131,8 +120,7 @@ bool websocket_server::start_server(std::shared_ptr head, bus_ scope_w_lock guard(self->rw_lock_); ws_session_ptr session = self->get_net_session(session_id); - if (session == nullptr || session->need_remove()) - { + if (session == nullptr || session->need_remove()) { return; } @@ -143,8 +131,7 @@ bool websocket_server::start_server(std::shared_ptr head, bus_ net_disconnect_event->set_ip(session_ptr->remote_address()); session->need_remove(true); --self->active_session_count_; - if (!session->add_net_event(net_disconnect_event)) - { + if (!session->add_net_event(net_disconnect_event)) { net_event::release(net_disconnect_event); } }) @@ -155,8 +142,7 @@ bool websocket_server::start_server(std::shared_ptr head, bus_ }) .bind_recv([weak](std::shared_ptr& session_ptr, std::string_view s) { const auto self = weak.lock(); - if (self == nullptr) - { + if (self == nullptr) { return; } auto session_id = session_ptr->get_user_data(); @@ -166,15 +152,13 @@ bool websocket_server::start_server(std::shared_ptr head, bus_ { scope_r_lock guard(self->rw_lock_); const ws_session_ptr session = self->get_net_session(session_id); - if (session == nullptr || session->need_remove()) - { + if (session == nullptr || session->need_remove()) { return; } parsed = session->add_buffer(s.data(), s.length()) >= 0 && session->parse_buffer_to_msg(); } - if (!parsed) - { + if (!parsed) { session_ptr->stop(); } }); @@ -189,18 +173,15 @@ void websocket_server::update_net_session() { { scope_r_lock guard(rw_lock_); sessions.reserve(sessions_.size()); - for (const auto& iter : sessions_) - { + for (const auto& iter : sessions_) { sessions.push_back(iter.second); } } - for (const auto& session : sessions) - { + for (const auto& session : sessions) { ARK_ASSERT_CONTINUE(session != nullptr); const bool disconnected = update_net_event(session); update_net_msg(session); - if (disconnected) - { + if (disconnected) { scope_w_lock guard(rw_lock_); close_session(session); } @@ -212,8 +193,7 @@ bool websocket_server::update_net_event(const ws_session_ptr& session) { bool disconnected = false; net_event* event{nullptr}; - while (session->pop_net_event(event)) - { + while (session->pop_net_event(event)) { disconnected = disconnected || event->get_type() == net_event_type::disconnect; net_event_cb_(event); net_event::release(event); @@ -226,22 +206,19 @@ void websocket_server::update_net_msg(const ws_session_ptr& session) { net_msg* msg{nullptr}; int msg_count = 0; - while (session->pop_net_msg(msg)) - { + while (session->pop_net_msg(msg)) { net_msg_cb_(msg, session->get_session_id()); net_msg::release(msg); ++msg_count; - if (msg_count >= ark_process_net_msg_count_once && !session->need_remove()) - { + if (msg_count >= ark_process_net_msg_count_once && !session->need_remove()) { break; } } } void websocket_server::shutdown() { - if (server_ != nullptr) - { + if (server_ != nullptr) { server_->stop(); } set_working(false); @@ -264,8 +241,7 @@ void websocket_server::close_session(conv_id_t session_id) { scope_r_lock guard(rw_lock_); session = get_net_session(session_id); } - if (session != nullptr) - { + if (session != nullptr) { session->get_session()->stop(); } } @@ -274,13 +250,11 @@ void websocket_server::close_all_session() { std::vector sessions; { scope_r_lock guard(rw_lock_); - for (const auto& entry : sessions_) - { + for (const auto& entry : sessions_) { sessions.push_back(entry.second); } } - for (const auto& session : sessions) - { + for (const auto& session : sessions) { session->get_session()->stop(); } } @@ -293,8 +267,7 @@ ws_session_ptr websocket_server::get_net_session(conv_id_t session_id) { bool websocket_server::send_msg(const char* msg, const size_t msg_len, conv_id_t session_id) { scope_r_lock guard(rw_lock_); auto session = get_net_session(session_id); - if (session == nullptr || session->need_remove()) - { + if (session == nullptr || session->need_remove()) { return false; } @@ -303,23 +276,20 @@ bool websocket_server::send_msg(const char* msg, const size_t msg_len, conv_id_t bool websocket_server::send_msg(msg_header* head, const char* msg_data, conv_id_t session_id) { ARK_ASSERT_RET_VAL(head != nullptr && msg_data != nullptr, false); - if (!head->accepts_body_size(head->message_length())) - { + if (!head->accepts_body_size(head->message_length())) { return false; } scope_r_lock guard(rw_lock_); auto session = get_net_session(session_id); - if (session == nullptr || session->need_remove()) - { + if (session == nullptr || session->need_remove()) { return false; } std::string buffer; head->serialize_to_string(buffer); const auto message_length = head->message_length(); - if (buffer.empty() || !head->accepts_body_size(message_length)) - { + if (buffer.empty() || !head->accepts_body_size(message_length)) { return false; } @@ -329,11 +299,9 @@ bool websocket_server::send_msg(msg_header* head, const char* msg_data, conv_id_ void websocket_server::send_msg_to_all_client(const char* msg, size_t msg_len) { scope_r_lock guard(rw_lock_); - for (const auto& it : sessions_) - { + for (const auto& it : sessions_) { auto& session = it.second; - if (session != nullptr && !session->need_remove()) - { + if (session != nullptr && !session->need_remove()) { session->get_session()->async_send(msg, msg_len); } } @@ -341,16 +309,14 @@ void websocket_server::send_msg_to_all_client(const char* msg, size_t msg_len) { void websocket_server::broadcast_msg(msg_header* head, const char* msg_data) { ARK_ASSERT_RET_NONE(head != nullptr && msg_data != nullptr); - if (!head->accepts_body_size(head->message_length())) - { + if (!head->accepts_body_size(head->message_length())) { return; } std::string buffer; head->serialize_to_string(buffer); const auto message_length = head->message_length(); - if (buffer.empty() || !head->accepts_body_size(message_length)) - { + if (buffer.empty() || !head->accepts_body_size(message_length)) { return; } buffer.append(msg_data, message_length); diff --git a/src/plugins/net/websocket_server.hpp b/src/plugins/net/websocket_server.hpp index 250ddaae9..d235a9c22 100644 --- a/src/plugins/net/websocket_server.hpp +++ b/src/plugins/net/websocket_server.hpp @@ -35,8 +35,7 @@ namespace ark { class websocket_server final : public net , public noncopyable - , public std::enable_shared_from_this -{ + , public std::enable_shared_from_this { public: template websocket_server(base_type* base_type_ptr, void (base_type::*handle_receive)(const net_msg*, conv_id_t), diff --git a/src/plugins/osssdk/oss_sdk_module.hpp b/src/plugins/osssdk/oss_sdk_module.hpp index d566178ff..169b689b5 100644 --- a/src/plugins/osssdk/oss_sdk_module.hpp +++ b/src/plugins/osssdk/oss_sdk_module.hpp @@ -24,8 +24,7 @@ namespace ark { -class oss_sdk_module : public module -{ +class oss_sdk_module : public module { public: //virtual method }; diff --git a/src/plugins/osssdk/oss_sdk_module_impl.hpp b/src/plugins/osssdk/oss_sdk_module_impl.hpp index 734e3b0d3..126094077 100644 --- a/src/plugins/osssdk/oss_sdk_module_impl.hpp +++ b/src/plugins/osssdk/oss_sdk_module_impl.hpp @@ -25,8 +25,7 @@ namespace ark { -class oss_sdk_module_impl final : public module_base -{ +class oss_sdk_module_impl final : public module_base { public: // TODO diff --git a/src/plugins/osssdk/oss_sdk_plugin.cpp b/src/plugins/osssdk/oss_sdk_plugin.cpp index d20d4321e..22a6dd514 100644 --- a/src/plugins/osssdk/oss_sdk_plugin.cpp +++ b/src/plugins/osssdk/oss_sdk_plugin.cpp @@ -35,15 +35,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void oss_sdk_plugin::install() { - if (!register_module(detail::make_oss_sdk_module(), module_update::disabled)) - { + if (!register_module(detail::make_oss_sdk_module(), module_update::disabled)) { throw std::runtime_error("OSS SDK module registration rejected"); } } void oss_sdk_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("OSS SDK module unregistration rejected"); } } diff --git a/src/plugins/osssdk/oss_sdk_plugin.hpp b/src/plugins/osssdk/oss_sdk_plugin.hpp index 349ad0c5a..18c099ea4 100644 --- a/src/plugins/osssdk/oss_sdk_plugin.hpp +++ b/src/plugins/osssdk/oss_sdk_plugin.hpp @@ -24,8 +24,7 @@ namespace ark { -class oss_sdk_plugin final : public plugin_base -{ +class oss_sdk_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/plugins/physic/physic_config_module.hpp b/src/plugins/physic/physic_config_module.hpp index 3b9d7a433..9d33e7261 100644 --- a/src/plugins/physic/physic_config_module.hpp +++ b/src/plugins/physic/physic_config_module.hpp @@ -25,8 +25,7 @@ namespace ark { -class physic_config_module : public module -{ +class physic_config_module : public module { public: ///get scene by config id virtual bool get_physic_scene(const std::string& scene_id, physic_scene& scene) const = 0; diff --git a/src/plugins/physic/physic_config_module_impl.cpp b/src/plugins/physic/physic_config_module_impl.cpp index c8cae281b..5574e35e3 100644 --- a/src/plugins/physic/physic_config_module_impl.cpp +++ b/src/plugins/physic/physic_config_module_impl.cpp @@ -39,13 +39,11 @@ namespace ark { bool physic_config_module_impl::init() { - if (!load_config()) - { + if (!load_config()) { return false; } - if (!load_scene()) - { + if (!load_scene()) { return false; } @@ -58,8 +56,7 @@ bool physic_config_module_impl::shut() { bool physic_config_module_impl::get_physic_scene(const std::string& scene_id, physic_scene& scene) const { auto iter = scene_list_.find(scene_id); - if (iter == scene_list_.end()) - { + if (iter == scene_list_.end()) { ARK_LOG_ERROR("do not have this scene scene_id={}", scene_id); return false; } @@ -80,45 +77,36 @@ bool physic_config_module_impl::load_scene() { std::string file_path = get_plugin_manager()->GetResPath() + physic_scene_path; std::multimap sub_path_list; - if (!get_scene_file_list("", file_path, sub_path_list)) - { + if (!get_scene_file_list("", file_path, sub_path_list)) { return false; } ///read scene - for (auto& iter : sub_path_list) - { + for (auto& iter : sub_path_list) { auto scene_id = iter.first; auto file_path = iter.second; ///find scene auto iter_scene = scene_list_.find(scene_id); - if (iter_scene == scene_list_.end()) - { + if (iter_scene == scene_list_.end()) { physic_scene scene; scene.scene_id = scene_id; iter_scene = scene_list_.insert(std::make_pair(scene_id, scene)).first; } - if (iter_scene == scene_list_.end()) - { + if (iter_scene == scene_list_.end()) { ARK_LOG_ERROR("do not have this scene scene_id={}", scene_id); return false; } auto& scene = iter_scene->second; ///load file - if (file_path.ends_with(physic_mesh_file_end)) - { - if (!load_terrain(scene, file_path)) - { + if (file_path.ends_with(physic_mesh_file_end)) { + if (!load_terrain(scene, file_path)) { return false; } - } - else if (file_path.ends_with(physic_collider_file_end)) - { - if (!load_collider(scene, file_path)) - { + } else if (file_path.ends_with(physic_collider_file_end)) { + if (!load_collider(scene, file_path)) { return false; } } @@ -139,13 +127,10 @@ bool physic_config_module_impl::load_collider(physic_scene& scene, const std::st const auto native_vector = [](const std::array& value) { return physx::PxVec3(value[0], value[1], value[2]); }; - for (const auto& resource : resources) - { + for (const auto& resource : resources) { std::unique_ptr object; - switch (resource.type) - { - case physic_resources::collider_type::box: - { + switch (resource.type) { + case physic_resources::collider_type::box: { auto box = std::make_unique(); box->position = native_vector(resource.position); box->center = native_vector(resource.center); @@ -153,8 +138,7 @@ bool physic_config_module_impl::load_collider(physic_scene& scene, const std::st object = std::move(box); break; } - case physic_resources::collider_type::capsule: - { + case physic_resources::collider_type::capsule: { auto capsule = std::make_unique(); capsule->position = native_vector(resource.position); capsule->center = native_vector(resource.center); @@ -163,8 +147,7 @@ bool physic_config_module_impl::load_collider(physic_scene& scene, const std::st object = std::move(capsule); break; } - case physic_resources::collider_type::sphere: - { + case physic_resources::collider_type::sphere: { auto sphere = std::make_unique(); sphere->position = native_vector(resource.position); sphere->center = native_vector(resource.center); @@ -172,15 +155,13 @@ bool physic_config_module_impl::load_collider(physic_scene& scene, const std::st object = std::move(sphere); break; } - case physic_resources::collider_type::mesh: - { + case physic_resources::collider_type::mesh: { auto mesh = std::make_unique(); mesh->position = native_vector(resource.position); mesh->convex = resource.convex; mesh->vertex_count = static_cast(resource.vertices.size()); mesh->vertices = new physx::PxVec3[mesh->vertex_count]; - for (std::size_t i = 0; i < resource.vertices.size(); ++i) - { + for (std::size_t i = 0; i < resource.vertices.size(); ++i) { mesh->vertices[i] = native_vector(resource.vertices[i]); } mesh->triangle_count = static_cast(resource.triangles.size()); @@ -209,34 +190,26 @@ bool physic_config_module_impl::get_scene_file_list( _finddata_t find_data; handle = _findfirst(search_path.c_str(), &find_data); - if (handle == -1) - { + if (handle == -1) { ARK_LOG_ERROR("can not open path={}", path); return false; } - do - { - if (find_data.attrib & _A_SUBDIR) - { + do { + if (find_data.attrib & _A_SUBDIR) { /// is sub dir - if (strcmp(find_data.name, ".") == 0 || strcmp(find_data.name, "..") == 0) - { + if (strcmp(find_data.name, ".") == 0 || strcmp(find_data.name, "..") == 0) { continue; } auto new_dir = path + physic_slash + find_data.name; - if (!get_scene_file_list(path, new_dir, sub_path_list)) - { + if (!get_scene_file_list(path, new_dir, sub_path_list)) { ARK_LOG_ERROR("read path failed path={}", new_dir); return false; } - } - else - { + } else { /// not sub dir - if (father_path.empty()) - { + if (father_path.empty()) { ARK_LOG_ERROR("not in a scene path={} file = {}", path, find_data.name); return false; } @@ -254,35 +227,27 @@ bool physic_config_module_impl::get_scene_file_list( #elif defined(ARK_PLATFORM_LINUX) || defined(ARK_PLATFORM_DARWIN) DIR* dir = opendir(path.c_str()); - if (dir == NULL) - { + if (dir == NULL) { ARK_LOG_ERROR("can not open path={}", path); return false; } struct dirent* entry; - while ((entry = readdir(dir)) != NULL) - { - if (entry->d_type == DT_DIR) - { + while ((entry = readdir(dir)) != NULL) { + if (entry->d_type == DT_DIR) { ///is sub dir - if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) - { + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } string new_dir = path + physic_slash + entry->d_name; - if (!get_scene_file_list(path, new_dir, sub_path_list)) - { + if (!get_scene_file_list(path, new_dir, sub_path_list)) { ARK_LOG_ERROR("read path failed path={}", new_dir); return false; } - } - else - { + } else { /// not sub dir - if (father_path.empty()) - { + if (father_path.empty()) { ARK_LOG_ERROR("not in a scene path={} file = {}", path, entry->d_name); return false; } @@ -328,38 +293,31 @@ void physic_config_module_impl::create_file_path(const std::string& file_path) { #ifdef ARK_PLATFORM_WIN int len = file_path.length(); char temp_path[256] = {0}; - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { temp_path[i] = file_path[i]; - if (temp_path[i] != '/') - { + if (temp_path[i] != '/') { continue; } - if (_access(temp_path, 0) != -1) - { + if (_access(temp_path, 0) != -1) { continue; } int ret = _mkdir(temp_path); - if (ret == -1) - { + if (ret == -1) { return; } } #elif defined(ARK_PLATFORM_LINUX) || defined(ARK_PLATFORM_DARWIN) int len = file_path.length(); char temp_path[256] = {0}; - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { temp_path[i] = file_path[i]; - if (temp_path[i] != '/') - { + if (temp_path[i] != '/') { continue; } - if (access(temp_path, F_OK) != -1) - { + if (access(temp_path, F_OK) != -1) { continue; } diff --git a/src/plugins/physic/physic_config_module_impl.hpp b/src/plugins/physic/physic_config_module_impl.hpp index a7d493151..a2e692a25 100644 --- a/src/plugins/physic/physic_config_module_impl.hpp +++ b/src/plugins/physic/physic_config_module_impl.hpp @@ -25,8 +25,7 @@ namespace ark { -class physic_config_module_impl final : public physic_config_module -{ +class physic_config_module_impl final : public physic_config_module { ARK_DECLARE_MODULE_FUNCTIONS public: bool init() override; diff --git a/src/plugins/physic/physic_define.hpp b/src/plugins/physic/physic_define.hpp index 272f08c12..03eb67455 100644 --- a/src/plugins/physic/physic_define.hpp +++ b/src/plugins/physic/physic_define.hpp @@ -35,8 +35,7 @@ inline physx::PxI32 open_file(FILE** file, const char* name, const char* mode) { char buf[max_length + 1]; physx::PxU32 i; - for (i = 0; i < max_length && name[i]; i++) - { + for (i = 0; i < max_length && name[i]; i++) { buf[i] = name[i] == '/' ? '\\' : name[i]; } buf[i] = 0; @@ -44,8 +43,7 @@ inline physx::PxI32 open_file(FILE** file, const char* name, const char* mode) { return i == max_length ? -1 : ::fopen_s(file, buf, mode); #elif defined(ARK_PLATFORM_LINUX) || defined(ARK_PLATFORM_DARWIN) FILE* fp = ::fopen(name, mode); - if (fp) - { + if (fp) { *file = fp; return 0; } @@ -57,8 +55,7 @@ inline physx::PxI32 open_file(FILE** file, const char* name, const char* mode) { } // namespace physic -struct physic_config -{ +struct physic_config { bool simulate{false}; physx::PxU32 dispatcher_threads{0}; physx::PxReal step{0.0333F}; @@ -67,14 +64,12 @@ struct physic_config uint32_t pvd_timeout{0}; }; -struct physic_mesh_file -{ +struct physic_mesh_file { std::string path{""}; std::string cooked_path{""}; }; -class collider -{ +class collider { public: virtual ~collider() = default; @@ -106,8 +101,7 @@ class collider bool trigger{false}; }; -class box_collider : public collider -{ +class box_collider : public collider { public: bool is_box_collider() const override { return true; @@ -119,8 +113,7 @@ class box_collider : public collider physx::PxVec3 size{zero_vec3}; }; -class capsule_collider : public collider -{ +class capsule_collider : public collider { public: bool is_capsule_collider() const override { return true; @@ -133,8 +126,7 @@ class capsule_collider : public collider physx::PxReal height{zero_real}; }; -class sphere_collider : public collider -{ +class sphere_collider : public collider { public: bool is_sphere_collider() const override { return true; @@ -146,8 +138,7 @@ class sphere_collider : public collider physx::PxReal radius{zero_real}; }; -class mesh_collider : public collider -{ +class mesh_collider : public collider { public: ~mesh_collider() { ARK_DELETE_ARRAY(physx::PxVec3, vertices); @@ -169,14 +160,11 @@ class mesh_collider : public collider physic_mesh_file mesh_file; }; -class physic_scene -{ +class physic_scene { public: ~physic_scene() { - for (auto iter : colliders) - { - if (iter) - { + for (auto iter : colliders) { + if (iter) { ARK_DELETE(iter); } } diff --git a/src/plugins/physic/physic_module.hpp b/src/plugins/physic/physic_module.hpp index 4a5d1d9a3..66fa3362d 100644 --- a/src/plugins/physic/physic_module.hpp +++ b/src/plugins/physic/physic_module.hpp @@ -25,8 +25,7 @@ namespace ark { ///3d position -class base_vec3_d -{ +class base_vec3_d { public: float x{0.0f}; float y{0.0f}; @@ -47,8 +46,7 @@ class base_vec3_d } const base_vec3_d& operator=(const base_vec3_d& rhs) { - if (this != &rhs) - { + if (this != &rhs) { x = rhs.x; y = rhs.y; z = rhs.z; @@ -60,8 +58,7 @@ class base_vec3_d using physic3_d = base_vec3_d; ///physic ray hit -struct physic_ray_hit -{ +struct physic_ray_hit { bool is_hit{false}; float hit_distance{0.0F}; guid_t hit_obj_id{0U}; @@ -69,8 +66,7 @@ struct physic_ray_hit }; ///physic trigger pair -struct physic_trigger_pair -{ +struct physic_trigger_pair { guid_t trigger_obj_id{0U}; guid_t other_obj_id{0U}; }; @@ -78,8 +74,7 @@ struct physic_trigger_pair ///call back function using trigger_call_back_function = std::function; -class physic_module : public module -{ +class physic_module : public module { public: ///create a new scene virtual guid_t create_scene(const std::string& scene_id) = 0; diff --git a/src/plugins/physic/physic_module_impl.cpp b/src/plugins/physic/physic_module_impl.cpp index b5fa3af58..ae73c09a0 100644 --- a/src/plugins/physic/physic_module_impl.cpp +++ b/src/plugins/physic/physic_module_impl.cpp @@ -25,8 +25,7 @@ namespace ark { #define SAFE_RELEASE(x) \ - if (x) \ - { \ + if (x) { \ x->release(); \ x = NULL; \ } @@ -44,8 +43,7 @@ bool physic_module_impl::init() { bool physic_module_impl::shut() { cooked_scene_list_.clear(); - for (auto& iter : scene_list_) - { + for (auto& iter : scene_list_) { SAFE_RELEASE(iter.second); } scene_list_.clear(); @@ -65,15 +63,13 @@ bool physic_module_impl::shut() { bool physic_module_impl::post_init() { ///store physic config config_ = physic_config_module_->get_physic_config(); - if (config_.step <= 0.0001) - { + if (config_.step <= 0.0001) { ARK_LOG_ERROR("physic simulate step <= 0"); exit(0); } ///init physic - if (!init_physic()) - { + if (!init_physic()) { ARK_LOG_ERROR("physic init failed"); exit(0); } @@ -81,19 +77,16 @@ bool physic_module_impl::post_init() { ///cook mesh cooked_scene_list_.clear(); auto& scene_list = physic_config_module_->get_physic_scene_list(); - for (auto& iter : scene_list) - { + for (auto& iter : scene_list) { auto& scene = iter.second; - if (!cook_scene_mesh(scene)) - { + if (!cook_scene_mesh(scene)) { ARK_LOG_ERROR("cook physic scene failed scene id = {}", scene.scene_id); exit(0); } } ///add simulate timer - if (config_.simulate) - { + if (config_.simulate) { std::chrono::milliseconds interval((int)(config_.step * 1000)); timer_module_->add_forever_timer(guid_t(), interval, this, &physic_module_impl::on_simulate); } @@ -103,16 +96,14 @@ bool physic_module_impl::post_init() { guid_t physic_module_impl::create_scene(const std::string& scene_id) { physic_scene_cooked scene_cooked; - if (!find_physic_scene(scene_id, scene_cooked)) - { + if (!find_physic_scene(scene_id, scene_cooked)) { ARK_LOG_ERROR("create scene failed scene id = {}", scene_id); return null_guid; } ///generate guid auto guid = guid_module_->create_guid(); - if (guid == null_guid) - { + if (guid == null_guid) { ARK_LOG_ERROR("create scene failed scene id = {}", scene_id); return null_guid; } @@ -125,14 +116,12 @@ guid_t physic_module_impl::create_scene(const std::string& scene_id) { scene_desc.filterShader = physx::PxDefaultSimulationFilterShader; auto px_scene = physics_->createScene(scene_desc); - if (px_scene == nullptr) - { + if (px_scene == nullptr) { ARK_LOG_ERROR("create scene failed"); return null_guid; } - if (!init_scene(px_scene, scene_cooked)) - { + if (!init_scene(px_scene, scene_cooked)) { ARK_LOG_ERROR("init scene failed scene"); SAFE_RELEASE(px_scene) return null_guid; @@ -150,8 +139,7 @@ guid_t physic_module_impl::create_scene(const std::string& scene_id) { bool physic_module_impl::destroy_scene(const guid_t& scene_obj_id) { ///check whether the particular scene exists auto px_scene = find_scene(scene_obj_id); - if (px_scene == nullptr) - { + if (px_scene == nullptr) { ARK_LOG_ERROR("scene does not exist"); return false; } @@ -169,11 +157,9 @@ bool physic_module_impl::ray_cast(const guid_t& scene_obj_id, const physic3_d& o physx::PxRaycastBuffer px_ray_hit; auto result = ray_cast(scene_obj_id, px_origin, px_direction, distance, px_ray_hit); - if (result) - { + if (result) { auto hit_actor = px_ray_hit.block.actor; - if (hit_actor && hit_actor->userData) - { + if (hit_actor && hit_actor->userData) { ray_hit.hit_obj_id = reinterpret_cast(hit_actor->userData); } @@ -188,15 +174,13 @@ bool physic_module_impl::ray_cast(const guid_t& scene_obj_id, const physic3_d& o bool physic_module_impl::ray_cast(const guid_t& scene_obj_id, const physx::PxVec3& origin, const physx::PxVec3& direction, const float distance, physx::PxRaycastBuffer& ray_hit) { auto px_scene = find_scene(scene_obj_id); - if (px_scene == nullptr) - { + if (px_scene == nullptr) { ARK_LOG_ERROR("this scene does not exist"); return false; } auto normal_dir = direction; - if (!normal_dir.isNormalized()) - { + if (!normal_dir.isNormalized()) { normal_dir = normal_dir.getNormalized(); } @@ -206,8 +190,7 @@ bool physic_module_impl::ray_cast(const guid_t& scene_obj_id, const physx::PxVec guid_t physic_module_impl::create_dynamic_box_actor( const guid_t& scene_obj_id, const physic3_d& position, const physic3_d& size) { auto px_scene = find_scene(scene_obj_id); - if (px_scene == nullptr) - { + if (px_scene == nullptr) { ARK_LOG_ERROR("this scene does not exist"); return null_guid; } @@ -223,8 +206,7 @@ guid_t physic_module_impl::create_dynamic_box_actor( guid_t physic_module_impl::create_static_box_actor( const guid_t& scene_obj_id, const physic3_d& position, const physic3_d& size) { auto px_scene = find_scene(scene_obj_id); - if (px_scene == nullptr) - { + if (px_scene == nullptr) { ARK_LOG_ERROR("this scene does not exist"); return null_guid; } @@ -240,8 +222,7 @@ guid_t physic_module_impl::create_static_box_actor( guid_t physic_module_impl::create_dynamic_capsule_actor( const guid_t& scene_obj_id, const physic3_d& position, const float radius, const float height) { auto px_scene = find_scene(scene_obj_id); - if (px_scene == nullptr) - { + if (px_scene == nullptr) { ARK_LOG_ERROR("this scene does not exist"); return null_guid; } @@ -257,8 +238,7 @@ guid_t physic_module_impl::create_dynamic_capsule_actor( guid_t physic_module_impl::create_static_capsule_actor( const guid_t& scene_obj_id, const physic3_d& position, const float radius, const float height) { auto px_scene = find_scene(scene_obj_id); - if (px_scene == nullptr) - { + if (px_scene == nullptr) { ARK_LOG_ERROR("this scene does not exist scene id={} index={}"); return null_guid; } @@ -274,8 +254,7 @@ guid_t physic_module_impl::create_static_capsule_actor( guid_t physic_module_impl::create_dynamic_sphere_actor( const guid_t& scene_obj_id, const physic3_d& position, const float radius) { auto px_scene = find_scene(scene_obj_id); - if (px_scene == nullptr) - { + if (px_scene == nullptr) { ARK_LOG_ERROR("this scene does not exist"); return null_guid; } @@ -290,8 +269,7 @@ guid_t physic_module_impl::create_dynamic_sphere_actor( guid_t physic_module_impl::create_static_sphere_actor( const guid_t& scene_obj_id, const physic3_d& position, const float radius) { auto px_scene = find_scene(scene_obj_id); - if (px_scene == nullptr) - { + if (px_scene == nullptr) { ARK_LOG_ERROR("this scene does not exist"); return null_guid; } @@ -308,8 +286,7 @@ guid_t physic_module_impl::create_dynamic_actor( SCENE_WRITE_LOCK(px_scene); auto actor = create_dynamic(transform, geometry, *material_); - if (actor == nullptr) - { + if (actor == nullptr) { ARK_LOG_ERROR("create actor failed"); return null_guid; } @@ -328,8 +305,7 @@ guid_t physic_module_impl::create_static_actor( SCENE_WRITE_LOCK(px_scene); auto actor = create_static(transform, geometry, *material_); - if (actor == nullptr) - { + if (actor == nullptr) { ARK_LOG_ERROR("create actor failed"); return null_guid; } @@ -345,22 +321,19 @@ guid_t physic_module_impl::create_static_actor( bool physic_module_impl::update_actor(const guid_t& actor_obj_id, const physic3_d& position) { auto actor = find_actor(actor_obj_id); - if (actor == nullptr) - { + if (actor == nullptr) { ARK_LOG_ERROR("actor does not exist actor id = {}", actor_obj_id); return false; } auto rigid_dynamic = actor->is(); - if (rigid_dynamic == nullptr) - { + if (rigid_dynamic == nullptr) { ARK_LOG_ERROR("actor can not be updated"); return false; } auto px_scene = actor->getScene(); - if (!px_scene) - { + if (!px_scene) { ARK_LOG_ERROR("scene is null"); return false; } @@ -371,12 +344,9 @@ bool physic_module_impl::update_actor(const guid_t& actor_obj_id, const physic3_ auto px_position = to_physx_vector(position); transform.p = px_position; - if (config_.simulate) - { + if (config_.simulate) { rigid_dynamic->setKinematicTarget(transform); - } - else - { + } else { rigid_dynamic->setGlobalPose(transform); } @@ -385,15 +355,13 @@ bool physic_module_impl::update_actor(const guid_t& actor_obj_id, const physic3_ bool physic_module_impl::destroy_actor(const guid_t& actor_obj_id) { auto actor = find_actor(actor_obj_id); - if (actor == nullptr) - { + if (actor == nullptr) { ARK_LOG_ERROR("actor does not exist actor id = {}", actor_obj_id); return false; } auto px_scene = actor->getScene(); - if (!px_scene) - { + if (!px_scene) { ARK_LOG_ERROR("scene is null"); return false; } @@ -408,15 +376,13 @@ bool physic_module_impl::destroy_actor(const guid_t& actor_obj_id) { bool physic_module_impl::get_actor_position(const guid_t& actor_obj_id, physic3_d& position) { auto actor = find_actor(actor_obj_id); - if (actor == nullptr) - { + if (actor == nullptr) { ARK_LOG_ERROR("actor does not exist actor id = {}", actor_obj_id); return false; } auto rigid_actor = actor->is(); - if (rigid_actor == nullptr) - { + if (rigid_actor == nullptr) { ARK_LOG_ERROR("actor does not exist actor id = {}", actor_obj_id); return false; } @@ -470,8 +436,7 @@ physic3_d physic_module_impl::ray_get_point(const physic3_d& origin, const physi auto px_direction = to_physx_vector(direction); auto normal_dir = px_direction; - if (!px_direction.isNormalized()) - { + if (!px_direction.isNormalized()) { normal_dir = px_direction.getNormalized(); } @@ -487,16 +452,14 @@ float physic_module_impl::get_height(const guid_t& scene_obj_id, const physic3_d physx::PxVec3 dir(0.0F, -1.0F, 0.0F); physx::PxRaycastBuffer ray_hit; auto result = ray_cast(scene_obj_id, px_position, dir, distance, ray_hit); - if (result) - { + if (result) { return ray_hit.block.position.y; } ///then ray cast up dir.y = -dir.y; result = ray_cast(scene_obj_id, px_position, dir, distance, ray_hit); - if (result) - { + if (result) { return ray_hit.block.position.y; } @@ -513,43 +476,34 @@ bool physic_module_impl::cook_scene_mesh(const physic_scene& scene) { ///cook terrain mesh auto terrain_mesh = create_triangle_mesh(scene); - if (terrain_mesh == nullptr) - { + if (terrain_mesh == nullptr) { ARK_LOG_ERROR("mesh is null"); return false; } scene_cooked.terrain_mesh = terrain_mesh; - for (auto& iter_collider : scene.colliders) - { + for (auto& iter_collider : scene.colliders) { auto collider = iter_collider; - if (collider->is_mesh_collider()) - { + if (collider->is_mesh_collider()) { ///cook scene object mesh auto mesh_collider = dynamic_cast(collider); - if (!mesh_collider) - { + if (!mesh_collider) { ARK_LOG_ERROR("mesh is null"); return false; } - if (mesh_collider->convex) - { + if (mesh_collider->convex) { auto collider_mesh = create_convex_mesh(mesh_collider); - if (!collider_mesh) - { + if (!collider_mesh) { ARK_LOG_ERROR("mesh is null"); return false; } scene_cooked.convex_colliders.insert(std::make_pair(collider_mesh, mesh_collider->position)); - } - else - { + } else { auto collider_mesh = create_triangle_mesh(mesh_collider); - if (!collider_mesh) - { + if (!collider_mesh) { ARK_LOG_ERROR("mesh is null"); return false; } @@ -573,8 +527,7 @@ bool physic_module_impl::cook_scene_mesh(const physic_scene& scene) { bool physic_module_impl::find_physic_scene(const std::string& scene_id, physic_scene_cooked& scene_cooked) { auto iter = cooked_scene_list_.find(scene_id); - if (iter == cooked_scene_list_.end()) - { + if (iter == cooked_scene_list_.end()) { return false; } @@ -637,8 +590,7 @@ void physic_module_impl::create_pvd_connection() { #if PX_SUPPORT_PVD pvd_transport_ = physx::PxDefaultPvdSocketTransportCreate(config_.pvd_host.c_str(), config_.pvd_port, config_.pvd_timeout); - if (pvd_transport_ == nullptr) - { + if (pvd_transport_ == nullptr) { ARK_LOG_ERROR("create pvd socket failed"); return; } @@ -650,8 +602,7 @@ void physic_module_impl::create_pvd_connection() { bool physic_module_impl::init_scene(physx::PxScene* px_scene, const physic_scene_cooked& scene_cooked) { auto& scene = *scene_cooked.scene; - if (!scene_cooked.terrain_mesh) - { + if (!scene_cooked.terrain_mesh) { ARK_LOG_ERROR("scene terrain mesh do not exist scene id = {}", scene.scene_id); return false; } @@ -668,22 +619,18 @@ bool physic_module_impl::init_scene(physx::PxScene* px_scene, const physic_scene px_scene->addActor(*terrain_actor); ///create actors - for (const auto& iter : scene_cooked.colliders) - { + for (const auto& iter : scene_cooked.colliders) { const auto collider = iter; auto actor = create_static(collider); - if (!actor) - { + if (!actor) { ARK_LOG_ERROR("create actor failed scene id={} file={}", scene.scene_id, scene.mesh_file.path); continue; } - if (collider->trigger) - { + if (collider->trigger) { physx::PxShape* shape = nullptr; actor->getShapes(&shape, 1); - if (shape) - { + if (shape) { shape->setFlag(physx::PxShapeFlag::eSIMULATION_SHAPE, false); shape->setFlag(physx::PxShapeFlag::eTRIGGER_SHAPE, true); } @@ -693,20 +640,17 @@ bool physic_module_impl::init_scene(physx::PxScene* px_scene, const physic_scene } ///create triangle actors - for (const auto& iter : scene_cooked.triangle_colliders) - { + for (const auto& iter : scene_cooked.triangle_colliders) { auto mesh = iter.first; auto& position = iter.second; - if (!mesh) - { + if (!mesh) { ARK_LOG_ERROR("create actor failed scene id={}", scene.scene_id); continue; } auto geometry = physx::PxTriangleMeshGeometry(mesh); auto actor = create_static(physx::PxTransform(position), geometry, *material_); - if (!actor) - { + if (!actor) { ARK_LOG_ERROR("create actor failed scene id={} file={}", scene.scene_id); continue; } @@ -715,20 +659,17 @@ bool physic_module_impl::init_scene(physx::PxScene* px_scene, const physic_scene } ///create convex actors - for (const auto& iter : scene_cooked.convex_colliders) - { + for (const auto& iter : scene_cooked.convex_colliders) { auto mesh = iter.first; auto& position = iter.second; - if (!mesh) - { + if (!mesh) { ARK_LOG_ERROR("create actor failed scene id={}", scene.scene_id); continue; } auto geometry = physx::PxConvexMeshGeometry(mesh); auto actor = create_static(physx::PxTransform(position), geometry, *material_); - if (!actor) - { + if (!actor) { ARK_LOG_ERROR("create actor failed scene id={} file={}", scene.scene_id); continue; } @@ -740,17 +681,14 @@ bool physic_module_impl::init_scene(physx::PxScene* px_scene, const physic_scene } physx::PxRigidStatic* physic_module_impl::create_static(collider* collider) { - if (collider == nullptr) - { + if (collider == nullptr) { ARK_LOG_ERROR("collider is null"); return nullptr; } - if (collider->is_box_collider()) - { + if (collider->is_box_collider()) { auto real_collider = dynamic_cast(collider); - if (real_collider == nullptr) - { + if (real_collider == nullptr) { ARK_LOG_ERROR("collider to BoxCollider failed"); return nullptr; } @@ -759,12 +697,9 @@ physx::PxRigidStatic* physic_module_impl::create_static(collider* collider) { physx::PxBoxGeometry geometry(half); auto transform = physx::PxTransform(real_collider->position); return create_static(transform, geometry, *material_); - } - else if (collider->is_capsule_collider()) - { + } else if (collider->is_capsule_collider()) { auto real_collider = dynamic_cast(collider); - if (real_collider == nullptr) - { + if (real_collider == nullptr) { ARK_LOG_ERROR("collider to CapsuleCollider failed"); return nullptr; } @@ -774,12 +709,9 @@ physx::PxRigidStatic* physic_module_impl::create_static(collider* collider) { physx::PxCapsuleGeometry geometry(real_collider->radius, real_collider->height * 0.5F); return create_static(transform, geometry, *material_); - } - else if (collider->is_sphere_collider()) - { + } else if (collider->is_sphere_collider()) { auto real_collider = dynamic_cast(collider); - if (real_collider == nullptr) - { + if (real_collider == nullptr) { ARK_LOG_ERROR("collider to SphereCollider failed"); return nullptr; } @@ -794,15 +726,13 @@ physx::PxRigidStatic* physic_module_impl::create_static(collider* collider) { physx::PxRigidStatic* physic_module_impl::create_static(const physx::PxTransform& transform, const physx::PxGeometry& geometry, physx::PxMaterial& material, const physx::PxTransform& shape_offset) { - if (!transform.isValid() || !shape_offset.isValid()) - { + if (!transform.isValid() || !shape_offset.isValid()) { ARK_LOG_ERROR("transform invalid"); return nullptr; } auto shape = physics_->createShape(geometry, material, true); - if (!shape) - { + if (!shape) { ARK_LOG_ERROR("createa shape failed"); return nullptr; } @@ -810,8 +740,7 @@ physx::PxRigidStatic* physic_module_impl::create_static(const physx::PxTransform shape->setLocalPose(shape_offset); auto actor = physics_->createRigidStatic(transform); - if (actor) - { + if (actor) { actor->attachShape(*shape); } @@ -822,15 +751,13 @@ physx::PxRigidStatic* physic_module_impl::create_static(const physx::PxTransform physx::PxRigidDynamic* physic_module_impl::create_dynamic(const physx::PxTransform& transform, const physx::PxGeometry& geometry, physx::PxMaterial& material, float density, const physx::PxTransform& shape_offset) { - if (!transform.isValid() || !shape_offset.isValid()) - { + if (!transform.isValid() || !shape_offset.isValid()) { ARK_LOG_ERROR("transform invalid"); return nullptr; } auto shape = physics_->createShape(geometry, material, true); - if (!shape) - { + if (!shape) { ARK_LOG_ERROR("createa shape failed"); return nullptr; } @@ -838,13 +765,11 @@ physx::PxRigidDynamic* physic_module_impl::create_dynamic(const physx::PxTransfo shape->setLocalPose(shape_offset); auto actor = physics_->createRigidDynamic(transform); - if (actor) - { + if (actor) { actor->attachShape(*shape); physx::PxRigidBodyExt::updateMassAndInertia(*actor, density); - if (config_.simulate) - { + if (config_.simulate) { actor->setRigidBodyFlag(physx::PxRigidBodyFlag::eKINEMATIC, true); } } @@ -857,17 +782,14 @@ physx::PxTriangleMesh* physic_module_impl::create_triangle_mesh(const physic_mes physx::PxTriangleMesh* mesh = nullptr; physx::PxDefaultFileInputData file(mesh_file.cooked_path.c_str()); - if (file.isValid()) - { + if (file.isValid()) { mesh = physics_->createTriangleMesh(file); } - if (!mesh) - { + if (!mesh) { ///need cook wave_front_obj wfo; - if (wfo.LoadObj(mesh_file.path.c_str(), false) == 0) - { + if (wfo.LoadObj(mesh_file.path.c_str(), false) == 0) { ARK_LOG_ERROR("load file failed file={}", mesh_file.path); return nullptr; } @@ -881,20 +803,17 @@ physx::PxTriangleMesh* physic_module_impl::create_triangle_mesh(const physic_mes mesh_desc.triangles.data = wfo.mIndices; file_output_stream out_file(mesh_file.cooked_path.c_str()); - if (!out_file.valid()) - { + if (!out_file.valid()) { ARK_LOG_ERROR("load file failed file={}", mesh_file.cooked_path); return nullptr; } bool result = cooking_->cookTriangleMesh(mesh_desc, out_file); - if (result) - { + if (result) { out_file.release(); physx::PxDefaultFileInputData cooked_file(mesh_file.cooked_path.c_str()); - if (!cooked_file.isValid()) - { + if (!cooked_file.isValid()) { ARK_LOG_ERROR("load file failed file={}", mesh_file.cooked_path); return nullptr; } @@ -910,8 +829,7 @@ physx::PxTriangleMesh* physic_module_impl::create_triangle_mesh(const physic_sce auto& mesh_file = scene_config.mesh_file; wave_front_obj wfo; - if (wfo.LoadObj(mesh_file.path.c_str(), false) == 0) - { + if (wfo.LoadObj(mesh_file.path.c_str(), false) == 0) { ARK_LOG_ERROR("load file failed file={}", mesh_file.path); return nullptr; } @@ -926,8 +844,7 @@ physx::PxTriangleMesh* physic_module_impl::create_triangle_mesh(const physic_sce physx::PxTriangleMeshCookingResult::Enum result{physx::PxTriangleMeshCookingResult::eFAILURE}; auto mesh = cooking_->createTriangleMesh(mesh_desc, physics_->getPhysicsInsertionCallback(), &result); - if (result != physx::PxTriangleMeshCookingResult::eSUCCESS) - { + if (result != physx::PxTriangleMeshCookingResult::eSUCCESS) { ARK_LOG_WARN("triangle mesh is too big scene ={}", mesh_file.path); } @@ -935,8 +852,7 @@ physx::PxTriangleMesh* physic_module_impl::create_triangle_mesh(const physic_sce } physx::PxTriangleMesh* physic_module_impl::create_triangle_mesh(mesh_collider* collider) { - if (collider->vertex_count == 0 || !collider->vertices || collider->triangle_count == 0 || !collider->triangles) - { + if (collider->vertex_count == 0 || !collider->vertices || collider->triangle_count == 0 || !collider->triangles) { ARK_LOG_ERROR("mesh collider do not have vertices"); return nullptr; } @@ -954,8 +870,7 @@ physx::PxTriangleMesh* physic_module_impl::create_triangle_mesh(mesh_collider* c } physx::PxConvexMesh* physic_module_impl::create_convex_mesh(mesh_collider* collider) { - if (collider->vertex_count == 0 || !collider->vertices) - { + if (collider->vertex_count == 0 || !collider->vertices) { ARK_LOG_ERROR("mesh collider do not have vertices"); return nullptr; } @@ -972,8 +887,7 @@ physx::PxConvexMesh* physic_module_impl::create_convex_mesh(mesh_collider* colli void physic_module_impl::scene_pvd_setting(physx::PxScene* px_scene) { auto pvd_client = px_scene->getScenePvdClient(); - if (pvd_client) - { + if (pvd_client) { pvd_client->setScenePvdFlags(physx::PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS | physx::PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES | physx::PxPvdSceneFlag::eTRANSMIT_CONTACTS); @@ -990,11 +904,9 @@ void physic_module_impl::quat_roate(physx::PxTransform& transform) { } void physic_module_impl::on_simulate(uint64_t timer_id, const guid_t& guid) { - for (auto& iter : scene_list_) - { + for (auto& iter : scene_list_) { auto px_scene = iter.second; - if (!px_scene) - { + if (!px_scene) { continue; } @@ -1008,8 +920,7 @@ void physic_module_impl::on_simulate(uint64_t timer_id, const guid_t& guid) { physx::PxScene* physic_module_impl::find_scene(const guid_t& scene_obj_id) { auto iter = scene_list_.find(scene_obj_id); - if (iter == scene_list_.end()) - { + if (iter == scene_list_.end()) { return nullptr; } @@ -1018,8 +929,7 @@ physx::PxScene* physic_module_impl::find_scene(const guid_t& scene_obj_id) { physx::PxActor* physic_module_impl::find_actor(const guid_t& actor_obj_id) { auto iter = actor_list_.find(actor_obj_id); - if (iter == actor_list_.end()) - { + if (iter == actor_list_.end()) { return nullptr; } diff --git a/src/plugins/physic/physic_module_impl.hpp b/src/plugins/physic/physic_module_impl.hpp index 3f102a669..2b47a74a9 100644 --- a/src/plugins/physic/physic_module_impl.hpp +++ b/src/plugins/physic/physic_module_impl.hpp @@ -29,32 +29,27 @@ namespace ark { -class simulation_event_callback final : public physx::PxSimulationEventCallback -{ +class simulation_event_callback final : public physx::PxSimulationEventCallback { public: void onContact(const physx::PxContactPairHeader& pair_header, const physx::PxContactPair* pairs, physx::PxU32 nb_pairs) override {}; void onTrigger(physx::PxTriggerPair* pairs, physx::PxU32 count) override { - for (physx::PxU32 i = 0; i < count; i++) - { + for (physx::PxU32 i = 0; i < count; i++) { // ignore pairs when shapes have been deleted auto& one_pair = pairs[i]; if (one_pair.flags & - (physx::PxTriggerPairFlag::eREMOVED_SHAPE_TRIGGER | physx::PxTriggerPairFlag::eREMOVED_SHAPE_OTHER)) - { + (physx::PxTriggerPairFlag::eREMOVED_SHAPE_TRIGGER | physx::PxTriggerPairFlag::eREMOVED_SHAPE_OTHER)) { continue; } auto actor_trigger = one_pair.triggerActor; - if (!actor_trigger || !actor_trigger->userData) - { + if (!actor_trigger || !actor_trigger->userData) { continue; } auto px_scene = actor_trigger->getScene(); - if (!px_scene || !px_scene->userData) - { + if (!px_scene || !px_scene->userData) { continue; } @@ -62,13 +57,11 @@ class simulation_event_callback final : public physx::PxSimulationEventCallback physic_trigger_pair trigger_pair; trigger_pair.trigger_obj_id = reinterpret_cast(actor_trigger->userData); - if (one_pair.otherActor && one_pair.otherActor->userData) - { + if (one_pair.otherActor && one_pair.otherActor->userData) { trigger_pair.other_obj_id = reinterpret_cast(one_pair.otherActor->userData); } - for (auto& iter : trigger_cb_list_) - { + for (auto& iter : trigger_cb_list_) { iter(scene_obj_id, trigger_pair); } } @@ -95,8 +88,7 @@ class simulation_event_callback final : public physx::PxSimulationEventCallback trigger_cb_list trigger_cb_list_; }; -class file_output_stream : public physx::PxOutputStream -{ +class file_output_stream : public physx::PxOutputStream { public: file_output_stream(const std::string& name) { physic::open_file(&file_, name.c_str(), "wb"); @@ -115,8 +107,7 @@ class file_output_stream : public physx::PxOutputStream } void release() { - if (file_) - { + if (file_) { fclose(file_); file_ = nullptr; } @@ -127,8 +118,7 @@ class file_output_stream : public physx::PxOutputStream }; ///physic scene -class physic_scene_cooked -{ +class physic_scene_cooked { public: ~physic_scene_cooked() { scene = nullptr; @@ -145,8 +135,7 @@ class physic_scene_cooked std::map convex_colliders; }; -class physic_module_impl final : public physic_module -{ +class physic_module_impl final : public physic_module { ARK_DECLARE_MODULE_FUNCTIONS public: bool init() override; diff --git a/src/plugins/physic/physic_resources.cpp b/src/plugins/physic/physic_resources.cpp index 7255d1cf6..ed87f9bc4 100644 --- a/src/plugins/physic/physic_resources.cpp +++ b/src/plugins/physic/physic_resources.cpp @@ -21,29 +21,25 @@ std::uint32_t unsigned_setting( const toml::node_view& node, const std::string& path, const std::string& field) { const auto value = node.value(); if (!node.is_integer() || !value || *value < 0 || - static_cast(*value) > std::numeric_limits::max()) - { + static_cast(*value) > std::numeric_limits::max()) { fail(path, field, "expected an unsigned 32-bit integer"); } return static_cast(*value); } float number(const nlohmann::json& value, const std::string& path, const std::string& field) { - if (!value.is_number()) - { + if (!value.is_number()) { fail(path, field, "expected a finite number"); } const auto result = value.get(); - if (!std::isfinite(result) || std::abs(result) > std::numeric_limits::max()) - { + if (!std::isfinite(result) || std::abs(result) > std::numeric_limits::max()) { fail(path, field, "number exceeds the finite float range"); } return static_cast(result); } std::array vector(const nlohmann::json& value, const std::string& path, const std::string& field) { - if (!value.is_array() || value.size() != 3) - { + if (!value.is_array() || value.size() != 3) { fail(path, field, "expected three coordinates"); } return {number(value[0], path, field), number(value[1], path, field), number(value[2], path, field)}; @@ -56,21 +52,18 @@ settings read_settings(const std::string& path) { settings result; const auto simulate = table["simulate"].value(); const auto host = table["debugger"]["host"].value(); - if (!simulate || !host || host->find('\0') != std::string::npos) - { + if (!simulate || !host || host->find('\0') != std::string::npos) { fail(path, "settings", "expected simulate boolean and debugger.host string"); } result.simulate = *simulate; result.dispatcher_threads = unsigned_setting(table["dispatcher_threads"], path, "dispatcher_threads"); result.frequency_hz = unsigned_setting(table["frequency_hz"], path, "frequency_hz"); - if (result.frequency_hz == 0) - { + if (result.frequency_hz == 0) { fail(path, "frequency_hz", "must be positive"); } result.debugger_host = *host; const auto port = unsigned_setting(table["debugger"]["port"], path, "debugger.port"); - if (port > std::numeric_limits::max()) - { + if (port > std::numeric_limits::max()) { fail(path, "debugger.port", "exceeds the port range"); } result.debugger_port = static_cast(port); @@ -79,30 +72,23 @@ settings read_settings(const std::string& path) { } std::vector read_colliders(const std::string& path) { - try - { + try { const auto document = nlohmann::json::parse(config_detail::read_file(path, "collider JSON")); if (!document.is_object() || !document.at("version").is_number_integer() || document.at("version") != 1 || - !document.at("colliders").is_array()) - { + !document.at("colliders").is_array()) { fail(path, "/", "expected version 1 and a colliders array"); } std::vector result; - for (const auto& entry : document.at("colliders")) - { + for (const auto& entry : document.at("colliders")) { const auto field = "/colliders/" + std::to_string(result.size()); collider value; const auto type = entry.at("type").get(); value.position = vector(entry.at("position"), path, field + "/position"); - if (type == "terrain") - { + if (type == "terrain") { value.type = collider_type::terrain; - } - else - { + } else { value.trigger = entry.at("trigger").get(); - if (type == "mesh") - { + if (type == "mesh") { value.type = collider_type::mesh; value.convex = entry.at("convex").get(); const auto& vertices = entry.at("vertices"); @@ -110,60 +96,46 @@ std::vector read_colliders(const std::string& path) { if (!vertices.is_array() || vertices.empty() || vertices.size() > std::numeric_limits::max() || !triangles.is_array() || triangles.empty() || triangles.size() % 3 != 0 || - triangles.size() > std::numeric_limits::max()) - { + triangles.size() > std::numeric_limits::max()) { fail(path, field, "expected bounded vertices and triangle indices"); } - for (const auto& vertex : vertices) - { + for (const auto& vertex : vertices) { value.vertices.push_back(vector(vertex, path, field + "/vertices")); } - for (const auto& index : triangles) - { - if (!index.is_number_integer() || index < 0 || index >= value.vertices.size()) - { + for (const auto& index : triangles) { + if (!index.is_number_integer() || index < 0 || index >= value.vertices.size()) { fail(path, field + "/triangles", "index is outside the vertices array"); } value.triangles.push_back(index.get()); } - } - else if (type == "box" || type == "capsule" || type == "sphere") - { + } else if (type == "box" || type == "capsule" || type == "sphere") { value.center = vector(entry.at("center"), path, field + "/center"); - if (type == "box") - { + if (type == "box") { value.type = collider_type::box; value.size = vector(entry.at("size"), path, field + "/size"); - } - else - { + } else { value.type = type == "capsule" ? collider_type::capsule : collider_type::sphere; value.radius = number(entry.at("radius"), path, field + "/radius"); - if (value.radius < 0) - { + if (value.radius < 0) { fail(path, field + "/radius", "must not be negative"); } - if (type == "capsule") - { + if (type == "capsule") { value.height = number(entry.at("height"), path, field + "/height"); - if (value.height < 0) - { + if (value.height < 0) { fail(path, field + "/height", "must not be negative"); } } } - } - else - { + } else { fail(path, field + "/type", "unknown collider type"); } } result.push_back(std::move(value)); } return result; + } catch (const nlohmann::json::exception& error) { + fail(path, "/", error.what()); } - catch (const nlohmann::json::exception& error) - { fail(path, "/", error.what()); } } } // namespace ark::physic_resources diff --git a/src/plugins/physic/physic_resources.hpp b/src/plugins/physic/physic_resources.hpp index 20edfafc2..dc7e31b9a 100644 --- a/src/plugins/physic/physic_resources.hpp +++ b/src/plugins/physic/physic_resources.hpp @@ -8,8 +8,7 @@ namespace ark::physic_resources { -struct settings -{ +struct settings { bool simulate{}; std::uint32_t dispatcher_threads{}; std::uint32_t frequency_hz{}; @@ -18,8 +17,7 @@ struct settings std::uint32_t debugger_timeout_ms{}; }; -enum class collider_type -{ +enum class collider_type { box, capsule, sphere, @@ -27,8 +25,7 @@ enum class collider_type terrain }; -struct collider -{ +struct collider { collider_type type{}; std::array position{}; std::array center{}; diff --git a/src/plugins/redis/detail/redis_awaitable.hpp b/src/plugins/redis/detail/redis_awaitable.hpp index 4be7d1086..0024add75 100644 --- a/src/plugins/redis/detail/redis_awaitable.hpp +++ b/src/plugins/redis/detail/redis_awaitable.hpp @@ -26,12 +26,9 @@ module_task redis_command(service_type& service, return service.start( std::move(command), [completion = std::move(completion)](redis_service_result result) mutable { - if (auto* error = std::get_if(&result)) - { + if (auto* error = std::get_if(&result)) { completion(*error, {}); - } - else - { + } else { completion({}, std::get(std::move(result))); } }, @@ -49,12 +46,9 @@ module_task redis_pipeline(service_type& service, return service.start_pipeline( std::move(commands), [completion = std::move(completion)](redis_service_result result) mutable { - if (auto* error = std::get_if(&result)) - { + if (auto* error = std::get_if(&result)) { completion(*error, {}); - } - else - { + } else { completion({}, std::get(std::move(result))); } }, diff --git a/src/plugins/redis/detail/redis_service.hpp b/src/plugins/redis/detail/redis_service.hpp index e1756229c..c4546c975 100644 --- a/src/plugins/redis/detail/redis_service.hpp +++ b/src/plugins/redis/detail/redis_service.hpp @@ -35,22 +35,19 @@ inline arknet::redis::result redis_acquire_failure(acquire_type acquired) { } template -class basic_redis_service -{ +class basic_redis_service { using queue_type = completion_queue; using control_type = database_request_control; struct operation; - struct request_registry - { + struct request_registry { std::mutex mutex; std::unordered_map> active; std::uint64_t next_id{1}; database_service_diagnostics diagnostics; }; - struct operation : std::enable_shared_from_this - { + struct operation : std::enable_shared_from_this { control_type control; std::weak_ptr registry; std::uint64_t id{}; @@ -62,25 +59,17 @@ class basic_redis_service typename pool_type::lease lease; void forward_cancel(std::optional cancellation) { - if (cancellation) - { - try - { - if (cancellation->target == control_type::stage::acquire) - { + if (cancellation) { + try { + if (cancellation->target == control_type::stage::acquire) { pool->cancel(cancellation->id); - } - else - { + } else { lease.cancel(cancellation->id); } - } - catch (...) - { + } catch (...) { // Keep the actual command alive after a failed cancel post; // only its native reply/deadline can establish the outcome. - if (auto requests = registry.lock()) - { + if (auto requests = registry.lock()) { std::lock_guard lock(requests->mutex); requests->diagnostics.cancellation_submission = std::current_exception(); } @@ -95,29 +84,21 @@ class basic_redis_service } void erase_request() { - if (auto requests = registry.lock()) - { + if (auto requests = registry.lock()) { std::lock_guard lock(requests->mutex); requests->active.erase(id); } } void return_lease(bool discard = false) { - try - { - if (discard) - { + try { + if (discard) { lease.discard(); - } - else - { + } else { lease.release(); } - } - catch (...) - { - if (auto requests = registry.lock()) - { + } catch (...) { + if (auto requests = registry.lock()) { std::lock_guard lock(requests->mutex); requests->diagnostics.lease_return = std::current_exception(); } @@ -125,8 +106,7 @@ class basic_redis_service } void finish(redis_service_result result) { - if (!control.finish()) - { + if (!control.finish()) { return; } return_lease(); @@ -135,21 +115,18 @@ class basic_redis_service } void acquired(typename pool_type::acquire_result result) { - if (!result) - { + if (!result) { finish(redis_acquire_failure(std::move(result))); return; } lease = std::move(result.connection); - if (control.cancelled()) - { + if (control.cancelled()) { finish(arknet::redis::result{arknet::redis::client_errc::cancelled, {}, {}, false}); return; } const auto remaining = std::chrono::duration_cast(deadline - std::chrono::steady_clock::now()); - if (remaining <= std::chrono::milliseconds::zero()) - { + if (remaining <= std::chrono::milliseconds::zero()) { finish(arknet::redis::result{arknet::redis::client_errc::timeout, {}, {}, false}); return; } @@ -157,8 +134,7 @@ class basic_redis_service const auto native_id = lease.async_pipeline( std::move(commands), [self = this->shared_from_this(), submission](arknet::redis::result response) mutable { - if (self->control.complete(submission)) - { + if (self->control.complete(submission)) { self->finish(std::move(response)); } }, @@ -219,35 +195,28 @@ class basic_redis_service auto completion = std::move(incoming); auto handler = std::make_shared(std::move(completion)); redis_service_result rejected; - if (!arknet::detail::checked_deadline(std::chrono::steady_clock::now(), timeout)) - { + if (!arknet::detail::checked_deadline(std::chrono::steady_clock::now(), timeout)) { std::get(rejected).error = arknet::redis::client_errc::invalid_command; - } - else - { - try - { + } else { + try { const auto id = initiate( std::move(commands), [handler](redis_service_result result) { - if (*handler) - { + if (*handler) { (*handler)(std::move(result)); } }, timeout); - if (id) - { + if (id) { return id; } std::get(rejected).error = accepting_ ? arknet::redis::client_errc::queue_full : arknet::redis::client_errc::closed; + } catch (...) { + rejected = std::current_exception(); } - catch (...) - { rejected = std::current_exception(); } } - if (*handler) - { + if (*handler) { (*handler)(std::move(rejected)); } return 0; @@ -259,8 +228,7 @@ class basic_redis_service { std::lock_guard lock(requests_->mutex); const auto found = requests_->active.find(id); - if (found != requests_->active.end()) - { + if (found != requests_->active.end()) { pending = found->second.lock(); } } @@ -294,16 +262,13 @@ class basic_redis_service { std::lock_guard lock(requests_->mutex); pending.reserve(requests_->active.size()); - for (const auto& [id, weak] : requests_->active) - { - if (auto request = weak.lock()) - { + for (const auto& [id, weak] : requests_->active) { + if (auto request = weak.lock()) { pending.push_back(std::move(request)); } } } - for (const auto& request : pending) - { + for (const auto& request : pending) { request->cancel(); } } @@ -360,19 +325,16 @@ class basic_redis_service template bool retire_native(finalizer_type finalizer) { check_owner(); - if (!logically_drained()) - { + if (!logically_drained()) { return false; } auto activity = activity_; auto pool = pool_; - if (activity->native_retired) - { + if (activity->native_retired) { return true; } database_service_activity::guard active(activity); - if (!finalizer(*pool)) - { + if (!finalizer(*pool)) { return false; } activity->native_retired = true; @@ -380,8 +342,7 @@ class basic_redis_service } void check_owner() const { - if (std::this_thread::get_id() != owner_) - { + if (std::this_thread::get_id() != owner_) { throw std::logic_error("Database service must be used on its module thread"); } } @@ -392,42 +353,34 @@ class basic_redis_service database_service_activity::guard active(activity_); auto completion = std::move(incoming); const auto deadline = arknet::detail::checked_deadline(std::chrono::steady_clock::now(), timeout); - if (!deadline) - { + if (!deadline) { throw std::invalid_argument("Database operation timeout is not representable"); } std::size_t bytes{}; - for (const auto& command : commands) - { - if (command.capacity() > (std::numeric_limits::max() - bytes) / sizeof(std::string)) - { + for (const auto& command : commands) { + if (command.capacity() > (std::numeric_limits::max() - bytes) / sizeof(std::string)) { return false; } bytes += command.capacity() * sizeof(std::string); - for (const auto& argument : command) - { - if (argument.capacity() > std::numeric_limits::max() - bytes) - { + for (const auto& argument : command) { + if (argument.capacity() > std::numeric_limits::max() - bytes) { return false; } bytes += argument.capacity(); } } - if (commands.capacity() > (std::numeric_limits::max() - bytes) / sizeof(arknet::redis::command)) - { + if (commands.capacity() > (std::numeric_limits::max() - bytes) / sizeof(arknet::redis::command)) { return false; } bytes += commands.capacity() * sizeof(arknet::redis::command); auto ticket = completions_->admit(bytes, std::move(completion)); - if (!ticket) - { + if (!ticket) { return 0; } auto queue = completions_; auto requests = requests_; std::shared_ptr pending; - try - { + try { pending = std::make_shared(); pending->queue = queue; pending->ticket = ticket; @@ -437,8 +390,7 @@ class basic_redis_service pending->commands = std::move(commands); { std::lock_guard lock(requests->mutex); - if (!requests->next_id) - { + if (!requests->next_id) { throw std::overflow_error("Database request IDs exhausted"); } pending->id = requests->next_id++; @@ -446,33 +398,27 @@ class basic_redis_service } const auto acquire_remaining = std::chrono::duration_cast(*deadline - std::chrono::steady_clock::now()); - if (acquire_remaining <= std::chrono::milliseconds::zero()) - { + if (acquire_remaining <= std::chrono::milliseconds::zero()) { pending->finish(arknet::redis::result{arknet::redis::client_errc::timeout, {}, {}, false}); return pending->id; } const auto submission = pending->control.begin(control_type::stage::acquire); const auto native_id = pending->pool->async_acquire( [pending, submission](typename pool_type::acquire_result acquired) mutable { - if (!pending->control.complete(submission)) - { + if (!pending->control.complete(submission)) { return; } - try - { pending->acquired(std::move(acquired)); } - catch (...) - { + try { + pending->acquired(std::move(acquired)); + } catch (...) { pending->return_lease(true); pending->finish(std::current_exception()); } }, acquire_remaining); pending->forward_cancel(pending->control.publish(submission, native_id)); - } - catch (...) - { - if (pending) - { + } catch (...) { + if (pending) { pending->control.finish(); pending->erase_request(); } diff --git a/src/plugins/redis/redis_module.cpp b/src/plugins/redis/redis_module.cpp index 280edd901..7563ff210 100644 --- a/src/plugins/redis/redis_module.cpp +++ b/src/plugins/redis/redis_module.cpp @@ -11,8 +11,7 @@ namespace ark { -class redis_module_impl final : public module_base -{ +class redis_module_impl final : public module_base { public: redis_module_impl(); ~redis_module_impl() override; @@ -35,8 +34,7 @@ class redis_module_impl final : public module_base void ensure_state(); }; -struct redis_module_impl::state -{ +struct redis_module_impl::state { using service_type = std::variant #if defined(ARKNET_ENABLE_SSL) , @@ -44,28 +42,23 @@ struct redis_module_impl::state #endif >; - struct connection - { + struct connection { detail::database_awaitable bridge; service_type service; connection(std::shared_ptr runtime, redis_options options) : bridge(std::move(runtime), options.max_operations) { - if (!options.max_input_bytes) - { + if (!options.max_input_bytes) { throw std::invalid_argument("Redis input byte limit must be positive"); } - if (options.tls) - { + if (options.tls) { #if defined(ARKNET_ENABLE_SSL) service = std::make_unique( std::move(options.pool), options.max_operations, options.max_input_bytes); #else throw std::invalid_argument("Redis TLS requires ARKNET_ENABLE_SSL"); #endif - } - else - { + } else { service = std::make_unique( std::move(options.pool), options.max_operations, options.max_input_bytes); } @@ -82,8 +75,7 @@ struct redis_module_impl::state } void check_owner() const { - if (owner != std::this_thread::get_id()) - { + if (owner != std::this_thread::get_id()) { throw std::logic_error("Redis module requires its owner thread"); } } @@ -97,8 +89,7 @@ struct redis_module_impl::state static task missing(std::shared_ptr pinned) { const auto executor = co_await asio::this_coro::executor; - if (!detail::is_database_executor(executor, *pinned->runtime)) - { + if (!detail::is_database_executor(executor, *pinned->runtime)) { throw std::logic_error("Redis operation requires its manager task executor"); } pinned->check_owner(); @@ -117,11 +108,9 @@ redis_module_impl::redis_module_impl() = default; redis_module_impl::~redis_module_impl() = default; void redis_module_impl::ensure_state() { - if (!state_) - { + if (!state_) { auto* manager = get_plugin_manager(); - if (!manager) - { + if (!manager) { throw std::logic_error("Redis module requires an installed plugin manager"); } state_ = std::make_shared(manager->get_task_runtime()); @@ -137,27 +126,21 @@ bool redis_module_impl::init() { bool redis_module_impl::configure(std::string name, redis_options options) { ensure_state(); if (!state_->accepting || state_->connections.contains(name) || - get_plugin_manager()->get_shutdown_state() != plugin_manager::shutdown_state::running) - { + get_plugin_manager()->get_shutdown_state() != plugin_manager::shutdown_state::running) { return false; } - if (name.empty()) - { + if (name.empty()) { throw std::invalid_argument("Redis connection name must not be empty"); } // Allocate the destination node and buckets before starting native IO. auto [entry, inserted] = state_->connections.try_emplace(std::move(name), nullptr); - if (!inserted) - { + if (!inserted) { return false; } - try - { + try { auto connection = std::make_shared(state_->runtime, std::move(options)); entry->second = std::move(connection); - } - catch (...) - { + } catch (...) { // This unpublished entry is still empty; preserve same-name retry. state_->connections.erase(entry); throw; @@ -169,8 +152,7 @@ task redis_module_impl::command( std::string name, arknet::redis::command command, std::chrono::milliseconds timeout) { ensure_state(); const auto found = state_->connections.find(name); - if (found == state_->connections.end()) - { + if (found == state_->connections.end()) { return state::missing(state_); } auto pinned = found->second; @@ -183,8 +165,7 @@ task redis_module_impl::pipeline( std::string name, std::vector commands, std::chrono::milliseconds timeout) { ensure_state(); const auto found = state_->connections.find(name); - if (found == state_->connections.end()) - { + if (found == state_->connections.end()) { return state::missing(state_); } auto pinned = found->second; @@ -194,11 +175,9 @@ task redis_module_impl::pipeline( } bool redis_module_impl::update() { - if (state_) - { + if (state_) { state_->check_owner(); - for (const auto& [name, connection] : state_->connections) - { + for (const auto& [name, connection] : state_->connections) { connection->visit([](auto& service) { service.update(); }); connection->bridge.dispatch(); } @@ -207,14 +186,11 @@ bool redis_module_impl::update() { } bool redis_module_impl::ready_to_shut() const { - if (state_) - { + if (state_) { state_->check_owner(); - for (const auto& [name, connection] : state_->connections) - { + for (const auto& [name, connection] : state_->connections) { if (!connection->bridge.quiescent() || - !connection->visit([](const auto& service) { return service.quiescent(); })) - { + !connection->visit([](const auto& service) { return service.quiescent(); })) { return false; } } @@ -223,22 +199,17 @@ bool redis_module_impl::ready_to_shut() const { } bool redis_module_impl::pre_shut() { - if (!ready_to_shut()) - { + if (!ready_to_shut()) { return false; } - if (state_) - { + if (state_) { state_->accepting = false; - for (const auto& [name, connection] : state_->connections) - { + for (const auto& [name, connection] : state_->connections) { connection->bridge.stop_accepting(); connection->visit([](auto& service) { service.stop_accepting(); }); } - for (const auto& [name, connection] : state_->connections) - { - if (!connection->visit([](auto& service) { return service.retire_native(); })) - { + for (const auto& [name, connection] : state_->connections) { + if (!connection->visit([](auto& service) { return service.retire_native(); })) { return false; } } @@ -247,17 +218,13 @@ bool redis_module_impl::pre_shut() { } bool redis_module_impl::shut() { - if (state_) - { + if (state_) { state_->check_owner(); - if (state_->accepting) - { + if (state_->accepting) { return false; } - for (const auto& [name, connection] : state_->connections) - { - if (!connection->visit([](const auto& service) { return service.native_retired(); })) - { + for (const auto& [name, connection] : state_->connections) { + if (!connection->visit([](const auto& service) { return service.native_retired(); })) { return false; } } diff --git a/src/plugins/redis/redis_module.hpp b/src/plugins/redis/redis_module.hpp index da1113d87..5e9b2168a 100644 --- a/src/plugins/redis/redis_module.hpp +++ b/src/plugins/redis/redis_module.hpp @@ -14,16 +14,14 @@ namespace ark { // All strings, authentication and TLS settings are owned by the configuration. -struct redis_options -{ +struct redis_options { arknet::redis::pool_options pool; std::size_t max_operations{64}; std::size_t max_input_bytes{1024 * 1024}; bool tls{}; }; -class redis_module : public module -{ +class redis_module : public module { public: // Owner-thread setup. Names are unique; duplicate names or sealed admission // return false. Invalid options (including unavailable TLS) throw. diff --git a/src/plugins/redis/redis_plugin.cpp b/src/plugins/redis/redis_plugin.cpp index 06a7725db..559d21b7f 100644 --- a/src/plugins/redis/redis_plugin.cpp +++ b/src/plugins/redis/redis_plugin.cpp @@ -34,15 +34,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void redis_plugin::install() { - if (!register_module(detail::make_redis_module(), module_update::enabled)) - { + if (!register_module(detail::make_redis_module(), module_update::enabled)) { throw std::runtime_error("redis module registration rejected"); } } void redis_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("redis module unregistration rejected"); } } diff --git a/src/plugins/redis/redis_plugin.hpp b/src/plugins/redis/redis_plugin.hpp index 83f498a06..d31ca3a91 100644 --- a/src/plugins/redis/redis_plugin.hpp +++ b/src/plugins/redis/redis_plugin.hpp @@ -27,8 +27,7 @@ namespace ark { -class redis_plugin final : public plugin_base -{ +class redis_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/plugins/utility/compress_module.hpp b/src/plugins/utility/compress_module.hpp index 3a96ecc95..132e7a3d7 100644 --- a/src/plugins/utility/compress_module.hpp +++ b/src/plugins/utility/compress_module.hpp @@ -25,8 +25,7 @@ namespace ark { -class compress_module : public module -{ +class compress_module : public module { public: virtual bool compress(IN const compress_type type, IN const char* in_data, IN std::size_t in_size, OUT std::string& compressed_buff, IN uint8_t compress_level = 1) = 0; diff --git a/src/plugins/utility/compress_module_impl.cpp b/src/plugins/utility/compress_module_impl.cpp index 24b5a003d..cb3f8a0e4 100644 --- a/src/plugins/utility/compress_module_impl.cpp +++ b/src/plugins/utility/compress_module_impl.cpp @@ -29,8 +29,7 @@ namespace ark { -class compress_module_impl final : public module_base -{ +class compress_module_impl final : public module_base { private: std::unique_ptr zstd_{nullptr}; @@ -65,8 +64,7 @@ class compress_module_impl final : public module_base bool compress_module_impl::init() { zstd_ = std::make_unique(); - if (!load_config()) - { + if (!load_config()) { return false; } @@ -80,8 +78,7 @@ bool compress_module_impl::init() { bool compress_module_impl::compress(IN const compress_type type, IN const char* in_data, IN std::size_t in_size, OUT std::string& compressed_buff, IN uint8_t compress_level) { bool result = false; - switch (type) - { + switch (type) { case compress_type::compress_type_zlib: result = zlib_compress(in_data, in_size, compressed_buff, compress_level); break; @@ -99,8 +96,7 @@ bool compress_module_impl::compress(IN const compress_type type, IN const char* bool compress_module_impl::decompress( IN const compress_type type, IN const char* in_data, IN std::size_t in_size, OUT std::string& decompressed_buff) { bool result = false; - switch (type) - { + switch (type) { case compress_type::compress_type_zlib: result = zlib_normal_decompress(in_data, in_size, decompressed_buff); break; diff --git a/src/plugins/utility/guid_module.hpp b/src/plugins/utility/guid_module.hpp index c684eafb4..928b2d1f4 100755 --- a/src/plugins/utility/guid_module.hpp +++ b/src/plugins/utility/guid_module.hpp @@ -24,8 +24,7 @@ namespace ark { -class guid_module : public module -{ +class guid_module : public module { public: virtual guid_t create_guid() = 0; virtual std::string parse_uid(const guid_t& id) = 0; diff --git a/src/plugins/utility/guid_module_impl.cpp b/src/plugins/utility/guid_module_impl.cpp index c648880ea..99e953317 100644 --- a/src/plugins/utility/guid_module_impl.cpp +++ b/src/plugins/utility/guid_module_impl.cpp @@ -28,8 +28,7 @@ namespace ark { -class guid_module_impl final : public module_base -{ +class guid_module_impl final : public module_base { public: bool init() override; diff --git a/src/plugins/utility/schedule_module.hpp b/src/plugins/utility/schedule_module.hpp index 00f679484..f22495d98 100644 --- a/src/plugins/utility/schedule_module.hpp +++ b/src/plugins/utility/schedule_module.hpp @@ -27,8 +27,7 @@ namespace ark { -class schedule_module : public module -{ +class schedule_module : public module { public: template void add_schedule(const std::string& cron_expression, receiver_type* receiver, void (receiver_type::*handler)()) { diff --git a/src/plugins/utility/schedule_module_impl.cpp b/src/plugins/utility/schedule_module_impl.cpp index 95ec1b962..1eae4aae3 100644 --- a/src/plugins/utility/schedule_module_impl.cpp +++ b/src/plugins/utility/schedule_module_impl.cpp @@ -32,8 +32,7 @@ namespace ark { namespace { -struct startup_schedule_state -{ +struct startup_schedule_state { std::mutex mutex; bool exposed{}; bool sealed{}; @@ -43,8 +42,7 @@ struct startup_schedule_state } // namespace -class schedule_module_impl final : public module_base -{ +class schedule_module_impl final : public module_base { friend struct schedule_startup_test_access; public: @@ -67,8 +65,7 @@ class schedule_module_impl final : public module_base bool schedule_module_impl::init() { auto state = std::make_shared(); auto* manager = get_plugin_manager(); - if (manager && !manager->prepare_startup_cleanup("Schedule", "ark_utility_plugin", state, release_startup)) - { + if (manager && !manager->prepare_startup_cleanup("Schedule", "ark_utility_plugin", state, release_startup)) { return false; } startup_ = std::move(state); @@ -80,14 +77,12 @@ startup_cleanup_result schedule_module_impl::release_startup(void* context) { auto& state = *static_cast(context); { std::lock_guard lock(state.mutex); - if (state.exposed) - { + if (state.exposed) { return startup_cleanup_result::unsafe; } state.sealed = true; } - if (!state.worker) - { + if (!state.worker) { return startup_cleanup_result::done; } @@ -96,8 +91,7 @@ startup_cleanup_result schedule_module_impl::release_startup(void* context) { state.worker->close(); state.dispatch.wait(); state.worker->threads_.stop(true); - if (!state.worker->ready_to_shut()) - { + if (!state.worker->ready_to_shut()) { // A failed internal dispatcher cannot certify ordinary readiness. Keep // the owner and any stored exception instead of entering its destructor. return startup_cleanup_result::failed; @@ -107,8 +101,7 @@ startup_cleanup_result schedule_module_impl::release_startup(void* context) { } bool schedule_module_impl::ready_to_shut() const { - if (startup_ && startup_->worker) - { + if (startup_ && startup_->worker) { startup_->worker->close(); } return !startup_ || !startup_->worker || startup_->worker->ready_to_shut(); @@ -119,17 +112,14 @@ bool schedule_module_impl::pre_shut() { } scheduler* schedule_module_impl::begin_registration() { - if (!startup_) - { + if (!startup_) { throw std::logic_error("Schedule module is not initialized"); } std::lock_guard lock(startup_->mutex); - if (startup_->sealed) - { + if (startup_->sealed) { return nullptr; } - if (!startup_->worker) - { + if (!startup_->worker) { throw std::logic_error("Schedule worker is not available"); } // A failed allocation or callback-registration attempt may already have @@ -139,23 +129,20 @@ scheduler* schedule_module_impl::begin_registration() { } void schedule_module_impl::add_cron_schedule(const std::string& cron_expression, scheduler_functor&& cb) { - if (auto* worker = begin_registration()) - { + if (auto* worker = begin_registration()) { worker->cron(cron_expression, std::move(cb)); } } void schedule_module_impl::add_interval_schedule( const std::chrono::system_clock::duration interval, scheduler_functor&& cb) { - if (auto* worker = begin_registration()) - { + if (auto* worker = begin_registration()) { worker->interval(interval, std::move(cb)); } } void schedule_module_impl::add_at_schedule(const std::string& target_time, scheduler_functor&& cb) { - if (auto* worker = begin_registration()) - { + if (auto* worker = begin_registration()) { worker->at(target_time, std::move(cb)); } } diff --git a/src/plugins/utility/scheduler.hpp b/src/plugins/utility/scheduler.hpp index 428247563..6282898d8 100644 --- a/src/plugins/utility/scheduler.hpp +++ b/src/plugins/utility/scheduler.hpp @@ -36,8 +36,7 @@ namespace ark { // this file is based on https://github.com/Bosma/Scheduler. // under the MIT license. -class interruptable_sleep final -{ +class interruptable_sleep final { using clock = std::chrono::system_clock; // InterruptableSleep offers a sleep that can be interrupted by any thread. @@ -89,8 +88,7 @@ class interruptable_sleep final std::condition_variable condition_; }; -class scheduler_task -{ +class scheduler_task { public: using clock = std::chrono::system_clock; @@ -108,8 +106,7 @@ class scheduler_task bool interval; }; -class in_task final : public scheduler_task -{ +class in_task final : public scheduler_task { public: using clock = std::chrono::system_clock; @@ -123,8 +120,7 @@ class in_task final : public scheduler_task } }; -class every_task final : public scheduler_task -{ +class every_task final : public scheduler_task { public: using clock = std::chrono::system_clock; @@ -140,8 +136,7 @@ class every_task final : public scheduler_task clock::duration interval_duration; }; -class cron_task final : public scheduler_task -{ +class cron_task final : public scheduler_task { public: cron_task(const std::string& expression, std::function&& f) : scheduler_task(std::move(f), true) @@ -155,8 +150,7 @@ class cron_task final : public scheduler_task ark::cron cron_expression; }; -class scheduler final -{ +class scheduler final { friend struct scheduler_test_access; friend class schedule_module_impl; @@ -177,8 +171,7 @@ class scheduler final // Owner-only fallback: discard queued timers and join dispatched work. // A callback must never destroy its own scheduler or wait for this owner // to join it. Running callbacks still require cooperative completion. - while (!dispatcher_retired_.load()) - { + while (!dispatcher_retired_.load()) { dispatcher_retired_.wait(false); } threads_.stop(true); @@ -211,8 +204,7 @@ class scheduler final // Owner-only; never join workers while they can still need owner progress. bool pre_shut() { - if (!ready_to_shut()) - { + if (!ready_to_shut()) { return false; } threads_.stop(true); @@ -225,8 +217,7 @@ class scheduler final template void in(const clock::time_point time, callable_type&& f, args_type&&... args) { operation registration(*this); - if (!registration.accepted) - { + if (!registration.accepted) { return; } @@ -243,8 +234,7 @@ class scheduler final template void at(const std::string& time, callable_type&& f, args_type&&... args) { operation registration(*this); - if (!registration.accepted) - { + if (!registration.accepted) { return; } @@ -255,27 +245,19 @@ class scheduler final // our final time as a time_point clock::time_point tp; - if (try_parse(tm, time, "%H:%M:%S")) - { + if (try_parse(tm, time, "%H:%M:%S")) { // convert tm back to time_t, then to a time_point and assign to final tp = clock::from_time_t(detail::scheduler_mktime(tm)); // if we've already passed this time, the user will mean next day, so add a day. - if (clock::now() >= tp) - { + if (clock::now() >= tp) { tp += std::chrono::hours(24); } - } - else if (try_parse(tm, time, "%Y-%m-%d %H:%M:%S")) - { + } else if (try_parse(tm, time, "%Y-%m-%d %H:%M:%S")) { tp = clock::from_time_t(detail::scheduler_mktime(tm)); - } - else if (try_parse(tm, time, "%Y/%m/%d %H:%M:%S")) - { + } else if (try_parse(tm, time, "%Y/%m/%d %H:%M:%S")) { tp = clock::from_time_t(detail::scheduler_mktime(tm)); - } - else - { + } else { // could not parse time throw std::runtime_error("Cannot parse time string: " + time); } @@ -288,8 +270,7 @@ class scheduler final template void every(const clock::duration time, callable_type&& f, args_type&&... args) { operation registration(*this, true); - if (!registration.accepted) - { + if (!registration.accepted) { return; } @@ -312,8 +293,7 @@ class scheduler final template void cron(const std::string& expression, callable_type&& f, args_type&&... args) { operation registration(*this, true); - if (!registration.accepted) - { + if (!registration.accepted) { return; } @@ -326,8 +306,7 @@ class scheduler final template void interval(const clock::duration time, callable_type&& f, args_type&&... args) { operation registration(*this, true); - if (!registration.accepted) - { + if (!registration.accepted) { return; } @@ -338,8 +317,7 @@ class scheduler final private: static int worker_count(unsigned int callbacks) { - if (callbacks >= static_cast(std::numeric_limits::max())) - { + if (callbacks >= static_cast(std::numeric_limits::max())) { throw std::length_error("Scheduler worker count exceeds the supported range"); } return static_cast(callbacks) + 1; @@ -351,8 +329,7 @@ class scheduler final : stopping_(false) , threads_(worker_count(max_n_tasks)) { auto dispatched = threads_.push([this](int) { dispatch(); }); - if (completion) - { + if (completion) { *completion = std::move(dispatched); } } @@ -373,8 +350,7 @@ class scheduler final // Intrusive stack records keep continuation authority on this instance, // including when the callback and registration code live in different DSOs. - struct callback_context - { + struct callback_context { explicit callback_context(scheduler& scheduler) : owner(&scheduler) , thread(std::this_thread::get_id()) { @@ -391,16 +367,14 @@ class scheduler final } void retire() { - if (!owner) - { + if (!owner) { return; } auto* scheduler = owner; { std::lock_guard lock(scheduler->mutex_); auto** entry = &scheduler->callback_contexts_; - while (*entry != this) - { + while (*entry != this) { entry = &(*entry)->next; } *entry = next; @@ -415,32 +389,27 @@ class scheduler final }; bool in_callback() const { - for (auto* context = callback_contexts_; context; context = context->next) - { - if (context->thread == std::this_thread::get_id()) - { + for (auto* context = callback_contexts_; context; context = context->next) { + if (context->thread == std::this_thread::get_id()) { return true; } } return false; } - struct operation - { + struct operation { explicit operation(scheduler& owner, bool recurring = false) : owner(owner) { std::lock_guard lock(owner.mutex_); accepted = !owner.closing_ && !owner.dispatcher_retired_ && (!owner.stopping_ || (!recurring && owner.in_callback())); - if (accepted) - { + if (accepted) { ++owner.outstanding_; } } ~operation() { - if (accepted) - { + if (accepted) { --owner.outstanding_; owner.sleeper_.interrupt(); } @@ -450,8 +419,7 @@ class scheduler final bool accepted{false}; }; - struct dispatched_task - { + struct dispatched_task { dispatched_task(scheduler& scheduler, std::shared_ptr task) : owner(scheduler) , context(scheduler) @@ -475,8 +443,7 @@ class scheduler final void add_task(const clock::time_point time, std::shared_ptr t) { { std::lock_guard lock(mutex_); - if (!closing_ && (!stopping_ || !t->recurring)) - { + if (!closing_ && (!stopping_ || !t->recurring)) { tasks_.emplace(time, std::move(t)); } } @@ -484,69 +451,51 @@ class scheduler final } void dispatch() { - try - { - while (true) - { + try { + while (true) { decltype(tasks_) retired; clock::time_point next; bool empty; bool finished; { std::lock_guard lock(mutex_); - if (closing_) - { + if (closing_) { retired.swap(tasks_); - } - else if (stopping_) - { - for (auto i = tasks_.begin(); i != tasks_.end();) - { - if (i->second->recurring) - { + } else if (stopping_) { + for (auto i = tasks_.begin(); i != tasks_.end();) { + if (i->second->recurring) { retired.insert(tasks_.extract(i++)); - } - else - { + } else { ++i; } } } empty = tasks_.empty(); finished = stopping_ && empty && outstanding_ == 0 && !callback_contexts_; - if (!empty) - { + if (!empty) { next = tasks_.begin()->first; } } retired.clear(); - if (finished) - { + if (finished) { dispatcher_retired_ = true; dispatcher_retired_.notify_all(); return; } - if (empty) - { + if (empty) { sleeper_.sleep(); - } - else - { + } else { sleeper_.sleep_until(next); } manage_tasks(); } - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { stop_accepting(); std::fputs("Scheduler dispatch failed: ", stderr); std::fputs(error.what(), stderr); std::fputs("; shutdown readiness remains closed.\n", stderr); throw; - } - catch (...) - { + } catch (...) { // A failed dispatcher cannot promise completion of accepted work. // Keep readiness closed and preserve owners for the owner's fallback. stop_accepting(); @@ -561,57 +510,43 @@ class scheduler final decltype(tasks_) dispatched; std::lock_guard lock(mutex_); auto end = tasks_.upper_bound(clock::now()); - for (auto i = tasks_.begin(); i != end;) - { + for (auto i = tasks_.begin(); i != end;) { dispatched.insert(tasks_.extract(i++)); } - try - { - for (auto& entry : dispatched) - { + try { + for (auto& entry : dispatched) { auto& task = entry.second; - if (closing_ || (stopping_ && task->recurring)) - { + if (closing_ || (stopping_ && task->recurring)) { continue; } ++outstanding_; - try - { + try { #ifdef ARK_SCHEDULER_SUBMISSION_TEST_HOOK ARK_SCHEDULER_SUBMISSION_TEST_HOOK(); #endif threads_.push([this, task](int) mutable { dispatched_task work{*this, std::move(task)}; - try - { + try { work.task->function(); - if (work.task->interval && !stopping_) - { + if (work.task->interval && !stopping_) { add_task(work.task->get_new_time(), work.task); } - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { std::fputs("Scheduler callback failed: ", stderr); std::fputs(error.what(), stderr); std::fputc('\n', stderr); - } - catch (...) - { + } catch (...) { // The discarded pool future previously contained this // exception. Destroy it here before retiring business // owners, and report it instead of retaining DSO code. std::fputs("Scheduler callback failed.\n", stderr); } }); - } - catch (...) - { + } catch (...) { --outstanding_; throw; } - if (task->recurring && !task->interval) - { + if (task->recurring && !task->interval) { tasks_.emplace(task->get_new_time(), task); } // The worker cannot enter its context until this lock is released. @@ -619,21 +554,15 @@ class scheduler final // retires its last capture with that callback's continuation authority. task.reset(); } - } - catch (...) - { + } catch (...) { // Successful handoffs left empty nodes. Return every remaining // owner, including unsubmitted callbacks, to instance storage before // unlocking. Equal allocators and the time-point comparator let // merge transfer these existing nodes without allocating. - for (auto i = dispatched.begin(); i != dispatched.end();) - { - if (!i->second) - { + for (auto i = dispatched.begin(); i != dispatched.end();) { + if (!i->second) { i = dispatched.erase(i); - } - else - { + } else { ++i; } } diff --git a/src/plugins/utility/timer_module.hpp b/src/plugins/utility/timer_module.hpp index 24e338957..a76e9b14c 100644 --- a/src/plugins/utility/timer_module.hpp +++ b/src/plugins/utility/timer_module.hpp @@ -27,8 +27,7 @@ namespace ark { -class timer_module : public module -{ +class timer_module : public module { public: template uint64_t add_single_timer(const guid_t& entity_id, const std::chrono::milliseconds interval, const uint32_t count, diff --git a/src/plugins/utility/timer_module_impl.cpp b/src/plugins/utility/timer_module_impl.cpp index 304cefed6..1f85f3bbf 100644 --- a/src/plugins/utility/timer_module_impl.cpp +++ b/src/plugins/utility/timer_module_impl.cpp @@ -27,19 +27,16 @@ namespace ark { namespace { -struct startup_timer_capsule -{ +struct startup_timer_capsule { std::unique_ptr wheel; }; startup_cleanup_result release_startup_timer(void* context) { auto& capsule = *static_cast(context); - if (capsule.wheel && capsule.wheel->has_retained_callbacks()) - { + if (capsule.wheel && capsule.wheel->has_retained_callbacks()) { return startup_cleanup_result::unsafe; } - if (capsule.wheel) - { + if (capsule.wheel) { capsule.wheel->shut(); capsule.wheel.reset(); } @@ -48,8 +45,7 @@ startup_cleanup_result release_startup_timer(void* context) { } // namespace -class timer_module_impl final : public module_base -{ +class timer_module_impl final : public module_base { public: bool init() override; bool update() override; @@ -71,8 +67,7 @@ bool timer_module_impl::init() { // The manager owns this capsule independently of the module. Enroll before // acquiring wheel storage; cleanup never captures an incomplete module. auto capsule = std::make_shared(); - if (!get_plugin_manager()->prepare_startup_cleanup("Timer", "ark_utility_plugin", capsule, release_startup_timer)) - { + if (!get_plugin_manager()->prepare_startup_cleanup("Timer", "ark_utility_plugin", capsule, release_startup_timer)) { return false; } timer_capsule_ = std::move(capsule); @@ -83,8 +78,7 @@ bool timer_module_impl::init() { } bool timer_module_impl::pre_shut() { - if (timer_capsule_ && timer_capsule_->wheel) - { + if (timer_capsule_ && timer_capsule_->wheel) { timer_capsule_->wheel->shut(); } return true; diff --git a/src/plugins/utility/utility_plugin.cpp b/src/plugins/utility/utility_plugin.cpp index 4b3d46a92..46a444143 100644 --- a/src/plugins/utility/utility_plugin.cpp +++ b/src/plugins/utility/utility_plugin.cpp @@ -34,39 +34,31 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void utility_plugin::install() { - if (!register_module(detail::make_guid_module(), module_update::disabled)) - { + if (!register_module(detail::make_guid_module(), module_update::disabled)) { throw std::runtime_error("utility guid module registration rejected"); } - if (!register_module(detail::make_timer_module(), module_update::enabled)) - { + if (!register_module(detail::make_timer_module(), module_update::enabled)) { throw std::runtime_error("utility timer module registration rejected"); } - if (!register_module(detail::make_schedule_module(), module_update::disabled)) - { + if (!register_module(detail::make_schedule_module(), module_update::disabled)) { throw std::runtime_error("utility schedule module registration rejected"); } - if (!register_module(detail::make_compress_module(), module_update::disabled)) - { + if (!register_module(detail::make_compress_module(), module_update::disabled)) { throw std::runtime_error("utility compress module registration rejected"); } } void utility_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("utility compress module unregistration rejected"); } - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("utility schedule module unregistration rejected"); } - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("utility timer module unregistration rejected"); } - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("utility guid module unregistration rejected"); } } diff --git a/src/plugins/utility/utility_plugin.hpp b/src/plugins/utility/utility_plugin.hpp index 79bf16fed..8de5a5af4 100755 --- a/src/plugins/utility/utility_plugin.hpp +++ b/src/plugins/utility/utility_plugin.hpp @@ -30,8 +30,7 @@ namespace ark { -class utility_plugin final : public plugin_base -{ +class utility_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/server/dir/dir_net_module.hpp b/src/server/dir/dir_net_module.hpp index ca8eb1c26..06b8fce6e 100755 --- a/src/server/dir/dir_net_module.hpp +++ b/src/server/dir/dir_net_module.hpp @@ -26,8 +26,7 @@ namespace ark { class net_server_service; -class dir_net_module : public module -{ +class dir_net_module : public module { public: virtual std::shared_ptr get_net_server() = 0; }; diff --git a/src/server/dir/dir_net_module_impl.cpp b/src/server/dir/dir_net_module_impl.cpp index ff81d3eed..b09ca6e19 100644 --- a/src/server/dir/dir_net_module_impl.cpp +++ b/src/server/dir/dir_net_module_impl.cpp @@ -31,8 +31,7 @@ bool dir_net_module_impl::init() { bus_module_ = get_plugin_manager()->try_find_module(); net_service_manager_module_ = get_plugin_manager()->try_find_module(); - if (bus_module_ == nullptr || net_service_manager_module_ == nullptr) - { + if (bus_module_ == nullptr || net_service_manager_module_ == nullptr) { ARK_LOG_ERROR("dir network startup requires Bus and Net modules"); return false; } @@ -46,15 +45,13 @@ bool dir_net_module_impl::post_init() { bool dir_net_module_impl::start_server() { auto ret = net_service_manager_module_->create_server(); - if (!ret) - { + if (!ret) { ARK_LOG_ERROR("Cannot start server net, busid = {}", bus_module_->get_self_bus_name()); return false; } net_server_ = net_service_manager_module_->get_inter_net_server(); - if (net_server_ == nullptr) - { + if (net_server_ == nullptr) { ARK_LOG_ERROR("Cannot find server net, busid = {}", bus_module_->get_self_bus_name()); return false; } diff --git a/src/server/dir/dir_net_module_impl.hpp b/src/server/dir/dir_net_module_impl.hpp index d368ea771..584e598f6 100644 --- a/src/server/dir/dir_net_module_impl.hpp +++ b/src/server/dir/dir_net_module_impl.hpp @@ -29,8 +29,7 @@ namespace ark { -class dir_net_module_impl final : public module_base -{ +class dir_net_module_impl final : public module_base { public: bool init() override; bool post_init() override; diff --git a/src/server/dir/dir_plugin.cpp b/src/server/dir/dir_plugin.cpp index 15b3fecc5..4bda69300 100644 --- a/src/server/dir/dir_plugin.cpp +++ b/src/server/dir/dir_plugin.cpp @@ -35,15 +35,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void dir_plugin::install() { - if (!register_module(detail::make_dir_net_module(), module_update::disabled)) - { + if (!register_module(detail::make_dir_net_module(), module_update::disabled)) { throw std::runtime_error("dir_net_module registration rejected"); } } void dir_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("dir_net_module unregistration rejected"); } } diff --git a/src/server/dir/dir_plugin.hpp b/src/server/dir/dir_plugin.hpp index c88b7180c..bedc84ed9 100644 --- a/src/server/dir/dir_plugin.hpp +++ b/src/server/dir/dir_plugin.hpp @@ -24,8 +24,7 @@ namespace ark { -class dir_plugin final : public plugin_base -{ +class dir_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/server/game/game_net_module.hpp b/src/server/game/game_net_module.hpp index 4fb227658..c76721eae 100644 --- a/src/server/game/game_net_module.hpp +++ b/src/server/game/game_net_module.hpp @@ -27,8 +27,7 @@ namespace ark { -class game_net_module : public module -{ +class game_net_module : public module { public: //class GateBaseInfo //{ diff --git a/src/server/game/game_net_module_impl.cpp b/src/server/game/game_net_module_impl.cpp index ff66ac445..56c64ffc9 100644 --- a/src/server/game/game_net_module_impl.cpp +++ b/src/server/game/game_net_module_impl.cpp @@ -38,8 +38,7 @@ bool game_net_module_impl::init() { net_service_manager_module_ = get_plugin_manager()->try_find_module(); map_module_ = get_plugin_manager()->try_find_module(); - if (bus_module_ == nullptr || net_service_manager_module_ == nullptr || kernel_module_ == nullptr) - { + if (bus_module_ == nullptr || net_service_manager_module_ == nullptr || kernel_module_ == nullptr) { ARK_LOG_ERROR("game network startup requires Bus, Net and Kernel modules"); return false; } @@ -51,8 +50,7 @@ bool game_net_module_impl::post_init() { // Metadata and Kernel finish init before any post_init callback. No order // between modules within the init stage is required for these registrations. auto* metadata = get_plugin_manager()->try_find_module(); - if (metadata == nullptr || metadata->find_meta(entity_meta_player::self_name()) == nullptr) - { + if (metadata == nullptr || metadata->find_meta(entity_meta_player::self_name()) == nullptr) { ARK_LOG_ERROR("game network startup requires Player metadata"); return false; } @@ -63,8 +61,7 @@ bool game_net_module_impl::post_init() { !kernel_module_->add_enter_scene_event( entity_meta_player::self_name(), this, &game_net_module_impl::on_enter_scene) || !kernel_module_->add_class_call_back( - entity_meta_player::self_name(), this, &game_net_module_impl::on_entity_event)) - { + entity_meta_player::self_name(), this, &game_net_module_impl::on_entity_event)) { ARK_LOG_ERROR("Cannot register game Player callbacks"); return false; } @@ -74,15 +71,13 @@ bool game_net_module_impl::post_init() { bool game_net_module_impl::start_server() { auto ret = net_service_manager_module_->create_server(); - if (!ret) - { + if (!ret) { ARK_LOG_ERROR("Cannot start server net, busid = {}", bus_module_->get_self_bus_name()); return false; } net_server_service_ = net_service_manager_module_->get_inter_net_server(); - if (net_server_service_ == nullptr) - { + if (net_server_service_ == nullptr) { ARK_LOG_ERROR("Cannot find server net, busid = {}", bus_module_->get_self_bus_name()); return false; } @@ -122,14 +117,12 @@ bool game_net_module_impl::start_server() { //} int game_net_module_impl::on_view_data_node_enter(const data_list& arg_var, const guid_t& self) { - if (arg_var.get_count() <= 0 || self == 0) - { + if (arg_var.get_count() <= 0 || self == 0) { return 1; } std::shared_ptr entity_ptr = kernel_module_->get_entity(self); - if (nullptr == entity_ptr) - { + if (nullptr == entity_ptr) { return 0; } @@ -141,12 +134,10 @@ int game_net_module_impl::on_view_data_node_enter(const data_list& arg_var, cons mask[(size_t)data_mask::pf_sync_view] = 1; kernel_module_->entity_node_to_protobuf_data(entity_ptr, entity->mutable_data(), mask); - for (size_t i = 0; i < arg_var.get_count(); i++) - { + for (size_t i = 0; i < arg_var.get_count(); i++) { guid_t ident_other = arg_var.int64(i); - if (self != ident_other) - { + if (self != ident_other) { send_msg_protobuf_to_gate(ark::protobuf::egmi_ack_entity_data_node_enter, msg, ident_other); } } @@ -155,14 +146,12 @@ int game_net_module_impl::on_view_data_node_enter(const data_list& arg_var, cons } int game_net_module_impl::on_self_data_node_enter(const guid_t& self) { - if (self == 0) - { + if (self == 0) { return 1; } std::shared_ptr entity_ptr = kernel_module_->get_entity(self); - if (nullptr == entity_ptr) - { + if (nullptr == entity_ptr) { return 1; } @@ -179,15 +168,13 @@ int game_net_module_impl::on_self_data_node_enter(const guid_t& self) { } int game_net_module_impl::on_self_data_table_enter(const guid_t& self) { - if (self == 0) - { + if (self == 0) { return 1; } std::shared_ptr entity_ptr = kernel_module_->get_entity(self); - if (nullptr == entity_ptr) - { + if (nullptr == entity_ptr) { return 1; } @@ -204,15 +191,13 @@ int game_net_module_impl::on_self_data_table_enter(const guid_t& self) { } int game_net_module_impl::on_view_data_table_enter(const data_list& arg_var, const guid_t& self) { - if (arg_var.get_count() <= 0 || self == 0) - { + if (arg_var.get_count() <= 0 || self == 0) { return 1; } std::shared_ptr entity_ptr = kernel_module_->get_entity(self); - if (nullptr == entity_ptr) - { + if (nullptr == entity_ptr) { return 1; } @@ -224,12 +209,10 @@ int game_net_module_impl::on_view_data_table_enter(const data_list& arg_var, con mask[(size_t)data_mask::pf_sync_view] = 1; kernel_module_->entity_table_to_protobuf_data(entity_ptr, entity->mutable_data(), mask); - for (size_t i = 0; i < arg_var.get_count(); i++) - { + for (size_t i = 0; i < arg_var.get_count(); i++) { guid_t ident_other = arg_var.int64(i); - if (self != ident_other && msg.data_list_size() > 0) - { + if (self != ident_other && msg.data_list_size() > 0) { send_msg_protobuf_to_gate(ark::protobuf::egmi_ack_entity_data_table_enter, msg, ident_other); } } @@ -238,8 +221,7 @@ int game_net_module_impl::on_view_data_table_enter(const data_list& arg_var, con } bool game_net_module_impl::process_leave_group(const guid_t& self, int map_id, int old_inst_id) { - if (old_inst_id <= 0) - { + if (old_inst_id <= 0) { return false; } @@ -247,26 +229,21 @@ bool game_net_module_impl::process_leave_group(const guid_t& self, int map_id, i data_list_impl value_all_old_player_list; map_module_->get_inst_entity_list(map_id, old_inst_id, value_all_old_object_list); - if (value_all_old_object_list.get_count() > 0) - { + if (value_all_old_object_list.get_count() > 0) { //broadcast self to others around - for (size_t i = 0; i < value_all_old_object_list.get_count(); i++) - { + for (size_t i = 0; i < value_all_old_object_list.get_count(); i++) { guid_t ident_bc = value_all_old_object_list.int64(i); auto entity_ptr = kernel_module_->get_entity(ident_bc); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { continue; } - if (value_all_old_object_list.int64(i) == self) - { + if (value_all_old_object_list.int64(i) == self) { value_all_old_object_list.set_int64(i, 0); } const std::string& class_name = entity_ptr->get_class_name(); - if (entity_meta_player::self_name() == class_name) - { + if (entity_meta_player::self_name() == class_name) { value_all_old_player_list << ident_bc; } } @@ -284,8 +261,7 @@ bool game_net_module_impl::process_leave_group(const guid_t& self, int map_id, i bool game_net_module_impl::process_enter_group(const guid_t& self, int scene_id, int new_group_id) { // broadcast self enter to others - if (new_group_id <= 0) - { + if (new_group_id <= 0) { return false; } @@ -297,38 +273,31 @@ bool game_net_module_impl::process_enter_group(const guid_t& self, int scene_id, data_list_impl value_player_list_no_self; map_module_->get_inst_entity_list(scene_id, new_group_id, value_all_object_list); - for (size_t i = 0; i < value_all_object_list.get_count(); i++) - { + for (size_t i = 0; i < value_all_object_list.get_count(); i++) { guid_t ident_bc = value_all_object_list.int64(i); auto entity_ptr = kernel_module_->get_entity(ident_bc); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { continue; } const std::string& class_name = entity_ptr->get_class_name(); - if (entity_meta_player::self_name() == class_name) - { + if (entity_meta_player::self_name() == class_name) { value_player_list << ident_bc; - if (ident_bc != self) - { + if (ident_bc != self) { value_player_list_no_self << ident_bc; } } - if (ident_bc != self) - { + if (ident_bc != self) { value_all_object_list_no_self << ident_bc; } } // broadcast others that I'm here(need exclude self) - if (value_player_list_no_self.get_count() > 0) - { + if (value_player_list_no_self.get_count() > 0) { auto entity_ptr = kernel_module_->get_entity(self); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { return false; } @@ -337,12 +306,10 @@ bool game_net_module_impl::process_enter_group(const guid_t& self, int scene_id, on_view_data_table_enter(value_player_list_no_self, self); const std::string class_name = entity_ptr->get_class_name(); - if (class_name == entity_meta_player::self_name()) - { + if (class_name == entity_meta_player::self_name()) { on_entity_list_enter(data_list_impl() << self, value_all_object_list_no_self); - for (size_t i = 0; i < value_all_object_list_no_self.get_count(); i++) - { + for (size_t i = 0; i < value_all_object_list_no_self.get_count(); i++) { // broadcast myself data to others guid_t ident_old = value_all_object_list_no_self.int64(i); @@ -356,26 +323,22 @@ bool game_net_module_impl::process_enter_group(const guid_t& self, int scene_id, } int game_net_module_impl::on_entity_list_enter(const data_list& self, const data_list& arg_var) { - if (self.get_count() <= 0 || arg_var.get_count() <= 0) - { + if (self.get_count() <= 0 || arg_var.get_count() <= 0) { return 1; } ark::protobuf::ack_entity_enter_list entity_enter_list_value; - for (size_t i = 0; i < arg_var.get_count(); i++) - { + for (size_t i = 0; i < arg_var.get_count(); i++) { guid_t ident_old = arg_var.int64(i); // Exclude empty entity - if (ident_old == 0) - { + if (ident_old == 0) { continue; } auto entity_ptr = kernel_module_->get_entity(ident_old); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { continue; } @@ -394,17 +357,14 @@ int game_net_module_impl::on_entity_list_enter(const data_list& self, const data enter_info_ptr->set_class_id(entity_ptr->get_class_name()); } - if (entity_enter_list_value.entity_list_size() <= 0) - { + if (entity_enter_list_value.entity_list_size() <= 0) { return 1; } - for (size_t i = 0; i < self.get_count(); i++) - { + for (size_t i = 0; i < self.get_count(); i++) { guid_t ident = self.int64(i); - if (ident != 0) - { + if (ident != 0) { send_msg_protobuf_to_gate(ark::protobuf::egmi_ack_entity_enter, entity_enter_list_value, ident); } } @@ -413,30 +373,25 @@ int game_net_module_impl::on_entity_list_enter(const data_list& self, const data } int game_net_module_impl::on_entity_list_leave(const data_list& self, const data_list& arg_var) { - if (self.get_count() <= 0 || arg_var.get_count() <= 0) - { + if (self.get_count() <= 0 || arg_var.get_count() <= 0) { return 1; } ark::protobuf::ack_entity_leave_list entity_leave_info_list_value; - for (size_t i = 0; i < arg_var.get_count(); i++) - { + for (size_t i = 0; i < arg_var.get_count(); i++) { guid_t ident_old = arg_var.int64(i); // Exclude empty entity - if (ident_old != 0) - { + if (ident_old != 0) { entity_leave_info_list_value.add_entity_list(ident_old); } } - for (size_t i = 0; i < self.get_count(); i++) - { + for (size_t i = 0; i < self.get_count(); i++) { guid_t ident = self.int64(i); - if (ident != 0) - { + if (ident != 0) { send_msg_protobuf_to_gate(ark::protobuf::egmi_ack_entity_leave, entity_leave_info_list_value, ident); } } @@ -446,16 +401,14 @@ int game_net_module_impl::on_entity_list_leave(const data_list& self, const data int game_net_module_impl::common_class_destory_event(const guid_t& self) { auto entity_ptr = kernel_module_->get_entity(self); - if (nullptr == entity_ptr) - { + if (nullptr == entity_ptr) { return 0; } int map_id = entity_ptr->get_int32(entity_meta_base_entity::map_id()); int map_inst_id = entity_ptr->get_int32(entity_meta_base_entity::map_inst_id()); - if (map_inst_id < 0) - { + if (map_inst_id < 0) { return 0; } @@ -464,23 +417,19 @@ int game_net_module_impl::common_class_destory_event(const guid_t& self) { data_list_impl value_broad_list_no_self; map_module_->get_inst_entity_list(map_id, map_inst_id, value_all_object_list); - for (size_t i = 0; i < value_all_object_list.get_count(); i++) - { + for (size_t i = 0; i < value_all_object_list.get_count(); i++) { guid_t ident_bc = value_all_object_list.int64(i); auto bc_entity_ptr = kernel_module_->get_entity(ident_bc); - if (nullptr == bc_entity_ptr) - { + if (nullptr == bc_entity_ptr) { continue; } const std::string& class_name = bc_entity_ptr->get_class_name(); - if (entity_meta_player::self_name() == class_name) - { + if (entity_meta_player::self_name() == class_name) { value_broad_case_list << ident_bc; - if (ident_bc != self) - { + if (ident_bc != self) { value_broad_list_no_self << ident_bc; } } @@ -492,33 +441,27 @@ int game_net_module_impl::common_class_destory_event(const guid_t& self) { int game_net_module_impl::on_common_class_event( const guid_t& self, const std::string& class_name, const entity_event class_event, const data_list& var) { - switch (class_event) - { + switch (class_event) { case entity_event::entity_evt_destroy: common_class_destory_event(self); break; - case entity_event::entity_evt_pre_load_data: - { + case entity_event::entity_evt_pre_load_data: { // do something - } - break; + } break; case entity_event::entity_evt_load_data: break; - case entity_event::entity_evt_data_finished: - { + case entity_event::entity_evt_data_finished: { // Just broadcast to self - if (class_name == entity_meta_player::self_name()) - { + if (class_name == entity_meta_player::self_name()) { on_entity_list_enter(data_list_impl() << self, data_list_impl() << self); on_self_data_node_enter(self); on_self_data_table_enter(self); } - } - break; + } break; case entity_event::entity_evt_all_finished: break; @@ -648,18 +591,15 @@ int game_net_module_impl::get_broadcast_entity_list(const int map_id, const int data_list_impl map_inst_entity_list; map_module_->get_inst_entity_list(map_id, inst_id, map_inst_entity_list); - for (size_t i = 0; i < map_inst_entity_list.get_count(); i++) - { + for (size_t i = 0; i < map_inst_entity_list.get_count(); i++) { auto entity_ptr = kernel_module_->get_entity(map_inst_entity_list.int64(i)); - if (entity_ptr == nullptr) - { + if (entity_ptr == nullptr) { continue; } const std::string& obj_class_name = entity_ptr->get_class_name(); - if (entity_meta_player::self_name() == obj_class_name) - { + if (entity_meta_player::self_name() == obj_class_name) { value_object.add_int64(map_inst_entity_list.int64(i)); } } @@ -669,8 +609,7 @@ int game_net_module_impl::get_broadcast_entity_list(const int map_id, const int int game_net_module_impl::on_entity_event( const guid_t& self, const std::string& class_name, const entity_event class_event, const data_list& var) { - switch (class_event) - { + switch (class_event) { case entity_event::entity_evt_destroy: // save data to db by yourself logic ARK_LOG_INFO("Player Offline, player_id = {}", self); diff --git a/src/server/game/game_net_module_impl.hpp b/src/server/game/game_net_module_impl.hpp index 99f244d2e..5d2fc750d 100644 --- a/src/server/game/game_net_module_impl.hpp +++ b/src/server/game/game_net_module_impl.hpp @@ -35,8 +35,7 @@ namespace ark { class game_net_module_impl final : public module_base -{ + class_meta_module> { public: bool init() override; bool post_init() override; diff --git a/src/server/game/game_plugin.cpp b/src/server/game/game_plugin.cpp index ee29a0728..87ea61d95 100644 --- a/src/server/game/game_plugin.cpp +++ b/src/server/game/game_plugin.cpp @@ -35,15 +35,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void game_plugin::install() { - if (!register_module(detail::make_game_net_module(), module_update::disabled)) - { + if (!register_module(detail::make_game_net_module(), module_update::disabled)) { throw std::runtime_error("game_net_module registration rejected"); } } void game_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("game_net_module unregistration rejected"); } } diff --git a/src/server/game/game_plugin.hpp b/src/server/game/game_plugin.hpp index 43e74559a..1db6bded9 100644 --- a/src/server/game/game_plugin.hpp +++ b/src/server/game/game_plugin.hpp @@ -24,8 +24,7 @@ namespace ark { -class game_plugin final : public plugin_base -{ +class game_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/server/login/login_net_module.hpp b/src/server/login/login_net_module.hpp index 14e668cbf..1abe78362 100644 --- a/src/server/login/login_net_module.hpp +++ b/src/server/login/login_net_module.hpp @@ -26,8 +26,6 @@ namespace ark { -class login_net_module : public module -{ -}; +class login_net_module : public module {}; } // namespace ark diff --git a/src/server/login/login_net_module_impl.cpp b/src/server/login/login_net_module_impl.cpp index b6b791da8..9d3e71934 100644 --- a/src/server/login/login_net_module_impl.cpp +++ b/src/server/login/login_net_module_impl.cpp @@ -31,8 +31,7 @@ bool login_net_module_impl::init() { bus_module_ = get_plugin_manager()->try_find_module(); net_service_manager_module_ = get_plugin_manager()->try_find_module(); - if (bus_module_ == nullptr || net_service_manager_module_ == nullptr) - { + if (bus_module_ == nullptr || net_service_manager_module_ == nullptr) { ARK_LOG_ERROR("login network startup requires Bus and Net modules"); return false; } @@ -46,15 +45,13 @@ bool login_net_module_impl::post_init() { bool login_net_module_impl::start_server() { auto ret = net_service_manager_module_->create_server(); - if (!ret) - { + if (!ret) { ARK_LOG_ERROR("Cannot start server net, busid = {}", bus_module_->get_self_bus_name()); return false; } net_server_ = net_service_manager_module_->get_inter_net_server(); - if (net_server_ == nullptr) - { + if (net_server_ == nullptr) { ARK_LOG_ERROR("Cannot find server net, busid = {}", bus_module_->get_self_bus_name()); return false; } diff --git a/src/server/login/login_net_module_impl.hpp b/src/server/login/login_net_module_impl.hpp index 6738bb16a..7549ea765 100644 --- a/src/server/login/login_net_module_impl.hpp +++ b/src/server/login/login_net_module_impl.hpp @@ -29,8 +29,7 @@ namespace ark { -class login_net_module_impl final : public module_base -{ +class login_net_module_impl final : public module_base { public: bool init() override; bool post_init() override; diff --git a/src/server/login/login_plugin.cpp b/src/server/login/login_plugin.cpp index 0aa99e8a1..7e4ad7341 100644 --- a/src/server/login/login_plugin.cpp +++ b/src/server/login/login_plugin.cpp @@ -35,15 +35,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void login_plugin::install() { - if (!register_module(detail::make_login_net_module(), module_update::disabled)) - { + if (!register_module(detail::make_login_net_module(), module_update::disabled)) { throw std::runtime_error("login_net_module registration rejected"); } } void login_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("login_net_module unregistration rejected"); } } diff --git a/src/server/login/login_plugin.hpp b/src/server/login/login_plugin.hpp index aa6661737..058b1dc28 100644 --- a/src/server/login/login_plugin.hpp +++ b/src/server/login/login_plugin.hpp @@ -24,8 +24,7 @@ namespace ark { -class login_plugin final : public plugin_base -{ +class login_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/server/master/master_net_module.hpp b/src/server/master/master_net_module.hpp index d2a4f9be7..d393d12fb 100755 --- a/src/server/master/master_net_module.hpp +++ b/src/server/master/master_net_module.hpp @@ -24,8 +24,6 @@ namespace ark { -class master_net_module : public module -{ -}; +class master_net_module : public module {}; } // namespace ark \ No newline at end of file diff --git a/src/server/master/master_net_module_impl.cpp b/src/server/master/master_net_module_impl.cpp index 14c434f95..a1709a4ab 100644 --- a/src/server/master/master_net_module_impl.cpp +++ b/src/server/master/master_net_module_impl.cpp @@ -31,8 +31,7 @@ bool master_net_module_impl::init() { bus_module_ = get_plugin_manager()->try_find_module(); net_service_manager_module_ = get_plugin_manager()->try_find_module(); - if (bus_module_ == nullptr || net_service_manager_module_ == nullptr) - { + if (bus_module_ == nullptr || net_service_manager_module_ == nullptr) { ARK_LOG_ERROR("master network startup requires Bus and Net modules"); return false; } @@ -53,15 +52,13 @@ bool master_net_module_impl::post_init() { bool master_net_module_impl::start_server() { auto ret = net_service_manager_module_->create_server(); - if (!ret) - { + if (!ret) { ARK_LOG_ERROR("Cannot start server net, busid = {}", bus_module_->get_self_bus_name()); return false; } net_server_ = net_service_manager_module_->get_inter_net_server(); - if (net_server_ == nullptr) - { + if (net_server_ == nullptr) { ARK_LOG_ERROR("Cannot find server net, busid = {}", bus_module_->get_self_bus_name()); return false; } diff --git a/src/server/master/master_net_module_impl.hpp b/src/server/master/master_net_module_impl.hpp index 09bd3cac4..1a36cb2cc 100644 --- a/src/server/master/master_net_module_impl.hpp +++ b/src/server/master/master_net_module_impl.hpp @@ -31,8 +31,7 @@ namespace ark { -class master_net_module_impl final : public module_base -{ +class master_net_module_impl final : public module_base { public: bool init() override; bool post_init() override; diff --git a/src/server/master/master_plugin.cpp b/src/server/master/master_plugin.cpp index 8e700c69e..a2e095f1e 100644 --- a/src/server/master/master_plugin.cpp +++ b/src/server/master/master_plugin.cpp @@ -35,15 +35,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void master_plugin::install() { - if (!register_module(detail::make_master_net_module(), module_update::disabled)) - { + if (!register_module(detail::make_master_net_module(), module_update::disabled)) { throw std::runtime_error("master_net_module registration rejected"); } } void master_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("master_net_module unregistration rejected"); } } diff --git a/src/server/master/master_plugin.hpp b/src/server/master/master_plugin.hpp index 0781481e4..e4cc1f592 100755 --- a/src/server/master/master_plugin.hpp +++ b/src/server/master/master_plugin.hpp @@ -24,8 +24,7 @@ namespace ark { -class master_plugin final : public plugin_base -{ +class master_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/server/proxy/proxy_net_module.hpp b/src/server/proxy/proxy_net_module.hpp index 5975bc4dd..9bbea1ff9 100755 --- a/src/server/proxy/proxy_net_module.hpp +++ b/src/server/proxy/proxy_net_module.hpp @@ -24,8 +24,7 @@ namespace ark { -class proxy_net_module : public module -{ +class proxy_net_module : public module { public: virtual bool verify_connect_data(const std::string& account, const std::string& key) = 0; }; diff --git a/src/server/proxy/proxy_net_module_impl.cpp b/src/server/proxy/proxy_net_module_impl.cpp index 762f448ee..a7183c723 100644 --- a/src/server/proxy/proxy_net_module_impl.cpp +++ b/src/server/proxy/proxy_net_module_impl.cpp @@ -32,8 +32,7 @@ bool proxy_net_module_impl::init() { msg_module_ = get_plugin_manager()->try_find_module(); net_service_manager_module_ = get_plugin_manager()->try_find_module(); - if (bus_module_ == nullptr || net_service_manager_module_ == nullptr) - { + if (bus_module_ == nullptr || net_service_manager_module_ == nullptr) { ARK_LOG_ERROR("proxy network startup requires Bus and Net modules"); return false; } @@ -47,15 +46,13 @@ bool proxy_net_module_impl::post_init() { bool proxy_net_module_impl::start_server() { auto ret = net_service_manager_module_->create_server(); - if (!ret) - { + if (!ret) { ARK_LOG_ERROR("Cannot start server net, busid = {}", bus_module_->get_self_bus_name()); return false; } net_server_ = net_service_manager_module_->get_inter_net_server(); - if (net_server_ == nullptr) - { + if (net_server_ == nullptr) { ARK_LOG_ERROR("Cannot find server net, busid = {}", bus_module_->get_self_bus_name()); return false; } @@ -71,8 +68,7 @@ void proxy_net_module_impl::on_select_server_result_process(const net_msg* msg, bool proxy_net_module_impl::verify_connect_data(const std::string& account, const std::string& key) { auto connect_data_ptr = pending_connections_.find_value(account); - if (connect_data_ptr != nullptr && key == connect_data_ptr->connect_key) - { + if (connect_data_ptr != nullptr && key == connect_data_ptr->connect_key) { pending_connections_.erase(account); return true; } @@ -81,20 +77,15 @@ bool proxy_net_module_impl::verify_connect_data(const std::string& account, cons } void proxy_net_module_impl::on_socket_event(const net_event* event) { - switch (event->get_type()) - { - case net_event_type::connect: - { + switch (event->get_type()) { + case net_event_type::connect: { ARK_LOG_INFO("Connected success, id = {}", event->get_id()); on_client_connected(event->get_id()); - } - break; - case net_event_type::disconnect: - { + } break; + case net_event_type::disconnect: { ARK_LOG_INFO("Connection closed, id = {}", event->get_id()); on_client_disconnect(event->get_id()); - } - break; + } break; default: break; } diff --git a/src/server/proxy/proxy_net_module_impl.hpp b/src/server/proxy/proxy_net_module_impl.hpp index b9403f62c..583106d63 100644 --- a/src/server/proxy/proxy_net_module_impl.hpp +++ b/src/server/proxy/proxy_net_module_impl.hpp @@ -30,8 +30,7 @@ namespace ark { -class proxy_net_module_impl final : public module_base -{ +class proxy_net_module_impl final : public module_base { public: bool init() override; bool post_init() override; @@ -67,8 +66,7 @@ class proxy_net_module_impl final : public module_base()) - { + if (!unregister_module()) { throw std::runtime_error("proxy_net_module unregistration rejected"); } } diff --git a/src/server/proxy/proxy_plugin.hpp b/src/server/proxy/proxy_plugin.hpp index 9c7d048fd..6fa9361fa 100755 --- a/src/server/proxy/proxy_plugin.hpp +++ b/src/server/proxy/proxy_plugin.hpp @@ -24,8 +24,7 @@ namespace ark { -class proxy_plugin final : public plugin_base -{ +class proxy_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/server/router/router_net_module.hpp b/src/server/router/router_net_module.hpp index 4608c96c0..29d8ab28b 100755 --- a/src/server/router/router_net_module.hpp +++ b/src/server/router/router_net_module.hpp @@ -26,8 +26,7 @@ namespace ark { class net_server_service; -class router_net_module : public module -{ +class router_net_module : public module { public: virtual std::shared_ptr get_net_server() = 0; }; diff --git a/src/server/router/router_net_module_impl.cpp b/src/server/router/router_net_module_impl.cpp index 5efc61a79..22136f580 100644 --- a/src/server/router/router_net_module_impl.cpp +++ b/src/server/router/router_net_module_impl.cpp @@ -31,8 +31,7 @@ bool router_net_module_impl::init() { bus_module_ = get_plugin_manager()->try_find_module(); net_service_manager_module_ = get_plugin_manager()->try_find_module(); - if (bus_module_ == nullptr || net_service_manager_module_ == nullptr) - { + if (bus_module_ == nullptr || net_service_manager_module_ == nullptr) { ARK_LOG_ERROR("router network startup requires Bus and Net modules"); return false; } @@ -46,15 +45,13 @@ bool router_net_module_impl::post_init() { bool router_net_module_impl::start_server() { auto ret = net_service_manager_module_->create_server(); - if (!ret) - { + if (!ret) { ARK_LOG_ERROR("Cannot start server net, busid = {}", bus_module_->get_self_bus_name()); return false; } net_server_ = net_service_manager_module_->get_inter_net_server(); - if (net_server_ == nullptr) - { + if (net_server_ == nullptr) { ARK_LOG_ERROR("Cannot find server net, busid = {}", bus_module_->get_self_bus_name()); return false; } diff --git a/src/server/router/router_net_module_impl.hpp b/src/server/router/router_net_module_impl.hpp index cedd6f319..3b404f181 100644 --- a/src/server/router/router_net_module_impl.hpp +++ b/src/server/router/router_net_module_impl.hpp @@ -29,8 +29,7 @@ namespace ark { -class router_net_module_impl final : public module_base -{ +class router_net_module_impl final : public module_base { public: bool init() override; bool post_init() override; diff --git a/src/server/router/router_plugin.cpp b/src/server/router/router_plugin.cpp index f182085f7..15a1507dc 100644 --- a/src/server/router/router_plugin.cpp +++ b/src/server/router/router_plugin.cpp @@ -35,15 +35,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void router_plugin::install() { - if (!register_module(detail::make_router_net_module(), module_update::disabled)) - { + if (!register_module(detail::make_router_net_module(), module_update::disabled)) { throw std::runtime_error("router_net_module registration rejected"); } } void router_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("router_net_module unregistration rejected"); } } diff --git a/src/server/router/router_plugin.hpp b/src/server/router/router_plugin.hpp index 07fa1bcff..365ef5b66 100755 --- a/src/server/router/router_plugin.hpp +++ b/src/server/router/router_plugin.hpp @@ -24,8 +24,7 @@ namespace ark { -class router_plugin final : public plugin_base -{ +class router_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/server/simulate/simulate_define.hpp b/src/server/simulate/simulate_define.hpp index 76044b9f8..3216c3577 100644 --- a/src/server/simulate/simulate_define.hpp +++ b/src/server/simulate/simulate_define.hpp @@ -11,8 +11,7 @@ using simulate_net_id = int64_t; using simulate_trigger_cb_function = std::function; -class simulate_scene -{ +class simulate_scene { public: simulate_scene() { } @@ -37,8 +36,7 @@ class simulate_scene const guid_t& find_actor(const simulate_net_id obj_id) { auto iter = net_id_actor_list_.find(obj_id); - if (iter == net_id_actor_list_.end()) - { + if (iter == net_id_actor_list_.end()) { return null_guid; } @@ -47,8 +45,7 @@ class simulate_scene simulate_net_id find_obj(const guid_t& actor_obj_id) { auto iter = actor_net_id_list_.find(actor_obj_id); - if (iter == actor_net_id_list_.end()) - { + if (iter == actor_net_id_list_.end()) { return 0; } @@ -57,8 +54,7 @@ class simulate_scene void remove_obj(const simulate_net_id obj_id) { auto iter = net_id_actor_list_.find(obj_id); - if (iter == net_id_actor_list_.end()) - { + if (iter == net_id_actor_list_.end()) { return; } @@ -69,8 +65,7 @@ class simulate_scene void remove_actor(const guid_t& actor_obj_id) { auto iter = actor_net_id_list_.find(actor_obj_id); - if (iter == actor_net_id_list_.end()) - { + if (iter == actor_net_id_list_.end()) { return; } diff --git a/src/server/simulate/simulate_module.hpp b/src/server/simulate/simulate_module.hpp index 37a4c75ad..1dcf8d4f7 100644 --- a/src/server/simulate/simulate_module.hpp +++ b/src/server/simulate/simulate_module.hpp @@ -27,8 +27,7 @@ namespace ark { -class simulate_module : public module -{ +class simulate_module : public module { public: virtual bool create_scene(const std::string& scene_id, const int32_t index) = 0; virtual bool destroy_scene(const std::string& scene_id, const int32_t index) = 0; diff --git a/src/server/simulate/simulate_module_impl.cpp b/src/server/simulate/simulate_module_impl.cpp index 5e1cce691..681fa451a 100644 --- a/src/server/simulate/simulate_module_impl.cpp +++ b/src/server/simulate/simulate_module_impl.cpp @@ -32,14 +32,12 @@ std::unique_ptr detail::make_simulate_module() { #define GET_AND_CHECK_OBJ_EXIST(scene_id, index) \ auto simulate_scene = find_scene_obj_actors(scene_id, index); \ - if (!simulate_scene) \ - { \ + if (!simulate_scene) { \ ARK_LOG_ERROR("scene has not been created scene id = {} index = {} obj id = {}", scene_id, index, obj_id); \ return false; \ } \ \ - if (simulate_scene->exist(obj_id)) \ - { \ + if (simulate_scene->exist(obj_id)) { \ ARK_LOG_ERROR("has created this obj scene id = {} index = {} obj id = {}", scene_id, index, obj_id); \ return false; \ } @@ -54,15 +52,13 @@ bool simulate_module_impl::init() { bool simulate_module_impl::create_scene(const std::string& scene_id, const int32_t index) { auto simulate_scene = find_scene_obj_actors(scene_id, index); - if (simulate_scene) - { + if (simulate_scene) { ARK_LOG_ERROR("has created this scene id = {} index = {}", scene_id, index); return false; } auto scene_obj_id = physic_module_->create_scene(scene_id); - if (scene_obj_id == null_guid) - { + if (scene_obj_id == null_guid) { ARK_LOG_ERROR("create scene failed scene id = {} index = {}", scene_id, index); return false; } @@ -73,14 +69,12 @@ bool simulate_module_impl::create_scene(const std::string& scene_id, const int32 bool simulate_module_impl::destroy_scene(const std::string& scene_id, const int32_t index) { auto simulate_scene = find_scene_obj_actors(scene_id, index); - if (!simulate_scene) - { + if (!simulate_scene) { ARK_LOG_ERROR("does not have this scene id = {} index = {}", scene_id, index); return false; } - if (!physic_module_->destroy_scene(simulate_scene->get_scene_obj_id())) - { + if (!physic_module_->destroy_scene(simulate_scene->get_scene_obj_id())) { ARK_LOG_ERROR("destroy scene failed scene id = {} index = {}", scene_id, index); return false; } @@ -94,17 +88,13 @@ bool simulate_module_impl::create_box(const std::string& scene_id, const int32_t GET_AND_CHECK_OBJ_EXIST(scene_id, index); guid_t actor_obj_id; - if (dynamic) - { + if (dynamic) { actor_obj_id = physic_module_->create_dynamic_box_actor(simulate_scene->get_scene_obj_id(), position, size); - } - else - { + } else { actor_obj_id = physic_module_->create_static_box_actor(simulate_scene->get_scene_obj_id(), position, size); } - if (actor_obj_id == null_guid) - { + if (actor_obj_id == null_guid) { ARK_LOG_ERROR("create actor failed scene id = {} index = {} obj id = {}", scene_id, index, obj_id); return false; } @@ -118,19 +108,15 @@ bool simulate_module_impl::create_capsule(const std::string& scene_id, const int GET_AND_CHECK_OBJ_EXIST(scene_id, index); guid_t actor_obj_id; - if (dynamic) - { + if (dynamic) { actor_obj_id = physic_module_->create_dynamic_capsule_actor(simulate_scene->get_scene_obj_id(), position, raius, height); - } - else - { + } else { actor_obj_id = physic_module_->create_static_capsule_actor(simulate_scene->get_scene_obj_id(), position, raius, height); } - if (actor_obj_id == null_guid) - { + if (actor_obj_id == null_guid) { ARK_LOG_ERROR("create actor failed scene id = {} index = {} obj id = {}", scene_id, index, obj_id); return false; } @@ -144,17 +130,13 @@ bool simulate_module_impl::create_sphere(const std::string& scene_id, const int3 GET_AND_CHECK_OBJ_EXIST(scene_id, index); guid_t actor_obj_id; - if (dynamic) - { + if (dynamic) { actor_obj_id = physic_module_->create_dynamic_sphere_actor(simulate_scene->get_scene_obj_id(), position, raius); - } - else - { + } else { actor_obj_id = physic_module_->create_static_sphere_actor(simulate_scene->get_scene_obj_id(), position, raius); } - if (actor_obj_id == null_guid) - { + if (actor_obj_id == null_guid) { ARK_LOG_ERROR("create actor failed scene id = {} index = {} obj id = {}", scene_id, index, obj_id); return false; } @@ -166,21 +148,18 @@ bool simulate_module_impl::create_sphere(const std::string& scene_id, const int3 bool simulate_module_impl::update_actor( const std::string& scene_id, const int32_t index, const simulate_net_id obj_id, const physic3_d& position) { auto simulate_scene = find_scene_obj_actors(scene_id, index); - if (!simulate_scene) - { + if (!simulate_scene) { ARK_LOG_ERROR("scene has not been created scene id = {} index = {} obj id = {}", scene_id, index, obj_id); return false; } auto actor_obj_id = simulate_scene->find_actor(obj_id); - if (actor_obj_id == null_guid) - { + if (actor_obj_id == null_guid) { ARK_LOG_ERROR("does not have this obj scene id = {} index = {} obj id = {}", scene_id, index, obj_id); return false; } - if (!physic_module_->update_actor(actor_obj_id, position)) - { + if (!physic_module_->update_actor(actor_obj_id, position)) { ARK_LOG_ERROR("update acotr failed scene id = {} index = {} obj id = {}", scene_id, index, obj_id); return false; } @@ -191,21 +170,18 @@ bool simulate_module_impl::update_actor( bool simulate_module_impl::destroy_actor( const std::string& scene_id, const int32_t index, const simulate_net_id obj_id) { auto simulate_scene = find_scene_obj_actors(scene_id, index); - if (!simulate_scene) - { + if (!simulate_scene) { ARK_LOG_ERROR("scene has not been created scene id = {} index = {} obj id = {}", scene_id, index, obj_id); return false; } auto actor_obj_id = simulate_scene->find_actor(obj_id); - if (actor_obj_id == null_guid) - { + if (actor_obj_id == null_guid) { ARK_LOG_ERROR("does not have this obj scene id = {} index = {} obj id = {}", scene_id, index, obj_id); return false; } - if (!physic_module_->destroy_actor(actor_obj_id)) - { + if (!physic_module_->destroy_actor(actor_obj_id)) { ARK_LOG_ERROR("destroy acotr failed scene id = {} index = {} obj id = {}", scene_id, index, obj_id); return false; } @@ -217,15 +193,13 @@ bool simulate_module_impl::destroy_actor( bool simulate_module_impl::ray_cast(const std::string& scene_id, const int32_t index, const physic3_d& start, const physic3_d& direction, const float distance, simulate::ack_ray_cast& ack_ray_cast) { auto simulate_scene = find_scene_obj_actors(scene_id, index); - if (!simulate_scene) - { + if (!simulate_scene) { ARK_LOG_ERROR("has created this scene id = {} index = {}", scene_id, index); return false; } physic_ray_hit ray_hit; - if (!physic_module_->ray_cast(simulate_scene->get_scene_obj_id(), start, direction, distance, ray_hit)) - { + if (!physic_module_->ray_cast(simulate_scene->get_scene_obj_id(), start, direction, distance, ray_hit)) { ARK_LOG_ERROR("ray cast failed scene id = {} index = {}", scene_id, index); return false; } @@ -250,20 +224,17 @@ bool simulate_module_impl::register_trigger_call_back(simulate_trigger_cb_functi void simulate_module_impl::insert_scene_obj_actors( const guid_t& scene_obj_id, const std::string& scene_id, const int32_t index) { auto iter = scene_index_scene_list_.find(scene_id); - if (iter == scene_index_scene_list_.end()) - { + if (iter == scene_index_scene_list_.end()) { index_scene_map obj_actors_list; iter = scene_index_scene_list_.insert(std::make_pair(scene_id, obj_actors_list)).first; - if (iter == scene_index_scene_list_.end()) - { + if (iter == scene_index_scene_list_.end()) { return; } } auto& index_obj_list = iter->second; auto iter_index = index_obj_list.find(index); - if (iter_index != index_obj_list.end()) - { + if (iter_index != index_obj_list.end()) { return; } @@ -275,15 +246,13 @@ void simulate_module_impl::insert_scene_obj_actors( void simulate_module_impl::remove_scene_obj_actors(const std::string& scene_id, const int32_t index) { auto iter = scene_index_scene_list_.find(scene_id); - if (iter == scene_index_scene_list_.end()) - { + if (iter == scene_index_scene_list_.end()) { return; } auto& index_obj_list = iter->second; auto iter_index = index_obj_list.find(index); - if (iter_index == index_obj_list.end()) - { + if (iter_index == index_obj_list.end()) { return; } @@ -295,15 +264,13 @@ void simulate_module_impl::remove_scene_obj_actors(const std::string& scene_id, simulate_scene* simulate_module_impl::find_scene_obj_actors(const std::string& scene_id, const int32_t index) { auto iter = scene_index_scene_list_.find(scene_id); - if (iter == scene_index_scene_list_.end()) - { + if (iter == scene_index_scene_list_.end()) { return nullptr; } auto& index_obj_list = iter->second; auto iter_index = index_obj_list.find(index); - if (iter_index == index_obj_list.end()) - { + if (iter_index == index_obj_list.end()) { return nullptr; } @@ -316,8 +283,7 @@ simulate::simulate_vec3 simulate_module_impl::to_simulation_vector(const physic3 void simulate_module_impl::trigger_call_back(const guid_t& scene_obj_id, const physic_trigger_pair& trigger_pair) { auto iter = scene_index_pair_list_.find(scene_obj_id); - if (iter == scene_index_pair_list_.end()) - { + if (iter == scene_index_pair_list_.end()) { ARK_LOG_ERROR("does not find scene"); return; } @@ -327,14 +293,12 @@ void simulate_module_impl::trigger_call_back(const guid_t& scene_obj_id, const p auto index = scene_pair.second; auto simulate_scene = find_scene_obj_actors(scene_id, index); - if (!simulate_scene) - { + if (!simulate_scene) { ARK_LOG_ERROR("does not find scene"); return; } - if (trigger_call_back_function_) - { + if (trigger_call_back_function_) { simulate::trigger_pair trigger_pair; trigger_pair.trigger_obj_id = simulate_scene->find_obj(trigger_pair.trigger_obj_id); trigger_pair.other_obj_id = simulate_scene->find_obj(trigger_pair.other_obj_id); diff --git a/src/server/simulate/simulate_module_impl.hpp b/src/server/simulate/simulate_module_impl.hpp index bba03e51b..66d4ab97d 100644 --- a/src/server/simulate/simulate_module_impl.hpp +++ b/src/server/simulate/simulate_module_impl.hpp @@ -26,8 +26,7 @@ namespace ark { -class simulate_module_impl final : public module_base -{ +class simulate_module_impl final : public module_base { public: bool init() override; diff --git a/src/server/simulate/simulate_msg_define.hpp b/src/server/simulate/simulate_msg_define.hpp index af93b7cc2..68cb2b898 100644 --- a/src/server/simulate/simulate_msg_define.hpp +++ b/src/server/simulate/simulate_msg_define.hpp @@ -7,8 +7,7 @@ namespace simulate { -enum class simulate_msg_type : uint16_t -{ +enum class simulate_msg_type : uint16_t { simulate_msg_unknown = 0, ///req msg starts from 1 @@ -32,8 +31,7 @@ enum class simulate_msg_type : uint16_t SIMULATE_REG_SERVER = 65535, }; -class simulate_vec3 -{ +class simulate_vec3 { public: simulate_vec3() { } @@ -209,8 +207,7 @@ class ack_ray_cast //SIMULATE_MSG_ACK_RAY_CAST }; ///trigger -class trigger_pair -{ +class trigger_pair { public: int64_t trigger_obj_id{0}; //trigger object int64_t other_obj_id{0}; //other object diff --git a/src/server/simulate/simulate_net_module.hpp b/src/server/simulate/simulate_net_module.hpp index 17b5bee22..8864e4045 100644 --- a/src/server/simulate/simulate_net_module.hpp +++ b/src/server/simulate/simulate_net_module.hpp @@ -24,8 +24,7 @@ namespace ark { -class simulate_net_module : public module -{ +class simulate_net_module : public module { public: //virtual method }; diff --git a/src/server/simulate/simulate_net_module_impl.cpp b/src/server/simulate/simulate_net_module_impl.cpp index 4da087a5d..fa25449b3 100644 --- a/src/server/simulate/simulate_net_module_impl.cpp +++ b/src/server/simulate/simulate_net_module_impl.cpp @@ -34,8 +34,7 @@ bool simulate_net_module_impl::init() { bus_module_ = get_plugin_manager()->try_find_module(); net_service_manager_module_ = get_plugin_manager()->try_find_module(); - if (bus_module_ == nullptr || net_service_manager_module_ == nullptr || simulate_module_ == nullptr) - { + if (bus_module_ == nullptr || net_service_manager_module_ == nullptr || simulate_module_ == nullptr) { ARK_LOG_ERROR("simulate network startup requires Bus, Net and Simulate modules"); return false; } @@ -51,15 +50,13 @@ bool simulate_net_module_impl::post_init() { bool simulate_net_module_impl::start_server() { auto ret = net_service_manager_module_->create_server(); - if (!ret) - { + if (!ret) { ARK_LOG_ERROR("Cannot start server net, busid = {}", bus_module_->get_self_bus_name()); return false; } net_server_service_ = net_service_manager_module_->get_inter_net_server(); - if (net_server_service_ == nullptr) - { + if (net_server_service_ == nullptr) { ARK_LOG_ERROR("Cannot find server net, busid = {}", bus_module_->get_self_bus_name()); return false; } @@ -95,8 +92,7 @@ void simulate_net_module_impl::on_recv_msg(const net_msg* msg, conv_id_t session msgpack::object_handle obj_handle; msgpack::unpack(obj_handle, msg->get_msg_data(), msg->get_msg_length()); auto unpack_obj = obj_handle.get(); - if (unpack_obj.is_nil()) - { + if (unpack_obj.is_nil()) { ARK_LOG_ERROR("unpack failed, busid = {} msg id = {}", bus_module_->get_self_bus_name(), msg->get_msg_id()); return; } @@ -104,101 +100,79 @@ void simulate_net_module_impl::on_recv_msg(const net_msg* msg, conv_id_t session using namespace simulate; bool result = false; auto msg_id = (simulate_msg_type)msg->get_msg_id(); - switch (msg_id) - { - case simulate_msg_type::simulate_msg_req_create_scene: - { + switch (msg_id) { + case simulate_msg_type::simulate_msg_req_create_scene: { auto obj = unpack_obj.as(); update_bus_id(obj.scene_id, obj.index, msg->get_src_bus()); result = simulate_module_->create_scene(obj.scene_id, obj.index); - } - break; - case simulate_msg_type::simulate_msg_req_destroy_scene: - { + } break; + case simulate_msg_type::simulate_msg_req_destroy_scene: { auto obj = unpack_obj.as(); update_bus_id(obj.scene_id, obj.index, msg->get_src_bus()); result = simulate_module_->destroy_scene(obj.scene_id, obj.index); - } - break; - case simulate_msg_type::simulate_msg_req_create_dynamic_box: - { + } break; + case simulate_msg_type::simulate_msg_req_create_dynamic_box: { auto obj = unpack_obj.as(); update_bus_id(obj.scene_id, obj.index, msg->get_src_bus()); auto position = from_simulation_vector(obj.position); auto size = from_simulation_vector(obj.size); result = simulate_module_->create_box(obj.scene_id, obj.index, obj.obj_id, position, size, true); - } - break; - case simulate_msg_type::simulate_msg_req_create_dynamic_capsule: - { + } break; + case simulate_msg_type::simulate_msg_req_create_dynamic_capsule: { auto obj = unpack_obj.as(); update_bus_id(obj.scene_id, obj.index, msg->get_src_bus()); auto position = from_simulation_vector(obj.position); result = simulate_module_->create_capsule( obj.scene_id, obj.index, obj.obj_id, position, obj.raidus, obj.height, true); - } - break; - case simulate_msg_type::simulate_msg_req_create_dynamic_sphere: - { + } break; + case simulate_msg_type::simulate_msg_req_create_dynamic_sphere: { auto obj = unpack_obj.as(); update_bus_id(obj.scene_id, obj.index, msg->get_src_bus()); auto position = from_simulation_vector(obj.position); result = simulate_module_->create_sphere(obj.scene_id, obj.index, obj.obj_id, position, obj.raidus, true); - } - break; - case simulate_msg_type::simulate_msg_req_create_static_box: - { + } break; + case simulate_msg_type::simulate_msg_req_create_static_box: { auto obj = unpack_obj.as(); update_bus_id(obj.scene_id, obj.index, msg->get_src_bus()); auto position = from_simulation_vector(obj.position); auto size = from_simulation_vector(obj.size); result = simulate_module_->create_box(obj.scene_id, obj.index, obj.obj_id, position, size, false); - } - break; - case simulate_msg_type::simulate_msg_req_create_static_capsule: - { + } break; + case simulate_msg_type::simulate_msg_req_create_static_capsule: { auto obj = unpack_obj.as(); update_bus_id(obj.scene_id, obj.index, msg->get_src_bus()); auto position = from_simulation_vector(obj.position); result = simulate_module_->create_capsule( obj.scene_id, obj.index, obj.obj_id, position, obj.raidus, obj.height, false); - } - break; - case simulate_msg_type::simulate_msg_req_create_static_sphere: - { + } break; + case simulate_msg_type::simulate_msg_req_create_static_sphere: { auto obj = unpack_obj.as(); update_bus_id(obj.scene_id, obj.index, msg->get_src_bus()); auto position = from_simulation_vector(obj.position); result = simulate_module_->create_sphere(obj.scene_id, obj.index, obj.obj_id, position, obj.raidus, false); - } - break; - case simulate_msg_type::simulate_msg_req_update_actor: - { + } break; + case simulate_msg_type::simulate_msg_req_update_actor: { auto obj = unpack_obj.as(); update_bus_id(obj.scene_id, obj.index, msg->get_src_bus()); auto position = from_simulation_vector(obj.position); result = simulate_module_->update_actor(obj.scene_id, obj.index, obj.obj_id, position); - } - break; - case simulate_msg_type::simulate_msg_req_destroy_actor: - { + } break; + case simulate_msg_type::simulate_msg_req_destroy_actor: { auto obj = unpack_obj.as(); update_bus_id(obj.scene_id, obj.index, msg->get_src_bus()); result = simulate_module_->destroy_actor(obj.scene_id, obj.index, obj.obj_id); - } - break; - case simulate_msg_type::simulate_msg_req_ray_cast: - { + } break; + case simulate_msg_type::simulate_msg_req_ray_cast: { auto obj = unpack_obj.as(); update_bus_id(obj.scene_id, obj.index, msg->get_src_bus()); @@ -207,21 +181,16 @@ void simulate_net_module_impl::on_recv_msg(const net_msg* msg, conv_id_t session ack_ray_cast ack_ray_cast; result = simulate_module_->ray_cast(obj.scene_id, obj.index, start, direction, obj.distance, ack_ray_cast); - if (result) - { + if (result) { send_ack_ray_cast(obj.scene_id, obj.index, ack_ray_cast); } - } - break; - default: - { + } break; + default: { ARK_LOG_ERROR("unknown msg id = {}", msg->get_msg_id()); - } - break; + } break; } - if (!result) - { + if (!result) { ARK_LOG_ERROR( "deal message failed, busid = {} msg id = {}", bus_module_->get_self_bus_name(), msg->get_msg_id()); return; @@ -245,30 +214,26 @@ void simulate_net_module_impl::trigger_call_back( void simulate_net_module_impl::send_msg(const std::string& scene_id, const int32_t index, const simulate::simulate_msg_type msg_id, const msgpack::sbuffer& buffer) { int32_t target_bus_id; - if (!get_bus_id(scene_id, index, target_bus_id)) - { + if (!get_bus_id(scene_id, index, target_bus_id)) { ARK_LOG_ERROR("get bus id failed scene id = {} index = {} msg id = {}", scene_id, index, (int)msg_id); return; } auto bus_id = bus_module_->get_self_bus_id(); auto net_service_ptr = net_service_manager_module_->get_inter_net_server(); - if (!net_service_ptr) - { + if (!net_service_ptr) { ARK_LOG_ERROR("get net service failed scene id = {} index = {} msg id = {}", scene_id, index, (int)msg_id); return; } auto net_ptr = net_service_ptr->get_net(); - if (!net_ptr) - { + if (!net_ptr) { ARK_LOG_ERROR("get net failed scene id = {} index = {} msg id = {}", scene_id, index, (int)msg_id); return; } auto session_id = net_service_manager_module_->get_session_id(target_bus_id); - if (session_id == 0) - { + if (session_id == 0) { ARK_LOG_ERROR("get session id failed scene id = {} index = {} msg id = {}", scene_id, index, (int)msg_id); return; } @@ -300,39 +265,32 @@ void simulate_net_module_impl::send_ack_trigger( void simulate_net_module_impl::update_bus_id(const std::string& scene_id, const int32_t index, const int32_t bus_id) { auto iter = scene_index_bus_list_.find(scene_id); - if (iter == scene_index_bus_list_.end()) - { + if (iter == scene_index_bus_list_.end()) { index_bus_map index_bus; iter = scene_index_bus_list_.insert(std::make_pair(scene_id, index_bus)).first; - if (iter == scene_index_bus_list_.end()) - { + if (iter == scene_index_bus_list_.end()) { return; } } auto& index_bus_map = iter->second; auto iter_index = index_bus_map.find(index); - if (iter_index == index_bus_map.end()) - { + if (iter_index == index_bus_map.end()) { index_bus_map.insert(std::make_pair(index, bus_id)); - } - else - { + } else { iter_index->second = bus_id; } } bool simulate_net_module_impl::get_bus_id(const std::string& scene_id, const int32_t index, int32_t& bus_id) { auto iter = scene_index_bus_list_.find(scene_id); - if (iter == scene_index_bus_list_.end()) - { + if (iter == scene_index_bus_list_.end()) { return false; } auto& index_bus_map = iter->second; auto iter_index = index_bus_map.find(index); - if (iter_index == index_bus_map.end()) - { + if (iter_index == index_bus_map.end()) { return false; } diff --git a/src/server/simulate/simulate_net_module_impl.hpp b/src/server/simulate/simulate_net_module_impl.hpp index 01452c8d4..dc4182f33 100644 --- a/src/server/simulate/simulate_net_module_impl.hpp +++ b/src/server/simulate/simulate_net_module_impl.hpp @@ -29,8 +29,7 @@ namespace ark { -class simulate_net_module_impl final : public module_base -{ +class simulate_net_module_impl final : public module_base { public: bool init() override; bool post_init() override; diff --git a/src/server/simulate/simulate_plugin.cpp b/src/server/simulate/simulate_plugin.cpp index a0cba4f9b..cd937c97a 100644 --- a/src/server/simulate/simulate_plugin.cpp +++ b/src/server/simulate/simulate_plugin.cpp @@ -35,23 +35,19 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void simulate_plugin::install() { - if (!register_module(detail::make_simulate_net_module(), module_update::disabled)) - { + if (!register_module(detail::make_simulate_net_module(), module_update::disabled)) { throw std::runtime_error("simulate_net_module registration rejected"); } - if (!register_module(detail::make_simulate_module(), module_update::disabled)) - { + if (!register_module(detail::make_simulate_module(), module_update::disabled)) { throw std::runtime_error("simulate_module registration rejected"); } } void simulate_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("simulate_module unregistration rejected"); } - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("simulate_net_module unregistration rejected"); } } diff --git a/src/server/simulate/simulate_plugin.hpp b/src/server/simulate/simulate_plugin.hpp index bc5e445c2..2765687b9 100644 --- a/src/server/simulate/simulate_plugin.hpp +++ b/src/server/simulate/simulate_plugin.hpp @@ -24,8 +24,7 @@ namespace ark { -class simulate_plugin final : public plugin_base -{ +class simulate_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/src/server/world/world_net_module.hpp b/src/server/world/world_net_module.hpp index a0a80c689..4ac7f00ed 100644 --- a/src/server/world/world_net_module.hpp +++ b/src/server/world/world_net_module.hpp @@ -28,8 +28,7 @@ namespace ark { class net_server_service; -class world_net_module : public module -{ +class world_net_module : public module { public: virtual bool send_msg_to_game(const int game_id, const ark::protobuf::game_message_id msg_id, google::protobuf::Message& data_value, const guid_t player = guid_t()) = 0; diff --git a/src/server/world/world_net_module_impl.cpp b/src/server/world/world_net_module_impl.cpp index 9f296c1c5..41c647f11 100644 --- a/src/server/world/world_net_module_impl.cpp +++ b/src/server/world/world_net_module_impl.cpp @@ -35,8 +35,7 @@ bool world_net_module_impl::init() { msg_module_ = get_plugin_manager()->try_find_module(); net_service_manager_module_ = get_plugin_manager()->try_find_module(); - if (bus_module_ == nullptr || net_service_manager_module_ == nullptr) - { + if (bus_module_ == nullptr || net_service_manager_module_ == nullptr) { ARK_LOG_ERROR("world network startup requires Bus and Net modules"); return false; } @@ -50,15 +49,13 @@ bool world_net_module_impl::post_init() { bool world_net_module_impl::start_server() { auto ret = net_service_manager_module_->create_server(); - if (!ret) - { + if (!ret) { ARK_LOG_ERROR("Cannot start server net, busid = {}", bus_module_->get_self_bus_name()); return false; } net_server_ = net_service_manager_module_->get_inter_net_server(); - if (net_server_ == nullptr) - { + if (net_server_ == nullptr) { ARK_LOG_ERROR("Cannot find server net, busid = {}", bus_module_->get_self_bus_name()); return false; } @@ -170,13 +167,11 @@ bool world_net_module_impl::send_msg_to_game(const int game_id, const ark::proto bool world_net_module_impl::send_msg_to_game(const data_list& arg_object_var, const data_list& arg_game_id, const ark::protobuf::game_message_id msg_id, google::protobuf::Message& data_value) { - if (arg_game_id.get_count() != arg_object_var.get_count()) - { + if (arg_game_id.get_count() != arg_object_var.get_count()) { return false; } - for (size_t i = 0; i < arg_object_var.get_count(); i++) - { + for (size_t i = 0; i < arg_object_var.get_count(); i++) { guid_t ident_other = arg_object_var.int64(i); int game_id = arg_game_id.get_int(i); @@ -190,8 +185,7 @@ bool world_net_module_impl::send_msg_to_player( const ark::protobuf::game_message_id msg_id, google::protobuf::Message& data_value, const guid_t player) { int game_id = get_player_game_id(player); - if (game_id < 0) - { + if (game_id < 0) { return false; } @@ -206,8 +200,7 @@ bool world_net_module_impl::send_msg_to_player( std::shared_ptr world_net_module_impl::get_suit_proxy_for_enter() { // return mProxyMap.begin()->second; auto client_service_ptr = net_service_manager_module_->get_client_service(ark::app_type::ark_app_proxy); - if (client_service_ptr == nullptr) - { + if (client_service_ptr == nullptr) { ARK_LOG_INFO("Connection data not found connection"); return nullptr; } diff --git a/src/server/world/world_net_module_impl.hpp b/src/server/world/world_net_module_impl.hpp index 1eb27950f..36f539612 100644 --- a/src/server/world/world_net_module_impl.hpp +++ b/src/server/world/world_net_module_impl.hpp @@ -31,8 +31,7 @@ namespace ark { -class world_net_module_impl final : public module_base -{ +class world_net_module_impl final : public module_base { public: bool init() override; bool post_init() override; diff --git a/src/server/world/world_plugin.cpp b/src/server/world/world_plugin.cpp index 9a7d3c884..201db269b 100644 --- a/src/server/world/world_plugin.cpp +++ b/src/server/world/world_plugin.cpp @@ -35,15 +35,13 @@ ARK_EXPORT_FUNC void DllExitPlugin(plugin_manager* manager) { } void world_plugin::install() { - if (!register_module(detail::make_world_net_module(), module_update::disabled)) - { + if (!register_module(detail::make_world_net_module(), module_update::disabled)) { throw std::runtime_error("world_net_module registration rejected"); } } void world_plugin::uninstall() { - if (!unregister_module()) - { + if (!unregister_module()) { throw std::runtime_error("world_net_module unregistration rejected"); } } diff --git a/src/server/world/world_plugin.hpp b/src/server/world/world_plugin.hpp index 1652b5c96..c5bc4199c 100755 --- a/src/server/world/world_plugin.hpp +++ b/src/server/world/world_plugin.hpp @@ -24,8 +24,7 @@ namespace ark { -class world_plugin final : public plugin_base -{ +class world_plugin final : public plugin_base { public: void install() override; void uninstall() override; diff --git a/tests/app/application_preset_stop.cpp b/tests/app/application_preset_stop.cpp index c3d28d406..b06d85a80 100644 --- a/tests/app/application_preset_stop.cpp +++ b/tests/app/application_preset_stop.cpp @@ -16,16 +16,14 @@ namespace { using namespace std::chrono_literals; void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { throw std::runtime_error(message); } } void reap(pid_t pid) { int status; - while (waitpid(pid, &status, 0) < 0 && errno == EINTR) - { + while (waitpid(pid, &status, 0) < 0 && errno == EINTR) { } } @@ -38,54 +36,42 @@ void exit_failure(int) { } int fixture(const std::string& mode, int identity) { - if (mode == "success") - { + if (mode == "success") { std::signal(SIGTERM, exit_success); - } - else if (mode == "failure") - { + } else if (mode == "failure") { std::signal(SIGTERM, exit_failure); - } - else - { + } else { std::signal(SIGTERM, SIG_IGN); } const auto pid = getpid(); require(write(identity, &pid, sizeof(pid)) == sizeof(pid), "fixture PID write failed"); close(identity); - if (mode == "early_failure") - { + if (mode == "early_failure") { return 37; } - if (mode != "not_ready") - { + if (mode != "not_ready") { std::cout << "timers_module, PostInit" << std::endl; } - if (mode == "ready_early_failure") - { + if (mode == "ready_early_failure") { return 37; } - for (;;) - { + for (;;) { pause(); } } -class owned_case -{ +class owned_case { public: owned_case() = default; owned_case(const owned_case&) = delete; owned_case& operator=(const owned_case&) = delete; ~owned_case() { - if (helper_ > 0) - { + if (helper_ > 0) { kill(helper_, SIGKILL); reap(helper_); } - if (child_ > 0) - { + if (child_ > 0) { kill(child_, SIGKILL); } std::error_code ignored; @@ -100,33 +86,26 @@ class owned_case const auto descriptor = std::to_string(identity[1]); helper_ = fork(); require(helper_ >= 0, "helper fork failed"); - if (helper_ == 0) - { + if (helper_ == 0) { // Trap handlers in a non-interactive shell require these signals // to be catchable when the shell starts, regardless of its runner. constexpr int signals[] = {SIGHUP, SIGINT, SIGTERM, SIGALRM, SIGPIPE}; sigset_t catchable; - if (sigemptyset(&catchable) != 0) - { + if (sigemptyset(&catchable) != 0) { _exit(126); } - for (const int number : signals) - { - if (std::signal(number, SIG_DFL) == SIG_ERR || sigaddset(&catchable, number) != 0) - { + for (const int number : signals) { + if (std::signal(number, SIG_DFL) == SIG_ERR || sigaddset(&catchable, number) != 0) { _exit(126); } } - if (sigprocmask(SIG_UNBLOCK, &catchable, nullptr) != 0) - { + if (sigprocmask(SIG_UNBLOCK, &catchable, nullptr) != 0) { _exit(126); } close(identity[0]); - if (broken_reader) - { + if (broken_reader) { int output[2]; - if (pipe(output) != 0 || dup2(output[1], STDOUT_FILENO) < 0) - { + if (pipe(output) != 0 || dup2(output[1], STDOUT_FILENO) < 0) { _exit(126); } close(output[0]); @@ -144,15 +123,13 @@ class owned_case close(identity[0]); require(received == sizeof(child_) && child_ > 0, "fixture did not report its PID"); require(child_ != helper_ && child_ != unrelated, "fixture identity is not an owned child"); - if (interrupt) - { + if (interrupt) { require(kill(helper_, interrupt) == 0, "helper interrupt failed"); } const auto deadline = std::chrono::steady_clock::now() + 5s; int status = 0; pid_t exited = 0; - while ((exited = waitpid(helper_, &status, WNOHANG)) == 0 && std::chrono::steady_clock::now() < deadline) - { + while ((exited = waitpid(helper_, &status, WNOHANG)) == 0 && std::chrono::steady_clock::now() < deadline) { std::this_thread::sleep_for(10ms); } require(exited == helper_, "helper failed to clean up within its test bound"); @@ -178,46 +155,38 @@ class owned_case } // namespace int main(int argc, char* argv[]) { - if (argc == 4 && std::string(argv[1]) == "--fixture") - { + if (argc == 4 && std::string(argv[1]) == "--fixture") { return fixture(argv[2], std::stoi(argv[3])); } - if (argc != 2) - { + if (argc != 2) { std::cerr << "Usage: application_preset_stop " << std::endl; return 2; } // Build runners can ignore or block SIGINT. Exercise both inherited states // every run; the helper child must restore its signal preconditions. const auto previous_interrupt = std::signal(SIGINT, SIG_IGN); - if (previous_interrupt == SIG_ERR) - { + if (previous_interrupt == SIG_ERR) { std::cerr << "could not prepare inherited SIGINT disposition" << std::endl; return 1; } sigset_t blocked, previous_mask; if (sigemptyset(&blocked) != 0 || sigaddset(&blocked, SIGINT) != 0 || - sigprocmask(SIG_BLOCK, &blocked, &previous_mask) != 0) - { + sigprocmask(SIG_BLOCK, &blocked, &previous_mask) != 0) { std::cerr << "could not prepare inherited SIGINT mask" << std::endl; return 1; } const auto directory = std::filesystem::temp_directory_path() / ("ark-preset-stop-" + std::to_string(getpid())); - if (!std::filesystem::create_directory(directory)) - { + if (!std::filesystem::create_directory(directory)) { return 1; } const auto unrelated = fork(); - if (unrelated == 0) - { - for (;;) - { + if (unrelated == 0) { + for (;;) { pause(); } } int result = 0; - try - { + try { require(unrelated > 0, "unrelated fixture fork failed"); owned_case{}.run(argv[1], argv[0], directory, "success", 0, false, 0, unrelated); owned_case{}.run(argv[1], argv[0], directory, "failure", 0, false, 23, unrelated); @@ -229,14 +198,11 @@ int main(int argc, char* argv[]) { owned_case{}.run(argv[1], argv[0], directory, "not_ready", SIGINT, false, 130, unrelated); owned_case{}.run(argv[1], argv[0], directory, "not_ready", SIGTERM, false, 143, unrelated); owned_case{}.run(argv[1], argv[0], directory, "ignore_term", 0, true, 141, unrelated); - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { std::cerr << error.what() << std::endl; result = 1; } - if (unrelated > 0) - { + if (unrelated > 0) { kill(unrelated, SIGTERM); reap(unrelated); } diff --git a/tests/app/bus_plugin.cpp b/tests/app/bus_plugin.cpp index a4bdf1fbe..9916b6f6e 100644 --- a/tests/app/bus_plugin.cpp +++ b/tests/app/bus_plugin.cpp @@ -15,16 +15,14 @@ namespace { void require(bool condition, const std::string& message) { - if (!condition) - { + if (!condition) { std::cerr << message << std::endl; std::_Exit(1); } } // Observe Bus serialization through the existing public Net relation seam. -class recording_net final : public ark::net -{ +class recording_net final : public ark::net { public: void update() override { } diff --git a/tests/app/business_runtime_plugin.cpp b/tests/app/business_runtime_plugin.cpp index 263ec1b1b..2edb112b9 100644 --- a/tests/app/business_runtime_plugin.cpp +++ b/tests/app/business_runtime_plugin.cpp @@ -29,8 +29,7 @@ void trace(const std::string& event) { // Late protocol results arrive after cancellation and must not revive the task. // The native-readiness deadline case has no task dependency: scheduling the // coroutine chain must not consume its separate 50 ms shutdown deadline. -class probe_module final : public ark::module -{ +class probe_module final : public ark::module { public: probe_module(ark::plugin_manager& manager, std::string mode) : manager_(manager) @@ -47,42 +46,35 @@ class probe_module final : public ark::module } bool init() override { - if (mode_.starts_with("boundary_")) - { + if (mode_.starts_with("boundary_")) { // No task, native thread or later poll can delay these hooks. return true; } native_ = std::thread([this] { - while (!native_release_.load(std::memory_order_acquire)) - { + while (!native_release_.load(std::memory_order_acquire)) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } trace("native-exit"); native_exited_.store(true, std::memory_order_release); }); auto& tasks = manager_.create_task_group(*this, 2); - if (mode_ == "timeout_native") - { + if (mode_ == "timeout_native") { trace("native-pending"); return true; } return manager_.get_tasks(*this).start(sequence(this), [this](std::exception_ptr error) { trace("complete-begin"); - if (error) - { - try - { std::rethrow_exception(error); } - catch (const arknet::system_error& failure) - { - if (failure.code() != asio::error::operation_aborted) - { + if (error) { + try { + std::rethrow_exception(error); + } catch (const arknet::system_error& failure) { + if (failure.code() != asio::error::operation_aborted) { throw; } trace("task-cancelled"); } } - if (manager_.stop(manager_.get_now_time())) - { + if (manager_.stop(manager_.get_now_time())) { throw std::runtime_error("Teardown entered the final completion stack"); } trace("callback-stop-pending"); @@ -92,14 +84,11 @@ class probe_module final : public ark::module } bool update() override { - if (mode_.starts_with("boundary_")) - { - if (cleanup_started_) - { + if (mode_.starts_with("boundary_")) { + if (cleanup_started_) { trace("update-after-cleanup"); } - if (!stop_requested_) - { + if (!stop_requested_) { stop_requested_ = true; trace("request-stop"); #if !defined(_WIN32) @@ -111,45 +100,37 @@ class probe_module final : public ark::module const auto state = manager_.get_shutdown_state(); const auto stopping = state == ark::plugin_manager::shutdown_state::stopping || state == ark::plugin_manager::shutdown_state::timed_out; - if (stopping && !stop_observed_) - { + if (stopping && !stop_observed_) { stop_observed_ = true; stop_started_ = std::chrono::steady_clock::now(); auto& tasks = manager_.get_tasks(*this); - if (tasks.start(rejected_root(), [](std::exception_ptr) {}) != 0) - { + if (tasks.start(rejected_root(), [](std::exception_ptr) {}) != 0) { throw std::runtime_error("Shutdown accepted a new root task"); } trace("root-rejected"); - if (mode_ == "update_throw_unknown") - { + if (mode_ == "update_throw_unknown") { trace("update-throw"); throw 7; } - if (mode_ == "update_throw") - { + if (mode_ == "update_throw") { trace("update-throw"); throw std::runtime_error("test drain update exception"); } } - if ((mode_ == "update_throw" || mode_ == "update_throw_unknown") && stopping && !update_resumed_) - { + if ((mode_ == "update_throw" || mode_ == "update_throw_unknown") && stopping && !update_resumed_) { update_resumed_ = true; trace("update-resumed"); } const auto delayed = stopping && std::chrono::steady_clock::now() - stop_started_ < std::chrono::milliseconds(200); - if ((completion_returned_ || (stopping && mode_ == "timeout_native")) && !owner_stopped_) - { + if ((completion_returned_ || (stopping && mode_ == "timeout_native")) && !owner_stopped_) { owner_stopped_ = true; trace("owner-stop"); } - if (owner_stopped_ && ++native_updates_ > 2 && (mode_ != "timeout_native" || !delayed)) - { + if (owner_stopped_ && ++native_updates_ > 2 && (mode_ != "timeout_native" || !delayed)) { native_release_.store(true, std::memory_order_release); } - if ((pending_ || mode_ == "timeout_native") && !stop_requested_ && !stopping) - { + if ((pending_ || mode_ == "timeout_native") && !stop_requested_ && !stopping) { stop_requested_ = true; trace("request-stop"); #if !defined(_WIN32) @@ -157,8 +138,7 @@ class probe_module final : public ark::module #endif } if (pending_ && stopping && mode_ != "timeout_stalled" && - ((completion_returned_) || (mode_ == "timeout_task" && !delayed))) - { + ((completion_returned_) || (mode_ == "timeout_task" && !delayed))) { trace("late-reply"); auto complete = std::move(pending_); complete({}, "late"); @@ -168,31 +148,25 @@ class probe_module final : public ark::module } bool ready_to_shut() const override { - if (mode_.starts_with("boundary_")) - { + if (mode_.starts_with("boundary_")) { trace("ready"); - if (mode_ == "boundary_readiness") - { + if (mode_ == "boundary_readiness") { expire_shutdown_deadline(); } trace("ready-return"); return true; } - if (!owner_stopped_ || !native_exited_.load(std::memory_order_acquire)) - { + if (!owner_stopped_ || !native_exited_.load(std::memory_order_acquire)) { return false; } - if (mode_ == "ready_throw" || mode_ == "ready_throw_unknown") - { + if (mode_ == "ready_throw" || mode_ == "ready_throw_unknown") { trace("ready-throw"); - if (mode_ == "ready_throw_unknown") - { + if (mode_ == "ready_throw_unknown") { throw 7; } throw std::runtime_error("test readiness exception"); } - if (native_.joinable()) - { + if (native_.joinable()) { native_.join(); trace("native-joined"); } @@ -201,19 +175,17 @@ class probe_module final : public ark::module bool pre_shut() override { trace("pre-shut"); - if (mode_.starts_with("boundary_")) - { + if (mode_.starts_with("boundary_")) { cleanup_started_ = true; - if (mode_ == "boundary_pre_shut") - { + if (mode_ == "boundary_pre_shut") { expire_shutdown_deadline(); } trace("pre-shut-return"); return true; } if ((!sequence_finished_ && mode_ != "timeout_native") || - (!completion_returned_ && mode_ != "timeout_native") || pending_ || bridge_.pending() || native_.joinable()) - { + (!completion_returned_ && mode_ != "timeout_native") || pending_ || bridge_.pending() || + native_.joinable()) { throw std::runtime_error("Teardown preceded task-frame or native-resource retirement"); } return mode_ != "pre_shut_false"; @@ -221,13 +193,11 @@ class probe_module final : public ark::module bool shut() override { trace("shut"); - if (mode_ == "boundary_shut") - { + if (mode_ == "boundary_shut") { expire_shutdown_deadline(); trace("shut-return"); } - if (mode_ == "shut_throw") - { + if (mode_ == "shut_throw") { throw std::runtime_error("test shutdown exception"); } return mode_ != "shut_false"; @@ -242,16 +212,14 @@ class probe_module final : public ark::module // Reentrant stop cannot clean up this hook's active stack; its caller // must notice expiry after the successful hook returns. if (manager_.stop_until(manager_.get_now_time(), std::chrono::steady_clock::time_point::min()) || - manager_.get_shutdown_state() != ark::plugin_manager::shutdown_state::stopping) - { + manager_.get_shutdown_state() != ark::plugin_manager::shutdown_state::stopping) { throw std::runtime_error("Shutdown deadline entered the active lifecycle hook"); } trace("deadline-expired"); } std::uint64_t start(callback complete) { - if (pending_) - { + if (pending_) { throw std::logic_error("Overlapping controlled operations"); } pending_ = std::move(complete); @@ -265,8 +233,7 @@ class probe_module final : public ark::module } static ark::task<> sequence(probe_module* self) { - struct frame_lifetime - { + struct frame_lifetime { probe_module& owner; ~frame_lifetime() { @@ -275,8 +242,7 @@ class probe_module final : public ark::module } } lifetime{*self}; - if (self->mode_ == "timeout_task" || self->mode_ == "timeout_stalled") - { + if (self->mode_ == "timeout_task" || self->mode_ == "timeout_stalled") { co_await asio::this_coro::reset_cancellation_state(asio::disable_cancellation()); } const auto response = @@ -315,8 +281,7 @@ probe_module* active_module{}; ARK_EXPORT_FUNC void DllEntryPlugin(ark::plugin_manager* manager, const std::string& name, ark::logger* logger) { ark::logger::init(logger); active_module = new probe_module(*manager, manager->get_plugin_conf(name)); - if (!manager->add_module(active_module->get_name(), active_module) || !manager->add_update_module(active_module)) - { + if (!manager->add_module(active_module->get_name(), active_module) || !manager->add_update_module(active_module)) { throw std::runtime_error("Cannot register the business-runtime test module"); } } diff --git a/tests/app/http_client_drain.cpp b/tests/app/http_client_drain.cpp index 1c369d4d0..a50b7eac9 100644 --- a/tests/app/http_client_drain.cpp +++ b/tests/app/http_client_drain.cpp @@ -28,8 +28,7 @@ using namespace std::chrono_literals; using http_result = std::pair; void require(bool condition, const std::string& message) { - if (!condition) - { + if (!condition) { std::cerr << message << std::endl; std::_Exit(1); } @@ -38,16 +37,14 @@ void require(bool condition, const std::string& message) { template void wait_for(predicate ready, pump update) { const auto deadline = std::chrono::steady_clock::now() + 5s; - while (!ready() && std::chrono::steady_clock::now() < deadline) - { + while (!ready() && std::chrono::steady_clock::now() < deadline) { update(); std::this_thread::sleep_for(1ms); } require(ready(), "Timed out waiting for HTTP DSO drain"); } -class controlled_peer -{ +class controlled_peer { public: controlled_peer() { server_.bind_recv([this](auto& session, arknet::http_request::request_type& request) { @@ -111,8 +108,7 @@ class controlled_peer ark::task<> cancelled_request( ark::plugin_manager& manager, asio::steady_timer& resume, bool& entered, bool& frame_retired) { - struct frame_lifetime - { + struct frame_lifetime { bool& retired; ~frame_lifetime() { @@ -196,8 +192,7 @@ int main(int argc, char* argv[]) { require(frame_retired && tasks.closed() && manager.pending_tasks() == 0, "Manager did not cancel and retire the suspended host coroutine"); require(future.valid(), "Native HTTP request did not obtain a DSO-created future"); - if (future.wait_for(0ms) == std::future_status::ready) - { + if (future.wait_for(0ms) == std::future_status::ready) { const auto early = future.get(); require(false, "Actual Net DSO completed the accepted task request before its controlled wire response: " + early.second); diff --git a/tests/app/http_examples.cpp b/tests/app/http_examples.cpp index 7e9eb04d9..4b4284ffb 100644 --- a/tests/app/http_examples.cpp +++ b/tests/app/http_examples.cpp @@ -21,15 +21,13 @@ namespace { void require(bool condition, const std::string& message) { - if (!condition) - { + if (!condition) { std::cerr << message << std::endl; std::_Exit(1); } } -struct observations -{ +struct observations { unsigned future_posts{}; unsigned callback_posts{}; unsigned callbacks{}; @@ -43,8 +41,7 @@ struct observations std::thread::id owner = std::this_thread::get_id(); }; -class client_service final : public ark::module_base -{ +class client_service final : public ark::module_base { public: explicit client_service(observations& events) : events_(events) { @@ -97,8 +94,7 @@ class client_service final : public ark::module_base ++events_.updates; auto pending = std::move(events_.pending); events_.pending.clear(); - for (auto& callback : pending) - { + for (auto& callback : pending) { callback(); } return true; @@ -127,8 +123,7 @@ class client_service final : public ark::module_base observations& events_; }; -class lease_client final : public ark::etcd_client -{ +class lease_client final : public ark::etcd_client { public: explicit lease_client(observations& events) : events_(events) { @@ -156,8 +151,7 @@ class lease_client final : public ark::etcd_client observations& events_; }; -class etcd_service final : public ark::module_base -{ +class etcd_service final : public ark::module_base { public: explicit etcd_service(observations& events) : events_(events) { @@ -174,8 +168,7 @@ class etcd_service final : public ark::module_base observations& events_; }; -class server_service final : public ark::module_base -{ +class server_service final : public ark::module_base { public: explicit server_service(observations& events) : events_(events) { @@ -202,8 +195,7 @@ class server_service final : public ark::module_base arknet::http_router router_; }; -class services final : public ark::plugin_base -{ +class services final : public ark::plugin_base { public: explicit services(observations& events) : events_(events) { @@ -246,8 +238,7 @@ int main(int argc, char* argv[]) { ark::logger log; ark::logger::init(&log); log.set_log_func([](spdlog::level::level_enum, const std::string&) {}); - for (int run = 0; run < 2; ++run) - { + for (int run = 0; run < 2; ++run) { observations events; ark::plugin_manager manager; services fixtures(events); diff --git a/tests/app/http_plugin.cpp b/tests/app/http_plugin.cpp index e49968e76..fb44fd1ed 100644 --- a/tests/app/http_plugin.cpp +++ b/tests/app/http_plugin.cpp @@ -20,15 +20,13 @@ using request_type = arknet::http::request; using response_type = arknet::http::response; void require(bool condition, const std::string& message) { - if (!condition) - { + if (!condition) { std::cerr << message << std::endl; std::_Exit(1); } } -struct wire_result -{ +struct wire_result { arknet::error_code error; response_type response; }; @@ -38,8 +36,7 @@ wire_result request(uint16_t port, arknet::http::verb method, const std::string& asio::ip::tcp::socket socket(context); wire_result result; socket.connect({asio::ip::make_address("127.0.0.1"), port}, result.error); - if (result.error) - { + if (result.error) { return result; } request_type request(method, target, 11); @@ -47,8 +44,7 @@ wire_result request(uint16_t port, arknet::http::verb method, const std::string& request.body() = std::move(body); request.prepare_payload(); arknet::http::write(socket, request, result.error); - if (!result.error) - { + if (!result.error) { beast::flat_buffer buffer; arknet::http::read(socket, buffer, result.response, result.error); } @@ -57,8 +53,7 @@ wire_result request(uint16_t port, arknet::http::verb method, const std::string& return result; } -struct route_state -{ +struct route_state { explicit route_state(std::atomic& retired) : retired(retired) { } @@ -114,8 +109,7 @@ int main(int argc, char* argv[]) { router.add(arknet::http::verb::get, "/retire", [state](const auto&, auto& response) { state->active.store(true); const auto deadline = std::chrono::steady_clock::now() + 5s; - while (!state->release.load() && std::chrono::steady_clock::now() < deadline) - { + while (!state->release.load() && std::chrono::steady_clock::now() < deadline) { std::this_thread::sleep_for(1ms); } require(state->release.load(), "Controlled HTTP route was never released"); @@ -144,8 +138,7 @@ int main(int argc, char* argv[]) { wire_result pending_result; std::thread pending([&] { pending_result = request(port, arknet::http::verb::get, "/retire"); }); const auto deadline = std::chrono::steady_clock::now() + 5s; - while (!state->active.load() && std::chrono::steady_clock::now() < deadline) - { + while (!state->active.load() && std::chrono::steady_clock::now() < deadline) { std::this_thread::sleep_for(1ms); } require(state->active.load(), "Pending HTTP wire request never entered its route"); @@ -162,8 +155,7 @@ int main(int argc, char* argv[]) { pending_result.response.body() == "retired", "An admitted route lost its response during drain"); const auto drain_deadline = std::chrono::steady_clock::now() + 5s; - while (!manager.stop(1) && std::chrono::steady_clock::now() < drain_deadline) - { + while (!manager.stop(1) && std::chrono::steady_clock::now() < drain_deadline) { manager.update(1); std::this_thread::sleep_for(1ms); } diff --git a/tests/app/kernel_plugin.cpp b/tests/app/kernel_plugin.cpp index 29ce85c1a..b031ff63b 100644 --- a/tests/app/kernel_plugin.cpp +++ b/tests/app/kernel_plugin.cpp @@ -19,22 +19,18 @@ namespace { void require(bool condition, const std::string& message) { - if (!condition) - { + if (!condition) { std::cerr << message << '\n'; std::_Exit(1); } } -struct entity_events -{ +struct entity_events { int on_event(const ark::guid_t&, const std::string&, ark::entity_event event, const ark::data_list&) { - if (event == ark::entity_event::entity_evt_data_finished) - { + if (event == ark::entity_event::entity_evt_data_finished) { ++created; } - if (event == ark::entity_event::entity_evt_destroy) - { + if (event == ark::entity_event::entity_evt_destroy) { ++destroyed; } return 0; @@ -61,18 +57,14 @@ int main(int argc, char* argv[]) { log.set_log_func([](spdlog::level::level_enum, const std::string&) {}); entity_events events; ark::plugin_manager manager; - if (argc == 3) - { + if (argc == 3) { const std::string mode = argv[2]; require(mode == "missing-json" || mode == "invalid-json", "Unknown JSON failure mode"); - try - { + try { static_cast(manager.start( 0, std::string(argv[1]) + "/", "conf/", {{"ark_kernel_plugin", ""}, {"ark_utility_plugin", ""}})); require(false, "Kernel startup accepted missing or invalid required JSON"); - } - catch (const ark::entity_json::error& error) - { + } catch (const ark::entity_json::error& error) { require(error.source() == "resource/meta/entity_schema.json" && error.pointer() == "/" && manager.get_startup_failure().starts_with("init:"), "Kernel JSON startup failure lost its source, pointer or lifecycle phase"); @@ -161,10 +153,11 @@ int main(int argc, char* argv[]) { std::get(values.at(107)) == std::numeric_limits::max(), "Kernel DSO snapshot retained borrowed scalar state"); bool limited = false; - try - { static_cast(kernel->capture_scalar_snapshot(*entity, selection, {1, 0})); } - catch (const std::length_error&) - { limited = true; } + try { + static_cast(kernel->capture_scalar_snapshot(*entity, selection, {1, 0})); + } catch (const std::length_error&) { + limited = true; + } require(limited, "Kernel DSO capture did not enforce its limits"); auto lazy = kernel->create_entity(1002, 7, 0, "LazyOwner", 0, ark::data_list_impl{}); require(lazy != nullptr, "Kernel DSO lazy entity creation failed"); @@ -188,14 +181,12 @@ int main(int argc, char* argv[]) { "Kernel actual DSO"); require(events.destroyed == 1, "Kernel shutdown did not dispatch entity destruction exactly once"); require(manager.stop(++tick), "Repeated Kernel stop failed"); - if (retained) - { + if (retained) { require(std::get(retained->fields.at(100)) == "Configured" && std::get(retained->fields.at(111)).value == 42, "Kernel DSO unload invalidated an owning scalar snapshot"); } - if (retained_nested) - { + if (retained_nested) { require(std::get(retained_nested->root.scalars.fields.at(100)) == "Configured" && std::get(retained_nested->root.tables.at(200).rows.at(3).fields.at(2)) == std::string("a\0b", 3) && diff --git a/tests/app/missing_entry_plugin.cpp b/tests/app/missing_entry_plugin.cpp index 0ba91718e..ad8b7b308 100644 --- a/tests/app/missing_entry_plugin.cpp +++ b/tests/app/missing_entry_plugin.cpp @@ -9,8 +9,7 @@ class plugin_manager; namespace { -struct library_probe -{ +struct library_probe { library_probe() { std::cerr << "app-startup-test:library_loaded\n"; } diff --git a/tests/app/net_plugin.cpp b/tests/app/net_plugin.cpp index 0c026e95a..2161153b0 100644 --- a/tests/app/net_plugin.cpp +++ b/tests/app/net_plugin.cpp @@ -20,8 +20,7 @@ namespace { using namespace std::chrono_literals; void require(bool condition, const std::string& message) { - if (!condition) - { + if (!condition) { std::cerr << message << std::endl; std::_Exit(1); } @@ -30,8 +29,7 @@ void require(bool condition, const std::string& message) { template void wait_for(predicate ready, pump update) { const auto deadline = std::chrono::steady_clock::now() + 5s; - while (!ready() && std::chrono::steady_clock::now() < deadline) - { + while (!ready() && std::chrono::steady_clock::now() < deadline) { update(); std::this_thread::sleep_for(1ms); } @@ -46,8 +44,7 @@ arknet::error_code listener_probe(asio::io_context&, const asio::ip::tcp::endpoi bool completed = false; bool timed_out = false; deadline.async_wait([&](const arknet::error_code& error) { - if (!error && !completed) - { + if (!error && !completed) { timed_out = true; arknet::error_code ignored; probe.cancel(ignored); @@ -65,8 +62,7 @@ arknet::error_code listener_probe(asio::io_context&, const asio::ip::tcp::endpoi return result; } -struct receiver -{ +struct receiver { void on_message(const ark::net_msg* message, ark::conv_id_t session) { require(std::this_thread::get_id() == owner, "Net callback left the manager thread"); require(session != 0 && message->get_msg_id() == 45000, "Net callback arguments changed"); @@ -77,8 +73,7 @@ struct receiver std::string body; }; -struct drain_hold final : ark::module -{ +struct drain_hold final : ark::module { bool ready_to_shut() const override { return ready; } @@ -171,8 +166,7 @@ int main(int argc, char* argv[]) { std::atomic answered{}; std::atomic pending_received{}; peer.bind_recv([&](auto& session, arknet::http_request::request_type& request) { - if (request.target() == "/pending") - { + if (request.target() == "/pending") { pending_received.store(true); return; } diff --git a/tests/app/owner_drain.hpp b/tests/app/owner_drain.hpp index 107f835ff..800946023 100644 --- a/tests/app/owner_drain.hpp +++ b/tests/app/owner_drain.hpp @@ -13,8 +13,7 @@ namespace ark::test { inline const char* shutdown_state_name(plugin_manager::shutdown_state state) { - switch (state) - { + switch (state) { case plugin_manager::shutdown_state::running: return "running"; case plugin_manager::shutdown_state::stopping: @@ -44,42 +43,33 @@ template std::size_t drain_owner(plugin_manager& manager, next_timestamp&& now, std::chrono::steady_clock::time_point deadline, std::string_view context) { std::size_t deferred_frames{}; - try - { - while (!manager.stop_until(now(), deadline)) - { + try { + while (!manager.stop_until(now(), deadline)) { const auto state = manager.get_shutdown_state(); if (state != plugin_manager::shutdown_state::stopping || !manager.get_shutdown_failure().empty() || - manager.get_shutdown_exception()) - { + manager.get_shutdown_exception()) { fail_owner_drain(manager, context, "shutdown failed"); } - if (std::chrono::steady_clock::now() >= deadline) - { + if (std::chrono::steady_clock::now() >= deadline) { fail_owner_drain(manager, context, "owner drain deadline reached"); } - if (deferred_frames++ == 0) - { + if (deferred_frames++ == 0) { std::cout << context << ": deferred shutdown; state=" << shutdown_state_name(state) << "; phase=; owner updates continue" << std::endl; } - if (!manager.update(now())) - { + if (!manager.update(now())) { fail_owner_drain(manager, context, "owner update failed during drain"); } std::this_thread::yield(); } - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { std::cerr << context << ": " << error.what() << std::endl; fail_owner_drain(manager, context, "owner drain threw"); + } catch (...) { + fail_owner_drain(manager, context, "owner drain threw a nonstandard exception"); } - catch (...) - { fail_owner_drain(manager, context, "owner drain threw a nonstandard exception"); } if (manager.get_shutdown_state() != plugin_manager::shutdown_state::stopped || - !manager.get_shutdown_failure().empty() || manager.get_shutdown_exception()) - { + !manager.get_shutdown_failure().empty() || manager.get_shutdown_exception()) { fail_owner_drain(manager, context, "stop returned without normal completion"); } std::cout << context << ": state=stopped; deferred owner frames=" << deferred_frames << std::endl; diff --git a/tests/app/shutdown_request.cpp b/tests/app/shutdown_request.cpp index 68e37de8e..e0ce70823 100644 --- a/tests/app/shutdown_request.cpp +++ b/tests/app/shutdown_request.cpp @@ -17,8 +17,7 @@ int checks{}; void check(bool condition, const char* message) { ++checks; - if (!condition) - { + if (!condition) { throw std::runtime_error(message); } } @@ -54,15 +53,12 @@ void concurrent_requests() { const auto owner = std::this_thread::get_id(); std::atomic start{false}; std::vector producers; - for (int i = 0; i < 4; ++i) - { + for (int i = 0; i < 4; ++i) { producers.emplace_back([&start, i] { - while (!start.load(std::memory_order_acquire)) - { + while (!start.load(std::memory_order_acquire)) { std::this_thread::yield(); } - for (int request = 0; request < 256; ++request) - { + for (int request = 0; request < 256; ++request) { ark::app_detail::request_stop(i % 2 == 0 ? SIGINT : ark::app_detail::command_stop_reason); } }); @@ -72,19 +68,16 @@ void concurrent_requests() { int observed_reason = 0; std::thread::id observer; // Match main's single observation followed by leaving the update loop. - for (;;) - { + for (;;) { const auto reason = ark::app_detail::requested_stop_reason(); - if (reason != 0) - { + if (reason != 0) { observer = std::this_thread::get_id(); observed_reason = reason; ++owner_stop_calls; break; } } - for (auto& producer : producers) - { + for (auto& producer : producers) { producer.join(); } check(observer == owner, "stop work left the owner thread"); @@ -99,8 +92,7 @@ void worker_signal() { std::atomic raise_result{-1}; std::thread producer([&raise_result] { raise_result.store(std::raise(SIGINT), std::memory_order_relaxed); }); const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); - while (ark::app_detail::requested_stop_reason() == 0 && std::chrono::steady_clock::now() < deadline) - { + while (ark::app_detail::requested_stop_reason() == 0 && std::chrono::steady_clock::now() < deadline) { std::this_thread::yield(); } producer.join(); @@ -112,8 +104,7 @@ void command_request() { check(ark::app_detail::requested_stop_reason() == 0, "fresh process already has a stop request"); std::thread producer([] { ark::app_detail::request_stop(ark::app_detail::command_stop_reason); }); const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); - while (ark::app_detail::requested_stop_reason() == 0 && std::chrono::steady_clock::now() < deadline) - { + while (ark::app_detail::requested_stop_reason() == 0 && std::chrono::steady_clock::now() < deadline) { std::this_thread::yield(); } producer.join(); @@ -127,39 +118,25 @@ void command_request() { } // namespace int main(int argc, char** argv) { - try - { + try { check(argc == 2, "exactly one process mode is required"); const std::string_view mode = argv[1]; - if (mode == "signal-int") - { + if (mode == "signal-int") { signal_before_logger(SIGINT); - } - else if (mode == "signal-term") - { + } else if (mode == "signal-term") { signal_before_logger(SIGTERM); - } - else if (mode == "concurrent") - { + } else if (mode == "concurrent") { concurrent_requests(); - } - else if (mode == "worker-signal") - { + } else if (mode == "worker-signal") { worker_signal(); - } - else if (mode == "command") - { + } else if (mode == "command") { command_request(); - } - else - { + } else { throw std::runtime_error("unknown process mode"); } std::cout << mode << ": " << checks << " checks passed\n"; return 0; - } - catch (const std::exception& failure) - { + } catch (const std::exception& failure) { std::cerr << "Application stop-request check failed: " << failure.what() << '\n'; return 1; } diff --git a/tests/app/startup_cleanup_allocation.cpp b/tests/app/startup_cleanup_allocation.cpp index b441bca8f..a737ca60d 100644 --- a/tests/app/startup_cleanup_allocation.cpp +++ b/tests/app/startup_cleanup_allocation.cpp @@ -22,15 +22,13 @@ bool fail_allocations{}; const char* active_mode = "setup"; ark::plugin_manager* active_manager{}; -struct context -{ +struct context { std::unique_ptr wheel; }; ark::startup_cleanup_result release(void* pointer) { auto& capsule = *static_cast(pointer); - if (capsule.wheel) - { + if (capsule.wheel) { capsule.wheel->shut(); capsule.wheel.reset(); } @@ -38,16 +36,14 @@ ark::startup_cleanup_result release(void* pointer) { return ark::startup_cleanup_result::done; } -class allocation_module final : public ark::module -{ +class allocation_module final : public ark::module { public: std::shared_ptr capsule; bool partial_wheel{}; bool init() override { fail_allocations = true; - if (partial_wheel) - { + if (partial_wheel) { capsule->wheel->init(1); } throw std::bad_alloc(); @@ -56,10 +52,8 @@ class allocation_module final : public ark::module } // namespace void* operator new(std::size_t size) { - if (!fail_allocations) - { - if (auto* pointer = std::malloc(size == 0 ? 1 : size)) - { + if (!fail_allocations) { + if (auto* pointer = std::malloc(size == 0 ? 1 : size)) { return pointer; } } @@ -90,17 +84,19 @@ void operator delete[](void* pointer, std::size_t) noexcept { // Otherwise a sanitizer's nothrow interceptor can bypass this replacement and // hand memory from its operator-new family to our replacement delete/free. void* operator new(std::size_t size, const std::nothrow_t&) noexcept { - try - { return ::operator new(size); } - catch (...) - { return nullptr; } + try { + return ::operator new(size); + } catch (...) { + return nullptr; + } } void* operator new[](std::size_t size, const std::nothrow_t&) noexcept { - try - { return ::operator new[](size); } - catch (...) - { return nullptr; } + try { + return ::operator new[](size); + } catch (...) { + return nullptr; + } } void operator delete(void* pointer, const std::nothrow_t&) noexcept { @@ -119,30 +115,29 @@ int allocation_family_probe() { const bool allocated = single && array; ::operator delete(single); ::operator delete[](array); - if (!allocated) - { + if (!allocated) { return 10; } // A constructor exception uses the matching nothrow placement-delete form. - struct construction_failure - { + struct construction_failure { construction_failure() { throw 17; } }; bool single_threw = false, array_threw = false; - try - { (void)new (std::nothrow) construction_failure; } - catch (int error) - { single_threw = error == 17; } - try - { (void)new (std::nothrow) construction_failure[2]; } - catch (int error) - { array_threw = error == 17; } - if (!single_threw || !array_threw) - { + try { + (void)new (std::nothrow) construction_failure; + } catch (int error) { + single_threw = error == 17; + } + try { + (void)new (std::nothrow) construction_failure[2]; + } catch (int error) { + array_threw = error == 17; + } + if (!single_threw || !array_threw) { return 11; } @@ -153,12 +148,12 @@ int allocation_family_probe() { ::operator delete(single); ::operator delete[](array); bool throwing_failed = false; - try - { (void)::operator new(1); } - catch (const std::bad_alloc&) - { throwing_failed = true; } - if (!failed || !throwing_failed || !fail_allocations) - { + try { + (void)::operator new(1); + } catch (const std::bad_alloc&) { + throwing_failed = true; + } + if (!failed || !throwing_failed || !fail_allocations) { return 12; } ark::app_detail::write_native_stderr( @@ -169,8 +164,7 @@ int allocation_family_probe() { } // namespace int main(int argc, char** argv) { - if (argc != 2) - { + if (argc != 2) { return 2; } active_mode = argv[1]; @@ -178,13 +172,10 @@ int main(int argc, char** argv) { // crash reporting until the parent's process timeout hides the cause. std::set_terminate([]() noexcept { ark::app_detail::write_native_stderr("Startup allocation probe: unexpected std::terminate\n"); - if (active_manager) - { + if (active_manager) { const auto& call = active_manager->get_startup_call(); ark::app_detail::write_startup_failure(call.phase.data(), active_mode, call.owner.data()); - } - else - { + } else { ark::app_detail::write_startup_failure("unexpected terminate", active_mode); } #ifdef ARK_PLATFORM_WIN @@ -193,8 +184,7 @@ int main(int argc, char** argv) { std::_Exit(86); }); const std::string_view mode(argv[1]); - if (mode == "allocation-family") - { + if (mode == "allocation-family") { // The failed allocation flag stays armed until this isolated exit. std::_Exit(allocation_family_probe()); } @@ -212,49 +202,39 @@ int main(int argc, char** argv) { module.capsule = std::make_shared(); module.capsule->wheel = std::make_unique(); module.partial_wheel = mode == "partial-wheel"; - if (mode != "partial-wheel") - { + if (mode != "partial-wheel") { module.capsule->wheel->init(1); } - if (!manager.add_module("allocation-wheel", &module)) - { + if (!manager.add_module("allocation-wheel", &module)) { return 3; } std::array, ark::startup_cleanup_capacity> capsules; constexpr std::array keys{"resource-0", "resource-1", "resource-2", "resource-3", "resource-4", "resource-5", "resource-6", "resource-7", "resource-8", "resource-9", "resource-10", "resource-11", "resource-12", "resource-13", "resource-14", "resource-15"}; - if (mode == "registry") - { + if (mode == "registry") { capsules[0] = module.capsule; - for (std::size_t index = 1; index < capsules.size(); ++index) - { + for (std::size_t index = 1; index < capsules.size(); ++index) { capsules[index] = std::make_shared(); } } - try - { - if (mode == "capsule") - { + try { + if (mode == "capsule") { fail_allocations = true; (void)std::make_shared(); return 4; } // Preparation and fixed phase recording themselves must not allocate. fail_allocations = true; - if (mode == "registry") - { - for (std::size_t index{}; index < capsules.size(); ++index) - { - if (!manager.prepare_startup_cleanup(keys[index], "allocation-test", capsules[index], release)) - { + if (mode == "registry") { + for (std::size_t index{}; index < capsules.size(); ++index) { + if (!manager.prepare_startup_cleanup(keys[index], "allocation-test", capsules[index], release)) { return 5; } const auto owners = capsules[index].use_count(); const bool duplicate = manager.prepare_startup_cleanup(keys[index], "other-plugin", capsules[index], release); - if (duplicate || capsules[index].use_count() != owners) - { + if (duplicate || capsules[index].use_count() != owners) { return 9; } } @@ -262,38 +242,29 @@ int main(int argc, char** argv) { const bool overflow = manager.prepare_startup_cleanup("overflow", "allocation-test", module.capsule, release); const bool duplicate = manager.prepare_startup_cleanup(keys[0], "other-plugin", module.capsule, release); - if (overflow || duplicate || module.capsule.use_count() != owners) - { + if (overflow || duplicate || module.capsule.use_count() != owners) { return 9; } - } - else if (!manager.prepare_startup_cleanup("allocation-wheel", "allocation-test", module.capsule, release)) - { + } else if (!manager.prepare_startup_cleanup("allocation-wheel", "allocation-test", module.capsule, release)) { return 5; } ark::startup_call_record record; record.enter("allocation-wheel", "constructor"); - if (record.result != ark::startup_call_result::entered) - { + if (record.result != ark::startup_call_result::entered) { return 6; } - if (mode == "terminate-probe") - { + if (mode == "terminate-probe") { std::terminate(); } - if (mode == "call-argument") - { + if (mode == "call-argument") { const auto failed_argument = []() -> const std::string& { throw std::bad_alloc{}; }; (void)manager.start(1, failed_argument(), configuration_directory, plugins); } fail_allocations = mode == "phase-record" || mode == "registry"; (void)manager.start(1, library_directory, configuration_directory, plugins); - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { const bool entered = manager.get_startup_call().result != ark::startup_call_result::not_entered; - if ((mode == "phase-record" && !entered) || (mode == "call-argument" && entered)) - { + if ((mode == "phase-record" && !entered) || (mode == "call-argument" && entered)) { return 8; } // Failure remains armed through the real production diagnostic, cleanup diff --git a/tests/app/startup_cleanup_plugin.cpp b/tests/app/startup_cleanup_plugin.cpp index 66d4d726c..c6141a7e6 100644 --- a/tests/app/startup_cleanup_plugin.cpp +++ b/tests/app/startup_cleanup_plugin.cpp @@ -15,15 +15,13 @@ void mark(const char* value) { std::fflush(stderr); } -struct library_guard -{ +struct library_guard { ~library_guard() { mark("forbidden_dso_destructor"); } } guard; -struct wheel_context -{ +struct wheel_context { std::unique_ptr wheel; std::string mode; std::string name{"isolated_wheel"}; @@ -36,35 +34,27 @@ struct wheel_context ark::startup_cleanup_result release(void* pointer) { auto& context = *static_cast(pointer); mark("release_enter"); - if (context.mode.starts_with("multi:")) - { + if (context.mode.starts_with("multi:")) { mark(context.name.c_str()); - if (context.name == "middle") - { - if (context.mode == "multi:unsafe") - { + if (context.name == "middle") { + if (context.mode == "multi:unsafe") { return ark::startup_cleanup_result::unsafe; } - if (context.mode == "multi:failed") - { + if (context.mode == "multi:failed") { return ark::startup_cleanup_result::failed; } - if (context.mode == "multi:throw") - { + if (context.mode == "multi:throw") { throw 4; } } } - if (context.mode == "unsafe:init") - { + if (context.mode == "unsafe:init") { return ark::startup_cleanup_result::unsafe; } - if (context.mode == "cleanup_throw:init") - { + if (context.mode == "cleanup_throw:init") { throw 4; } - if (context.wheel) - { + if (context.wheel) { context.wheel->shut(); context.wheel.reset(); } @@ -72,24 +62,20 @@ ark::startup_cleanup_result release(void* pointer) { return ark::startup_cleanup_result::done; } -class isolated_wheel_module final : public ark::module -{ +class isolated_wheel_module final : public ark::module { public: explicit isolated_wheel_module(std::shared_ptr context) : context_(std::move(context)) { - if (context_->mode == "throw:before_acquire") - { + if (context_->mode == "throw:before_acquire") { throw std::runtime_error("constructor before acquire"); } context_->wheel = std::make_unique(); - if (context_->mode == "throw:partial_acquire") - { + if (context_->mode == "throw:partial_acquire") { throw std::runtime_error("constructor partial acquire"); } context_->wheel->init(1); mark("acquired"); - if (context_->mode == "throw:after_acquire") - { + if (context_->mode == "throw:after_acquire") { throw std::runtime_error("constructor after acquire"); } } @@ -136,15 +122,12 @@ class isolated_wheel_module final : public ark::module private: bool step(std::string_view phase) { mark(std::string(phase).c_str()); - if (context_->mode.starts_with("multi:")) - { + if (context_->mode.starts_with("multi:")) { return phase != "init"; } const auto separator = context_->mode.find(':'); - if (std::string_view(context_->mode).substr(separator + 1) == phase) - { - if (context_->mode.starts_with("throw:")) - { + if (std::string_view(context_->mode).substr(separator + 1) == phase) { + if (context_->mode.starts_with("throw:")) { throw std::runtime_error("wheel hook failure"); } return false; @@ -160,20 +143,16 @@ class isolated_wheel_module final : public ark::module ARK_EXPORT_FUNC void DllEntryPlugin(ark::plugin_manager* manager, const std::string& name, ark::logger* shared_logger) { ark::logger::init(shared_logger); const auto& mode = manager->get_plugin_conf(name); - if (mode.starts_with("multi:")) - { - for (const char* owner : {"older", "middle", "newer"}) - { + if (mode.starts_with("multi:")) { + for (const char* owner : {"older", "middle", "newer"}) { auto context = std::make_shared(); context->name = owner; context->mode = mode; - if (!manager->prepare_startup_cleanup(owner, name, context, release)) - { + if (!manager->prepare_startup_cleanup(owner, name, context, release)) { throw std::runtime_error("multi cleanup enrollment rejected before acquisition"); } auto module = std::make_unique(context); - if (!manager->add_module(module->get_name(), module.get())) - { + if (!manager->add_module(module->get_name(), module.get())) { throw std::runtime_error("multi module registration failed"); } module.release(); @@ -182,20 +161,17 @@ ARK_EXPORT_FUNC void DllEntryPlugin(ark::plugin_manager* manager, const std::str } auto context = std::make_shared(); context->mode = mode; - if (!manager->prepare_startup_cleanup("isolated_wheel", name, context, release)) - { + if (!manager->prepare_startup_cleanup("isolated_wheel", name, context, release)) { throw std::runtime_error("cleanup enrollment rejected before acquisition"); } // The host already holds a complete independent capsule if this constructor // throws. Only normal successful registration owns the complete module. auto module = std::make_unique(context); - if (!manager->add_module(module->get_name(), module.get())) - { + if (!manager->add_module(module->get_name(), module.get())) { throw std::runtime_error("module registration failed"); } module.release(); - if (context->mode == "throw:install") - { + if (context->mode == "throw:install") { throw std::runtime_error("partially published installation"); } } diff --git a/tests/app/startup_failure_plugin.cpp b/tests/app/startup_failure_plugin.cpp index 4cb58bf3c..b1f50ca71 100644 --- a/tests/app/startup_failure_plugin.cpp +++ b/tests/app/startup_failure_plugin.cpp @@ -13,15 +13,13 @@ namespace { -class startup_failure_module final : public ark::module -{ +class startup_failure_module final : public ark::module { public: void start_owned_io() { // Registration owns this real listener until DllExitPlugin, just as // runtime plugins own modules that can survive a partial startup. endpoint_ = std::make_unique(1024, 4096, 1); - if (!endpoint_->start("127.0.0.1", 0) || !endpoint_->is_started() || endpoint_->get_listen_port() == 0) - { + if (!endpoint_->start("127.0.0.1", 0) || !endpoint_->is_started() || endpoint_->get_listen_port() == 0) { throw std::runtime_error("Startup test endpoint did not start"); } std::cerr << "app-startup-test:owned_io_started port=" << endpoint_->get_listen_port() << '\n'; @@ -56,8 +54,7 @@ class startup_failure_module final : public ark::module bool update() override { // Record forbidden entry only once, keeping failure output bounded. - if (!updated_) - { + if (!updated_) { updated_ = true; record("update"); } @@ -75,14 +72,11 @@ class startup_failure_module final : public ark::module private: bool record(std::string_view phase) { std::cerr << "app-startup-test:" << phase << '\n'; - if (phase == failed_phase_) - { - if (behavior_ == "throw") - { + if (phase == failed_phase_) { + if (behavior_ == "throw") { throw std::runtime_error("test startup exception in " + std::string(phase)); } - if (behavior_ == "unknown") - { + if (behavior_ == "unknown") { throw 7; } return false; @@ -106,22 +100,18 @@ ARK_EXPORT_FUNC void DllEntryPlugin( ark::plugin_manager* manager, const std::string& plugin_name, ark::logger* shared_logger) { ark::logger::init(shared_logger); const auto& mode = manager->get_plugin_conf(plugin_name); - if (mode == "utf8:init") - { - if (manager->get_app_name() != "应用-é-🧪") - { + if (mode == "utf8:init") { + if (manager->get_app_name() != "应用-é-🧪") { throw std::runtime_error("Launcher lost UTF-8 application-name arguments"); } #ifdef ARK_PLATFORM_WIN // A shared console title can change in another process. Check it only // when this child owns its console, avoiding cross-test interference. DWORD console_process{}; - if (GetConsoleProcessList(&console_process, 1) == 1 && console_process == GetCurrentProcessId()) - { + if (GetConsoleProcessList(&console_process, 1) == 1 && console_process == GetCurrentProcessId()) { wchar_t title[256]{}; const auto expected_title = L"应用-é-🧪-1.0.1.1-" + std::to_wstring(manager->get_bus_id()); - if (GetConsoleTitleW(title, 256) == 0 || std::wstring_view(title) != expected_title) - { + if (GetConsoleTitleW(title, 256) == 0 || std::wstring_view(title) != expected_title) { throw std::runtime_error("Launcher lost the native Unicode console title"); } } @@ -133,13 +123,11 @@ ARK_EXPORT_FUNC void DllEntryPlugin( fixture = new startup_failure_module; fixture->fail_at(mode); fixture->start_owned_io(); - if (!manager->add_module(fixture->get_name(), fixture) || !manager->add_update_module(fixture)) - { + if (!manager->add_module(fixture->get_name(), fixture) || !manager->add_update_module(fixture)) { std::cerr << "Startup test module registration failed\n"; std::abort(); } - if (mode == "throw:load_plugin") - { + if (mode == "throw:load_plugin") { std::cerr << "app-startup-test:load_plugin\n"; throw std::runtime_error("test plugin entry exception"); } diff --git a/tests/app/static_services.cpp b/tests/app/static_services.cpp index ffa83a80d..395c4d481 100644 --- a/tests/app/static_services.cpp +++ b/tests/app/static_services.cpp @@ -55,11 +55,9 @@ void on_signal(int) { } void require(bool condition, const std::string& message) { - if (!condition) - { + if (!condition) { #ifdef ARK_COMPOSED_PLUGIN_TEST - if (composed_peer) - { + if (composed_peer) { std::cerr << message << std::endl; std::_Exit(1); } @@ -83,8 +81,7 @@ void write_configuration(const std::string& endpoint) { "[[bus.applications]]\nname = 'login'\ntype = 32\n" "[[bus.relations]]\nsource = 'game'\ntarget = 'world'\n" "[[bus.relations]]\nsource = 'game'\ntarget = 'game'\n"; - for (const auto& id : {"1.1.31.1", "1.1.30.1", "1.2.30.1", "2.1.30.1", "1.1.32.1"}) - { + for (const auto& id : {"1.1.31.1", "1.1.30.1", "1.2.30.1", "2.1.30.1", "1.1.32.1"}) { output << "[[bus.processes]]\nbus_id = '" << id << "'\nserver_endpoint = ''\nintranet_endpoint = '" << (std::string(id) == "1.1.30.1" ? endpoint : "") << "'\nthreads = 1\nmax_connections = 10\n"; } @@ -95,8 +92,7 @@ void write_configuration(const std::string& endpoint) { #ifdef ARK_COMPOSED_PLUGIN_TEST // No Kernel/Net object crosses onto an HTTP worker. Only this independently // owned capture is retained by the native route, and snapshots own their values. -struct route_capture -{ +struct route_capture { std::thread::id owner; std::atomic& retired; std::atomic calls{}; @@ -131,15 +127,13 @@ void binary_echo(unsigned short port) { arknet::error_code result; stream.expires_at(bounded_deadline(2s)); stream.async_connect({asio::ip::make_address("127.0.0.1"), port}, [&](arknet::error_code error) { - if (error) - { + if (error) { result = error; return; } stream.expires_at(bounded_deadline(2s)); arknet::http::async_write(stream, request, [&](arknet::error_code error, std::size_t) { - if (error) - { + if (error) { result = error; return; } @@ -153,8 +147,7 @@ void binary_echo(unsigned short port) { "Composed HTTP binary echo did not complete while SS was live"); } -class composition_probe -{ +class composition_probe { public: composition_probe(ark::plugin_manager& manager, unsigned short port) : manager_(manager) @@ -181,8 +174,7 @@ class composition_probe } ~composition_probe() { - if (std::uncaught_exceptions()) - { + if (std::uncaught_exceptions()) { std::cerr << "Composed peer failed; retain live callback/DSO owners until isolated exit" << std::endl; std::_Exit(1); } @@ -218,8 +210,7 @@ class composition_probe }; #endif -struct receiver -{ +struct receiver { ark::plugin_manager& manager; ark::net_service_manager_module& network; ark::msg_module& messages; @@ -255,21 +246,16 @@ struct receiver require(body.ParseFromArray(message->get_msg_data(), static_cast(message->get_msg_length())) && body.y() == 12.5F && body.z() == -7.0F, "SS response Protobuf payload changed"); - if (body.x() == 1.0F) - { - if (replies == 0 && !defer_markers) - { + if (body.x() == 1.0F) { + if (replies == 0 && !defer_markers) { mark("first-roundtrip"); } replies = 1; - } - else - { + } else { require(body.x() == 2.0F && replies == 1 && disconnects == 1 && connects == 2, "Restart response arrived without exactly one disconnect and reconnect"); replies = 2; - if (!defer_markers) - { + if (!defer_markers) { mark("second-roundtrip"); } } @@ -278,12 +264,9 @@ struct receiver void event(const ark::net_event* event) { require(std::this_thread::get_id() == owner, "SS connection event left manager owner thread"); require(event->get_bus_id() == server_id.bus_id, "Unexpected static target connection event"); - if (event->get_type() == ark::net_event_type::connect) - { + if (event->get_type() == ark::net_event_type::connect) { ++connects; - } - else if (event->get_type() == ark::net_event_type::disconnect) - { + } else if (event->get_type() == ark::net_event_type::disconnect) { ++disconnects; ark::protobuf::point_3d body; require(replies == 1 && !network.get_net_connection_bus(client_id.bus_id, server_id.bus_id) && @@ -304,13 +287,11 @@ int peer(const std::string& role, const std::string& plugins, int generation, un manager.set_bus_id(role == "server" ? server_id.bus_id : client_id.bus_id); bool started = false; std::string diagnostic; - try - { + try { std::unordered_map selected{ {"ark_bus_plugin", "bus.toml"}, {"ark_net_plugin", ""}, {"ark_utility_plugin", ""}}; #ifdef ARK_COMPOSED_PLUGIN_TEST - if (http_port) - { + if (http_port) { selected.emplace("ark_kernel_plugin", ""); selected.emplace("ark_http_plugin", role + "-http.toml"); } @@ -318,14 +299,10 @@ int peer(const std::string& role, const std::string& plugins, int generation, un require(http_port == 0 && remote_http_port == 0, "Composition needs the independent composed test target"); #endif started = manager.start(ark::date_time::get_now_time(), plugins + "/", "", selected); - } - catch (const std::exception& error) - { - if (role != "invalid") - { + } catch (const std::exception& error) { + if (role != "invalid") { #ifdef ARK_COMPOSED_PLUGIN_TEST - if (http_port) - { + if (http_port) { std::cerr << "Composed startup failed: " << error.what() << std::endl; std::_Exit(1); } @@ -334,8 +311,7 @@ int peer(const std::string& role, const std::string& plugins, int generation, un } diagnostic = error.what(); } - if (role == "invalid") - { + if (role == "invalid") { require(!started && manager.get_startup_failure().find("post_init:") != std::string::npos && diagnostic.find("static Bus target 1.1.30.1") != std::string::npos && diagnostic.find("intranet_endpoint") != std::string::npos, @@ -353,8 +329,7 @@ int peer(const std::string& role, const std::string& plugins, int generation, un require(network && messages, "Actual Bus/Net interfaces missing"); #ifdef ARK_COMPOSED_PLUGIN_TEST std::unique_ptr composed; - if (http_port) - { + if (http_port) { composed = std::make_unique(manager, http_port); } int http_generation{}; @@ -362,17 +337,14 @@ int peer(const std::string& role, const std::string& plugins, int generation, un receiver received{manager, *network, *messages, generation}; received.defer_markers = http_port != 0; auto clients = network->get_client_service(ark::app_type::ark_app_world); - if (role == "server") - { + if (role == "server") { require(!clients, "Undeclared outgoing relation created a server client"); require(network->create_server(), "Actual SS listener failed to start"); auto server = network->get_intra_net_server(); require(server && !network->get_inter_net_server(), "Static target listener selection changed"); require(server->reg_msg_callback(45010, &received, &receiver::request), "SS request callback rejected"); mark("server-ready-" + std::to_string(generation)); - } - else - { + } else { require(clients && !network->get_client_service(ark::app_type::ark_app_game) && !network->get_client_service(ark::app_type::ark_app_login), "Static bootstrap did not exclude self or undeclared type"); @@ -385,12 +357,10 @@ int peer(const std::string& role, const std::string& plugins, int generation, un // Existing reconnect interval is 30s. Allow 5s for the initial and final // round trips; do not change or accelerate the production retry clock. const auto deadline = started_at + 40s; - while (!stopping && std::chrono::steady_clock::now() < deadline && (role == "server" || received.replies != 2)) - { + while (!stopping && std::chrono::steady_clock::now() < deadline && (role == "server" || received.replies != 2)) { require(manager.update(ark::date_time::get_now_time()), "Actual plugin update failed"); #ifdef ARK_COMPOSED_PLUGIN_TEST - if (composed && role == "client" && received.replies > http_generation) - { + if (composed && role == "client" && received.replies > http_generation) { binary_echo(http_port); binary_echo(remote_http_port); http_generation = received.replies; @@ -399,14 +369,12 @@ int peer(const std::string& role, const std::string& plugins, int generation, un mark(http_generation == 1 ? "first-roundtrip" : "second-roundtrip"); } #endif - if (role == "client") - { + if (role == "client") { require(!clients->get_connection_info(ark::bus_addr(1, 2, 30, 1).bus_id) && !clients->get_connection_info(ark::bus_addr(2, 1, 30, 1).bus_id), "Bootstrap crossed configured channel/zone boundary"); const auto now = std::chrono::steady_clock::now(); - if (now >= send_at && network->get_net_connection_bus(client_id.bus_id, server_id.bus_id)) - { + if (now >= send_at && network->get_net_connection_bus(client_id.bus_id, server_id.bus_id)) { ark::protobuf::point_3d body; body.set_y(12.5F); body.set_z(-7.0F); @@ -421,8 +389,7 @@ int peer(const std::string& role, const std::string& plugins, int generation, un // Drop public shared services while their DSO implementations remain loaded. clients.reset(); #ifdef ARK_COMPOSED_PLUGIN_TEST - if (composed) - { + if (composed) { composed->before_stop(); } #endif @@ -430,16 +397,14 @@ int peer(const std::string& role, const std::string& plugins, int generation, un manager, ark::date_time::get_now_time, std::chrono::steady_clock::now() + 5s, "Static Bus actual DSOs"); require(manager.stop(ark::date_time::get_now_time()), "Actual plugin normal repeated stop failed"); #ifdef ARK_COMPOSED_PLUGIN_TEST - if (composed) - { + if (composed) { composed->after_stop(); } #endif return 0; } -class child -{ +class child { public: child(const std::string& executable, const std::string& role, const std::string& plugins, int generation, const std::string& log_name, unsigned short http_port = 0, unsigned short remote_http_port = 0) { @@ -448,21 +413,16 @@ class child const auto remote_http_text = std::to_string(remote_http_port); pid_ = ::fork(); require(pid_ >= 0, "fork failed"); - if (pid_ == 0) - { + if (pid_ == 0) { const auto log = ::open(log_name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0600); - if (log < 0 || ::dup2(log, STDOUT_FILENO) < 0 || ::dup2(log, STDERR_FILENO) < 0) - { + if (log < 0 || ::dup2(log, STDOUT_FILENO) < 0 || ::dup2(log, STDERR_FILENO) < 0) { ::_exit(126); } ::close(log); - if (http_port) - { + if (http_port) { ::execl(executable.c_str(), executable.c_str(), role.c_str(), plugins.c_str(), generation_text.c_str(), http_text.c_str(), remote_http_text.c_str(), static_cast(nullptr)); - } - else - { + } else { ::execl(executable.c_str(), executable.c_str(), role.c_str(), plugins.c_str(), generation_text.c_str(), static_cast(nullptr)); } @@ -474,22 +434,18 @@ class child child& operator=(const child&) = delete; ~child() { - if (pid_ > 0) - { + if (pid_ > 0) { ::kill(pid_, SIGKILL); - while (::waitpid(pid_, &status_, 0) < 0 && errno == EINTR) - { + while (::waitpid(pid_, &status_, 0) < 0 && errno == EINTR) { } } } bool exited() { - if (pid_ > 0) - { + if (pid_ > 0) { const auto result = ::waitpid(pid_, &status_, WNOHANG); require(result >= 0 || errno == EINTR, "waitpid failed"); - if (result == pid_) - { + if (result == pid_) { pid_ = -1; } } @@ -503,8 +459,7 @@ class child void finish() { const auto deadline = bounded_deadline(5s); - while (!exited() && std::chrono::steady_clock::now() < deadline) - { + while (!exited() && std::chrono::steady_clock::now() < deadline) { std::this_thread::sleep_for(5ms); } require(exited() && WIFEXITED(status_) && WEXITSTATUS(status_) == 0, "Owned child did not exit normally"); @@ -517,8 +472,7 @@ class child void await_marker(const std::string& name, child& process, std::chrono::seconds timeout) { const auto deadline = bounded_deadline(timeout); - while (!std::filesystem::exists(name) && std::chrono::steady_clock::now() < deadline) - { + while (!std::filesystem::exists(name) && std::chrono::steady_clock::now() < deadline) { require(!process.exited(), "Owned child exited before " + name); std::this_thread::sleep_for(5ms); } @@ -533,16 +487,13 @@ int controller(const std::string& executable, const std::string& plugins, const std::filesystem::create_directories(directory); std::filesystem::current_path(directory); std::cout << "Static Bus raw child logs: " << directory << std::endl; - if (!schema.empty()) - { + if (!schema.empty()) { controller_deadline = std::chrono::steady_clock::now() + 55s; } int invalid_case = 0; - if (schema.empty()) - { + if (schema.empty()) { for (const auto& endpoint : {"", "tcp://0.0.0.0:1234", "tcp://[::]:1234", "tcp://[0:0:0:0:0:0:0:0]:1234", - "tcp://127.0.0.1:0", "ws://127.0.0.1:1234", "tcp://127.0.0.1:1234/path"}) - { + "tcp://127.0.0.1:0", "ws://127.0.0.1:1234", "tcp://127.0.0.1:1234/path"}) { write_configuration(endpoint); child invalid(executable, "invalid", plugins, 0, "invalid-" + std::to_string(++invalid_case) + ".log"); invalid.finish(); @@ -554,16 +505,14 @@ int controller(const std::string& executable, const std::string& plugins, const write_configuration("tcp://127.0.0.1:" + std::to_string(port)); unsigned short server_http{}, client_http{}; #ifdef ARK_COMPOSED_PLUGIN_TEST - if (!schema.empty()) - { + if (!schema.empty()) { std::filesystem::create_directories("resource/meta"); std::filesystem::copy_file(schema, "resource/meta/entity_schema.json"); asio::ip::tcp::acceptor server_reservation(context, {asio::ip::make_address("127.0.0.1"), 0}); asio::ip::tcp::acceptor client_reservation(context, {asio::ip::make_address("127.0.0.1"), 0}); server_http = server_reservation.local_endpoint().port(); client_http = client_reservation.local_endpoint().port(); - for (const auto& entry : {std::pair{"server", server_http}, std::pair{"client", client_http}}) - { + for (const auto& entry : {std::pair{"server", server_http}, std::pair{"client", client_http}}) { std::ofstream http(std::string(entry.first) + "-http.toml"); http.exceptions(std::ios::failbit | std::ios::badbit); http << "[http]\nhost = '127.0.0.1'\nport = " << entry.second << "\nthreads = 3\n"; @@ -577,8 +526,7 @@ int controller(const std::string& executable, const std::string& plugins, const await_marker("first-roundtrip", client, 5s); first.stop(); #ifdef ARK_COMPOSED_PLUGIN_TEST - if (server_http) - { + if (server_http) { require_refused(server_http); require_refused(port); } @@ -590,8 +538,7 @@ int controller(const std::string& executable, const std::string& plugins, const client.finish(); second.stop(); #ifdef ARK_COMPOSED_PLUGIN_TEST - if (server_http) - { + if (server_http) { require_refused(server_http); require_refused(client_http); require_refused(port); @@ -600,8 +547,7 @@ int controller(const std::string& executable, const std::string& plugins, const "owned snapshots, callback retirement, endpoint closure and repeated normal stop passed\n"; } #endif - if (schema.empty()) - { + if (schema.empty()) { std::cout << "Static Bus actual two-process DSOs: eligibility, invalid endpoint diagnostics, SS registration, " "Protobuf request/response, lost-route rejection, target restart, 30s policy reconnect and normal " "stop passed\n"; @@ -611,31 +557,24 @@ int controller(const std::string& executable, const std::string& plugins, const } // namespace int main(int argc, char* argv[]) { - try - { - if (argc == 3) - { + try { + if (argc == 3) { return controller( std::filesystem::absolute(argv[0]).string(), std::filesystem::absolute(argv[1]).string(), argv[2]); } #ifdef ARK_COMPOSED_PLUGIN_TEST - if (argc == 5 && std::string(argv[3]) == "--composed") - { + if (argc == 5 && std::string(argv[3]) == "--composed") { return controller(std::filesystem::absolute(argv[0]).string(), std::filesystem::absolute(argv[1]).string(), argv[2], std::filesystem::absolute(argv[4]).string()); } - if (argc == 6) - { + if (argc == 6) { composed_peer = true; // The composed probe prevents unwinding active callback captures; // controller timeouts still terminate/reap only this owned child. - try - { + try { return peer(argv[1], argv[2], std::stoi(argv[3]), static_cast(std::stoi(argv[4])), static_cast(std::stoi(argv[5]))); - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { std::cerr << error.what() << std::endl; std::_Exit(1); } @@ -643,9 +582,7 @@ int main(int argc, char* argv[]) { #endif require(argc == 4, "Expected plugin directory and runtime, or peer arguments"); return peer(argv[1], argv[2], std::stoi(argv[3])); - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { std::cerr << error.what() << std::endl; return 1; } diff --git a/tests/app/typed_examples.cpp b/tests/app/typed_examples.cpp index 96215bcd7..c2cc62f61 100644 --- a/tests/app/typed_examples.cpp +++ b/tests/app/typed_examples.cpp @@ -37,8 +37,7 @@ static_assert(std::same_as(); auto* maps = manager.find_module(); require( @@ -102,14 +96,12 @@ int main(int argc, char* argv[]) { "Entity example must create four players"); unsigned edited = 0; unsigned table_demo = 0; - for (std::size_t i = 0; i < ids.get_count(); ++i) - { + for (std::size_t i = 0; i < ids.get_count(); ++i) { auto player = kernel->get_entity(ids.int64(i)); require( player && player->get_string(ark::entity_meta_player::name()) == "Xiaoming", "Player name changed"); for (const auto& field : {ark::entity_meta_player::career(), ark::entity_meta_player::camp(), - ark::entity_meta_player::last_map_id(), ark::entity_meta_player::level()}) - { + ark::entity_meta_player::last_map_id(), ark::entity_meta_player::level()}) { require(player->get_int32(field) == 1, "Player initialization changed: " + field); } const auto gender = player->get_int32(ark::entity_meta_player::gender_index()); @@ -117,8 +109,7 @@ int main(int argc, char* argv[]) { edited += gender == 11; require(player->get_custom_int32("test") == 111, "Custom data initialization changed"); require(player->add_custom_u_int32("unsigned_sequence", 0), "Custom uint32 creation failed"); - for (const auto value : {std::numeric_limits::max(), std::uint32_t{0}}) - { + for (const auto value : {std::numeric_limits::max(), std::uint32_t{0}}) { require(player->set_custom_u_int32("unsigned_sequence", value) && player->get_custom_u_int32("unsigned_sequence") == value, "Public entity custom uint32 update failed through the real Kernel DSO"); @@ -129,8 +120,7 @@ int main(int argc, char* argv[]) { require(items && items->first() && items->first()->get_int64(ark::entity_meta_item_bag::guid_index()) == 1111, "Initial item row GUID changed"); - if (items->get_row_count() == 2) - { + if (items->get_row_count() == 2) { auto* row = items->first(); row = items->next(); require(row && row->get_int32(ark::entity_meta_item_bag::count_index()) == 22, @@ -166,8 +156,7 @@ int main(int argc, char* argv[]) { auto* schedules = manager.find_module(); auto* compression = manager.find_module(); for (auto* service : {static_cast(guids), static_cast(timers), - static_cast(schedules), static_cast(compression)}) - { + static_cast(schedules), static_cast(compression)}) { require(service && service->get_plugin_manager() == &manager, "Utility interface lost manager ownership"); } require(guids->get_name() == typeid(ark::guid_module).name() && @@ -180,8 +169,7 @@ int main(int argc, char* argv[]) { require(first_id != ark::null_guid && second_id != first_id && !guids->parse_uid(first_id).empty(), "Utility GUID generation or parsing failed"); const std::string input("utility binary\0round trip", 25); - for (auto algorithm : {ark::compress_type::compress_type_zlib, ark::compress_type::compress_type_zstd}) - { + for (auto algorithm : {ark::compress_type::compress_type_zlib, ark::compress_type::compress_type_zstd}) { std::string packed; std::string unpacked; require(compression->compress(algorithm, input.data(), input.size(), packed), "Utility compression failed"); @@ -192,8 +180,7 @@ int main(int argc, char* argv[]) { const auto timer_id = timers->add_single_timer(first_id, std::chrono::milliseconds(20), 1, &timer, &timer_receiver::on_timer); require(timer_id != 0 && timer.calls == 0, "Utility timer fired without manager updates"); - for (int i = 1; i <= 5; ++i) - { + for (int i = 1; i <= 5; ++i) { require(manager.update(i * 10), "Sample owner update failed"); } require(timer.calls == 1 && timer.timer_id == timer_id && timer.entity_id == first_id, @@ -202,15 +189,12 @@ int main(int argc, char* argv[]) { ark::test::drain_owner( manager, [&] { return ++tick; }, std::chrono::steady_clock::now() + std::chrono::seconds(5), sample); require(manager.stop(++tick), "Repeated stop must not unregister Utility modules twice"); - if (sample == "entity_operations") - { + if (sample == "entity_operations") { require(entity_events.destroyed == 4, "Shutdown must destroy each demonstration player exactly once"); } require(manager.get_shutdown_state() == ark::plugin_manager::shutdown_state::stopped, "Sample resources were retained instead of stopped"); - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { require(false, "Sample lifecycle exception: " + std::string(error.what()) + "; startup: " + manager.get_startup_failure()); } @@ -218,14 +202,11 @@ int main(int argc, char* argv[]) { const auto output = events.str(); std::cout << output; std::size_t previous{}; - for (const std::string event : {sample == "timers" ? "init" : "Init", "PostInit", "PreShut", "Shut"}) - { + for (const std::string event : {sample == "timers" ? "init" : "Init", "PostInit", "PreShut", "Shut"}) { auto position = output.find(sample + "_module", previous); - while (position != std::string::npos) - { + while (position != std::string::npos) { const auto end = output.find('\n', position); - if (output.substr(position, end - position).find(", " + event) != std::string::npos) - { + if (output.substr(position, end - position).find(", " + event) != std::string::npos) { break; } position = output.find(sample + "_module", end); diff --git a/tests/compression/compression.cpp b/tests/compression/compression.cpp index 476d1ebe3..b1da9ad5d 100644 --- a/tests/compression/compression.cpp +++ b/tests/compression/compression.cpp @@ -35,16 +35,14 @@ static_assert(std::is_nothrow_move_assignable_v); std::string payload(std::size_t size, uint32_t seed = 1) { std::string result(size, '\0'); - for (char& byte : result) - { + for (char& byte : result) { seed = seed * 1664525u + 1013904223u; byte = static_cast(seed >> 24); } return result; } -struct dictionary_file -{ +struct dictionary_file { std::filesystem::path path; dictionary_file() @@ -55,8 +53,7 @@ struct dictionary_file const auto bytes = payload(4096); output.write(bytes.data(), static_cast(bytes.size())); output.close(); - if (!output) - { + if (!output) { throw std::runtime_error("cannot write temporary dictionary"); } } @@ -100,8 +97,7 @@ std::string external_zstd(const std::string& input, bool content_size = true) { template void check_compression_boundary(bound_type bound, compress_type compress) { std::size_t rejected = 0; - while (static_cast(bound(rejected)) < capacity) - { + while (static_cast(bound(rejected)) < capacity) { ++rejected; } REQUIRE(rejected > 0); @@ -153,8 +149,7 @@ TEST_CASE("Zstandard moves retain populated contexts dictionaries and frame comp CHECK(destination.dict_compress(1, input.data(), input.size(), moved_frame)); CHECK(moved_frame == frame); - for (auto* reused : {&source, &moved}) - { + for (auto* reused : {&source, &moved}) { REQUIRE(reused->init_z_std_dict(1, dictionary.path.string(), 1)); std::string reused_frame; REQUIRE(reused->dict_compress(1, input.data(), input.size(), reused_frame)); @@ -170,8 +165,7 @@ TEST_CASE("Zstandard moves retain populated contexts dictionaries and frame comp TEST_CASE("compression preserves binary bytes and appends successful results") { const auto input = payload(8192); ark::zstd_compress zstd; - for (int algorithm = 0; algorithm < 3; ++algorithm) - { + for (int algorithm = 0; algorithm < 3; ++algorithm) { std::string compressed = prefix; const bool packed = algorithm == 0 ? ark::zlib_compress::compress(input.data(), input.size(), 1, compressed) : algorithm == 1 ? ark::lz4_compress::compress(input.data(), input.size(), 1, compressed) @@ -214,8 +208,7 @@ TEST_CASE("compression retains strict compression bound and rejects unrepresenta const auto too_large = static_cast((std::numeric_limits::max)()) + 1; CHECK_FALSE(ark::lz4_compress::compress("x", static_cast(LZ4_MAX_INPUT_SIZE) + 1, 1, output)); CHECK_FALSE(ark::lz4_compress::decompress("x", too_large, output)); - if constexpr (sizeof(std::size_t) > sizeof(uLong)) - { + if constexpr (sizeof(std::size_t) > sizeof(uLong)) { const auto source_size = static_cast((std::numeric_limits::max)()) + 1; CHECK_FALSE(ark::zlib_compress::decompress("x", source_size, output)); } @@ -226,8 +219,7 @@ TEST_CASE("decompression accepts exactly one MiB and rejects larger outputs") { ark::zstd_compress zstd; dictionary_file dictionary; REQUIRE(zstd.init_z_std_dict(1, dictionary.path.string(), 1)); - for (const std::size_t size : {capacity - 1, capacity, capacity + 1}) - { + for (const std::size_t size : {capacity - 1, capacity, capacity + 1}) { const std::string input(size, 'a'); const auto zlib_frame = external_zlib(input); const auto lz4_frame = external_lz4(input); @@ -268,8 +260,7 @@ TEST_CASE("corrupt truncated and unknown-size frames preserve caller output") { REQUIRE(ZSTD_getDictID_fromFrame(different_dictionary.data(), different_dictionary.size()) == 1); CHECK_FALSE(zstd.dict_decompress(1, different_dictionary.data(), different_dictionary.size(), output)); for (const auto& frame : {std::string("bad"), external_zstd(input, false), - std::string("\x28\xb5\x2f\xfd\xe0\x01\x00\x00\x00\x01\x00\x00\x00", 13)}) - { + std::string("\x28\xb5\x2f\xfd\xe0\x01\x00\x00\x00\x01\x00\x00\x00", 13)}) { CHECK_FALSE(zstd.normal_decompress(frame.data(), frame.size(), output)); CHECK_FALSE(zstd.dict_decompress(1, frame.data(), frame.size(), output)); } @@ -303,45 +294,38 @@ TEST_CASE("parallel compression calls own their output buffers") { std::barrier start(workers); std::atomic passed = true; std::vector threads; - for (int worker = 0; worker < workers; ++worker) - { + for (int worker = 0; worker < workers; ++worker) { threads.emplace_back([&, worker] { // Dictionary contexts belong to one thread; sharing one instance is unsupported. ark::zstd_compress zstd; - if (!zstd.init_z_std_dict(1, dictionary.path.string(), 1)) - { + if (!zstd.init_z_std_dict(1, dictionary.path.string(), 1)) { passed = false; } start.arrive_and_wait(); - for (int iteration = 0; iteration < 20; ++iteration) - { + for (int iteration = 0; iteration < 20; ++iteration) { const auto input = payload(128 * 1024 + iteration, worker * 100 + iteration + 1); std::string packed; std::string output = prefix; if (!ark::zlib_compress::compress(input.data(), input.size(), 1, packed) || - !ark::zlib_compress::decompress(packed.data(), packed.size(), output) || output != prefix + input) - { + !ark::zlib_compress::decompress(packed.data(), packed.size(), output) || output != prefix + input) { passed = false; } packed.clear(); output = prefix; if (!ark::lz4_compress::compress(input.data(), input.size(), 1, packed) || - !ark::lz4_compress::decompress(packed.data(), packed.size(), output) || output != prefix + input) - { + !ark::lz4_compress::decompress(packed.data(), packed.size(), output) || output != prefix + input) { passed = false; } packed.clear(); output = prefix; if (!normal_zstd.normal_compress(input.data(), input.size(), 1, packed) || - !normal_zstd.normal_decompress(packed.data(), packed.size(), output) || output != prefix + input) - { + !normal_zstd.normal_decompress(packed.data(), packed.size(), output) || output != prefix + input) { passed = false; } packed.clear(); output = prefix; if (!zstd.dict_compress(1, input.data(), input.size(), packed) || - !zstd.dict_decompress(1, packed.data(), packed.size(), output) || output != prefix + input) - { + !zstd.dict_decompress(1, packed.data(), packed.size(), output) || output != prefix + input) { passed = false; } } diff --git a/tests/compression/zstd_ownership.cpp b/tests/compression/zstd_ownership.cpp index 3c2e0a5a9..6dc4bb09c 100644 --- a/tests/compression/zstd_ownership.cpp +++ b/tests/compression/zstd_ownership.cpp @@ -22,8 +22,7 @@ namespace { -enum resource : std::size_t -{ +enum resource : std::size_t { cctx, dctx, cdict, @@ -38,8 +37,7 @@ bool fail_map{}; bool fail_next_new{}; bool fail(resource kind) { - if (fail_resource == kind) - { + if (fail_resource == kind) { fail_resource = resource_count; return true; } @@ -67,8 +65,7 @@ ZSTD_CDict* create_cdict(const void* data, std::size_t size, int level) { ZSTD_DDict* create_ddict(const void* data, std::size_t size) { auto* value = fail(ddict) ? nullptr : ZSTD_createDDict(data, size); live[ddict] += value != nullptr; - if (value && std::exchange(fail_map, false)) - { + if (value && std::exchange(fail_map, false)) { fail_next_new = true; } return value; @@ -105,8 +102,7 @@ void free_buffer(void* value) noexcept { std::free(value); } -struct dictionary_file -{ +struct dictionary_file { std::filesystem::path path; std::string bytes; @@ -115,8 +111,7 @@ struct dictionary_file ("ark-zstd-ownership-" + std::to_string(seed) + "-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()))) , bytes(4096, '\0') { - for (auto& byte : bytes) - { + for (auto& byte : bytes) { seed = seed * 1664525u + 1013904223u; byte = static_cast(seed >> 24); } @@ -137,12 +132,10 @@ struct dictionary_file // Only this executable replaces map allocation and the native resource entrypoints. // Production inline definitions never mix with differently expanded definitions. void* operator new(std::size_t size) { - if (std::exchange(fail_next_new, false)) - { + if (std::exchange(fail_next_new, false)) { throw std::bad_alloc{}; } - if (auto* value = std::malloc(size ? size : 1)) - { + if (auto* value = std::malloc(size ? size : 1)) { return value; } throw std::bad_alloc{}; @@ -206,8 +199,7 @@ TEST_CASE("Zstandard duplicate dictionary keys retain the first pair without lea const auto first_frame = frame(codec, input); REQUIRE(first_frame.size() < input.size()); // Exercise actual dictionary references. const auto initial = live; - for (int attempt = 0; attempt < 8; ++attempt) - { + for (int attempt = 0; attempt < 8; ++attempt) { CHECK(codec.init_z_std_dict(1, replacement.path.string(), 15)); CHECK(live == initial); CHECK(frame(codec, input) == first_frame); @@ -226,8 +218,7 @@ TEST_CASE("Zstandard dictionary creation failures preserve existing entries and const auto input = dictionary.bytes.substr(100, 2048); const auto original = frame(codec, input); const auto initial = live; - for (auto kind : {cdict, ddict}) - { + for (auto kind : {cdict, ddict}) { fail_resource = kind; CHECK_FALSE(codec.init_z_std_dict(2, dictionary.path.string(), 1)); CHECK(fail_resource == resource_count); @@ -255,10 +246,11 @@ TEST_CASE("Zstandard dictionary insertion exceptions leave no partial entry and const auto initial = live; fail_map = true; bool caught{}; - try - { codec.init_z_std_dict(2, dictionary.path.string(), 1); } - catch (const std::bad_alloc&) - { caught = true; } + try { + codec.init_z_std_dict(2, dictionary.path.string(), 1); + } catch (const std::bad_alloc&) { + caught = true; + } CHECK_FALSE(fail_map); CHECK_FALSE(fail_next_new); CHECK(caught); @@ -336,8 +328,7 @@ TEST_CASE("Zstandard populated moves release overwritten owners once and retain TEST_CASE("Zstandard fallible move construction preserves the source after allocation failure" * doctest::skip(std::is_nothrow_move_constructible_v)) { - if constexpr (!std::is_nothrow_move_constructible_v) - { + if constexpr (!std::is_nothrow_move_constructible_v) { dictionary_file dictionary(1); const auto input = dictionary.bytes.substr(100, 2048); check_empty_resources(); @@ -349,10 +340,11 @@ TEST_CASE("Zstandard fallible move construction preserves the source after alloc bool caught{}; // Arm immediately before construction; doctest assertion setup may allocate too. fail_next_new = true; - try - { ark::zstd_compress moved(std::move(source)); } - catch (const std::bad_alloc&) - { caught = true; } + try { + ark::zstd_compress moved(std::move(source)); + } catch (const std::bad_alloc&) { + caught = true; + } const bool consumed = !std::exchange(fail_next_new, false); CHECK(consumed); CHECK(caught); diff --git a/tests/config_tool/exporter.cpp b/tests/config_tool/exporter.cpp index 06ac4990b..3c1883697 100644 --- a/tests/config_tool/exporter.cpp +++ b/tests/config_tool/exporter.cpp @@ -13,8 +13,7 @@ namespace { -struct temporary_directory -{ +struct temporary_directory { std::filesystem::path path; temporary_directory() { @@ -128,14 +127,11 @@ TEST_CASE("Real XLSX worksheets export through the same schema and typed-row val workbook.workbook().worksheet(1).setName("fields"); workbook.workbook().addWorksheet("GuestPlayer"); for (const auto& [name, source] : - std::map{{"fields", "fields.csv"}, {"GuestPlayer", "GuestPlayer.csv"}}) - { + std::map{{"fields", "fields.csv"}, {"GuestPlayer", "GuestPlayer.csv"}}) { const auto table = read_table(std::filesystem::path(ARK_CONFIG_TOOL_FIXTURE_DIR) / source); auto sheet = workbook.workbook().worksheet(name); - for (std::size_t row = 0; row < table.rows.size(); ++row) - { - for (std::size_t column = 0; column < table.rows[row].size(); ++column) - { + for (std::size_t row = 0; row < table.rows.size(); ++row) { + for (std::size_t column = 0; column < table.rows[row].size(); ++column) { sheet.cell(static_cast(row + 1), static_cast(column + 1)).value() = table.rows[row][column].text; } @@ -191,8 +187,7 @@ TEST_CASE("XLSX scalar types retain exact text integers and reject unsafe numeri workbook.create(file.string(), OpenXLSX::XLDoNotOverwrite); auto sheet = workbook.workbook().worksheet(1); const std::vector names{"id", "value", "flag", "ratio", "label", "field_name"}; - for (std::size_t i = 0; i < names.size(); ++i) - { + for (std::size_t i = 0; i < names.size(); ++i) { sheet.cell(1, static_cast(i + 1)).value() = names[i]; } sheet.cell("A2").value() = 1; diff --git a/tests/consul/entry.cpp b/tests/consul/entry.cpp index 597dd1244..02a2705f6 100644 --- a/tests/consul/entry.cpp +++ b/tests/consul/entry.cpp @@ -10,8 +10,7 @@ namespace { void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { std::cerr << message << std::endl; std::_Exit(1); } diff --git a/tests/consul/entry_factory.cpp b/tests/consul/entry_factory.cpp index 5fbf51591..a22ad8a2a 100644 --- a/tests/consul/entry_factory.cpp +++ b/tests/consul/entry_factory.cpp @@ -11,8 +11,7 @@ unsigned created{}; unsigned destroyed{}; unsigned updated{}; -class entry_consul final : public ark::module_base -{ +class entry_consul final : public ark::module_base { public: entry_consul() { ++created; @@ -67,8 +66,7 @@ std::unique_ptr make_consul_module() { } // namespace ark::detail ARK_EXPORT_FUNC unsigned consul_entry_events(unsigned event) { - switch (event) - { + switch (event) { case 0: return created; case 1: diff --git a/tests/consul/exports.cpp b/tests/consul/exports.cpp index a5cbd76dc..825dcb0ca 100644 --- a/tests/consul/exports.cpp +++ b/tests/consul/exports.cpp @@ -8,8 +8,7 @@ namespace { void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { std::cerr << message << std::endl; std::_Exit(1); } diff --git a/tests/consumer/config/shared.cpp b/tests/consumer/config/shared.cpp index b65b6eb56..8dfadde99 100644 --- a/tests/consumer/config/shared.cpp +++ b/tests/consumer/config/shared.cpp @@ -4,8 +4,7 @@ #include "shared.hpp" bool read_config_from_shared_library(const std::string& path, bool application) { - if (application) - { + if (application) { return ark::load_application_manifest(path).plugin_library_dir == "shared/"; } return ark::plugin_config_detail::load_http(path).host == "localhost"; diff --git a/tests/consumer/config/shared_library.cpp b/tests/consumer/config/shared_library.cpp index a45d67aae..08fc6f134 100644 --- a/tests/consumer/config/shared_library.cpp +++ b/tests/consumer/config/shared_library.cpp @@ -14,8 +14,7 @@ TEST_CASE("Application and plugin readers link and diagnose from a shared librar std::filesystem::temp_directory_path() / ("ark-shared-config-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + ".toml"); - struct cleanup - { + struct cleanup { std::filesystem::path path; ~cleanup() { @@ -34,15 +33,11 @@ TEST_CASE("Application and plugin readers link and diagnose from a shared librar write("[http]\nhost='localhost'\nport=0\nthreads=1\n"); CHECK(read_config_from_shared_library(path.string(), false)); write("[broken\nsecret='SECRET_SENTINEL'\n"); - for (const auto application : {true, false}) - { - try - { + for (const auto application : {true, false}) { + try { static_cast(read_config_from_shared_library(path.string(), application)); FAIL("malformed configuration accepted by shared library"); - } - catch (const std::runtime_error& error) - { + } catch (const std::runtime_error& error) { CHECK(std::string(error.what()).find(path.string() + ":1:") != std::string::npos); CHECK(std::string(error.what()).find("SECRET_SENTINEL") == std::string::npos); } diff --git a/tests/consumer/main.cpp b/tests/consumer/main.cpp index 9b081cb24..4a88484e1 100644 --- a/tests/consumer/main.cpp +++ b/tests/consumer/main.cpp @@ -22,8 +22,7 @@ static_assert(sizeof(ark::guid_t) == 8); namespace { -class sample_module final : public ark::module -{ +class sample_module final : public ark::module { public: bool init() override { initialized_ = true; @@ -43,54 +42,44 @@ class sample_module final : public ark::module bool check_packaged_dependencies(); int main() { - if (!check_packaged_dependencies()) - { + if (!check_packaged_dependencies()) { return 9; } sample_module service; - if (!service.init() || !service.initialized() || !service.update() || !service.shut()) - { + if (!service.init() || !service.initialized() || !service.update() || !service.shut()) { return 1; } - if (ark::plugin_manager::instance()->get_app_name() != "ark") - { + if (ark::plugin_manager::instance()->get_app_name() != "ark") { return 2; } // This also detects accidental recursion between conversion helpers and types. if (!::lexical_cast(std::string("true")) || ::lexical_cast("false") || - ::lexical_cast(std::string("42")) != 42) - { + ::lexical_cast(std::string("42")) != 42) { return 3; } - try - { + try { (void)::lexical_cast("nope"); return 4; + } catch (const std::invalid_argument&) { } - catch (const std::invalid_argument&) - {} ark::small_string text("abc"); text.append("defghijkl"); - if (std::string(text.c_str()) != "abcdefghijkl" || text.find("def") != 3) - { + if (std::string(text.c_str()) != "abcdefghijkl" || text.find("def") != 3) { return 5; } auto copy = text; text.clear(); - if (!text.empty() || std::string(copy.c_str()) != "abcdefghijkl") - { + if (!text.empty() || std::string(copy.c_str()) != "abcdefghijkl") { return 6; } ark::data_node_name node_name("a name longer than the inline buffer"); - if (std::string(node_name.c_str()) != "a name longer than the inline buffer") - { + if (std::string(node_name.c_str()) != "a name longer than the inline buffer") { return 7; } #ifdef ARK_USE_GUID_32 ark::uid_generator_thread_safe ids; const auto id = ids.get_uid(); - if (ids.parse_uid(id) != "ID=" + std::to_string(id)) - { + if (ids.parse_uid(id) != "ID=" + std::to_string(id)) { return 8; } #endif diff --git a/tests/consumer/net/main.cpp b/tests/consumer/net/main.cpp index 6a6af1f8c..60c7a0fd2 100644 --- a/tests/consumer/net/main.cpp +++ b/tests/consumer/net/main.cpp @@ -20,8 +20,7 @@ static_assert(std::is_base_of_v(ark::load_application_manifest(path)); DOCTEST_FAIL("invalid manifest was accepted"); - } - catch (const ark::application_manifest_error& error) - { + } catch (const ark::application_manifest_error& error) { DOCTEST_CHECK(error.path() == path); DOCTEST_CHECK(std::string(error.what()).find(path) != std::string::npos); DOCTEST_CHECK((error.line() > 0) == has_position); @@ -205,8 +198,7 @@ void check_manifest(const ark::application_manifest& actual, const ark::applicat DOCTEST_TEST_CASE("built-in TOML application presets match their explicit plugin schema") { const auto root = std::filesystem::path(ARK_TEST_SOURCE_DIR); - for (const auto& preset : application_presets) - { + for (const auto& preset : application_presets) { DOCTEST_CAPTURE(preset.filename); check_manifest(ark::load_application_manifest(utf8_path(root / "config" / preset.filename)), preset.manifest); } @@ -228,17 +220,14 @@ DOCTEST_TEST_CASE("guest-room TOML declares its complete plugin configuration") DOCTEST_TEST_CASE("every built-in TOML application preset has an explicit schema expectation") { const auto root = std::filesystem::path(ARK_TEST_SOURCE_DIR); std::set expected; - for (const auto& preset : application_presets) - { + for (const auto& preset : application_presets) { DOCTEST_CAPTURE(preset.filename); DOCTEST_CHECK(expected.emplace(preset.filename).second); } std::set actual; - for (const auto& entry : std::filesystem::directory_iterator(root / "config")) - { + for (const auto& entry : std::filesystem::directory_iterator(root / "config")) { const auto name = entry.path().filename().string(); - if (name.ends_with(".app.toml")) - { + if (name.ends_with(".app.toml")) { DOCTEST_CAPTURE(name); DOCTEST_CHECK(expected.contains(name)); actual.insert(name); @@ -266,39 +255,32 @@ DOCTEST_TEST_CASE("deployment TOML application payloads match their explicit plu bool has_kind = false; bool has_metadata = false; std::string line; - while (std::getline(input, line)) - { + while (std::getline(input, line)) { has_data = has_data || line == "data:"; has_kind = has_kind || line == "kind: ConfigMap"; has_metadata = has_metadata || line == "metadata:"; - if (line.starts_with(" ") && !line.starts_with(" ")) - { + if (line.starts_with(" ") && !line.starts_with(" ")) { const auto scalar = line.find(": |"); - if (scalar != std::string::npos) - { + if (scalar != std::string::npos) { const auto key = line.substr(2, scalar - 2); DOCTEST_CAPTURE(key); DOCTEST_CHECK((key.ends_with(".app.toml") || key.ends_with(".plugin.toml"))); - if (key.ends_with(".plugin.toml")) - { + if (key.ends_with(".plugin.toml")) { DOCTEST_CHECK(plugin_keys.emplace(key).second); } } } - if (!line.starts_with(" ") || !line.ends_with(".app.toml: |-")) - { + if (!line.starts_with(" ") || !line.ends_with(".app.toml: |-")) { continue; } const auto name = line.substr(2, line.size() - 2 - 4); DOCTEST_CAPTURE(name); DOCTEST_CHECK(application_keys.emplace(name).second); std::string payload; - while (input.peek() == ' ' || input.peek() == '\n') - { + while (input.peek() == ' ' || input.peek() == '\n') { const auto position = input.tellg(); std::getline(input, line); - if (!line.empty() && !line.starts_with(" ")) - { + if (!line.empty() && !line.starts_with(" ")) { input.seekg(position); break; } @@ -307,12 +289,9 @@ DOCTEST_TEST_CASE("deployment TOML application payloads match their explicit plu const auto matches = [&](const auto& preset) { return name == preset.filename; }; const auto actual = ark::load_application_manifest(files.write(payload, name)); const auto expected = std::find_if(application_presets.begin(), application_presets.end(), matches); - if (expected != application_presets.end()) - { + if (expected != application_presets.end()) { check_manifest(actual, expected->manifest); - } - else - { + } else { const auto external = std::find_if(deployment_only_presets.begin(), deployment_only_presets.end(), matches); DOCTEST_REQUIRE(external != deployment_only_presets.end()); check_manifest(actual, external->manifest); @@ -370,8 +349,7 @@ config = 'nested/service.toml' DOCTEST_TEST_CASE("Missing directories and omitted or empty plugin arrays retain empty manifest semantics") { manifest_files files; - for (const auto input : {"[application]\n", "plugins = []\n[application]\n"}) - { + for (const auto input : {"[application]\n", "plugins = []\n[application]\n"}) { const auto manifest = ark::load_application_manifest(files.write(input)); DOCTEST_CHECK(manifest.plugin_library_dir.empty()); DOCTEST_CHECK(manifest.plugin_config_dir.empty()); @@ -387,8 +365,7 @@ DOCTEST_TEST_CASE("TOML validates required tables exact field types and plugin n "[application]\n[[plugins]]\n", "[application]\n[[plugins]]\nname = ''\n", "[application]\n[[plugins]]\nname = 42\n", "[application]\n[[plugins]]\nname = 'Plugin'\nconfig = []\n", "[application]\n[[plugins]]\nname = 'Plugin'\nconfig = {}\n"}; - for (const auto input : invalid) - { + for (const auto input : invalid) { DOCTEST_CAPTURE(input); check_error(files.write(input)); } @@ -399,8 +376,7 @@ DOCTEST_TEST_CASE("TOML rejects unknown fields at every schema level") { const std::array invalid = {"typo = 1\n[application]\n", "[application]\nplugin_lib_dir = 'bin/'\n", "[application]\n[[plugins]]\nname = 'Plugin'\nconf = ''\n", "[application]\n[extra]\n"}; - for (const auto input : invalid) - { + for (const auto input : invalid) { check_error(files.write(input)); } } @@ -410,8 +386,7 @@ DOCTEST_TEST_CASE("TOML rejects duplicate and empty plugin names before returnin const std::array invalid = { "[application]\n[[plugins]]\nname = 'Plugin'\n[[plugins]]\nname = 'Plugin'\n", "[application]\n[[plugins]]\n", "[application]\n[[plugins]]\nname = ''\n"}; - for (const auto input : invalid) - { + for (const auto input : invalid) { check_error(files.write(input)); } auto manifest = ark::load_application_manifest(files.write("[application]\n[[plugins]]\nname = 'Original'\n")); @@ -428,23 +403,20 @@ DOCTEST_TEST_CASE("TOML syntax errors have source positions without disclosing c "[application]\n[logging]\nlevel = 'info'\nlevel = 'SECRET_SENTINEL'\n", "[application]\n[logging]\n[logging]\n", "[application]\n[logging.loggers.oss]\nlevel = 'info'\n[logging.loggers.oss]\n"}; - for (std::size_t index = 0; index < invalid.size(); ++index) - { + for (std::size_t index = 0; index < invalid.size(); ++index) { const auto path = files.write(invalid[index], "syntax.toml"); check_error(path); - try - { static_cast(ark::load_application_manifest(path)); } - catch (const ark::application_manifest_error& error) - { DOCTEST_CHECK(std::string(error.what()).find("SECRET_SENTINEL") == std::string::npos); } + try { + static_cast(ark::load_application_manifest(path)); + } catch (const ark::application_manifest_error& error) { + DOCTEST_CHECK(std::string(error.what()).find("SECRET_SENTINEL") == std::string::npos); + } } const auto path = files.write("[application]\nplugin_library_dir = 7\n"); - try - { + try { static_cast(ark::load_application_manifest(path)); DOCTEST_FAIL("numeric directory accepted"); - } - catch (const ark::application_manifest_error& error) - { + } catch (const ark::application_manifest_error& error) { DOCTEST_CHECK(error.line() == 2); DOCTEST_CHECK(error.column() > 0); } @@ -454,19 +426,14 @@ DOCTEST_TEST_CASE("application manifests require a TOML suffix and never parse X manifest_files files; // Merely renaming XML does not convert its contents into TOML. check_error(files.write("")); - for (const auto name : {"old.app.conf", "config.xml", "config.TOML", "config.toml.extra", "no-extension"}) - { - for (const auto contents : {"", "[application]\n"}) - { + for (const auto name : {"old.app.conf", "config.xml", "config.TOML", "config.toml.extra", "no-extension"}) { + for (const auto contents : {"", "[application]\n"}) { const auto path = files.write(contents, name); check_error(path, false); - try - { + try { static_cast(ark::load_application_manifest(path)); DOCTEST_FAIL("non-TOML application manifest accepted"); - } - catch (const ark::application_manifest_error& error) - { + } catch (const ark::application_manifest_error& error) { DOCTEST_CHECK(std::string(error.what()).find("path must end in .toml") != std::string::npos); DOCTEST_CHECK( std::string(error.what()).find("XML manifests are no longer supported") != std::string::npos); @@ -483,8 +450,7 @@ DOCTEST_TEST_CASE("Manifest strings and input reject raw or decoded embedded NUL const std::array decoded = {"[application]\nplugin_library_dir = \"x\\u0000y\"\n", "[application]\nplugin_config_dir = \"x\\u0000y\"\n", "[application]\n[[plugins]]\nname = \"x\\u0000y\"\n", "[application]\n[[plugins]]\nname = 'Plugin'\nconfig = \"x\\u0000y\"\n"}; - for (std::size_t index = 0; index < decoded.size(); ++index) - { + for (std::size_t index = 0; index < decoded.size(); ++index) { check_error(files.write(decoded[index], "nul.toml")); } std::string input = "[application]\n"; @@ -511,8 +477,7 @@ DOCTEST_TEST_CASE("TOML supports UTF8 values and native Unicode filenames and re DOCTEST_TEST_CASE("raw NUL diagnostics count UTF8 code points and ignore the leading BOM") { manifest_files files; - struct example - { + struct example { std::string_view prefix; std::size_t line; std::size_t column; @@ -521,20 +486,16 @@ DOCTEST_TEST_CASE("raw NUL diagnostics count UTF8 code points and ignore the lea const std::array examples = {{{"# ascii ", 1, 9}, {"\xef\xbb\xbf# ascii ", 1, 9}, {"# 配置😀 ", 1, 7}, {"\xef\xbb\xbf# 配置😀 ", 1, 7}, {"[application]\nplugin_config_dir = '配置😀' ", 2, 27}, {"[application]\r\nplugin_config_dir = '配置😀' ", 2, 27}}}; - for (const auto& entry : examples) - { + for (const auto& entry : examples) { DOCTEST_CAPTURE(entry.prefix); auto contents = std::string(entry.prefix); contents += '\0'; contents += "SECRET_SENTINEL"; const auto path = files.write(contents); - try - { + try { static_cast(ark::load_application_manifest(path)); DOCTEST_FAIL("raw NUL accepted"); - } - catch (const ark::application_manifest_error& error) - { + } catch (const ark::application_manifest_error& error) { DOCTEST_CHECK(error.path() == path); DOCTEST_CHECK(error.line() == entry.line); DOCTEST_CHECK(error.column() == entry.column); @@ -598,15 +559,13 @@ DOCTEST_TEST_CASE("logging rejects bad fields ranges and disabled outputs before "[logging]\nqueue_count = 65536\n", "[logging]\nqueue_count = 1.0\n", "[logging]\npattern = ''\n", "[logging]\noutput_path = ''\n", "[logging]\noutput_path = \"x\\u0000y\"\n", "[logging]\nunknown = true\n", "[logging]\nconsole = false\n", "[logging]\nloggers = []\n", "[logging.loggers]\noss = 1\n", - "[logging.loggers.oss]\nloggers = {}\n", "[logging.loggers.\"x\\u0000y\"]\nlevel = 'info'\n"}) - { + "[logging.loggers.oss]\nloggers = {}\n", "[logging.loggers.\"x\\u0000y\"]\nlevel = 'info'\n"}) { DOCTEST_CAPTURE(std::string_view(bad)); const auto path = files.write(std::string(bad) + "[application]\n"); check_error(path); - try - { static_cast(ark::load_application_manifest(path)); } - catch (const ark::application_manifest_error& error) - { + try { + static_cast(ark::load_application_manifest(path)); + } catch (const ark::application_manifest_error& error) { DOCTEST_CHECK(std::string(error.what()).find("logging") != std::string::npos); DOCTEST_CHECK(std::string(error.what()).find("SECRET_SENTINEL") == std::string::npos); } diff --git a/tests/core/buffer_failure.cpp b/tests/core/buffer_failure.cpp index 8f90f64a8..4f7ad5a5f 100644 --- a/tests/core/buffer_failure.cpp +++ b/tests/core/buffer_failure.cpp @@ -16,20 +16,15 @@ unsigned skip_arrays_before_failure{}; // Fail one ordinary array allocation deterministically, without exhausting memory. void* operator new[](std::size_t size) { - if (fail_next_array) - { - if (skip_arrays_before_failure > 0) - { + if (fail_next_array) { + if (skip_arrays_before_failure > 0) { --skip_arrays_before_failure; - } - else - { + } else { fail_next_array = false; throw std::bad_alloc{}; } } - if (auto* result = std::malloc(size ? size : 1)) - { + if (auto* result = std::malloc(size ? size : 1)) { return result; } throw std::bad_alloc{}; @@ -46,10 +41,11 @@ void operator delete[](void* value, std::size_t) noexcept { TEST_CASE("Buffer default construction allocation propagates bad_alloc") { fail_next_array = true; bool caught{}; - try - { ark::buffer candidate(8); } - catch (const std::bad_alloc&) - { caught = true; } + try { + ark::buffer candidate(8); + } catch (const std::bad_alloc&) { + caught = true; + } CHECK_FALSE(fail_next_array); CHECK(caught); } @@ -61,10 +57,11 @@ TEST_CASE("Buffer default growth allocation propagates bad_alloc and retains unr const auto* unread = value.get_data(); fail_next_array = true; bool caught{}; - try - { value.write("defg", 4); } - catch (const std::bad_alloc&) - { caught = true; } + try { + value.write("defg", 4); + } catch (const std::bad_alloc&) { + caught = true; + } CHECK_FALSE(fail_next_array); CHECK(caught); CHECK(value.get_capacity() == 4); @@ -76,18 +73,18 @@ TEST_CASE("Buffer default growth allocation propagates bad_alloc and retains unr } TEST_CASE("Buffer self append retains state when snapshot or subsequent growth allocation throws") { - for (unsigned skipped = 0; skipped < 2; ++skipped) - { + for (unsigned skipped = 0; skipped < 2; ++skipped) { ark::buffer value(4); REQUIRE(value.write("abcd", 4)); const auto* unread = value.get_data(); skip_arrays_before_failure = skipped; fail_next_array = true; bool caught{}; - try - { value.write(unread, 4); } - catch (const std::bad_alloc&) - { caught = true; } + try { + value.write(unread, 4); + } catch (const std::bad_alloc&) { + caught = true; + } CHECK_FALSE(fail_next_array); CHECK(caught); CHECK(value.get_data() == unread); diff --git a/tests/core/buffer_hooks.cpp b/tests/core/buffer_hooks.cpp index c36753db6..37b439970 100644 --- a/tests/core/buffer_hooks.cpp +++ b/tests/core/buffer_hooks.cpp @@ -16,25 +16,20 @@ bool return_null{}; bool throw_allocation{}; char* allocate_bytes(size_t size) { - if (throw_allocation) - { + if (throw_allocation) { throw_allocation = false; throw std::bad_alloc{}; } - if (return_null) - { + if (return_null) { return_null = false; return nullptr; } auto* result = static_cast(std::malloc(size ? size : 1)); - if (!result) - { + if (!result) { throw std::bad_alloc{}; } - for (auto& entry : live) - { - if (!entry) - { + for (auto& entry : live) { + if (!entry) { entry = result; ++allocations; return result; @@ -44,10 +39,8 @@ char* allocate_bytes(size_t size) { } void release_bytes(char*& value) noexcept { - for (auto& entry : live) - { - if (entry == value) - { + for (auto& entry : live) { + if (entry == value) { entry = nullptr; std::free(value); value = nullptr; @@ -90,8 +83,7 @@ TEST_CASE("Buffer uses matching custom hooks for growth replacement moves and de } CHECK(allocations - initial_allocations == 4); CHECK(releases - initial_releases == 4); - for (const auto* entry : live) - { + for (const auto* entry : live) { CHECK(entry == nullptr); } } diff --git a/tests/core/bus_configuration.cpp b/tests/core/bus_configuration.cpp index 63bb93c80..5ee4eda46 100644 --- a/tests/core/bus_configuration.cpp +++ b/tests/core/bus_configuration.cpp @@ -51,8 +51,7 @@ check_interval = '10s' check_timeout = '3s' )"; -class configuration_file -{ +class configuration_file { public: configuration_file() : path_(std::filesystem::temp_directory_path() / @@ -148,8 +147,7 @@ TEST_CASE("Bus rejects malformed identifiers endpoints numbers references and un {"type = 30", "type = 30\nextra = 1"}, {"source = 'game'", "source = 'game'\nextra = 1"}, {"threads = 2", "threads = 2\nextra = 1"}, {"port = 8500", "port = 8500\nextra = 1"}, {"[[bus.applications]]", "[[bus.wrong_applications]]"}, {"[bus.registry]", "[bus.wrong_registry]"}, - {"server_endpoint = 'udp://0.0.0.0:9101'", ""}}) - { + {"server_endpoint = 'udp://0.0.0.0:9101'", ""}}) { INFO(from, " -> ", to); CHECK_THROWS_AS( ark::bus_config_detail::load(file.write(replace(configuration, from, to)), 0), std::runtime_error); @@ -202,13 +200,10 @@ check_timeout = '3s' TEST_CASE("Bus diagnostics identify the file array index and invalid field") { configuration_file file; const auto path = file.write(replace(configuration, "threads = 2", "threads = 256")); - try - { + try { static_cast(ark::bus_config_detail::load(path, 0)); FAIL("invalid threads accepted"); - } - catch (const std::runtime_error& error) - { + } catch (const std::runtime_error& error) { const std::string message = error.what(); CHECK(message.find(path) != std::string::npos); CHECK(message.find("bus.processes[0]") != std::string::npos); @@ -237,18 +232,13 @@ TEST_CASE("Bus rejects duplicate application names types relations and process I std::vector>{{"name = 'game'", "name = 'world'", "name"}, {"type = 31", "type = 30", "type"}, {"[bus.registry]", "[[bus.relations]]\nsource = 'game'\ntarget = 'world'\n[bus.registry]", "source/target"}, - {"'1.1.31.1'", "'1.1.30.1'", "bus_id"}}) - { - for (const auto self : {ark::bus_addr(1, 1, 30, 1).bus_id, ark::bus_addr(1, 1, 31, 1).bus_id}) - { + {"'1.1.31.1'", "'1.1.30.1'", "bus_id"}}) { + for (const auto self : {ark::bus_addr(1, 1, 30, 1).bus_id, ark::bus_addr(1, 1, 31, 1).bus_id}) { const auto path = file.write(replace(configuration, from, to)); - try - { + try { static_cast(ark::bus_config_detail::load(path, self)); FAIL("duplicate configuration accepted"); - } - catch (const std::runtime_error& error) - { + } catch (const std::runtime_error& error) { const std::string message = error.what(); CHECK(message.find(path) != std::string::npos); CHECK(message.find("duplicate") != std::string::npos); @@ -274,8 +264,7 @@ TEST_CASE("Bus module retains bracketed IPv6 endpoint hosts without brackets for CHECK(module.get_self_proc().server_ep.get_port() == 9102); CHECK(module.get_self_proc().intranet_ep.get_ip() == "2001:db8::1"); CHECK(module.get_self_proc().intranet_ep.get_port() == 0); - for (const auto& host : {"::", "::ffff:192.0.2.1", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"}) - { + for (const auto& host : {"::", "::ffff:192.0.2.1", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"}) { const auto endpoint = ark::bus_config_detail::parse_endpoint( "tcp://[" + std::string(host) + "]:65535/path", "test", "server_endpoint"); CHECK(endpoint.get_ip() == host); diff --git a/tests/core/business_runtime.cpp b/tests/core/business_runtime.cpp index 14cc0d342..df3bb3211 100644 --- a/tests/core/business_runtime.cpp +++ b/tests/core/business_runtime.cpp @@ -17,8 +17,7 @@ namespace { -class observed_module final : public ark::module -{ +class observed_module final : public ark::module { public: explicit observed_module(std::string name) : name_(std::move(name)) { @@ -30,16 +29,14 @@ class observed_module final : public ark::module std::vector get_dependencies() const override { ++dependency_reads; - if (dependency_metadata_throws) - { + if (dependency_metadata_throws) { throw std::runtime_error("dependency metadata must not be read again"); } return dependencies; } bool update() override { - if (on_update) - { + if (on_update) { on_update(); } return true; @@ -52,8 +49,7 @@ class observed_module final : public ark::module bool pre_shut() override { ++pre_shut_calls; - if (on_pre_shut) - { + if (on_pre_shut) { on_pre_shut(); } return pre_shut_result; @@ -61,8 +57,7 @@ class observed_module final : public ark::module bool shut() override { ++shut_calls; - if (on_shut) - { + if (on_shut) { on_shut(); } return shut_result; @@ -130,8 +125,7 @@ ark::task<> consume_provider(ark::module& provider, std::string& result) { using bridge_type = ark::detail::database_awaitable; -struct controlled_service -{ +struct controlled_service { using callback = std::function; callback pending; callback first_callback; @@ -142,8 +136,7 @@ struct controlled_service std::uint64_t start(callback completion) { CHECK_FALSE(pending); pending = std::move(completion); - if (!first_callback) - { + if (!first_callback) { first_callback = pending; } return ++started; @@ -157,8 +150,7 @@ struct controlled_service void cancel() { ++cancelled; - if (!defer_cancellation) - { + if (!defer_cancellation) { complete_cancelled(); } } @@ -180,8 +172,7 @@ ark::task<> sequential_operations(controlled_service& service, bridge_type& brid using ark::module; -class removal_module final : public module -{ +class removal_module final : public module { public: explicit removal_module(unsigned& destroyed) : destroyed_(destroyed) { @@ -200,8 +191,7 @@ class removal_module final : public module unsigned& destroyed_; }; -struct removal_owner -{ +struct removal_owner { ark::plugin_manager& manager; std::unordered_map modules_; @@ -230,8 +220,7 @@ TEST_CASE("Registered modules share one bounded owner executor after completion unsigned first_updates{}, second_updates{}, handlers{}, completions{}; first.on_update = [&] { ++first_updates; }; second.on_update = [&] { ++second_updates; }; - for (unsigned index = 0; index < 4; ++index) - { + for (unsigned index = 0; index < 4; ++index) { asio::post(runtime->get_executor(), [&] { CHECK(first_updates > 0); CHECK(second_updates > 0); @@ -363,8 +352,7 @@ TEST_CASE("Update and cancellation completion exceptions preserve owner reentran module.on_update = [] { throw std::runtime_error("module update failed"); }; REQUIRE(tasks.start(ready_task(), [&](std::exception_ptr error) { CHECK(error); - if (error) - { + if (error) { CHECK_THROWS_AS(std::rethrow_exception(error), arknet::system_error); } CHECK_FALSE(manager.stop(3)); @@ -391,10 +379,11 @@ TEST_CASE("Manager owner and active registry checks reject mutations before they unsigned rejected{}; std::thread worker([&] { auto rejects = [&](auto action) { - try - { action(); } - catch (const std::logic_error&) - { ++rejected; } + try { + action(); + } catch (const std::logic_error&) { + ++rejected; + } }; rejects([&] { manager.get_task_runtime(); }); rejects([&] { manager.get_tasks(module); }); @@ -482,8 +471,7 @@ TEST_CASE("Managed task groups enforce registration capacity identity and termin auto* original = &manager.create_task_group(first, 1); CHECK_THROWS_AS(manager.create_task_group(first), std::logic_error); std::vector> modules; - for (unsigned index = 0; index < 40; ++index) - { + for (unsigned index = 0; index < 40; ++index) { auto next = std::make_unique("next-" + std::to_string(index)); REQUIRE(manager.add_module(next->get_name(), next.get())); manager.create_task_group(*next); @@ -516,8 +504,7 @@ TEST_CASE("Every module must be ready before any shutdown hook and updates retir REQUIRE(manager.update(2)); REQUIRE(manager.pending_tasks() == 0); - for (unsigned attempt = 0; attempt < 2; ++attempt) - { + for (unsigned attempt = 0; attempt < 2; ++attempt) { CHECK_FALSE(manager.stop(3 + attempt)); CHECK(manager.get_shutdown_state() == ark::plugin_manager::shutdown_state::stopping); CHECK(manager.get_shutdown_failure().empty()); @@ -607,8 +594,7 @@ TEST_CASE("Modules without a readiness override keep their default shutdown beha } TEST_CASE("Shutdown hook failure is observable and retains modules without repeated teardown") { - for (unsigned failure = 0; failure < 4; ++failure) - { + for (unsigned failure = 0; failure < 4; ++failure) { CAPTURE(failure); ark::plugin_manager manager; observed_module module("failed-shutdown"); @@ -616,12 +602,10 @@ TEST_CASE("Shutdown hook failure is observable and retains modules without repea auto& tasks = manager.create_task_group(module); module.pre_shut_result = failure != 0; module.shut_result = failure != 1; - if (failure == 2) - { + if (failure == 2) { module.on_pre_shut = [] { throw std::runtime_error("pre_shut failed"); }; } - if (failure == 3) - { + if (failure == 3) { module.on_shut = [] { throw std::runtime_error("shut failed"); }; } CHECK_FALSE(manager.stop(1)); @@ -748,15 +732,13 @@ TEST_CASE("Shutdown retains resources after a required provider is removed") { } TEST_CASE("Shutdown uses unchanged cached metadata but validates an invalidated graph once") { - for (const bool changed : {false, true}) - { + for (const bool changed : {false, true}) { ark::plugin_manager manager; observed_module module("module"), added("added"); REQUIRE(manager.add_module(module.get_name(), &module)); REQUIRE(manager.start(0, {}, {}, {})); module.dependency_metadata_throws = true; - if (changed) - { + if (changed) { REQUIRE(manager.add_module(added.get_name(), &added)); CHECK_FALSE(manager.stop(1)); CHECK(manager.get_shutdown_state() == ark::plugin_manager::shutdown_state::failed); @@ -768,9 +750,7 @@ TEST_CASE("Shutdown uses unchanged cached metadata but validates an invalidated CHECK(module.dependency_reads == 2); CHECK(module.pre_shut_calls == 0); CHECK(added.pre_shut_calls == 0); - } - else - { + } else { CHECK(manager.stop(1)); CHECK(module.dependency_reads == 1); CHECK(module.pre_shut_calls == 1); diff --git a/tests/core/business_runtime_contract.cpp b/tests/core/business_runtime_contract.cpp index 0547a0af9..55778dff4 100644 --- a/tests/core/business_runtime_contract.cpp +++ b/tests/core/business_runtime_contract.cpp @@ -30,8 +30,7 @@ namespace { #endif } -class owner_module final : public ark::module -{ +class owner_module final : public ark::module { public: const std::string& get_name() const override { return name_; @@ -55,23 +54,20 @@ ark::task<> ready_task() { } // namespace int main(int argc, char** argv) { - if (argc != 2) - { + if (argc != 2) { return 2; } std::set_terminate(contract_exit); const std::string_view mode(argv[1]); auto manager = std::make_unique(); owner_module module; - if (mode == "--pending-destruction") - { + if (mode == "--pending-destruction") { manager->add_module(module.get_name(), &module); manager->create_task_group(module).start(ready_task()); manager.reset(); return 3; } - if (mode == "--wrong-thread-destruction") - { + if (mode == "--wrong-thread-destruction") { std::thread worker([owned = std::move(manager)]() mutable { std::set_terminate(contract_exit); owned.reset(); @@ -79,20 +75,17 @@ int main(int argc, char** argv) { worker.join(); return 3; } - if (mode == "--update-destruction") - { + if (mode == "--update-destruction") { manager->add_module(module.get_name(), &module); manager->add_update_module(&module); module.on_update = [&] { manager.reset(); }; manager->update(1); return 3; } - if (mode == "--final-completion-destruction") - { + if (mode == "--final-completion-destruction") { manager->add_module(module.get_name(), &module); manager->create_task_group(module).start(ready_task(), [&](std::exception_ptr error) { - if (error || manager->pending_tasks()) - { + if (error || manager->pending_tasks()) { std::_Exit(4); } manager.reset(); diff --git a/tests/core/callbacks.cpp b/tests/core/callbacks.cpp index ccfee5d47..b5e08047d 100644 --- a/tests/core/callbacks.cpp +++ b/tests/core/callbacks.cpp @@ -18,8 +18,7 @@ namespace { -struct receiver -{ +struct receiver { void on_timer(std::uint64_t timer_id, const ark::guid_t& entity_id) { timer_id_ = timer_id; entity_id_ = entity_id; @@ -34,8 +33,7 @@ struct receiver int calls_{}; }; -class capturing_timer final : public ark::timer_module -{ +class capturing_timer final : public ark::timer_module { public: using ark::timer_module::add_forever_timer; using ark::timer_module::add_single_timer; @@ -60,8 +58,7 @@ class capturing_timer final : public ark::timer_module } }; -class capturing_schedule final : public ark::schedule_module -{ +class capturing_schedule final : public ark::schedule_module { public: using ark::schedule_module::add_at_schedule; using ark::schedule_module::add_interval_schedule; @@ -128,8 +125,7 @@ DOCTEST_TEST_CASE("Member schedule callbacks preserve receiver and scheduling ex #if defined(ARK_HAS_PROTOBUF) namespace { -struct network_receiver -{ +struct network_receiver { network_receiver() = default; network_receiver(const network_receiver&) = delete; @@ -153,8 +149,7 @@ struct network_receiver std::vector events; }; -struct callback_capture -{ +struct callback_capture { ark::net_msg_functor message; ark::net_msg_functor forward; ark::net_event_functor event; @@ -165,8 +160,7 @@ struct callback_capture class capturing_server final : public ark::net_server_service - , public callback_capture -{ + , public callback_capture { public: bool start(std::shared_ptr, ark::bus_id_t, const ark::endpoint&, uint8_t, uint32_t, size_t) override { @@ -208,8 +202,7 @@ class capturing_server final class capturing_client final : public ark::net_client_service - , public callback_capture -{ + , public callback_capture { public: bool start_client(std::shared_ptr, ark::bus_id_t, const ark::endpoint&) override { return false; @@ -268,14 +261,11 @@ void check_network_registration(service_type& service, callback_capture& capture constexpr bool server = std::is_same_v; network_receiver target; REQUIRE(service.reg_msg_callback(71, &target, &network_receiver::on_message)); - if constexpr (std::is_same_v) - { + if constexpr (std::is_same_v) { // The existing server forward overload takes int rather than conv_id_t. REQUIRE(service.reg_forward_msg_callback(&target, &network_receiver::on_forward)); REQUIRE(service.reg_reg_server_call_back(&target, &network_receiver::on_message)); - } - else - { + } else { REQUIRE(service.reg_forward_msg_callback(&target, &network_receiver::on_message)); } REQUIRE(service.reg_net_event_callback(&target, &network_receiver::on_event)); @@ -293,14 +283,12 @@ void check_network_registration(service_type& service, callback_capture& capture captured.message(message.get(), session); captured.forward(message.get(), session + 1); copied(message.get(), session + 2); - if (server) - { + if (server) { captured.session(message.get(), session + 3); } captured.event(&event); REQUIRE(target.messages.size() == (server ? 4 : 3)); - for (std::size_t index = 0; index < target.messages.size(); ++index) - { + for (std::size_t index = 0; index < target.messages.size(); ++index) { CHECK(target.messages[index].first == message.get()); CHECK(target.messages[index].second == session + index); } diff --git a/tests/core/concurrency.cpp b/tests/core/concurrency.cpp index f92d674dd..28c3cabb4 100644 --- a/tests/core/concurrency.cpp +++ b/tests/core/concurrency.cpp @@ -16,8 +16,7 @@ namespace { -struct throwing_value -{ +struct throwing_value { int value = 0; bool throw_copy = false; bool throw_assign = false; @@ -30,15 +29,13 @@ struct throwing_value throwing_value(const throwing_value& other) : value(other.value) { - if (other.throw_copy) - { + if (other.throw_copy) { throw std::runtime_error("copy failed"); } } throwing_value& operator=(const throwing_value& other) { - if (throw_assign) - { + if (throw_assign) { throw std::runtime_error("assignment failed"); } value = other.value; @@ -52,21 +49,20 @@ bool queue_operation_finishes(ark::queue& values, operation_type auto completion = done.get_future(); std::exception_ptr failure; std::thread worker([&] { - try - { operation(); } - catch (...) - { failure = std::current_exception(); } + try { + operation(); + } catch (...) { + failure = std::current_exception(); + } done.set_value(); }); const bool finished = completion.wait_for(std::chrono::seconds(2)) == std::future_status::ready; - if (!finished) - { + if (!finished) { // Recover a leaked spin lock so the regression reports a failure instead of hanging the process. values.unlock(); } worker.join(); - if (failure) - { + if (failure) { std::rethrow_exception(failure); } return finished; @@ -137,60 +133,46 @@ DOCTEST_TEST_CASE("Queue producers consumers and count observers share one synch std::atomic invalid_values{0}; std::atomic invalid_count{false}; std::vector workers; - for (int producer = 0; producer < producer_count; ++producer) - { + for (int producer = 0; producer < producer_count; ++producer) { workers.emplace_back([&, producer] { - for (int value = 0; value < values_per_producer; ++value) - { + for (int value = 0; value < values_per_producer; ++value) { values.push(producer * values_per_producer + value); } ++finished_producers; }); } - for (int consumer = 0; consumer < 3; ++consumer) - { + for (int consumer = 0; consumer < 3; ++consumer) { workers.emplace_back([&] { - while (finished_producers.load() < producer_count || values.count() > 0) - { + while (finished_producers.load() < producer_count || values.count() > 0) { int value; - if (values.pop(value)) - { - if (value < 0 || value >= total) - { + if (values.pop(value)) { + if (value < 0 || value >= total) { ++invalid_values; - } - else - { + } else { ++received[value]; } - } - else - { + } else { std::this_thread::yield(); } } }); } std::thread observer([&] { - while (finished_producers.load() < producer_count || values.count() > 0) - { + while (finished_producers.load() < producer_count || values.count() > 0) { const int size = values.count(); - if (size < 0 || size > total) - { + if (size < 0 || size > total) { invalid_count = true; } } }); - for (auto& worker : workers) - { + for (auto& worker : workers) { worker.join(); } observer.join(); DOCTEST_CHECK(invalid_values.load() == 0); DOCTEST_CHECK_FALSE(invalid_count.load()); DOCTEST_CHECK(values.count() == 0); - for (const auto& count : received) - { + for (const auto& count : received) { DOCTEST_REQUIRE(count.load() == 1); } } diff --git a/tests/core/containers.cpp b/tests/core/containers.cpp index 0ac03212c..6d48a9d78 100644 --- a/tests/core/containers.cpp +++ b/tests/core/containers.cpp @@ -15,8 +15,7 @@ namespace { -struct counted_object -{ +struct counted_object { explicit counted_object(int& destroyed) : destroyed_(destroyed) { } @@ -109,8 +108,7 @@ DOCTEST_TEST_CASE("Object-map constant end iterators delimit all entries") { DOCTEST_CHECK(constant_values.cbegin() != constant_values.cend()); DOCTEST_CHECK(constant_values.cend() == constant_values.end()); int count = 0; - for (auto it = constant_values.cbegin(); it != constant_values.cend(); ++it) - { + for (auto it = constant_values.cbegin(); it != constant_values.cend(); ++it) { ++count; } DOCTEST_CHECK(count == 2); @@ -237,8 +235,7 @@ DOCTEST_TEST_CASE_TEMPLATE("Shared object maps copy ownership and move entries w namespace { -struct pod_iterator_buckets : ark::string_traits -{ +struct pod_iterator_buckets : ark::string_traits { static std::size_t hash(const char* key) { return key[0] == 'z' ? 2 : 0; } @@ -314,8 +311,7 @@ DOCTEST_TEST_CASE("POD string pointer mappings expose the stored pointer slot wi } DOCTEST_TEST_CASE("POD string empty and missing lookup paths reach end without dereferencing it") { - for (const std::size_t buckets : {std::size_t{0}, std::size_t{4}}) - { + for (const std::size_t buckets : {std::size_t{0}, std::size_t{4}}) { ark::pod_string values(buckets); DOCTEST_CHECK(values.begin() == values.end()); DOCTEST_CHECK(values.find("missing") == values.end()); diff --git a/tests/core/cxx20_language.cpp b/tests/core/cxx20_language.cpp index 877b96ea9..eafab4b7b 100644 --- a/tests/core/cxx20_language.cpp +++ b/tests/core/cxx20_language.cpp @@ -15,12 +15,9 @@ namespace { -struct custom_value -{ -}; +struct custom_value {}; -enum class integer_enum : std::uint32_t -{ +enum class integer_enum : std::uint32_t { value }; @@ -104,8 +101,7 @@ TEST_CASE("UID bit layouts reject invalid widths before shifting") { {63, 1, -1}, {std::numeric_limits::max(), 0, 0}, {0, std::numeric_limits::max(), std::numeric_limits::max()}, {0, 0, std::numeric_limits::min()}}}; - for (const auto& widths : invalid) - { + for (const auto& widths : invalid) { CAPTURE(widths); CHECK_THROWS_AS(ark::bits_allocator(widths[0], widths[1], widths[2]), std::invalid_argument); } @@ -121,8 +117,7 @@ TEST_CASE("UID bit allocation retains fixed values and maximum unsigned fields") CHECK(allocator.get_max_delta_seconds() == 536870911); CHECK(allocator.get_max_sequence() == 1023); - struct allocation_case - { + struct allocation_case { int64_t delta; int64_t worker; int64_t sequence; @@ -131,8 +126,7 @@ TEST_CASE("UID bit allocation retains fixed values and maximum unsigned fields") const std::array cases{{{0, 0, 0, 0}, {1, 0, 0, 17179869184}, {0, 1, 0, 1024}, {0, 0, 1, 1}, {123456789, 16777215, 1023, 2120971502076559359}, {536870911, 16777215, 1023, 9223372036854775807}}}; - for (const auto& input : cases) - { + for (const auto& input : cases) { CAPTURE(input.delta); CAPTURE(input.worker); CAPTURE(input.sequence); @@ -143,26 +137,20 @@ TEST_CASE("UID bit allocation retains fixed values and maximum unsigned fields") TEST_CASE("UID fields cannot spill into adjacent fields") { ark::bits_allocator allocator(29, 24, 10); for (const auto& value : std::array, 7>{{{-1, 0, 0}, {536870912, 0, 0}, {0, -1, 0}, - {0, 16777216, 0}, {0, 0, -1}, {0, 0, 1024}, {std::numeric_limits::max(), 0, 0}}}) - { + {0, 16777216, 0}, {0, 0, -1}, {0, 0, 1024}, {std::numeric_limits::max(), 0, 0}}}) { CAPTURE(value); CHECK_THROWS_AS(allocator.alloc(value[0], value[1], value[2]), std::out_of_range); } CHECK(allocator.alloc(1, 0, 0) == 17179869184); - for (const auto& widths : std::array, 3>{{{63, 0, 0}, {0, 63, 0}, {0, 0, 63}}}) - { + for (const auto& widths : std::array, 3>{{{63, 0, 0}, {0, 63, 0}, {0, 0, 63}}}) { ark::bits_allocator edge(widths[0], widths[1], widths[2]); - for (int field = 0; field < 3; ++field) - { + for (int field = 0; field < 3; ++field) { std::array value{}; value[field] = std::numeric_limits::max(); - if (widths[field] == 63) - { + if (widths[field] == 63) { CHECK(edge.alloc(value[0], value[1], value[2]) == value[field]); - } - else - { + } else { CHECK_THROWS_AS(edge.alloc(value[0], value[1], value[2]), std::out_of_range); } } diff --git a/tests/core/data_allocation_failure.cpp b/tests/core/data_allocation_failure.cpp index 36c565782..fa06d3664 100644 --- a/tests/core/data_allocation_failure.cpp +++ b/tests/core/data_allocation_failure.cpp @@ -25,16 +25,16 @@ template bool default_failure(F&& operation) { fail_next_array = true; bool threw{}; - try - { operation(); } - catch (const std::bad_alloc&) - { threw = true; } + try { + operation(); + } catch (const std::bad_alloc&) { + threw = true; + } CHECK_FALSE(fail_next_array); return threw; } -struct saved_value -{ +struct saved_value { ark::data_type type; std::string content; const void* storage{}; @@ -43,20 +43,15 @@ struct saved_value saved_value save(const ark::data& value) { saved_value result{value.get_type(), {}, nullptr, 0}; - if (result.type == ark::data_type::dt_string) - { + if (result.type == ark::data_type::dt_string) { result.content = value.get_string(); result.storage = value.get_string(); - } - else if (result.type == ark::data_type::dt_userdata) - { + } else if (result.type == ark::data_type::dt_userdata) { std::size_t size{}; const auto* data = static_cast(value.get_user_data(size)); result.content.assign(data, size); result.storage = value.get_raw_user_data(); - } - else - { + } else { result.number = value.get_int(); } return result; @@ -72,8 +67,7 @@ void unchanged(const ark::data& value, const saved_value& previous) { template void initial_value(T& value, int kind) { - switch (kind) - { + switch (kind) { case 0: value.set_int(42); break; @@ -89,11 +83,9 @@ void initial_value(T& value, int kind) { } } -class tracked_allocator -{ +class tracked_allocator { public: - enum class failure - { + enum class failure { none, null, exception @@ -106,12 +98,10 @@ class tracked_allocator void* alloc(std::size_t size) { const auto mode = successful_before_failure ? (--successful_before_failure, failure::none) : std::exchange(next, failure::none); - if (mode == failure::null) - { + if (mode == failure::null) { return nullptr; } - if (mode == failure::exception) - { + if (mode == failure::exception) { throw std::bad_alloc{}; } auto* value = new char[size]; @@ -120,13 +110,11 @@ class tracked_allocator } void free(void* value, std::size_t size) { - if (!value) - { + if (!value) { return; } const auto found = live.find(value); - if (found == live.end() || found->second != std::make_pair(id_, size)) - { + if (found == live.end() || found->second != std::make_pair(id_, size)) { std::abort(); } live.erase(found); @@ -148,19 +136,17 @@ using tracked_data = ark::data_base<8, tracked_allocator>; // Exercise the real default allocator and default ARK_NEW_ARRAY_RET expansion. // Only its standard nothrow new[] call fails; successful storage uses normal new[]/delete[]. void* operator new[](std::size_t size, const std::nothrow_t&) noexcept { - if (fail_next_array && fail_array_after) - { + if (fail_next_array && fail_array_after) { --fail_array_after; - } - else if (fail_next_array) - { + } else if (fail_next_array) { fail_next_array = false; return nullptr; } - try - { return ::operator new[](size); } - catch (...) - { return nullptr; } + try { + return ::operator new[](size); + } catch (...) { + return nullptr; + } } void operator delete[](void* value, const std::nothrow_t&) noexcept { @@ -176,20 +162,15 @@ TEST_CASE("Default data allocator null user data construction reports bad_alloc" } TEST_CASE("Default data allocator failed setters retain scalar inline string heap string and user data") { - for (int kind = 0; kind < 4; ++kind) - { - for (bool user_data : {false, true}) - { + for (int kind = 0; kind < 4; ++kind) { + for (bool user_data : {false, true}) { ark::data_impl value; initial_value(value, kind); const auto previous = save(value); CHECK(default_failure([&] { - if (user_data) - { + if (user_data) { value.set_user_data(bytes, sizeof(bytes)); - } - else - { + } else { value.set_string(text); } })); @@ -199,33 +180,25 @@ TEST_CASE("Default data allocator failed setters retain scalar inline string hea } TEST_CASE("Default data allocator failed copies and assignments retain both operands") { - for (bool user_data : {false, true}) - { + for (bool user_data : {false, true}) { ark::data_impl source; - if (user_data) - { + if (user_data) { source.set_user_data(bytes, sizeof(bytes)); - } - else - { + } else { source.set_string(text); } const auto before_source = save(source); const ark::data& erased = source; - for (int operation = 0; operation < 5; ++operation) - { + for (int operation = 0; operation < 5; ++operation) { ark::data_impl target(ark::data_type::dt_string, "old allocated string value"); const auto before_target = save(target); CHECK(default_failure([&] { - switch (operation) - { - case 0: - { + switch (operation) { + case 0: { ark::data_impl copy(source); break; } - case 1: - { + case 1: { ark::data_impl copy(erased); break; } @@ -256,8 +229,7 @@ TEST_CASE("Default data allocator inline strings need no heap allocation") { } TEST_CASE("Data setters retain self source storage until replacement is complete") { - for (const auto input : {"abc", text}) - { + for (const auto input : {"abc", text}) { ark::data_impl value(ark::data_type::dt_string, input); value.set_string(value.get_string()); CHECK(std::string(value.get_string()) == input); @@ -284,28 +256,22 @@ TEST_CASE("Data setters retain self source storage until replacement is complete } TEST_CASE("Custom data allocators preserve old values and matching storage ownership on null and throw") { - for (auto mode : {tracked_allocator::failure::null, tracked_allocator::failure::exception}) - { + for (auto mode : {tracked_allocator::failure::null, tracked_allocator::failure::exception}) { REQUIRE(tracked_allocator::live.empty()); - for (int kind = 0; kind < 4; ++kind) - { - for (int operation = 0; operation < 6; ++operation) - { + for (int kind = 0; kind < 4; ++kind) { + for (int operation = 0; operation < 6; ++operation) { tracked_data value; initial_value(value, kind); tracked_data source(ark::data_type::dt_string, text); - if (operation == 3) - { + if (operation == 3) { source.set_user_data(bytes, sizeof(bytes)); } const auto previous = save(value); const auto allocations = tracked_allocator::live; tracked_allocator::next = mode; bool threw{}; - try - { - switch (operation) - { + try { + switch (operation) { case 0: value.set_string(text); break; @@ -318,20 +284,18 @@ TEST_CASE("Custom data allocators preserve old values and matching storage owner case 3: value.assign(source); break; - case 4: - { + case 4: { tracked_data copy(source); break; } - default: - { + default: { tracked_data copy(ark::data_type::dt_userdata, bytes, sizeof(bytes)); break; } } + } catch (const std::bad_alloc&) { + threw = true; } - catch (const std::bad_alloc&) - { threw = true; } CHECK(threw); CHECK(tracked_allocator::next == tracked_allocator::failure::none); unchanged(value, previous); @@ -347,8 +311,7 @@ TEST_CASE("Custom allocator node conversion rejects null allocation without losi meta->set_type(ark::data_type::dt_string); ark::node_string source(meta); source.set_string(text); - for (auto mode : {tracked_allocator::failure::null, tracked_allocator::failure::exception}) - { + for (auto mode : {tracked_allocator::failure::null, tracked_allocator::failure::exception}) { tracked_data value(ark::data_type::dt_string, "old allocated string value"); const auto previous = save(value); tracked_allocator::next = mode; @@ -359,8 +322,7 @@ TEST_CASE("Custom allocator node conversion rejects null allocation without losi } TEST_CASE("Custom allocator self source failures retain string and user data") { - for (auto mode : {tracked_allocator::failure::null, tracked_allocator::failure::exception}) - { + for (auto mode : {tracked_allocator::failure::null, tracked_allocator::failure::exception}) { tracked_data value(ark::data_type::dt_string, text); auto previous = save(value); tracked_allocator::next = mode; @@ -434,8 +396,7 @@ TEST_CASE("Raw user data length rejects a size_t header overflow") { TEST_CASE("DataList excessive user data is rejected before allocating or publishing an index") { constexpr auto maximum = std::numeric_limits::max(); - for (const auto size : {maximum, maximum - sizeof(std::size_t) + 1, maximum - sizeof(std::size_t)}) - { + for (const auto size : {maximum, maximum - sizeof(std::size_t) + 1, maximum - sizeof(std::size_t)}) { ark::base_data_list<1, 16, tracked_allocator> values; REQUIRE(values.add_string("1234567")); // Old code attempts index growth first. Refuse that allocation so even @@ -466,16 +427,14 @@ namespace { template void failed_list_append(tracked_allocator::failure mode, bool fail_buffer_after_index) { - for (int kind = 0; kind < 3; ++kind) - { + for (int kind = 0; kind < 3; ++kind) { ark::base_data_list values; REQUIRE(values.add_int(17)); const auto previous_memory = values.get_mem_usage(); tracked_allocator::next = mode; tracked_allocator::successful_before_failure = fail_buffer_after_index ? 1 : 0; const auto append = [&] { - if (kind == 0) - { + if (kind == 0) { return values.add_user_data(text, sizeof(text)); } return kind == 1 ? values.add_string(text) : values.add_string(text, sizeof(text)); @@ -486,24 +445,19 @@ void failed_list_append(tracked_allocator::failure mode, bool fail_buffer_after_ tracked_allocator::successful_before_failure = 0; CHECK(values.get_count() == 1); CHECK(values.get_int(0) == 17); - if (fail_buffer_after_index) - { + if (fail_buffer_after_index) { CHECK(values.get_mem_usage() > previous_memory); } // Avoid inspecting an incomplete old-code record in the red regression. - if (values.get_count() == 1) - { + if (values.get_count() == 1) { REQUIRE(append()); CHECK(values.get_count() == 2); - if (kind == 0) - { + if (kind == 0) { std::size_t size{}; const auto* result = values.user_data(1, size); CHECK(size == sizeof(text)); CHECK(std::memcmp(result, text, size) == 0); - } - else - { + } else { CHECK(std::string(values.string(1)) == text); } } @@ -594,8 +548,7 @@ void fill_copy_list(List& values, int first = 17) { template void check_copy_list(const List& values, int first = 17) { CHECK(values.get_count() == 3); - if (values.get_count() == 3) - { + if (values.get_count() == 3) { CHECK(values.get_int(0) == first); CHECK(std::string(values.string(1)) == text); CHECK(values.get_int(2) == first + 1); @@ -605,16 +558,12 @@ void check_copy_list(const List& values, int first = 17) { void recover_failed_copy(std::size_t owner) { // Red regressions recover only storage owned by the failed constructor; // live source/target allocators keep their own allocations untouched. - for (auto it = tracked_allocator::live.begin(); it != tracked_allocator::live.end();) - { - if (it->second.first == owner) - { + for (auto it = tracked_allocator::live.begin(); it != tracked_allocator::live.end();) { + if (it->second.first == owner) { auto* pointer = static_cast(it->first); it = tracked_allocator::live.erase(it); delete[] pointer; - } - else - { + } else { ++it; } } @@ -623,12 +572,9 @@ void recover_failed_copy(std::size_t owner) { } // namespace TEST_CASE("DataList copy constructors release partial storage after null and throwing allocations") { - for (bool through_interface : {false, true}) - { - for (auto mode : {tracked_allocator::failure::null, tracked_allocator::failure::exception}) - { - for (std::size_t position : {1u, 2u}) - { + for (bool through_interface : {false, true}) { + for (auto mode : {tracked_allocator::failure::null, tracked_allocator::failure::exception}) { + for (std::size_t position : {1u, 2u}) { CAPTURE(through_interface); CAPTURE(position); CAPTURE(static_cast(mode)); @@ -639,13 +585,10 @@ TEST_CASE("DataList copy constructors release partial storage after null and thr tracked_allocator::next = mode; tracked_allocator::successful_before_failure = position; const auto copy = [&] { - if (through_interface) - { + if (through_interface) { const ark::data_list& interface = source; copy_list destination(interface); - } - else - { + } else { copy_list destination(source); } }; @@ -656,8 +599,7 @@ TEST_CASE("DataList copy constructors release partial storage after null and thr tracked_allocator::successful_before_failure = 0; CHECK(tracked_allocator::live == original); check_copy_list(source); - if (source.get_count() == 3) - { + if (source.get_count() == 3) { CHECK(static_cast(source.string(1)) == static_cast(storage)); } recover_failed_copy(failed_owner); @@ -667,12 +609,10 @@ TEST_CASE("DataList copy constructors release partial storage after null and thr } TEST_CASE("DataList self assignment preserves inline and allocated values and its by-value result") { - for (bool allocated : {false, true}) - { + for (bool allocated : {false, true}) { copy_list source; REQUIRE(source.add_int(17)); - if (allocated) - { + if (allocated) { REQUIRE(source.add_string(text)); REQUIRE(source.add_int(18)); } @@ -683,12 +623,10 @@ TEST_CASE("DataList self assignment preserves inline and allocated values and it auto returned = (source = *same); CHECK(source.get_count() == count); CHECK(returned.get_count() == count); - if (source.get_count() == count && returned.get_count() == count) - { + if (source.get_count() == count && returned.get_count() == count) { CHECK(source.get_int(0) == 17); CHECK(returned.get_int(0) == 17); - if (allocated) - { + if (allocated) { CHECK(returned.string(1) != source.string(1)); REQUIRE(returned.set_string(1, "changed")); CHECK(std::string(source.string(1)) == text); @@ -700,10 +638,8 @@ TEST_CASE("DataList self assignment preserves inline and allocated values and it } TEST_CASE("DataList self assignment return-copy failures preserve values and allocator ownership") { - for (auto mode : {tracked_allocator::failure::null, tracked_allocator::failure::exception}) - { - for (std::size_t position : {1u, 2u}) - { + for (auto mode : {tracked_allocator::failure::null, tracked_allocator::failure::exception}) { + for (std::size_t position : {1u, 2u}) { copy_list source; fill_copy_list(source); const auto original = tracked_allocator::live; @@ -717,8 +653,7 @@ TEST_CASE("DataList self assignment return-copy failures preserve values and all tracked_allocator::successful_before_failure = 0; CHECK(tracked_allocator::live == original); check_copy_list(source); - if (source.get_count() == 3) - { + if (source.get_count() == 3) { CHECK(static_cast(source.string(1)) == static_cast(storage)); } recover_failed_copy(tracked_allocator::next_id); @@ -727,23 +662,18 @@ TEST_CASE("DataList self assignment return-copy failures preserve values and all } TEST_CASE("Default DataList copies and self assignment preserve the source on null array allocations") { - for (bool through_interface : {false, true}) - { - for (std::size_t position : {1u, 2u}) - { + for (bool through_interface : {false, true}) { + for (std::size_t position : {1u, 2u}) { ark::base_data_list<1, 16> source; fill_copy_list(source); const auto* storage = source.string(1); fail_next_array = true; fail_array_after = position; const auto copy = [&] { - if (through_interface) - { + if (through_interface) { const ark::data_list& interface = source; ark::base_data_list<1, 16> destination(interface); - } - else - { + } else { ark::base_data_list<1, 16> destination(source); } }; @@ -752,8 +682,7 @@ TEST_CASE("Default DataList copies and self assignment preserve the source on nu fail_next_array = false; fail_array_after = 0; check_copy_list(source); - if (source.get_count() == 3) - { + if (source.get_count() == 3) { CHECK(static_cast(source.string(1)) == static_cast(storage)); } fail_next_array = true; @@ -764,8 +693,7 @@ TEST_CASE("Default DataList copies and self assignment preserve the source on nu fail_next_array = false; fail_array_after = 0; check_copy_list(source); - if (source.get_count() == 3) - { + if (source.get_count() == 3) { CHECK(static_cast(source.string(1)) == static_cast(storage)); } } @@ -774,10 +702,8 @@ TEST_CASE("Default DataList copies and self assignment preserve the source on nu TEST_CASE("DataList tokenizing constructor releases partial storage after null and throwing allocations") { constexpr char source[] = "abcdefghijklmnop,qrstuvwxyzabcdefgh,tail"; - for (auto mode : {tracked_allocator::failure::null, tracked_allocator::failure::exception}) - { - for (std::size_t position : {0u, 1u, 2u, 3u}) - { + for (auto mode : {tracked_allocator::failure::null, tracked_allocator::failure::exception}) { + for (std::size_t position : {0u, 1u, 2u, 3u}) { CAPTURE(position); CAPTURE(static_cast(mode)); const auto original = tracked_allocator::live; @@ -796,8 +722,7 @@ TEST_CASE("DataList tokenizing constructor releases partial storage after null a TEST_CASE("Default DataList tokenizing constructor reports null array allocations") { constexpr char source[] = "abcdefghijklmnop,qrstuvwxyzabcdefgh,tail"; - for (std::size_t position : {0u, 1u, 2u, 3u}) - { + for (std::size_t position : {0u, 1u, 2u, 3u}) { fail_next_array = true; fail_array_after = position; CHECK_THROWS_AS((ark::base_data_list<1, 16>(source, sizeof(source) - 1, ',')), std::bad_alloc); diff --git a/tests/core/data_allocation_hooks.cpp b/tests/core/data_allocation_hooks.cpp index e7e72f11d..26c964a70 100644 --- a/tests/core/data_allocation_hooks.cpp +++ b/tests/core/data_allocation_hooks.cpp @@ -16,18 +16,14 @@ std::size_t allocations{}; std::size_t releases{}; void* hook_allocate(std::size_t size) { - if (fail_next && successful_before_failure) - { + if (fail_next && successful_before_failure) { --successful_before_failure; - } - else if (fail_next) - { + } else if (fail_next) { fail_next = false; return nullptr; } auto* pointer = std::malloc(size ? size : 1); - if (!pointer) - { + if (!pointer) { throw std::bad_alloc{}; } live.insert(pointer); @@ -36,10 +32,8 @@ void* hook_allocate(std::size_t size) { } void hook_free(void*& pointer) { - if (pointer) - { - if (live.erase(pointer) != 1) - { + if (pointer) { + if (live.erase(pointer) != 1) { std::abort(); } ++releases; @@ -137,20 +131,15 @@ TEST_CASE("DataList array hooks release partial copies and preserve self assignm REQUIRE(source.add_string("a copied value longer than the inline buffer")); REQUIRE(source.add_int(18)); const auto original = live; - for (bool through_interface : {false, true}) - { - for (std::size_t position : {1u, 2u}) - { + for (bool through_interface : {false, true}) { + for (std::size_t position : {1u, 2u}) { fail_next = true; successful_before_failure = position; const auto copy = [&] { - if (through_interface) - { + if (through_interface) { const ark::data_list& interface = source; list destination(interface); - } - else - { + } else { list destination(source); } }; @@ -160,11 +149,9 @@ TEST_CASE("DataList array hooks release partial copies and preserve self assignm successful_before_failure = 0; CHECK(live == original); // Recover only a red-regression constructor's unpublished buffers. - for (auto it = live.begin(); it != live.end();) - { + for (auto it = live.begin(); it != live.end();) { void* pointer = *it++; - if (!original.contains(pointer)) - { + if (!original.contains(pointer)) { hook_free(pointer); } } @@ -192,8 +179,7 @@ TEST_CASE("DataList tokenizing constructor retains matching array hooks on failu constexpr char source[] = "abcdefghijklmnop,qrstuvwxyzabcdefgh,tail"; const auto initial_allocations = allocations; const auto initial_releases = releases; - for (std::size_t position : {0u, 1u, 2u, 3u}) - { + for (std::size_t position : {0u, 1u, 2u, 3u}) { fail_next = true; successful_before_failure = position; CHECK_THROWS_AS((ark::base_data_list<1, 16>(source, sizeof(source) - 1, ',')), std::bad_alloc); @@ -202,8 +188,7 @@ TEST_CASE("DataList tokenizing constructor retains matching array hooks on failu successful_before_failure = 0; CHECK(live.empty()); // Recover only unpublished storage left by the old constructor in a red run. - while (!live.empty()) - { + while (!live.empty()) { void* pointer = *live.begin(); hook_free(pointer); } diff --git a/tests/core/data_length_bounds.cpp b/tests/core/data_length_bounds.cpp index 2f40685c1..48e6e9e64 100644 --- a/tests/core/data_length_bounds.cpp +++ b/tests/core/data_length_bounds.cpp @@ -13,8 +13,7 @@ namespace { -struct measured_allocator -{ +struct measured_allocator { static inline std::size_t calls{}; static inline std::size_t requested{}; static inline bool reject{}; @@ -22,8 +21,7 @@ struct measured_allocator void* alloc(std::size_t size) { ++calls; requested = size; - if (reject) - { + if (reject) { return nullptr; } return new char[size]; @@ -40,8 +38,7 @@ struct measured_allocator using measured_data = ark::data_base<8, measured_allocator>; constexpr char payload[] = "binary\0value"; -struct reject_allocations -{ +struct reject_allocations { reject_allocations() { measured_allocator::reject = true; } @@ -55,8 +52,7 @@ struct reject_allocations TEST_CASE("Kernel owned user data rejects unrepresentable storage before allocation") { const std::size_t limit = std::numeric_limits::max(); - for (const auto size : {limit - sizeof(std::size_t) + 1, limit, std::numeric_limits::max()}) - { + for (const auto size : {limit - sizeof(std::size_t) + 1, limit, std::numeric_limits::max()}) { CAPTURE(size); measured_data previous(ark::data_type::dt_string, "existing allocated value"); const auto* storage = previous.get_string(); @@ -122,19 +118,16 @@ TEST_CASE("Kernel owned data rejects oversized raw metadata during copy and assi TEST_CASE("Kernel owned data keeps valid inline string and binary storage behavior") { measured_data value; - for (const auto* text : {"", "1234567", "12345678", "a longer allocated string"}) - { + for (const auto* text : {"", "1234567", "12345678", "a longer allocated string"}) { value.set_string(text); CHECK(std::string(value.get_string()) == text); } - for (const auto size : {std::size_t{0}, sizeof(payload)}) - { + for (const auto size : {std::size_t{0}, sizeof(payload)}) { value.set_user_data(payload, size); std::size_t actual{}; const auto* bytes = value.get_user_data(actual); CHECK(actual == size); - if (size) - { + if (size) { CHECK(std::memcmp(bytes, payload, size) == 0); } measured_data copy(value); @@ -142,8 +135,7 @@ TEST_CASE("Kernel owned data keeps valid inline string and binary storage behavi std::size_t copied_size{}; const auto* copied_bytes = copy.get_user_data(copied_size); CHECK(copied_size == size); - if (size) - { + if (size) { CHECK(std::memcmp(copied_bytes, payload, size) == 0); } } diff --git a/tests/core/data_strings.cpp b/tests/core/data_strings.cpp index c5c79766c..5a4161edd 100644 --- a/tests/core/data_strings.cpp +++ b/tests/core/data_strings.cpp @@ -16,8 +16,7 @@ const std::array string_values{"", "a", "1234567", "12345678", s } // namespace DOCTEST_TEST_CASE("Kernel string data compare content in independent inline and allocated storage") { - for (const auto& value : string_values) - { + for (const auto& value : string_values) { DOCTEST_CAPTURE(value); string_data left(ark::data_type::dt_string, value.c_str()); string_data right(ark::data_type::dt_string, value.c_str()); @@ -70,10 +69,8 @@ DOCTEST_TEST_CASE("Kernel string comparisons preserve null pointer distinctions } DOCTEST_TEST_CASE("Kernel string swap preserves both values across inline boundaries and repeated swaps") { - for (const auto& first : string_values) - { - for (const auto& second : string_values) - { + for (const auto& first : string_values) { + for (const auto& second : string_values) { DOCTEST_CAPTURE(first); DOCTEST_CAPTURE(second); string_data left(ark::data_type::dt_string, first.c_str()); @@ -100,8 +97,7 @@ DOCTEST_TEST_CASE("Kernel string swap preserves both values across inline bounda } DOCTEST_TEST_CASE("Kernel string self swaps and copy assignment retain independent owning values") { - for (const auto& value : string_values) - { + for (const auto& value : string_values) { DOCTEST_CAPTURE(value); string_data original(ark::data_type::dt_string, value.c_str()); original.swap(original); @@ -112,8 +108,7 @@ DOCTEST_TEST_CASE("Kernel string self swaps and copy assignment retain independe const auto& self = copy; copy = self; DOCTEST_CHECK(std::string(copy.get_string()) == value); - for (const auto& before : string_values) - { + for (const auto& before : string_values) { DOCTEST_CAPTURE(before); string_data assigned(ark::data_type::dt_string, before.c_str()); assigned = copy; diff --git a/tests/core/dynamic_library.cpp b/tests/core/dynamic_library.cpp index 56f98f10b..0320ffc4b 100644 --- a/tests/core/dynamic_library.cpp +++ b/tests/core/dynamic_library.cpp @@ -17,8 +17,7 @@ namespace ark::detail { -struct dynamic_library_test_access -{ +struct dynamic_library_test_access { static bool succeeded(int result) { return dynamic_library::native_unload_succeeded(result); } @@ -33,8 +32,7 @@ struct dynamic_library_test_access } }; -struct plugin_manager_test_access -{ +struct plugin_manager_test_access { static void configure(plugin_manager& manager, const std::string& name) { manager.plugins_.emplace(name, "ownership.toml"); manager.plugin_conf_dir_ = "conf/"; @@ -54,10 +52,8 @@ struct plugin_manager_test_access } static void release_retained(plugin_manager& manager) { - for (auto& [name, library] : manager.plugin_libs_) - { - if (library) - { + for (auto& [name, library] : manager.plugin_libs_) { + if (library) { CHECK(library->unload()); delete library; library = nullptr; @@ -73,8 +69,7 @@ namespace { using library_access = ark::detail::dynamic_library_test_access; using manager_access = ark::detail::plugin_manager_test_access; -enum class plugin_failure -{ +enum class plugin_failure { none, allocation, manager_metadata, @@ -82,8 +77,7 @@ enum class plugin_failure install }; -struct plugin_events -{ +struct plugin_events { plugin_failure failure{}; unsigned destroyed{}; unsigned deallocated{}; @@ -94,8 +88,7 @@ struct plugin_events ark::plugin* retained{}; }; -class ownership_plugin final : public ark::plugin_base -{ +class ownership_plugin final : public ark::plugin_base { public: inline static plugin_events* events{}; @@ -118,8 +111,7 @@ class ownership_plugin final : public ark::plugin_base void set_plugin_manager(ark::plugin_manager* manager) override { ++events->manager_assignments; - if (events->failure == plugin_failure::manager_metadata) - { + if (events->failure == plugin_failure::manager_metadata) { throw std::runtime_error("manager metadata failed"); } plugin_base::set_plugin_manager(manager); @@ -127,8 +119,7 @@ class ownership_plugin final : public ark::plugin_base void set_plugin_conf(const std::string& configuration) override { ++events->configuration_assignments; - if (events->failure == plugin_failure::configuration_metadata) - { + if (events->failure == plugin_failure::configuration_metadata) { throw std::runtime_error("configuration metadata failed"); } CHECK(configuration == "conf/ownership.toml"); @@ -138,8 +129,7 @@ class ownership_plugin final : public ark::plugin_base void install() override { ++events->installs; events->retained = this; - if (events->failure == plugin_failure::install) - { + if (events->failure == plugin_failure::install) { throw std::runtime_error("installation failed"); } } @@ -163,13 +153,11 @@ constexpr int native_failure = 0; constexpr int native_failure = 1; #endif -class quiet_logger -{ +class quiet_logger { public: explicit quiet_logger(bool throw_error = false) { logger_.set_log_func([throw_error](spdlog::level::level_enum level, const std::string&) { - if (throw_error && level == spdlog::level::err) - { + if (throw_error && level == spdlog::level::err) { throw std::runtime_error("load diagnostic failed"); } }); @@ -185,8 +173,7 @@ class quiet_logger ark::logger logger_; }; -struct retained_manager -{ +struct retained_manager { ark::plugin_manager manager; ~retained_manager() { @@ -206,25 +193,19 @@ struct retained_manager TEST_CASE("Plugin candidates retain nothrow allocation and retire failed metadata once") { for (const auto failure : {plugin_failure::allocation, plugin_failure::manager_metadata, - plugin_failure::configuration_metadata, plugin_failure::none}) - { + plugin_failure::configuration_metadata, plugin_failure::none}) { CAPTURE(static_cast(failure)); plugin_events events{failure}; ownership_plugin::events = &events; ark::plugin_manager manager; manager_access::configure(manager, "ownership-probe"); - if (failure == plugin_failure::manager_metadata) - { + if (failure == plugin_failure::manager_metadata) { CHECK_THROWS_WITH_AS(manager.register_plugin("ownership-probe"), "manager metadata failed", std::runtime_error); - } - else if (failure == plugin_failure::configuration_metadata) - { + } else if (failure == plugin_failure::configuration_metadata) { CHECK_THROWS_WITH_AS(manager.register_plugin("ownership-probe"), "configuration metadata failed", std::runtime_error); - } - else - { + } else { CHECK_NOTHROW(manager.register_plugin("ownership-probe")); } CHECK(events.manager_assignments == (failure == plugin_failure::allocation ? 0 : 1)); @@ -238,8 +219,7 @@ TEST_CASE("Plugin candidates retain nothrow allocation and retire failed metadat CHECK(events.deallocated == events.destroyed); CHECK(manager.get_startup_failure() == (failure == plugin_failure::allocation ? "allocate_plugin: ownership-probe" : "")); - if (failure == plugin_failure::none) - { + if (failure == plugin_failure::none) { // A distinct library stem still unregisters through the RTTI key. CHECK_NOTHROW(manager.unregister_plugin()); CHECK(events.uninstalls == 1); @@ -268,19 +248,15 @@ TEST_CASE("Plugin installation exceptions keep the existing explicit cleanup bou } TEST_CASE("Failed library loading retires unpublished wrappers even when diagnostics throw") { - for (const bool throw_error : {false, true}) - { + for (const bool throw_error : {false, true}) { quiet_logger logger(throw_error); ark::plugin_manager manager; const auto start = [&] { return manager.start(0, ARK_UNLOAD_PROBE_DIR, {}, {{"ark_missing_ownership_probe", ""}}); }; - if (throw_error) - { + if (throw_error) { CHECK_THROWS_WITH_AS(start(), "load diagnostic failed", std::runtime_error); - } - else - { + } else { CHECK_FALSE(start()); } CHECK(manager_access::libraries(manager).empty()); @@ -299,15 +275,13 @@ TEST_CASE("A null plugin allocation fails its real entrypoint before later libra REQUIRE(first.load(ARK_ALLOCATION_PROBE_DIR)); REQUIRE(second.load(ARK_ALLOCATION_PROBE_DIR)); using set_entry = void (*)(void (*)(ark::plugin_manager*, const std::string&)); - for (auto* library : {&first, &second}) - { + for (auto* library : {&first, &second}) { const auto set = reinterpret_cast(library->get_symbol("allocation_probe_set_entry")); REQUIRE(set != nullptr); set(allocate_entry_plugin); } - struct startup_module final : ark::module - { + struct startup_module final : ark::module { bool init() override { ++calls; return true; @@ -476,8 +450,7 @@ bool unknown_exit_exception{}; void failing_exit(ark::plugin_manager*) { ++failing_exit_calls; - if (unknown_exit_exception) - { + if (unknown_exit_exception) { throw 7; } throw std::runtime_error("test plugin exit exception"); @@ -486,14 +459,12 @@ void failing_exit(ark::plugin_manager*) { } // namespace TEST_CASE("Plugin exit exceptions retain handles and never retry uninstall or native close") { - for (const bool unknown : {false, true}) - { + for (const bool unknown : {false, true}) { quiet_logger logger; constexpr const char* name = "ark_plugin_allocation_first"; ark::dynamic_library observer(name); - struct close_observer - { + struct close_observer { ark::dynamic_library& library; ~close_observer() { @@ -509,8 +480,7 @@ TEST_CASE("Plugin exit exceptions retain handles and never retry uninstall or na REQUIRE(set_entry != nullptr); REQUIRE(set_exit != nullptr); - struct reset_callbacks - { + struct reset_callbacks { decltype(set_entry) reset_entry; decltype(set_exit) reset_exit; @@ -542,22 +512,19 @@ TEST_CASE("Plugin exit exceptions retain handles and never retry uninstall or na const auto failure = owner.manager.get_shutdown_exception(); REQUIRE(failure); bool observed{}; - try - { std::rethrow_exception(failure); } - catch (const std::runtime_error& error) - { + try { + std::rethrow_exception(failure); + } catch (const std::runtime_error& error) { CHECK_FALSE(unknown); CHECK(std::string(error.what()) == "test plugin exit exception"); observed = true; - } - catch (int value) - { + } catch (int value) { CHECK(unknown); CHECK(value == 7); observed = true; + } catch (...) { + FAIL("Plugin exit lost its exception type"); } - catch (...) - { FAIL("Plugin exit lost its exception type"); } CHECK(observed); const auto retained = manager_access::libraries(owner.manager); REQUIRE(retained.size() == 1); @@ -575,8 +542,7 @@ TEST_CASE("Plugin exit exceptions retain handles and never retry uninstall or na namespace { -struct cleanup_events -{ +struct cleanup_events { std::vector order; bool provider_cleaned{}; bool provider_stopped{}; @@ -587,19 +553,15 @@ struct cleanup_events cleanup_events* active_cleanup{}; -class lifetime_provider : public ark::module -{ +class lifetime_provider : public ark::module { public: int value{42}; std::function callback; }; -class lifetime_consumer : public ark::module -{ -}; +class lifetime_consumer : public ark::module {}; -class lifetime_provider_impl final : public ark::module_base -{ +class lifetime_provider_impl final : public ark::module_base { public: ~lifetime_provider_impl() override { CHECK(active_cleanup->consumer_destroyed); @@ -624,13 +586,11 @@ class lifetime_provider_impl final : public ark::module_base } }; -class lifetime_consumer_impl final : public ark::module_base -{ +class lifetime_consumer_impl final : public ark::module_base { public: bool init() override { provider_ = find_module(); - if (!provider_) - { + if (!provider_) { return false; } tasks_ = &get_plugin_manager()->create_task_group(*this); @@ -682,8 +642,7 @@ class lifetime_consumer_impl final : public ark::module_base -{ +class lifetime_provider_plugin final : public ark::plugin_base { public: void install() override { REQUIRE(register_module( @@ -699,8 +658,7 @@ class lifetime_provider_plugin final : public ark::plugin_base -{ +class lifetime_consumer_plugin final : public ark::plugin_base { public: void install() override { REQUIRE(register_module( @@ -719,8 +677,7 @@ class lifetime_consumer_plugin final : public ark::plugin_base create_child(ark::guid_t parent, ark::id_type config_id) { auto result = kernel.create_container_entity(parent, ark::entity_meta_player::items_index(), "item", config_id); - if (result) - { + if (result) { contained_.push_back(result->get_id()); } return result; @@ -150,15 +144,12 @@ ark::protobuf::protobuf_entity_data entity_data(configured_world& world, const s return data; } -struct creation_observer -{ +struct creation_observer { int on_class_event(const ark::guid_t& id, const std::string&, ark::entity_event event, const ark::data_list&) { if (event >= ark::entity_event::entity_evt_pre_load_data && - event <= ark::entity_event::entity_evt_data_finished) - { + event <= ark::entity_event::entity_evt_data_finished) { events.push_back(event); - if (event == ark::entity_event::entity_evt_pre_load_data) - { + if (event == ark::entity_event::entity_evt_pre_load_data) { snapshot_saved = kernel->entity_node_to_protobuf_data(kernel->get_entity(id), &pre_load_data); } } @@ -404,8 +395,7 @@ TEST_CASE("public entity custom uint32 updates preserve the full unsigned range" REQUIRE(object->add_custom_u_int32("sequence", 0)); CHECK(object->get_custom_u_int32("sequence") == 0); for (const auto value : - {std::numeric_limits::max(), std::uint32_t{0x80000000}, std::uint32_t{1}, std::uint32_t{0}}) - { + {std::numeric_limits::max(), std::uint32_t{0x80000000}, std::uint32_t{1}, std::uint32_t{0}}) { REQUIRE(object->set_custom_u_int32("sequence", value)); CHECK(object->get_custom_u_int32("sequence") == value); CHECK(object->find_custom_data("sequence")); @@ -413,8 +403,7 @@ TEST_CASE("public entity custom uint32 updates preserve the full unsigned range" } TEST_CASE("public entity uint64 setters preserve values and report only actual changes") { - struct uint64_observer - { + struct uint64_observer { int changed( const ark::guid_t&, const std::string&, std::uint32_t, const ark::data& before, const ark::data& after) { CHECK(before.get_type() == ark::data_type::dt_uint64); @@ -471,8 +460,7 @@ TEST_CASE("public entity custom uint32 rejects other scalar types without changi REQUIRE(object->add_custom_float("float", 1.25F)); REQUIRE(object->add_custom_double("double", 2.5)); REQUIRE(object->add_custom_string("string", "preserved")); - for (const auto* name : {"boolean", "signed32", "signed64", "float", "double", "string"}) - { + for (const auto* name : {"boolean", "signed32", "signed64", "float", "double", "string"}) { CHECK_FALSE(object->set_custom_u_int32(name, 0)); CHECK_FALSE(object->set_custom_u_int32(name, std::numeric_limits::max())); } diff --git a/tests/core/entity_custom_hooks.hpp b/tests/core/entity_custom_hooks.hpp index 7e4a9f00f..d4a24eab8 100644 --- a/tests/core/entity_custom_hooks.hpp +++ b/tests/core/entity_custom_hooks.hpp @@ -7,8 +7,7 @@ void record_delete_hook(const void* value) noexcept; template void delete_value(value_type*& value) { - if (value != nullptr) - { + if (value != nullptr) { record_delete_hook(value); delete value; value = nullptr; @@ -22,7 +21,6 @@ void delete_value(value_type*& value) { // A supported custom allocator can throw while constructing a string value. #define ARK_NEW_ARRAY_RET(element_type, size) \ - do \ - { \ + do { \ return new element_type[(size)]; \ } while (false) diff --git a/tests/core/entity_custom_ownership.cpp b/tests/core/entity_custom_ownership.cpp index 97c069983..2ba63c5fa 100644 --- a/tests/core/entity_custom_ownership.cpp +++ b/tests/core/entity_custom_ownership.cpp @@ -20,10 +20,8 @@ bool observe{}, return_null{}, fail_after_candidate{}; bool fail_next_heap{}; void record_release(void* value) noexcept { - for (auto& entry : live) - { - if (value != nullptr && entry == value) - { + for (auto& entry : live) { + if (value != nullptr && entry == value) { entry = nullptr; ++releases; break; @@ -32,8 +30,7 @@ void record_release(void* value) noexcept { } void reset() { - for (auto* entry : live) - { + for (auto* entry : live) { REQUIRE(entry == nullptr); } allocations = releases = hook_deletes = injected_failures = 0; @@ -41,8 +38,7 @@ void reset() { } void release_unpublished() { - for (auto* entry : live) - { + for (auto* entry : live) { // Recover a baseline leak after recording the failing ownership checks. delete static_cast(entry); } @@ -65,14 +61,12 @@ std::shared_ptr schema() { } // namespace void* operator new(std::size_t size) { - if (fail_next_heap) - { + if (fail_next_heap) { fail_next_heap = false; ++injected_failures; throw std::bad_alloc{}; } - if (auto* value = std::malloc(size ? size : 1)) - { + if (auto* value = std::malloc(size ? size : 1)) { return value; } throw std::bad_alloc{}; @@ -100,23 +94,20 @@ void operator delete[](void* value, std::size_t) noexcept { } void* operator new(std::size_t size, const std::nothrow_t&) noexcept { - if (observe && return_null) - { + if (observe && return_null) { return_null = false; ++injected_failures; return nullptr; } void* value{}; - try - { value = ::operator new(size); } - catch (...) - { return nullptr; } - if (observe) - { - for (auto& entry : live) - { - if (entry == nullptr) - { + try { + value = ::operator new(size); + } catch (...) { + return nullptr; + } + if (observe) { + for (auto& entry : live) { + if (entry == nullptr) { entry = value; ++allocations; fail_next_heap = fail_after_candidate; @@ -133,10 +124,8 @@ void operator delete(void* value, const std::nothrow_t&) noexcept { } void entity_custom_test::record_delete_hook(const void* value) noexcept { - for (const auto* entry : live) - { - if (entry == value) - { + for (const auto* entry : live) { + if (entry == value) { ++hook_deletes; return; } @@ -144,8 +133,7 @@ void entity_custom_test::record_delete_hook(const void* value) noexcept { } TEST_CASE("Entity custom scalar insertion exceptions release unpublished candidates through the delete hook") { - for (std::size_t index = 0; index < adders.size(); ++index) - { + for (std::size_t index = 0; index < adders.size(); ++index) { CAPTURE(index); reset(); ark::entity_impl object(schema(), 1, 0, 1, 0, ark::data_list_impl{}); @@ -184,8 +172,7 @@ TEST_CASE("Entity custom string value allocation exceptions release the unpublis } TEST_CASE("Entity custom candidates preserve null duplicate and successful owning map behavior") { - for (const auto add : adders) - { + for (const auto add : adders) { reset(); { ark::entity_impl object(schema(), 1, 0, 1, 0, ark::data_list_impl{}); diff --git a/tests/core/entity_json_loading.cpp b/tests/core/entity_json_loading.cpp index e871a9da6..3995fc422 100644 --- a/tests/core/entity_json_loading.cpp +++ b/tests/core/entity_json_loading.cpp @@ -37,8 +37,7 @@ std::string schema() { {"class":"Item","rows":[{"id":2,"count":7}]}]})"; } -class resource_files -{ +class resource_files { public: resource_files() : previous_(std::filesystem::current_path()) @@ -70,8 +69,7 @@ class resource_files std::filesystem::path previous_, directory_; }; -class guid_sequence final : public ark::guid_module -{ +class guid_sequence final : public ark::guid_module { public: ark::guid_t create_guid() override { return next_++; @@ -85,14 +83,12 @@ class guid_sequence final : public ark::guid_module ark::guid_t next_{1000}; }; -class json_world -{ +class json_world { public: explicit json_world(bool replace_after_metadata = false, bool omit_player = false, ark::guid_t owner = 42) { ark::logger::init(&logger_); logger_.set_log_func([](spdlog::level::level_enum, const std::string&) {}); - if (owner != 42) - { + if (owner != 42) { auto text = schema(); const std::string original = "\"owner\":\"42\""; const auto position = text.find(original); @@ -100,8 +96,7 @@ class json_world text.replace(position, original.size(), "\"owner\":\"" + std::to_string(owner) + "\""); files_.write("entity_schema.json", text); } - if (omit_player) - { + if (omit_player) { auto document = ark::entity_json::parse(schema()); document.classes.erase(document.classes.begin()); files_.write("entity_schema.json", ark::entity_json::serialize(document)); @@ -115,8 +110,7 @@ class json_world REQUIRE(kernel.init()); REQUIRE(config.init()); REQUIRE(metadata.init()); - if (replace_after_metadata) - { + if (replace_after_metadata) { files_.write("entity_schema.json", "{"); } REQUIRE(config.post_init()); @@ -157,8 +151,7 @@ class json_world } // namespace TEST_CASE("scalar snapshots capture configured GUID boundaries without narrowing or retaining the entity") { - for (const auto guid : {std::numeric_limits::min(), std::numeric_limits::max()}) - { + for (const auto guid : {std::numeric_limits::min(), std::numeric_limits::max()}) { json_world world(false, false, guid); auto source = world.create(10); REQUIRE(source != nullptr); @@ -175,8 +168,7 @@ TEST_CASE("scalar snapshots capture configured GUID boundaries without narrowing } TEST_CASE("public entity GUID setters preserve tagged callback values through name and index") { - struct guid_observer - { + struct guid_observer { int changed( const ark::guid_t&, const std::string&, std::uint32_t, const ark::data& before, const ark::data& after) { CHECK(before.get_type() == ark::data_type::dt_guid); @@ -297,17 +289,13 @@ TEST_CASE("Malformed selected Kernel JSON fails startup instead of silently load ark::logger::init(&logger); logger.set_log_func([](spdlog::level::level_enum, const std::string&) {}); for (const auto& contents : - {std::string("{"), std::string(R"({"format":"wrong","version":1,"classes":[],"configs":[]})")}) - { + {std::string("{"), std::string(R"({"format":"wrong","version":1,"classes":[],"configs":[]})")}) { files.write("entity_schema.json", contents); ark::class_meta_module_impl metadata; - try - { + try { static_cast(metadata.init()); FAIL("selected invalid JSON did not fail startup"); - } - catch (const ark::entity_json::error& error) - { + } catch (const ark::entity_json::error& error) { CHECK(error.source().find("resource") != std::string::npos); CHECK(std::string(error.what()).find("entity_schema.json") != std::string::npos); } @@ -325,13 +313,10 @@ TEST_CASE("Missing Kernel JSON rejects manager startup even beside valid legacy ark::class_meta_module_impl metadata; metadata.set_plugin_manager(&manager); REQUIRE(manager.add_module(GET_CLASS_NAME(ark::class_meta_module), &metadata)); - try - { + try { static_cast(manager.start(0, {}, {}, {})); FAIL("missing required JSON accepted legacy XML"); - } - catch (const ark::entity_json::error& error) - { + } catch (const ark::entity_json::error& error) { CHECK(error.source() == "resource/meta/entity_schema.json"); CHECK(error.pointer() == "/"); CHECK(std::string(error.what()).find("could not open JSON input") != std::string::npos); diff --git a/tests/core/entity_nested_snapshot.cpp b/tests/core/entity_nested_snapshot.cpp index 964bed262..9e3d504cd 100644 --- a/tests/core/entity_nested_snapshot.cpp +++ b/tests/core/entity_nested_snapshot.cpp @@ -19,14 +19,12 @@ namespace { using namespace ark::entity_sync; -class nested_world -{ +class nested_world { public: nested_world() { root_schema->create_data_meta("amount", 1)->set_type(ark::data_type::dt_int32); root_schema->create_data_meta("secret", 2)->set_type(ark::data_type::dt_string); - for (const auto& schema : {row_schema, item_schema}) - { + for (const auto& schema : {row_schema, item_schema}) { schema->create_data_meta("amount", 1)->set_type(ark::data_type::dt_uint32); schema->create_data_meta("label", 2)->set_type(ark::data_type::dt_string); } @@ -40,12 +38,10 @@ class nested_world ~nested_world() { // Existing parent relationships are strong references. Detach even // deliberately malformed/cyclic test graphs before releasing the world. - for (const auto& entity : entities) - { + for (const auto& entity : entities) { const auto bag = entity->find_container(201); bag->remove(0u); - while (const auto slot = bag->first()) - { + while (const auto slot = bag->first()) { bag->remove(slot); } } @@ -75,31 +71,23 @@ class nested_world std::size_t string_bytes(const nested_entity_snapshot& state) { std::size_t total = state.scalars.class_name.size(); - for (const auto& [index, value] : state.scalars.fields) - { - if (const auto text = std::get_if(&value)) - { + for (const auto& [index, value] : state.scalars.fields) { + if (const auto text = std::get_if(&value)) { total += text->size(); } } - for (const auto& [index, table] : state.tables) - { + for (const auto& [index, table] : state.tables) { total += table.class_name.size(); - for (const auto& [number, row] : table.rows) - { - for (const auto& [column, value] : row.fields) - { - if (const auto text = std::get_if(&value)) - { + for (const auto& [number, row] : table.rows) { + for (const auto& [column, value] : row.fields) { + if (const auto text = std::get_if(&value)) { total += text->size(); } } } } - for (const auto& [index, container] : state.containers) - { - for (const auto& [slot, child] : container) - { + for (const auto& [index, container] : state.containers) { + for (const auto& [slot, child] : container) { total += string_bytes(child); } } @@ -113,8 +101,7 @@ TEST_CASE("Nested owning capture preserves row keys and distinct lifetimes acros const auto selection = world.selection(); auto* table = world.root->find_table(200); REQUIRE(table != nullptr); - for (const auto number : {1u, 2u, 3u}) - { + for (const auto number : {1u, 2u, 3u}) { REQUIRE(table->add_row(number) != nullptr); } const auto original = world.capture(selection); @@ -146,8 +133,7 @@ TEST_CASE("Nested capture reflects committed row state when add delete or clear REQUIRE(world.root_schema->get_class_call_back_manager()->add_table_call_back( 200, [&](const ark::guid_t&, const ark::table_event_data& event, const ark::data&, const ark::data&) { - if (event.op_type == fail_operation) - { + if (event.op_type == fail_operation) { throw std::runtime_error("table callback"); } return 0; @@ -324,8 +310,7 @@ TEST_CASE("Nested capture bounds aggregate state and leaves the previous value i auto selection = world.selection(); selection.root.fields = {1, 2}; REQUIRE(world.root->set_string(2, "root-text")); - for (const auto number : {1u, 2u}) - { + for (const auto number : {1u, 2u}) { const auto row = world.root->find_table(200)->add_row(number); REQUIRE(row->set_string(2, "row-text")); } diff --git a/tests/core/entity_nested_stream.cpp b/tests/core/entity_nested_stream.cpp index a332b2c56..bd92978c2 100644 --- a/tests/core/entity_nested_stream.cpp +++ b/tests/core/entity_nested_stream.cpp @@ -398,8 +398,7 @@ TEST_CASE("Nested owning copies preserve every scalar alternative across baselin {4, std::int64_t{-4}}, {5, std::uint64_t{5}}, {6, 1.25f}, {7, 2.5}, {8, std::string(256, 's')}, {9, guid_value{99}}}; trusted.root.fields.clear(); - for (const auto& [index, value] : baseline.snapshot.root.scalars.fields) - { + for (const auto& [index, value] : baseline.snapshot.root.scalars.fields) { trusted.root.fields.emplace(index, static_cast(value.index())); } nested_publisher publisher(trusted, baseline); @@ -413,8 +412,7 @@ TEST_CASE("Nested owning copies preserve every scalar alternative across baselin const auto packet = publisher.update(next); REQUIRE(packet != nullptr); REQUIRE(replica.apply(*packet) == nested_apply_result::applied); - for (const auto& [index, value] : expected.root.scalars.fields) - { + for (const auto& [index, value] : expected.root.scalars.fields) { CHECK(replica.state()->root.scalars.fields.at(index).index() == value.index()); CHECK(replica.state()->root.scalars.fields.at(index) == value); } diff --git a/tests/core/entity_nested_stream_allocation.cpp b/tests/core/entity_nested_stream_allocation.cpp index 60e459148..d484ebf65 100644 --- a/tests/core/entity_nested_stream_allocation.cpp +++ b/tests/core/entity_nested_stream_allocation.cpp @@ -14,12 +14,10 @@ const char* phase = "setup"; } // namespace void* operator new(std::size_t size) { - if (armed && ++allocation_count == fail_at) - { + if (armed && ++allocation_count == fail_at) { throw std::bad_alloc{}; } - if (void* memory = std::malloc(size ? size : 1)) - { + if (void* memory = std::malloc(size ? size : 1)) { return memory; } throw std::bad_alloc{}; @@ -44,24 +42,21 @@ TEST_CASE("Every nested publisher allocation failure preserves its state revisio source.root.containers.at(201).clear(); source.root.containers.at(202).emplace(7, structural); const auto unchanged_source = source; - for (std::size_t position = 1; position < 2048 && !completed; ++position) - { + for (std::size_t position = 1; position < 2048 && !completed; ++position) { nested_publisher publisher(nested_test::binding(), nested_test::initial()); const auto before = publisher.baseline(); allocation_count = 0; fail_at = position; armed = true; bool failed = false; - try - { + try { const auto packet = publisher.update(source); completed = packet != nullptr; + } catch (const std::bad_alloc&) { + failed = true; } - catch (const std::bad_alloc&) - { failed = true; } armed = false; - if (failed) - { + if (failed) { CHECK(publisher.baseline() == before); CHECK(source == unchanged_source); const auto retry = publisher.update(source); @@ -84,8 +79,7 @@ TEST_CASE("Every nested replica allocation failure preserves its committed state source.root.containers.at(201).clear(); source.root.containers.at(202).emplace(7, structural); const auto packet = publisher.update(source); - for (std::size_t position = 1; position < 2048 && !completed; ++position) - { + for (std::size_t position = 1; position < 2048 && !completed; ++position) { nested_replica replica(nested_test::binding()); REQUIRE(replica.apply(nested_test::initial()) == nested_apply_result::applied); const auto before = replica.state(); @@ -93,13 +87,13 @@ TEST_CASE("Every nested replica allocation failure preserves its committed state fail_at = position; armed = true; bool failed = false; - try - { completed = replica.apply(*packet) == nested_apply_result::applied; } - catch (const std::bad_alloc&) - { failed = true; } + try { + completed = replica.apply(*packet) == nested_apply_result::applied; + } catch (const std::bad_alloc&) { + failed = true; + } armed = false; - if (failed) - { + if (failed) { CHECK(replica.valid()); CHECK(replica.state() == before); CHECK(replica.revision() == 1); @@ -117,20 +111,19 @@ TEST_CASE("Every first nested baseline allocation failure preserves an uninstall stream_test::allocation_diagnostic diagnostic(phase, fail_at, allocation_count); bool completed = false; const auto baseline = nested_test::initial(); - for (std::size_t position = 1; position < 2048 && !completed; ++position) - { + for (std::size_t position = 1; position < 2048 && !completed; ++position) { nested_replica replica(nested_test::binding()); allocation_count = 0; fail_at = position; armed = true; bool failed = false; - try - { completed = replica.apply(baseline) == nested_apply_result::applied; } - catch (const std::bad_alloc&) - { failed = true; } + try { + completed = replica.apply(baseline) == nested_apply_result::applied; + } catch (const std::bad_alloc&) { + failed = true; + } armed = false; - if (failed) - { + if (failed) { CHECK_FALSE(replica.valid()); CHECK(replica.state() == nullptr); CHECK(replica.revision() == 0); @@ -145,21 +138,20 @@ TEST_CASE("Every nested tombstone allocation failure leaves publisher active at phase = "nested-tombstone"; stream_test::allocation_diagnostic diagnostic(phase, fail_at, allocation_count); bool completed = false; - for (std::size_t position = 1; position < 2048 && !completed; ++position) - { + for (std::size_t position = 1; position < 2048 && !completed; ++position) { nested_publisher publisher(nested_test::binding(), nested_test::initial()); const auto before = publisher.baseline(); allocation_count = 0; fail_at = position; armed = true; bool failed = false; - try - { completed = publisher.remove() != nullptr; } - catch (const std::bad_alloc&) - { failed = true; } + try { + completed = publisher.remove() != nullptr; + } catch (const std::bad_alloc&) { + failed = true; + } armed = false; - if (failed) - { + if (failed) { CHECK(publisher.baseline() == before); const auto packet = publisher.remove(); REQUIRE(packet != nullptr); @@ -179,25 +171,22 @@ TEST_CASE("A nested string patch copy fails without publishing a partial variant const std::map sentinel{{99, true}}; bool completed = false; std::size_t failures{}; - for (std::size_t position = 1; position < 16 && !completed; ++position) - { + for (std::size_t position = 1; position < 16 && !completed; ++position) { auto output = sentinel; nested_detail::patch_budget budget(nested_stream_limits{}); allocation_count = 0; fail_at = position; armed = true; bool failed = false; - try - { + try { nested_detail::patch_fields(before, next, output, budget); completed = true; + } catch (const std::bad_alloc&) { + failed = true; } - catch (const std::bad_alloc&) - { failed = true; } armed = false; CHECK(next == unchanged); - if (failed) - { + if (failed) { ++failures; CHECK(output == sentinel); nested_detail::patch_budget retry_budget(nested_stream_limits{}); @@ -220,24 +209,21 @@ TEST_CASE("Every nested publisher construction allocation failure preserves the baseline.snapshot.root.containers.at(201).at(1).tables.at(200).rows.at(1).fields.at(2) = std::string(80, 'c'); const auto unchanged = baseline.snapshot; bool completed = false; - for (std::size_t position = 1; position < 2048 && !completed; ++position) - { + for (std::size_t position = 1; position < 2048 && !completed; ++position) { allocation_count = 0; fail_at = position; armed = true; bool failed = false; - try - { + try { nested_publisher publisher(trusted, baseline); completed = publisher.baseline() != nullptr; + } catch (const std::bad_alloc&) { + failed = true; } - catch (const std::bad_alloc&) - { failed = true; } armed = false; CHECK(baseline.snapshot == unchanged); CHECK(baseline.revision == 1); - if (failed) - { + if (failed) { nested_publisher retry(trusted, baseline); CHECK(retry.baseline()->snapshot == unchanged); CHECK(retry.baseline()->revision == 1); diff --git a/tests/core/entity_scalar_stream_allocation.cpp b/tests/core/entity_scalar_stream_allocation.cpp index 90eeb65c8..b41e57777 100644 --- a/tests/core/entity_scalar_stream_allocation.cpp +++ b/tests/core/entity_scalar_stream_allocation.cpp @@ -18,8 +18,7 @@ bool armed{}; const char* phase = "setup"; std::size_t allocation_count{}, failure_position{}; -class allocation_failure final -{ +class allocation_failure final { public: allocation_failure(std::size_t position, const char* operation) { phase = operation; @@ -56,12 +55,10 @@ scalar_snapshot changed(const scalar_baseline& source) { } // namespace void* operator new(std::size_t size) { - if (armed && ++allocation_count == failure_position) - { + if (armed && ++allocation_count == failure_position) { throw std::bad_alloc{}; } - if (void* result = std::malloc(size ? size : 1)) - { + if (void* result = std::malloc(size ? size : 1)) { return result; } throw std::bad_alloc{}; @@ -78,33 +75,27 @@ void operator delete(void* pointer, std::size_t) noexcept { TEST_CASE("Scalar publisher construction and baseline copies preserve their source at every failed allocation") { const auto source = initial(); const auto untouched = source.snapshot; - for (const bool construct : {true, false}) - { + for (const bool construct : {true, false}) { bool completed = false; std::size_t failures{}; scalar_publisher original(source); - for (std::size_t position = 1; position < 256 && !completed; ++position) - { + for (std::size_t position = 1; position < 256 && !completed; ++position) { std::optional publisher; std::optional baseline; bool failed = false; { allocation_failure failure( position, construct ? "scalar-publisher-construction" : "scalar-baseline-return"); - try - { - if (construct) - { + try { + if (construct) { publisher.emplace(source); - } - else - { + } else { baseline.emplace(detail::direct_value{[&] { return original.baseline(); }}); } completed = true; + } catch (const std::bad_alloc&) { + failed = true; } - catch (const std::bad_alloc&) - { failed = true; } } failures += failed; CHECK(source.snapshot == untouched); @@ -112,8 +103,7 @@ TEST_CASE("Scalar publisher construction and baseline copies preserve their sour CHECK(retained.snapshot == untouched); CHECK(retained.generation == 7); CHECK(retained.revision == 1); - if (completed) - { + if (completed) { CHECK((construct ? publisher->baseline().snapshot : baseline->snapshot) == untouched); } } @@ -128,22 +118,21 @@ TEST_CASE("Scalar publisher allocation failure preserves revision and permits on const auto untouched = next; bool completed = false; std::size_t failures{}; - for (std::size_t position = 1; position < 256 && !completed; ++position) - { + for (std::size_t position = 1; position < 256 && !completed; ++position) { scalar_publisher publisher(source); bool failed = false; std::shared_ptr packet; { allocation_failure failure(position, "scalar-publisher-update"); - try - { packet = publisher.update(next); } - catch (const std::bad_alloc&) - { failed = true; } + try { + packet = publisher.update(next); + } catch (const std::bad_alloc&) { + failed = true; + } } failures += failed; CHECK(next == untouched); - if (failed) - { + if (failed) { const auto before = publisher.baseline(); CHECK(before.snapshot == source.snapshot); CHECK(before.revision == 1); @@ -166,15 +155,12 @@ TEST_CASE("Scalar baseline allocation failures retain first-install and prior-ge auto replacement = source; replacement.generation = 8; replacement.snapshot = changed(source); - for (const bool installed : {false, true}) - { + for (const bool installed : {false, true}) { bool completed = false; std::size_t failures{}; - for (std::size_t position = 1; position < 256 && !completed; ++position) - { + for (std::size_t position = 1; position < 256 && !completed; ++position) { scalar_replica replica(source.schema_id, 17, "Player"); - if (installed) - { + if (installed) { REQUIRE(replica.apply(source) == scalar_apply_result::applied); } const auto retained = replica.state(); @@ -183,27 +169,25 @@ TEST_CASE("Scalar baseline allocation failures retain first-install and prior-ge { allocation_failure failure( position, installed ? "scalar-new-generation-baseline" : "scalar-first-baseline"); - try - { completed = replica.apply(incoming) == scalar_apply_result::applied; } - catch (const std::bad_alloc&) - { failed = true; } + try { + completed = replica.apply(incoming) == scalar_apply_result::applied; + } catch (const std::bad_alloc&) { + failed = true; + } } failures += failed; - if (failed) - { + if (failed) { CHECK(replica.state() == retained); CHECK(replica.valid() == installed); CHECK(replica.revision() == (installed ? 1 : 0)); - if (installed) - { + if (installed) { CHECK(replica.apply(source) == scalar_apply_result::duplicate); } REQUIRE(replica.apply(incoming) == scalar_apply_result::applied); } CHECK(*replica.state() == incoming.snapshot); CHECK(replica.apply(incoming) == scalar_apply_result::duplicate); - if (retained) - { + if (retained) { CHECK(*retained == source.snapshot); } } @@ -220,22 +204,21 @@ TEST_CASE("Scalar delta allocation failures preserve committed state and exactly REQUIRE(packet); bool completed = false; std::size_t failures{}; - for (std::size_t position = 1; position < 256 && !completed; ++position) - { + for (std::size_t position = 1; position < 256 && !completed; ++position) { scalar_replica replica(source.schema_id, 17, "Player"); REQUIRE(replica.apply(source) == scalar_apply_result::applied); const auto retained = replica.state(); bool failed = false; { allocation_failure failure(position, "scalar-replica-delta"); - try - { completed = replica.apply(*packet) == scalar_apply_result::applied; } - catch (const std::bad_alloc&) - { failed = true; } + try { + completed = replica.apply(*packet) == scalar_apply_result::applied; + } catch (const std::bad_alloc&) { + failed = true; + } } failures += failed; - if (failed) - { + if (failed) { CHECK(replica.state() == retained); CHECK(replica.valid()); CHECK(replica.revision() == 1); diff --git a/tests/core/entity_snapshot.cpp b/tests/core/entity_snapshot.cpp index 4293f843d..ff7659cf2 100644 --- a/tests/core/entity_snapshot.cpp +++ b/tests/core/entity_snapshot.cpp @@ -31,16 +31,14 @@ scalar_snapshot capture_scalar_snapshot( constexpr std::array all_fields{1, 2, 3, 4, 5, 6, 7, 8, 9}; -class snapshot_entity -{ +class snapshot_entity { public: explicit snapshot_entity(std::string class_name = "SnapshotOwner") : schema(std::make_shared(class_name)) { const std::array types{ark::data_type::dt_boolean, ark::data_type::dt_int32, ark::data_type::dt_uint32, ark::data_type::dt_int64, ark::data_type::dt_uint64, ark::data_type::dt_float, ark::data_type::dt_double, ark::data_type::dt_string, ark::data_type::dt_guid}; - for (std::uint32_t index = 1; index <= types.size(); ++index) - { + for (std::uint32_t index = 1; index <= types.size(); ++index) { add_field(index, types[index - 1]); } source = std::make_shared( @@ -217,8 +215,7 @@ TEST_CASE("scalar snapshot rejects invalid selections and unsupported declared t ark::data_type::dt_array, ark::data_type::dt_table, ark::data_type::dt_pointer, ark::data_type::dt_userdata, static_cast(999)}; std::uint32_t index = 20; - for (const auto type : unsupported) - { + for (const auto type : unsupported) { fixture.add_field(index, type); const std::array selection{index++}; CHECK_THROWS_AS(capture_scalar_snapshot(*fixture.source, selection), std::invalid_argument); @@ -232,16 +229,14 @@ TEST_CASE("scalar snapshot rejects nonfinite selected floats while preserving so const std::array floats{6}; const std::array doubles{7}; for (const auto value : {std::numeric_limits::infinity(), -std::numeric_limits::infinity(), - std::numeric_limits::quiet_NaN()}) - { + std::numeric_limits::quiet_NaN()}) { static_cast(fixture.source->set_float(6, value)); CHECK_THROWS_AS(capture_scalar_snapshot(*fixture.source, floats), std::invalid_argument); const auto after = fixture.source->get_float(6); CHECK((std::isnan(value) ? std::isnan(after) : after == value)); } for (const auto value : {std::numeric_limits::infinity(), -std::numeric_limits::infinity(), - std::numeric_limits::quiet_NaN()}) - { + std::numeric_limits::quiet_NaN()}) { static_cast(fixture.source->set_double(7, value)); CHECK_THROWS_AS(capture_scalar_snapshot(*fixture.source, doubles), std::invalid_argument); const auto after = fixture.source->get_double(7); diff --git a/tests/core/entity_snapshot_interface.cpp b/tests/core/entity_snapshot_interface.cpp index 32b9f8f86..ff6de7007 100644 --- a/tests/core/entity_snapshot_interface.cpp +++ b/tests/core/entity_snapshot_interface.cpp @@ -13,8 +13,7 @@ using namespace ark; // An external source implementation of the original pure interface, without a // capture override. The newly added default must preserve its concreteness. -class legacy_snapshot_kernel : public ark::kernel_module -{ +class legacy_snapshot_kernel : public ark::kernel_module { public: bool do_event( const guid_t& self, const std::string& name, entity_event event, const data_list& value_list) override { @@ -156,8 +155,7 @@ class legacy_snapshot_kernel : public ark::kernel_module static_assert(!std::is_abstract_v); -class custom_snapshot_kernel final : public legacy_snapshot_kernel -{ +class custom_snapshot_kernel final : public legacy_snapshot_kernel { public: ark::entity_sync::scalar_snapshot capture_scalar_snapshot( const ark::entity&, std::span, const ark::entity_sync::snapshot_limits& = {}) override { diff --git a/tests/core/header_regressions.cpp b/tests/core/header_regressions.cpp index b321684c9..5ac2e5dcf 100644 --- a/tests/core/header_regressions.cpp +++ b/tests/core/header_regressions.cpp @@ -13,8 +13,7 @@ DOCTEST_TEST_CASE("128-bit GUID decimal strings round-trip the full unsigned ran constexpr auto maximum = (std::numeric_limits::max)(); const std::array, 6> components = { {{0, 0}, {0, maximum}, {maximum, 0}, {maximum, maximum}, {maximum / 2 + 1, 42}, {123, 456}}}; - for (const auto& [high, low] : components) - { + for (const auto& [high, low] : components) { const ark::guid_t128 original(high, low); ark::guid_t128 parsed(7, 9); DOCTEST_CAPTURE(original.to_string()); @@ -30,8 +29,7 @@ DOCTEST_TEST_CASE("128-bit GUID parsing rejects malformed and overflowing compon const std::array invalid = {"", "1", "1-", "-1", "a-1", "1-a", "1-2-3", " 1-2", "1- 2", "1-2 ", "+1-2", "1-+2", "1--2", "18446744073709551616-0", "0-18446744073709551616", std::string("1-2\0", 4), std::string("1\0-2", 4)}; - for (const auto& input : invalid) - { + for (const auto& input : invalid) { ark::guid_t128 parsed(7, 9); DOCTEST_CAPTURE(input); DOCTEST_CHECK_FALSE(parsed.from_string(input)); diff --git a/tests/core/headers/plugin_base.cpp b/tests/core/headers/plugin_base.cpp index 5e5ebf9b5..68b28ad86 100644 --- a/tests/core/headers/plugin_base.cpp +++ b/tests/core/headers/plugin_base.cpp @@ -1,8 +1,7 @@ // Copyright (c) 2026 OpenArkStudio. Licensed under Apache-2.0. See LICENSE. #include -class compile_plugin final : public ark::plugin_base -{ +class compile_plugin final : public ark::plugin_base { public: void install() override { } diff --git a/tests/core/kernel_callbacks.cpp b/tests/core/kernel_callbacks.cpp index bd7ab871c..c3af8d9ff 100644 --- a/tests/core/kernel_callbacks.cpp +++ b/tests/core/kernel_callbacks.cpp @@ -19,8 +19,7 @@ namespace { // Exercise registration against the real metadata/callback managers without // loading external metadata or installing process-wide sync callbacks. -class callback_metadata final : public ark::class_meta_module -{ +class callback_metadata final : public ark::class_meta_module { public: callback_metadata() { auto owner = std::make_shared("Owner"); @@ -66,8 +65,7 @@ class callback_metadata final : public ark::class_meta_module ark::class_meta_manager::class_meta_list classes, empty; }; -class callback_guid final : public ark::guid_module -{ +class callback_guid final : public ark::guid_module { public: ark::guid_t create_guid() override { return 100; @@ -78,8 +76,7 @@ class callback_guid final : public ark::guid_module } }; -class callback_world -{ +class callback_world { public: callback_world() { ark::logger::init(&logger_); @@ -115,8 +112,7 @@ class callback_world callback_guid guid_; }; -class callback_receiver -{ +class callback_receiver { public: callback_receiver() = default; callback_receiver(const callback_receiver&) = delete; @@ -137,8 +133,7 @@ class callback_receiver event_id = event; arguments = &args; ++calls; - if (throw_on_event) - { + if (throw_on_event) { throw std::runtime_error("receiver failure"); } return 17; @@ -151,8 +146,7 @@ class callback_receiver node_index = index; old_value = old_data.get_int(); new_value = new_data.get_int(); - if (order) - { + if (order) { order->push_back(tag); } ++calls; @@ -163,8 +157,7 @@ class callback_receiver const ark::data& new_data) { id = self; table_event = event; - if (event.op_type == static_cast(ark::table_op_type::table_update)) - { + if (event.op_type == static_cast(ark::table_op_type::table_update)) { old_value = old_data.get_int(); new_value = new_data.get_int(); } @@ -216,8 +209,7 @@ class callback_receiver bool throw_on_event{}; }; -class cloned_component final : public ark::component -{ +class cloned_component final : public ark::component { public: cloned_component() : component(0, "clone") { @@ -283,8 +275,7 @@ TEST_CASE("Kernel member adapters preserve scalar and table callback routing by ark::entity_impl entity(world.metadata.find_meta("Owner"), 77, 0, 1, 0, ark::data_list_impl{}); REQUIRE(entity.set_int32(10, 13)); REQUIRE(entity.set_int32(10, 21)); - for (const auto* receiver : {&by_name, &by_index}) - { + for (const auto* receiver : {&by_name, &by_index}) { CHECK(receiver->calls == 2); CHECK(receiver->id == 77); CHECK(receiver->node_name == "level"); @@ -299,8 +290,7 @@ TEST_CASE("Kernel member adapters preserve scalar and table callback routing by REQUIRE(row != nullptr); REQUIRE(row->set_int32(1, 4)); REQUIRE(row->set_int32(1, 9)); - for (const auto* receiver : {&by_name, &by_index}) - { + for (const auto* receiver : {&by_name, &by_index}) { CHECK(receiver->calls == 5); CHECK(receiver->id == 77); CHECK(receiver->table_event.table_index == 20); @@ -327,8 +317,7 @@ TEST_CASE("Kernel member adapters preserve class scene move and copied container const std::string name = "Owner"; ark::data_list_impl arguments; REQUIRE(callbacks->on_class_event(self, name, ark::entity_event::entity_evt_all_finished, arguments)); - for (const auto* receiver : {&class_receiver, &common_class}) - { + for (const auto* receiver : {&class_receiver, &common_class}) { CHECK(receiver->calls == 1); CHECK(receiver->id == self); CHECK(receiver->class_name == &name); @@ -349,8 +338,7 @@ TEST_CASE("Kernel member adapters preserve class scene move and copied container CHECK(move.old_position == &previous); CHECK(move.new_position == ¤t); REQUIRE(callbacks->on_container_call_back(self, 30, {}, ark::container_op_type::op_swap, 2, 4)); - for (const auto* receiver : {&container, &common_container}) - { + for (const auto* receiver : {&container, &common_container}) { CHECK(receiver->calls == 1); CHECK(receiver->id == self); CHECK(receiver->container_index == 30); diff --git a/tests/core/kernel_common_class_callbacks.cpp b/tests/core/kernel_common_class_callbacks.cpp index 63d718df6..1c6675a55 100644 --- a/tests/core/kernel_common_class_callbacks.cpp +++ b/tests/core/kernel_common_class_callbacks.cpp @@ -14,8 +14,7 @@ namespace { -class common_event_guid final : public ark::guid_module -{ +class common_event_guid final : public ark::guid_module { public: ark::guid_t create_guid() override { return 1; @@ -26,8 +25,7 @@ class common_event_guid final : public ark::guid_module } }; -class common_event_receiver -{ +class common_event_receiver { public: explicit common_event_receiver(std::vector& deliveries) : deliveries_(deliveries) { @@ -58,8 +56,7 @@ TEST_CASE("Kernel common class callbacks remain callable for every real metadata ark::logger::init(&logger); logger.set_log_func([](spdlog::level::level_enum, const std::string&) {}); - struct reset_logger - { + struct reset_logger { ~reset_logger() { ark::logger::set_instance(nullptr); } @@ -92,8 +89,7 @@ TEST_CASE("Kernel common class callbacks remain callable for every real metadata common_event_receiver receiver(deliveries); receiver.expected_arguments = &arguments; REQUIRE(kernel.add_common_class_event(&receiver, &common_event_receiver::on_class, -4)); - for (const auto* name : {"Player", "Item", "Player", "Item"}) - { + for (const auto* name : {"Player", "Item", "Player", "Item"}) { REQUIRE(kernel.do_event(77, name, ark::entity_event::entity_evt_all_finished, arguments)); } CHECK(deliveries == std::vector{"Player", "Item", "Player", "Item"}); diff --git a/tests/core/kernel_delayed_sync.cpp b/tests/core/kernel_delayed_sync.cpp index 9ae5f7c54..587c669e7 100644 --- a/tests/core/kernel_delayed_sync.cpp +++ b/tests/core/kernel_delayed_sync.cpp @@ -22,8 +22,7 @@ namespace ark { // Test-only access to the existing delivery callback. The actual serializer and // send_sync_msg path remain intact; this does not implement a transport. -class kernel_delayed_sync_test_access -{ +class kernel_delayed_sync_test_access { public: static auto& delivery_callbacks(kernel_module_impl& kernel) { return kernel.sync_functors_; @@ -34,8 +33,7 @@ class kernel_delayed_sync_test_access namespace { -class delayed_sync_files -{ +class delayed_sync_files { public: delayed_sync_files() : previous_(std::filesystem::current_path()) @@ -66,8 +64,7 @@ class delayed_sync_files std::filesystem::path previous_, directory_; }; -class sync_guid_sequence final : public ark::guid_module -{ +class sync_guid_sequence final : public ark::guid_module { public: ark::guid_t create_guid() override { return next_++; @@ -81,21 +78,18 @@ class sync_guid_sequence final : public ark::guid_module ark::guid_t next_{1000}; }; -struct delivery -{ +struct delivery { ark::data_mask mask; ark::guid_t target; ark::protobuf::protobuf_delay_entity message; }; -class delayed_sync_world -{ +class delayed_sync_world { public: delayed_sync_world() { ark::logger::init(&logger_); logger_.set_log_func([this](spdlog::level::level_enum level, const std::string& message) { - if (level >= spdlog::level::err) - { + if (level >= spdlog::level::err) { errors.push_back(message); } }); @@ -111,15 +105,13 @@ class delayed_sync_world REQUIRE(config_.post_init()); REQUIRE(kernel.post_init()); REQUIRE(maps_.create_map(1)); - for (const auto mask : {ark::data_mask::pf_sync_view, ark::data_mask::pf_sync_self}) - { + for (const auto mask : {ark::data_mask::pf_sync_view, ark::data_mask::pf_sync_self}) { ark::kernel_delayed_sync_test_access::delivery_callbacks( kernel)[mask] = [this, mask](const ark::guid_t& target, const google::protobuf::Message& message) { const auto* delayed = dynamic_cast(&message); REQUIRE(delayed != nullptr); deliveries.push_back({mask, target, *delayed}); - if (on_delivery) - { + if (on_delivery) { on_delivery(mask); } return true; @@ -133,10 +125,8 @@ class delayed_sync_world on_delivery = {}; // Retire pending raw-node batches before destroying their entities. kernel.update(); - for (const auto id : children_) - { - if (kernel.get_entity(id)) - { + for (const auto id : children_) { + if (kernel.get_entity(id)) { kernel.destroy_entity(id); } } @@ -158,13 +148,11 @@ class delayed_sync_world CHECK(deliveries.empty()); REQUIRE(kernel.update()); REQUIRE(deliveries.size() == count); - for (const auto& event : deliveries) - { + for (const auto& event : deliveries) { CHECK(event.target == owner->get_id()); CHECK(event.message.id() == owner->get_id()); } - if (count == 2) - { + if (count == 2) { CHECK(deliveries[0].mask == ark::data_mask::pf_sync_view); CHECK(deliveries[1].mask == ark::data_mask::pf_sync_self); } @@ -196,15 +184,13 @@ class delayed_sync_world } // namespace TEST_CASE("Kernel retirement cancels queued updates while preserving live entities and destroy events") { - struct destroy_observer - { + struct destroy_observer { std::vector events; std::shared_ptr owner; int on_event(const ark::guid_t& id, const std::string&, ark::entity_event event, const ark::data_list&) { - if (id == 10 && - (event == ark::entity_event::entity_evt_pre_destroy || event == ark::entity_event::entity_evt_destroy)) - { + if (id == 10 && (event == ark::entity_event::entity_evt_pre_destroy || + event == ark::entity_event::entity_evt_destroy)) { events.push_back(event); // Destruction callbacks may collect one final old-object change. REQUIRE(owner->set_u_int32(100, 80 + static_cast(events.size()))); @@ -231,8 +217,7 @@ TEST_CASE("Kernel retirement cancels queued updates while preserving live entiti REQUIRE(world.kernel.update()); CHECK(world.errors.empty()); REQUIRE(world.deliveries.size() == 2); - for (const auto& event : world.deliveries) - { + for (const auto& event : world.deliveries) { CHECK(event.target == 20); CHECK(event.message.data().datas_uint32().at(100) == 29); } @@ -250,14 +235,12 @@ TEST_CASE("Kernel retirement during delivery skips later masks of the active ent recreate = true; } world.on_delivery = [&](ark::data_mask) { - if (retired) - { + if (retired) { return; } retired = true; REQUIRE(world.kernel.destroy_entity(10)); - if (recreate) - { + if (recreate) { world.owner = world.kernel.create_entity(10, 1, 0, "Owner", 0, ark::data_list_impl{}); REQUIRE(world.owner != nullptr); REQUIRE(world.owner != old_owner); @@ -272,16 +255,12 @@ TEST_CASE("Kernel retirement during delivery skips later masks of the active ent CHECK(world.deliveries.front().message.data().datas_uint32().at(100) == 7); world.on_delivery = {}; world.deliveries.clear(); - if (recreate) - { + if (recreate) { world.flush(); - for (const auto& event : world.deliveries) - { + for (const auto& event : world.deliveries) { CHECK(event.message.data().datas_uint32().at(100) == 99); } - } - else - { + } else { REQUIRE(world.kernel.update()); CHECK(world.deliveries.empty()); } @@ -300,8 +279,7 @@ TEST_CASE("Kernel retirement during delivery removes another queued lifetime wit const std::weak_ptr retired_lifetime = victim; bool retired = false; world.on_delivery = [&](ark::data_mask) { - if (!retired) - { + if (!retired) { retired = true; REQUIRE(world.kernel.destroy_entity(20)); victim.reset(); @@ -312,8 +290,7 @@ TEST_CASE("Kernel retirement during delivery removes another queued lifetime wit CHECK(world.errors.empty()); REQUIRE(world.deliveries.size() == 4); std::map counts; - for (const auto& event : world.deliveries) - { + for (const auto& event : world.deliveries) { ++counts[event.target]; CHECK(event.message.data().datas_uint32().at(100) == (event.target == 10 ? 7 : 27)); } @@ -330,8 +307,7 @@ TEST_CASE("Kernel delayed container-only changes reach existing mask delivery ca REQUIRE(child->set_u_int32(1, 7)); const auto slot = bag->find(child->get_id()); world.flush(); - for (const auto& event : world.deliveries) - { + for (const auto& event : world.deliveries) { const auto& payload = event.message.data().datas_container().at(201).datas_value().at(slot); CHECK(payload.id() == child->get_id()); CHECK(payload.data().datas_uint32().at(1) == 7); @@ -344,8 +320,7 @@ TEST_CASE("Kernel delayed container-only changes reach existing mask delivery ca const auto child = world.create_child(); const auto slot = bag->find(child->get_id()); world.flush(); - for (const auto& event : world.deliveries) - { + for (const auto& event : world.deliveries) { CHECK(event.message.container_entity().at(201).entity_list().at(slot) == child->get_id()); CHECK(event.message.data().datas_container().empty()); } @@ -358,8 +333,7 @@ TEST_CASE("Kernel delayed container-only changes reach existing mask delivery ca world.deliveries.clear(); REQUIRE(bag->remove(slot)); world.flush(); - for (const auto& event : world.deliveries) - { + for (const auto& event : world.deliveries) { CHECK(event.message.container_entity().at(201).entity_list().at(slot) == ark::null_guid); CHECK(event.message.destroy_entity().at(201).entity_list().empty()); } @@ -373,8 +347,7 @@ TEST_CASE("Kernel delayed container-only changes reach existing mask delivery ca child->update_sent(); REQUIRE(bag->destroy(slot)); world.flush(); - for (const auto& event : world.deliveries) - { + for (const auto& event : world.deliveries) { CHECK(event.message.container_entity().at(201).entity_list().at(slot) == ark::null_guid); CHECK(event.message.destroy_entity().at(201).entity_list().at(slot) == ark::null_guid); } @@ -409,31 +382,25 @@ TEST_CASE("Kernel delayed scalar table mixed and empty controls retain existing scalar = table = container = true; } - if (scalar) - { + if (scalar) { REQUIRE(world.owner->set_u_int32(100, 9)); } - if (table) - { + if (table) { const auto inventory = world.owner->find_table(200); REQUIRE(inventory != nullptr); inventory->clear(); } - if (container) - { + if (container) { world.create_child(); } world.flush(scalar || table || container ? 2 : 0); - for (const auto& event : world.deliveries) - { + for (const auto& event : world.deliveries) { CHECK(event.message.data().datas_uint32().count(100) == (scalar ? 1 : 0)); - if (scalar) - { + if (scalar) { CHECK(event.message.data().datas_uint32().at(100) == 9); } CHECK(event.message.clear_tables_size() == (table ? 1 : 0)); - if (table) - { + if (table) { CHECK(event.message.clear_tables(0) == 200); } CHECK(event.message.data().datas_container().count(201) == (container ? 1 : 0)); @@ -445,8 +412,7 @@ TEST_CASE("Kernel delayed callback mutations remain pending until the next flush world.create_child(); bool changed = false; world.on_delivery = [&](ark::data_mask) { - if (changed) - { + if (changed) { return; } changed = true; @@ -459,8 +425,7 @@ TEST_CASE("Kernel delayed callback mutations remain pending until the next flush world.flush(); CHECK(changed); - for (const auto& event : world.deliveries) - { + for (const auto& event : world.deliveries) { CHECK(event.message.data().datas_container().count(201) == 1); CHECK(event.message.data().datas_container().count(202) == 0); CHECK(event.message.data().datas_uint32().empty()); @@ -469,8 +434,7 @@ TEST_CASE("Kernel delayed callback mutations remain pending until the next flush world.on_delivery = {}; world.deliveries.clear(); world.flush(); - for (const auto& event : world.deliveries) - { + for (const auto& event : world.deliveries) { CHECK(event.message.data().datas_uint32().at(100) == 42); REQUIRE(event.message.clear_tables_size() == 1); CHECK(event.message.clear_tables(0) == 200); @@ -488,8 +452,7 @@ TEST_CASE("Kernel rejects recursive delayed flushes and retains their new change world.create_child(); bool attempted = false; world.on_delivery = [&](ark::data_mask) { - if (attempted) - { + if (attempted) { return; } attempted = true; @@ -504,8 +467,7 @@ TEST_CASE("Kernel rejects recursive delayed flushes and retains their new change world.on_delivery = {}; world.deliveries.clear(); world.flush(); - for (const auto& event : world.deliveries) - { + for (const auto& event : world.deliveries) { CHECK(event.message.data().datas_uint32().at(100) == 27); } } @@ -522,8 +484,7 @@ TEST_CASE("Kernel delayed flush guard resets after callback exceptions") { world.on_delivery = {}; world.deliveries.clear(); world.flush(); - for (const auto& event : world.deliveries) - { + for (const auto& event : world.deliveries) { CHECK(event.message.data().datas_uint32().at(100) == 63); CHECK(event.message.data().datas_container().empty()); } @@ -536,8 +497,7 @@ TEST_CASE("Kernel container swaps preserve child ownership parent bindings and c using operation = ark::container_op_type; using record = std::tuple; - struct observer - { + struct observer { std::vector events; int on_event(const ark::guid_t&, std::uint32_t container, operation op, std::uint32_t from, std::uint32_t to) { @@ -557,8 +517,7 @@ TEST_CASE("Kernel container swaps preserve child ownership parent bindings and c const auto first_slot = source->find(first->get_id()); REQUIRE(first_slot == 1); const std::weak_ptr first_lifetime = first; - for (const auto index : {201u, 202u}) - { + for (const auto index : {201u, 202u}) { REQUIRE(static_cast(world.kernel) .add_container_call_back("Owner", index, &observed, &observer::on_event, 100)); } @@ -689,8 +648,7 @@ TEST_CASE("Real Kernel captures converge through trusted nested streams across r } nested_replica replay(trusted); REQUIRE(replay.apply(*retained) == nested_apply_result::applied); - for (const auto& packet : packets) - { + for (const auto& packet : packets) { REQUIRE(replay.apply(*packet) == nested_apply_result::applied); } CHECK(*replay.state() == final_state); diff --git a/tests/core/kernel_metadata_files.hpp b/tests/core/kernel_metadata_files.hpp index 4d467f5c2..565ac44e1 100644 --- a/tests/core/kernel_metadata_files.hpp +++ b/tests/core/kernel_metadata_files.hpp @@ -8,8 +8,7 @@ namespace ark::test { -class metadata_files -{ +class metadata_files { public: metadata_files() : previous_(std::filesystem::current_path()) diff --git a/tests/core/kernel_snapshot_test_access.hpp b/tests/core/kernel_snapshot_test_access.hpp index 0bedf107b..b84cd86bb 100644 --- a/tests/core/kernel_snapshot_test_access.hpp +++ b/tests/core/kernel_snapshot_test_access.hpp @@ -5,8 +5,7 @@ namespace ark { -class kernel_nested_snapshot_test_access -{ +class kernel_nested_snapshot_test_access { public: static std::uint64_t row_counter(const table_impl& table) { return table.last_incarnation_; diff --git a/tests/core/logging_paths.cpp b/tests/core/logging_paths.cpp index ee880ac11..c3782ec43 100644 --- a/tests/core/logging_paths.cpp +++ b/tests/core/logging_paths.cpp @@ -52,8 +52,7 @@ std::filesystem::path native_path(const spdlog::filename_t& filename) { #endif } -struct filename_case -{ +struct filename_case { spdlog::filename_t input; spdlog::filename_t directory; spdlog::filename_t basename; @@ -85,8 +84,7 @@ spdlog::filename_t expected_filename(const filename_case& entry, const std::tm& return native_filename(std::filesystem::path(entry.directory) / day / name); } -class log_directory -{ +class log_directory { public: const std::filesystem::path directory = std::filesystem::temp_directory_path() / @@ -102,8 +100,7 @@ class log_directory } }; -class temporary_current_directory -{ +class temporary_current_directory { public: explicit temporary_current_directory(const std::filesystem::path& directory) : previous_(std::filesystem::current_path()) { @@ -119,8 +116,7 @@ class temporary_current_directory std::filesystem::path previous_; }; -class logger_registration -{ +class logger_registration { public: explicit logger_registration(std::string name) : name_(std::move(name)) { @@ -147,8 +143,7 @@ std::string read_log(const spdlog::filename_t& file) { } // namespace TEST_CASE("Logging path splitting keeps directories separate from basenames and extensions") { - for (const auto& entry : filename_cases) - { + for (const auto& entry : filename_cases) { const auto [directory, basename, extension] = filename_calculator::split_by_dir_and_extenstion(entry.input); CHECK(directory == entry.directory); CHECK(basename == entry.basename); @@ -164,8 +159,7 @@ TEST_CASE("Logging path splitting keeps directories separate from basenames and } TEST_CASE("Logging filename calculation preserves relative paths without creating directories") { - for (const auto& entry : filename_cases) - { + for (const auto& entry : filename_cases) { const auto before = spdlog::details::os::localtime(); const auto actual = filename_calculator::calc_filename(entry.input); const auto after = spdlog::details::os::localtime(); @@ -326,8 +320,7 @@ TEST_CASE("owned asynchronous logging drains its queue when the wrapper is relea { ark::logger logger; REQUIRE(logger.init_logger(settings, "drain.log")); - for (int i = 0; i < 32; ++i) - { + for (int i = 0; i < 32; ++i) { logger.log_t(ark::detail::log_source_location(), spdlog::level::info, "async marker {}", i); } } @@ -358,8 +351,7 @@ TEST_CASE("Logging callback reset restores configured output formatting and leve settings.output_path = output_directory.string(); ark::logger logger; #ifdef ARK_LOGGING_CONFIG_TESTS - if (route == "toml") - { + if (route == "toml") { const auto config = files.directory / "logging.app.toml"; { std::ofstream output(config); @@ -419,8 +411,7 @@ TEST_CASE("Logging UTF-8 output directories and filenames create native files wi settings.pattern = "%v"; settings.queue_count = route == "async" ? 8 : 0; #ifdef ARK_LOGGING_CONFIG_TESTS - if (route == "toml") - { + if (route == "toml") { const auto config = files.directory / "logging.app.toml"; const auto path = directory.generic_u8string(); const std::string configured_output_path(reinterpret_cast(path.data()), path.size()); @@ -462,8 +453,7 @@ TEST_CASE("Logging native UTF-8 file sinks preserve append truncation and bounde SUBCASE("hourly append and truncate") { const auto output = native_path(filename_calculator::calc_filename(filename)); std::string expected; - for (const bool truncate : {false, false, true}) - { + for (const bool truncate : {false, false, true}) { { auto sink = std::make_shared(filename, truncate); spdlog::logger logger("native-hourly", sink); @@ -471,8 +461,7 @@ TEST_CASE("Logging native UTF-8 file sinks preserve append truncation and bounde logger.info("{}", payload); logger.flush(); } - if (truncate) - { + if (truncate) { expected.clear(); } expected += payload + eol; @@ -486,8 +475,7 @@ TEST_CASE("Logging native UTF-8 file sinks preserve append truncation and bounde auto sink = std::make_shared(filename, payload.size() + 1 + eol.size(), 2); spdlog::logger logger("native-size", sink); logger.set_pattern("%v"); - for (int i = 0; i < 4; ++i) - { + for (int i = 0; i < 4; ++i) { logger.info("{}{}", payload, i); } logger.flush(); diff --git a/tests/core/logging_source.cpp b/tests/core/logging_source.cpp index d60b9cbfb..bef68e4d3 100644 --- a/tests/core/logging_source.cpp +++ b/tests/core/logging_source.cpp @@ -17,8 +17,7 @@ static_assert(std::string_view(SPDLOG_FILE_BASENAME("")) == "external-basename") namespace { -class captured_logger -{ +class captured_logger { public: std::vector> messages; @@ -61,8 +60,7 @@ TEST_CASE("Logging macros capture caller file and line at every level") { spdlog::level::info, spdlog::level::warn, spdlog::level::err, spdlog::level::critical}; constexpr std::array contents = {"trace", "debug 1", "info", "warn 2", "error", "critical 3"}; REQUIRE(capture.messages.size() == levels.size()); - for (std::size_t index = 0; index < levels.size(); ++index) - { + for (std::size_t index = 0; index < levels.size(); ++index) { CHECK(capture.messages[index].first == levels[index]); CHECK(capture.messages[index].second == "[logging_source.cpp:" + std::to_string(lines[index]) + "]" + contents[index]); diff --git a/tests/core/lru_map_failure.cpp b/tests/core/lru_map_failure.cpp index e21f5116c..07b8ac656 100644 --- a/tests/core/lru_map_failure.cpp +++ b/tests/core/lru_map_failure.cpp @@ -18,8 +18,7 @@ int failure_limit{-1}; int allocation_count{}; const char* phase{"setup"}; -class allocation_diagnostic final -{ +class allocation_diagnostic final { public: allocation_diagnostic() : previous_handler_(std::set_terminate(terminate)) { @@ -36,8 +35,7 @@ class allocation_diagnostic final std::fprintf(stderr, "LRU allocation terminate: phase=%s fail_after=%d allocation_count=%d deferred=%d\n", phase, failure_limit, allocation_count, deferred_allocations_before_failure); std::fflush(stderr); - if (active_ && active_->previous_handler_) - { + if (active_ && active_->previous_handler_) { active_->previous_handler_(); } std::_Exit(EXIT_FAILURE); @@ -47,8 +45,7 @@ class allocation_diagnostic final inline static allocation_diagnostic* active_{}; }; -struct allocation_key -{ +struct allocation_key { int value{}; allocation_key(int value) @@ -58,8 +55,7 @@ struct allocation_key bool operator==(const allocation_key&) const = default; }; -struct allocating_value -{ +struct allocating_value { std::shared_ptr owner; std::unique_ptr payload; @@ -79,15 +75,13 @@ struct allocating_value } // namespace template<> -struct std::hash -{ +struct std::hash { std::size_t operator()(const allocation_key& key) const noexcept { // Copying first constructs empty standard containers. MSVC Debug's // _Hash_vec allocator constructor allocates its proxy inside noexcept. // Arm at the first source lookup, before any entry is allocated, so every // content allocation is covered without claiming that proxy OOM unwinds. - if (deferred_allocations_before_failure >= 0) - { + if (deferred_allocations_before_failure >= 0) { allocations_before_failure = deferred_allocations_before_failure; deferred_allocations_before_failure = -1; } @@ -96,21 +90,17 @@ struct std::hash }; void* operator new(std::size_t size) { - if (allocations_before_failure >= 0) - { + if (allocations_before_failure >= 0) { ++allocation_count; } - if (allocations_before_failure == 0) - { + if (allocations_before_failure == 0) { allocations_before_failure = -1; throw std::bad_alloc{}; } - if (allocations_before_failure > 0) - { + if (allocations_before_failure > 0) { --allocations_before_failure; } - if (auto* result = std::malloc(size ? size : 1)) - { + if (auto* result = std::malloc(size ? size : 1)) { return result; } throw std::bad_alloc{}; @@ -128,8 +118,7 @@ TEST_CASE("LRU allocation failure rolls back insertion and releases candidate va allocation_diagnostic diagnostic; bool saw_failure{}; bool saw_success{}; - for (int limit = 0; limit < 64; ++limit) - { + for (int limit = 0; limit < 64; ++limit) { ark::lru_map> values(2); values.insert(1, std::make_shared(10)); values.insert(2, std::make_shared(20)); @@ -139,14 +128,14 @@ TEST_CASE("LRU allocation failure rolls back insertion and releases candidate va failure_limit = limit; allocation_count = 0; allocations_before_failure = limit; - try - { values.insert(3, candidate); } - catch (const std::bad_alloc&) - { caught = true; } + try { + values.insert(3, candidate); + } catch (const std::bad_alloc&) { + caught = true; + } allocations_before_failure = -1; REQUIRE(values.size() == 2); - if (caught) - { + if (caught) { saw_failure = true; CHECK(allocation_count == limit + 1); CHECK(candidate.use_count() == 1); @@ -156,9 +145,7 @@ TEST_CASE("LRU allocation failure rolls back insertion and releases candidate va REQUIRE(values.find(2) != values.end()); values.erase(2); CHECK(values.size() == 1); - } - else - { + } else { saw_success = true; CHECK(allocation_count == limit); CHECK(candidate.use_count() == 2); @@ -175,8 +162,7 @@ TEST_CASE("LRU allocation failure during copy assignment retains both caches and allocation_diagnostic diagnostic; bool saw_failure{}; bool saw_success{}; - for (int limit = 0; limit < 64; ++limit) - { + for (int limit = 0; limit < 64; ++limit) { const auto source_owner = std::make_shared(10); ark::lru_map source(2); source.insert(1, source_owner); @@ -189,15 +175,15 @@ TEST_CASE("LRU allocation failure during copy assignment retains both caches and failure_limit = limit; allocation_count = 0; deferred_allocations_before_failure = limit; - try - { destination = source; } - catch (const std::bad_alloc&) - { caught = true; } + try { + destination = source; + } catch (const std::bad_alloc&) { + caught = true; + } allocations_before_failure = -1; REQUIRE(deferred_allocations_before_failure == -1); REQUIRE(source.size() == 2); - if (caught) - { + if (caught) { saw_failure = true; CHECK(allocation_count == limit + 1); REQUIRE(destination.size() == 1); @@ -212,9 +198,7 @@ TEST_CASE("LRU allocation failure during copy assignment retains both caches and source.insert(3, std::make_shared(30)); CHECK(source.find(1) == source.end()); CHECK(source.size() == 2); - } - else - { + } else { saw_success = true; CHECK(allocation_count == limit); CHECK(destination_owner.use_count() == 1); @@ -236,8 +220,7 @@ TEST_CASE("LRU allocation failure during copy construction releases partial copi allocation_diagnostic diagnostic; bool saw_failure{}; bool saw_success{}; - for (int limit = 0; limit < 64; ++limit) - { + for (int limit = 0; limit < 64; ++limit) { const auto source_owner = std::make_shared(10); ark::lru_map source(2); source.insert(1, source_owner); @@ -248,15 +231,15 @@ TEST_CASE("LRU allocation failure during copy construction releases partial copi failure_limit = limit; allocation_count = 0; deferred_allocations_before_failure = limit; - try - { copied.emplace(source); } - catch (const std::bad_alloc&) - { caught = true; } + try { + copied.emplace(source); + } catch (const std::bad_alloc&) { + caught = true; + } allocations_before_failure = -1; REQUIRE(deferred_allocations_before_failure == -1); REQUIRE(source.size() == 2); - if (caught) - { + if (caught) { saw_failure = true; CHECK(allocation_count == limit + 1); CHECK_FALSE(copied.has_value()); @@ -264,9 +247,7 @@ TEST_CASE("LRU allocation failure during copy construction releases partial copi source.insert(3, std::make_shared(30)); CHECK(source.find(1) == source.end()); CHECK(source.size() == 2); - } - else - { + } else { saw_success = true; CHECK(allocation_count == limit); REQUIRE(copied.has_value()); diff --git a/tests/core/lru_maps.cpp b/tests/core/lru_maps.cpp index 815cf8116..e4d6097b7 100644 --- a/tests/core/lru_maps.cpp +++ b/tests/core/lru_maps.cpp @@ -9,8 +9,7 @@ namespace { -struct checked_key -{ +struct checked_key { int value{}; static inline int copies_before_failure{-1}; @@ -20,12 +19,10 @@ struct checked_key checked_key(const checked_key& other) : value(other.value) { - if (copies_before_failure == 0) - { + if (copies_before_failure == 0) { throw std::runtime_error("key copy failed"); } - if (copies_before_failure > 0) - { + if (copies_before_failure > 0) { --copies_before_failure; } } @@ -38,8 +35,7 @@ struct checked_key } // namespace template<> -struct std::hash -{ +struct std::hash { std::size_t operator()(const checked_key& key) const noexcept { return std::hash{}(key.value); } @@ -89,21 +85,20 @@ TEST_CASE("LRU copy assignment replaces entries and preserves independent evicti TEST_CASE("LRU failed insertion preserves recency and can be followed by lookup erase and eviction") { bool saw_failure{}; bool saw_success{}; - for (int limit = 0; limit < 12; ++limit) - { + for (int limit = 0; limit < 12; ++limit) { ark::lru_map values(2); values.insert(checked_key{1}, 10); values.insert(checked_key{2}, 20); const checked_key candidate{3}; checked_key::copies_before_failure = limit; bool caught{}; - try - { values.insert(candidate, 30); } - catch (const std::runtime_error&) - { caught = true; } + try { + values.insert(candidate, 30); + } catch (const std::runtime_error&) { + caught = true; + } checked_key::copies_before_failure = -1; - if (caught) - { + if (caught) { saw_failure = true; REQUIRE(values.size() == 2); CHECK(values.find(candidate) == values.end()); @@ -112,9 +107,7 @@ TEST_CASE("LRU failed insertion preserves recency and can be followed by lookup REQUIRE(values.find(checked_key{2}) != values.end()); values.erase(checked_key{2}); CHECK(values.size() == 1); - } - else - { + } else { saw_success = true; REQUIRE(values.size() == 2); CHECK(values.find(checked_key{1}) == values.end()); @@ -130,8 +123,7 @@ TEST_CASE("LRU failed insertion preserves recency and can be followed by lookup TEST_CASE("LRU key copy failure during assignment retains both caches and their eviction order") { bool saw_failure{}; bool saw_success{}; - for (int limit = 0; limit < 12; ++limit) - { + for (int limit = 0; limit < 12; ++limit) { const auto source_owner = std::make_shared(10); ark::lru_map> source(2); source.insert(checked_key{1}, source_owner); @@ -142,14 +134,14 @@ TEST_CASE("LRU key copy failure during assignment retains both caches and their destination.insert(checked_key{9}, destination_owner); bool caught{}; checked_key::copies_before_failure = limit; - try - { destination = source; } - catch (const std::runtime_error&) - { caught = true; } + try { + destination = source; + } catch (const std::runtime_error&) { + caught = true; + } checked_key::copies_before_failure = -1; REQUIRE(source.size() == 2); - if (caught) - { + if (caught) { saw_failure = true; REQUIRE(destination.size() == 1); REQUIRE(destination.find(checked_key{9}) != destination.end()); @@ -162,9 +154,7 @@ TEST_CASE("LRU key copy failure during assignment retains both caches and their source.insert(checked_key{3}, std::make_shared(30)); CHECK(source.find(checked_key{2}) == source.end()); REQUIRE(source.find(checked_key{1}) != source.end()); - } - else - { + } else { saw_success = true; CHECK(destination_owner.use_count() == 1); CHECK(source_owner.use_count() == 3); diff --git a/tests/core/module_dependencies.cpp b/tests/core/module_dependencies.cpp index 9933a0825..738e44e00 100644 --- a/tests/core/module_dependencies.cpp +++ b/tests/core/module_dependencies.cpp @@ -15,8 +15,7 @@ namespace { constexpr std::array dependency_phases{"init", "post_init", "check_config", "pre_update"}; -class dependency_module final : public ark::module -{ +class dependency_module final : public ark::module { public: dependency_module(std::string name, std::vector dependencies, std::vector& events) : name(std::move(name)) @@ -25,8 +24,7 @@ class dependency_module final : public ark::module } std::vector get_dependencies() const override { - if (metadata_throws) - { + if (metadata_throws) { throw std::runtime_error("dependency metadata failed"); } return dependencies; @@ -58,10 +56,8 @@ class dependency_module final : public ark::module private: bool record(int phase) { events.emplace_back(std::string(dependency_phases[phase]) + ":" + name); - if (phase == failed_phase) - { - if (throws) - { + if (phase == failed_phase) { + if (throws) { throw std::runtime_error("ordered startup failed"); } return false; @@ -76,24 +72,20 @@ bool start_dependencies(ark::plugin_manager& manager) { std::vector phase_events(const std::vector& order) { std::vector events; - for (const auto* phase : dependency_phases) - { - for (const auto& name : order) - { + for (const auto* phase : dependency_phases) { + for (const auto& name : order) { events.emplace_back(std::string(phase) + ":" + name); } } return events; } -class dependency_provider : public ark::module -{ +class dependency_provider : public ark::module { public: bool initialized{}; }; -class dependency_provider_impl final : public ark::module_base -{ +class dependency_provider_impl final : public ark::module_base { public: bool init() override { initialized = true; @@ -101,12 +93,9 @@ class dependency_provider_impl final : public ark::module_base -{ +class dependency_consumer_impl final : public ark::module_base { public: bool init() override { return find_module()->initialized; @@ -143,8 +132,7 @@ TEST_CASE("Module dependencies reject missing providers before any startup hook" } TEST_CASE("Module dependencies reject self and indirect cycles before independent modules start") { - for (const bool self : {false, true}) - { + for (const bool self : {false, true}) { ark::plugin_manager manager; std::vector events; dependency_module first("first", {self ? "first" : "second"}, events); @@ -160,8 +148,7 @@ TEST_CASE("Module dependencies reject self and indirect cycles before independen } TEST_CASE("Module dependencies order transitive diamond providers once in every startup phase") { - for (const bool reverse : {false, true}) - { + for (const bool reverse : {false, true}) { ark::plugin_manager manager; std::vector events; dependency_module root("root", {}, events); @@ -169,12 +156,10 @@ TEST_CASE("Module dependencies order transitive diamond providers once in every dependency_module right("right", {"root", "root"}, events); dependency_module sink("sink", {"right", "left"}, events); std::array modules{&root, &left, &right, &sink}; - if (reverse) - { + if (reverse) { std::reverse(modules.begin(), modules.end()); } - for (auto* module : modules) - { + for (auto* module : modules) { REQUIRE(manager.add_module(module->name, module)); } REQUIRE(start_dependencies(manager)); @@ -184,20 +169,17 @@ TEST_CASE("Module dependencies order transitive diamond providers once in every } TEST_CASE("Module dependencies use stable registration-key order for independent ready nodes") { - for (const bool reverse : {false, true}) - { + for (const bool reverse : {false, true}) { ark::plugin_manager manager; std::vector events; dependency_module first("alpha", {}, events); dependency_module second("middle", {}, events); dependency_module third("omega", {}, events); std::array modules{&first, &second, &third}; - if (reverse) - { + if (reverse) { std::reverse(modules.begin(), modules.end()); } - for (auto* module : modules) - { + for (auto* module : modules) { REQUIRE(manager.add_module(module->name, module)); } REQUIRE(start_dependencies(manager)); @@ -206,10 +188,8 @@ TEST_CASE("Module dependencies use stable registration-key order for independent } TEST_CASE("Module dependencies stop ordered startup at its first false or exception") { - for (int phase = 0; phase < static_cast(dependency_phases.size()); ++phase) - { - for (const bool throws : {false, true}) - { + for (int phase = 0; phase < static_cast(dependency_phases.size()); ++phase) { + for (const bool throws : {false, true}) { ark::plugin_manager manager; std::vector events; dependency_module provider("provider", {}, events); @@ -217,16 +197,12 @@ TEST_CASE("Module dependencies stop ordered startup at its first false or except dependency_module later("later", {"failing"}, events); failing.failed_phase = phase; failing.throws = throws; - for (auto* module : {&later, &failing, &provider}) - { + for (auto* module : {&later, &failing, &provider}) { REQUIRE(manager.add_module(module->name, module)); } - if (throws) - { + if (throws) { CHECK_THROWS_WITH_AS(start_dependencies(manager), "ordered startup failed", std::runtime_error); - } - else - { + } else { CHECK_FALSE(start_dependencies(manager)); } auto expected = phase_events({"provider", "failing", "later"}); diff --git a/tests/core/module_factory.cpp b/tests/core/module_factory.cpp index 3b3a9e50e..8cff1cf6d 100644 --- a/tests/core/module_factory.cpp +++ b/tests/core/module_factory.cpp @@ -5,8 +5,7 @@ namespace construction_test { namespace { -class service_impl final : public ark::module_base -{ +class service_impl final : public ark::module_base { public: explicit service_impl(counts& events) : events_(events) { diff --git a/tests/core/module_factory.hpp b/tests/core/module_factory.hpp index 21f112a79..1b5893cc9 100644 --- a/tests/core/module_factory.hpp +++ b/tests/core/module_factory.hpp @@ -7,14 +7,12 @@ namespace construction_test { -struct counts -{ +struct counts { unsigned destroyed{}; unsigned updates{}; }; -class service : public ark::module -{ +class service : public ark::module { public: virtual service* lookup_self() = 0; }; diff --git a/tests/core/module_initialization.cpp b/tests/core/module_initialization.cpp index 09f3b5268..6c93dbe0a 100644 --- a/tests/core/module_initialization.cpp +++ b/tests/core/module_initialization.cpp @@ -16,8 +16,7 @@ namespace { -class unused_guid_module final : public ark::guid_module -{ +class unused_guid_module final : public ark::guid_module { public: ark::guid_t create_guid() override { return {}; @@ -28,8 +27,7 @@ class unused_guid_module final : public ark::guid_module } }; -class startup_observer final : public ark::module -{ +class startup_observer final : public ark::module { public: bool init() override { ++init_calls; @@ -65,13 +63,10 @@ void verify_initialization_order(bool config_init_first, bool config_post_init_f register_module.operator()(&guid); REQUIRE(map.init()); - if (config_init_first) - { + if (config_init_first) { REQUIRE(config.init()); REQUIRE(kernel.init()); - } - else - { + } else { REQUIRE(kernel.init()); REQUIRE(config.init()); } @@ -82,13 +77,10 @@ void verify_initialization_order(bool config_init_first, bool config_post_init_f REQUIRE(metadata.find_meta("Player") != nullptr); REQUIRE(metadata.find_static_meta("attribute") != nullptr); - if (config_post_init_first) - { + if (config_post_init_first) { REQUIRE(config.post_init()); REQUIRE(kernel.post_init()); - } - else - { + } else { REQUIRE(kernel.post_init()); REQUIRE(config.post_init()); } @@ -127,8 +119,7 @@ TEST_CASE("kernel and config initialize before schema regardless of consumer ord TEST_CASE("Kernel rejects missing declared providers before actual modules initialize") { for (const auto* missing : - {typeid(ark::class_meta_module).name(), typeid(ark::config_module).name(), typeid(ark::guid_module).name()}) - { + {typeid(ark::class_meta_module).name(), typeid(ark::config_module).name(), typeid(ark::guid_module).name()}) { CAPTURE(missing); ark::plugin_manager manager; ark::class_meta_module_impl metadata; @@ -141,8 +132,7 @@ TEST_CASE("Kernel rejects missing declared providers before actual modules initi // proves graph validation precedes even otherwise runnable modules. REQUIRE(manager.add_module("!startup-observer", &observer)); const auto add = [&](interface_type* implementation) { - if (std::string(missing) != typeid(interface_type).name()) - { + if (std::string(missing) != typeid(interface_type).name()) { implementation->set_plugin_manager(&manager); REQUIRE(manager.add_module(typeid(interface_type).name(), implementation)); } @@ -195,8 +185,7 @@ TEST_CASE("Kernel manager startup loads real metadata and configuration with rev } TEST_CASE("sync callback registration replaces the prior owner for every singleton mask handler") { - struct observations - { + struct observations { unsigned nodes{}, tables{}, containers{}, delayed{}; }; diff --git a/tests/core/msg_dependencies.cpp b/tests/core/msg_dependencies.cpp index a22ad84c4..b084b7d19 100644 --- a/tests/core/msg_dependencies.cpp +++ b/tests/core/msg_dependencies.cpp @@ -14,8 +14,7 @@ namespace { template -class observed_provider : public ark::module_base -{ +class observed_provider : public ark::module_base { public: std::vector get_dependencies() const override { return dependencies; @@ -42,8 +41,7 @@ class observed_provider : public ark::module_base } bool pre_shut() override { - if (dependent_stopped) - { + if (dependent_stopped) { CHECK(*dependent_stopped); } phases.emplace_back("pre_shut"); @@ -55,8 +53,7 @@ class observed_provider : public ark::module_base const bool* dependent_stopped{}; }; -class bus_provider final : public observed_provider -{ +class bus_provider final : public observed_provider { public: const std::string get_app_whole_name(ark::bus_id_t) override { return {}; @@ -115,8 +112,7 @@ class bus_provider final : public observed_provider ark::reg_center registry_; }; -class net_provider final : public observed_provider -{ +class net_provider final : public observed_provider { public: bool create_server(std::size_t, const ark::msg_header&, const ark::msg_header&) override { return false; @@ -163,8 +159,7 @@ class net_provider final : public observed_provider messages{ark::detail::make_msg_module()}; }; -class message_dependent final : public ark::module_base -{ +class message_dependent final : public ark::module_base { public: explicit message_dependent(fixture& state) : state_(state) { @@ -234,8 +228,7 @@ TEST_CASE("Message production factory declares its retained Bus and Net provider } TEST_CASE("Message missing providers fail manager validation before any startup hook") { - for (const bool missing_bus : {true, false}) - { + for (const bool missing_bus : {true, false}) { CAPTURE(missing_bus); fixture state; const std::string missing = @@ -253,8 +246,7 @@ TEST_CASE("Message missing providers fail manager validation before any startup } TEST_CASE("Message provider cycles fail validation before any startup hook") { - for (const bool cycle_via_bus : {true, false}) - { + for (const bool cycle_via_bus : {true, false}) { CAPTURE(cycle_via_bus); fixture state; auto& dependencies = cycle_via_bus ? state.bus.dependencies : state.network.dependencies; @@ -269,8 +261,7 @@ TEST_CASE("Message provider cycles fail validation before any startup hook") { TEST_CASE("Message graph orders provider startup and reverses admission stop") { // The production send-failure path writes through the host logger. - struct logger_scope - { + struct logger_scope { logger_scope() { current.set_log_func([](auto, const auto&) {}); ark::logger::init(¤t); diff --git a/tests/core/murmur_hash.cpp b/tests/core/murmur_hash.cpp index a0beb95c9..bb297c527 100644 --- a/tests/core/murmur_hash.cpp +++ b/tests/core/murmur_hash.cpp @@ -37,8 +37,7 @@ std::uint32_t verification_value(hash_function hash) { std::array key{}; std::array hashes{}; std::array result{}; - for (int length = 0; length < 256; ++length) - { + for (int length = 0; length < 256; ++length) { key[length] = static_cast(length); hash(key.data(), length, 256 - length, hashes.data() + length * output_size); } @@ -50,10 +49,8 @@ std::uint32_t verification_value(hash_function hash) { template std::array little_words(const std::array& bytes) { std::array words{}; - for (std::size_t word = 0; word < word_count; ++word) - { - for (std::size_t byte = 0; byte < sizeof(word_type); ++byte) - { + for (std::size_t word = 0; word < word_count; ++word) { + for (std::size_t byte = 0; byte < sizeof(word_type); ++byte) { words[word] |= static_cast(bytes[word * sizeof(word_type) + byte]) << (byte * 8); } } @@ -63,24 +60,19 @@ std::array little_words(const std::array void check_byte_buffers(hash_function hash) { alignas(8) std::array key{}; - for (std::size_t index = 0; index < key.size(); ++index) - { + for (std::size_t index = 0; index < key.size(); ++index) { key[index] = static_cast(index * 37 + 0x80); } // Cover every tail path and both sides of several full-block boundaries. - for (int length = 0; length <= 257; ++length) - { + for (int length = 0; length <= 257; ++length) { if (length > 65 && length != 127 && length != 128 && length != 129 && length != 255 && length != 256 && - length != 257) - { + length != 257) { continue; } - for (const auto seed : {0u, 1u, 0x80000000u, 0xffffffffu}) - { + for (const auto seed : {0u, 1u, 0x80000000u, 0xffffffffu}) { alignas(8) std::array expected{}; hash(key.data(), length, seed, expected.data()); - for (std::size_t offset = 0; offset < 8; ++offset) - { + for (std::size_t offset = 0; offset < 8; ++offset) { CAPTURE(length); CAPTURE(seed); CAPTURE(offset); @@ -120,13 +112,11 @@ TEST_CASE("Murmur3 retains upstream verification values and the legacy swapped-b TEST_CASE("Murmur3 rotations preserve full-width seeds and multi-block golden words") { std::array key{}; - for (std::size_t index = 0; index < key.size(); ++index) - { + for (std::size_t index = 0; index < key.size(); ++index) { key[index] = static_cast(index); } - struct golden_case - { + struct golden_case { int length; std::uint32_t seed; std::uint32_t x86_32; @@ -152,18 +142,14 @@ TEST_CASE("Murmur3 rotations preserve full-width seeds and multi-block golden wo {33, 0xffffffffu, 0x74b4bba8u, {0xc8d61452u, 0x878dd688u, 0xad51e4b6u, 0x5b85edf7u}, {0xcdcdff4c5a639071ull, 0x8332c8a91ba2cf3dull}}, }}; - for (std::size_t index = 0; index < little.size(); ++index) - { + for (std::size_t index = 0; index < little.size(); ++index) { CAPTURE(index); - if (index == 2) - { - for (std::size_t byte = 0; byte < key.size(); ++byte) - { + if (index == 2) { + for (std::size_t byte = 0; byte < key.size(); ++byte) { key[byte] = static_cast(byte * 37 + 0x80); } } - for (const bool legacy : {false, true}) - { + for (const bool legacy : {false, true}) { CAPTURE(legacy); const auto& expected = legacy ? swapped[index] : little[index]; std::array actual32{}; @@ -186,15 +172,13 @@ TEST_CASE("Murmur3 rotations preserve full-width seeds and multi-block golden wo TEST_CASE("Murmur2 retains seed-zero golden words around block boundaries") { std::array key{}; - for (std::size_t index = 0; index < key.size(); ++index) - { + for (std::size_t index = 0; index < key.size(); ++index) { key[index] = static_cast(index); } const std::array, 10> cases{ {{0, 0}, {1, 0xe94e6ebdu}, {3, 0xe2558031u}, {4, 0xa4985988u}, {15, 0x8184d621u}, {16, 0x5f3c0743u}, {17, 0xb1aad377u}, {31, 0x1d7d6ee1u}, {32, 0xf1bc6c23u}, {33, 0x915a6941u}}}; - for (const auto& [length, expected] : cases) - { + for (const auto& [length, expected] : cases) { CAPTURE(length); std::array result{}; ark::murmur_hash::murmur_hash2(key.data(), length, result.data()); @@ -207,8 +191,7 @@ TEST_CASE("Murmur3 default and legacy policies agree until a complete block is p 0x80, 0xff, 0x00, 0x01, 0xa5, 0x5a, 0x81, 0xfe, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09}; using hash_function = void (*)(const void*, int, std::uint32_t, void*); - struct policy_case - { + struct policy_case { hash_function standard; hash_function legacy; int block_size; @@ -219,12 +202,9 @@ TEST_CASE("Murmur3 default and legacy policies agree until a complete block is p {hash_x86_128, hash_x86_128_legacy, 16}, {ark::murmur_hash::murmur_hash3_x64_128, ark::murmur_hash::murmur_hash3_x64_128_legacy_msvc, 16}, }}; - for (const auto& policy : policies) - { - for (int length = 0; length < policy.block_size; ++length) - { - for (const auto seed : {0u, 0x80000000u, 0xffffffffu}) - { + for (const auto& policy : policies) { + for (int length = 0; length < policy.block_size; ++length) { + for (const auto seed : {0u, 0x80000000u, 0xffffffffu}) { CAPTURE(length); CAPTURE(seed); std::array standard{}; diff --git a/tests/core/native_loader/host.cpp b/tests/core/native_loader/host.cpp index 790093f81..0d38885e7 100644 --- a/tests/core/native_loader/host.cpp +++ b/tests/core/native_loader/host.cpp @@ -9,8 +9,7 @@ namespace { void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { std::cerr << message << '\n'; std::exit(1); } @@ -26,8 +25,7 @@ void verify_load(const std::string& directory) { const auto loaded = library.load(directory); #ifdef ARK_PLATFORM_WIN const auto error = GetLastError(); - if (!loaded) - { + if (!loaded) { std::cerr << "Native load failed: " << error << '\n'; } #endif diff --git a/tests/core/nested_wire.cpp b/tests/core/nested_wire.cpp index 6a120f5a2..1901d824e 100644 --- a/tests/core/nested_wire.cpp +++ b/tests/core/nested_wire.cpp @@ -202,8 +202,7 @@ TEST_CASE("Nested wire retains unknown-field compatibility within byte and recur message.GetReflection()->MutableUnknownFields(&message)->AddVarint(999, 1); CHECK(wire::decode(message, nested_test::binding()).snapshot == nested_test::initial().snapshot); auto* group = message.GetReflection()->MutableUnknownFields(&message)->AddGroup(998); - for (int depth = 0; depth < 10; ++depth) - { + for (int depth = 0; depth < 10; ++depth) { group = group->AddGroup(998); } wire::limits budget; diff --git a/tests/core/net_health_timer.cpp b/tests/core/net_health_timer.cpp index ad4465682..5fca07b9f 100644 --- a/tests/core/net_health_timer.cpp +++ b/tests/core/net_health_timer.cpp @@ -20,8 +20,7 @@ namespace { using namespace std::chrono_literals; template -class observed_provider : public ark::module_base -{ +class observed_provider : public ark::module_base { public: std::vector get_dependencies() const override { return dependencies; @@ -48,8 +47,7 @@ class observed_provider : public ark::module_base } bool pre_shut() override { - if (dependent_stopped) - { + if (dependent_stopped) { CHECK(*dependent_stopped); } phases.emplace_back("pre_shut"); @@ -61,8 +59,7 @@ class observed_provider : public ark::module_base const bool* dependent_stopped{}; }; -class bus_provider final : public observed_provider -{ +class bus_provider final : public observed_provider { public: const std::string get_app_whole_name(ark::bus_id_t) override { return {}; @@ -102,8 +99,7 @@ class bus_provider final : public observed_provider bool get_target_bus_relations(std::vector&) override { ++configuration_reads; - if (throw_before_registration) - { + if (throw_before_registration) { throw std::runtime_error("controlled Bus configuration failure"); } return true; @@ -126,16 +122,14 @@ class bus_provider final : public observed_provider ark::reg_center registry_; }; -struct registration -{ +struct registration { std::uint64_t id; std::uint32_t count; std::chrono::milliseconds interval; std::weak_ptr callback_lifetime; }; -class timer_provider final : public observed_provider -{ +class timer_provider final : public observed_provider { public: using ark::timer_module::add_forever_timer; @@ -167,8 +161,7 @@ class timer_provider final : public observed_provider std::uint64_t add_single_timer(const ark::guid_t& entity, std::chrono::milliseconds interval, std::uint32_t count, ark::timer_functor&& callback) override { ++attempts; - if (reject_registration) - { + if (reject_registration) { return 0; } auto lifetime = std::make_shared(1); @@ -193,8 +186,7 @@ class timer_provider final : public observed_provider ark::time_wheel_manager wheel_; }; -struct receiver -{ +struct receiver { void on_timer(std::uint64_t, const ark::guid_t&) { ++calls; } @@ -202,8 +194,7 @@ struct receiver unsigned calls{}; }; -struct fixture -{ +struct fixture { fixture() { REQUIRE(manager.add_module(typeid(ark::bus_module).name(), &bus)); REQUIRE(manager.add_module(typeid(ark::timer_module).name(), &timer)); @@ -217,8 +208,7 @@ struct fixture std::unique_ptr network{ark::detail::make_net_service_manager_module()}; }; -class net_dependent final : public ark::module_base -{ +class net_dependent final : public ark::module_base { public: explicit net_dependent(fixture& state) : state_(state) { @@ -275,8 +265,7 @@ TEST_CASE("Net declares its actual required Bus and Timer interfaces") { } TEST_CASE("Net missing providers fail real manager startup before module side effects") { - for (const bool missing_bus : {true, false}) - { + for (const bool missing_bus : {true, false}) { CAPTURE(missing_bus); fixture state; const std::string missing = missing_bus ? typeid(ark::bus_module).name() : typeid(ark::timer_module).name(); @@ -297,8 +286,7 @@ TEST_CASE("Net missing providers fail real manager startup before module side ef } TEST_CASE("Net required providers participate in cycle validation before initialization") { - for (const bool cycle_via_bus : {true, false}) - { + for (const bool cycle_via_bus : {true, false}) { CAPTURE(cycle_via_bus); fixture state; auto& dependencies = cycle_via_bus ? state.bus.dependencies : state.timer.dependencies; diff --git a/tests/core/node_copy_hooks.hpp b/tests/core/node_copy_hooks.hpp index 225e33a6a..1d7368320 100644 --- a/tests/core/node_copy_hooks.hpp +++ b/tests/core/node_copy_hooks.hpp @@ -6,9 +6,7 @@ namespace node_copy_hooks { -struct allocation_tag -{ -}; +struct allocation_tag {}; inline bool return_null{}; inline std::size_t allocations{}; @@ -16,8 +14,7 @@ inline std::size_t releases{}; template void release(T*& pointer) noexcept { - if (pointer) - { + if (pointer) { ++releases; delete pointer; pointer = nullptr; @@ -27,14 +24,12 @@ void release(T*& pointer) noexcept { } // namespace node_copy_hooks inline void* operator new(std::size_t size, node_copy_hooks::allocation_tag) noexcept { - if (node_copy_hooks::return_null) - { + if (node_copy_hooks::return_null) { node_copy_hooks::return_null = false; return nullptr; } auto* pointer = ::operator new(size, std::nothrow); - if (pointer) - { + if (pointer) { ++node_copy_hooks::allocations; } return pointer; diff --git a/tests/core/node_copy_ownership.cpp b/tests/core/node_copy_ownership.cpp index b483b4a3e..479ed6c96 100644 --- a/tests/core/node_copy_ownership.cpp +++ b/tests/core/node_copy_ownership.cpp @@ -39,25 +39,24 @@ void fail_string_buffer_allocation(std::size_t minimum_size) { } // namespace void* operator new(std::size_t size) { - if ((fail_minimum_size && size >= fail_minimum_size) || (fail_remaining && --fail_remaining == 0)) - { + if ((fail_minimum_size && size >= fail_minimum_size) || (fail_remaining && --fail_remaining == 0)) { fail_minimum_size = 0; failed_size = size; failure_consumed = true; throw std::bad_alloc{}; } - if (auto* pointer = std::malloc(size ? size : 1)) - { + if (auto* pointer = std::malloc(size ? size : 1)) { return pointer; } throw std::bad_alloc{}; } void* operator new(std::size_t size, const std::nothrow_t&) noexcept { - try - { return ::operator new(size); } - catch (...) - { return nullptr; } + try { + return ::operator new(size); + } catch (...) { + return nullptr; + } } void operator delete(void* pointer) noexcept { @@ -73,8 +72,7 @@ void operator delete(void* pointer, const std::nothrow_t&) noexcept { } TEST_CASE("Node clone string allocation failure destroys the unpublished candidate") { - for (bool simulate_proxy : {false, true}) - { + for (bool simulate_proxy : {false, true}) { CAPTURE(simulate_proxy); const auto schema = std::make_shared("Copy"); auto meta = field(schema, ark::data_type::dt_string); @@ -92,18 +90,16 @@ TEST_CASE("Node clone string allocation failure destroys the unpublished candida // character buffer allocated by copy_from(), independent of STL rounding. fail_string_buffer_allocation(minimum_size); bool threw{}; - try - { - if (simulate_proxy) - { + try { + if (simulate_proxy) { // Exercise an extra small allocation even on libraries without proxies. auto* proxy = ::operator new(2 * sizeof(void*)); ::operator delete(proxy); } manager.create_data(&source); + } catch (const std::bad_alloc&) { + threw = true; } - catch (const std::bad_alloc&) - { threw = true; } CHECK(threw); CHECK(failure_consumed); CHECK(failed_size >= minimum_size); @@ -128,10 +124,11 @@ TEST_CASE("Node clone map allocation failure destroys the copied unpublished can #endif fail_second_allocation(); bool threw{}; - try - { manager.create_data(&source); } - catch (const std::bad_alloc&) - { threw = true; } + try { + manager.create_data(&source); + } catch (const std::bad_alloc&) { + threw = true; + } CHECK(threw); CHECK(failure_consumed); CHECK(manager.is_empty()); @@ -143,8 +140,7 @@ TEST_CASE("Node clone map allocation failure destroys the copied unpublished can } TEST_CASE("Node creation and lazy creation release candidates if map insertion throws") { - for (bool lazy : {false, true}) - { + for (bool lazy : {false, true}) { const auto schema = std::make_shared("Create"); auto meta = field(schema, ark::data_type::dt_int32); ark::node_manager manager(schema); @@ -152,19 +148,15 @@ TEST_CASE("Node creation and lazy creation release candidates if map insertion t const auto references = meta.use_count(); fail_second_allocation(); bool threw{}; - try - { - if (lazy) - { + try { + if (lazy) { manager.create_data(name); - } - else - { + } else { manager.create_data(meta); } + } catch (const std::bad_alloc&) { + threw = true; } - catch (const std::bad_alloc&) - { threw = true; } CHECK(threw); CHECK(failure_consumed); CHECK(manager.is_empty()); diff --git a/tests/core/node_data_storage.cpp b/tests/core/node_data_storage.cpp index f685db167..3a90091d2 100644 --- a/tests/core/node_data_storage.cpp +++ b/tests/core/node_data_storage.cpp @@ -14,15 +14,13 @@ namespace { -class tracked_allocator -{ +class tracked_allocator { public: static inline std::unordered_map outstanding; static inline bool fail_next{false}; void* alloc(std::size_t size) { - if (fail_next) - { + if (fail_next) { fail_next = false; throw std::bad_alloc{}; } @@ -33,8 +31,7 @@ class tracked_allocator } void free(void* ptr, std::size_t size) { - if (ptr == nullptr) - { + if (ptr == nullptr) { return; } @@ -49,8 +46,7 @@ class tracked_allocator } }; -class allocation_scope -{ +class allocation_scope { public: allocation_scope() { DOCTEST_REQUIRE(tracked_allocator::outstanding.empty()); @@ -58,8 +54,7 @@ class allocation_scope ~allocation_scope() { // Keep a failing ownership assertion from leaking test allocations. - for (const auto& [ptr, size] : tracked_allocator::outstanding) - { + for (const auto& [ptr, size] : tracked_allocator::outstanding) { delete[] static_cast(ptr); } @@ -80,16 +75,14 @@ using tracked_data = ark::data_base<8, tracked_allocator>; DOCTEST_TEST_CASE("GUID data values preserve their tag through factory copy assignment node conversion and equality") { for (const auto value : - {std::numeric_limits::min(), ark::guid_t{}, std::numeric_limits::max()}) - { + {std::numeric_limits::min(), ark::guid_t{}, std::numeric_limits::max()}) { auto original = ark::data_impl::from_guid(value); ark::data_impl copied(original); const ark::data& erased = original; ark::data_impl copied_data(erased); ark::data_impl assigned(ark::data_type::dt_string, "previous allocation"); assigned.assign(erased); - for (auto* item : {&original, &copied, &copied_data, &assigned}) - { + for (auto* item : {&original, &copied, &copied_data, &assigned}) { DOCTEST_CHECK(item->get_type() == ark::data_type::dt_guid); #if defined(ARK_USE_GUID_32) DOCTEST_CHECK(item->get_int() == value); @@ -136,8 +129,7 @@ DOCTEST_TEST_CASE("Node conversion releases an old allocated string before retai } DOCTEST_TEST_CASE("Node conversion releases replaced string and user data allocations") { - for (const auto& text : {std::string("short"), std::string(80, 'x')}) - { + for (const auto& text : {std::string("short"), std::string(80, 'x')}) { ark::node_string source(metadata(ark::data_type::dt_string)); source.set_string(text); const auto expected = text.size() + 1 > 8 ? 1u : 0u; @@ -145,8 +137,7 @@ DOCTEST_TEST_CASE("Node conversion releases replaced string and user data alloca allocation_scope allocations; { tracked_data value(ark::data_type::dt_string, "previous allocated storage"); - for (int repeat = 0; repeat < 5; ++repeat) - { + for (int repeat = 0; repeat < 5; ++repeat) { DOCTEST_REQUIRE(value.from(&source)); DOCTEST_CHECK(std::string(value.get_string()) == text); DOCTEST_CHECK(tracked_allocator::outstanding.size() == expected); @@ -186,24 +177,18 @@ DOCTEST_TEST_CASE("Null node conversion preserves the existing allocation and va } DOCTEST_TEST_CASE("Failed node replacement allocation preserves the previous value and ownership") { - for (int kind = 0; kind < 3; ++kind) - { + for (int kind = 0; kind < 3; ++kind) { allocation_scope allocations; ark::node_string source(metadata(ark::data_type::dt_string)); source.set_string(std::string(80, 'x')); { const char bytes[] = "owned payload"; tracked_data value; - if (kind == 0) - { + if (kind == 0) { value.set_int(42); - } - else if (kind == 1) - { + } else if (kind == 1) { value.set_string("previous allocated storage"); - } - else - { + } else { value.set_user_data(bytes, sizeof(bytes)); } @@ -215,16 +200,11 @@ DOCTEST_TEST_CASE("Failed node replacement allocation preserves the previous val DOCTEST_CHECK(value.get_type() == previous_type); DOCTEST_CHECK(tracked_allocator::outstanding == previous_allocations); DOCTEST_CHECK(source.get_string() == std::string(80, 'x')); - if (kind == 0) - { + if (kind == 0) { DOCTEST_CHECK(value.get_int() == 42); - } - else if (kind == 1) - { + } else if (kind == 1) { DOCTEST_CHECK(std::string(value.get_string()) == "previous allocated storage"); - } - else - { + } else { std::size_t size = 0; const auto* result = value.get_user_data(size); DOCTEST_CHECK(size == sizeof(bytes)); diff --git a/tests/core/object_map_cleanup.cpp b/tests/core/object_map_cleanup.cpp index 394cb9344..b9bfb5383 100644 --- a/tests/core/object_map_cleanup.cpp +++ b/tests/core/object_map_cleanup.cpp @@ -11,8 +11,7 @@ namespace { -struct guarded_key -{ +struct guarded_key { int value{}; static inline int copies_before_failure{-1}; static inline int copies{}; @@ -23,12 +22,10 @@ struct guarded_key guarded_key(const guarded_key& other) : value(other.value) { - if (copies_before_failure == 0) - { + if (copies_before_failure == 0) { throw std::runtime_error("key copy failed"); } - if (copies_before_failure > 0) - { + if (copies_before_failure > 0) { --copies_before_failure; } ++copies; @@ -39,8 +36,7 @@ struct guarded_key auto operator<=>(const guarded_key&) const = default; }; -struct cleanup_value -{ +struct cleanup_value { explicit cleanup_value(int& destroyed) : destroyed(destroyed) { } @@ -55,8 +51,7 @@ struct cleanup_value } // namespace template<> -struct std::hash -{ +struct std::hash { std::size_t operator()(const guarded_key& key) const noexcept { return std::hash{}(key.value); } @@ -82,10 +77,11 @@ TEST_CASE_TEMPLATE("Owning object maps clear entries without copying keys or ret const auto copies = guarded_key::copies; bool caught{}; guarded_key::copies_before_failure = 1; - try - { values.clear(); } - catch (const std::runtime_error&) - { caught = true; } + try { + values.clear(); + } catch (const std::runtime_error&) { + caught = true; + } guarded_key::copies_before_failure = -1; CHECK_FALSE(caught); CHECK(guarded_key::copies == copies); @@ -121,10 +117,11 @@ TEST_CASE_TEMPLATE( const auto copies = guarded_key::copies; bool caught{}; guarded_key::copies_before_failure = 0; - try - { values.clear(); } - catch (const std::runtime_error&) - { caught = true; } + try { + values.clear(); + } catch (const std::runtime_error&) { + caught = true; + } guarded_key::copies_before_failure = -1; CHECK_FALSE(caught); CHECK(guarded_key::copies == copies); @@ -152,10 +149,11 @@ TEST_CASE_TEMPLATE("Object maps with reference values retain borrowed objects du const auto copies = guarded_key::copies; bool caught{}; guarded_key::copies_before_failure = 0; - try - { values.clear(); } - catch (const std::runtime_error&) - { caught = true; } + try { + values.clear(); + } catch (const std::runtime_error&) { + caught = true; + } guarded_key::copies_before_failure = -1; CHECK_FALSE(caught); CHECK(guarded_key::copies == copies); diff --git a/tests/core/object_vectors.cpp b/tests/core/object_vectors.cpp index 8e1068cc1..16c1add77 100644 --- a/tests/core/object_vectors.cpp +++ b/tests/core/object_vectors.cpp @@ -11,8 +11,7 @@ namespace { -struct vector_object -{ +struct vector_object { vector_object(int value, int& destroyed) : value(value) , destroyed(destroyed) { @@ -200,12 +199,9 @@ DOCTEST_TEST_CASE("Shared-vector moves preserve external references and safely r DOCTEST_TEST_CASE_TEMPLATE("Object-vector slots and const forward and reverse iteration preserve their contracts", vector_type, ark::pointer_vector, ark::shared_vector) { auto make_value = [](int value) { - if constexpr (std::is_same_v) - { + if constexpr (std::is_same_v) { return new int(value); - } - else - { + } else { return std::make_shared(value); } }; @@ -228,15 +224,13 @@ DOCTEST_TEST_CASE_TEMPLATE("Object-vector slots and const forward and reverse it DOCTEST_CHECK(values.size() == 3); std::vector forward; - for (auto it = observed.cbegin(); it != observed.cend(); ++it) - { + for (auto it = observed.cbegin(); it != observed.cend(); ++it) { forward.push_back(**it); } const std::vector expected_forward{1, 2, 3}; DOCTEST_CHECK(forward == expected_forward); std::vector reverse; - for (auto it = observed.crbegin(); it != observed.crend(); ++it) - { + for (auto it = observed.crbegin(); it != observed.crend(); ++it) { reverse.push_back(**it); } const std::vector expected_reverse{3, 2, 1}; diff --git a/tests/core/physic_resources.cpp b/tests/core/physic_resources.cpp index 7574e3a76..aed4bf1de 100644 --- a/tests/core/physic_resources.cpp +++ b/tests/core/physic_resources.cpp @@ -12,18 +12,15 @@ namespace { -struct resource_directory -{ +struct resource_directory { std::filesystem::path path; resource_directory() { const auto prefix = "ark-physic-resources-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()); - for (unsigned i = 0;; ++i) - { + for (unsigned i = 0;; ++i) { path = std::filesystem::temp_directory_path() / (prefix + "-" + std::to_string(i)); - if (std::filesystem::create_directory(path)) - { + if (std::filesystem::create_directory(path)) { break; } } @@ -78,13 +75,12 @@ TEST_CASE("Physic resources reject invalid TOML values and XML contents") { document = ""; } const auto path = files.write("physic.toml", document); - try - { + try { (void)ark::physic_resources::read_settings(path); FAIL("Invalid physics settings must not load"); + } catch (const std::runtime_error& error) { + CHECK(std::string(error.what()).find("physic.toml") != std::string::npos); } - catch (const std::runtime_error& error) - { CHECK(std::string(error.what()).find("physic.toml") != std::string::npos); } } TEST_CASE("Physic resources load all shipped collider types with zero-based mesh indices") { @@ -109,8 +105,7 @@ TEST_CASE("Physic resources load all shipped collider types with zero-based mesh CHECK(colliders[2].convex); CHECK_FALSE(colliders[4].convex); CHECK(colliders[5].radius == 2); - for (const auto index : {2U, 4U}) - { + for (const auto index : {2U, 4U}) { const auto& mesh = colliders[index]; REQUIRE(mesh.vertices.size() == 88); REQUIRE(mesh.triangles.size() == 240); @@ -149,11 +144,10 @@ TEST_CASE("Physic resources reject malformed collider geometry before creating S document["version"] = 2; } const auto path = files.write("colliders.json", document.dump()); - try - { + try { (void)ark::physic_resources::read_colliders(path); FAIL("Invalid collider data must not load"); + } catch (const std::runtime_error& error) { + CHECK(std::string(error.what()).find("colliders.json") != std::string::npos); } - catch (const std::runtime_error& error) - { CHECK(std::string(error.what()).find("colliders.json") != std::string::npos); } } diff --git a/tests/core/plugin_allocation_entry.cpp b/tests/core/plugin_allocation_entry.cpp index 63a15dce3..7fdec2475 100644 --- a/tests/core/plugin_allocation_entry.cpp +++ b/tests/core/plugin_allocation_entry.cpp @@ -24,8 +24,7 @@ ARK_EXPORT_FUNC void DllEntryPlugin(ark::plugin_manager* manager, const std::str } ARK_EXPORT_FUNC void DllExitPlugin(ark::plugin_manager* manager) { - if (exit_entry) - { + if (exit_entry) { exit_entry(manager); } } diff --git a/tests/core/plugin_configuration.cpp b/tests/core/plugin_configuration.cpp index d5cbb1707..b3c037b88 100644 --- a/tests/core/plugin_configuration.cpp +++ b/tests/core/plugin_configuration.cpp @@ -11,8 +11,7 @@ namespace { -class configuration_file -{ +class configuration_file { public: configuration_file() : path_( @@ -58,8 +57,7 @@ TEST_CASE("HTTP rejects missing mistyped unknown and out-of-range settings") { "[http]\nhost='localhost'\nport=9090\nthreads=0\n", "[http]\nhost='localhost'\nport=9090\nthreads=256\n", "[http]\nhost='localhost'\nport=9090\nthreads=4.0\n", "[http]\nhost='localhost'\nport='9090'\nthreads=4\n", "[http]\nhost=''\nport=9090\nthreads=4\n", "[http]\nhost=\"\\u0000\"\nport=9090\nthreads=4\n", - "[http]\nport=9090\nthreads=4\n", "[wrong]\nhost='localhost'\n", ""}) - { + "[http]\nport=9090\nthreads=4\n", "[wrong]\nhost='localhost'\n", ""}) { CHECK_THROWS_AS(ark::plugin_config_detail::load_http(file.write(text)), std::runtime_error); } } @@ -70,8 +68,7 @@ TEST_CASE("Consul accepts a hostname and validates its port before network acces CHECK(config.host == "localhost"); CHECK(config.port == 8500); for (const auto text : {"[consul]\nhost='localhost'\nport=0\n", "[consul]\nhost='localhost'\nport=65536\n", - "[consul]\nhost='localhost'\n", "[consul]\nhost='localhost'\nport=8500\npassword='not-logged'\n"}) - { + "[consul]\nhost='localhost'\n", "[consul]\nhost='localhost'\nport=8500\npassword='not-logged'\n"}) { CHECK_THROWS_AS(ark::plugin_config_detail::load_consul(file.write(text)), std::runtime_error); } } @@ -79,13 +76,10 @@ TEST_CASE("Consul accepts a hostname and validates its port before network acces TEST_CASE("Plugin configuration diagnostics identify the file and invalid field") { configuration_file file; const auto path = file.write("[http]\nhost='localhost'\nport=9090\nthreads=false\n"); - try - { + try { static_cast(ark::plugin_config_detail::load_http(path)); FAIL("invalid threads accepted"); - } - catch (const std::runtime_error& error) - { + } catch (const std::runtime_error& error) { CHECK(std::string(error.what()).find(path) != std::string::npos); CHECK(std::string(error.what()).find("threads") != std::string::npos); } @@ -102,16 +96,12 @@ TEST_CASE("Shared plugin reader rejects malformed encoding NUL paths and directo std::string raw_nul = "[http]\n"; raw_nul += '\0'; raw_nul += "SECRET_SENTINEL"; - for (const auto& contents : {std::string("[http\nsecret='SECRET_SENTINEL'\n"), invalid_utf8, raw_nul}) - { + for (const auto& contents : {std::string("[http\nsecret='SECRET_SENTINEL'\n"), invalid_utf8, raw_nul}) { const auto path = file.write(contents); - try - { + try { static_cast(ark::plugin_config_detail::load_http(path)); FAIL("invalid configuration accepted"); - } - catch (const std::runtime_error& error) - { + } catch (const std::runtime_error& error) { CHECK(std::string(error.what()).find(path + ":") != std::string::npos); CHECK(std::string(error.what()).find("SECRET_SENTINEL") == std::string::npos); } @@ -127,22 +117,15 @@ TEST_CASE("Shared plugin raw NUL diagnostics use UTF8 source columns") { contents += '\0'; contents += "SECRET_SENTINEL"; const auto path = file.write(contents); - for (const auto http : {true, false}) - { - try - { - if (http) - { + for (const auto http : {true, false}) { + try { + if (http) { static_cast(ark::plugin_config_detail::load_http(path)); - } - else - { + } else { static_cast(ark::plugin_config_detail::load_consul(path)); } FAIL("raw NUL accepted"); - } - catch (const std::runtime_error& error) - { + } catch (const std::runtime_error& error) { const auto message = std::string(error.what()); CHECK(message == path + ":1:7: configuration contains NUL"); } diff --git a/tests/core/plugin_construction.cpp b/tests/core/plugin_construction.cpp index 0eb4cf148..8993b7787 100644 --- a/tests/core/plugin_construction.cpp +++ b/tests/core/plugin_construction.cpp @@ -19,8 +19,7 @@ using construction_test::counts; using construction_test::make_service; using construction_test::service; -class test_plugin final : public ark::plugin_base -{ +class test_plugin final : public ark::plugin_base { public: using plugin_base::register_module; using plugin_base::unregister_module; @@ -33,8 +32,7 @@ class test_plugin final : public ark::plugin_base } }; -class other_plugin final : public ark::plugin_base -{ +class other_plugin final : public ark::plugin_base { public: using plugin_base::register_module; using plugin_base::unregister_module; @@ -51,8 +49,7 @@ static_assert(!std::is_copy_assignable_v); static_assert(!std::is_move_constructible_v); static_assert(!std::is_move_assignable_v); -class throwing_service final : public service -{ +class throwing_service final : public service { public: explicit throwing_service(counts& events) : events_(events) { @@ -74,14 +71,12 @@ class throwing_service final : public service counts& events_; }; -struct metadata_counts : counts -{ +struct metadata_counts : counts { unsigned manager_assignments{}; unsigned name_assignments{}; }; -class metadata_service final : public ark::module_base -{ +class metadata_service final : public ark::module_base { public: explicit metadata_service(metadata_counts& events) : events_(events) { @@ -109,8 +104,7 @@ class metadata_service final : public ark::module_base metadata_counts& events_; }; -class registration_guard final : public ark::module_base -{ +class registration_guard final : public ark::module_base { public: registration_guard(test_plugin& owner, metadata_counts& events) : owner_(owner) @@ -133,8 +127,7 @@ class registration_guard final : public ark::module_base metadata_counts& events_; }; -class guarded_service final : public ark::module_base -{ +class guarded_service final : public ark::module_base { public: explicit guarded_service(test_plugin& owner) : owner_(owner) { @@ -163,8 +156,7 @@ ark::task<> accepted_work() { } // namespace TEST_CASE("Typed private factories preserve interface identity and explicit update admission") { - for (const auto mode : {ark::module_update::disabled, ark::module_update::enabled}) - { + for (const auto mode : {ark::module_update::disabled, ark::module_update::enabled}) { ark::plugin_manager manager; test_plugin owner; owner.set_plugin_manager(&manager); @@ -208,18 +200,20 @@ TEST_CASE("Typed construction rejects foreign threads before candidate metadata bool registration_rejected{}, empty_removal_rejected{}; std::exception_ptr unexpected; std::thread worker([&] { - try - { owner.register_module(std::make_unique(rejected), ark::module_update::enabled); } - catch (const std::logic_error&) - { registration_rejected = true; } - catch (...) - { unexpected = std::current_exception(); } - try - { owner.unregister_module(); } - catch (const std::logic_error&) - { empty_removal_rejected = true; } - catch (...) - { unexpected = std::current_exception(); } + try { + owner.register_module(std::make_unique(rejected), ark::module_update::enabled); + } catch (const std::logic_error&) { + registration_rejected = true; + } catch (...) { + unexpected = std::current_exception(); + } + try { + owner.unregister_module(); + } catch (const std::logic_error&) { + empty_removal_rejected = true; + } catch (...) { + unexpected = std::current_exception(); + } }); worker.join(); CHECK(unexpected == nullptr); diff --git a/tests/core/plugin_manager_startup.cpp b/tests/core/plugin_manager_startup.cpp index 86774f3c6..f3f6592e5 100644 --- a/tests/core/plugin_manager_startup.cpp +++ b/tests/core/plugin_manager_startup.cpp @@ -11,8 +11,7 @@ namespace { -enum class startup_phase : std::size_t -{ +enum class startup_phase : std::size_t { init, post_init, check_config, @@ -22,15 +21,13 @@ enum class startup_phase : std::size_t constexpr std::array phase_names{"init", "post_init", "check_config", "pre_update"}; -enum class failure_mode -{ +enum class failure_mode { false_result, standard_exception, unknown_exception }; -class counted_module final : public ark::module -{ +class counted_module final : public ark::module { public: explicit counted_module( startup_phase failed_phase = startup_phase::none, failure_mode mode = failure_mode::false_result) @@ -75,14 +72,11 @@ class counted_module final : public ark::module private: bool record(startup_phase phase) { ++calls[static_cast(phase)]; - if (phase == failed_phase_) - { - if (mode_ == failure_mode::standard_exception) - { + if (phase == failed_phase_) { + if (mode_ == failure_mode::standard_exception) { throw std::runtime_error("startup module exception"); } - if (mode_ == failure_mode::unknown_exception) - { + if (mode_ == failure_mode::unknown_exception) { throw 91; } return false; @@ -94,8 +88,7 @@ class counted_module final : public ark::module failure_mode mode_; }; -class unconfigured_logger_scope -{ +class unconfigured_logger_scope { public: unconfigured_logger_scope() { ark::logger::set_instance(&logger_); @@ -119,23 +112,20 @@ bool start(ark::plugin_manager& manager) { TEST_CASE("Plugin startup calls each successful module phase once") { ark::plugin_manager manager; std::array modules; - for (std::size_t index = 0; index < modules.size(); ++index) - { + for (std::size_t index = 0; index < modules.size(); ++index) { REQUIRE(manager.add_module("counted-module-" + std::to_string(index), &modules[index])); } CHECK(manager.get_startup_failure().empty()); CHECK(start(manager)); CHECK(manager.get_startup_failure().empty()); - for (const auto& module : modules) - { + for (const auto& module : modules) { CHECK(module.calls == std::array{1, 1, 1, 1}); } } TEST_CASE("Plugin startup returns false without repeating a failed phase or running later phases") { - for (std::size_t failed = 0; failed < phase_names.size(); ++failed) - { + for (std::size_t failed = 0; failed < phase_names.size(); ++failed) { CAPTURE(std::string(phase_names[failed])); ark::plugin_manager manager; counted_module module(static_cast(failed)); @@ -144,45 +134,35 @@ TEST_CASE("Plugin startup returns false without repeating a failed phase or runn CHECK_FALSE(start(manager)); CHECK(manager.get_startup_failure() == std::string(phase_names[failed]) + ": counted-module-single"); CHECK(module.late_calls == 0); - for (std::size_t phase = 0; phase < phase_names.size(); ++phase) - { + for (std::size_t phase = 0; phase < phase_names.size(); ++phase) { CHECK(module.calls[phase] == (phase <= failed ? 1u : 0u)); } } } TEST_CASE("Plugin startup stops a phase at its first failure independently of module iteration order") { - for (std::size_t failed = 0; failed < phase_names.size(); ++failed) - { - for (const auto mode : {failure_mode::false_result, failure_mode::standard_exception}) - { + for (std::size_t failed = 0; failed < phase_names.size(); ++failed) { + for (const auto mode : {failure_mode::false_result, failure_mode::standard_exception}) { CAPTURE(std::string(phase_names[failed])); ark::plugin_manager manager; std::array modules{counted_module(static_cast(failed), mode), counted_module(static_cast(failed), mode), counted_module(static_cast(failed), mode)}; - for (std::size_t index = 0; index < modules.size(); ++index) - { + for (std::size_t index = 0; index < modules.size(); ++index) { REQUIRE(manager.add_module("counted-module-" + std::to_string(index), &modules[index])); } - if (mode == failure_mode::false_result) - { + if (mode == failure_mode::false_result) { CHECK_FALSE(start(manager)); - } - else - { + } else { CHECK_THROWS_WITH_AS(start(manager), "startup module exception", std::runtime_error); } - for (std::size_t phase = 0; phase < phase_names.size(); ++phase) - { + for (std::size_t phase = 0; phase < phase_names.size(); ++phase) { unsigned phase_calls = 0; - for (const auto& module : modules) - { + for (const auto& module : modules) { CHECK(module.calls[phase] <= 1); phase_calls += module.calls[phase]; - if (phase == failed && module.calls[phase] == 1) - { + if (phase == failed && module.calls[phase] == 1) { const auto index = static_cast(&module - modules.data()); CHECK(manager.get_startup_failure() == std::string(phase_names[failed]) + ": counted-module-" + std::to_string(index)); @@ -208,26 +188,20 @@ TEST_CASE("Plugin startup returns false without a configured logger") { } TEST_CASE("Startup exceptions preserve the first module and phase without cleanup or exception translation") { - for (std::size_t failed = 0; failed < phase_names.size(); ++failed) - { - for (const auto mode : {failure_mode::standard_exception, failure_mode::unknown_exception}) - { + for (std::size_t failed = 0; failed < phase_names.size(); ++failed) { + for (const auto mode : {failure_mode::standard_exception, failure_mode::unknown_exception}) { CAPTURE(std::string(phase_names[failed])); ark::plugin_manager manager; counted_module module(static_cast(failed), mode); REQUIRE(manager.add_module("throwing-module", &module)); - if (mode == failure_mode::standard_exception) - { + if (mode == failure_mode::standard_exception) { CHECK_THROWS_WITH_AS(start(manager), "startup module exception", std::runtime_error); - } - else - { + } else { CHECK_THROWS_AS(start(manager), int); } CHECK(manager.get_startup_failure() == std::string(phase_names[failed]) + ": throwing-module"); CHECK(module.late_calls == 0); - for (std::size_t phase = 0; phase < phase_names.size(); ++phase) - { + for (std::size_t phase = 0; phase < phase_names.size(); ++phase) { CHECK(module.calls[phase] == (phase <= failed ? 1u : 0u)); } } @@ -255,21 +229,20 @@ TEST_CASE("Nullable module lookup preserves RTTI keys without asserting or mutat } TEST_CASE("Nullable module lookup rejects a foreign thread and preserves owner access") { - for (const bool registered : {false, true}) - { + for (const bool registered : {false, true}) { CAPTURE(registered); ark::plugin_manager manager; counted_module expected; - if (registered) - { + if (registered) { REQUIRE(manager.add_module(typeid(counted_module).name(), &expected)); } bool rejected = false; std::thread foreign([&] { - try - { (void)manager.try_find_module(); } - catch (const std::logic_error&) - { rejected = true; } + try { + (void)manager.try_find_module(); + } catch (const std::logic_error&) { + rejected = true; + } }); foreign.join(); CHECK(rejected); diff --git a/tests/core/pod_array_failure.cpp b/tests/core/pod_array_failure.cpp index ababe8975..b4e5e685b 100644 --- a/tests/core/pod_array_failure.cpp +++ b/tests/core/pod_array_failure.cpp @@ -14,13 +14,11 @@ size_t fail_array_call{}; bool failure_consumed{}; void* allocate_array(size_t bytes) { - if (fail_array_call && --fail_array_call == 0) - { + if (fail_array_call && --fail_array_call == 0) { failure_consumed = true; throw std::bad_alloc{}; } - if (auto* result = std::malloc(bytes ? bytes : 1)) - { + if (auto* result = std::malloc(bytes ? bytes : 1)) { return result; } throw std::bad_alloc{}; @@ -39,10 +37,11 @@ void* operator new[](std::size_t bytes) { } void* operator new[](std::size_t bytes, const std::nothrow_t&) noexcept { - try - { return allocate_array(bytes); } - catch (...) - { return nullptr; } + try { + return allocate_array(bytes); + } catch (...) { + return nullptr; + } } void operator delete[](void* value) noexcept { @@ -64,10 +63,11 @@ TEST_CASE("POD array default allocation failure throws without replacing live st const auto* original = values.data(); fail_array(1); bool caught{}; - try - { values.push_back(values[0]); } - catch (const std::bad_alloc&) - { caught = true; } + try { + values.push_back(values[0]); + } catch (const std::bad_alloc&) { + caught = true; + } CHECK(failure_consumed); CHECK(caught); CHECK(values.data() == original); @@ -79,8 +79,7 @@ TEST_CASE("POD array default allocation failure throws without replacing live st } TEST_CASE("Array map rolls back pointer growth bucket and node allocation failures") { - for (size_t ordinal = 1; ordinal <= 3; ++ordinal) - { + for (size_t ordinal = 1; ordinal <= 3; ++ordinal) { INFO("failed array allocation ordinal=", ordinal); int original = 11; int candidate = 22; @@ -90,10 +89,11 @@ TEST_CASE("Array map rolls back pointer growth bucket and node allocation failur REQUIRE(values.add_element(existing_name, &original)); fail_array(ordinal); // Pointer array, index bucket expansion, then index node. bool caught{}; - try - { values.add_element(new_name, &candidate); } - catch (const std::bad_alloc&) - { caught = true; } + try { + values.add_element(new_name, &candidate); + } catch (const std::bad_alloc&) { + caught = true; + } CHECK(failure_consumed); CHECK(caught); REQUIRE(values.get_count() == 1); @@ -125,10 +125,11 @@ TEST_CASE("Array map failed duplicate insertion preserves the existing name and REQUIRE(values.add_element(name, &original)); fail_array(3); // Bucket expansion succeeds; allocating the duplicate node fails. bool caught{}; - try - { values.add_element(name, &candidate); } - catch (const std::bad_alloc&) - { caught = true; } + try { + values.add_element(name, &candidate); + } catch (const std::bad_alloc&) { + caught = true; + } CHECK(failure_consumed); CHECK(caught); REQUIRE(values.get_count() == 1); diff --git a/tests/core/pod_arrays.cpp b/tests/core/pod_arrays.cpp index dd463c48c..6dfa47970 100644 --- a/tests/core/pod_arrays.cpp +++ b/tests/core/pod_arrays.cpp @@ -12,15 +12,13 @@ namespace { -enum class failure_mode -{ +enum class failure_mode { none, null_result, exception }; -struct controlled_allocator -{ +struct controlled_allocator { static inline failure_mode failure{}; static inline size_t allocations{}; static inline size_t releases{}; @@ -31,17 +29,14 @@ struct controlled_allocator last_bytes = bytes; const auto mode = failure; failure = failure_mode::none; - if (mode == failure_mode::null_result) - { + if (mode == failure_mode::null_result) { return nullptr; } - if (mode == failure_mode::exception) - { + if (mode == failure_mode::exception) { throw std::bad_alloc{}; } auto* result = std::malloc(bytes); - if (!result) - { + if (!result) { throw std::bad_alloc{}; } ++allocations; @@ -146,10 +141,8 @@ TEST_CASE("POD array null and throwing allocations retain storage size and value REQUIRE(controlled_allocator::live == 0); const auto initial_allocations = controlled_allocator::allocations; const auto initial_releases = controlled_allocator::releases; - for (const auto failure : {failure_mode::null_result, failure_mode::exception}) - { - for (int operation = 0; operation != 7; ++operation) - { + for (const auto failure : {failure_mode::null_result, failure_mode::exception}) { + for (int operation = 0; operation != 7; ++operation) { INFO("failure=", static_cast(failure), " operation=", operation); controlled_array values; values.push_back(11); @@ -162,8 +155,7 @@ TEST_CASE("POD array null and throwing allocations retain storage size and value const auto releases = controlled_allocator::releases; controlled_allocator::failure = failure; const auto fail_operation = [&] { - switch (operation) - { + switch (operation) { case 0: values.push_back(values[0]); break; @@ -179,8 +171,7 @@ TEST_CASE("POD array null and throwing allocations retain storage size and value case 4: values.insert(0, values[1]); break; - case 5: - { + case 5: { controlled_array copy(values); break; } diff --git a/tests/core/protobuf_messages.cpp b/tests/core/protobuf_messages.cpp index 840fc0156..5c09ceb40 100644 --- a/tests/core/protobuf_messages.cpp +++ b/tests/core/protobuf_messages.cpp @@ -207,8 +207,7 @@ DOCTEST_TEST_CASE("Protocol descriptors and textual enum values use the new publ DOCTEST_TEST_CASE("Guest-room snake-case enum symbols preserve numeric wire values") { namespace wire = ark::protobuf::guest_room; - for (const auto kind : {wire::action_unspecified, wire::action_damage, wire::action_skill, wire::action_rest}) - { + for (const auto kind : {wire::action_unspecified, wire::action_damage, wire::action_skill, wire::action_rest}) { const auto numeric = static_cast(kind); wire::action_request request; const auto original = diff --git a/tests/core/random_generator.cpp b/tests/core/random_generator.cpp index a9d240a9c..030de3f1f 100644 --- a/tests/core/random_generator.cpp +++ b/tests/core/random_generator.cpp @@ -18,8 +18,7 @@ TEST_CASE("Random generator retains its seed sequence and resets its count") { generator.set_seed(1); const std::array expected{476707713, 1186278907, 505671508, 2137716191, 936145377, 1215825599}; - for (const auto value : expected) - { + for (const auto value : expected) { CHECK(generator.random() == value); } CHECK(generator.get_seed() == 3535774167u); @@ -38,8 +37,7 @@ TEST_CASE("Signed random ranges retain legacy in-range values and unsigned overl const std::array expected_signed{13, 7, 8, 91, 77, 99}; const std::array expected_unsigned{23, 17, 18, 101, 87, 109}; - for (std::size_t index = 0; index < expected_signed.size(); ++index) - { + for (std::size_t index = 0; index < expected_signed.size(); ++index) { CHECK(signed_values.random(-100, 100) == expected_signed[index]); CHECK(unsigned_values.random(10u, 110u) == expected_unsigned[index]); } @@ -55,8 +53,7 @@ TEST_CASE("Signed random ranges decode full-width spans without overflow") { ark::random_generator generator; generator.set_seed(1); const std::array expected{-1670775935, -961204741, -1641812140, -9767457, -1211338271, -931658049}; - for (const auto value : expected) - { + for (const auto value : expected) { CHECK(generator.random(std::numeric_limits::min(), std::numeric_limits::max()) == value); } CHECK(generator.get_seed() == 3535774167u); @@ -69,28 +66,22 @@ TEST_CASE("Signed random ranges preserve half-open reversed and equal bounds") { const std::array, 12> ranges{ {{lowest, highest}, {lowest, 0}, {-1, highest}, {lowest, 1}, {-100, 100}, {-100, -1}, {0, highest}, {lowest, lowest + 1}, {highest - 1, highest}, {lowest, lowest}, {highest, highest}, {0, 0}}}; - for (const auto& bounds : ranges) - { + for (const auto& bounds : ranges) { CAPTURE(bounds[0]); CAPTURE(bounds[1]); - for (const std::uint32_t seed : {0u, 1u, 123456789u, std::numeric_limits::max()}) - { + for (const std::uint32_t seed : {0u, 1u, 123456789u, std::numeric_limits::max()}) { ark::random_generator forward; ark::random_generator reversed; forward.set_seed(seed); reversed.set_seed(seed); - for (int index = 0; index < 64; ++index) - { + for (int index = 0; index < 64; ++index) { const int value = forward.random(bounds[0], bounds[1]); CHECK(value == reversed.random(bounds[1], bounds[0])); - if (bounds[0] == bounds[1]) - { + if (bounds[0] == bounds[1]) { CHECK(value == bounds[0]); CHECK(forward.get_seed() == seed); CHECK(forward.get_random_count() == 0); - } - else - { + } else { CHECK(value >= bounds[0]); CHECK(value < bounds[1]); CHECK(forward.get_random_count() == index + 1); @@ -107,8 +98,7 @@ namespace { template void check_xoshiro_sequence( generator_type& generator, const std::array& expected) { - for (const auto value : expected) - { + for (const auto value : expected) { CHECK(generator.random() == value); } } diff --git a/tests/core/scheduler_drain.cpp b/tests/core/scheduler_drain.cpp index 215549abe..d66137f8c 100644 --- a/tests/core/scheduler_drain.cpp +++ b/tests/core/scheduler_drain.cpp @@ -23,8 +23,7 @@ using namespace std::chrono_literals; namespace ark { -struct scheduler_test_access -{ +struct scheduler_test_access { static std::size_t outstanding(const scheduler& value) { return value.outstanding_.load(); } @@ -33,13 +32,10 @@ struct scheduler_test_access std::lock_guard lock(value.mutex_); std::size_t count{}; decltype(value.tasks_) advanced; - for (auto i = value.tasks_.begin(); i != value.tasks_.end();) - { - if (!i->second->recurring) - { + for (auto i = value.tasks_.begin(); i != value.tasks_.end();) { + if (!i->second->recurring) { ++count; - if (advance) - { + if (advance) { auto node = value.tasks_.extract(i++); node.key() = scheduler::clock::now(); advanced.insert(std::move(node)); @@ -60,10 +56,8 @@ namespace { template bool eventually(predicate&& ready) { const auto deadline = std::chrono::steady_clock::now() + 5s; - while (!ready()) - { - if (std::chrono::steady_clock::now() >= deadline) - { + while (!ready()) { + if (std::chrono::steady_clock::now() >= deadline) { return false; } std::this_thread::yield(); @@ -71,15 +65,13 @@ bool eventually(predicate&& ready) { return true; } -struct gate -{ +struct gate { std::promise promise; std::shared_future future{promise.get_future()}; std::atomic opened{false}; void open() { - if (!opened.exchange(true)) - { + if (!opened.exchange(true)) { promise.set_value(); } } @@ -89,8 +81,7 @@ struct gate } }; -struct release_on_exit -{ +struct release_on_exit { gate& value; ~release_on_exit() { @@ -98,8 +89,7 @@ struct release_on_exit } }; -struct retiring_capture -{ +struct retiring_capture { ark::scheduler& scheduler; gate& entered; gate& release; @@ -115,8 +105,7 @@ struct retiring_capture } }; -struct receiver -{ +struct receiver { gate entered; gate release; std::atomic calls{0}; @@ -128,8 +117,7 @@ struct receiver } }; -struct schedule_module_access : ark::schedule_module -{ +struct schedule_module_access : ark::schedule_module { static void at(ark::schedule_module& module, const std::string& time, ark::scheduler_functor callback) { // Form the protected callback overload's member pointer without casting // the factory's production module to a test implementation. @@ -139,15 +127,13 @@ struct schedule_module_access : ark::schedule_module } }; -struct cleanup_probe final : ark::module -{ +struct cleanup_probe final : ark::module { unsigned pre_shut_calls{}; unsigned shut_calls{}; std::function on_update; bool update() override { - if (on_update) - { + if (on_update) { on_update(); } return true; @@ -254,8 +240,7 @@ TEST_CASE("Scheduler resource close discards future captures and seals running c std::atomic calls{}; std::atomic capture_retired{}; - struct closing_capture - { + struct closing_capture { ark::scheduler& scheduler; gate& entered; gate& release; @@ -317,8 +302,7 @@ TEST_CASE("Scheduler callback exception owners retire before readiness") { ark::scheduler scheduler(1); release_on_exit unblock{release}; - struct callback_error - { + struct callback_error { gate& entered; gate& release; @@ -340,8 +324,7 @@ TEST_CASE("Scheduler reports standard exception cause before retiring its callba ark::scheduler scheduler(1); std::atomic reported{}; - struct callback_error final : std::exception - { + struct callback_error final : std::exception { std::atomic& reported; explicit callback_error(std::atomic& reported) @@ -366,8 +349,7 @@ TEST_CASE("Scheduler capture destruction can schedule same-instance one-shot com release_on_exit unblock{release}; std::atomic calls{}; - struct continuation_capture - { + struct continuation_capture { ark::scheduler& scheduler; std::atomic& calls; @@ -393,8 +375,7 @@ TEST_CASE("Scheduler fast callback captures retain continuation authority throug ark::scheduler scheduler(8); std::atomic calls{}; - struct continuation_capture - { + struct continuation_capture { ark::scheduler& scheduler; std::atomic& calls; @@ -403,8 +384,7 @@ TEST_CASE("Scheduler fast callback captures retain continuation authority throug } }; - for (unsigned i = 0; i < 64; ++i) - { + for (unsigned i = 0; i < 64; ++i) { scheduler.in(24h, [capture = std::make_shared(scheduler, calls)] {}); } scheduler.stop_accepting(); @@ -455,13 +435,10 @@ TEST_CASE("Scheduler interval rearms after completion during normal operation") release_on_exit unblock{release}; std::atomic calls{}; scheduler.interval(0ms, [&] { - if (++calls == 1) - { + if (++calls == 1) { entered.open(); release.wait(); - } - else - { + } else { scheduler.stop_accepting(); } }); @@ -479,14 +456,11 @@ TEST_CASE("Scheduler every retains overlapping dispatch during normal operation" std::atomic calls{}; std::atomic first_finished{}, overlap{}; scheduler.every(1ms, [&] { - if (++calls == 1) - { + if (++calls == 1) { entered.open(); release.wait(); first_finished = true; - } - else - { + } else { overlap = !first_finished; scheduler.stop_accepting(); } @@ -508,16 +482,13 @@ TEST_CASE("Scheduler concurrent accepted at continuations and cron use caller-ow std::array from, expected; std::atomic calls{}; std::atomic calendars_match{true}; - for (unsigned i = 0; i < workers; ++i) - { + for (unsigned i = 0; i < workers; ++i) { from[i] = ark::scheduler::clock::from_time_t(1700000000 + i * 86400); expected[i] = expression.cron_to_next(from[i]); scheduler.in(0ms, [&, i] { start.arrive_and_wait(); - for (unsigned round = 0; round < rounds; ++round) - { - if (expression.cron_to_next(from[i]) != expected[i]) - { + for (unsigned round = 0; round < rounds; ++round) { + if (expression.cron_to_next(from[i]) != expected[i]) { calendars_match = false; } scheduler.at("2000-01-01 00:00:00", [&] { ++calls; }); @@ -536,8 +507,7 @@ TEST_CASE("Scheduler concurrent registration and stop retires every admitted cap std::barrier start(5); std::atomic owners{}, destroyed{}, calls{}; - struct owner - { + struct owner { std::atomic& destroyed; ~owner() { @@ -546,12 +516,10 @@ TEST_CASE("Scheduler concurrent registration and stop retires every admitted cap }; std::vector producers; - for (unsigned i = 0; i < 4; ++i) - { + for (unsigned i = 0; i < 4; ++i) { producers.emplace_back([&] { start.arrive_and_wait(); - for (unsigned j = 0; j < 500; ++j) - { + for (unsigned j = 0; j < 500; ++j) { auto capture = std::make_shared(destroyed); ++owners; scheduler.every(24h, [capture, &calls] { ++calls; }); @@ -560,8 +528,7 @@ TEST_CASE("Scheduler concurrent registration and stop retires every admitted cap } start.arrive_and_wait(); scheduler.stop_accepting(); - for (auto& producer : producers) - { + for (auto& producer : producers) { producer.join(); } REQUIRE(eventually([&] { return scheduler.ready_to_shut(); })); @@ -574,8 +541,7 @@ TEST_CASE("Scheduler readiness includes a registration copying captures when sto ark::scheduler scheduler(1); release_on_exit unblock{release}; - struct copying_callable - { + struct copying_callable { gate& entered; gate& release; @@ -711,8 +677,7 @@ TEST_CASE("Manager deadline retains accepted future one-shot work without cleanu ark::plugin_manager manager; ark::scheduler scheduler(1); - struct scheduler_probe final : ark::module - { + struct scheduler_probe final : ark::module { ark::scheduler& scheduler; unsigned cleanup_calls{}; @@ -824,8 +789,7 @@ TEST_CASE("Scheduler evaluates nested bind expressions and unwraps generic refer } TEST_CASE("Scheduler member callbacks retain shared receivers and borrow raw receivers") { - struct member_receiver - { + struct member_receiver { int calls{}; int invoke(int value, std::promise& completed) { diff --git a/tests/core/scheduler_failure.cpp b/tests/core/scheduler_failure.cpp index bbc105ed9..23a7ebe26 100644 --- a/tests/core/scheduler_failure.cpp +++ b/tests/core/scheduler_failure.cpp @@ -14,8 +14,7 @@ thread_local bool reject_submission{}; thread_local unsigned rejected_allocations{}; void before_scheduler_submission() { - if (reject_submission) - { + if (reject_submission) { reject_submission = false; reject_allocations = true; } @@ -29,13 +28,11 @@ void before_scheduler_submission() { #undef ARK_SCHEDULER_SUBMISSION_TEST_HOOK void* operator new(std::size_t size) { - if (reject_allocations) - { + if (reject_allocations) { ++rejected_allocations; throw std::bad_alloc{}; } - if (auto* memory = std::malloc(size ? size : 1)) - { + if (auto* memory = std::malloc(size ? size : 1)) { return memory; } throw std::bad_alloc{}; @@ -50,8 +47,7 @@ void operator delete(void* memory, std::size_t) noexcept { } namespace ark { -struct scheduler_test_access -{ +struct scheduler_test_access { // The initial production dispatcher has already reached readiness. Reopen // only test state, leaving that dispatcher retired, so this thread can run // the actual dispatch()/manage_tasks() with deterministic allocation faults. @@ -66,10 +62,9 @@ struct scheduler_test_access } static void dispatch(scheduler& value) { - try - { value.dispatch(); } - catch (...) - { + try { + value.dispatch(); + } catch (...) { reject_allocations = false; throw; } @@ -104,10 +99,8 @@ using namespace std::chrono_literals; template bool eventually(predicate&& ready) { const auto deadline = std::chrono::steady_clock::now() + 5s; - while (!ready()) - { - if (std::chrono::steady_clock::now() >= deadline) - { + while (!ready()) { + if (std::chrono::steady_clock::now() >= deadline) { return false; } std::this_thread::yield(); @@ -115,8 +108,7 @@ bool eventually(predicate&& ready) { return true; } -struct test_recovery -{ +struct test_recovery { ark::scheduler& scheduler; ~test_recovery() { @@ -124,15 +116,13 @@ struct test_recovery reject_submission = false; // No production retry/recovery is claimed. Retire retained owners only // after observing failure with readiness closed and submitted work done. - if (eventually([&] { return ark::scheduler_test_access::work_retired(scheduler); })) - { + if (eventually([&] { return ark::scheduler_test_access::work_retired(scheduler); })) { ark::scheduler_test_access::recover_only_for_test(scheduler); } } }; -struct capture -{ +struct capture { std::atomic& destroyed; ~capture() { @@ -140,8 +130,7 @@ struct capture } }; -struct failing_recurrence final : ark::scheduler_task -{ +struct failing_recurrence final : ark::scheduler_task { unsigned phase; failing_recurrence(unsigned phase, std::function&& callback) @@ -151,8 +140,7 @@ struct failing_recurrence final : ark::scheduler_task clock::time_point get_new_time() const override { reject_allocations = true; - if (phase == 1) - { + if (phase == 1) { throw std::bad_alloc{}; } // The next allocation is the production recurrence map's emplace. @@ -168,12 +156,9 @@ void check_failure(unsigned phase) { REQUIRE(eventually([&] { return scheduler.ready_to_shut(); })); ark::scheduler_test_access::prepare_manual_dispatch(scheduler); test_recovery recover{scheduler}; - if (phase == 0) - { + if (phase == 0) { scheduler.in(0ms, [owner = std::make_shared(destroyed), &submitted_calls] { ++submitted_calls; }); - } - else - { + } else { ark::scheduler_test_access::insert(scheduler, std::make_shared( phase, [owner = std::make_shared(destroyed), &submitted_calls] { ++submitted_calls; })); diff --git a/tests/core/scheduler_startup_cleanup.cpp b/tests/core/scheduler_startup_cleanup.cpp index a108103dc..fe3d41b51 100644 --- a/tests/core/scheduler_startup_cleanup.cpp +++ b/tests/core/scheduler_startup_cleanup.cpp @@ -36,10 +36,8 @@ thread_local bool reject_allocations{}; } // namespace void* operator new(std::size_t size) { - if (!reject_allocations) - { - if (auto* pointer = std::malloc(size ? size : 1)) - { + if (!reject_allocations) { + if (auto* pointer = std::malloc(size ? size : 1)) { return pointer; } } @@ -67,17 +65,19 @@ void operator delete[](void* pointer, std::size_t) noexcept { } void* operator new(std::size_t size, const std::nothrow_t&) noexcept { - try - { return ::operator new(size); } - catch (...) - { return nullptr; } + try { + return ::operator new(size); + } catch (...) { + return nullptr; + } } void* operator new[](std::size_t size, const std::nothrow_t&) noexcept { - try - { return ::operator new[](size); } - catch (...) - { return nullptr; } + try { + return ::operator new[](size); + } catch (...) { + return nullptr; + } } void operator delete(void* pointer, const std::nothrow_t&) noexcept { @@ -90,8 +90,7 @@ void operator delete[](void* pointer, const std::nothrow_t&) noexcept { namespace ark { -struct schedule_startup_test_access -{ +struct schedule_startup_test_access { static auto state(schedule_module& module) { return static_cast(module).startup_; } @@ -118,19 +117,16 @@ using access = ark::schedule_startup_test_access; #endif } -struct failing_module final : ark::module -{ +struct failing_module final : ark::module { unsigned phase{}; bool throws{}; unsigned ordinary_cleanup{}; bool step(unsigned current) const { - if (phase != current) - { + if (phase != current) { return true; } - if (throws) - { + if (throws) { throw std::runtime_error("controlled later Schedule startup failure"); } return false; @@ -178,10 +174,8 @@ auto make_schedule(ark::plugin_manager& manager) { template bool eventually(Predicate&& ready) { const auto deadline = std::chrono::steady_clock::now() + 5s; - while (!ready()) - { - if (std::chrono::steady_clock::now() >= deadline) - { + while (!ready()) { + if (std::chrono::steady_clock::now() >= deadline) { return false; } std::this_thread::yield(); @@ -198,8 +192,7 @@ template void retire_test_owner(const State& state) { // Explicit fixture teardown after retention assertions. The failed manager // must never perform this ordinary cancellation or retry its cleanup action. - if (state->worker) - { + if (state->worker) { state->worker->close(); REQUIRE(eventually([&] { return state->worker->ready_to_shut(); })); REQUIRE(state->worker->pre_shut()); @@ -215,10 +208,8 @@ TEST_CASE("Scheduler rejects overflowing worker counts before creating threads") } TEST_CASE("Schedule failed startup retires its unexposed workers after every failed phase") { - for (unsigned phase{}; phase < 4; ++phase) - { - for (bool throws : {false, true}) - { + for (unsigned phase{}; phase < 4; ++phase) { + for (bool throws : {false, true}) { CAPTURE(phase); CAPTURE(throws); ark::plugin_manager manager; @@ -230,12 +221,9 @@ TEST_CASE("Schedule failed startup retires its unexposed workers after every fai failure.throws = throws; REQUIRE(manager.add_module("Schedule", schedule.get())); REQUIRE(manager.add_module("failure", &failure)); - if (throws) - { + if (throws) { CHECK_THROWS_AS(manager.start(0, {}, {}, {}), std::runtime_error); - } - else - { + } else { CHECK_FALSE(manager.start(0, {}, {}, {})); } auto state = access::state(*schedule); @@ -278,8 +266,7 @@ TEST_CASE("Schedule successful startup disarms failure cleanup and keeps normal TEST_CASE("Schedule full cleanup registry rejects init before acquiring a scheduler") { ark::plugin_manager manager; auto older = std::make_shared(0); - for (std::size_t index{}; index < ark::startup_cleanup_capacity; ++index) - { + for (std::size_t index{}; index < ark::startup_cleanup_capacity; ++index) { REQUIRE(manager.prepare_startup_cleanup("owner-" + std::to_string(index), "test", older, release_older)); } auto schedule = make_schedule(manager); @@ -349,12 +336,10 @@ TEST_CASE("Schedule attempted invalid registration remains unsafe even without a } int main(int argc, char** argv) { - if (argc == 2 && std::string_view(argv[1]) == "--allocation-failure") - { + if (argc == 2 && std::string_view(argv[1]) == "--allocation-failure") { ark::plugin_manager manager; auto older = std::make_shared(0); - if (!manager.prepare_startup_cleanup("older", "test", older, release_older)) - { + if (!manager.prepare_startup_cleanup("older", "test", older, release_older)) { exit_probe(2); } auto schedule = make_schedule(manager); @@ -364,22 +349,19 @@ int main(int argc, char** argv) { failing_module failure; manager.add_module("failure", &failure); // Prepare all owning call arguments before arming persistent rejection. - if (manager.start(0, {}, {}, {})) - { + if (manager.start(0, {}, {}, {})) { exit_probe(2); } reject_allocations = true; state.reset(); schedule.reset(); state = retained.lock(); - if (!state || !state->worker) - { + if (!state || !state->worker) { exit_probe(2); } const auto result = manager.cleanup_failed_startup(); if (result != ark::startup_cleanup_result::done || manager.cleanup_failed_startup() != result || - state->worker || !dispatcher_retired(state) || *older != 1 || retained.expired()) - { + state->worker || !dispatcher_retired(state) || *older != 1 || retained.expired()) { exit_probe(2); } std::fputs("Schedule startup allocation failure: dispatcher retired; workers joined; candidate gone; exit 1\n", diff --git a/tests/core/startup_cleanup.cpp b/tests/core/startup_cleanup.cpp index 017efb616..9737e418d 100644 --- a/tests/core/startup_cleanup.cpp +++ b/tests/core/startup_cleanup.cpp @@ -12,8 +12,7 @@ namespace { -struct owned_wheel -{ +struct owned_wheel { std::unique_ptr wheel; unsigned releases{}; ark::startup_cleanup_result result{ark::startup_cleanup_result::done}; @@ -24,31 +23,26 @@ struct owned_wheel ark::startup_cleanup_result release_wheel(void* pointer) { auto& context = *static_cast(pointer); ++context.releases; - if (context.manager) - { + if (context.manager) { CHECK(context.manager->cleanup_failed_startup() == ark::startup_cleanup_result::unsafe); CHECK_FALSE(context.manager->prepare_startup_cleanup("reentrant", "test", {}, release_wheel)); CHECK_THROWS_AS(context.manager->update(1), std::logic_error); CHECK_THROWS_AS(context.manager->add_module("forbidden", nullptr), std::logic_error); } - if (context.throw_release) - { + if (context.throw_release) { throw 42; } - if (context.result != ark::startup_cleanup_result::done) - { + if (context.result != ark::startup_cleanup_result::done) { return context.result; } - if (context.wheel) - { + if (context.wheel) { context.wheel->shut(); context.wheel.reset(); } return context.result; } -class wheel_module : public ark::module -{ +class wheel_module : public ark::module { public: wheel_module(std::shared_ptr context, unsigned phase, bool throws) : context_(std::move(context)) @@ -90,10 +84,8 @@ class wheel_module : public ark::module private: bool step(unsigned phase) { ++calls; - if (phase == failed_phase_) - { - if (throws_) - { + if (phase == failed_phase_) { + if (throws_) { throw std::runtime_error("private wheel startup failure"); } return false; @@ -109,10 +101,8 @@ class wheel_module : public ark::module } // namespace TEST_CASE("Startup cleanup owns capsules before acquisition and runs once after each failed phase") { - for (unsigned phase{}; phase < 4; ++phase) - { - for (bool throws : {false, true}) - { + for (unsigned phase{}; phase < 4; ++phase) { + for (bool throws : {false, true}) { ark::plugin_manager manager; auto context = std::make_shared(); context->manager = &manager; @@ -122,12 +112,9 @@ TEST_CASE("Startup cleanup owns capsules before acquisition and runs once after REQUIRE(context->wheel->initialized()); REQUIRE(manager.add_module("private-wheel", &module)); auto& tasks = manager.create_task_group(module); - if (throws) - { + if (throws) { CHECK_THROWS_AS(manager.start(1, {}, {}, {}), std::runtime_error); - } - else - { + } else { CHECK_FALSE(manager.start(1, {}, {}, {})); } CHECK(context->releases == 0); @@ -180,10 +167,8 @@ TEST_CASE("Startup cleanup rejects unsafe enrollment and only disarms on success TEST_CASE("Unsafe and throwing startup cleanup retain their capsule and never retry") { for (const auto result : {ark::startup_cleanup_result::unsafe, ark::startup_cleanup_result::failed, - ark::startup_cleanup_result::not_run}) - { - for (bool throws : {false, true}) - { + ark::startup_cleanup_result::not_run}) { + for (bool throws : {false, true}) { ark::plugin_manager manager; auto context = std::make_shared(); context->result = result; @@ -205,14 +190,12 @@ TEST_CASE("Unsafe and throwing startup cleanup retain their capsule and never re namespace { -struct cleanup_trace -{ +struct cleanup_trace { std::array calls{}; std::size_t count{}; }; -struct traced_context -{ +struct traced_context { cleanup_trace* trace{}; unsigned id{}; ark::startup_cleanup_result result{ark::startup_cleanup_result::done}; @@ -222,20 +205,17 @@ struct traced_context ark::startup_cleanup_result trace_cleanup(void* pointer) { auto& context = *static_cast(pointer); auto& trace = *context.trace; - if (trace.count < trace.calls.size()) - { + if (trace.count < trace.calls.size()) { trace.calls[trace.count] = context.id; } ++trace.count; - if (context.throws) - { + if (context.throws) { throw 17; } return context.result; } -class startup_failure_module final : public ark::module -{ +class startup_failure_module final : public ark::module { public: bool init() override { return false; @@ -255,8 +235,7 @@ TEST_CASE("Startup cleanup accepts sixteen independent owners and rejects withou ark::plugin_manager manager; startup_failure_module module; REQUIRE(manager.add_module("failure", &module)); - for (std::size_t index{}; index < resource_keys.size(); ++index) - { + for (std::size_t index{}; index < resource_keys.size(); ++index) { auto context = std::make_shared(); context->trace = &trace; context->id = static_cast(index); @@ -275,8 +254,7 @@ TEST_CASE("Startup cleanup accepts sixteen independent owners and rejects withou CHECK(overflow.use_count() == 1); CHECK(manager.cleanup_failed_startup() == ark::startup_cleanup_result::done); REQUIRE(trace.count == ark::startup_cleanup_capacity); - for (std::size_t index{}; index < trace.count; ++index) - { + for (std::size_t index{}; index < trace.count; ++index) { CHECK(trace.calls[index] == ark::startup_cleanup_capacity - index - 1); CHECK_FALSE(retained[index].expired()); } @@ -286,22 +264,18 @@ TEST_CASE("Startup cleanup accepts sixteen independent owners and rejects withou TEST_CASE("Startup cleanup stops at the first incomplete newer owner and retains all contexts") { for (const auto result : {ark::startup_cleanup_result::unsafe, ark::startup_cleanup_result::failed, - ark::startup_cleanup_result::not_run}) - { - for (bool throws : {false, true}) - { + ark::startup_cleanup_result::not_run}) { + for (bool throws : {false, true}) { cleanup_trace trace; ark::plugin_manager manager; startup_failure_module module; REQUIRE(manager.add_module("failure", &module)); std::array, 3> retained; - for (unsigned index{}; index < retained.size(); ++index) - { + for (unsigned index{}; index < retained.size(); ++index) { auto context = std::make_shared(); context->trace = &trace; context->id = index; - if (index == 1) - { + if (index == 1) { context->result = result; context->throws = throws; } @@ -316,8 +290,7 @@ TEST_CASE("Startup cleanup stops at the first incomplete newer owner and retains REQUIRE(trace.count == 2); CHECK(trace.calls[0] == 2); CHECK(trace.calls[1] == 1); - for (const auto& context : retained) - { + for (const auto& context : retained) { CHECK_FALSE(context.expired()); } } @@ -328,16 +301,14 @@ TEST_CASE("Successful startup disarms all owners and permits no late enrollment" cleanup_trace trace; ark::plugin_manager manager; std::array, 3> contexts; - for (std::size_t index{}; index < contexts.size(); ++index) - { + for (std::size_t index{}; index < contexts.size(); ++index) { contexts[index] = std::make_shared(); contexts[index]->trace = &trace; REQUIRE(manager.prepare_startup_cleanup(resource_keys[index], "plugin", contexts[index], trace_cleanup)); CHECK(contexts[index].use_count() == 2); } REQUIRE(manager.start(1, {}, {}, {})); - for (const auto& context : contexts) - { + for (const auto& context : contexts) { CHECK(context.use_count() == 1); } CHECK(trace.count == 0); diff --git a/tests/core/stream_allocation_diagnostics.hpp b/tests/core/stream_allocation_diagnostics.hpp index 1d54347f6..018c7f47f 100644 --- a/tests/core/stream_allocation_diagnostics.hpp +++ b/tests/core/stream_allocation_diagnostics.hpp @@ -10,8 +10,7 @@ namespace stream_test { // Only installed in the isolated, single-threaded allocation executables. No // C++ allocation or logging is needed if an injected failure hits noexcept code. -class allocation_diagnostic final -{ +class allocation_diagnostic final { public: allocation_diagnostic(const char* const& phase, const std::size_t& position, const std::size_t& count) noexcept : phase_(phase) @@ -32,15 +31,13 @@ class allocation_diagnostic final private: [[noreturn]] static void terminate() noexcept { - if (const auto* context = active_) - { + if (const auto* context = active_) { std::fprintf(stderr, "stream allocation terminate: phase=%s fail_at=%zu allocation_count=%zu\n", context->phase_, context->position_, context->count_); std::fflush(stderr); active_ = context->previous_context_; // Preserve doctest's existing crash reporting and failure exit. - if (context->previous_handler_) - { + if (context->previous_handler_) { context->previous_handler_(); } } diff --git a/tests/core/strings.cpp b/tests/core/strings.cpp index bc32622c4..f6f047f7f 100644 --- a/tests/core/strings.cpp +++ b/tests/core/strings.cpp @@ -9,8 +9,7 @@ #include DOCTEST_TEST_CASE("String utilities exclude the C-string terminator from character splits") { - for (const uint32_t limit : {0U, 1U, 2U}) - { + for (const uint32_t limit : {0U, 1U, 2U}) { const char input[] = {'a', 'b', 'c', '\0'}; const char empty[] = {'\0'}; std::vector parts{"existing"}; @@ -21,20 +20,16 @@ DOCTEST_TEST_CASE("String utilities exclude the C-string terminator from charact parts.clear(); ark::string_utils::split(parts, std::string("a\0b\0", 4), '\0', limit); - if (limit == 1) - { + if (limit == 1) { DOCTEST_CHECK(parts == std::vector{"a", std::string("b\0", 2)}); - } - else - { + } else { DOCTEST_CHECK(parts == std::vector{"a", "b"}); } } } DOCTEST_TEST_CASE("String utilities strip whole C strings without crossing the input range") { - for (const char direction : {'b', 'B', 'l', 'L', 'r', 'R'}) - { + for (const char direction : {'b', 'B', 'l', 'L', 'r', 'R'}) { DOCTEST_CHECK(ark::string_utils::strip("", " \t", direction).empty()); DOCTEST_CHECK(ark::string_utils::strip(" \t ", " \t", direction).empty()); DOCTEST_CHECK(ark::string_utils::strip("", 'x', direction).empty()); @@ -46,8 +41,7 @@ DOCTEST_TEST_CASE("String utilities strip whole C strings without crossing the i DOCTEST_CHECK(ark::string_utils::strip(high_bytes, high_bytes, direction).empty()); } - for (const char direction : {'b', 'B', 'x'}) - { + for (const char direction : {'b', 'B', 'x'}) { DOCTEST_CHECK(ark::string_utils::strip(" \tabc\t ", " \t", direction) == "abc"); DOCTEST_CHECK(ark::string_utils::strip("xxabcxx", 'x', direction) == "abc"); } @@ -58,8 +52,7 @@ DOCTEST_TEST_CASE("String utilities strip whole C strings without crossing the i } DOCTEST_TEST_CASE("String utilities treat empty patterns as no change") { - for (const uint32_t limit : {0U, 1U, 2U}) - { + for (const uint32_t limit : {0U, 1U, 2U}) { std::vector parts{"existing"}; ark::string_utils::split(parts, "abc", "", limit); DOCTEST_CHECK(parts == std::vector{"existing", "abc"}); @@ -71,8 +64,7 @@ DOCTEST_TEST_CASE("String utilities treat empty patterns as no change") { ark::string_utils::split(parts, std::string{}, "", limit); DOCTEST_CHECK(parts.size() == 1); - for (const auto replacement : {"", "x"}) - { + for (const auto replacement : {"", "x"}) { DOCTEST_CHECK(ark::string_utils::replace("abc", "", replacement, limit) == "abc"); DOCTEST_CHECK(ark::string_utils::replace(std::string("abc"), "", replacement, limit) == "abc"); DOCTEST_CHECK(ark::string_utils::replace("", "", replacement, limit).empty()); @@ -104,8 +96,7 @@ DOCTEST_TEST_CASE("String utility patterns retain split and replacement limits") ark::string_utils::split(parts, "a:b:c", ':', 2); DOCTEST_CHECK(parts == std::vector{"existing", "a", "b:c"}); - for (const auto text : {"xooxoox", "plain", ""}) - { + for (const auto text : {"xooxoox", "plain", ""}) { const std::string input(text); DOCTEST_CHECK(ark::string_utils::replace(text, "oo", "ee") == ark::string_utils::replace(input, "oo", "ee")); } diff --git a/tests/core/table_row_allocation.cpp b/tests/core/table_row_allocation.cpp index 56b905d17..d2e7f2ca5 100644 --- a/tests/core/table_row_allocation.cpp +++ b/tests/core/table_row_allocation.cpp @@ -44,28 +44,23 @@ void stop_observing_allocations() { } // namespace void* operator new(std::size_t size) { - if (observed_table) - { + if (observed_table) { ++allocation_calls; - if (observed_table->get_row_count() == initial_row_count) - { + if (observed_table->get_row_count() == initial_row_count) { insertion_allocation = allocation_calls; } - if (allocation_calls == throw_allocation) - { + if (allocation_calls == throw_allocation) { throw std::bad_alloc{}; } } - if (auto* value = std::malloc(size ? size : 1)) - { + if (auto* value = std::malloc(size ? size : 1)) { return value; } throw std::bad_alloc{}; } void operator delete(void* value) noexcept { - if (value && value == candidate_row) - { + if (value && value == candidate_row) { candidate_row = nullptr; ++candidate_releases; } @@ -79,23 +74,20 @@ void operator delete(void* value, std::size_t) noexcept { // Keep the production ARK_NEW hook unchanged. Successful allocations retain // ordinary new/delete pairing; only the armed nothrow allocation returns null. void* operator new(std::size_t size, const std::nothrow_t&) noexcept { - if (fail_next_nothrow) - { + if (fail_next_nothrow) { fail_next_nothrow = false; ++failed_allocations; return nullptr; } - try - { + try { auto* value = ::operator new(size); - if (observed_table) - { + if (observed_table) { candidate_row = value; } return value; + } catch (...) { + return nullptr; } - catch (...) - { return nullptr; } } void operator delete(void* value, const std::nothrow_t&) noexcept { @@ -113,8 +105,7 @@ std::shared_ptr table_metadata() { return metadata; } -class table_fixture -{ +class table_fixture { public: table_fixture() : table(metadata, [this](ark::mask_type, ark::node*, const ark::table_event_data& event, const ark::data&, @@ -148,8 +139,7 @@ TEST_CASE("Kernel table row insertion preserves automatic and explicit indices a CHECK(fixture.table.get_row_count() == 4); REQUIRE(fixture.events.size() == 4); const unsigned indices[]{1, 2, 7, 3}; - for (unsigned i = 0; i < 4; ++i) - { + for (unsigned i = 0; i < 4; ++i) { CHECK(fixture.events[i].row == indices[i]); CHECK(fixture.events[i].op_type == static_cast(ark::table_op_type::table_add)); } @@ -158,8 +148,7 @@ TEST_CASE("Kernel table row insertion preserves automatic and explicit indices a TEST_CASE("Kernel table callback exceptions preserve already published rows") { ark::table_impl table(table_metadata(), [](ark::mask_type, ark::node*, const ark::table_event_data& event, const ark::data&, const ark::data&) { - if (event.op_type == static_cast(ark::table_op_type::table_add)) - { + if (event.op_type == static_cast(ark::table_op_type::table_add)) { throw std::runtime_error("after publication"); } return 0; @@ -248,10 +237,11 @@ TEST_CASE("Kernel table insertion exceptions release only the unpublished row an const auto initial_releases = candidate_releases; bool threw = false; observe_allocations(fixture.table, insertion_site); - try - { static_cast(fixture.table.add_row(requested)); } - catch (const std::bad_alloc&) - { threw = true; } + try { + static_cast(fixture.table.add_row(requested)); + } catch (const std::bad_alloc&) { + threw = true; + } stop_observing_allocations(); CHECK(threw); CHECK(ark::kernel_nested_snapshot_test_access::row_counter(fixture.table) == initial_incarnation); @@ -266,8 +256,7 @@ TEST_CASE("Kernel table insertion exceptions release only the unpublished row an CHECK(candidate_row == nullptr); // Clean up a leaked candidate when checking an unfixed implementation. // An already published row remains owned by the table. - if (candidate_row && fixture.table.find_row(expected) == nullptr) - { + if (candidate_row && fixture.table.find_row(expected) == nullptr) { delete static_cast(candidate_row); } diff --git a/tests/core/tasks.cpp b/tests/core/tasks.cpp index 31408a0c6..c52fb866e 100644 --- a/tests/core/tasks.cpp +++ b/tests/core/tasks.cpp @@ -32,12 +32,10 @@ ark::task<> receive_value(std::string& result, unsigned& resumed) { } ark::task<> wait_for_cancel(asio::steady_timer& timer, unsigned& cancelled) { - try - { co_await timer.async_wait(asio::use_awaitable); } - catch (const asio::system_error& error) - { - if (error.code() != asio::error::operation_aborted) - { + try { + co_await timer.async_wait(asio::use_awaitable); + } catch (const asio::system_error& error) { + if (error.code() != asio::error::operation_aborted) { throw; } ++cancelled; @@ -63,8 +61,7 @@ TEST_CASE("Public task SDK returns owning values after admission stops") { CHECK_FALSE(tasks.closed()); CHECK(tasks.poll(0) == 0); CHECK(result.empty()); - for (unsigned step = 0; step < 32 && !tasks.closed(); ++step) - { + for (unsigned step = 0; step < 32 && !tasks.closed(); ++step) { tasks.poll(1); } CHECK(tasks.closed()); @@ -97,8 +94,7 @@ TEST_CASE("Public task SDK cancellation remains explicit and owner polled") { tasks.stop_accepting(); CHECK(completed == 0); CHECK_FALSE(tasks.closed()); - for (unsigned step = 0; step < 32 && !tasks.closed(); ++step) - { + for (unsigned step = 0; step < 32 && !tasks.closed(); ++step) { tasks.poll(1); } CHECK(tasks.closed()); @@ -114,14 +110,16 @@ TEST_CASE("Public task SDK rejects invalid owners and construction limits") { ark::task_group tasks(runtime); unsigned rejected{}; std::thread worker([&] { - try - { tasks.poll(); } - catch (const std::logic_error&) - { ++rejected; } - try - { tasks.cancel_all(); } - catch (const std::logic_error&) - { ++rejected; } + try { + tasks.poll(); + } catch (const std::logic_error&) { + ++rejected; + } + try { + tasks.cancel_all(); + } catch (const std::logic_error&) { + ++rejected; + } }); worker.join(); CHECK(rejected == 2); diff --git a/tests/core/templates.cpp b/tests/core/templates.cpp index e420f680f..c843ae3f3 100644 --- a/tests/core/templates.cpp +++ b/tests/core/templates.cpp @@ -46,8 +46,7 @@ DOCTEST_TEST_CASE("Plugin-manager typed lookup exposes the requested module type } DOCTEST_TEST_CASE("Unsigned 32-bit conversion preserves decimal boundaries and accepted prefixes") { - struct conversion_case - { + struct conversion_case { const char* text; std::uint32_t expected; }; @@ -55,8 +54,7 @@ DOCTEST_TEST_CASE("Unsigned 32-bit conversion preserves decimal boundaries and a const conversion_case cases[] = {{"0", 0u}, {"2147483647", 2147483647u}, {"2147483648", 2147483648u}, {"4045620583", 4045620583u}, {"4294967295", std::numeric_limits::max()}, {" \t+42suffix", 42u}, {"-1", std::numeric_limits::max()}}; - for (const auto& value : cases) - { + for (const auto& value : cases) { DOCTEST_CAPTURE(value.text); DOCTEST_CHECK(lexical_cast(std::string(value.text)) == value.expected); DOCTEST_CHECK(lexical_cast(value.text) == value.expected); @@ -64,8 +62,7 @@ DOCTEST_TEST_CASE("Unsigned 32-bit conversion preserves decimal boundaries and a } DOCTEST_TEST_CASE("Unsigned 64-bit conversion preserves decimal boundaries and accepted prefixes") { - struct conversion_case - { + struct conversion_case { const char* text; std::uint64_t expected; }; @@ -75,8 +72,7 @@ DOCTEST_TEST_CASE("Unsigned 64-bit conversion preserves decimal boundaries and a {"18446744073709551614", 18446744073709551614ULL}, {"18446744073709551615", std::numeric_limits::max()}, {" \t+42suffix", 42ULL}, {"-1", std::numeric_limits::max()}}; - for (const auto& value : cases) - { + for (const auto& value : cases) { DOCTEST_CAPTURE(std::string(value.text)); DOCTEST_CHECK(lexical_cast(std::string(value.text)) == value.expected); DOCTEST_CHECK(lexical_cast(value.text) == value.expected); diff --git a/tests/core/thread_pool_construction.cpp b/tests/core/thread_pool_construction.cpp index 7fcedf4c5..fe10d85c5 100644 --- a/tests/core/thread_pool_construction.cpp +++ b/tests/core/thread_pool_construction.cpp @@ -43,19 +43,15 @@ namespace { int process_threads() noexcept { #ifdef _WIN32 const auto snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); - if (snapshot == INVALID_HANDLE_VALUE) - { + if (snapshot == INVALID_HANDLE_VALUE) { return -1; } THREADENTRY32 entry{}; entry.dwSize = sizeof(entry); int count{}; - if (Thread32First(snapshot, &entry)) - { - do - { - if (entry.th32OwnerProcessID == GetCurrentProcessId()) - { + if (Thread32First(snapshot, &entry)) { + do { + if (entry.th32OwnerProcessID == GetCurrentProcessId()) { ++count; } } while (Thread32Next(snapshot, &entry)); @@ -65,27 +61,22 @@ int process_threads() noexcept { #elif defined(__APPLE__) thread_act_array_t threads{}; mach_msg_type_number_t count{}; - if (task_threads(mach_task_self(), &threads, &count) != KERN_SUCCESS) - { + if (task_threads(mach_task_self(), &threads, &count) != KERN_SUCCESS) { return -1; } - for (mach_msg_type_number_t index{}; index < count; ++index) - { + for (mach_msg_type_number_t index{}; index < count; ++index) { mach_port_deallocate(mach_task_self(), threads[index]); } vm_deallocate(mach_task_self(), reinterpret_cast(threads), count * sizeof(thread_t)); return static_cast(count); #else auto* directory = opendir("/proc/self/task"); - if (!directory) - { + if (!directory) { return -1; } int count{}; - while (const auto* entry = readdir(directory)) - { - if (entry->d_name[0] != '.') - { + while (const auto* entry = readdir(directory)) { + if (entry->d_name[0] != '.') { ++count; } } @@ -104,8 +95,7 @@ std::size_t active_budget{}; void before_allocation(std::size_t size) { ++attempts; - if (armed && remaining-- == 0) - { + if (armed && remaining-- == 0) { // Stay failed: rollback, exception propagation and joining must not // depend on another successful allocation on this owner thread. remaining = 0; @@ -118,8 +108,7 @@ void before_allocation(std::size_t size) { void* allocate(std::size_t size) { before_allocation(size); - if (auto* pointer = std::malloc(size ? size : 1)) - { + if (auto* pointer = std::malloc(size ? size : 1)) { return pointer; } throw std::bad_alloc{}; @@ -128,14 +117,12 @@ void* allocate(std::size_t size) { void* allocate_aligned(std::size_t size, std::size_t alignment) { before_allocation(size); #ifdef _WIN32 - if (auto* pointer = _aligned_malloc(size ? size : 1, alignment)) - { + if (auto* pointer = _aligned_malloc(size ? size : 1, alignment)) { return pointer; } #else void* pointer{}; - if (posix_memalign(&pointer, alignment, size ? size : 1) == 0) - { + if (posix_memalign(&pointer, alignment, size ? size : 1) == 0) { return pointer; } #endif @@ -202,17 +189,19 @@ void operator delete[](void* pointer, std::size_t, std::align_val_t) noexcept { // Keep every nothrow form in the same allocation family under sanitizers. void* operator new(std::size_t size, const std::nothrow_t&) noexcept { - try - { return ::operator new(size); } - catch (...) - { return nullptr; } + try { + return ::operator new(size); + } catch (...) { + return nullptr; + } } void* operator new[](std::size_t size, const std::nothrow_t&) noexcept { - try - { return ::operator new[](size); } - catch (...) - { return nullptr; } + try { + return ::operator new[](size); + } catch (...) { + return nullptr; + } } void operator delete(void* pointer, const std::nothrow_t&) noexcept { @@ -224,17 +213,19 @@ void operator delete[](void* pointer, const std::nothrow_t&) noexcept { } void* operator new(std::size_t size, std::align_val_t alignment, const std::nothrow_t&) noexcept { - try - { return ::operator new(size, alignment); } - catch (...) - { return nullptr; } + try { + return ::operator new(size, alignment); + } catch (...) { + return nullptr; + } } void* operator new[](std::size_t size, std::align_val_t alignment, const std::nothrow_t&) noexcept { - try - { return ::operator new[](size, alignment); } - catch (...) - { return nullptr; } + try { + return ::operator new[](size, alignment); + } catch (...) { + return nullptr; + } } void operator delete(void* pointer, std::align_val_t alignment, const std::nothrow_t&) noexcept { @@ -258,26 +249,20 @@ void arm(std::size_t index) { int settled_process_threads() { auto count = process_threads(); - if (count < 0) - { + if (count < 0) { return count; } auto stable_since = std::chrono::steady_clock::now(); const auto deadline = stable_since + std::chrono::seconds(2); - while (std::chrono::steady_clock::now() < deadline) - { + while (std::chrono::steady_clock::now() < deadline) { const auto current = process_threads(); - if (current < 0) - { + if (current < 0) { return current; } - if (current != count) - { + if (current != count) { count = current; stable_since = std::chrono::steady_clock::now(); - } - else if (std::chrono::steady_clock::now() - stable_since >= std::chrono::milliseconds(100)) - { + } else if (std::chrono::steady_clock::now() - stable_since >= std::chrono::milliseconds(100)) { return count; } std::this_thread::yield(); @@ -287,10 +272,8 @@ int settled_process_threads() { bool workers_retired() { const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); - while (process_threads() != baseline_threads) - { - if (std::chrono::steady_clock::now() >= deadline) - { + while (process_threads() != baseline_threads) { + if (std::chrono::steady_clock::now() >= deadline) { return false; } std::this_thread::yield(); @@ -304,21 +287,17 @@ int constructor_failure(std::size_t index) { std::thread runtime_warmup([] {}); runtime_warmup.join(); baseline_threads = settled_process_threads(); - if (baseline_threads < 1) - { + if (baseline_threads < 1) { return 20; } bool threw{}; arm(index); active_stage = "constructing pool"; - try - { + try { ctpl::thread_pool pool(4); // Destruction also runs with the persistent owner-thread fault armed. active_stage = "pool constructed"; - } - catch (const std::bad_alloc&) - { + } catch (const std::bad_alloc&) { active_stage = "caught bad_alloc"; threw = true; } @@ -326,8 +305,7 @@ int constructor_failure(std::size_t index) { const bool retired = workers_retired(); const bool persistent = armed && rejected == (threw ? 1u : 0u); armed = false; - if (!retired || !persistent) - { + if (!retired || !persistent) { std::fprintf(stderr, "constructor budget=%zu retired=%d persistent=%d baseline=%d failure=%d current=%d attempts=%zu " "rejected=%zu\n", @@ -337,8 +315,7 @@ int constructor_failure(std::size_t index) { return !threw ? no_failure : threads_at_failure > baseline_threads ? partial_workers : 0; } -struct capture -{ +struct capture { unsigned& destroyed; ~capture() { @@ -346,8 +323,7 @@ struct capture } }; -struct submission -{ +struct submission { std::shared_ptr owner; std::atomic* calls; @@ -363,8 +339,7 @@ struct submission }; std::future submit(ctpl::thread_pool& pool, submission&& callback, bool variadic) { - if (variadic) - { + if (variadic) { return pool.push(std::move(callback), 7); } return pool.push(std::move(callback)); @@ -377,8 +352,7 @@ std::size_t queue_boundary(bool variadic) { ctpl::thread_pool pool(0); std::atomic calls{}; std::array counts{}; - for (auto& count : counts) - { + for (auto& count : counts) { submission callback{{}, &calls}; const auto before = attempts; auto future = submit(pool, std::move(callback), variadic); @@ -396,37 +370,34 @@ int submission_failure(std::size_t index, bool variadic, std::size_t boundary) { bool threw{}; { ctpl::thread_pool pool(0); - for (std::size_t count{}; count < boundary; ++count) - { + for (std::size_t count{}; count < boundary; ++count) { auto future = submit(pool, submission{{}, &calls}, variadic); } // Prepare all call arguments before arming; rejected allocations must // come from the actual push body, including its real queue insertion. submission callback{owner, &calls}; arm(index); - try - { auto future = submit(pool, std::move(callback), variadic); } - catch (const std::bad_alloc&) - { threw = true; } + try { + auto future = submit(pool, std::move(callback), variadic); + } catch (const std::bad_alloc&) { + threw = true; + } callback.owner.reset(); - if (!armed || rejected != (threw ? 1u : 0u) || owner.use_count() != (threw ? 1 : 2) || calls != 0) - { + if (!armed || rejected != (threw ? 1u : 0u) || owner.use_count() != (threw ? 1 : 2) || calls != 0) { armed = false; return 22; } // Discarding queued wrappers must release every capture without running // callbacks, while the allocation failure is still armed. pool.stop(false); - if (owner.use_count() != 1 || calls != 0 || rejected != (threw ? 1u : 0u)) - { + if (owner.use_count() != 1 || calls != 0 || rejected != (threw ? 1u : 0u)) { armed = false; return 23; } armed = false; } owner.reset(); - if (destroyed != 1) - { + if (destroyed != 1) { return 24; } return threw ? 0 : no_failure; @@ -435,8 +406,7 @@ int submission_failure(std::size_t index, bool variadic, std::size_t boundary) { int run_child(const char* executable, const char* mode, std::size_t index, std::size_t boundary, std::chrono::steady_clock::time_point controller_deadline) { const auto deadline = std::min(controller_deadline, std::chrono::steady_clock::now() + std::chrono::seconds(5)); - if (std::chrono::steady_clock::now() >= deadline) - { + if (std::chrono::steady_clock::now() >= deadline) { return 91; } const auto index_text = std::to_string(index); @@ -446,8 +416,7 @@ int run_child(const char* executable, const char* mode, std::size_t index, std:: STARTUPINFOA startup{}; startup.cb = sizeof(startup); PROCESS_INFORMATION process{}; - if (!CreateProcessA(executable, command.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup, &process)) - { + if (!CreateProcessA(executable, command.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup, &process)) { return 90; } const auto milliseconds = @@ -455,12 +424,9 @@ int run_child(const char* executable, const char* mode, std::size_t index, std:: const auto wait = WaitForSingleObject(process.hProcess, static_cast(std::max(0, milliseconds))); DWORD code = 91; - if (wait == WAIT_OBJECT_0) - { + if (wait == WAIT_OBJECT_0) { GetExitCodeProcess(process.hProcess, &code); - } - else - { + } else { TerminateProcess(process.hProcess, 91); WaitForSingleObject(process.hProcess, 1000); } @@ -469,29 +435,23 @@ int run_child(const char* executable, const char* mode, std::size_t index, std:: return static_cast(code); #else const auto child = fork(); - if (child < 0) - { + if (child < 0) { return 90; } - if (child == 0) - { + if (child == 0) { execlp(executable, executable, mode, index_text.c_str(), boundary_text.c_str(), static_cast(nullptr)); std::_Exit(90); } int status{}; - while (true) - { + while (true) { const auto result = waitpid(child, &status, WNOHANG); - if (result == child) - { + if (result == child) { break; } - if (result < 0 && errno != EINTR) - { + if (result < 0 && errno != EINTR) { return 90; } - if (std::chrono::steady_clock::now() >= deadline) - { + if (std::chrono::steady_clock::now() >= deadline) { kill(child, SIGKILL); waitpid(child, &status, 0); return 91; @@ -506,25 +466,19 @@ int sweep(const char* executable, const char* mode, std::size_t boundary, std::chrono::steady_clock::time_point controller_deadline) { unsigned passed{}, partial{}, failed{}; bool succeeded{}; - for (std::size_t index{}; index < 128; ++index) - { + for (std::size_t index{}; index < 128; ++index) { const auto code = run_child(executable, mode, index, boundary, controller_deadline); - if (code == no_failure) - { + if (code == no_failure) { succeeded = true; break; } - if (code == 0 || code == partial_workers) - { + if (code == 0 || code == partial_workers) { ++passed; partial += code == partial_workers; - } - else - { + } else { ++failed; std::printf("%s allocation %zu failed: child exit %d\n", mode, index, code); - if (code >= 90) - { + if (code >= 90) { break; // a timeout or process-control failure must not start another child } } @@ -540,16 +494,16 @@ int sweep(const char* executable, const char* mode, std::size_t boundary, int main(int argc, char** argv) { std::set_terminate([]() noexcept { int exception_kind{}; - if (auto exception = std::current_exception()) - { - try - { std::rethrow_exception(exception); } - catch (const std::bad_alloc&) - { exception_kind = 1; } - catch (const std::exception&) - { exception_kind = 2; } - catch (...) - { exception_kind = 3; } + if (auto exception = std::current_exception()) { + try { + std::rethrow_exception(exception); + } catch (const std::bad_alloc&) { + exception_kind = 1; + } catch (const std::exception&) { + exception_kind = 2; + } catch (...) { + exception_kind = 3; + } } std::fprintf(stderr, "terminate mode=%s stage=%s budget=%zu exception=%d uncaught=%d armed=%d remaining=%zu attempts=%zu " @@ -559,32 +513,27 @@ int main(int argc, char** argv) { std::fflush(stderr); std::_Exit(86); }); - if (argc == 4) - { + if (argc == 4) { const auto index = static_cast(std::strtoull(argv[2], nullptr, 10)); const auto boundary = static_cast(std::strtoull(argv[3], nullptr, 10)); active_mode = argv[1]; active_stage = "child dispatch"; active_budget = index; - if (std::string_view(argv[1]) == "constructor") - { + if (std::string_view(argv[1]) == "constructor") { return constructor_failure(index); } - if (std::string_view(argv[1]) == "single" || std::string_view(argv[1]) == "variadic") - { + if (std::string_view(argv[1]) == "single" || std::string_view(argv[1]) == "variadic") { return submission_failure(index, std::string_view(argv[1]) == "variadic", boundary); } return 2; } - if (argc != 1) - { + if (argc != 1) { return 2; } const auto controller_deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30); const auto single = queue_boundary(false); const auto variadic = queue_boundary(true); - if (single == 2048 || variadic == 2048) - { + if (single == 2048 || variadic == 2048) { std::fputs("Could not discover a real queue insertion allocation\n", stderr); return 25; } diff --git a/tests/core/timer_hooks.cpp b/tests/core/timer_hooks.cpp index 078df592b..983f53b1b 100644 --- a/tests/core/timer_hooks.cpp +++ b/tests/core/timer_hooks.cpp @@ -8,8 +8,7 @@ namespace { -struct allocation_tag -{ +struct allocation_tag { ~allocation_tag(); mutable bool allocated{}; }; @@ -22,30 +21,24 @@ bool fail_standard_allocation{}; std::size_t fail_container_after{std::numeric_limits::max()}; allocation_tag::~allocation_tag() { - if (!allocated) - { + if (!allocated) { return; } // A placement argument outlives construction through the full new-expression. // Arm after construction so MSVC's noexcept Debug iterator proxies cannot fail. - if (fail_container_after == 0) - { + if (fail_container_after == 0) { fail_container_after = std::numeric_limits::max(); fail_standard_allocation = true; - } - else if (fail_container_after != std::numeric_limits::max()) - { + } else if (fail_container_after != std::numeric_limits::max()) { --fail_container_after; } } bool should_fail() { - if (fail_after == std::numeric_limits::max()) - { + if (fail_after == std::numeric_limits::max()) { return false; } - if (fail_after > 0) - { + if (fail_after > 0) { --fail_after; return false; } @@ -55,12 +48,10 @@ bool should_fail() { template void release(T*& value) noexcept { - if (!value) - { + if (!value) { return; } - if (live.erase(value) != 1) - { + if (live.erase(value) != 1) { std::abort(); } ++releases; @@ -71,13 +62,11 @@ void release(T*& value) noexcept { } // namespace void* operator new(std::size_t size) { - if (fail_standard_allocation) - { + if (fail_standard_allocation) { fail_standard_allocation = false; throw std::bad_alloc{}; } - if (auto* value = std::malloc(size ? size : 1)) - { + if (auto* value = std::malloc(size ? size : 1)) { return value; } throw std::bad_alloc{}; @@ -92,8 +81,7 @@ void operator delete(void* value, std::size_t) noexcept { } void* operator new(std::size_t size, const allocation_tag& tag) noexcept { - if (should_fail()) - { + if (should_fail()) { return nullptr; } auto* value = ::operator new(size); @@ -129,8 +117,7 @@ TEST_CASE("Time wheel owns cancelled timers until shutdown") { } TEST_CASE("Time wheel partial initialization null failures release every allocation") { - for (const std::size_t position : {0u, 17u, ark::free_timer_size, ark::free_timer_size + ark::tv_num - 1}) - { + for (const std::size_t position : {0u, 17u, ark::free_timer_size, ark::free_timer_size + ark::tv_num - 1}) { REQUIRE(live.empty()); ark::time_wheel_manager manager; fail_after = position; @@ -145,8 +132,7 @@ TEST_CASE("Time wheel partial initialization null failures release every allocat } TEST_CASE("Time wheel container allocation exceptions unwind initialization without leaking") { - for (const std::size_t position : {0u, 17u, ark::free_timer_size, ark::free_timer_size + ark::tv_num - 1}) - { + for (const std::size_t position : {0u, 17u, ark::free_timer_size, ark::free_timer_size + ark::tv_num - 1}) { REQUIRE(live.empty()); ark::time_wheel_manager manager; fail_container_after = position; @@ -160,8 +146,7 @@ TEST_CASE("Time wheel pool exhaustion returns zero for a null allocation and rec REQUIRE(live.empty()); ark::time_wheel_manager manager; manager.init(0); - for (std::size_t i = 0; i < ark::free_timer_size; ++i) - { + for (std::size_t i = 0; i < ark::free_timer_size; ++i) { CHECK(manager.add_timer(ark::null_guid, 1, 1h, [](auto, const auto&) {}) != 0); } fail_after = 0; @@ -195,8 +180,7 @@ TEST_CASE("Time wheel growth container exception releases the uncommitted timer" REQUIRE(live.empty()); ark::time_wheel_manager manager; manager.init(0); - for (std::size_t i = 0; i < ark::free_timer_size; ++i) - { + for (std::size_t i = 0; i < ark::free_timer_size; ++i) { manager.add_timer(ark::null_guid, 1, 1h, [](auto, const auto&) {}); } const auto initial_live = live.size(); @@ -226,8 +210,7 @@ TEST_CASE("Time wheel destructor releases active completed and cancelled entries } TEST_CASE("Timer container failure injection starts after noexcept object construction") { - class proxy_probe - { + class proxy_probe { public: proxy_probe() noexcept : proxy_(::operator new(1)) { @@ -247,13 +230,12 @@ TEST_CASE("Timer container failure injection starts after noexcept object constr fail_container_after = 0; auto* value = ARK_NEW proxy_probe; bool threw{}; - try - { + try { auto* storage = ::operator new(1); ::operator delete(storage); + } catch (const std::bad_alloc&) { + threw = true; } - catch (const std::bad_alloc&) - { threw = true; } CHECK(threw); CHECK_FALSE(fail_standard_allocation); release(value); @@ -262,8 +244,7 @@ TEST_CASE("Timer container failure injection starts after noexcept object constr } TEST_CASE("Timer hook constructor failure releases storage without arming a later allocation") { - class throwing_probe - { + class throwing_probe { public: throwing_probe() { throw std::bad_alloc{}; diff --git a/tests/core/timer_module_init.cpp b/tests/core/timer_module_init.cpp index ec01ccd14..36bf00e9e 100644 --- a/tests/core/timer_module_init.cpp +++ b/tests/core/timer_module_init.cpp @@ -27,15 +27,13 @@ std::array live_wheel_allocations{}; std::size_t live_count() { std::size_t count{}; - for (auto* pointer : live_wheel_allocations) - { + for (auto* pointer : live_wheel_allocations) { count += pointer != nullptr; } return count; } -class receiver -{ +class receiver { public: void on_timer(std::uint64_t, const ark::guid_t&) { ++calls; @@ -44,20 +42,16 @@ class receiver unsigned calls{}; }; -class later_failure final : public ark::module -{ +class later_failure final : public ark::module { public: bool post_init() override { - if (arm) - { + if (arm) { id = timer->add_forever_timer(ark::null_guid, std::chrono::milliseconds(10), &target, &receiver::on_timer); - if (remove) - { + if (remove) { removed = timer->remove_timer(id); } } - if (persistent_failure) - { + if (persistent_failure) { fail_allocations = true; throw std::bad_alloc{}; } @@ -84,8 +78,7 @@ class later_failure final : public ark::module unsigned normal_stops{}; }; -struct independent_resource -{ +struct independent_resource { unsigned releases{}; std::size_t wheel_storage_at_release{}; }; @@ -97,13 +90,11 @@ ark::startup_cleanup_result release_independent_resource(void* pointer) { return ark::startup_cleanup_result::done; } -class enrolling_failure final : public ark::module -{ +class enrolling_failure final : public ark::module { public: bool post_init() override { enrolled = manager->prepare_startup_cleanup("after_timer", "test", resource, release_independent_resource); - if (arm) - { + if (arm) { timer_id = timer->add_forever_timer(ark::null_guid, std::chrono::milliseconds(10), &target, &receiver::on_timer); } @@ -125,14 +116,11 @@ class enrolling_failure final : public ark::module // The fixed array tracks real production ARK_NEW storage without allocating. void* operator new(std::size_t size) { ++allocation_attempts; - if (fail_standard_remaining && --fail_standard_remaining == 0) - { + if (fail_standard_remaining && --fail_standard_remaining == 0) { throw std::bad_alloc{}; } - if (!fail_allocations) - { - if (auto* pointer = std::malloc(size ? size : 1)) - { + if (!fail_allocations) { + if (auto* pointer = std::malloc(size ? size : 1)) { return pointer; } } @@ -144,10 +132,8 @@ void* operator new[](std::size_t size) { } void operator delete(void* pointer) noexcept { - for (auto& live : live_wheel_allocations) - { - if (live == pointer) - { + for (auto& live : live_wheel_allocations) { + if (live == pointer) { live = nullptr; break; } @@ -169,20 +155,15 @@ void operator delete[](void* pointer, std::size_t) noexcept { void* operator new(std::size_t size, const std::nothrow_t&) noexcept { ++nothrow_calls; - if (fail_remaining && --fail_remaining == 0) - { + if (fail_remaining && --fail_remaining == 0) { return nullptr; } - try - { + try { auto* pointer = ::operator new(size); - for (auto& live : live_wheel_allocations) - { - if (!live) - { + for (auto& live : live_wheel_allocations) { + if (!live) { live = pointer; - if (fail_after_timer && --fail_after_timer == 0) - { + if (fail_after_timer && --fail_after_timer == 0) { // Only inject at time_wheel_data (no allocating constructor), // before the following list insertion, never a Debug STL proxy. fail_allocations = true; @@ -191,9 +172,9 @@ void* operator new(std::size_t size, const std::nothrow_t&) noexcept { } } std::abort(); + } catch (...) { + return nullptr; } - catch (...) - { return nullptr; } } void operator delete(void* value, const std::nothrow_t&) noexcept { @@ -201,10 +182,11 @@ void operator delete(void* value, const std::nothrow_t&) noexcept { } void* operator new[](std::size_t size, const std::nothrow_t&) noexcept { - try - { return ::operator new[](size); } - catch (...) - { return nullptr; } + try { + return ::operator new[](size); + } catch (...) { + return nullptr; + } } void operator delete[](void* value, const std::nothrow_t&) noexcept { @@ -212,8 +194,7 @@ void operator delete[](void* value, const std::nothrow_t&) noexcept { } TEST_CASE("Production timer module rejects null allocations without continuing initialization") { - for (const std::size_t ordinal : {1u, 18u, ark::free_timer_size + 1, ark::free_timer_size + ark::tv_num}) - { + for (const std::size_t ordinal : {1u, 18u, ark::free_timer_size + 1, ark::free_timer_size + ark::tv_num}) { ark::plugin_manager manager; auto timer = ark::detail::make_timer_module(); timer->set_plugin_manager(&manager); @@ -229,8 +210,7 @@ TEST_CASE("Production timer module rejects null allocations without continuing i } TEST_CASE("Production timer startup releases partial null allocations exactly once") { - for (const std::size_t ordinal : {1u, 18u, ark::free_timer_size + 1, ark::free_timer_size + ark::tv_num}) - { + for (const std::size_t ordinal : {1u, 18u, ark::free_timer_size + 1, ark::free_timer_size + ark::tv_num}) { ark::plugin_manager manager; auto timer = ark::detail::make_timer_module(); timer->set_plugin_manager(&manager); @@ -246,18 +226,18 @@ TEST_CASE("Production timer startup releases partial null allocations exactly on } TEST_CASE("Production timer startup cleans up under persistent container allocation failure") { - for (const std::size_t ordinal : {1u, 18u}) - { + for (const std::size_t ordinal : {1u, 18u}) { ark::plugin_manager manager; auto timer = ark::detail::make_timer_module(); timer->set_plugin_manager(&manager); REQUIRE(manager.add_module("Timer", timer.get())); fail_after_timer = ordinal; bool threw{}; - try - { (void)manager.start(1, {}, {}, {}); } - catch (const std::bad_alloc&) - { threw = true; } + try { + (void)manager.start(1, {}, {}, {}); + } catch (const std::bad_alloc&) { + threw = true; + } const auto attempts = allocation_attempts; const auto first = manager.cleanup_failed_startup(); const auto second = manager.cleanup_failed_startup(); @@ -278,10 +258,11 @@ TEST_CASE("Production timer capsule allocation failure precedes acquisition") { const auto calls = nothrow_calls; fail_allocations = true; bool threw{}; - try - { (void)timer->init(); } - catch (const std::bad_alloc&) - { threw = true; } + try { + (void)timer->init(); + } catch (const std::bad_alloc&) { + threw = true; + } fail_allocations = false; CHECK(threw); CHECK(nothrow_calls == calls); @@ -304,8 +285,7 @@ TEST_CASE("Production timer rejected enrollment acquires no wheel storage") { } TEST_CASE("Production Timer composes with independent cleanup owners and retains unsafe predecessors") { - for (const bool arm : {false, true}) - { + for (const bool arm : {false, true}) { ark::plugin_manager manager; auto before = std::make_shared(); auto after = std::make_shared(); @@ -334,8 +314,7 @@ TEST_CASE("Production Timer composes with independent cleanup owners and retains CHECK(after->releases == 1); CHECK(after->wheel_storage_at_release == ark::free_timer_size + ark::tv_num); CHECK(later.target.calls == 0); - if (arm) - { + if (arm) { REQUIRE(later.timer_id != 0); CHECK(result == ark::startup_cleanup_result::unsafe); CHECK(before->releases == 0); @@ -345,9 +324,7 @@ TEST_CASE("Production Timer composes with independent cleanup owners and retains CHECK(timer->pre_shut()); CHECK(manager.cleanup_failed_startup() == ark::startup_cleanup_result::unsafe); CHECK(before->releases == 0); - } - else - { + } else { CHECK(result == ark::startup_cleanup_result::done); CHECK(before->releases == 1); CHECK(before->wheel_storage_at_release == 0); @@ -359,8 +336,7 @@ TEST_CASE("Production Timer composes with independent cleanup owners and retains TEST_CASE("Production Timer rejects a full cleanup registry before wheel acquisition") { ark::plugin_manager manager; std::array, ark::startup_cleanup_capacity> resources; - for (std::size_t index{}; index < resources.size(); ++index) - { + for (std::size_t index{}; index < resources.size(); ++index) { resources[index] = std::make_shared(); REQUIRE(manager.prepare_startup_cleanup( "external_" + std::to_string(index), "test", resources[index], release_independent_resource)); @@ -373,8 +349,7 @@ TEST_CASE("Production Timer rejects a full cleanup registry before wheel acquisi CHECK(nothrow_calls == calls); CHECK(live_count() == 0); CHECK(manager.cleanup_failed_startup() == ark::startup_cleanup_result::done); - for (const auto& resource : resources) - { + for (const auto& resource : resources) { CHECK(resource->releases == 1); CHECK(resource->wheel_storage_at_release == 0); } @@ -388,10 +363,11 @@ TEST_CASE("Production timer wheel object allocation failure leaves an independen // allocate; the second allocation attempts to construct the wheel itself. fail_standard_remaining = 2; bool threw{}; - try - { (void)timer->init(); } - catch (const std::bad_alloc&) - { threw = true; } + try { + (void)timer->init(); + } catch (const std::bad_alloc&) { + threw = true; + } REQUIRE(threw); CHECK(fail_standard_remaining == 0); CHECK(live_count() == 0); @@ -405,12 +381,9 @@ TEST_CASE("Production timer wheel object allocation failure leaves an independen } TEST_CASE("Production timer later startup failure releases only callback-free storage") { - for (bool arm : {false, true}) - { - for (bool remove : {false, true}) - { - for (bool persistent_failure : {false, true}) - { + for (bool arm : {false, true}) { + for (bool remove : {false, true}) { + for (bool persistent_failure : {false, true}) { ark::plugin_manager manager; auto timer = ark::detail::make_timer_module(); timer->set_plugin_manager(&manager); @@ -422,10 +395,11 @@ TEST_CASE("Production timer later startup failure releases only callback-free st REQUIRE(manager.add_module("Timer", timer.get())); REQUIRE(manager.add_module("later", &later)); bool returned{}, threw{}; - try - { returned = manager.start(1, {}, {}, {}); } - catch (const std::bad_alloc&) - { threw = true; } + try { + returned = manager.start(1, {}, {}, {}); + } catch (const std::bad_alloc&) { + threw = true; + } const auto live_before = live_count(); const auto attempts = allocation_attempts; const auto result = manager.cleanup_failed_startup(); @@ -439,17 +413,14 @@ TEST_CASE("Production timer later startup failure releases only callback-free st CHECK(repeated == result); CHECK(later.normal_stops == 0); CHECK(later.target.calls == 0); - if (arm && !remove) - { + if (arm && !remove) { CHECK(result == ark::startup_cleanup_result::unsafe); CHECK(live_count() == live_before); CHECK(timer->remove_timer(later.id)); // A later change cannot retry an already-entered action. CHECK(manager.cleanup_failed_startup() == ark::startup_cleanup_result::unsafe); CHECK(live_count() == live_before); - } - else - { + } else { CHECK(result == ark::startup_cleanup_result::done); CHECK(live_count() == 0); CHECK(later.removed == (arm && remove)); diff --git a/tests/core/xxtea.cpp b/tests/core/xxtea.cpp index 1fd7afee0..7c2e52693 100644 --- a/tests/core/xxtea.cpp +++ b/tests/core/xxtea.cpp @@ -23,8 +23,7 @@ std::string encrypt(const std::string& message, const void* key) { size_t length = 0; std::unique_ptr value( ark::xxtea::xxtea_encrypt(message.data(), message.size(), key, &length), &std::free); - if (!value) - { + if (!value) { return {}; } return {static_cast(value.get()), length}; @@ -34,8 +33,7 @@ std::string encrypt(const std::string& message, const void* key) { DOCTEST_TEST_CASE("XXTEA reads short keys only through their terminating zero") { const std::string message("binary\0message", 14); - for (size_t length = 0; length < 16; ++length) - { + for (size_t length = 0; length < 16; ++length) { DOCTEST_CAPTURE(length); // Exact allocation makes reading beyond the terminator observable. auto short_key = std::make_unique(length + 1); @@ -74,8 +72,7 @@ DOCTEST_TEST_CASE("XXTEA preserves full-width and zero-terminated key normalizat TEST_CASE("XXTEA retains the established ciphertext byte order") { const auto to_hex = [](const std::string& bytes) { std::string result; - for (unsigned char value : bytes) - { + for (unsigned char value : bytes) { constexpr std::string_view digits = "0123456789abcdef"; result.push_back(digits[value >> 4]); result.push_back(digits[value & 15]); @@ -91,8 +88,7 @@ TEST_CASE("XXTEA retains the established ciphertext byte order") { TEST_CASE("XXTEA rejects invalid raw buffer arguments before reading them") { std::array bytes{}; size_t length = 99; - for (size_t size : {size_t{1}, size_t{2}, size_t{3}, size_t{5}, size_t{6}, size_t{7}}) - { + for (size_t size : {size_t{1}, size_t{2}, size_t{3}, size_t{5}, size_t{6}, size_t{7}}) { CAPTURE(size); CHECK(ark::xxtea::xxtea_decrypt(bytes.data(), size, "k", &length) == nullptr); CHECK(length == 99); @@ -103,8 +99,7 @@ TEST_CASE("XXTEA rejects invalid raw buffer arguments before reading them") { CHECK(ark::xxtea::xxtea_decrypt(bytes.data(), 8, nullptr, &length) == nullptr); CHECK(ark::xxtea::xxtea_encrypt(bytes.data(), 1, "k", nullptr) == nullptr); CHECK(ark::xxtea::xxtea_decrypt(bytes.data(), 8, "k", nullptr) == nullptr); - if constexpr (sizeof(size_t) > sizeof(uint32_t)) - { + if constexpr (sizeof(size_t) > sizeof(uint32_t)) { const size_t too_large = size_t{(std::numeric_limits::max)()} + 1; CHECK(ark::xxtea::xxtea_encrypt(bytes.data(), too_large, "k", &length) == nullptr); CHECK(ark::xxtea::xxtea_decrypt(bytes.data(), too_large, "k", &length) == nullptr); diff --git a/tests/database/awaitable_lifetime.cpp b/tests/database/awaitable_lifetime.cpp index ffc1e0d9e..9fcf5393d 100644 --- a/tests/database/awaitable_lifetime.cpp +++ b/tests/database/awaitable_lifetime.cpp @@ -17,8 +17,7 @@ namespace ark::detail { -struct database_awaitable_test_access -{ +struct database_awaitable_test_access { template static bool fail_post(database_awaitable& bridge) { return bridge.state_->schedule(64, [](auto, auto) { throw std::bad_alloc(); }); @@ -29,8 +28,7 @@ struct database_awaitable_test_access namespace { -struct response -{ +struct response { std::string data; bool cancelled{}; bool outcome_unknown{}; @@ -297,8 +295,7 @@ TEST_CASE("A throwing native cancellation request never replaces an accepted ope auto result = co_await bridge.wait( [&](callback_type completion) { native = std::move(completion); - if (cancel_before_publication) - { + if (cancel_before_publication) { CHECK(group.cancel(task)); } return std::uint64_t{61}; @@ -315,16 +312,16 @@ TEST_CASE("A throwing native cancellation request never replaces an accepted ope }; task = group.start(operation(), [](std::exception_ptr error) { CHECK_FALSE(error); }); group.poll(); - if (!cancel_before_publication) - { + if (!cancel_before_publication) { CHECK(group.cancel(task)); } CHECK(cancellations == 1); REQUIRE(bridge.cancellation_exception()); - try - { std::rethrow_exception(bridge.cancellation_exception()); } - catch (const std::runtime_error& error) - { CHECK(std::string(error.what()) == "native cancellation submission failed"); } + try { + std::rethrow_exception(bridge.cancellation_exception()); + } catch (const std::runtime_error& error) { + CHECK(std::string(error.what()) == "native cancellation submission failed"); + } CHECK(bridge.pending() == 1); CHECK(group.pending() == 1); CHECK(received == 0); @@ -367,14 +364,13 @@ TEST_CASE("Inline native refusal and initiation exceptions are asynchronously de group.poll(); CHECK(received == 1); auto throwing = [&]() -> module_task<> { - try - { + try { co_await bridge.wait([](callback_type) -> std::uint64_t { throw std::runtime_error("initiation failed"); }, [](std::uint64_t) {}); FAIL("A C++ initiation exception must not become a native success"); + } catch (const std::runtime_error& error) { + caught = std::string(error.what()) == "initiation failed"; } - catch (const std::runtime_error& error) - { caught = std::string(error.what()) == "initiation failed"; } }; group.start(throwing(), [](std::exception_ptr error) { CHECK_FALSE(error); }); group.poll(); @@ -401,30 +397,28 @@ TEST_CASE("Bridge quota and executor mismatch fail before starting native operat group.start(collect_one(bridge, native, received, result, runtime)); group.poll(); auto full = [&]() -> module_task<> { - try - { + try { co_await bridge.wait( [&](callback_type) { ++extra_starts; return std::uint64_t{1}; }, [](std::uint64_t) {}); + } catch (const std::length_error&) { + ++rejected; } - catch (const std::length_error&) - { ++rejected; } }; auto wrong_executor = [&]() -> module_task<> { - try - { + try { co_await foreign.wait( [&](callback_type) { ++extra_starts; return std::uint64_t{1}; }, [](std::uint64_t) {}); + } catch (const std::logic_error&) { + ++rejected; } - catch (const std::logic_error&) - { ++rejected; } }; group.start(full(), [](std::exception_ptr error) { CHECK_FALSE(error); }); group.start(wrong_executor(), [](std::exception_ptr error) { CHECK_FALSE(error); }); @@ -439,8 +433,7 @@ TEST_CASE("Bridge quota and executor mismatch fail before starting native operat CHECK(received == 1); bridge.stop_accepting(); auto closed = [&]() -> module_task<> { - try - { + try { co_await bridge.wait( [&](callback_type) { ++extra_starts; @@ -448,9 +441,9 @@ TEST_CASE("Bridge quota and executor mismatch fail before starting native operat }, [](std::uint64_t) {}); FAIL("Closed bridge accepted an operation"); + } catch (const std::logic_error&) { + ++rejected; } - catch (const std::logic_error&) - { ++rejected; } }; group.start(closed(), [](std::exception_ptr error) { CHECK_FALSE(error); }); group.poll(); diff --git a/tests/database/completion_queue.cpp b/tests/database/completion_queue.cpp index bebec95a8..37178f3c0 100644 --- a/tests/database/completion_queue.cpp +++ b/tests/database/completion_queue.cpp @@ -124,8 +124,7 @@ TEST_CASE("IO producers only deliver business callbacks on the module thread") { std::vector::ticket> records; unsigned callbacks{}; bool wrong_thread{}; - for (unsigned index = 0; index < 16; ++index) - { + for (unsigned index = 0; index < 16; ++index) { records.push_back(queue.admit(1, [&](std::string result) { wrong_thread |= std::this_thread::get_id() != owner; CHECK(result == std::string("binary\0value", 12)); @@ -134,18 +133,15 @@ TEST_CASE("IO producers only deliver business callbacks on the module thread") { REQUIRE(records.back()); } std::vector workers; - for (unsigned lane = 0; lane < 4; ++lane) - { + for (unsigned lane = 0; lane < 4; ++lane) { workers.emplace_back([&, lane] { - for (unsigned index = lane; index < records.size(); index += 4) - { + for (unsigned index = lane; index < records.size(); index += 4) { queue.complete(records[index], std::string("binary\0value", 12)); queue.complete(records[index], "duplicate must be ignored"); } }); } - for (auto& worker : workers) - { + for (auto& worker : workers) { worker.join(); } CHECK(callbacks == 0); @@ -224,10 +220,11 @@ TEST_CASE("Only completion production is allowed off the module thread") { completion_queue queue(1, 1); std::atomic rejected{}; std::thread worker([&] { - try - { queue.dispatch(); } - catch (const std::logic_error&) - { rejected = true; } + try { + queue.dispatch(); + } catch (const std::logic_error&) { + rejected = true; + } }); worker.join(); CHECK(rejected.load()); @@ -243,32 +240,27 @@ TEST_CASE("Module dispatch overlaps native completion producers") { std::vector::ticket> records; unsigned callbacks{}; unsigned total{}; - for (unsigned index = 0; index < count; ++index) - { + for (unsigned index = 0; index < count; ++index) { records.push_back(queue.admit(1, [&](unsigned value) { ++callbacks; total += value; })); } std::vector producers; - for (unsigned lane = 0; lane < 4; ++lane) - { + for (unsigned lane = 0; lane < 4; ++lane) { producers.emplace_back([&, lane] { - for (unsigned index = lane; index < count; index += 4) - { + for (unsigned index = lane; index < count; index += 4) { queue.complete(records[index], index + 1); std::this_thread::yield(); } }); } const auto expires = std::chrono::steady_clock::now() + std::chrono::seconds(3); - while (callbacks < count && std::chrono::steady_clock::now() < expires) - { + while (callbacks < count && std::chrono::steady_clock::now() < expires) { queue.dispatch(7); std::this_thread::yield(); } - for (auto& producer : producers) - { + for (auto& producer : producers) { producer.join(); } queue.dispatch(count); diff --git a/tests/database/construction_allocation_probe.hpp b/tests/database/construction_allocation_probe.hpp index c4666ddc8..839194c88 100644 --- a/tests/database/construction_allocation_probe.hpp +++ b/tests/database/construction_allocation_probe.hpp @@ -33,14 +33,11 @@ const char* protocol{}; long budget{}; void before_allocation() { - if (armed) - { - if (remaining == 0) - { + if (armed) { + if (remaining == 0) { throw std::bad_alloc(); } - if (remaining > 0) - { + if (remaining > 0) { --remaining; } ++allocations; @@ -51,8 +48,7 @@ void before_allocation() { void* operator new(std::size_t size) { ark_database_allocation_probe::before_allocation(); - if (void* pointer = std::malloc(size ? size : 1)) - { + if (void* pointer = std::malloc(size ? size : 1)) { return pointer; } throw std::bad_alloc(); @@ -84,13 +80,11 @@ void* operator new(std::size_t size, std::align_val_t alignment) { #if defined(_WIN32) pointer = _aligned_malloc(size ? size : 1, static_cast(alignment)); #else - if (posix_memalign(&pointer, static_cast(alignment), size ? size : 1) != 0) - { + if (posix_memalign(&pointer, static_cast(alignment), size ? size : 1) != 0) { pointer = nullptr; } #endif - if (!pointer) - { + if (!pointer) { throw std::bad_alloc(); } return pointer; @@ -122,10 +116,11 @@ void operator delete[](void* pointer, std::size_t, std::align_val_t alignment) n // Keep nothrow replacements in the same allocation family under sanitizers. void* operator new(std::size_t size, const std::nothrow_t&) noexcept { - try - { return ::operator new(size); } - catch (...) - { return nullptr; } + try { + return ::operator new(size); + } catch (...) { + return nullptr; + } } void* operator new[](std::size_t size, const std::nothrow_t&) noexcept { @@ -141,10 +136,11 @@ void operator delete[](void* pointer, const std::nothrow_t&) noexcept { } void* operator new(std::size_t size, std::align_val_t alignment, const std::nothrow_t&) noexcept { - try - { return ::operator new(size, alignment); } - catch (...) - { return nullptr; } + try { + return ::operator new(size, alignment); + } catch (...) { + return nullptr; + } } void* operator new[](std::size_t size, std::align_val_t alignment, const std::nothrow_t&) noexcept { diff --git a/tests/database/module_construction_allocation.cpp b/tests/database/module_construction_allocation.cpp index 5ce7bd0ba..c7ff030f3 100644 --- a/tests/database/module_construction_allocation.cpp +++ b/tests/database/module_construction_allocation.cpp @@ -26,15 +26,12 @@ template int probe(std::unique_ptr module, Options options, bool populated) { ark::plugin_manager manager; module->set_plugin_manager(&manager); - if (!module->init()) - { + if (!module->init()) { return 3; } - if (populated) - { + if (populated) { // Keep an existing live connection across the failed insertion/retry. - if (!configure(*module, "existing", options)) - { + if (!configure(*module, "existing", options)) { return 3; } } @@ -45,37 +42,28 @@ int probe(std::unique_ptr module, Options options, bool populated) { bool caught{}; remaining = budget; armed = true; - try - { - if (!module->configure(std::move(name), std::move(attempted_options))) - { + try { + if (!module->configure(std::move(name), std::move(attempted_options))) { armed = false; return 4; } armed = false; - } - catch (const std::bad_alloc&) - { + } catch (const std::bad_alloc&) { const bool persistent = armed && remaining == 0; armed = false; - if (!persistent || budget < 0) - { + if (!persistent || budget < 0) { return 5; } caught = true; - } - catch (...) - { + } catch (...) { armed = false; return 6; } name.assign(160, 'n'); - if (caught && !configure(*module, name, options)) - { + if (caught && !configure(*module, name, options)) { return 7; // A failed configure must release its name for retry. } - if (!configure(*module, "healthy-fallback", options)) - { + if (!configure(*module, "healthy-fallback", options)) { return 8; } // Duplicate rejection must preserve the installed connection, without @@ -85,16 +73,12 @@ int probe(std::unique_ptr module, Options options, bool populated) { armed = true; const bool duplicate = module->configure(std::move(name), std::move(duplicate_options)); armed = false; - if (duplicate || !module->ready_to_shut() || !module->pre_shut() || !module->shut()) - { + if (duplicate || !module->ready_to_shut() || !module->pre_shut() || !module->shut()) { return 9; } - if (caught) - { + if (caught) { std::printf("caught %s budget=%ld allocations=%ld\n", protocol, budget, allocations); - } - else - { + } else { std::printf("constructed %s allocations=%ld\n", protocol, allocations); } return budget < 0 || allocations <= budget ? 0 : 10; @@ -103,15 +87,13 @@ int probe(std::unique_ptr module, Options options, bool populated) { int main(int argc, char** argv) { using namespace ark_database_allocation_probe; - if (argc != 3 && argc != 4) - { + if (argc != 3 && argc != 4) { return 2; } protocol = argv[1]; char* end{}; budget = std::strtol(argv[2], &end, 10); - if (end == argv[2] || *end || budget < -1 || (argc == 4 && std::strcmp(argv[3], "populated") != 0)) - { + if (end == argv[2] || *end || budget < -1 || (argc == 4 && std::strcmp(argv[3], "populated") != 0)) { return 2; } std::set_terminate([] { @@ -119,15 +101,13 @@ int main(int argc, char** argv) { stderr, "terminate %s budget=%ld allocations=%ld armed=%d\n", protocol, budget, allocations, armed); std::_Exit(86); }); - if (std::strcmp(protocol, "redis") == 0 || std::strcmp(protocol, "redis-tls") == 0) - { + if (std::strcmp(protocol, "redis") == 0 || std::strcmp(protocol, "redis-tls") == 0) { ark::redis_options options; options.tls = std::strcmp(protocol, "redis-tls") == 0; return probe(ark::detail::make_redis_module(), std::move(options), argc == 4); } #if defined(ARKNET_ENABLE_SSL) - if (std::strcmp(protocol, "mysql") == 0) - { + if (std::strcmp(protocol, "mysql") == 0) { return probe(ark::detail::make_mysql_module(), ark::mysql_options{}, argc == 4); } #endif diff --git a/tests/database/mysql_service.cpp b/tests/database/mysql_service.cpp index d6a7ce18b..a58e60548 100644 --- a/tests/database/mysql_service.cpp +++ b/tests/database/mysql_service.cpp @@ -29,8 +29,7 @@ unsigned checks{}; std::string required_environment(const char* name, bool allow_empty = false) { const auto* value = std::getenv(name); - if (!value || (!allow_empty && !*value)) - { + if (!value || (!allow_empty && !*value)) { throw std::invalid_argument(std::string("Required test environment variable: ") + name); } return value; @@ -40,8 +39,7 @@ std::uint16_t mysql_port() { const auto text = required_environment("ARK_DATABASE_MYSQL_PORT"); unsigned port{}; const auto parsed = std::from_chars(text.data(), text.data() + text.size(), port); - if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size() || !port || port > 65535) - { + if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size() || !port || port > 65535) { throw std::invalid_argument("ARK_DATABASE_MYSQL_PORT must be an integer between 1 and 65535"); } return static_cast(port); @@ -49,22 +47,19 @@ std::uint16_t mysql_port() { void require(bool condition, const char* message) { ++checks; - if (!condition) - { + if (!condition) { throw std::runtime_error(message); } } mysql_service_reply await(mysql_service& service, std::optional& completion) { const auto deadline = std::chrono::steady_clock::now() + 6s; - while (!completion && std::chrono::steady_clock::now() < deadline) - { + while (!completion && std::chrono::steady_clock::now() < deadline) { service.update(); std::this_thread::sleep_for(1ms); } require(bool(completion), "No MySQL module completion before timeout"); - if (auto* failure = std::get_if(&*completion)) - { + if (auto* failure = std::get_if(&*completion)) { std::rethrow_exception(*failure); } auto reply = std::get(std::move(*completion)); @@ -102,8 +97,7 @@ mysql_service_reply execute(mysql_service& service, std::string sql, std::vector } void success(const mysql_service_reply& reply) { - if (!reply.result) - { + if (!reply.result) { throw std::runtime_error("Native MySQL failed: " + std::to_string(static_cast(reply.result.status.code)) + " " + reply.result.status.message); } @@ -130,14 +124,12 @@ void check_row(const query_result& result, const std::string& binary) { void wait_for_mysql_sleep(mysql_service& observer, const std::string& tag) { const auto expires = std::chrono::steady_clock::now() + 4s; - while (std::chrono::steady_clock::now() < expires) - { + while (std::chrono::steady_clock::now() < expires) { auto active = query(observer, "SELECT COUNT(*) FROM information_schema.processlist WHERE ID <> CONNECTION_ID() " "AND STATE = 'User sleep' AND INFO LIKE '%" + tag + "%'"); success(active); - if (std::get(active.result.rows[0][0]) != 0) - { + if (std::get(active.result.rows[0][0]) != 0) { return; } std::this_thread::sleep_for(1ms); @@ -205,8 +197,7 @@ void check_cancellation(const pool_options& options, const std::string& table) { [&](auto result) { ready_result = std::move(result); }, 4s); require(ready_id != 0, "Queued-result cancellation operation was not admitted"); const auto ready_deadline = std::chrono::steady_clock::now() + 5s; - while (ready.is_pending(ready_id) && std::chrono::steady_clock::now() < ready_deadline) - { + while (ready.is_pending(ready_id) && std::chrono::steady_clock::now() < ready_deadline) { std::this_thread::sleep_for(1ms); } require(!ready.is_pending(ready_id) && !ready_result && !ready.cancel(ready_id), @@ -269,8 +260,7 @@ int main() { pool_options options; std::string table; bool table_created{}; - try - { + try { options.connection.host = required_environment("ARK_DATABASE_MYSQL_HOST"); options.connection.port = mysql_port(); options.connection.username = required_environment("ARK_DATABASE_MYSQL_USER"); @@ -347,12 +337,11 @@ int main() { "Module retained an oversized waiting parameter input"); require(service.update() == 0 && rejected_callbacks == 0, "Unaccepted input triggered a callback"); bool invalid_deadline_rejected{}; - try - { + try { service.submit_query("SELECT 1", [&](auto) { ++rejected_callbacks; }, std::chrono::milliseconds::max()); + } catch (const std::invalid_argument&) { + invalid_deadline_rejected = true; } - catch (const std::invalid_argument&) - { invalid_deadline_rejected = true; } require(invalid_deadline_rejected && rejected_callbacks == 0, "Unrepresentable operation deadline was admitted or completed"); @@ -428,8 +417,7 @@ int main() { "SELECT ?", {std::string("owned")}, [&](mysql_service_result result) { require(std::this_thread::get_id() == owner, "Destruction callback escaped the module thread"); - if (auto* failure = std::get_if(&result)) - { + if (auto* failure = std::get_if(&result)) { std::rethrow_exception(*failure); } const auto& reply = std::get(result); @@ -441,8 +429,7 @@ int main() { 3s), "Destruction test was not admitted"); const auto destruction_deadline = std::chrono::steady_clock::now() + 6s; - while (!destroyed && std::chrono::steady_clock::now() < destruction_deadline) - { + while (!destroyed && std::chrono::steady_clock::now() < destruction_deadline) { ephemeral->update(); std::this_thread::sleep_for(1ms); } @@ -467,18 +454,14 @@ int main() { << " checks passed (owning query/prepared results, bounded admission, shared deadline, module-thread " "callbacks, stop and callback destruction)\n"; return 0; - } - catch (const std::exception& error) - { - if (table_created) - { - try - { + } catch (const std::exception& error) { + if (table_created) { + try { mysql_service cleanup(options); success(query(cleanup, "DROP TABLE IF EXISTS " + table)); + } catch (const std::exception& cleanup_error) { + std::cerr << "Fixture cleanup failed for " << table << ": " << cleanup_error.what() << '\n'; } - catch (const std::exception& cleanup_error) - { std::cerr << "Fixture cleanup failed for " << table << ": " << cleanup_error.what() << '\n'; } } std::cerr << error.what() << '\n'; return 1; diff --git a/tests/database/mysql_transaction_relay.hpp b/tests/database/mysql_transaction_relay.hpp index b55d53da1..cc7c2b371 100644 --- a/tests/database/mysql_transaction_relay.hpp +++ b/tests/database/mysql_transaction_relay.hpp @@ -12,8 +12,7 @@ #include // Test-only transparent TCP relay: it never parses or decrypts MySQL/TLS. -class mysql_transaction_relay -{ +class mysql_transaction_relay { public: explicit mysql_transaction_relay(std::uint16_t upstream) : upstream_(upstream) @@ -21,15 +20,13 @@ class mysql_transaction_relay , worker_([this] { deadline_.expires_after(std::chrono::seconds(8)); deadline_.async_wait([this](arknet::error_code error) { - if (!error) - { + if (!error) { timed_out_ = true; close(); } }); asio::co_spawn(io_, connect(), [this](std::exception_ptr error) { - if (error) - { + if (error) { failed_ = true; close(); } @@ -71,11 +68,9 @@ class mysql_transaction_relay asio::awaitable connect() { co_await acceptor_.async_accept(downstream_, asio::use_awaitable); co_await upstream_socket_.async_connect({asio::ip::address_v4::loopback(), upstream_}, asio::use_awaitable); - for (const bool responses : {false, true}) - { + for (const bool responses : {false, true}) { asio::co_spawn(io_, forward(responses), [this](std::exception_ptr error) { - if (error) - { + if (error) { failed_ = true; } close(); @@ -87,24 +82,20 @@ class mysql_transaction_relay auto& source = responses ? upstream_socket_ : downstream_; auto& destination = responses ? downstream_ : upstream_socket_; std::array bytes; - for (;;) - { + for (;;) { arknet::error_code error; const auto count = co_await source.async_read_some(asio::buffer(bytes), asio::redirect_error(asio::use_awaitable, error)); - if (error) - { + if (error) { co_return; } - if (responses && dropping_) - { + if (responses && dropping_) { discarded_bytes_ += count; continue; } co_await asio::async_write( destination, asio::buffer(bytes.data(), count), asio::redirect_error(asio::use_awaitable, error)); - if (error) - { + if (error) { co_return; } } diff --git a/tests/database/mysql_transaction_state.cpp b/tests/database/mysql_transaction_state.cpp index 065d2e556..629770197 100644 --- a/tests/database/mysql_transaction_state.cpp +++ b/tests/database/mysql_transaction_state.cpp @@ -58,9 +58,9 @@ TEST_CASE("Invalid transaction deadlines reject inline before acquiring a connec { mysql_transaction_service service(pool, {1, 1024}); unsigned calls{}; - for (const auto options : {mysql_transaction_options{0ms, 1s}, mysql_transaction_options{1s, 0ms}, - mysql_transaction_options{-1ms, 1s}, mysql_transaction_options{std::chrono::milliseconds::max(), 1s}}) - { + for (const auto options : + {mysql_transaction_options{0ms, 1s}, mysql_transaction_options{1s, 0ms}, + mysql_transaction_options{-1ms, 1s}, mysql_transaction_options{std::chrono::milliseconds::max(), 1s}}) { CHECK(service.start(options, [&](auto result) { ++calls; CHECK(result.result.status.code == arknet::mysql::connection_errc::invalid_options); @@ -74,10 +74,11 @@ TEST_CASE("Invalid transaction deadlines reject inline before acquiring a connec CHECK(service.update() == 0); bool wrong_thread_rejected{}; std::thread worker([&] { - try - { service.update(); } - catch (const std::logic_error&) - { wrong_thread_rejected = true; } + try { + service.update(); + } catch (const std::logic_error&) { + wrong_thread_rejected = true; + } }); worker.join(); CHECK(wrong_thread_rejected); @@ -116,15 +117,11 @@ TEST_CASE("Prepared transaction admission charges parameter vector and string ca state->deadline = std::chrono::steady_clock::now() + 1s; owner->states[0] = state; unsigned rejected{}; - for (const bool vector_capacity : {false, true}) - { + for (const bool vector_capacity : {false, true}) { std::vector parameters; - if (vector_capacity) - { + if (vector_capacity) { parameters.reserve(1024); - } - else - { + } else { std::string binary("x\0y", 3); binary.reserve(2048); parameters.emplace_back(std::move(binary)); @@ -151,8 +148,7 @@ TEST_CASE("Prepared transaction admission charges parameter vector and string ca TEST_CASE("Statement cleanup preserves business results and uses the original transaction deadline") { using arknet::mysql::connection_errc; auto pool = std::make_shared(arknet::mysql::pool_options{}); - for (const bool exception : {false, true}) - { + for (const bool exception : {false, true}) { auto owner = std::make_shared( pool, mysql_transaction_limits{1, 1024}, arknet::mysql::query_options{}); auto state = std::make_shared(); @@ -165,12 +161,9 @@ TEST_CASE("Statement cleanup preserves business results and uses the original tr state->cleanup_deadline = std::chrono::steady_clock::now() + 1s; std::optional delivered; REQUIRE(owner->reserve(state, 0, [&](auto reply) { delivered = std::move(reply); })); - if (exception) - { + if (exception) { owner->advance(state, std::make_exception_ptr(std::runtime_error("Statement cleanup initiation"))); - } - else - { + } else { owner->issue(state, {}, mysql_transaction_phase::closing_statement); } owner->update(1); @@ -182,14 +175,11 @@ TEST_CASE("Statement cleanup preserves business results and uses the original tr CHECK_FALSE(delivered->rollback); CHECK(delivered->transaction_status.outcome == mysql_transaction_outcome::unconfirmed); CHECK(delivered->transaction_status.discard_requested); - if (exception) - { + if (exception) { REQUIRE(delivered->statement_close_exception); CHECK_THROWS_AS(std::rethrow_exception(delivered->statement_close_exception), std::runtime_error); CHECK_FALSE(delivered->statement_close); - } - else - { + } else { REQUIRE(delivered->statement_close); CHECK(delivered->statement_close->code == connection_errc::timeout); CHECK_FALSE(delivered->statement_close_exception); @@ -206,8 +196,7 @@ TEST_CASE("Cancellation between prepared native completion and owner polling pre auto owner = std::make_shared( pool, mysql_transaction_limits{1, 1024}, arknet::mysql::query_options{}); for (const auto phase : {mysql_transaction_phase::preparing, mysql_transaction_phase::executing, - mysql_transaction_phase::closing_statement}) - { + mysql_transaction_phase::closing_statement}) { auto state = std::make_shared(); state->phase = phase; state->logical_id = 7; @@ -225,8 +214,7 @@ TEST_CASE("Cancellation between prepared native completion and owner polling pre namespace ark::detail { -struct database_service_test_access -{ +struct database_service_test_access { static auto owner(mysql_transaction_service& service) { return service.owner_; } @@ -236,8 +224,7 @@ struct database_service_test_access namespace { -struct transaction_capture -{ +struct transaction_capture { std::weak_ptr owner; unsigned& destroyed; @@ -279,8 +266,7 @@ TEST_CASE("Transaction drain seals only BEGIN and never closes the borrowed pool std::atomic acquired{}; CHECK(pool->async_acquire([&](auto) { acquired = true; }, 100ms) != 0); const auto deadline = std::chrono::steady_clock::now() + 2s; - while (!acquired && std::chrono::steady_clock::now() < deadline) - { + while (!acquired && std::chrono::steady_clock::now() < deadline) { std::this_thread::sleep_for(1ms); } CHECK(acquired); @@ -290,8 +276,7 @@ TEST_CASE("Transaction drain seals only BEGIN and never closes the borrowed pool TEST_CASE("Accepted transaction commands remain admitted after new BEGIN is sealed") { auto pool = std::make_shared(arknet::mysql::pool_options{}); for (const auto phase : - {mysql_transaction_phase::query, mysql_transaction_phase::committing, mysql_transaction_phase::rolling_back}) - { + {mysql_transaction_phase::query, mysql_transaction_phase::committing, mysql_transaction_phase::rolling_back}) { auto owner = std::make_shared( pool, mysql_transaction_limits{1, 1024}, arknet::mysql::query_options{}); auto state = std::make_shared(); @@ -353,8 +338,7 @@ TEST_CASE("Idle transaction deadlines and undispatched native events prevent dra TEST_CASE("Transaction drain waits for terminal delivery and its callback captures") { auto pool = std::make_shared(arknet::mysql::pool_options{}); - for (const bool throwing : {false, true}) - { + for (const bool throwing : {false, true}) { auto owner = std::make_shared( pool, mysql_transaction_limits{1, 1024}, arknet::mysql::query_options{}); auto state = std::make_shared(); @@ -365,8 +349,7 @@ TEST_CASE("Transaction drain waits for terminal delivery and its callback captur REQUIRE(owner->reserve(state, 32, [&, capture = std::move(capture)](auto) { CHECK_FALSE(owner->quiescent()); CHECK_FALSE(owner->logically_drained()); - if (throwing) - { + if (throwing) { throw std::runtime_error("expected transaction completion failure"); } })); @@ -374,14 +357,11 @@ TEST_CASE("Transaction drain waits for terminal delivery and its callback captur CHECK_FALSE(owner->logically_drained()); owner->deliver(state); CHECK_FALSE(owner->logically_drained()); - if (throwing) - { + if (throwing) { CHECK_THROWS_AS(owner->update(1), std::runtime_error); CHECK_FALSE(owner->logically_drained()); CHECK(owner->update(1) == 0); - } - else - { + } else { CHECK(owner->update(1) == 1); } CHECK(destroyed == 1); @@ -394,10 +374,8 @@ TEST_CASE("Transaction drain waits for terminal delivery and its callback captur TEST_CASE("Transaction activity survives facade destruction from inline and queued completions") { auto pool = std::make_shared(arknet::mysql::pool_options{}); - for (const bool queued : {false, true}) - { - for (const bool throwing : {false, true}) - { + for (const bool queued : {false, true}) { + for (const bool throwing : {false, true}) { auto service = std::make_unique(pool, mysql_transaction_limits{1, 1024}); std::weak_ptr owner = database_service_test_access::owner(*service); unsigned destroyed{}; @@ -409,13 +387,11 @@ TEST_CASE("Transaction activity survives facade destruction from inline and queu REQUIRE(active); CHECK(active->activity->depth > 0); CHECK_FALSE(active->logically_drained()); - if (throwing) - { + if (throwing) { throw std::runtime_error("expected self-destruction completion failure"); } }; - if (queued) - { + if (queued) { auto active = owner.lock(); auto state = std::make_shared(); state->phase = mysql_transaction_phase::terminal; @@ -424,13 +400,10 @@ TEST_CASE("Transaction activity survives facade destruction from inline and queu active->deliver(state); } service->stop_accepting(); - if (throwing) - { + if (throwing) { CHECK_THROWS_AS( queued ? service->update() : service->start({1s, 1s}, std::move(completion)), std::runtime_error); - } - else - { + } else { CHECK( (queued ? service->update() : service->start({1s, 1s}, std::move(completion))) == (queued ? 1 : 0)); } diff --git a/tests/database/mysql_transactions.cpp b/tests/database/mysql_transactions.cpp index 5ffc7c282..1b31c1c94 100644 --- a/tests/database/mysql_transactions.cpp +++ b/tests/database/mysql_transactions.cpp @@ -29,16 +29,14 @@ unsigned checks{}; void require(bool value, const std::string& message) { ++checks; - if (!value) - { + if (!value) { throw std::runtime_error(message); } } std::string environment(const char* name, bool empty_allowed = false) { const auto* value = std::getenv(name); - if (!value || (!empty_allowed && !*value)) - { + if (!value || (!empty_allowed && !*value)) { throw std::invalid_argument(std::string("Required test environment variable: ") + name); } return value; @@ -51,15 +49,13 @@ pool_options test_options() { options.acquire_timeout = 2s; options.reset_timeout = 2s; options.connection.host = environment("ARK_DATABASE_MYSQL_HOST"); - if (options.connection.host != "127.0.0.1") - { + if (options.connection.host != "127.0.0.1") { throw std::invalid_argument("Transaction fault-relay tests require ARK_DATABASE_MYSQL_HOST=127.0.0.1"); } const auto port = environment("ARK_DATABASE_MYSQL_PORT"); unsigned number{}; const auto parsed = std::from_chars(port.data(), port.data() + port.size(), number); - if (parsed.ec != std::errc{} || parsed.ptr != port.data() + port.size() || !number || number > 65535) - { + if (parsed.ec != std::errc{} || parsed.ptr != port.data() + port.size() || !number || number > 65535) { throw std::invalid_argument("ARK_DATABASE_MYSQL_PORT must be an integer between 1 and 65535"); } options.connection.port = static_cast(number); @@ -73,10 +69,8 @@ pool_options test_options() { template void wait_until(predicate_type predicate) { const auto end = std::chrono::steady_clock::now() + 6s; - while (!predicate()) - { - if (std::chrono::steady_clock::now() >= end) - { + while (!predicate()) { + if (std::chrono::steady_clock::now() >= end) { throw std::runtime_error("Timed out waiting for a transaction observation"); } std::this_thread::sleep_for(1ms); @@ -92,8 +86,7 @@ mysql_service_reply observe(mysql_service& observer, std::string sql) { observer.update(); return bool(result); }); - if (auto* failure = std::get_if(&*result)) - { + if (auto* failure = std::get_if(&*result)) { std::rethrow_exception(*failure); } auto reply = std::get(std::move(*result)); @@ -103,8 +96,7 @@ mysql_service_reply observe(mysql_service& observer, std::string sql) { std::int64_t integer(const query_result& result) { require(result.rows.size() == 1 && result.rows[0].size() == 1, "Expected one scalar result"); - if (const auto* number = std::get_if(&result.rows[0][0])) - { + if (const auto* number = std::get_if(&result.rows[0][0])) { return static_cast(*number); } return std::get(result.rows[0][0]); @@ -126,8 +118,7 @@ mysql_transaction_reply run(mysql_transaction_service& service, submitter submit return bool(response); }); require(calls == 1, "Missing transaction callback"); - if (response->initiation_exception) - { + if (response->initiation_exception) { std::rethrow_exception(response->initiation_exception); } return std::move(*response); @@ -399,8 +390,7 @@ void check_prepare_delivery_cancellation( // Exercise the production owner directly only to observe its private mailbox // barrier. No synthetic response or protocol endpoint is involved. auto owner = std::make_shared(native, mysql_transaction_limits{1, 8192}, query_options{}); - try - { + try { std::optional begun; require(owner->begin({3s, 1s}, [&](auto reply) { begun = std::move(reply); }) != 0, "Prepare-delivery barrier did not admit BEGIN"); @@ -442,9 +432,7 @@ void check_prepare_delivery_cancellation( "A prepared write ran after cancellation at the native-publication barrier"); require(prepared_count(observer) == count && owner->retained_input->load() == 0, "Barrier cancellation leaked a statement or parameter reservation"); - } - catch (...) - { + } catch (...) { owner->close(); throw; } @@ -684,8 +672,7 @@ void check_coroutine(mysql_transaction_service& service) { return tasks.pending() == 0; }); tasks.close(); - if (error) - { + if (error) { std::rethrow_exception(error); } require(completed && tasks.closed(), "Coroutine group did not finish explicitly"); @@ -702,10 +689,9 @@ void check_throwing_delivery(mysql_transaction_service& service) { }) != 0, "Throwing BEGIN delivery was not accepted"); wait_until([&] { - try - { service.update(1); } - catch (const std::runtime_error& error) - { + try { + service.update(1); + } catch (const std::runtime_error& error) { require( std::string(error.what()) == "Expected transaction callback failure", "Unexpected delivery failure"); observed = true; @@ -799,16 +785,14 @@ void check_natural_drain(const std::shared_ptr& native) { } // namespace int main() { - try - { + try { const auto options = test_options(); auto native = std::make_shared(options); mysql_service observer(options); const auto table = "ark_transaction_" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()); observe(observer, "CREATE TABLE " + table + " (id INT PRIMARY KEY, value VARBINARY(64)) ENGINE=InnoDB"); - try - { + try { { mysql_transaction_service service(native, {1, 8192}); check_commit(service, observer, table); @@ -834,9 +818,7 @@ int main() { check_unknown_commit(options, observer, table); check_cleanup_failure(options, observer, table); check_prepare_cancellation(options, observer, table); - } - catch (...) - { + } catch (...) { observe(observer, "DROP TABLE IF EXISTS " + table); native->close_and_wait(); throw; @@ -845,9 +827,7 @@ int main() { require(native->close_and_wait(), "Native pool did not complete its explicit test-owner shutdown barrier"); std::cout << "Private MySQL transaction checks passed: " << checks << '\n'; return 0; - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { std::cerr << error.what() << '\n'; return 1; } diff --git a/tests/database/operations_awaitable.cpp b/tests/database/operations_awaitable.cpp index 9d005c4d0..4e783151d 100644 --- a/tests/database/operations_awaitable.cpp +++ b/tests/database/operations_awaitable.cpp @@ -28,8 +28,7 @@ using ark::detail::module_task_group; // Controlled service callbacks exercise the operation/bridge contract without // a network endpoint. They do not simulate a database or establish live results. -struct redis_service_stub -{ +struct redis_service_stub { using callback = std::function; std::vector submitted; std::chrono::milliseconds timeout{}; @@ -51,12 +50,10 @@ struct redis_service_stub ++starts; submitted = std::move(commands); timeout = limit; - if (throw_on_start) - { + if (throw_on_start) { throw std::runtime_error("Redis initiation failed locally"); } - if (inline_reply) - { + if (inline_reply) { handler(std::move(immediate)); return 0; } @@ -75,8 +72,7 @@ struct redis_service_stub }; template -struct operation_owner -{ +struct operation_owner { std::shared_ptr runtime = std::make_shared(); module_task_group tasks{runtime, 1}; database_awaitable bridge{runtime, 1}; @@ -104,8 +100,7 @@ struct operation_owner } void drain() { - for (unsigned step = 0; step < 16 && tasks.pending(); ++step) - { + for (unsigned step = 0; step < 16 && tasks.pending(); ++step) { bridge.dispatch(); tasks.poll(); } @@ -199,21 +194,17 @@ TEST_CASE("Redis operation owns inputs before a lazy task starts and retains ord } TEST_CASE("Redis inline rejection and local exceptions use owner delivery rather than a synthetic success") { - for (unsigned mode = 0; mode < 3; ++mode) - { + for (unsigned mode = 0; mode < 3; ++mode) { CAPTURE(mode); redis_service_stub service; operation_owner owner; service.inline_reply = true; service.throw_on_start = mode == 2; - if (mode == 0) - { + if (mode == 0) { arknet::redis::result rejection; rejection.error = arknet::redis::client_errc::queue_full; service.immediate = std::move(rejection); - } - else - { + } else { service.immediate = std::make_exception_ptr(std::runtime_error("Redis callback failed locally")); } owner.start(ark::detail::redis_command(service, owner.bridge, {"PING"}, 18ms)); @@ -222,14 +213,11 @@ TEST_CASE("Redis inline rejection and local exceptions use owner delivery rather CHECK(owner.bridge.pending() == 1); owner.drain(); CHECK(owner.completed == 1); - if (mode == 0) - { + if (mode == 0) { CHECK_FALSE(owner.error); REQUIRE(owner.result); CHECK(owner.result->error == arknet::redis::client_errc::queue_full); - } - else - { + } else { CHECK_FALSE(owner.result); REQUIRE(owner.error); CHECK_THROWS_AS(std::rethrow_exception(owner.error), std::runtime_error); @@ -275,8 +263,7 @@ TEST_CASE("Real plain and TLS Redis services instantiate the facade and reject i #if defined(ARKNET_ENABLE_SSL) namespace { -struct mysql_service_stub -{ +struct mysql_service_stub { using callback = std::function; std::string sql; std::vector parameters; @@ -306,12 +293,10 @@ struct mysql_service_stub sql = std::move(text); parameters = std::move(values); timeout = limit; - if (throw_on_start) - { + if (throw_on_start) { throw std::runtime_error("MySQL initiation failed locally"); } - if (inline_reply) - { + if (inline_reply) { handler(std::move(immediate)); return 0; } @@ -388,21 +373,17 @@ TEST_CASE("MySQL query and execute own their lazy inputs and preserve execution } TEST_CASE("MySQL inline rejection and local exceptions are preserved through both operation entry points") { - for (unsigned mode = 0; mode < 3; ++mode) - { + for (unsigned mode = 0; mode < 3; ++mode) { CAPTURE(mode); mysql_service_stub service; operation_owner owner; service.inline_reply = true; service.throw_on_start = mode == 2; - if (mode == 0) - { + if (mode == 0) { ark::detail::mysql_service_reply rejected; rejected.result.status.code = arknet::mysql::connection_errc::queue_full; service.immediate = std::move(rejected); - } - else - { + } else { service.immediate = std::make_exception_ptr(std::runtime_error("MySQL callback failed locally")); } owner.start(mode == 1 ? ark::detail::mysql_query(service, owner.bridge, "SELECT 1", 18ms) @@ -412,14 +393,11 @@ TEST_CASE("MySQL inline rejection and local exceptions are preserved through bot CHECK(owner.bridge.pending() == 1); owner.drain(); CHECK(owner.completed == 1); - if (mode == 0) - { + if (mode == 0) { CHECK_FALSE(owner.error); REQUIRE(owner.result); CHECK(owner.result->result.status.code == arknet::mysql::connection_errc::queue_full); - } - else - { + } else { CHECK_FALSE(owner.result); REQUIRE(owner.error); CHECK_THROWS_AS(std::rethrow_exception(owner.error), std::runtime_error); diff --git a/tests/database/public_failure_service.cpp b/tests/database/public_failure_service.cpp index 218606b79..23ec466a6 100644 --- a/tests/database/public_failure_service.cpp +++ b/tests/database/public_failure_service.cpp @@ -25,16 +25,14 @@ namespace { using namespace std::chrono_literals; unsigned checks{}; -class acceptance_failure : public std::runtime_error -{ +class acceptance_failure : public std::runtime_error { public: using std::runtime_error::runtime_error; }; void require(bool condition, const std::string& message) { ++checks; - if (!condition) - { + if (!condition) { throw acceptance_failure(message); } } @@ -63,8 +61,7 @@ ark::task<> observer_interval() { } template -struct module_owner -{ +struct module_owner { ark::plugin_manager manager; std::unique_ptr database_owner; module_type& database; @@ -91,12 +88,10 @@ struct module_owner } ~module_owner() { - if (!stopped) - { - try - { finish(); } - catch (...) - { + if (!stopped) { + try { + finish(); + } catch (...) { std::cerr << "Public database failure test could not drain\n" << std::flush; std::_Exit(1); } @@ -113,8 +108,7 @@ struct module_owner [this](std::exception_ptr error) { completions_on_owner = completions_on_owner && std::this_thread::get_id() == thread && runtime->get_executor().running_in_this_thread(); - if (error && !failure) - { + if (error && !failure) { failure = std::move(error); } ++completions; @@ -123,8 +117,7 @@ struct module_owner } void check_failure() const { - if (failure) - { + if (failure) { std::rethrow_exception(failure); } } @@ -132,8 +125,7 @@ struct module_owner void preflight(ark::task<> workflow) { start(std::move(workflow)); const auto deadline = std::chrono::steady_clock::now() + 20s; - while (tasks->pending()) - { + while (tasks->pending()) { require(std::chrono::steady_clock::now() < deadline, "Failure preflight did not complete"); require(manager.update(0), "Failure preflight update failed"); std::this_thread::sleep_for(1ms); @@ -146,14 +138,12 @@ struct module_owner const auto deadline = std::chrono::steady_clock::now() + 30s; // Finish the slow command and independent observer before cleanup. This // preserves server-side no-replay evidence without relying on shutdown grace. - while (tasks->pending()) - { + while (tasks->pending()) { require(std::chrono::steady_clock::now() < deadline, "Failure workflows did not complete"); require(manager.update(0), "Failure workflow owner update failed"); std::this_thread::sleep_for(1ms); } - while (!(stopped = manager.stop(0))) - { + while (!(stopped = manager.stop(0))) { require(manager.get_shutdown_state() != ark::plugin_manager::shutdown_state::failed && std::chrono::steady_clock::now() < deadline, "Failure workflows did not retire native resources"); @@ -205,8 +195,7 @@ ark::task<> redis_preflight(redis_owner& owner, std::string key) { require(observer.replies[0].text == "PONG", "Redis observer could not authenticate"); } -struct redis_slow_state -{ +struct redis_slow_state { std::optional result; bool observed{}; bool recovered{}; @@ -225,16 +214,13 @@ ark::task<> redis_slow(redis_owner& owner, redis_slow_state& state, std::string std::string client_field(std::string_view line, std::string_view name) { const auto marker = std::string(name) + "="; - for (std::size_t position{}; position < line.size();) - { + for (std::size_t position{}; position < line.size();) { const auto end = line.find(' ', position); const auto field = line.substr(position, end == std::string_view::npos ? end : end - position); - if (field.starts_with(marker)) - { + if (field.starts_with(marker)) { return std::string(field.substr(marker.size())); } - if (end == std::string_view::npos) - { + if (end == std::string_view::npos) { break; } position = end + 1; @@ -249,27 +235,23 @@ std::optional blocked_redis_client(const arknet::redis::result& lis reply.type == arknet::redis::value_type::verbatim_string, "Redis CLIENT LIST did not return a bulk/verbatim string"); std::string_view remaining = reply.text; - if (reply.type == arknet::redis::value_type::verbatim_string) - { + if (reply.type == arknet::redis::value_type::verbatim_string) { // Native RESP3 results retain their format tag. Parse a view without // altering the owning result or accepting unrelated format encodings. require(remaining.starts_with("txt:"), "Redis CLIENT LIST returned a non-text verbatim string"); remaining.remove_prefix(4); } std::optional blocked; - while (!remaining.empty()) - { + while (!remaining.empty()) { const auto newline = remaining.find('\n'); const auto line = remaining.substr(0, newline); if (client_field(line, "name") == tag && client_field(line, "cmd") == "blpop" && - client_field(line, "flags").find('b') != std::string::npos) - { + client_field(line, "flags").find('b') != std::string::npos) { require(!blocked, "Redis observer saw concurrent replay of the uniquely named BLPOP"); blocked = client_field(line, "id"); require(!blocked->empty(), "Redis observer could not identify its blocked client"); } - if (newline == std::string_view::npos) - { + if (newline == std::string_view::npos) { break; } remaining.remove_prefix(newline + 1); @@ -281,23 +263,20 @@ ark::task<> redis_observe(redis_owner& owner, redis_slow_state& state, std::stri std::optional original; std::optional quiet_until; const auto deadline = std::chrono::steady_clock::now() + 12s; - for (;;) - { + for (;;) { owner.check_failure(); require(std::chrono::steady_clock::now() < deadline, "Redis observer did not see deadline and recovery"); arknet::redis::command clients{"CLIENT", "LIST"}; auto listing = co_await owner.database.command("observer", std::move(clients), 3s); owner.check_executor(); const auto blocked = blocked_redis_client(listing, tag); - if (blocked) - { + if (blocked) { require(!quiet_until, "Redis observer saw a new blocked command after the original drained"); require(!original || *original == *blocked, "Redis observer saw BLPOP replayed on a new connection"); original = *blocked; state.observed = true; } - if (state.result && !state.recovered) - { + if (state.result && !state.recovered) { require(state.observed, "Redis deadline completed before server-visible BLPOP observation"); require(state.result->error == arknet::redis::client_errc::timeout && state.result->command_may_have_run, "Sent Redis deadline lost its timeout/unknown execution state"); @@ -308,14 +287,11 @@ ark::task<> redis_observe(redis_owner& owner, redis_slow_state& state, std::stri require(recovered.replies[0].text == "PONG", "Explicit new Redis request did not recover after deadline"); state.recovered = true; } - if (!blocked && state.recovered) - { - if (!quiet_until) - { + if (!blocked && state.recovered) { + if (!quiet_until) { quiet_until = std::chrono::steady_clock::now() + 500ms; } - if (std::chrono::steady_clock::now() >= *quiet_until) - { + if (std::chrono::steady_clock::now() >= *quiet_until) { break; } } @@ -329,8 +305,7 @@ void check_redis() { options.pool.connection.host = environment("ARK_DATABASE_REDIS_HOST"); options.pool.connection.port = std::to_string(port("ARK_DATABASE_REDIS_PORT")); options.pool.connection.password = environment("ARK_DATABASE_REDIS_PASSWORD"); - if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) - { + if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) { options.pool.connection.username = user; } options.pool.max_connections = 1; @@ -394,8 +369,7 @@ ark::task<> mysql_preflight(mysql_owner& owner) { mysql_success(observer); } -struct mysql_slow_state -{ +struct mysql_slow_state { std::optional result; bool observed{}; bool recovered{}; @@ -416,24 +390,21 @@ ark::task<> mysql_observe(mysql_owner& owner, mysql_slow_state& state, std::stri const auto sql = "SELECT CAST(ID AS SIGNED) FROM information_schema.processlist " "WHERE ID <> CONNECTION_ID() AND STATE = 'User sleep' AND INFO LIKE '%" + tag + "%'"; - for (;;) - { + for (;;) { owner.check_failure(); require(std::chrono::steady_clock::now() < deadline, "MySQL observer did not see deadline and recovery"); auto listing = co_await owner.database.query("observer", sql, 3s); owner.check_executor(); mysql_success(listing); require(listing.result.rows.size() <= 1, "MySQL observer saw concurrent replay of its tagged SLEEP"); - if (!listing.result.rows.empty()) - { + if (!listing.result.rows.empty()) { require(!quiet_until, "MySQL observer saw a new SLEEP after the original drained"); const auto id = std::get(listing.result.rows[0][0]); require(!original || *original == id, "MySQL observer saw SLEEP replayed on a new connection"); original = id; state.observed = true; } - if (state.result && !state.recovered) - { + if (state.result && !state.recovered) { require(state.observed, "MySQL deadline completed before server-visible SLEEP observation"); require(state.result->result.status.code == arknet::mysql::connection_errc::timeout && state.result->result.status.outcome_unknown, @@ -445,14 +416,11 @@ ark::task<> mysql_observe(mysql_owner& owner, mysql_slow_state& state, std::stri "Explicit new MySQL request did not recover after deadline"); state.recovered = true; } - if (listing.result.rows.empty() && state.recovered) - { - if (!quiet_until) - { + if (listing.result.rows.empty() && state.recovered) { + if (!quiet_until) { quiet_until = std::chrono::steady_clock::now() + 500ms; } - if (std::chrono::steady_clock::now() >= *quiet_until) - { + if (std::chrono::steady_clock::now() >= *quiet_until) { break; } } @@ -498,31 +466,25 @@ void check_mysql() { } // namespace int main(int argc, char** argv) { - try - { + try { require(argc == 2, "Usage: ark_database_public_failure_service_tests redis|mysql"); const std::string_view protocol(argv[1]); - if (protocol == "redis") - { + if (protocol == "redis") { check_redis(); } #if defined(ARKNET_ENABLE_SSL) - else if (protocol == "mysql") - { + else if (protocol == "mysql") { check_mysql(); } #endif - else - { + else { throw acceptance_failure("Requested failure-test protocol is not enabled"); } std::cout << protocol << " public module real-service failure checks passed: " << checks << '\n'; return 0; - } - catch (const acceptance_failure& error) - { std::cerr << error.what() << '\n'; } - catch (...) - { + } catch (const acceptance_failure& error) { + std::cerr << error.what() << '\n'; + } catch (...) { // Never emit authentication configuration or server-controlled messages. std::cerr << "Public database failure acceptance raised an unexpected exception\n"; } diff --git a/tests/database/public_mysql_module.cpp b/tests/database/public_mysql_module.cpp index 66e4517d7..d2c2824bf 100644 --- a/tests/database/public_mysql_module.cpp +++ b/tests/database/public_mysql_module.cpp @@ -16,14 +16,12 @@ namespace { using namespace std::chrono_literals; using namespace mysql_test; -struct observed_commands -{ +struct observed_commands { std::atomic queries{}, prepares{}, executes{}, closes{}, commits{}, rollbacks{}; std::atomic allow_rollback{true}; }; -struct rollback_guard -{ +struct rollback_guard { observed_commands& seen; ~rollback_guard() { @@ -32,85 +30,61 @@ struct rollback_guard }; asio::awaitable serve(mysql_peer& server, observed_commands& seen, bool tls = false) { - if (tls) - { + if (tls) { co_await server.send(greeting("mysql_native_password", true)); co_await server.receive(); co_await server.upgrade(); co_await server.receive(); co_await server.send(ok_packet); - } - else - { + } else { co_await authenticate(server); } bool active{}; - try - { - while (true) - { + try { + while (true) { const auto command = co_await receive_command(server); REQUIRE_FALSE(command.empty()); const auto kind = static_cast(command[0]); - if (kind == 0x1f) - { + if (kind == 0x1f) { active = false; co_await server.send(ok_packet); - } - else if (kind == 0x03) - { + } else if (kind == 0x03) { const auto sql = command.substr(1); - if (sql.starts_with("USE ")) - { + if (sql.starts_with("USE ")) { co_await server.send(ok_packet); - } - else if (sql == "START TRANSACTION") - { + } else if (sql == "START TRANSACTION") { active = true; auto ok = ok_packet; ok[3] = 3; co_await server.send(std::move(ok)); - } - else if (sql.starts_with("COMMIT")) - { + } else if (sql.starts_with("COMMIT")) { ++seen.commits; active = false; co_await server.send(ok_packet); - } - else if (sql.starts_with("ROLLBACK")) - { + } else if (sql.starts_with("ROLLBACK")) { ++seen.rollbacks; asio::steady_timer pause(co_await asio::this_coro::executor); - while (!seen.allow_rollback) - { + while (!seen.allow_rollback) { pause.expires_after(1ms); co_await pause.async_wait(asio::use_awaitable); } active = false; co_await server.send(ok_packet); - } - else - { + } else { ++seen.queries; - if (sql == "slow") - { + if (sql == "slow") { co_await server.wait_for_eof(); co_return; } - if (active) - { + if (active) { auto ok = ok_packet; ok[3] = 3; co_await server.send(std::move(ok)); - } - else - { + } else { co_await one_integer(server, "42", true); } } - } - else if (kind == 0x16) - { + } else if (kind == 0x16) { ++seen.prepares; std::string response(12, '\0'); response[1] = 7; @@ -118,39 +92,29 @@ asio::awaitable serve(mysql_peer& server, observed_commands& seen, bool tl co_await server.send(std::move(response)); co_await server.send(column_packet("parameter")); co_await server.send(eof_packet); - } - else if (kind == 0x17) - { + } else if (kind == 0x17) { ++seen.executes; REQUIRE(command.size() >= 22); CHECK(static_cast(command[1]) == 7); auto ok = ok_packet; - if (active) - { + if (active) { ok[3] = 3; } co_await server.send(std::move(ok)); - } - else if (kind == 0x19) - { + } else if (kind == 0x19) { ++seen.closes; - } - else - { + } else { FAIL("Unexpected public MySQL command"); co_return; } } - } - catch (const arknet::system_error& error) - { + } catch (const arknet::system_error& error) { CHECK((error.code() == asio::error::eof || error.code() == asio::error::connection_reset || error.code() == asio::ssl::error::stream_truncated)); } } -struct module_owner -{ +struct module_owner { ark::plugin_manager manager; std::unique_ptr database_owner{ark::detail::make_mysql_module()}; ark::mysql_module& database{*database_owner}; @@ -174,8 +138,7 @@ struct module_owner void drain() { const auto deadline = std::chrono::steady_clock::now() + 5s; - while (manager.pending_tasks() && std::chrono::steady_clock::now() < deadline) - { + while (manager.pending_tasks() && std::chrono::steady_clock::now() < deadline) { REQUIRE(manager.update(0)); std::this_thread::sleep_for(1ms); } @@ -184,8 +147,7 @@ struct module_owner void stop() { const auto deadline = std::chrono::steady_clock::now() + 5s; - while (!manager.stop(0) && std::chrono::steady_clock::now() < deadline) - { + while (!manager.stop(0) && std::chrono::steady_clock::now() < deadline) { REQUIRE(manager.get_shutdown_state() != ark::plugin_manager::shutdown_state::failed); REQUIRE(manager.update(0)); std::this_thread::sleep_for(1ms); @@ -218,8 +180,7 @@ ark::task<> abandon_transaction(ark::mysql_module& database, std::optional reply; std::exception_ptr failure; unsigned completions{}; @@ -254,8 +215,7 @@ ark::task<> reuse_after_queued_cancellation( } // namespace TEST_CASE("Public MySQL coroutines own native query results and prepared cleanup diagnostics") { - for (const bool tls : {false, true}) - { + for (const bool tls : {false, true}) { observed_commands seen; mysql_peer peer([&seen, tls](mysql_peer& server) { return serve(server, seen, tls); }); module_owner owner; @@ -285,8 +245,7 @@ TEST_CASE("Public MySQL coroutines own native query results and prepared cleanup } TEST_CASE("Public MySQL transactions retain a lease across query and terminal steps") { - for (const bool commit : {false, true}) - { + for (const bool commit : {false, true}) { observed_commands seen; mysql_peer peer([&seen](mysql_peer& server) { return serve(server, seen); }); module_owner owner; @@ -305,8 +264,7 @@ TEST_CASE("Public MySQL transactions retain a lease across query and terminal st } TEST_CASE("Public MySQL abandoned transactions drain deadline rollback before shutdown") { - for (const bool hold_rollback : {false, true}) - { + for (const bool hold_rollback : {false, true}) { CAPTURE(hold_rollback); observed_commands seen; seen.allow_rollback = !hold_rollback; @@ -316,8 +274,7 @@ TEST_CASE("Public MySQL abandoned transactions drain deadline rollback before sh std::optional begun; std::exception_ptr failure; - struct drain_guard - { + struct drain_guard { observed_commands& seen; module_owner& owner; @@ -330,14 +287,12 @@ TEST_CASE("Public MySQL abandoned transactions drain deadline rollback before sh auto& tasks = owner.manager.create_task_group(owner.database); REQUIRE(tasks.start(abandon_transaction(owner.database, begun), [&](auto error) { failure = error; })); const auto deadline = std::chrono::steady_clock::now() + 5s; - while (!seen.rollbacks && std::chrono::steady_clock::now() < deadline) - { + while (!seen.rollbacks && std::chrono::steady_clock::now() < deadline) { REQUIRE(owner.manager.update(0)); std::this_thread::sleep_for(1ms); } REQUIRE(seen.rollbacks == 1); - if (hold_rollback) - { + if (hold_rollback) { // The peer has received ROLLBACK but cannot complete it yet. CHECK_FALSE(owner.manager.stop(0)); CHECK(owner.manager.get_shutdown_state() == ark::plugin_manager::shutdown_state::stopping); @@ -347,12 +302,9 @@ TEST_CASE("Public MySQL abandoned transactions drain deadline rollback before sh REQUIRE_FALSE(failure); REQUIRE(begun); REQUIRE(*begun); - if (begun->transaction) - { + if (begun->transaction) { CHECK(begun->transaction_status.outcome == ark::mysql_transaction_outcome::active); - } - else - { + } else { CHECK(begun->transaction_status.outcome == ark::mysql_transaction_outcome::rolled_back); REQUIRE(begun->rollback); CHECK(*begun->rollback); @@ -367,8 +319,7 @@ TEST_CASE("Public MySQL abandoned transactions drain deadline rollback before sh TEST_CASE("MySQL owner delivery preserves successful BEGIN results across transaction expiry") { using namespace ark::detail; - for (const bool expire_before_delivery : {false, true}) - { + for (const bool expire_before_delivery : {false, true}) { CAPTURE(expire_before_delivery); observed_commands seen; seen.allow_rollback = false; @@ -390,8 +341,7 @@ TEST_CASE("MySQL owner delivery preserves successful BEGIN results across transa REQUIRE(state); const auto wait_until = [](auto ready) { const auto deadline = std::chrono::steady_clock::now() + 5s; - while (!ready()) - { + while (!ready()) { REQUIRE(std::chrono::steady_clock::now() < deadline); std::this_thread::sleep_for(1ms); } @@ -413,8 +363,7 @@ TEST_CASE("MySQL owner delivery preserves successful BEGIN results across transa REQUIRE(*begun); REQUIRE((begun->status_flags & 1u) != 0); } - if (!expire_before_delivery) - { + if (!expire_before_delivery) { state->deadline = std::chrono::steady_clock::time_point::max(); REQUIRE(owner->update(1) == 1); REQUIRE(reply); @@ -438,16 +387,13 @@ TEST_CASE("MySQL owner delivery preserves successful BEGIN results across transa REQUIRE(reply); REQUIRE(*reply); CHECK(calls == 1); - if (expire_before_delivery) - { + if (expire_before_delivery) { // bool reports the business result, not a live transaction token. CHECK_FALSE(reply->transaction); CHECK(reply->transaction_status.outcome == mysql_transaction_outcome::rolled_back); REQUIRE(reply->rollback); CHECK(*reply->rollback); - } - else - { + } else { CHECK(reply->transaction->snapshot().outcome == mysql_transaction_outcome::rolled_back); } CHECK_FALSE(state->status.discard_requested); @@ -495,8 +441,7 @@ TEST_CASE("Manager stop cancels sent MySQL work and retires unknown outcomes wit const auto id = tasks.start(slow(owner.database, replies), [&](auto error) { failure = error; }); REQUIRE(id); const auto deadline = std::chrono::steady_clock::now() + 3s; - while (!seen.queries && std::chrono::steady_clock::now() < deadline) - { + while (!seen.queries && std::chrono::steady_clock::now() < deadline) { REQUIRE(owner.manager.update(0)); std::this_thread::sleep_for(1ms); } @@ -527,8 +472,7 @@ TEST_CASE("Public MySQL cancels a queued acquire without losing its transaction // Drain before destroying reports captured by pending completions, including // when an assertion below unwinds the host stack. - struct drain_guard - { + struct drain_guard { module_owner& owner; ark::task_group& tasks; @@ -557,8 +501,7 @@ TEST_CASE("Public MySQL cancels a queued acquire without losing its transaction CHECK(std::this_thread::get_id() == thread); })); const auto deadline = std::chrono::steady_clock::now() + 3s; - while (!overflow.completions && std::chrono::steady_clock::now() < deadline) - { + while (!overflow.completions && std::chrono::steady_clock::now() < deadline) { REQUIRE(owner.manager.update(0)); std::this_thread::sleep_for(1ms); } diff --git a/tests/database/public_mysql_plugin.cpp b/tests/database/public_mysql_plugin.cpp index 41c7ca80e..6c4616ebe 100644 --- a/tests/database/public_mysql_plugin.cpp +++ b/tests/database/public_mysql_plugin.cpp @@ -11,8 +11,7 @@ namespace { ark::task<> request(ark::mysql_module& database) { auto result = co_await database.query("test", "SELECT 1", std::chrono::milliseconds(10)); - if (result) - { + if (result) { throw std::runtime_error("Expected unavailable test endpoint"); } } @@ -22,20 +21,17 @@ int main() { ark::logger::init(nullptr); ark::logger::instance()->set_log_func([](spdlog::level::level_enum, const std::string&) {}); ark::plugin_manager manager; - if (!manager.start(0, ARK_DATABASE_PLUGIN_DIR, "", {{"ark_database_mysql_plugin", ""}})) - { + if (!manager.start(0, ARK_DATABASE_PLUGIN_DIR, "", {{"ark_database_mysql_plugin", ""}})) { return 1; } auto* database = manager.find_module(); - if (!database) - { + if (!database) { return 2; } ark::mysql_options options; options.pool.connection.host = "127.0.0.1"; options.pool.connection.port = 1; - if (!database->configure("test", std::move(options))) - { + if (!database->configure("test", std::move(options))) { return 3; } std::exception_ptr failure; @@ -43,48 +39,41 @@ int main() { if (!manager.create_task_group(*database).start(request(*database), [&](auto error) { failure = error; completed = true; - })) - { + })) { return 4; } const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); // Complete the public coroutine while running. Process shutdown cancels // residual tasks; it no longer completes business requests on their behalf. - while (!completed && std::chrono::steady_clock::now() < deadline) - { + while (!completed && std::chrono::steady_clock::now() < deadline) { manager.update(0); std::this_thread::sleep_for(std::chrono::milliseconds(1)); } - if (!completed) - { + if (!completed) { return 8; } - while (!manager.stop(0) && std::chrono::steady_clock::now() < deadline) - { - if (manager.get_shutdown_state() == ark::plugin_manager::shutdown_state::failed) - { + while (!manager.stop(0) && std::chrono::steady_clock::now() < deadline) { + if (manager.get_shutdown_state() == ark::plugin_manager::shutdown_state::failed) { return 5; } manager.update(0); std::this_thread::sleep_for(std::chrono::milliseconds(1)); } - if (manager.get_shutdown_state() != ark::plugin_manager::shutdown_state::stopped || failure) - { + if (manager.get_shutdown_state() != ark::plugin_manager::shutdown_state::stopped || failure) { std::cerr << "MySQL shutdown state=" << static_cast(manager.get_shutdown_state()) << " pending=" << manager.pending_tasks() << " phase=" << manager.get_shutdown_failure() << "\n"; - if (failure) - { - try - { std::rethrow_exception(failure); } - catch (const std::exception& error) - { std::cerr << error.what() << "\n"; } - catch (...) - { std::cerr << "Non-standard task exception\n"; } + if (failure) { + try { + std::rethrow_exception(failure); + } catch (const std::exception& error) { + std::cerr << error.what() << "\n"; + } catch (...) { + std::cerr << "Non-standard task exception\n"; + } } return 6; } - if (manager.pending_tasks()) - { + if (manager.pending_tasks()) { return 7; } std::cout << "Public MySQL DSO registration, coroutine delivery and shutdown passed\n"; diff --git a/tests/database/public_plugin_cancellation.cpp b/tests/database/public_plugin_cancellation.cpp index 7d539bbf2..05e3a10ad 100644 --- a/tests/database/public_plugin_cancellation.cpp +++ b/tests/database/public_plugin_cancellation.cpp @@ -33,15 +33,13 @@ namespace { using namespace std::chrono_literals; -class acceptance_failure : public std::runtime_error -{ +class acceptance_failure : public std::runtime_error { public: using std::runtime_error::runtime_error; }; void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { throw acceptance_failure(message); } } @@ -61,16 +59,14 @@ std::uint16_t port(const char* name) { return static_cast(number); } -struct completion -{ +struct completion { unsigned count{}; bool on_owner{}; std::exception_ptr error; }; // Public interfaces only: no implementation/factory object is linked into this host. -class plugin_host -{ +class plugin_host { public: ark::plugin_manager manager; ark::task_group* tasks{}; @@ -85,12 +81,10 @@ class plugin_host } ~plugin_host() { - if (!stopped_) - { - try - { stop(); } - catch (...) - { + if (!stopped_) { + try { + stop(); + } catch (...) { std::cerr << "Database cancellation acceptance could not naturally drain\n" << std::flush; std::_Exit(1); } @@ -113,8 +107,7 @@ class plugin_host } static void check_completion(const completion& record) { - if (record.error) - { + if (record.error) { std::rethrow_exception(record.error); } require(record.count == 1 && record.on_owner, "DSO root completion repeated or escaped its owner"); @@ -122,8 +115,7 @@ class plugin_host void pump_until(const std::function& done) { const auto deadline = std::chrono::steady_clock::now() + 25s; - while (!done()) - { + while (!done()) { require(std::chrono::steady_clock::now() < deadline, "Database cancellation acceptance exceeded bound"); require(manager.update(0), "Database cancellation owner update failed"); // Throttling only; server-visible state establishes cancellation readiness. @@ -141,8 +133,7 @@ class plugin_host void stop() { const auto deadline = std::chrono::steady_clock::now() + 30s; - while (!(stopped_ = manager.stop(0))) - { + while (!(stopped_ = manager.stop(0))) { require(manager.get_shutdown_state() != ark::plugin_manager::shutdown_state::failed && std::chrono::steady_clock::now() < deadline, "Cancelled DSO requests did not naturally retire within the shutdown bound"); @@ -158,15 +149,13 @@ class plugin_host } bool stop_step() { - if (stopped_) - { + if (stopped_) { return true; } stopped_ = manager.stop(0); require(manager.get_shutdown_state() != ark::plugin_manager::shutdown_state::failed, "Observed-request resource shutdown failed"); - if (stopped_) - { + if (stopped_) { require(tasks->closed() && tasks->pending() == 0 && manager.pending_tasks() == 0, "Resource shutdown retained a managed request"); require(manager.stop(0), "Observed-request resource stop was not idempotent"); @@ -189,8 +178,7 @@ ark::task<> observer_interval() { co_await timer.async_wait(asio::use_awaitable); } -struct cancellation_state -{ +struct cancellation_state { ark::task_group::task_id request_id{}; completion request, observer; bool observed{}; @@ -207,8 +195,7 @@ void cancel_observed(plugin_host& host, cancellation_state& state) { state.cancelled = true; } -struct stop_state -{ +struct stop_state { completion request, observer; bool observed{}; bool stop_requested{}; @@ -220,26 +207,21 @@ void drive_observed_stop(plugin_host& target, plugin_host& observer, stop_state& require(target.manager.get_task_runtime() != observer.manager.get_task_runtime(), "Stop observer must own an independent runtime"); const auto deadline = std::chrono::steady_clock::now() + 25s; - while (!state.target_stopped || state.observer.count == 0) - { + while (!state.target_stopped || state.observer.count == 0) { require(std::chrono::steady_clock::now() < deadline && !state.request.error && !state.observer.error, "Observed-request shutdown failed or exceeded its bound"); require(!target.manager.get_task_runtime()->get_executor().running_in_this_thread() && !observer.manager.get_task_runtime()->get_executor().running_in_this_thread(), "Target stop must originate on the outer owner frame"); - if (state.observed && !state.stop_requested) - { + if (state.observed && !state.stop_requested) { require(state.request.count == 0 && target.manager.pending_tasks() == 1 && observer.tasks->pending() == 1, "Target request or independent observer retired before stop"); state.stop_requested = true; require(!target.stop_step(), "Pending target request was destroyed synchronously by stop"); - } - else if (state.stop_requested && !state.target_stopped) - { + } else if (state.stop_requested && !state.target_stopped) { state.target_stopped = target.stop_step(); } - if (!state.target_stopped) - { + if (!state.target_stopped) { require(target.manager.update(0), "Target resource-shutdown update failed"); } require(observer.manager.get_shutdown_state() == ark::plugin_manager::shutdown_state::running && @@ -259,16 +241,13 @@ void redis_success(const arknet::redis::result& result) { std::string client_field(std::string_view line, std::string_view name) { const auto marker = std::string(name) + "="; - for (std::size_t position{}; position < line.size();) - { + for (std::size_t position{}; position < line.size();) { const auto end = line.find(' ', position); const auto field = line.substr(position, end == std::string_view::npos ? end : end - position); - if (field.starts_with(marker)) - { + if (field.starts_with(marker)) { return std::string(field.substr(marker.size())); } - if (end == std::string_view::npos) - { + if (end == std::string_view::npos) { break; } position = end + 1; @@ -283,25 +262,21 @@ std::optional blocked_client(const arknet::redis::result& listing, reply.type == arknet::redis::value_type::verbatim_string, "Redis CLIENT LIST result was not text"); std::string_view remaining = reply.text; - if (reply.type == arknet::redis::value_type::verbatim_string) - { + if (reply.type == arknet::redis::value_type::verbatim_string) { require(remaining.starts_with("txt:"), "Redis CLIENT LIST verbatim result had an unexpected format"); remaining.remove_prefix(4); } std::optional found; - while (!remaining.empty()) - { + while (!remaining.empty()) { const auto end = remaining.find('\n'); const auto line = remaining.substr(0, end); if (client_field(line, "name") == tag && client_field(line, "cmd") == "blpop" && - client_field(line, "flags").find('b') != std::string::npos) - { + client_field(line, "flags").find('b') != std::string::npos) { require(!found, "Redis observer saw concurrent replay of its tagged pipeline"); found = client_field(line, "id"); require(!found->empty(), "Redis observer could not identify the blocked client"); } - if (end == std::string_view::npos) - { + if (end == std::string_view::npos) { break; } remaining.remove_prefix(end + 1); @@ -316,8 +291,7 @@ ark::task<> redis_preflight(plugin_host& host, ark::redis_module& database, cons redis_success(removed); require(removed.replies[0].type == arknet::redis::value_type::integer && removed.replies[0].integer == 0, "Exclusive Redis cancellation keys already existed"); - for (const auto* name : {"primary", "observer"}) - { + for (const auto* name : {"primary", "observer"}) { arknet::redis::command ping_command{"PING"}; auto ping = co_await database.command(name, std::move(ping_command), 5s); host.check_executor(); @@ -338,21 +312,18 @@ ark::task<> redis_observe(plugin_host& host, ark::redis_module& database, cancel std::optional original; std::optional quiet_until; const auto deadline = std::chrono::steady_clock::now() + 15s; - for (;;) - { + for (;;) { require(!state.request.error && std::chrono::steady_clock::now() < deadline, "Redis cancellation raised a coroutine exception or exceeded the observation bound"); arknet::redis::command clients{"CLIENT", "LIST"}; auto listing = co_await database.command("observer", std::move(clients), 3s); host.check_executor(); const auto blocked = blocked_client(listing, tag); - if (blocked) - { + if (blocked) { require(!quiet_until && (!original || *original == *blocked), "Redis replayed its tagged pipeline"); original = *blocked; state.observed = true; - if (!state.cancelled) - { + if (!state.cancelled) { arknet::redis::command get_counter{"GET", tag + "_counter"}; auto counter = co_await database.command("observer", std::move(get_counter), 3s); host.check_executor(); @@ -363,8 +334,7 @@ ark::task<> redis_observe(plugin_host& host, ark::redis_module& database, cancel std::cout << "redis server-visible tagged BLPOP active; task cancellation requested\n"; } } - if (result && !state.recovered) - { + if (result && !state.recovered) { std::cout << "redis native cancellation code=" << static_cast(result->error) << " may_have_run=" << result->command_may_have_run << " transport=" << result->transport_error.value() << " partial=" << result->replies.size() @@ -372,8 +342,7 @@ ark::task<> redis_observe(plugin_host& host, ark::redis_module& database, cancel require(state.observed && state.cancelled && result->error == arknet::redis::client_errc::cancelled && result->command_may_have_run && !result->transport_error && result->replies.size() <= 1, "Redis cancellation lost its original sent/uncertain native result semantics"); - if (!result->replies.empty()) - { + if (!result->replies.empty()) { require( result->replies[0].type == arknet::redis::value_type::integer && result->replies[0].integer == 1, "Redis cancellation changed its retained partial reply"); @@ -385,15 +354,12 @@ ark::task<> redis_observe(plugin_host& host, ark::redis_module& database, cancel require(recovered.replies[0].text == "PONG", "Redis explicit follow-up could not recover"); state.recovered = true; } - if (!blocked && state.recovered) - { + if (!blocked && state.recovered) { state.retired_on_server = true; - if (!quiet_until) - { + if (!quiet_until) { quiet_until = std::chrono::steady_clock::now() + 500ms; } - if (std::chrono::steady_clock::now() >= *quiet_until) - { + if (std::chrono::steady_clock::now() >= *quiet_until) { break; } } @@ -418,8 +384,7 @@ void check_redis() { require(options.pool.connection.host == "127.0.0.1", "Redis cancellation requires an owned IPv4 loopback service"); options.pool.connection.port = std::to_string(port("ARK_DATABASE_REDIS_PORT")); options.pool.connection.password = environment("ARK_DATABASE_REDIS_PASSWORD"); - if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) - { + if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) { options.pool.connection.username = user; } options.pool.max_connections = 1; @@ -453,23 +418,19 @@ void check_redis() { bool redis_target_present(const arknet::redis::result& listing, const std::string& tag, const std::string& original) { redis_success(listing); std::string_view remaining = listing.replies[0].text; - if (remaining.starts_with("txt:")) - { + if (remaining.starts_with("txt:")) { remaining.remove_prefix(4); } bool present{}; - while (!remaining.empty()) - { + while (!remaining.empty()) { const auto end = remaining.find('\n'); const auto line = remaining.substr(0, end); const auto id = client_field(line, "id"); - if (client_field(line, "name") == tag || id == original) - { + if (client_field(line, "name") == tag || id == original) { require(!present && id == original, "Stopped Redis target reconnected or replayed its pipeline"); present = true; } - if (end == std::string_view::npos) - { + if (end == std::string_view::npos) { break; } remaining.remove_prefix(end + 1); @@ -482,15 +443,13 @@ ark::task<> redis_stop_observe(plugin_host& observer, ark::redis_module& databas std::optional original; std::optional quiet_until; const auto deadline = std::chrono::steady_clock::now() + 18s; - for (;;) - { + for (;;) { require(std::chrono::steady_clock::now() < deadline, "Stopped Redis target did not retire on the server"); arknet::redis::command clients{"CLIENT", "LIST"}; auto listing = co_await database.command("observer", std::move(clients), 3s); observer.check_executor(); const auto blocked = blocked_client(listing, tag); - if (!state.observed && blocked) - { + if (!state.observed && blocked) { original = *blocked; arknet::redis::command get_counter{"GET", tag + "_counter"}; auto counter = co_await database.command("observer", std::move(get_counter), 3s); @@ -501,23 +460,17 @@ ark::task<> redis_stop_observe(plugin_host& observer, ark::redis_module& databas std::cout << "redis-stop server-visible tagged BLPOP and counter=1; outer-frame stop enabled\n"; } const bool present = original && redis_target_present(listing, tag, *original); - if (state.target_stopped) - { + if (state.target_stopped) { state.observed_after_stop = true; require(result.has_value(), "Redis stop lost its owning native result"); - if (!present) - { - if (!quiet_until) - { + if (!present) { + if (!quiet_until) { quiet_until = std::chrono::steady_clock::now() + 500ms; } - if (std::chrono::steady_clock::now() >= *quiet_until) - { + if (std::chrono::steady_clock::now() >= *quiet_until) { break; } - } - else - { + } else { require(!quiet_until, "Retired Redis target returned during the no-replay window"); } } @@ -542,8 +495,7 @@ void check_redis_stop() { require(options.pool.connection.host == "127.0.0.1", "Redis stop acceptance requires owned IPv4 loopback"); options.pool.connection.port = std::to_string(port("ARK_DATABASE_REDIS_PORT")); options.pool.connection.password = environment("ARK_DATABASE_REDIS_PASSWORD"); - if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) - { + if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) { options.pool.connection.username = user; } options.pool.max_connections = 1; @@ -573,8 +525,7 @@ void check_redis_stop() { require(result && result->error == arknet::redis::client_errc::cancelled && result->command_may_have_run && !result->transport_error && result->replies.size() <= 1, "Redis manager-stop result lost its owning cancelled/uncertain semantics"); - if (!result->replies.empty()) - { + if (!result->replies.empty()) { require(result->replies[0].type == arknet::redis::value_type::integer && result->replies[0].integer == 1, "Redis manager-stop partial reply changed after both hosts were destroyed"); } @@ -606,8 +557,7 @@ void check_redis_tls_stop() { require(options.pool.connection.host == "127.0.0.1", "Redis TLS stop requires an owned IPv4 loopback service"); options.pool.connection.port = std::to_string(port("ARK_DATABASE_REDIS_PORT")); options.pool.connection.password = environment("ARK_DATABASE_REDIS_PASSWORD"); - if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) - { + if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) { options.pool.connection.username = user; } options.pool.certificate_authority = environment("ARK_DATABASE_REDIS_CA"); @@ -642,8 +592,7 @@ void check_redis_tls_stop() { require(result && result->error == arknet::redis::client_errc::cancelled && result->command_may_have_run && !result->transport_error && result->replies.size() <= 1, "Redis TLS manager-stop result lost its owning cancelled/uncertain semantics"); - if (!result->replies.empty()) - { + if (!result->replies.empty()) { require(result->replies[0].type == arknet::redis::value_type::integer && result->replies[0].integer == 1, "Redis TLS manager-stop partial reply changed after both hosts were destroyed"); } @@ -685,31 +634,27 @@ ark::task<> mysql_observe(plugin_host& host, ark::mysql_module& database, cancel const auto sql = "SELECT CAST(ID AS SIGNED), STATE FROM information_schema.processlist " "WHERE ID <> CONNECTION_ID() AND INFO LIKE '%" + tag + "%'"; - for (;;) - { + for (;;) { require(!state.request.error && std::chrono::steady_clock::now() < deadline, "MySQL cancellation raised a coroutine exception or exceeded the server-retirement bound"); auto listing = co_await database.query("observer", sql, 3s); host.check_executor(); mysql_success(listing); require(listing.result.rows.size() <= 1, "MySQL observer saw concurrent replay of its tagged UPDATE"); - if (!listing.result.rows.empty()) - { + if (!listing.result.rows.empty()) { require(listing.result.rows[0].size() == 2, "MySQL observer lost its ID/state fields"); const auto id = std::get(listing.result.rows[0][0]); require(!quiet_until && (!original || *original == id), "MySQL replayed its tagged UPDATE"); original = id; const auto* phase = std::get_if(&listing.result.rows[0][1]); - if (!state.cancelled && phase && *phase == "User sleep") - { + if (!state.cancelled && phase && *phase == "User sleep") { state.observed = true; cancel_observed(host, state); require(!result, "MySQL cancellation fabricated an immediate native result"); std::cout << "mysql server-visible tagged UPDATE active; task cancellation requested\n"; } } - if (result && !state.recovered) - { + if (result && !state.recovered) { std::cout << "mysql native cancellation code=" << static_cast(result->result.status.code) << " outcome_unknown=" << result->result.status.outcome_unknown << " transport=" << result->result.status.transport_error.value() << '\n'; @@ -725,15 +670,12 @@ ark::task<> mysql_observe(plugin_host& host, ark::mysql_module& database, cancel "MySQL explicit follow-up could not recover"); state.recovered = true; } - if (listing.result.rows.empty() && state.recovered) - { + if (listing.result.rows.empty() && state.recovered) { state.retired_on_server = true; - if (!quiet_until) - { + if (!quiet_until) { quiet_until = std::chrono::steady_clock::now() + 500ms; } - if (std::chrono::steady_clock::now() >= *quiet_until) - { + if (std::chrono::steady_clock::now() >= *quiet_until) { break; } } @@ -811,8 +753,7 @@ ark::task<> mysql_stop_observe(plugin_host& observer, ark::mysql_module& databas std::optional original; std::optional quiet_until; const auto deadline = std::chrono::steady_clock::now() + 18s; - for (;;) - { + for (;;) { require(std::chrono::steady_clock::now() < deadline, "Stopped MySQL target did not retire on the server"); const auto sql = "SELECT CAST(ID AS SIGNED),STATE FROM information_schema.processlist WHERE ID <> CONNECTION_ID() AND (" + @@ -821,32 +762,26 @@ ark::task<> mysql_stop_observe(plugin_host& observer, ark::mysql_module& databas observer.check_executor(); mysql_success(listing); require(listing.result.rows.size() <= 1, "Manager stop replayed the tagged MySQL UPDATE concurrently"); - if (!listing.result.rows.empty()) - { + if (!listing.result.rows.empty()) { const auto& row = listing.result.rows[0]; require(row.size() == 2, "MySQL stop observer lost its ID/state fields"); const auto id = std::get(row[0]); require(!quiet_until && (!original || *original == id), "Stopped MySQL target reconnected or replayed"); original = id; const auto* phase = std::get_if(&row[1]); - if (!state.observed && phase && *phase == "User sleep") - { + if (!state.observed && phase && *phase == "User sleep") { state.observed = true; std::cout << "mysql-stop server-visible tagged UPDATE in User sleep; outer-frame stop enabled\n"; } } - if (state.target_stopped) - { + if (state.target_stopped) { state.observed_after_stop = true; require(result.has_value(), "MySQL stop lost its owning native result"); - if (listing.result.rows.empty()) - { - if (!quiet_until) - { + if (listing.result.rows.empty()) { + if (!quiet_until) { quiet_until = std::chrono::steady_clock::now() + 500ms; } - if (std::chrono::steady_clock::now() >= *quiet_until) - { + if (std::chrono::steady_clock::now() >= *quiet_until) { break; } } @@ -936,14 +871,11 @@ ark::task<> mysql_transaction_request(plugin_host& host, ark::mysql_module& data require(bool(*owned) && mysql_scalar(owned->result) == 1 && owned->transaction_status.outcome == ark::mysql_transaction_outcome::active, "MySQL cancellation transaction did not read its uncommitted pre-write"); - if (prepared) - { + if (prepared) { std::vector parameters{std::int64_t{10}, std::int64_t{1}}; result = co_await database.execute(begun.transaction, "UPDATE `" + tag + "` SET n=n+? WHERE id=? AND SLEEP(10)=0 /*" + tag + "*/", std::move(parameters)); - } - else - { + } else { result = co_await database.query( begun.transaction, "UPDATE `" + tag + "` SET n=n+10 WHERE id=1 AND SLEEP(10)=0 /*" + tag + "*/"); } @@ -959,8 +891,7 @@ ark::task<> mysql_transaction_observe(plugin_host& host, ark::mysql_module& data const auto observer_id = mysql_scalar(identity.result); std::optional quiet_until; const auto deadline = std::chrono::steady_clock::now() + 18s; - for (;;) - { + for (;;) { require(!state.request.error && std::chrono::steady_clock::now() < deadline, "MySQL transaction cancellation failed or exceeded the server-session retirement bound"); const auto sql = "SELECT CAST(ID AS SIGNED), STATE, INFO, COMMAND FROM information_schema.processlist " @@ -970,16 +901,14 @@ ark::task<> mysql_transaction_observe(plugin_host& host, ark::mysql_module& data host.check_executor(); mysql_success(listing); require(listing.result.rows.size() <= 1, "MySQL transaction cancellation observed concurrent replay"); - if (!listing.result.rows.empty()) - { + if (!listing.result.rows.empty()) { const auto& row = listing.result.rows[0]; require(row.size() == 4 && original && original != observer_id && std::get(row[0]) == original && !quiet_until, "MySQL transaction cancellation changed session or replayed after retirement"); const auto* phase = std::get_if(&row[1]); const auto* text = std::get_if(&row[2]); - if (!state.cancelled && phase && *phase == "User sleep" && text && text->find(tag) != std::string::npos) - { + if (!state.cancelled && phase && *phase == "User sleep" && text && text->find(tag) != std::string::npos) { const auto* command = std::get_if(&row[3]); require(!prepared || (command && *command == "Execute"), "MySQL prepared cancellation did not observe statement execute on its exact session"); @@ -996,8 +925,7 @@ ark::task<> mysql_transaction_observe(plugin_host& host, ark::mysql_module& data << "; task cancellation requested\n"; } } - if (result && !state.recovered) - { + if (result && !state.recovered) { require(state.observed && state.cancelled, "MySQL transaction cancelled before server observation"); mysql_cancelled_transaction(*result); auto recovered = co_await database.query("primary", "SELECT CAST(CONNECTION_ID() AS SIGNED), 9", 5s); @@ -1009,14 +937,11 @@ ark::task<> mysql_transaction_observe(plugin_host& host, ark::mysql_module& data "MySQL transaction cancellation did not recover through an explicit request on a fresh connection"); state.recovered = true; } - if (listing.result.rows.empty() && state.recovered) - { - if (!quiet_until) - { + if (listing.result.rows.empty() && state.recovered) { + if (!quiet_until) { quiet_until = std::chrono::steady_clock::now() + 500ms; } - if (std::chrono::steady_clock::now() >= *quiet_until) - { + if (std::chrono::steady_clock::now() >= *quiet_until) { state.retired_on_server = true; break; } @@ -1097,8 +1022,7 @@ ark::task<> mysql_transaction_stop_observe(plugin_host& observer, ark::mysql_mod const auto observer_id = mysql_scalar(identity.result); std::optional quiet_until; const auto deadline = std::chrono::steady_clock::now() + 18s; - for (;;) - { + for (;;) { require(std::chrono::steady_clock::now() < deadline, "Manager-stopped MySQL transaction did not retire on the server"); const auto sql = "SELECT CAST(ID AS SIGNED),STATE,INFO,COMMAND FROM information_schema.processlist " @@ -1108,16 +1032,14 @@ ark::task<> mysql_transaction_stop_observe(plugin_host& observer, ark::mysql_mod observer.check_executor(); mysql_success(listing); require(listing.result.rows.size() <= 1, "Manager stop replayed the transaction request concurrently"); - if (!listing.result.rows.empty()) - { + if (!listing.result.rows.empty()) { const auto& row = listing.result.rows[0]; require(row.size() == 4 && original && original != observer_id && std::get(row[0]) == original && !quiet_until, "Manager-stopped transaction changed session or replayed after retirement"); const auto* phase = std::get_if(&row[1]); const auto* text = std::get_if(&row[2]); - if (!state.observed && phase && *phase == "User sleep" && text && text->find(tag) != std::string::npos) - { + if (!state.observed && phase && *phase == "User sleep" && text && text->find(tag) != std::string::npos) { const auto* command = std::get_if(&row[3]); require(!prepared || (command && *command == "Execute"), "Manager stop preceded the transaction's actual prepared execute"); @@ -1133,19 +1055,15 @@ ark::task<> mysql_transaction_stop_observe(plugin_host& observer, ark::mysql_mod << " observer=" << observer_id << "; own-read=1 external-read=0; outer-frame stop enabled\n"; } } - if (state.target_stopped) - { + if (state.target_stopped) { state.observed_after_stop = true; require(result.has_value(), "Manager stop lost the owning transaction result"); mysql_cancelled_transaction(*result); - if (listing.result.rows.empty()) - { - if (!quiet_until) - { + if (listing.result.rows.empty()) { + if (!quiet_until) { quiet_until = std::chrono::steady_clock::now() + 500ms; } - if (std::chrono::steady_clock::now() >= *quiet_until) - { + if (std::chrono::steady_clock::now() >= *quiet_until) { break; } } @@ -1214,70 +1132,49 @@ void check_mysql_transaction_stop(bool prepared = false) { } // namespace int main(int argc, char** argv) { - try - { + try { require(argc == 2, "Usage: ark_database_public_plugin_cancellation_tests " "redis|redis-stop|mysql|mysql-stop|mysql-transaction|mysql-statement|mysql-transaction-stop|" "mysql-statement-stop|redis-tls-stop"); const std::string_view protocol(argv[1]); - if (protocol == "redis") - { + if (protocol == "redis") { check_redis(); - } - else if (protocol == "redis-stop") - { + } else if (protocol == "redis-stop") { check_redis_stop(); } #if defined(ARKNET_ENABLE_SSL) - else if (protocol == "redis-tls-stop") - { + else if (protocol == "redis-tls-stop") { check_redis_tls_stop(); - } - else if (protocol == "mysql") - { + } else if (protocol == "mysql") { check_mysql(); - } - else if (protocol == "mysql-stop") - { + } else if (protocol == "mysql-stop") { check_mysql_stop(); - } - else if (protocol == "mysql-transaction") - { + } else if (protocol == "mysql-transaction") { check_mysql_transaction(); - } - else if (protocol == "mysql-statement") - { + } else if (protocol == "mysql-statement") { check_mysql_transaction(true); - } - else if (protocol == "mysql-transaction-stop") - { + } else if (protocol == "mysql-transaction-stop") { check_mysql_transaction_stop(); - } - else if (protocol == "mysql-statement-stop") - { + } else if (protocol == "mysql-statement-stop") { check_mysql_transaction_stop(true); } #endif - else - { + else { throw acceptance_failure("Requested database cancellation protocol is not enabled"); } if (protocol == "redis-stop" || protocol == "mysql-stop" || protocol == "mysql-transaction-stop" || - protocol == "mysql-statement-stop" || protocol == "redis-tls-stop") - { + protocol == "mysql-statement-stop" || protocol == "redis-tls-stop") { std::cout << protocol << " real DSO manager-stop cancellation, independent observation and resource retirement passed\n"; - } - else - { + } else { std::cout << protocol << " real DSO request cancellation, owner completion and natural retirement passed\n"; } return 0; + } catch (const acceptance_failure& error) { + std::cerr << error.what() << '\n'; + } catch (...) { + std::cerr << "Database DSO cancellation acceptance raised an unexpected coroutine/native exception\n"; } - catch (const acceptance_failure& error) - { std::cerr << error.what() << '\n'; } - catch (...) - { std::cerr << "Database DSO cancellation acceptance raised an unexpected coroutine/native exception\n"; } return 1; } diff --git a/tests/database/public_plugin_isolation.cpp b/tests/database/public_plugin_isolation.cpp index 477fa47f7..ba3d8e74e 100644 --- a/tests/database/public_plugin_isolation.cpp +++ b/tests/database/public_plugin_isolation.cpp @@ -22,23 +22,20 @@ namespace { using namespace std::chrono_literals; -class acceptance_failure : public std::runtime_error -{ +class acceptance_failure : public std::runtime_error { public: using std::runtime_error::runtime_error; }; void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { throw acceptance_failure(message); } } std::string environment(const char* name, bool allow_empty = false) { const auto* value = std::getenv(name); - if (!value || (!allow_empty && !*value)) - { + if (!value || (!allow_empty && !*value)) { throw acceptance_failure(std::string("Required test environment variable: ") + name); } return value; @@ -55,8 +52,7 @@ std::uint16_t port(const char* name) { // The executable only knows public interfaces. The actual module allocation, // implementation and deletion belong to the hidden-symbol plugin's DLL API. -class plugin_host -{ +class plugin_host { public: ark::plugin_manager manager; @@ -70,12 +66,10 @@ class plugin_host } ~plugin_host() { - if (!stopped_) - { - try - { drain(); } - catch (...) - { + if (!stopped_) { + try { + drain(); + } catch (...) { std::cerr << "Database plugin acceptance could not drain\n" << std::flush; std::_Exit(1); } @@ -99,15 +93,13 @@ class plugin_host require(tasks_->pending() == 1, "DSO workflow was not pending before application completion"); // Application operations complete their business workflow before framework cleanup. const auto deadline = std::chrono::steady_clock::now() + 30s; - while (tasks_->pending()) - { + while (tasks_->pending()) { require(std::chrono::steady_clock::now() < deadline, "DSO workflow did not complete"); require(manager.update(0), "DSO workflow owner update failed"); std::this_thread::sleep_for(1ms); } drain(); - if (failure_) - { + if (failure_) { std::rethrow_exception(failure_); } require(completions_ == 1 && completion_on_owner_ && tasks_->pending() == 0 && tasks_->closed() && @@ -120,8 +112,7 @@ class plugin_host private: void drain() { const auto deadline = std::chrono::steady_clock::now() + 30s; - while (!(stopped_ = manager.stop(0))) - { + while (!(stopped_ = manager.stop(0))) { require(manager.get_shutdown_state() != ark::plugin_manager::shutdown_state::failed && std::chrono::steady_clock::now() < deadline, "Database plugin did not finish managed/native retirement"); @@ -150,8 +141,7 @@ void mysql_success(plugin_host& host, const reply_type& reply) { } std::uint64_t integer(const arknet::mysql::field_value& field) { - if (const auto* value = std::get_if(&field)) - { + if (const auto* value = std::get_if(&field)) { return *value; } const auto* value = std::get_if(&field); @@ -166,8 +156,7 @@ std::uint64_t connection_id(const arknet::mysql::query_result& result) { void rows(const arknet::mysql::query_result& result, std::uint64_t reader_id, bool changed) { require(result.rows.size() == (changed ? 2 : 1), "Isolation read returned an unexpected row count"); - for (std::size_t index = 0; index < result.rows.size(); ++index) - { + for (std::size_t index = 0; index < result.rows.size(); ++index) { const auto& row = result.rows[index]; require(row.size() == 3 && integer(row[0]) == index + 1 && integer(row[2]) == reader_id, "Isolation read lost its row order or pinned server connection"); @@ -217,8 +206,7 @@ ark::task<> isolation_case(plugin_host& host, ark::mysql_module& database, std:: bool writer_ended{}; std::exception_ptr failure; const auto select = "SELECT id, payload, CONNECTION_ID() FROM " + table + " ORDER BY id"; - try - { + try { const std::string inspect = "SELECT CONNECTION_ID(), @@SESSION.transaction_isolation, @@GLOBAL.transaction_isolation"; auto level = co_await database.query(reader.transaction, inspect); @@ -264,18 +252,15 @@ ark::task<> isolation_case(plugin_host& host, ark::mysql_module& database, std:: retained_after.push_back(std::move(after)); std::cout << (repeatable ? "REPEATABLE READ" : "READ COMMITTED") << ": independent reader=" << reader_id << " writer=" << writer_id << ", uncommitted data hidden, committed visibility verified\n"; + } catch (...) { + failure = std::current_exception(); } - catch (...) - { failure = std::current_exception(); } - if (failure) - { - if (writer && !writer_ended) - { + if (failure) { + if (writer && !writer_ended) { co_await database.rollback(writer); host.check_executor(); } - if (!reader_ended) - { + if (!reader_ended) { co_await database.rollback(reader.transaction); host.check_executor(); } @@ -289,18 +274,16 @@ ark::task<> isolation_workflow(plugin_host& host, ark::mysql_module& database, s "writer", "CREATE TABLE " + table + " (id BIGINT PRIMARY KEY, payload VARCHAR(32)) ENGINE=InnoDB", 5s); mysql_success(host, created); std::exception_ptr failure; - try - { + try { auto initial = co_await database.query("writer", "INSERT INTO " + table + " VALUES (1, 'original')", 5s); mysql_success(host, initial); co_await isolation_case(host, database, table, repeatable, retained_snapshots, retained_after); + } catch (...) { + failure = std::current_exception(); } - catch (...) - { failure = std::current_exception(); } auto dropped = co_await database.query("writer", "DROP TABLE " + table, 5s); mysql_success(host, dropped); - if (failure) - { + if (failure) { std::rethrow_exception(failure); } } @@ -330,8 +313,7 @@ void check_isolation(bool repeatable) { } require(retained_snapshots.size() == 1 && retained_after.size() == 1, "Isolation owning results did not survive module/manager/runtime destruction"); - for (std::size_t index = 0; index < 1; ++index) - { + for (std::size_t index = 0; index < 1; ++index) { require(bool(retained_snapshots[index]) && bool(retained_after[index]), "Isolation retained result failed"); const auto reader_id = integer(retained_snapshots[index].result.rows.at(0).at(2)); rows(retained_snapshots[index].result, reader_id, false); @@ -342,8 +324,7 @@ void check_isolation(bool repeatable) { } // namespace int main(int argc, char** argv) { - try - { + try { require(argc == 2, "Usage: ark_database_public_plugin_isolation_tests repeatable-read|read-committed"); const std::string_view expected(argv[1]); require(expected == "repeatable-read" || expected == "read-committed", "Unknown expected isolation level"); @@ -351,10 +332,10 @@ int main(int argc, char** argv) { std::cout << "MySQL isolation real DSO/service, owner delivery, natural drain and owning-result checks passed\n"; return 0; + } catch (const acceptance_failure& error) { + std::cerr << error.what() << '\n'; + } catch (...) { + std::cerr << "MySQL isolation acceptance raised an unexpected exception\n"; } - catch (const acceptance_failure& error) - { std::cerr << error.what() << '\n'; } - catch (...) - { std::cerr << "MySQL isolation acceptance raised an unexpected exception\n"; } return 1; } diff --git a/tests/database/public_plugin_restart.cpp b/tests/database/public_plugin_restart.cpp index 78e87e13a..e1481f651 100644 --- a/tests/database/public_plugin_restart.cpp +++ b/tests/database/public_plugin_restart.cpp @@ -27,15 +27,13 @@ namespace { using namespace std::chrono_literals; -class acceptance_failure : public std::runtime_error -{ +class acceptance_failure : public std::runtime_error { public: using std::runtime_error::runtime_error; }; void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { throw acceptance_failure(message); } } @@ -55,16 +53,14 @@ std::uint16_t port(const char* name) { return static_cast(number); } -struct completion -{ +struct completion { unsigned count{}; bool on_owner{}; std::exception_ptr error; }; // Public interfaces only: no implementation/factory object is linked into this host. -class plugin_host -{ +class plugin_host { public: ark::plugin_manager manager; ark::task_group* tasks{}; @@ -79,12 +75,10 @@ class plugin_host } ~plugin_host() { - if (!stopped_) - { - try - { stop(); } - catch (...) - { + if (!stopped_) { + try { + stop(); + } catch (...) { std::cerr << "Database restart acceptance could not naturally drain\n" << std::flush; std::_Exit(1); } @@ -107,8 +101,7 @@ class plugin_host } static void check_completion(const completion& record) { - if (record.error) - { + if (record.error) { std::rethrow_exception(record.error); } require(record.count == 1 && record.on_owner, "DSO root completion repeated or escaped its owner"); @@ -116,8 +109,7 @@ class plugin_host void pump_until(const std::function& done) { const auto deadline = std::chrono::steady_clock::now() + 25s; - while (!done()) - { + while (!done()) { require(std::chrono::steady_clock::now() < deadline, "Database restart acceptance exceeded bound"); require(manager.update(0), "Database restart owner update failed"); // Throttling only; server-visible state establishes restart readiness. @@ -137,8 +129,7 @@ class plugin_host void stop() { const auto deadline = std::chrono::steady_clock::now() + 30s; - while (!(stopped_ = manager.stop(0))) - { + while (!(stopped_ = manager.stop(0))) { require(manager.get_shutdown_state() != ark::plugin_manager::shutdown_state::failed && std::chrono::steady_clock::now() < deadline, "Interrupted DSO requests did not naturally retire within the shutdown bound"); @@ -169,8 +160,7 @@ ark::task<> observer_interval() { // The shell actor owns the service and signal authority. The host publishes // observed server state and waits for independently verified service readiness. -class fault_barrier -{ +class fault_barrier { public: explicit fault_barrier(std::string protocol) : directory_(environment("ARK_DATABASE_FAULT_DIR")) @@ -242,16 +232,13 @@ void redis_success(const arknet::redis::result& result) { std::string client_field(std::string_view line, std::string_view name) { const auto marker = std::string(name) + "="; - for (std::size_t position{}; position < line.size();) - { + for (std::size_t position{}; position < line.size();) { const auto end = line.find(' ', position); const auto field = line.substr(position, end == std::string_view::npos ? end : end - position); - if (field.starts_with(marker)) - { + if (field.starts_with(marker)) { return std::string(field.substr(marker.size())); } - if (end == std::string_view::npos) - { + if (end == std::string_view::npos) { break; } position = end + 1; @@ -266,25 +253,21 @@ std::optional blocked_client(const arknet::redis::result& listing, reply.type == arknet::redis::value_type::verbatim_string, "Redis CLIENT LIST result was not text"); std::string_view remaining = reply.text; - if (reply.type == arknet::redis::value_type::verbatim_string) - { + if (reply.type == arknet::redis::value_type::verbatim_string) { require(remaining.starts_with("txt:"), "Redis CLIENT LIST verbatim result had an unexpected format"); remaining.remove_prefix(4); } std::optional found; - while (!remaining.empty()) - { + while (!remaining.empty()) { const auto end = remaining.find('\n'); const auto line = remaining.substr(0, end); if (client_field(line, "name") == tag && client_field(line, "cmd") == "xread" && - client_field(line, "flags").find('b') != std::string::npos) - { + client_field(line, "flags").find('b') != std::string::npos) { require(!found, "Redis observer saw concurrent replay of its tagged read-only command"); found = client_field(line, "id"); require(!found->empty(), "Redis observer could not identify the blocked client"); } - if (end == std::string_view::npos) - { + if (end == std::string_view::npos) { break; } remaining.remove_prefix(end + 1); @@ -316,15 +299,13 @@ ark::task<> redis_request( ark::task<> redis_observe(plugin_host& host, ark::redis_module& database, fault_barrier& barrier, const completion& request, const std::optional& result, std::string tag) { const auto deadline = std::chrono::steady_clock::now() + 10s; - for (;;) - { + for (;;) { require(!request.count && !result && std::chrono::steady_clock::now() < deadline, "Redis request retired before server-active observation or observation exceeded bound"); arknet::redis::command clients{"CLIENT", "LIST"}; auto listing = co_await database.command("observer", std::move(clients), 3s); host.check_executor(); - if (const auto id = blocked_client(listing, tag)) - { + if (const auto id = blocked_client(listing, tag)) { require(!request.count && !result, "Redis request completed before fault readiness"); barrier.observed(*id); co_return; @@ -415,8 +396,7 @@ void check_redis() { #if defined(ARKNET_ENABLE_SSL) ark::task<> mysql_preflight(plugin_host& host, ark::mysql_module& database) { - for (const auto* name : {"primary", "observer"}) - { + for (const auto* name : {"primary", "observer"}) { auto ready = co_await database.query(name, "SELECT 1", 5s); host.check_executor(); require(bool(ready), "MySQL restart preflight failed"); @@ -435,19 +415,16 @@ ark::task<> mysql_observe(plugin_host& host, ark::mysql_module& database, fault_ const auto sql = "SELECT CAST(ID AS SIGNED), STATE FROM information_schema.processlist " "WHERE ID <> CONNECTION_ID() AND INFO LIKE '%" + tag + "%'"; - for (;;) - { + for (;;) { require(!request.count && !result && std::chrono::steady_clock::now() < deadline, "MySQL request retired before server-active observation or observation exceeded bound"); auto listing = co_await database.query("observer", sql, 3s); host.check_executor(); require(bool(listing) && listing.result.rows.size() <= 1, "MySQL independent active observer failed"); - if (!listing.result.rows.empty()) - { + if (!listing.result.rows.empty()) { require(listing.result.rows[0].size() == 2, "MySQL observer lost its ID/state fields"); const auto* phase = std::get_if(&listing.result.rows[0][1]); - if (phase && *phase == "User sleep") - { + if (phase && *phase == "User sleep") { const auto id = std::get(listing.result.rows[0][0]); require(!request.count && !result, "MySQL request completed before fault readiness"); barrier.observed(std::to_string(id)); @@ -550,29 +527,25 @@ void check_mysql() { } // namespace int main(int argc, char** argv) { - try - { + try { require(argc <= 2, "Usage: ark_database_public_plugin_restart_tests [redis|mysql]"); const std::string_view protocol(argc == 1 ? "redis" : argv[1]); - if (protocol == "redis") - { + if (protocol == "redis") { check_redis(); } #if defined(ARKNET_ENABLE_SSL) - else if (protocol == "mysql") - { + else if (protocol == "mysql") { check_mysql(); } #endif - else - { + else { throw acceptance_failure("Unsupported database restart protocol"); } return 0; + } catch (const acceptance_failure& error) { + std::cerr << error.what() << '\n'; + } catch (...) { + std::cerr << "Database restart acceptance failed with an unexpected exception\n"; } - catch (const acceptance_failure& error) - { std::cerr << error.what() << '\n'; } - catch (...) - { std::cerr << "Database restart acceptance failed with an unexpected exception\n"; } return 1; } diff --git a/tests/database/public_plugin_server_termination.cpp b/tests/database/public_plugin_server_termination.cpp index 916edb8f8..f0eee24a5 100644 --- a/tests/database/public_plugin_server_termination.cpp +++ b/tests/database/public_plugin_server_termination.cpp @@ -30,15 +30,13 @@ namespace { using namespace std::chrono_literals; -class acceptance_failure : public std::runtime_error -{ +class acceptance_failure : public std::runtime_error { public: using std::runtime_error::runtime_error; }; void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { throw acceptance_failure(message); } } @@ -58,16 +56,14 @@ std::uint16_t port(const char* name) { return static_cast(number); } -struct completion -{ +struct completion { unsigned count{}; bool on_owner{}; std::exception_ptr error; }; // Public interfaces only: no implementation/factory object is linked into this host. -class plugin_host -{ +class plugin_host { public: ark::plugin_manager manager; ark::task_group* tasks{}; @@ -82,12 +78,10 @@ class plugin_host } ~plugin_host() { - if (!stopped_) - { - try - { stop(); } - catch (...) - { + if (!stopped_) { + try { + stop(); + } catch (...) { std::cerr << "Database termination acceptance could not naturally drain\n" << std::flush; std::_Exit(1); } @@ -110,8 +104,7 @@ class plugin_host } static void check_completion(const completion& record) { - if (record.error) - { + if (record.error) { std::rethrow_exception(record.error); } require(record.count == 1 && record.on_owner, "DSO root completion repeated or escaped its owner"); @@ -119,8 +112,7 @@ class plugin_host void pump_until(const std::function& done) { const auto deadline = std::chrono::steady_clock::now() + 25s; - while (!done()) - { + while (!done()) { require(std::chrono::steady_clock::now() < deadline, "Database termination acceptance exceeded bound"); require(manager.update(0), "Database termination owner update failed"); // Throttling only; server-visible state establishes termination readiness. @@ -138,8 +130,7 @@ class plugin_host void stop() { const auto deadline = std::chrono::steady_clock::now() + 30s; - while (!(stopped_ = manager.stop(0))) - { + while (!(stopped_ = manager.stop(0))) { require(manager.get_shutdown_state() != ark::plugin_manager::shutdown_state::failed && std::chrono::steady_clock::now() < deadline, "Interrupted DSO requests did not naturally retire within the shutdown bound"); @@ -170,8 +161,7 @@ ark::task<> observer_interval() { // The shell actor owns the service and signal authority. This host only publishes // an observed server-side request ID through a fresh, private token barrier. -class fault_barrier -{ +class fault_barrier { public: explicit fault_barrier(std::string protocol) : directory_(environment("ARK_DATABASE_FAULT_DIR")) @@ -228,16 +218,13 @@ void redis_success(const arknet::redis::result& result) { std::string client_field(std::string_view line, std::string_view name) { const auto marker = std::string(name) + "="; - for (std::size_t position{}; position < line.size();) - { + for (std::size_t position{}; position < line.size();) { const auto end = line.find(' ', position); const auto field = line.substr(position, end == std::string_view::npos ? end : end - position); - if (field.starts_with(marker)) - { + if (field.starts_with(marker)) { return std::string(field.substr(marker.size())); } - if (end == std::string_view::npos) - { + if (end == std::string_view::npos) { break; } position = end + 1; @@ -252,25 +239,21 @@ std::optional blocked_client(const arknet::redis::result& listing, reply.type == arknet::redis::value_type::verbatim_string, "Redis CLIENT LIST result was not text"); std::string_view remaining = reply.text; - if (reply.type == arknet::redis::value_type::verbatim_string) - { + if (reply.type == arknet::redis::value_type::verbatim_string) { require(remaining.starts_with("txt:"), "Redis CLIENT LIST verbatim result had an unexpected format"); remaining.remove_prefix(4); } std::optional found; - while (!remaining.empty()) - { + while (!remaining.empty()) { const auto end = remaining.find('\n'); const auto line = remaining.substr(0, end); if (client_field(line, "name") == tag && client_field(line, "cmd") == "xread" && - client_field(line, "flags").find('b') != std::string::npos) - { + client_field(line, "flags").find('b') != std::string::npos) { require(!found, "Redis observer saw concurrent replay of its tagged read-only command"); found = client_field(line, "id"); require(!found->empty(), "Redis observer could not identify the blocked client"); } - if (end == std::string_view::npos) - { + if (end == std::string_view::npos) { break; } remaining.remove_prefix(end + 1); @@ -302,15 +285,13 @@ ark::task<> redis_request( ark::task<> redis_observe(plugin_host& host, ark::redis_module& database, fault_barrier& barrier, const completion& request, const std::optional& result, std::string tag) { const auto deadline = std::chrono::steady_clock::now() + 10s; - for (;;) - { + for (;;) { require(!request.count && !result && std::chrono::steady_clock::now() < deadline, "Redis request retired before server-active observation or observation exceeded bound"); arknet::redis::command clients{"CLIENT", "LIST"}; auto listing = co_await database.command("observer", std::move(clients), 3s); host.check_executor(); - if (const auto id = blocked_client(listing, tag)) - { + if (const auto id = blocked_client(listing, tag)) { require(!request.count && !result, "Redis request completed before fault readiness"); barrier.observed(*id); co_return; @@ -371,8 +352,7 @@ void check_redis() { #if defined(ARKNET_ENABLE_SSL) ark::task<> mysql_preflight(plugin_host& host, ark::mysql_module& database) { - for (const auto* name : {"primary", "observer"}) - { + for (const auto* name : {"primary", "observer"}) { auto ready = co_await database.query(name, "SELECT 1", 5s); host.check_executor(); require(bool(ready), "MySQL termination preflight failed"); @@ -391,19 +371,16 @@ ark::task<> mysql_observe(plugin_host& host, ark::mysql_module& database, fault_ const auto sql = "SELECT CAST(ID AS SIGNED), STATE FROM information_schema.processlist " "WHERE ID <> CONNECTION_ID() AND INFO LIKE '%" + tag + "%'"; - for (;;) - { + for (;;) { require(!request.count && !result && std::chrono::steady_clock::now() < deadline, "MySQL request retired before server-active observation or observation exceeded bound"); auto listing = co_await database.query("observer", sql, 3s); host.check_executor(); require(bool(listing) && listing.result.rows.size() <= 1, "MySQL independent active observer failed"); - if (!listing.result.rows.empty()) - { + if (!listing.result.rows.empty()) { require(listing.result.rows[0].size() == 2, "MySQL observer lost its ID/state fields"); const auto* phase = std::get_if(&listing.result.rows[0][1]); - if (phase && *phase == "User sleep") - { + if (phase && *phase == "User sleep") { const auto id = std::get(listing.result.rows[0][0]); require(!request.count && !result, "MySQL request completed before fault readiness"); barrier.observed(std::to_string(id)); @@ -472,30 +449,26 @@ void check_mysql() { } // namespace int main(int argc, char** argv) { - try - { + try { require(argc == 2, "Usage: ark_database_public_plugin_server_termination_tests redis|mysql"); const std::string_view protocol(argv[1]); - if (protocol == "redis") - { + if (protocol == "redis") { check_redis(); } #if defined(ARKNET_ENABLE_SSL) - else if (protocol == "mysql") - { + else if (protocol == "mysql") { check_mysql(); } #endif - else - { + else { throw acceptance_failure("Requested server termination protocol is not enabled"); } std::cout << protocol << " real DSO server termination, owner completion and natural retirement passed\n"; return 0; + } catch (const acceptance_failure& error) { + std::cerr << error.what() << '\n'; + } catch (...) { + std::cerr << "Database DSO server termination acceptance raised an unexpected coroutine/native exception\n"; } - catch (const acceptance_failure& error) - { std::cerr << error.what() << '\n'; } - catch (...) - { std::cerr << "Database DSO server termination acceptance raised an unexpected coroutine/native exception\n"; } return 1; } diff --git a/tests/database/public_plugin_service.cpp b/tests/database/public_plugin_service.cpp index ec32934ba..7818fa4f4 100644 --- a/tests/database/public_plugin_service.cpp +++ b/tests/database/public_plugin_service.cpp @@ -32,23 +32,20 @@ namespace { using namespace std::chrono_literals; -class acceptance_failure : public std::runtime_error -{ +class acceptance_failure : public std::runtime_error { public: using std::runtime_error::runtime_error; }; void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { throw acceptance_failure(message); } } std::string environment(const char* name, bool allow_empty = false) { const auto* value = std::getenv(name); - if (!value || (!allow_empty && !*value)) - { + if (!value || (!allow_empty && !*value)) { throw acceptance_failure(std::string("Required test environment variable: ") + name); } return value; @@ -65,8 +62,7 @@ std::uint16_t port(const char* name) { // The executable only knows public interfaces. The actual module allocation, // implementation and deletion belong to the hidden-symbol plugin's DLL API. -class plugin_host -{ +class plugin_host { public: ark::plugin_manager manager; @@ -80,12 +76,10 @@ class plugin_host } ~plugin_host() { - if (!stopped_) - { - try - { drain(); } - catch (...) - { + if (!stopped_) { + try { + drain(); + } catch (...) { std::cerr << "Database plugin acceptance could not drain\n" << std::flush; std::_Exit(1); } @@ -109,15 +103,13 @@ class plugin_host require(tasks_->pending() == 1, "DSO workflow was not pending before application completion"); // Application operations complete their business workflow before framework cleanup. const auto deadline = std::chrono::steady_clock::now() + 30s; - while (tasks_->pending()) - { + while (tasks_->pending()) { require(std::chrono::steady_clock::now() < deadline, "DSO workflow did not complete"); require(manager.update(0), "DSO workflow owner update failed"); std::this_thread::sleep_for(1ms); } drain(); - if (failure_) - { + if (failure_) { std::rethrow_exception(failure_); } require(completions_ == 1 && completion_on_owner_ && tasks_->pending() == 0 && tasks_->closed() && @@ -130,8 +122,7 @@ class plugin_host private: void drain() { const auto deadline = std::chrono::steady_clock::now() + 30s; - while (!(stopped_ = manager.stop(0))) - { + while (!(stopped_ = manager.stop(0))) { require(manager.get_shutdown_state() != ark::plugin_manager::shutdown_state::failed && std::chrono::steady_clock::now() < deadline, "Database plugin did not finish managed/native retirement"); @@ -172,12 +163,10 @@ void check_redis() { ark::redis_options options; options.pool.connection.host = environment("ARK_DATABASE_REDIS_HOST"); options.pool.connection.port = std::to_string(port("ARK_DATABASE_REDIS_PORT")); - if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) - { + if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) { options.pool.connection.username = user; } - if (const auto* password = std::getenv("ARK_DATABASE_REDIS_PASSWORD")) - { + if (const auto* password = std::getenv("ARK_DATABASE_REDIS_PASSWORD")) { options.pool.connection.password = password; } options.pool.max_connections = 1; @@ -238,8 +227,7 @@ void check_redis_tls(std::string_view mode) { environment(mode == "redis-tls-wrong-host" ? "ARK_DATABASE_REDIS_WRONG_HOST" : "ARK_DATABASE_REDIS_HOST"); options.pool.connection.port = std::to_string(port("ARK_DATABASE_REDIS_PORT")); options.pool.connection.password = environment("ARK_DATABASE_REDIS_PASSWORD"); - if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) - { + if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) { options.pool.connection.username = user; } options.pool.certificate_authority = @@ -256,24 +244,18 @@ void check_redis_tls(std::string_view mode) { options.pool.connection.host = "invalid.invalid"; options.pool.connection.password = "changed"; options.pool.certificate_authority = "missing-certificate.pem"; - if (mode == "redis-tls") - { + if (mode == "redis-tls") { host.run(redis_tls_workflow(host, *database, binary, command, pipeline)); - } - else - { + } else { host.run(redis_tls_rejection_workflow(host, *database, rejected)); } } - if (mode == "redis-tls") - { + if (mode == "redis-tls") { require(command && pipeline && bool(*command) && bool(*pipeline) && command->replies[0].text == binary && pipeline->replies[0].text == binary && pipeline->replies[1].text.empty() && pipeline->replies[2].text == "PONG", "Redis TLS owning command/pipeline results did not survive host destruction"); - } - else - { + } else { require(rejected && certificate_verification_failed(*rejected), "Redis TLS owning verification error did not survive host destruction"); std::cout << "Native connection_failed / TLS certificate verification failed; command_may_have_run=false; " @@ -298,8 +280,7 @@ ark::task<> mysql_workflow(plugin_host& host, ark::mysql_module& database, std:: std::get(prepared->result.rows[0][1]) == binary && prepared->statement_close && bool(*prepared->statement_close) && !prepared->statement_close_exception, "MySQL DSO prepared binary result or statement cleanup failed"); - for (const bool commit : {true, false}) - { + for (const bool commit : {true, false}) { auto begun = co_await database.begin("service", {10s, 3s}); host.check_executor(); require(bool(begun) && begun.transaction && @@ -358,8 +339,7 @@ void mysql_success(plugin_host& host, const reply_type& reply) { std::uint64_t mysql_integer(const arknet::mysql::query_result& result) { require(result.rows.size() == 1 && result.rows[0].size() == 1, "MySQL DSO scalar result has wrong shape"); const auto& field = result.rows[0][0]; - if (const auto* value = std::get_if(&field)) - { + if (const auto* value = std::get_if(&field)) { return *value; } const auto* value = std::get_if(&field); @@ -391,8 +371,7 @@ ark::task<> mysql_write_checks(plugin_host& host, ark::mysql_module& database, s std::get(retained->result.rows[0][0]) == binary, "MySQL DSO observer did not see the parameterized autocommit write"); - for (const bool commit : {true, false}) - { + for (const bool commit : {true, false}) { auto begun = co_await database.begin("service", {15s, 3s}); mysql_success(host, begun); require(begun.transaction && begun.transaction_status.outcome == ark::mysql_transaction_outcome::active, @@ -401,8 +380,7 @@ ark::task<> mysql_write_checks(plugin_host& host, ark::mysql_module& database, s const auto predicate = " WHERE id=" + std::to_string(id); std::exception_ptr failure; bool ended{}; - try - { + try { std::vector values{std::int64_t{id}, binary}; auto inserted = co_await database.execute( begun.transaction, "INSERT INTO " + table + " (id, payload) VALUES (?, ?)", std::move(values)); @@ -431,13 +409,11 @@ ark::task<> mysql_write_checks(plugin_host& host, ark::mysql_module& database, s mysql_success(host, visible); require(mysql_integer(visible.result) == (commit ? 1 : 0), "MySQL DSO observer did not see confirmed commit/rollback visibility"); + } catch (...) { + failure = std::current_exception(); } - catch (...) - { failure = std::current_exception(); } - if (failure) - { - if (!ended) - { + if (failure) { + if (!ended) { // Explicit cleanup only; cancellation is not rollback evidence. co_await database.rollback(begun.transaction); host.check_executor(); @@ -460,14 +436,14 @@ ark::task<> mysql_write_workflow(plugin_host& host, ark::mysql_module& database, "service", "CREATE TABLE " + table + " (id BIGINT PRIMARY KEY, payload VARBINARY(128)) ENGINE=InnoDB", 5s); mysql_success(host, created); std::exception_ptr failure; - try - { co_await mysql_write_checks(host, database, table, std::move(binary), retained, retained_transaction); } - catch (...) - { failure = std::current_exception(); } + try { + co_await mysql_write_checks(host, database, table, std::move(binary), retained, retained_transaction); + } catch (...) { + failure = std::current_exception(); + } auto dropped = co_await database.query("observer", "DROP TABLE " + table, 5s); mysql_success(host, dropped); - if (failure) - { + if (failure) { std::rethrow_exception(failure); } } @@ -508,40 +484,31 @@ void check_mysql_transactions() { } // namespace int main(int argc, char** argv) { - try - { + try { require(argc == 2, "Usage: ark_database_public_plugin_service_tests " "redis|mysql|mysql-transactions|redis-tls|redis-tls-untrusted-ca|redis-tls-wrong-host"); const std::string_view protocol(argv[1]); - if (protocol == "redis") - { + if (protocol == "redis") { check_redis(); } #if defined(ARKNET_ENABLE_SSL) - else if (protocol == "redis-tls" || protocol == "redis-tls-untrusted-ca" || protocol == "redis-tls-wrong-host") - { + else if (protocol == "redis-tls" || protocol == "redis-tls-untrusted-ca" || + protocol == "redis-tls-wrong-host") { check_redis_tls(protocol); - } - else if (protocol == "mysql") - { + } else if (protocol == "mysql") { check_mysql(); - } - else if (protocol == "mysql-transactions") - { + } else if (protocol == "mysql-transactions") { check_mysql_transactions(); } #endif - else - { + else { throw acceptance_failure("Requested database plugin protocol is not enabled"); } std::cout << protocol << " real DSO/service, owner delivery, drain and owning-result checks passed\n"; return 0; - } - catch (const acceptance_failure& error) - { std::cerr << error.what() << '\n'; } - catch (...) - { + } catch (const acceptance_failure& error) { + std::cerr << error.what() << '\n'; + } catch (...) { // Do not print credentials or server-controlled native exception text. std::cerr << "Database plugin service acceptance raised an unexpected exception\n"; } diff --git a/tests/database/public_redis_module.cpp b/tests/database/public_redis_module.cpp index 55b82c2e8..8ac0a7826 100644 --- a/tests/database/public_redis_module.cpp +++ b/tests/database/public_redis_module.cpp @@ -22,14 +22,12 @@ using result_type = arknet::redis::result; using client_errc = arknet::redis::client_errc; // Bounded loopback RESP protocol peer, not a Redis server implementation. -class redis_peer -{ +class redis_peer { public: explicit redis_peer(bool tls = false) : tls_(tls) { #if defined(ARKNET_ENABLE_SSL) - if (tls_) - { + if (tls_) { const std::string directory = ARK_DATABASE_REDIS_CERT_DIR; context_.use_certificate_chain_file(directory + "/server.pem"); context_.use_private_key_file(directory + "/server-key.pem", asio::ssl::context::pem); @@ -67,8 +65,7 @@ class redis_peer asio::awaitable serve() { deadline_.expires_after(5s); deadline_.async_wait([this](arknet::error_code error) { - if (!error) - { + if (!error) { arknet::error_code ignored; acceptor_.close(ignored); socket_.close(ignored); @@ -76,18 +73,15 @@ class redis_peer }); arknet::error_code error; co_await acceptor_.async_accept(socket_, asio::redirect_error(asio::use_awaitable, error)); - if (error) - { + if (error) { co_return; } #if defined(ARKNET_ENABLE_SSL) - if (tls_) - { + if (tls_) { asio::ssl::stream stream(socket_, context_); co_await stream.async_handshake( asio::ssl::stream_base::server, asio::redirect_error(asio::use_awaitable, error)); - if (!error) - { + if (!error) { co_await exchange(stream); } co_return; @@ -100,84 +94,59 @@ class redis_peer asio::awaitable exchange(stream_type& stream) { arknet::error_code error; arknet::redis::detail::resp_decoder decoder; - for (;;) - { + for (;;) { arknet::redis::value value; const auto status = decoder.next(value); - if (status == arknet::redis::detail::resp_status::ready) - { - if (value.type != arknet::redis::value_type::array || value.elements.empty()) - { + if (status == arknet::redis::detail::resp_status::ready) { + if (value.type != arknet::redis::value_type::array || value.elements.empty()) { throw std::runtime_error("Expected RESP command array"); } arknet::redis::command arguments; - for (auto& argument : value.elements) - { + for (auto& argument : value.elements) { arguments.push_back(std::move(argument.text)); } std::string response; - if (arguments == arknet::redis::command{"HELLO", "3"}) - { + if (arguments == arknet::redis::command{"HELLO", "3"}) { response = "%1\r\n+proto\r\n:3\r\n"; - } - else if (arguments == arknet::redis::command{"RESET"}) - { + } else if (arguments == arknet::redis::command{"RESET"}) { response = "+RESET\r\n"; - } - else - { + } else { ++business_commands_; - if (arguments.size() == 2 && arguments[0] == "ECHO") - { + if (arguments.size() == 2 && arguments[0] == "ECHO") { response = "$" + std::to_string(arguments[1].size()) + "\r\n" + arguments[1] + "\r\n"; - } - else if (arguments == arknet::redis::command{"PING"}) - { + } else if (arguments == arknet::redis::command{"PING"}) { response = "+PONG\r\n"; - } - else if (arguments == arknet::redis::command{"GET", "missing"}) - { + } else if (arguments == arknet::redis::command{"GET", "missing"}) { response = "$-1\r\n"; - } - else if (arguments == arknet::redis::command{"FAIL"}) - { + } else if (arguments == arknet::redis::command{"FAIL"}) { response = "-ERR fixture\r\n"; - } - else if (arguments == arknet::redis::command{"BLOCK"}) - { + } else if (arguments == arknet::redis::command{"BLOCK"}) { blocked_ = true; continue; - } - else - { + } else { throw std::runtime_error("Unexpected command in RESP fixture"); } } - if (blocked_) - { + if (blocked_) { continue; } co_await asio::async_write( stream, asio::buffer(response), asio::redirect_error(asio::use_awaitable, error)); - if (error) - { + if (error) { co_return; } continue; } - if (status != arknet::redis::detail::resp_status::need_more) - { + if (status != arknet::redis::detail::resp_status::need_more) { throw std::runtime_error("Invalid fixture RESP input"); } std::array bytes; const auto count = co_await stream.async_read_some(asio::buffer(bytes), asio::redirect_error(asio::use_awaitable, error)); - if (error) - { + if (error) { co_return; } - if (!decoder.append(std::string_view(bytes.data(), count))) - { + if (!decoder.append(std::string_view(bytes.data(), count))) { throw std::runtime_error("RESP fixture limit reached"); } } @@ -197,8 +166,7 @@ class redis_peer std::thread worker_; }; -struct module_owner -{ +struct module_owner { ark::plugin_manager manager; std::unique_ptr redis_owner{ark::detail::make_redis_module()}; ark::redis_module& redis{*redis_owner}; @@ -211,13 +179,11 @@ struct module_owner module_owner() { redis.set_plugin_manager(&manager); redis.set_name("redis"); - if (!manager.add_module("redis", &redis) || !manager.add_module("consumer", &consumer)) - { + if (!manager.add_module("redis", &redis) || !manager.add_module("consumer", &consumer)) { throw std::runtime_error("Cannot install Redis test modules"); } // ARK_REGISTER_MODULE installs this update hook before module init. - if (!manager.add_update_module(&redis)) - { + if (!manager.add_update_module(&redis)) { throw std::runtime_error("Cannot register Redis update hook"); } tasks = &manager.create_task_group(consumer); @@ -225,8 +191,7 @@ struct module_owner ~module_owner() { const auto deadline = std::chrono::steady_clock::now() + 4s; - while (!manager.stop(0) && std::chrono::steady_clock::now() < deadline) - { + while (!manager.stop(0) && std::chrono::steady_clock::now() < deadline) { manager.update(0); std::this_thread::sleep_for(1ms); } @@ -256,10 +221,8 @@ struct module_owner template bool pump_until(predicate_type predicate) { const auto deadline = std::chrono::steady_clock::now() + 3s; - while (!predicate()) - { - if (std::chrono::steady_clock::now() >= deadline) - { + while (!predicate()) { + if (std::chrono::steady_clock::now() >= deadline) { return false; } manager.update(0); diff --git a/tests/database/public_redis_plugin.cpp b/tests/database/public_redis_plugin.cpp index d63dacab8..dd2e8ec20 100644 --- a/tests/database/public_redis_plugin.cpp +++ b/tests/database/public_redis_plugin.cpp @@ -11,13 +11,11 @@ namespace { ark::task<> request(ark::redis_module& database) { auto missing = co_await database.command("missing", {"PING"}); - if (missing.error != arknet::redis::client_errc::not_connected) - { + if (missing.error != arknet::redis::client_errc::not_connected) { throw std::runtime_error("Expected missing connection result across the plugin boundary"); } auto result = co_await database.command("test", {"PING"}, std::chrono::milliseconds(10)); - if (result) - { + if (result) { throw std::runtime_error("Expected unavailable test endpoint"); } } @@ -27,20 +25,17 @@ int main() { ark::logger::init(nullptr); ark::logger::instance()->set_log_func([](spdlog::level::level_enum, const std::string&) {}); ark::plugin_manager manager; - if (!manager.start(0, ARK_DATABASE_PLUGIN_DIR, "", {{"ark_database_redis_plugin", ""}})) - { + if (!manager.start(0, ARK_DATABASE_PLUGIN_DIR, "", {{"ark_database_redis_plugin", ""}})) { return 1; } auto* database = manager.find_module(); - if (!database) - { + if (!database) { return 2; } ark::redis_options options; options.pool.connection.host = "127.0.0.1"; options.pool.connection.port = "1"; - if (!database->configure("test", std::move(options))) - { + if (!database->configure("test", std::move(options))) { return 3; } std::exception_ptr failure; @@ -48,48 +43,41 @@ int main() { if (!manager.create_task_group(*database).start(request(*database), [&](auto error) { failure = error; completed = true; - })) - { + })) { return 4; } const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); // Complete the public coroutine while running. Process shutdown cancels // residual tasks; it no longer completes business requests on their behalf. - while (!completed && std::chrono::steady_clock::now() < deadline) - { + while (!completed && std::chrono::steady_clock::now() < deadline) { manager.update(0); std::this_thread::sleep_for(std::chrono::milliseconds(1)); } - if (!completed) - { + if (!completed) { return 8; } - while (!manager.stop(0) && std::chrono::steady_clock::now() < deadline) - { - if (manager.get_shutdown_state() == ark::plugin_manager::shutdown_state::failed) - { + while (!manager.stop(0) && std::chrono::steady_clock::now() < deadline) { + if (manager.get_shutdown_state() == ark::plugin_manager::shutdown_state::failed) { return 5; } manager.update(0); std::this_thread::sleep_for(std::chrono::milliseconds(1)); } - if (manager.get_shutdown_state() != ark::plugin_manager::shutdown_state::stopped || failure) - { + if (manager.get_shutdown_state() != ark::plugin_manager::shutdown_state::stopped || failure) { std::cerr << "Public Redis DSO shutdown state=" << static_cast(manager.get_shutdown_state()) << ", pending tasks=" << manager.pending_tasks() << '\n'; - if (failure) - { - try - { std::rethrow_exception(failure); } - catch (const std::exception& error) - { std::cerr << "Public Redis DSO task failed: " << error.what() << '\n'; } - catch (...) - { std::cerr << "Public Redis DSO task failed with an unknown exception\n"; } + if (failure) { + try { + std::rethrow_exception(failure); + } catch (const std::exception& error) { + std::cerr << "Public Redis DSO task failed: " << error.what() << '\n'; + } catch (...) { + std::cerr << "Public Redis DSO task failed with an unknown exception\n"; + } } return 6; } - if (manager.pending_tasks()) - { + if (manager.pending_tasks()) { return 7; } std::cout << "Public Redis DSO registration, coroutine delivery and shutdown passed\n"; diff --git a/tests/database/public_service.cpp b/tests/database/public_service.cpp index 077b59996..e0a12b60f 100644 --- a/tests/database/public_service.cpp +++ b/tests/database/public_service.cpp @@ -25,16 +25,14 @@ namespace { using namespace std::chrono_literals; unsigned checks{}; -class acceptance_failure : public std::runtime_error -{ +class acceptance_failure : public std::runtime_error { public: using std::runtime_error::runtime_error; }; void require(bool condition, const std::string& message) { ++checks; - if (!condition) - { + if (!condition) { throw acceptance_failure(message); } } @@ -54,20 +52,16 @@ std::uint16_t port(const char* name) { return static_cast(number); } -struct workflow_result -{ +struct workflow_result { std::exception_ptr failure; unsigned completions{}; bool completion_on_owner{}; }; -struct unwind_workflow -{ -}; +struct unwind_workflow {}; void verify_workflow(const workflow_result& result) { - if (result.failure) - { + if (result.failure) { std::rethrow_exception(result.failure); } require(result.completions == 1 && result.completion_on_owner, @@ -77,8 +71,7 @@ void verify_workflow(const workflow_result& result) { // Register the real implementation exactly as a plugin does, with a consumer's // manager-owned task group sharing the module's manual_runtime. template -struct module_owner -{ +struct module_owner { ark::plugin_manager manager; std::unique_ptr database_owner; module_type& database; @@ -104,14 +97,12 @@ struct module_owner } ~module_owner() { - if (!stopped) - { + if (!stopped) { // Never destroy business captures or a group with suspended tasks. // Failure paths keep pumping accepted work before unwinding. - try - { finish(); } - catch (...) - { + try { + finish(); + } catch (...) { std::cerr << "Public database cleanup could not drain\n" << std::flush; std::_Exit(1); } @@ -139,17 +130,14 @@ struct module_owner void finish() { const auto deadline = std::chrono::steady_clock::now() + 30s; // Explicit application completion precedes resource cleanup, including host unwinding. - while (tasks->pending()) - { + while (tasks->pending()) { require(std::chrono::steady_clock::now() < deadline, "Public database workflow did not complete"); require(manager.update(0), "Public database workflow owner update failed"); std::this_thread::sleep_for(1ms); } - while (!(stopped = manager.stop(0))) - { + while (!(stopped = manager.stop(0))) { if (manager.get_shutdown_state() == ark::plugin_manager::shutdown_state::failed || - std::chrono::steady_clock::now() >= deadline) - { + std::chrono::steady_clock::now() >= deadline) { throw acceptance_failure("Public database manager did not drain/stop successfully"); } require(manager.update(0), "Public database manager update failed during drain"); @@ -185,12 +173,10 @@ void check_redis(bool unwind) { ark::redis_options options; options.pool.connection.host = environment("ARK_DATABASE_REDIS_HOST"); options.pool.connection.port = std::to_string(port("ARK_DATABASE_REDIS_PORT")); - if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) - { + if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) { options.pool.connection.username = user; } - if (const auto* password = std::getenv("ARK_DATABASE_REDIS_PASSWORD")) - { + if (const auto* password = std::getenv("ARK_DATABASE_REDIS_PASSWORD")) { options.pool.connection.password = password; } options.pool.max_connections = 1; @@ -199,8 +185,7 @@ void check_redis(bool unwind) { std::optional retained; workflow_result report; bool unwound{}; - try - { + try { module_owner owner(report, ark::detail::make_redis_module()); ark::redis_module& database = owner.database; require(database.configure("primary", options), "Cannot configure public Redis module"); @@ -213,14 +198,13 @@ void check_redis(bool unwind) { commands[0][1] = "changed"; commands.clear(); owner.start(redis_workflow(owner, std::move(pending), binary, retained)); - if (unwind) - { + if (unwind) { throw unwind_workflow{}; } owner.verify(); + } catch (const unwind_workflow&) { + unwound = true; } - catch (const unwind_workflow&) - { unwound = true; } require(unwound == unwind, "Redis host stack did not unwind as requested"); verify_workflow(report); require(retained && retained->replies[0].text == binary, @@ -268,8 +252,7 @@ ark::task<> mysql_checks(module_owner& owner, ark::taskstatement_close && bool(*retained_prepared->statement_close), "Public MySQL prepared statement close was not reported"); - for (const bool commit : {true, false}) - { + for (const bool commit : {true, false}) { auto begun = co_await database.begin("primary", {10s, 3s}); owner.check_executor(); success(begun); @@ -315,15 +298,15 @@ ark::task<> mysql_workflow(module_owner& owner, ark::task retained_text, retained_prepared; workflow_result report; bool unwound{}; - try - { + try { module_owner owner(report, ark::detail::make_mysql_module()); ark::mysql_module& database = owner.database; require(database.configure("primary", options), "Cannot configure public MySQL module"); @@ -359,14 +341,13 @@ void check_mysql(bool unwind) { parameters[0] = std::int64_t{123}; parameters[1] = std::string("changed"); owner.start(mysql_workflow(owner, std::move(prepared), table, binary, retained_text, retained_prepared)); - if (unwind) - { + if (unwind) { throw unwind_workflow{}; } owner.verify(); + } catch (const unwind_workflow&) { + unwound = true; } - catch (const unwind_workflow&) - { unwound = true; } require(unwound == unwind, "MySQL host stack did not unwind as requested"); verify_workflow(report); require(retained_text && std::get(retained_text->result.rows[0][1]) == "owned text" && @@ -378,33 +359,27 @@ void check_mysql(bool unwind) { } // namespace int main(int argc, char** argv) { - try - { + try { require(argc == 2, "Usage: ark_database_public_service_tests redis|mysql"); const std::string_view protocol(argv[1]); - if (protocol == "redis") - { + if (protocol == "redis") { check_redis(false); check_redis(true); } #if defined(ARKNET_ENABLE_SSL) - else if (protocol == "mysql") - { + else if (protocol == "mysql") { check_mysql(false); check_mysql(true); } #endif - else - { + else { throw acceptance_failure("Requested public database protocol is not enabled"); } std::cout << protocol << " public module real-service checks passed: " << checks << '\n'; return 0; - } - catch (const acceptance_failure& error) - { std::cerr << error.what() << '\n'; } - catch (...) - { + } catch (const acceptance_failure& error) { + std::cerr << error.what() << '\n'; + } catch (...) { // Native diagnostics can contain server-controlled text. Do not emit // endpoint/authentication configuration or arbitrary exception messages. std::cerr << "Public database service acceptance raised an unexpected exception\n"; diff --git a/tests/database/redis_service.cpp b/tests/database/redis_service.cpp index 066ea1c69..f18c5a3d5 100644 --- a/tests/database/redis_service.cpp +++ b/tests/database/redis_service.cpp @@ -17,22 +17,19 @@ using redis_service = ark::detail::redis_service; using service_result = ark::detail::redis_service_result; void check(bool condition, const char* message) { - if (!condition) - { + if (!condition) { throw std::runtime_error(message); } } arknet::redis::result await_result(redis_service& service, std::optional& completion) { const auto expires = std::chrono::steady_clock::now() + 5s; - while (!completion && std::chrono::steady_clock::now() < expires) - { + while (!completion && std::chrono::steady_clock::now() < expires) { service.update(); std::this_thread::sleep_for(1ms); } check(bool(completion), "Cancelled Redis operation did not deliver a terminal continuation"); - if (auto* failure = std::get_if(&*completion)) - { + if (auto* failure = std::get_if(&*completion)) { std::rethrow_exception(*failure); } auto result = std::get(std::move(*completion)); @@ -53,18 +50,15 @@ arknet::redis::result command(redis_service& service, arknet::redis::command arg void wait_for_block(redis_service& observer, std::int64_t client_id) { const auto expires = std::chrono::steady_clock::now() + 4s; const auto marker = "id=" + std::to_string(client_id) + " "; - while (std::chrono::steady_clock::now() < expires) - { + while (std::chrono::steady_clock::now() < expires) { const auto clients = command(observer, {"CLIENT", "LIST"}); check(clients.replies.size() == 1, "Redis CLIENT LIST response shape changed"); const auto& listing = clients.replies.front().text; const auto start = listing.find(marker); - if (start != std::string::npos) - { + if (start != std::string::npos) { const auto end = listing.find('\n', start); const auto blocked = listing.find("cmd=blpop", start); - if (blocked != std::string::npos && (end == std::string::npos || blocked < end)) - { + if (blocked != std::string::npos && (end == std::string::npos || blocked < end)) { return; } } @@ -114,11 +108,9 @@ void check_cancellation(const arknet::redis::pool_options& options, const std::s command(observer, {"LPUSH", blocking_key, "after-cancel"}); const auto consumed_deadline = std::chrono::steady_clock::now() + 4s; bool consumed{}; - while (std::chrono::steady_clock::now() < consumed_deadline) - { + while (std::chrono::steady_clock::now() < consumed_deadline) { consumed = command(observer, {"LLEN", blocking_key}).replies.front().integer == 0; - if (consumed) - { + if (consumed) { break; } } @@ -132,8 +124,7 @@ void check_cancellation(const arknet::redis::pool_options& options, const std::s ready.start({"ECHO", "native-success"}, [&](auto result) { ready_result = std::move(result); }, 4s); check(ready_id != 0, "Ready-result request was not admitted"); const auto ready_deadline = std::chrono::steady_clock::now() + 5s; - while (ready.is_pending(ready_id) && std::chrono::steady_clock::now() < ready_deadline) - { + while (ready.is_pending(ready_id) && std::chrono::steady_clock::now() < ready_deadline) { std::this_thread::sleep_for(1ms); } check(!ready.is_pending(ready_id) && !ready_result && !ready.cancel(ready_id), @@ -193,24 +184,20 @@ void check_cancellation(const arknet::redis::pool_options& options, const std::s } // namespace int main() { - try - { + try { const auto* host = std::getenv("ARK_DATABASE_REDIS_HOST"); const auto* port = std::getenv("ARK_DATABASE_REDIS_PORT"); - if (!host || !*host || !port || !*port) - { + if (!host || !*host || !port || !*port) { throw std::invalid_argument( "Set ARK_DATABASE_REDIS_HOST and ARK_DATABASE_REDIS_PORT for an isolated test server"); } arknet::redis::pool_options options; options.connection.host = host; options.connection.port = port; - if (const auto* username = std::getenv("ARK_DATABASE_REDIS_USER")) - { + if (const auto* username = std::getenv("ARK_DATABASE_REDIS_USER")) { options.connection.username = username; } - if (const auto* password = std::getenv("ARK_DATABASE_REDIS_PASSWORD")) - { + if (const auto* password = std::getenv("ARK_DATABASE_REDIS_PASSWORD")) { options.connection.password = password; } options.connection.client_name = "ark-database-service-test"; @@ -223,8 +210,7 @@ int main() { unsigned callbacks{}; const auto owner = std::this_thread::get_id(); auto handler = [&](ark::detail::redis_service_result result) { - if (std::this_thread::get_id() != owner) - { + if (std::this_thread::get_id() != owner) { throw std::runtime_error("Business callback escaped the module thread"); } ++callbacks; @@ -234,60 +220,49 @@ int main() { const auto key = "ark-private-service-" + std::to_string(unique); const std::string expected("binary\0value", 12); std::string input = expected; - if (!service.submit_pipeline({{"SET", key, input}, {"GET", key}}, handler, 2s)) - { + if (!service.submit_pipeline({{"SET", key, input}, {"GET", key}}, handler, 2s)) { throw std::runtime_error("First operation was not admitted"); } input.assign("modified caller storage"); - if (service.submit({"PING"}, handler, 2s)) - { + if (service.submit({"PING"}, handler, 2s)) { throw std::runtime_error("Completed/active operations bypassed module admission limit"); } auto await = [&] { const auto expires = std::chrono::steady_clock::now() + 4s; - while (!completed && std::chrono::steady_clock::now() < expires) - { + while (!completed && std::chrono::steady_clock::now() < expires) { service.update(); std::this_thread::sleep_for(1ms); } - if (!completed) - { + if (!completed) { throw std::runtime_error("No module completion before timeout"); } - if (auto failure = std::get_if(&*completed)) - { + if (auto failure = std::get_if(&*completed)) { std::rethrow_exception(*failure); } auto result = std::get(std::move(*completed)); completed.reset(); - if (!result) - { + if (!result) { throw std::runtime_error("Native Redis failed: " + std::to_string(static_cast(result.error))); } return result; }; auto owned = await(); if (owned.replies.size() != 2 || owned.replies[1].type != arknet::redis::value_type::bulk_string || - owned.replies[1].text != expected) - { + owned.replies[1].text != expected) { throw std::runtime_error("Pipeline/binary result did not preserve ownership"); } - if (!service.submit({"DEL", key}, handler, 2s)) - { + if (!service.submit({"DEL", key}, handler, 2s)) { throw std::runtime_error("Module admission did not recover after dispatch"); } auto removed = await(); - if (removed.replies.size() != 1 || removed.replies[0].integer != 1 || owned.replies[1].text != expected) - { + if (removed.replies.size() != 1 || removed.replies[0].integer != 1 || owned.replies[1].text != expected) { throw std::runtime_error("A later command invalidated an owning result"); } - if (!service.submit({"PING"}, handler, 2s)) - { + if (!service.submit({"PING"}, handler, 2s)) { throw std::runtime_error("Stop test was not admitted"); } service.stop(); - if (service.update() != 0 || callbacks != 2 || service.submit({"PING"}, handler, 2s)) - { + if (service.update() != 0 || callbacks != 2 || service.submit({"PING"}, handler, 2s)) { throw std::runtime_error("Stop delivered business code or accepted new work"); } auto ephemeral = std::make_unique(options); @@ -295,38 +270,31 @@ int main() { if (!ephemeral->submit( {"PING"}, [&](ark::detail::redis_service_result result) { - if (auto failure = std::get_if(&result)) - { + if (auto failure = std::get_if(&result)) { std::rethrow_exception(*failure); } - if (!std::get(result)) - { + if (!std::get(result)) { throw std::runtime_error("Callback-destruction PING failed"); } ephemeral.reset(); destroyed_from_callback = true; }, - 2s)) - { + 2s)) { throw std::runtime_error("Callback-destruction operation was not admitted"); } const auto destruction_deadline = std::chrono::steady_clock::now() + 4s; - while (!destroyed_from_callback && std::chrono::steady_clock::now() < destruction_deadline) - { + while (!destroyed_from_callback && std::chrono::steady_clock::now() < destruction_deadline) { ephemeral->update(); std::this_thread::sleep_for(1ms); } - if (!destroyed_from_callback) - { + if (!destroyed_from_callback) { throw std::runtime_error("Callback-destruction completion timed out"); } check_cancellation(options, key); std::cout << "private Redis service: owning binary pipeline, admission, module-thread dispatch and stop passed\n"; return 0; - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { std::cerr << error.what() << '\n'; return 1; } diff --git a/tests/database/redis_service_tls.cpp b/tests/database/redis_service_tls.cpp index 128a01e8e..2b16e1654 100644 --- a/tests/database/redis_service_tls.cpp +++ b/tests/database/redis_service_tls.cpp @@ -29,8 +29,7 @@ using service_type = ark::detail::tls_redis_service; using bridge_type = ark::detail::database_awaitable; using result_type = arknet::redis::result; -struct peer_observation -{ +struct peer_observation { arknet::error_code handshake_error; arknet::error_code read_error; arknet::error_code write_error; @@ -39,8 +38,7 @@ struct peer_observation }; // A bounded RESP-over-TLS protocol test endpoint, not a Redis server implementation. -class tls_endpoint -{ +class tls_endpoint { public: explicit tls_endpoint(const std::string& certificate = "server.pem") { const std::string directory = ARK_DATABASE_REDIS_CERT_DIR; @@ -72,8 +70,7 @@ class tls_endpoint } peer_observation finish() { - if (completion_.wait_for(6s) != std::future_status::ready) - { + if (completion_.wait_for(6s) != std::future_status::ready) { throw std::runtime_error("TLS protocol endpoint did not finish"); } return completion_.get(); @@ -84,26 +81,21 @@ class tls_endpoint asio::ssl::stream stream(io_, context_); asio::steady_timer deadline(io_, 5s); deadline.async_wait([&](arknet::error_code error) { - if (!error) - { + if (!error) { observation_.timed_out = true; arknet::error_code ignored; acceptor_.cancel(ignored); stream.next_layer().close(ignored); } }); - try - { + try { co_await acceptor_.async_accept(stream.next_layer(), asio::use_awaitable); co_await stream.async_handshake(asio::ssl::stream_base::server, asio::redirect_error(asio::use_awaitable, observation_.handshake_error)); - if (!observation_.handshake_error) - { + if (!observation_.handshake_error) { co_await exchange(stream); } - } - catch (...) - { + } catch (...) { deadline.cancel(); throw; } @@ -113,88 +105,65 @@ class tls_endpoint asio::awaitable exchange(asio::ssl::stream& stream) { arknet::redis::detail::resp_decoder decoder; bool blocked = false; - for (;;) - { + for (;;) { arknet::redis::value value; const auto status = decoder.next(value); - if (status == arknet::redis::detail::resp_status::ready) - { - if (value.type != arknet::redis::value_type::array || value.elements.empty()) - { + if (status == arknet::redis::detail::resp_status::ready) { + if (value.type != arknet::redis::value_type::array || value.elements.empty()) { throw std::runtime_error("Unexpected protocol command"); } arknet::redis::command arguments; - for (auto& argument : value.elements) - { - if (argument.type != arknet::redis::value_type::bulk_string) - { + for (auto& argument : value.elements) { + if (argument.type != arknet::redis::value_type::bulk_string) { throw std::runtime_error("Expected a binary RESP command argument"); } arguments.push_back(std::move(argument.text)); } ++commands_; std::string response; - if (arguments == arknet::redis::command{"HELLO", "3"}) - { + if (arguments == arknet::redis::command{"HELLO", "3"}) { response = "%1\r\n+proto\r\n:3\r\n"; - } - else if (arguments == arknet::redis::command{"RESET"}) - { - if (blocked) - { + } else if (arguments == arknet::redis::command{"RESET"}) { + if (blocked) { // A released lease may queue RESET behind its cancelled reply slot. // Keep both unanswered until the client closes the transport. continue; } response = "+RESET\r\n"; - } - else - { - if (blocked) - { + } else { + if (blocked) { throw std::runtime_error("Unexpected command after blocked TLS test request"); } ++business_commands_; - if (arguments.size() == 2 && arguments[0] == "ECHO") - { + if (arguments.size() == 2 && arguments[0] == "ECHO") { response = "$" + std::to_string(arguments[1].size()) + "\r\n" + arguments[1] + "\r\n"; - } - else if (arguments == arknet::redis::command{"PING"}) - { + } else if (arguments == arknet::redis::command{"PING"}) { response = "+PONG\r\n"; - } - else if (arguments == arknet::redis::command{"BLPOP", "ark-tls-test", "0"}) - { + } else if (arguments == arknet::redis::command{"BLPOP", "ark-tls-test", "0"}) { // Deliberately send no reply: exercise a genuinely sent cancellation. blocked = true; continue; - } - else - { + } else { throw std::runtime_error("Unsupported command in TLS protocol test endpoint"); } } co_await asio::async_write(stream, asio::buffer(response), asio::redirect_error(asio::use_awaitable, observation_.write_error)); - if (observation_.write_error) - { + if (observation_.write_error) { co_return; } continue; } - if (status != arknet::redis::detail::resp_status::need_more) - { + if (status != arknet::redis::detail::resp_status::need_more) { throw std::runtime_error("Invalid RESP input in TLS protocol test endpoint"); } std::array bytes; const auto count = co_await stream.async_read_some( asio::buffer(bytes), asio::redirect_error(asio::use_awaitable, observation_.read_error)); - if (observation_.read_error) - { + if (observation_.read_error) { co_return; } - if (!decoder.append(std::string_view(bytes.data(), count))) - { + if (!decoder.append(std::string_view(bytes.data(), count))) { throw std::runtime_error("RESP protocol test endpoint limit exceeded"); } } @@ -215,10 +184,8 @@ class tls_endpoint template bool wait_until(predicate_type predicate, std::chrono::milliseconds maximum = 3s) { const auto deadline = std::chrono::steady_clock::now() + maximum; - while (!predicate()) - { - if (std::chrono::steady_clock::now() >= deadline) - { + while (!predicate()) { + if (std::chrono::steady_clock::now() >= deadline) { return false; } std::this_thread::sleep_for(1ms); @@ -242,16 +209,14 @@ arknet::redis::pool_options options_for(const tls_endpoint& endpoint) { } result_type take_result(ark::detail::redis_service_result result) { - if (auto* error = std::get_if(&result)) - { + if (auto* error = std::get_if(&result)) { std::rethrow_exception(*error); } return std::get(std::move(result)); } void check_peer(const peer_observation& observation) { - if (observation.failure) - { + if (observation.failure) { std::rethrow_exception(observation.failure); } CHECK_FALSE(observation.timed_out); @@ -298,12 +263,9 @@ ark::detail::module_task<> issue_command(service_type& service, bridge_type& bri return service.start( std::move(arguments), [complete = std::move(complete)](ark::detail::redis_service_result value) mutable { - if (auto* error = std::get_if(&value)) - { + if (auto* error = std::get_if(&value)) { complete(*error, {}); - } - else - { + } else { complete({}, std::get(std::move(value))); } }, @@ -381,8 +343,7 @@ TEST_CASE("Redis TLS sent cancellation resumes an owning coroutine result on the group.poll(); return group.pending() == 0 && bridge.pending() == 0; }); - if (!drained) - { + if (!drained) { // A failed test cannot legally destroy a still-suspended coroutine owner. std::fputs("Redis TLS coroutine did not drain before the test deadline\n", stderr); std::_Exit(1); diff --git a/tests/database/redis_stop_capture.cpp b/tests/database/redis_stop_capture.cpp index dba4ca001..37212da1f 100644 --- a/tests/database/redis_stop_capture.cpp +++ b/tests/database/redis_stop_capture.cpp @@ -8,8 +8,7 @@ namespace { -struct release_service -{ +struct release_service { std::unique_ptr* owner{}; bool* destroyed{}; @@ -22,11 +21,9 @@ struct release_service } // namespace int main() { - try - { + try { const auto missing_lease = ark::detail::redis_acquire_failure({}); - if (missing_lease.error != arknet::redis::client_errc::not_connected || missing_lease.command_may_have_run) - { + if (missing_lease.error != arknet::redis::client_errc::not_connected || missing_lease.command_may_have_run) { throw std::runtime_error("A failed acquire with no lease was reported as command success"); } arknet::redis::pool::acquire_result rejected; @@ -40,8 +37,7 @@ int main() { if (failure.error != arknet::redis::client_errc::handshake_failed || failure.transport_error != asio::error::connection_aborted || failure.replies.size() != 1 || failure.replies[0].type != arknet::redis::value_type::error || - failure.replies[0].text != "ERR authentication fixture" || failure.command_may_have_run) - { + failure.replies[0].text != "ERR authentication fixture" || failure.command_may_have_run) { throw std::runtime_error("Acquire failure lost its original error or owning replies"); } arknet::redis::pool_options options; @@ -54,23 +50,19 @@ int main() { auto capture = std::make_shared(); capture->owner = &service; capture->destroyed = &destroyed; - if (!service->submit({"PING"}, [capture, &callbacks](auto) { ++callbacks; }, std::chrono::seconds(1))) - { + if (!service->submit({"PING"}, [capture, &callbacks](auto) { ++callbacks; }, std::chrono::seconds(1))) { throw std::runtime_error("Stop-capture operation was not admitted"); } capture.reset(); // stop() removes the queued business capture. Its destructor releases // the service while that same stop() call is still active. service->stop(); - if (service || !destroyed || callbacks) - { + if (service || !destroyed || callbacks) { throw std::runtime_error("Stop did not release its capture without invoking business code"); } std::cout << "private Redis stop capture can destroy its service safely\n"; return 0; - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { std::cerr << error.what() << '\n'; return 1; } diff --git a/tests/database/request_control.cpp b/tests/database/request_control.cpp index 7a153b72a..2d00105a0 100644 --- a/tests/database/request_control.cpp +++ b/tests/database/request_control.cpp @@ -67,10 +67,9 @@ TEST_CASE("Completion before native submit returns preserves the next stage ID") TEST_CASE("A throwing native initiation rolls its phase back before terminal completion") { database_request_control control; const auto submission = control.begin(stage::acquire); - try - { throw std::runtime_error("native initiation failed"); } - catch (const std::runtime_error&) - { + try { + throw std::runtime_error("native initiation failed"); + } catch (const std::runtime_error&) { CHECK(control.complete(submission)); CHECK(control.finish()); } diff --git a/tests/database/sample_plugin.cpp b/tests/database/sample_plugin.cpp index 01b91ecbe..f5452fdae 100644 --- a/tests/database/sample_plugin.cpp +++ b/tests/database/sample_plugin.cpp @@ -30,8 +30,7 @@ static_assert(std::same_as -{ +class rejecting_database : public ark::module_base { public: #ifdef ARK_DATABASE_SAMPLE_MYSQL bool configure(std::string name, ark::mysql_options) override { @@ -91,8 +90,7 @@ class rejecting_database : public ark::module_base }; void require(bool condition, const std::string& message) { - if (!condition) - { + if (!condition) { std::cerr << message << '\n'; std::_Exit(1); } diff --git a/tests/database/service_awaitable.cpp b/tests/database/service_awaitable.cpp index 3186e931f..1aeffd6d1 100644 --- a/tests/database/service_awaitable.cpp +++ b/tests/database/service_awaitable.cpp @@ -37,16 +37,14 @@ unsigned checks{}; void require(bool condition, const char* message) { ++checks; - if (!condition) - { + if (!condition) { throw std::runtime_error(message); } } std::string environment(const char* name, bool allow_empty = false) { const auto* value = std::getenv(name); - if (!value || (!allow_empty && !*value)) - { + if (!value || (!allow_empty && !*value)) { throw std::invalid_argument(std::string("Required test environment variable: ") + name); } return value; @@ -56,8 +54,7 @@ std::uint16_t port(const char* name) { const auto text = environment(name); unsigned number{}; const auto parsed = std::from_chars(text.data(), text.data() + text.size(), number); - if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size() || number == 0 || number > 65535) - { + if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size() || number == 0 || number > 65535) { throw std::invalid_argument(std::string(name) + " must be an integer between 1 and 65535"); } return static_cast(number); @@ -66,15 +63,13 @@ std::uint16_t port(const char* name) { template void pump(service_type& service, database_awaitable& bridge, module_task_group& group) { const auto deadline = std::chrono::steady_clock::now() + 10s; - while (group.pending() && std::chrono::steady_clock::now() < deadline) - { + while (group.pending() && std::chrono::steady_clock::now() < deadline) { service.update(); bridge.dispatch(); group.poll(); std::this_thread::sleep_for(1ms); } - if (group.pending() || bridge.pending()) - { + if (group.pending() || bridge.pending()) { // A failed drain cannot safely destroy its suspended task owner. Make // that failed test explicit without pretending destructors can join. std::cerr << "Native coroutine did not drain before the test deadline\n" << std::flush; @@ -88,12 +83,10 @@ void check_redis() { arknet::redis::pool_options options; options.connection.host = environment("ARK_DATABASE_REDIS_HOST"); options.connection.port = std::to_string(port("ARK_DATABASE_REDIS_PORT")); - if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) - { + if (const auto* user = std::getenv("ARK_DATABASE_REDIS_USER")) { options.connection.username = user; } - if (const auto* password = std::getenv("ARK_DATABASE_REDIS_PASSWORD")) - { + if (const auto* password = std::getenv("ARK_DATABASE_REDIS_PASSWORD")) { options.connection.password = password; } options.max_connections = 1; @@ -129,8 +122,7 @@ void check_redis() { }; require(group.start(sequence(), done) != 0, "Redis coroutine task was not accepted"); pump(service, bridge, group); - if (task_error) - { + if (task_error) { std::rethrow_exception(task_error); } require(completions == 1, "Redis task did not complete exactly once"); @@ -152,8 +144,7 @@ void check_redis() { group.close(); require(!group.closed(), "Redis close silently detached a pending coroutine"); pump(service, bridge, group); - if (task_error) - { + if (task_error) { std::rethrow_exception(task_error); } require(group.closed() && completions == 2, "Redis close did not drain every accepted task"); @@ -213,8 +204,7 @@ void check_mysql() { }; require(group.start(sequence(), done) != 0, "MySQL coroutine task was not accepted"); pump(service, bridge, group); - if (task_error) - { + if (task_error) { std::rethrow_exception(task_error); } require(completions == 1, "MySQL task did not complete exactly once"); @@ -233,8 +223,7 @@ void check_mysql() { group.close(); require(!group.closed(), "MySQL close silently detached a pending coroutine"); pump(service, bridge, group); - if (task_error) - { + if (task_error) { std::rethrow_exception(task_error); } require(group.closed() && completions == 2, "MySQL close did not drain every accepted task"); @@ -245,32 +234,25 @@ void check_mysql() { } // namespace int main(int argc, char** argv) { - try - { - if (argc != 2) - { + try { + if (argc != 2) { throw std::invalid_argument("Usage: ark_database_service_awaitable_tests redis|mysql"); } const std::string_view protocol(argv[1]); - if (protocol == "redis") - { + if (protocol == "redis") { check_redis(); } #if defined(ARKNET_ENABLE_SSL) - else if (protocol == "mysql") - { + else if (protocol == "mysql") { check_mysql(); } #endif - else - { + else { throw std::invalid_argument("Requested protocol is not enabled in this test executable"); } std::cout << protocol << " native coroutine checks passed: " << checks << '\n'; return 0; - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { std::cerr << error.what() << '\n'; return 1; } diff --git a/tests/database/service_construction_allocation.cpp b/tests/database/service_construction_allocation.cpp index 5a635b0be..8b58aca3f 100644 --- a/tests/database/service_construction_allocation.cpp +++ b/tests/database/service_construction_allocation.cpp @@ -23,33 +23,25 @@ int probe(Options options) { // idle: construction starts a worker but never sends a database request. remaining = budget; armed = true; - try - { + try { Service service(std::move(options)); armed = false; - if (!service.quiescent() || service.native_retired()) - { + if (!service.quiescent() || service.native_retired()) { return 3; } service.stop_accepting(); - if (!service.logically_drained() || !service.retire_native() || !service.native_retired()) - { + if (!service.logically_drained() || !service.retire_native() || !service.native_retired()) { return 4; } - } - catch (const std::bad_alloc&) - { + } catch (const std::bad_alloc&) { const bool persistent = armed && remaining == 0; armed = false; - if (!persistent || budget < 0) - { + if (!persistent || budget < 0) { return 5; } std::printf("caught %s budget=%ld allocations=%ld\n", protocol, budget, allocations); return 0; - } - catch (...) - { + } catch (...) { armed = false; return 6; } @@ -60,15 +52,13 @@ int probe(Options options) { int main(int argc, char** argv) { using namespace ark_database_allocation_probe; - if (argc != 3) - { + if (argc != 3) { return 2; } protocol = argv[1]; char* end{}; budget = std::strtol(argv[2], &end, 10); - if (end == argv[2] || *end || budget < -1) - { + if (end == argv[2] || *end || budget < -1) { return 2; } std::set_terminate([] { @@ -76,17 +66,14 @@ int main(int argc, char** argv) { stderr, "terminate %s budget=%ld allocations=%ld armed=%d\n", protocol, budget, allocations, armed); std::_Exit(86); }); - if (std::strcmp(protocol, "redis") == 0) - { + if (std::strcmp(protocol, "redis") == 0) { return probe(arknet::redis::pool_options{}); } #if defined(ARKNET_ENABLE_SSL) - if (std::strcmp(protocol, "redis-tls") == 0) - { + if (std::strcmp(protocol, "redis-tls") == 0) { return probe(arknet::redis::pool_options{}); } - if (std::strcmp(protocol, "mysql") == 0) - { + if (std::strcmp(protocol, "mysql") == 0) { return probe(arknet::mysql::pool_options{}); } #endif diff --git a/tests/database/service_retirement.cpp b/tests/database/service_retirement.cpp index 6aeff40cc..d9c1800a3 100644 --- a/tests/database/service_retirement.cpp +++ b/tests/database/service_retirement.cpp @@ -21,8 +21,7 @@ namespace ark::detail { -struct database_service_test_access -{ +struct database_service_test_access { template static auto activity(service_type& service) { return service.activity_; @@ -71,8 +70,7 @@ using service_types = std::tuple; #endif template -struct service_traits -{ +struct service_traits { using reply_type = arknet::redis::result; static auto options() { @@ -97,8 +95,7 @@ struct service_traits #if defined(ARKNET_ENABLE_SSL) template<> -struct service_traits -{ +struct service_traits { using reply_type = ark::detail::mysql_service_reply; static auto options() { @@ -122,8 +119,7 @@ struct service_traits }; #endif -struct finalizer_failure : std::runtime_error -{ +struct finalizer_failure : std::runtime_error { std::shared_ptr origin; explicit finalizer_failure(std::shared_ptr value) @@ -132,8 +128,7 @@ struct finalizer_failure : std::runtime_error } }; -struct callback_capture -{ +struct callback_capture { std::weak_ptr activity; unsigned& destroyed; @@ -145,21 +140,18 @@ struct callback_capture ~callback_capture() { auto retained = activity.lock(); CHECK(retained); - if (retained) - { + if (retained) { CHECK(retained->depth > 0); } ++destroyed; } }; -struct worker_exit_probe -{ +struct worker_exit_probe { std::shared_ptr> exited; ~worker_exit_probe() { - if (exited) - { + if (exited) { *exited = true; } } @@ -170,16 +162,14 @@ void observe_worker_exit(std::shared_ptr> exited) { probe.exited = std::move(exited); } -struct native_observation -{ +struct native_observation { std::promise completed; std::atomic callbacks{}; std::atomic captures_destroyed{}; std::shared_ptr> worker_exited = std::make_shared>(false); }; -struct native_capture -{ +struct native_capture { std::shared_ptr observation; explicit native_capture(std::shared_ptr state) @@ -242,8 +232,7 @@ TEST_CASE_TEMPLATE_DEFINE("Inline refusal may destroy its facade before captures owner.reset(); auto retained = activity.lock(); CHECK(retained); - if (retained) - { + if (retained) { CHECK(retained->depth > 0); } }; @@ -280,8 +269,7 @@ TEST_CASE_TEMPLATE_DEFINE("Dispatch may destroy its facade while its shared acti owner.reset(); auto retained = activity.lock(); CHECK(retained); - if (retained) - { + if (retained) { CHECK(retained->depth > 0); } }); @@ -342,18 +330,15 @@ TEST_CASE_TEMPLATE_DEFINE("Failed native finalization preserves the exact pool o auto origin = std::make_shared(42); auto failure = std::make_exception_ptr(finalizer_failure(origin)); bool observed{}; - try - { + try { test_access::retire(service, [&](auto&) -> bool { std::rethrow_exception(failure); }); - } - catch (const finalizer_failure& error) - { + } catch (const finalizer_failure& error) { observed = true; CHECK(error.origin == origin); CHECK(std::string(error.what()) == "injected native finalizer failure"); + } catch (...) { + FAIL("Native finalization changed the exception type"); } - catch (...) - { FAIL("Native finalization changed the exception type"); } CHECK(observed); CHECK_FALSE(pool.expired()); CHECK_FALSE(service.native_retired()); @@ -423,8 +408,7 @@ TEST_CASE_TEMPLATE_DEFINE("Accepted coroutine A then B survives root admission s tasks.poll(); tasks.stop_accepting(); const auto deadline = std::chrono::steady_clock::now() + 5s; - while (tasks.pending() && std::chrono::steady_clock::now() < deadline) - { + while (tasks.pending() && std::chrono::steady_clock::now() < deadline) { service.update(); bridge.dispatch(); tasks.poll(); diff --git a/tests/database/task_group.cpp b/tests/database/task_group.cpp index 78eee677a..b5418c8c8 100644 --- a/tests/database/task_group.cpp +++ b/tests/database/task_group.cpp @@ -24,23 +24,22 @@ module_task<> throw_task() { } module_task<> wait_task(asio::steady_timer& timer, bool& cancelled) { - try - { co_await timer.async_wait(asio::use_awaitable); } - catch (const asio::system_error& error) - { cancelled = error.code() == asio::error::operation_aborted; } + try { + co_await timer.async_wait(asio::use_awaitable); + } catch (const asio::system_error& error) { + cancelled = error.code() == asio::error::operation_aborted; + } } module_task<> multi_step_task(unsigned& started, unsigned& resumed) { ++started; - for (unsigned step = 0; step < 3; ++step) - { + for (unsigned step = 0; step < 3; ++step) { co_await asio::post(asio::use_awaitable); ++resumed; } } -struct capture_release -{ +struct capture_release { std::thread::id owner; unsigned& released; bool& wrong_thread; @@ -80,16 +79,16 @@ TEST_CASE("Task completion and exceptions run on the module owner") { REQUIRE(group.start(throw_task(), [&](std::exception_ptr error) { CHECK(std::this_thread::get_id() == owner); REQUIRE(error); - try - { std::rethrow_exception(error); } - catch (const std::runtime_error& failure) - { CHECK(std::string(failure.what()) == "task body failure"); } + try { + std::rethrow_exception(error); + } catch (const std::runtime_error& failure) { + CHECK(std::string(failure.what()) == "task body failure"); + } ++completed; })); CHECK(group.start(finish_task(started)) == 0); CHECK(started == 0); - for (unsigned step = 0; step < 16 && group.pending(); ++step) - { + for (unsigned step = 0; step < 16 && group.pending(); ++step) { group.poll(1); } CHECK(completed == 2); @@ -118,8 +117,7 @@ TEST_CASE("Close requests cancellation and requires explicit owner polling to dr group.close(); CHECK_FALSE(group.closed()); CHECK(completed == 0); - for (unsigned step = 0; step < 16 && !group.closed(); ++step) - { + for (unsigned step = 0; step < 16 && !group.closed(); ++step) { group.poll(1); } CHECK(group.closed()); @@ -154,18 +152,21 @@ TEST_CASE("Task group rejects cross-thread state access") { module_task_group group(runtime); unsigned rejected{}; std::thread worker([&] { - try - { group.pending(); } - catch (const std::logic_error&) - { ++rejected; } - try - { group.close(); } - catch (const std::logic_error&) - { ++rejected; } - try - { group.stop_accepting(); } - catch (const std::logic_error&) - { ++rejected; } + try { + group.pending(); + } catch (const std::logic_error&) { + ++rejected; + } + try { + group.close(); + } catch (const std::logic_error&) { + ++rejected; + } + try { + group.stop_accepting(); + } catch (const std::logic_error&) { + ++rejected; + } }); worker.join(); CHECK(rejected == 3); @@ -176,10 +177,11 @@ TEST_CASE("Task group rejects cross-thread state access") { REQUIRE(group.pending() == 0); group.stop_accepting(); std::thread closed_worker([&] { - try - { group.stop_accepting(); } - catch (const std::logic_error&) - { ++rejected; } + try { + group.stop_accepting(); + } catch (const std::logic_error&) { + ++rejected; + } }); closed_worker.join(); CHECK(rejected == 4); @@ -206,8 +208,7 @@ TEST_CASE("Stopping admission preserves accepted tasks across multiple awaits") CHECK_FALSE(error); ++completed; }) != 0); - if (poll_first) - { + if (poll_first) { group.poll(1); CHECK(started == 1); } @@ -217,8 +218,7 @@ TEST_CASE("Stopping admission preserves accepted tasks across multiple awaits") CHECK_FALSE(group.closed()); CHECK(completed == 0); CHECK(group.start(finish_task(rejected_started)) == 0); - for (unsigned step = 0; step < 16 && !group.closed(); ++step) - { + for (unsigned step = 0; step < 16 && !group.closed(); ++step) { group.poll(1); } CHECK(group.closed()); @@ -249,8 +249,7 @@ TEST_CASE("Close still cancels accepted work after admission has stopped") { CHECK(completed == 0); CHECK(group.pending() == 1); group.close(); - for (unsigned step = 0; step < 16 && !group.closed(); ++step) - { + for (unsigned step = 0; step < 16 && !group.closed(); ++step) { group.poll(1); } CHECK(group.closed()); @@ -297,8 +296,7 @@ TEST_CASE("Stopped admission releases accepted and refused captures on the owner 0); CHECK(released == 2); CHECK(refused_started == 0); - for (unsigned step = 0; step < 16 && !group.closed(); ++step) - { + for (unsigned step = 0; step < 16 && !group.closed(); ++step) { group.poll(1); } CHECK(group.closed()); @@ -314,19 +312,18 @@ TEST_CASE("Close before the first poll still drains the accepted task completion unsigned started{}; unsigned completed{}; group.start(finish_task(started), [&](std::exception_ptr error) { - if (error) - { - try - { std::rethrow_exception(error); } - catch (const asio::system_error& failure) - { CHECK(failure.code() == asio::error::operation_aborted); } + if (error) { + try { + std::rethrow_exception(error); + } catch (const asio::system_error& failure) { + CHECK(failure.code() == asio::error::operation_aborted); + } } ++completed; }); group.close(); CHECK_FALSE(group.closed()); - for (unsigned step = 0; step < 16 && !group.closed(); ++step) - { + for (unsigned step = 0; step < 16 && !group.closed(); ++step) { group.poll(1); } CHECK(group.closed()); diff --git a/tests/database/task_group_contract.cpp b/tests/database/task_group_contract.cpp index 72959c487..84026db13 100644 --- a/tests/database/task_group_contract.cpp +++ b/tests/database/task_group_contract.cpp @@ -41,14 +41,12 @@ ark::task<> pending_task() { } // namespace int main(int argc, char** argv) { - if (argc != 2) - { + if (argc != 2) { return 2; } install_contract_exit(); const std::string_view mode(argv[1]); - if (mode == "--pending-destruction") - { + if (mode == "--pending-destruction") { auto runtime = std::make_shared(); ark::task_group group(runtime); group.start(pending_task()); @@ -56,8 +54,7 @@ int main(int argc, char** argv) { // Destroying this owner violates the documented drain precondition. return 0; } - if (mode == "--wrong-thread-destruction") - { + if (mode == "--wrong-thread-destruction") { auto runtime = std::make_shared(); auto group = std::make_unique(runtime); std::thread worker([owned = std::move(group)]() mutable { diff --git a/tests/database/transactions_awaitable.cpp b/tests/database/transactions_awaitable.cpp index 8e888cacf..cd9fa6ebd 100644 --- a/tests/database/transactions_awaitable.cpp +++ b/tests/database/transactions_awaitable.cpp @@ -28,8 +28,7 @@ static_assert(std::is_nothrow_move_constructible_v); // Controlled callback endpoints check only the factory/bridge contract. They // neither simulate a database nor establish lease/deadline/commit correctness. -struct transaction_stub -{ +struct transaction_stub { using callback = std::function; std::vector submitted; mysql_transaction_options options{}; @@ -72,12 +71,10 @@ struct transaction_stub CHECK_FALSE(in_callback); CHECK(active == 0); submitted.push_back(std::move(operation)); - if (throw_on_start) - { + if (throw_on_start) { throw std::runtime_error("Transaction initiation threw before acceptance"); } - if (inline_reply) - { + if (inline_reply) { handler(std::move(immediate)); return 0; } @@ -102,8 +99,7 @@ struct transaction_stub } }; -struct transaction_owner -{ +struct transaction_owner { std::shared_ptr runtime = std::make_shared(); module_task_group tasks{runtime, 1}; database_awaitable bridge{runtime, 1}; @@ -135,8 +131,7 @@ struct transaction_owner } void drain() { - for (unsigned step = 0; step < 16 && tasks.pending(); ++step) - { + for (unsigned step = 0; step < 16 && tasks.pending(); ++step) { deliver(); } CHECK(tasks.pending() == 0); @@ -146,8 +141,7 @@ struct transaction_owner module_task operation( unsigned kind, transaction_stub& endpoint, database_awaitable& bridge) { - switch (kind) - { + switch (kind) { case 0: return mysql_transaction_begin(endpoint, bridge, {83ms, 19ms}); case 1: @@ -181,8 +175,7 @@ module_task<> sequential_transaction( TEST_CASE("Transaction factories own options and SQL before lazy start and drop without submission") { transaction_stub endpoint; transaction_owner owner; - for (unsigned kind = 0; kind < 5; ++kind) - { + for (unsigned kind = 0; kind < 5; ++kind) { auto unstarted = operation(kind, endpoint, owner.bridge); } CHECK(endpoint.submitted.empty()); @@ -243,8 +236,7 @@ TEST_CASE("Transaction factories own options and SQL before lazy start and drop } TEST_CASE("All transaction factories deliver ID zero refusals on the owner executor") { - for (unsigned kind = 0; kind < 5; ++kind) - { + for (unsigned kind = 0; kind < 5; ++kind) { CAPTURE(kind); transaction_stub endpoint; transaction_owner owner; @@ -267,8 +259,7 @@ TEST_CASE("All transaction factories deliver ID zero refusals on the owner execu } TEST_CASE("Transaction initiation throws remain distinct from the reply initiation diagnostic") { - for (unsigned kind = 0; kind < 5; ++kind) - { + for (unsigned kind = 0; kind < 5; ++kind) { CAPTURE(kind); transaction_stub endpoint; transaction_owner owner; @@ -350,8 +341,7 @@ TEST_CASE("Transaction initiation throws remain distinct from the reply initiati } TEST_CASE("All transaction cancellations retain the record until the native uncertain terminal") { - for (unsigned kind = 0; kind < 5; ++kind) - { + for (unsigned kind = 0; kind < 5; ++kind) { CAPTURE(kind); transaction_stub endpoint; transaction_owner owner; @@ -384,8 +374,7 @@ TEST_CASE("All transaction cancellations retain the record until the native unce } TEST_CASE("Transaction sequences retire callback and bridge capacity before the next step at quota one") { - for (const auto rollback : {false, true}) - { + for (const auto rollback : {false, true}) { CAPTURE(rollback); transaction_stub endpoint; transaction_owner owner; diff --git a/tests/etcd_client/entry.cpp b/tests/etcd_client/entry.cpp index 7420feeca..0241c9bab 100644 --- a/tests/etcd_client/entry.cpp +++ b/tests/etcd_client/entry.cpp @@ -10,8 +10,7 @@ namespace { void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { std::cerr << message << std::endl; std::_Exit(1); } diff --git a/tests/etcd_client/entry_factory.cpp b/tests/etcd_client/entry_factory.cpp index ab69b24a0..e83481b85 100644 --- a/tests/etcd_client/entry_factory.cpp +++ b/tests/etcd_client/entry_factory.cpp @@ -11,8 +11,7 @@ unsigned created{}; unsigned destroyed{}; unsigned updated{}; -class entry_etcd_client final : public ark::module_base -{ +class entry_etcd_client final : public ark::module_base { public: entry_etcd_client() { ++created; @@ -47,8 +46,7 @@ std::unique_ptr make_etcd_client_module() { } // namespace ark::detail ARK_EXPORT_FUNC unsigned etcd_client_entry_events(unsigned event) { - switch (event) - { + switch (event) { case 0: return created; case 1: diff --git a/tests/etcd_client/exports.cpp b/tests/etcd_client/exports.cpp index f6ef4cb20..72bab4d7e 100644 --- a/tests/etcd_client/exports.cpp +++ b/tests/etcd_client/exports.cpp @@ -8,8 +8,7 @@ namespace { void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { std::cerr << message << std::endl; std::_Exit(1); } diff --git a/tests/guest_room/codec.cpp b/tests/guest_room/codec.cpp index 0a750eb45..fcbd5f5b4 100644 --- a/tests/guest_room/codec.cpp +++ b/tests/guest_room/codec.cpp @@ -27,8 +27,7 @@ std::string frame(ark::msg_id_t id, const std::string& body) { std::string hex(const std::string& bytes) { static constexpr char digits[] = "0123456789abcdef"; std::string text; - for (const unsigned char byte : bytes) - { + for (const unsigned char byte : bytes) { text.push_back(digits[byte >> 4]); text.push_back(digits[byte & 15]); } @@ -38,8 +37,7 @@ std::string hex(const std::string& bytes) { std::string unhex(const std::string& text) { REQUIRE(text.size() % 2 == 0); std::string bytes; - for (std::size_t index = 0; index < text.size(); index += 2) - { + for (std::size_t index = 0; index < text.size(); index += 2) { bytes.push_back(static_cast(std::stoul(text.substr(index, 2), nullptr, 16))); } return bytes; @@ -71,40 +69,31 @@ ark::entity_sync::nested_stream_binding initial_binding() { ark::entity_sync::nested_scalar_type scalar_type(const std::string& name) { using type = ark::entity_sync::nested_scalar_type; - if (name.starts_with("bool")) - { + if (name.starts_with("bool")) { return type::boolean; } - if (name.starts_with("int32")) - { + if (name.starts_with("int32")) { return type::int32; } - if (name.starts_with("uint32")) - { + if (name.starts_with("uint32")) { return type::uint32; } - if (name.starts_with("int64")) - { + if (name.starts_with("int64")) { return type::int64; } - if (name.starts_with("uint64")) - { + if (name.starts_with("uint64")) { return type::uint64; } - if (name.starts_with("float")) - { + if (name.starts_with("float")) { return type::real32; } - if (name.starts_with("double")) - { + if (name.starts_with("double")) { return type::real64; } - if (name.starts_with("guid")) - { + if (name.starts_with("guid")) { return type::guid; } - if (name.starts_with("bytes")) - { + if (name.starts_with("bytes")) { return type::bytes; } throw std::invalid_argument("Unknown scalar fixture type"); @@ -118,21 +107,17 @@ TEST_CASE("Guest room golden frames match the C sharp shared fixture") { const auto fixtures = json::parse(input); CHECK(fixtures["format"] == "ark.guest-room.protobuf"); std::map bindings; - for (const auto& vector : fixtures["vectors"]) - { - if (vector["message_id"].get() == snapshot) - { + for (const auto& vector : fixtures["vectors"]) { + if (vector["message_id"].get() == snapshot) { wire::room_baseline room; REQUIRE(room.ParseFromString(unhex(vector["body_hex"].get()))); - for (const auto& player : room.players()) - { + for (const auto& player : room.players()) { const auto trusted = decode_binding(player.binding()); bindings.insert_or_assign(trusted.root_id, trusted); } } } - for (const auto& vector : fixtures["vectors"]) - { + for (const auto& vector : fixtures["vectors"]) { const auto id = vector["message_id"].get(); const auto body = unhex(vector["body_hex"].get()); const auto bytes = frame(id, body); @@ -141,8 +126,7 @@ TEST_CASE("Guest room golden frames match the C sharp shared fixture") { parsed.parse_from_array(bytes.data()); CHECK(parsed.message_id() == id); CHECK(parsed.message_length() == body.size()); - switch (id) - { + switch (id) { case join: protobuf_roundtrip(body); break; @@ -155,14 +139,12 @@ TEST_CASE("Guest room golden frames match the C sharp shared fixture") { case action: protobuf_roundtrip(body); break; - case snapshot: - { + case snapshot: { protobuf_roundtrip(body); wire::room_baseline room; REQUIRE(room.ParseFromString(body)); REQUIRE(room.players_size() >= 1); - for (const auto& player : room.players()) - { + for (const auto& player : room.players()) { const auto trusted = decode_binding(player.binding()); const auto state = decode(player.state(), trusted); validate_player(state.snapshot); @@ -172,14 +154,12 @@ TEST_CASE("Guest room golden frames match the C sharp shared fixture") { } break; } - case delta: - { + case delta: { protobuf_roundtrip(body); wire::room_delta room; REQUIRE(room.ParseFromString(body)); REQUIRE(room.changed_size() >= 1); - for (const auto& change : room.changed()) - { + for (const auto& change : room.changed()) { const auto& trusted = bindings.at(static_cast(change.root().entity_id())); state_wire::nested_delta encoded; encode(decode(change, trusted), encoded, trusted); @@ -198,8 +178,7 @@ TEST_CASE("Guest room golden frames match the C sharp shared fixture") { FAIL("unknown golden message"); } } - for (const auto& vector : fixtures["scalar_vectors"]) - { + for (const auto& vector : fixtures["scalar_vectors"]) { const auto body = unhex(vector["body_hex"].get()); const auto name = vector["name"].get(); state_wire::scalar_field field; @@ -218,8 +197,7 @@ TEST_CASE("Guest room golden frames match the C sharp shared fixture") { const ark::entity_sync::nested_stream_binding trusted{ "scalar-fixture", 42, 1, 1, {"Types", {{100, scalar_type(name)}}, {}, {}}}; if (name.starts_with("guid") && (field.guid_value() < std::numeric_limits::min() || - field.guid_value() > std::numeric_limits::max())) - { + field.guid_value() > std::numeric_limits::max())) { CHECK_THROWS_AS(ark::entity_sync::nested_wire::decode(envelope, trusted), std::invalid_argument); continue; } @@ -228,40 +206,23 @@ TEST_CASE("Guest room golden frames match the C sharp shared fixture") { state_wire::nested_baseline encoded; ark::entity_sync::nested_wire::encode(decoded, encoded, trusted); CHECK(encoded.snapshot().root().fields(0).SerializeAsString() == body); - if (name.starts_with("bool")) - { + if (name.starts_with("bool")) { CHECK(std::holds_alternative(value)); - } - else if (name.starts_with("int32")) - { + } else if (name.starts_with("int32")) { CHECK(std::holds_alternative(value)); - } - else if (name.starts_with("uint32")) - { + } else if (name.starts_with("uint32")) { CHECK(std::holds_alternative(value)); - } - else if (name.starts_with("int64")) - { + } else if (name.starts_with("int64")) { CHECK(std::holds_alternative(value)); - } - else if (name.starts_with("uint64")) - { + } else if (name.starts_with("uint64")) { CHECK(std::holds_alternative(value)); - } - else if (name.starts_with("float")) - { + } else if (name.starts_with("float")) { CHECK(std::get(value) == 1.5f); - } - else if (name.starts_with("double")) - { + } else if (name.starts_with("double")) { CHECK(std::get(value) == -2.25); - } - else if (name.starts_with("guid")) - { + } else if (name.starts_with("guid")) { CHECK(std::holds_alternative(value)); - } - else if (name.starts_with("bytes")) - { + } else if (name.starts_with("bytes")) { CHECK(std::get(value) == std::string("A\0B", 3)); } } @@ -275,8 +236,7 @@ TEST_CASE("Guest room Net retains split headers bodies and coalesced frames") { body.set_protocol_version(protocol_version); return body.SerializeAsString(); }()); - for (std::size_t split = 1; split < bytes.size(); ++split) - { + for (std::size_t split = 1; split < bytes.size(); ++split) { ark::tcp_client_session session(std::make_shared
(), 1, nullptr, 16); session.add_buffer(bytes.data(), split); REQUIRE(session.parse_buffer_to_msg()); @@ -297,19 +257,13 @@ TEST_CASE("Guest room Net retains split headers bodies and coalesced frames") { } TEST_CASE("Guest room invalid headers fail before body allocation and callback") { - for (const auto kind : {0, 1, 2}) - { + for (const auto kind : {0, 1, 2}) { auto bytes = frame(join, "").substr(0, 12); - if (kind == 0) - { + if (kind == 0) { bytes[0] = 'X'; - } - else if (kind == 1) - { + } else if (kind == 1) { bytes[7] = 1; - } - else - { + } else { bytes[10] = 0x20; bytes[11] = 1; // 8193-byte body, with no body present. } @@ -346,8 +300,7 @@ TEST_CASE("Guest room reconnect owns fresh parser state and reserved IDs cannot REQUIRE(fresh.pop_net_msg(message)); CHECK(message->get_msg_id() == ping); ark::net_msg::release(message); - for (const auto id : {0, 1, 65535, 60001, 60007, 12345}) - { + for (const auto id : {0, 1, 65535, 60001, 60007, 12345}) { const auto unsupported_frame = frame(static_cast(id), "{}"); header request(true); request.parse_from_array(unsupported_frame.data()); @@ -367,10 +320,9 @@ TEST_CASE("Guest room reconnect owns fresh parser state and reserved IDs cannot TEST_CASE("Guest room validates UTF-8 names independently of protobuf text fields") { CHECK(valid_name(std::string(64, 'a'))); CHECK(valid_name("访客")); - for (const auto& name : - {std::string(), std::string(65, 'a'), std::string("a\nb"), std::string("a\xc2\x85"), std::string("\xc0\x80"), - std::string("\xed\xa0\x80"), std::string("\xf4\x90\x80\x80"), std::string("\xe4\xb8"), std::string("\xff")}) - { + for (const auto& name : {std::string(), std::string(65, 'a'), std::string("a\nb"), std::string("a\xc2\x85"), + std::string("\xc0\x80"), std::string("\xed\xa0\x80"), std::string("\xf4\x90\x80\x80"), + std::string("\xe4\xb8"), std::string("\xff")}) { CHECK_FALSE(valid_name(name)); } } @@ -430,12 +382,9 @@ TEST_CASE("Generic protobuf alternatives preserve widths signedness zero presenc invalid = encoded; invalid.mutable_snapshot()->mutable_root()->mutable_fields(8)->set_guid_value( std::numeric_limits::min()); - if constexpr (sizeof(ark::guid_t) < sizeof(std::int64_t)) - { + if constexpr (sizeof(ark::guid_t) < sizeof(std::int64_t)) { CHECK_THROWS_AS(nested_wire::decode(invalid, trusted), std::invalid_argument); - } - else - { + } else { CHECK(std::get(nested_wire::decode(invalid, trusted).snapshot.root.scalars.fields.at(9)).value == std::numeric_limits::min()); } @@ -494,8 +443,7 @@ TEST_CASE("Public nested delta codec keeps revision gaps and tombstones detectab auto wrong = initial; wrong.snapshot.root.scalars.fields.at(104) = std::uint32_t{101}; CHECK_THROWS_AS(validate_player(wrong.snapshot), std::invalid_argument); - for (const auto current : {104u, 105u}) - { + for (const auto current : {104u, 105u}) { wrong = initial; wrong.snapshot.root.scalars.fields.at(current) = std::uint32_t{0}; wrong.snapshot.root.scalars.fields.at(current + 2) = std::uint32_t{0}; @@ -522,8 +470,7 @@ TEST_CASE("Guest room largest protobuf roster stays inside framing budget") { using namespace ark::entity_sync; wire::room_baseline roster; roster.set_room("lobby"); - for (ark::guid_t index = 1; index <= 16; ++index) - { + for (ark::guid_t index = 1; index <= 16; ++index) { auto& player = *roster.add_players(); player.set_player_id("18446744073709551615"); auto state = initial_player(); @@ -535,8 +482,7 @@ TEST_CASE("Guest room largest protobuf roster stays inside framing budget") { root.scalars.fields.at(100) = std::string(64, '"'); root.scalars.fields.at(101) = 960.0; root.scalars.fields.at(102) = 540.0; - for (std::uint32_t field = 103; field <= 108; ++field) - { + for (std::uint32_t field = 103; field <= 108; ++field) { root.scalars.fields.at(field) = std::numeric_limits::max(); } root.tables.at(inventory_index) diff --git a/tests/guest_room/server.cpp b/tests/guest_room/server.cpp index 936ada728..c69eda44e 100644 --- a/tests/guest_room/server.cpp +++ b/tests/guest_room/server.cpp @@ -36,29 +36,24 @@ using json = nlohmann::json; using tcp = asio::ip::tcp; void require(bool condition, const std::string& reason) { - if (!condition) - { + if (!condition) { throw std::runtime_error(reason); } } -struct launcher -{ +struct launcher { pid_t pid{-1}; bool stopped{false}; launcher(const std::string& program, const std::string& directory, const std::string& log_name = "launcher.log") { pid = fork(); require(pid >= 0, "fork failed"); - if (pid == 0) - { - if (chdir(directory.c_str()) != 0) - { + if (pid == 0) { + if (chdir(directory.c_str()) != 0) { _exit(126); } const int log = open(log_name.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600); - if (log < 0) - { + if (log < 0) { _exit(126); } dup2(log, STDOUT_FILENO); @@ -74,10 +69,8 @@ struct launcher kill(pid, SIGTERM); const auto deadline = std::chrono::steady_clock::now() + 5s; int status = 0; - while (std::chrono::steady_clock::now() < deadline) - { - if (waitpid(pid, &status, WNOHANG) == pid) - { + while (std::chrono::steady_clock::now() < deadline) { + if (waitpid(pid, &status, WNOHANG) == pid) { stopped = true; require(WIFEXITED(status) && WEXITSTATUS(status) == 0, "launcher failed normal shutdown"); return; @@ -90,10 +83,8 @@ struct launcher void expect_failure(const std::filesystem::path& log_path) { const auto deadline = std::chrono::steady_clock::now() + 5s; int status = 0; - while (std::chrono::steady_clock::now() < deadline) - { - if (waitpid(pid, &status, WNOHANG) == pid) - { + while (std::chrono::steady_clock::now() < deadline) { + if (waitpid(pid, &status, WNOHANG) == pid) { stopped = true; require(WIFEXITED(status) && WEXITSTATUS(status) == 1, "invalid profile did not fail normal startup"); std::ifstream log(log_path); @@ -109,8 +100,7 @@ struct launcher } ~launcher() { - if (pid > 0 && !stopped) - { + if (pid > 0 && !stopped) { kill(pid, SIGKILL); int status = 0; waitpid(pid, &status, 0); @@ -118,8 +108,7 @@ struct launcher } }; -struct client -{ +struct client { asio::io_context context; tcp::socket socket{context}; std::function pump; @@ -128,11 +117,9 @@ struct client : pump(std::move(update)) { const auto deadline = std::chrono::steady_clock::now() + (retry ? 5s : 1s); asio::error_code ec; - do - { + do { socket.connect({asio::ip::make_address("127.0.0.1"), port}, ec); - if (!ec) - { + if (!ec) { socket.non_blocking(true); return; } @@ -146,13 +133,11 @@ struct client void write(const std::string& bytes) { std::size_t offset = 0; const auto deadline = std::chrono::steady_clock::now() + 3s; - while (offset < bytes.size() && std::chrono::steady_clock::now() < deadline) - { + while (offset < bytes.size() && std::chrono::steady_clock::now() < deadline) { asio::error_code ec; offset += socket.write_some(asio::buffer(bytes.data() + offset, bytes.size() - offset), ec); require(!ec || ec == asio::error::would_block || ec == asio::error::try_again, "write failed"); - if (ec) - { + if (ec) { std::this_thread::sleep_for(2ms); } } @@ -177,18 +162,15 @@ struct client std::string bytes(count, '\0'); std::size_t offset = 0; const auto deadline = std::chrono::steady_clock::now() + 3s; - while (offset < count && std::chrono::steady_clock::now() < deadline) - { - if (pump) - { + while (offset < count && std::chrono::steady_clock::now() < deadline) { + if (pump) { pump(); } asio::error_code ec; offset += socket.read_some(asio::buffer(bytes.data() + offset, count - offset), ec); require(!ec || ec == asio::error::would_block || ec == asio::error::try_again, "unexpected disconnect while reading frame"); - if (ec) - { + if (ec) { std::this_thread::sleep_for(2ms); } } @@ -210,17 +192,13 @@ struct client } void quiet() { - if (pump) - { + if (pump) { const auto until = std::chrono::steady_clock::now() + 50ms; - while (std::chrono::steady_clock::now() < until) - { + while (std::chrono::steady_clock::now() < until) { pump(); std::this_thread::sleep_for(1ms); } - } - else - { + } else { std::this_thread::sleep_for(50ms); } asio::error_code ec; @@ -239,15 +217,12 @@ struct client socket.shutdown(tcp::socket::shutdown_send, ec); const auto deadline = std::chrono::steady_clock::now() + 3s; char byte; - while (std::chrono::steady_clock::now() < deadline) - { - if (pump) - { + while (std::chrono::steady_clock::now() < deadline) { + if (pump) { pump(); } socket.read_some(asio::buffer(&byte, 1), ec); - if (ec == asio::error::eof || ec == asio::error::connection_reset) - { + if (ec == asio::error::eof || ec == asio::error::connection_reset) { socket.close(); return; } @@ -285,14 +260,12 @@ void error_is(client& peer, const std::string& code, std::optional(error); require(body.code() == code && body.message().size() <= 160, "wrong error response"); require(body.has_action_sequence() == sequence.has_value(), "wrong error correlation presence"); - if (sequence) - { + if (sequence) { require(body.action_sequence() == *sequence, "wrong action error correlation"); } } -struct roster -{ +struct roster { std::map> players; std::map bindings; std::map identities; @@ -316,8 +289,7 @@ struct roster players.clear(); bindings.clear(); identities.clear(); - for (const auto& value : body.players()) - { + for (const auto& value : body.players()) { add(value); } } @@ -325,19 +297,16 @@ struct roster wire::room_delta changes(client& peer) { const auto body = peer.receive(delta); require(body.room() == "lobby", "wrong delta room"); - for (const auto& value : body.added()) - { + for (const auto& value : body.added()) { add(value); } - for (const auto& value : body.changed()) - { + for (const auto& value : body.changed()) { const auto id = static_cast(value.root().entity_id()); require(players.contains(id), "delta references unknown Entity"); const auto change = decode(value, bindings.at(id)); require(players.at(id)->apply(change) == ark::entity_sync::nested_apply_result::applied, "delta gap, invalid fields or stale generation"); - if (const auto state = players.at(id)->state()) - { + if (const auto state = players.at(id)->state()) { validate_player(*state); } } @@ -485,29 +454,23 @@ void exercise(unsigned short port) { own.changes(alice); alice.close(); - for (const auto kind : {0, 1, 2, 3, 4}) - { + for (const auto kind : {0, 1, 2, 3, 4}) { client malformed(port); auto bytes = client::encode(join, "").substr(0, 12); - if (kind == 0) - { + if (kind == 0) { bytes[0] = 'X'; } - if (kind == 1) - { + if (kind == 1) { bytes[7] = 1; } - if (kind == 2) - { + if (kind == 2) { bytes[10] = 0x20; bytes[11] = 1; } - if (kind == 3) - { + if (kind == 3) { bytes = client::encode(join, std::string(1, static_cast(0x80))); } - if (kind == 4) - { + if (kind == 4) { bytes = client::encode(12345, ""); } malformed.write(bytes); @@ -515,8 +478,7 @@ void exercise(unsigned short port) { } client queued(port); std::string overflow; - for (unsigned index = 0; index < 9; ++index) - { + for (unsigned index = 0; index < 9; ++index) { overflow += client::encode(ping, heartbeat.SerializeAsString()); } queued.write(overflow); @@ -551,8 +513,7 @@ void exercise_attributes(unsigned short port) { const auto changed = own.changes(owner); other.changes(observer); require(changed.added_size() == 0 && changed.changed_size() == 1, "action sent a full/added baseline"); - for (const auto* state : {&own, &other}) - { + for (const auto* state : {&own, &other}) { require(state->number(id, 104) == hp && state->number(id, 105) == mp && state->number(id, 108) == sequence, "wrong authoritative attributes or acknowledgement"); } @@ -574,15 +535,13 @@ void exercise_attributes(unsigned short port) { const auto noop = accept_action(4, wire::action_rest, 100, 100); require(noop.changed(0).root().fields_size() == 1 && noop.changed(0).root().fields(0).index() == 108, "clamped action must acknowledge only action_seq"); - for (std::uint32_t next = 5; next <= 9; ++next) - { + for (std::uint32_t next = 5; next <= 9; ++next) { accept_action(next, wire::action_skill, 100, 100 - (next - 4) * 20); } reject_action(10, wire::action_skill, "insufficient_resource"); accept_action(10, wire::action_rest, 100, 20); accept_action(11, wire::action_skill, 100, 0); - for (std::uint32_t next = 12; next <= 18; ++next) - { + for (std::uint32_t next = 12; next <= 18; ++next) { accept_action(next, wire::action_damage, next == 18 ? 0 : 100 - (next - 11) * 15, 0); } accept_action(19, wire::action_damage, 0, 0); @@ -643,8 +602,7 @@ void exercise_resource_boundary(unsigned short port) { template void pump_until(Ready ready, Update update) { const auto deadline = std::chrono::steady_clock::now() + 3s; - while (!ready() && std::chrono::steady_clock::now() < deadline) - { + while (!ready() && std::chrono::steady_clock::now() < deadline) { update(); std::this_thread::sleep_for(1ms); } @@ -708,8 +666,7 @@ void run_resource_cleanup_child( const std::string& program, const std::filesystem::path& runtime, const std::string& port) { const auto child = fork(); require(child >= 0, "resource cleanup child fork failed"); - if (child == 0) - { + if (child == 0) { execl(program.c_str(), program.c_str(), "--resource-cleanup-only", runtime.c_str(), port.c_str(), static_cast(nullptr)); _exit(127); @@ -719,23 +676,19 @@ void run_resource_cleanup_child( // cannot be interrupted by those operation deadlines or owner polling. const auto deadline = std::chrono::steady_clock::now() + 20s; int status = 0; - while (std::chrono::steady_clock::now() < deadline) - { + while (std::chrono::steady_clock::now() < deadline) { const auto result = waitpid(child, &status, WNOHANG); - if (result == child) - { + if (result == child) { require(WIFEXITED(status) && WEXITSTATUS(status) == 0, "controlled resource cleanup child failed"); return; } - if (result < 0 && errno != EINTR) - { + if (result < 0 && errno != EINTR) { throw std::runtime_error("resource cleanup child wait failed"); } std::this_thread::sleep_for(10ms); } kill(child, SIGKILL); - while (waitpid(child, &status, 0) < 0 && errno == EINTR) - { + while (waitpid(child, &status, 0) < 0 && errno == EINTR) { } throw std::runtime_error("controlled resource cleanup child exceeded its observation deadline"); } @@ -743,16 +696,14 @@ void run_resource_cleanup_child( } // namespace int main(int argc, char** argv) { - try - { + try { require(argc == 4, "usage: server-test LAUNCHER RUNTIME_DIR PORT"); const room_module dependency_probe; require(dependency_probe.get_dependencies() == std::vector{typeid(ark::kernel_module).name(), typeid(ark::map_module).name(), typeid(ark::net_service_manager_module).name()}, "room must retire its Entity state and callbacks before Kernel, Map and Net shutdown"); - if (std::string(argv[1]) == "--resource-cleanup-only") - { + if (std::string(argv[1]) == "--resource-cleanup-only") { exercise_resource_cleanup( std::filesystem::absolute(argv[2]), static_cast(std::stoul(argv[3]))); return 0; @@ -787,19 +738,15 @@ int main(int argc, char** argv) { launcher resource_boundary(argv[1], argv[2], "launcher-resource-boundary.log"); exercise_resource_boundary(port); resource_boundary.stop(); - for (const auto* field : {"hp", "move_seq", "hp_max", "mp_max"}) - { + for (const auto* field : {"hp", "move_seq", "hp_max", "mp_max"}) { auto invalid = original; auto& invalid_profile = invalid["configs"][0]["rows"][0]; const auto name_of_field = std::string(field); - if (name_of_field == "hp_max" || name_of_field == "mp_max") - { + if (name_of_field == "hp_max" || name_of_field == "mp_max") { // Keep the current resource in bounds so only the zero maximum rejects startup. invalid_profile[name_of_field] = 0; invalid_profile[name_of_field == "hp_max" ? "hp" : "mp"] = 0; - } - else - { + } else { invalid_profile[name_of_field] = name_of_field == "hp" ? 101 : 1; } { @@ -821,9 +768,7 @@ int main(int argc, char** argv) { "protobuf baselines/deltas/tombstones, attribute actions, configured defaults, uint32 clamp boundaries, " "disconnect/rejoin, invalid framing and normal shutdown passed\n"; return 0; - } - catch (const std::exception& exception) - { + } catch (const std::exception& exception) { std::cerr << exception.what() << '\n'; return 1; } diff --git a/tests/install/consumer/database.cpp b/tests/install/consumer/database.cpp index 26086b960..e540056a2 100644 --- a/tests/install/consumer/database.cpp +++ b/tests/install/consumer/database.cpp @@ -28,8 +28,7 @@ static_assert(std::is_abstract_v && std::is_abstract_v(&address), sizeof(address)) == 0, "HTTP connect failed"); const std::string request = "GET /installed HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"; std::size_t sent{}; - while (sent != request.size()) - { + while (sent != request.size()) { const auto count = ::send(client, request.data() + sent, request.size() - sent, 0); require(count > 0, "HTTP send failed"); sent += static_cast(count); @@ -135,8 +131,7 @@ int main(int argc, char** argv) { std::string response; char bytes[4096]; ssize_t count; - while ((count = ::recv(client, bytes, sizeof(bytes), 0)) > 0) - { + while ((count = ::recv(client, bytes, sizeof(bytes), 0)) > 0) { response.append(bytes, static_cast(count)); require(response.size() <= 65536, "HTTP response exceeded the fixture bound"); } @@ -146,8 +141,7 @@ int main(int argc, char** argv) { response.starts_with("HTTP/1.1 200 ") && response.ends_with("installed-http-cxx20"), "HTTP response mismatch"); std::cout << "HTTP response: 200 installed-http-cxx20\n"; const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); - while (!manager.stop_until(ark::date_time::get_now_time(), deadline)) - { + while (!manager.stop_until(ark::date_time::get_now_time(), deadline)) { require(manager.get_shutdown_state() == ark::plugin_manager::shutdown_state::stopping && manager.get_shutdown_failure().empty() && !manager.get_shutdown_exception() && std::chrono::steady_clock::now() < deadline, diff --git a/tests/install/consumer/network.cpp b/tests/install/consumer/network.cpp index 9a2bc0486..be133e22b 100644 --- a/tests/install/consumer/network.cpp +++ b/tests/install/consumer/network.cpp @@ -36,8 +36,7 @@ namespace { void require(bool condition, const std::string& reason) { - if (!condition) - { + if (!condition) { std::cerr << reason << std::endl; // A failed acceptance must retain live callback/DSO owners until exit. std::_Exit(1); @@ -170,8 +169,7 @@ int main(int argc, char** argv) { header.serialize_to_string(frame); frame += body; std::size_t sent{}; - while (sent != frame.size()) - { + while (sent != frame.size()) { const auto count = ::send(client, frame.data() + sent, frame.size() - sent, 0); require(count > 0, "TCP frame send failed"); sent += static_cast(count); @@ -179,16 +177,14 @@ int main(int argc, char** argv) { require(!received, "Net callback ran before owner update"); std::string response; const auto request_deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); - while (response.size() < frame.size()) - { + while (response.size() < frame.size()) { require(std::chrono::steady_clock::now() < request_deadline && manager.update(ark::date_time::get_now_time()), "TCP request exceeded its owner observation or update failed"); char bytes[4096]; const auto count = ::recv(client, bytes, sizeof(bytes), MSG_DONTWAIT); require(count > 0 || (count < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)), "TCP reply receive failed"); - if (count > 0) - { + if (count > 0) { response.append(bytes, static_cast(count)); require(response.size() <= frame.size(), "TCP reply exceeded the fixture bound"); } @@ -215,16 +211,14 @@ int main(int argc, char** argv) { std::thread peer([client] { char byte{}; ssize_t count{}; - do - { + do { count = ::recv(client, &byte, 1, 0); } while (count < 0 && errno == EINTR); require(count == 0, "Net shutdown did not send EOF to the accepted TCP peer"); ::close(client); }); const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); - while (!manager.stop_until(ark::date_time::get_now_time(), deadline)) - { + while (!manager.stop_until(ark::date_time::get_now_time(), deadline)) { require(manager.get_shutdown_state() == ark::plugin_manager::shutdown_state::stopping && manager.get_shutdown_failure().empty() && !manager.get_shutdown_exception() && std::chrono::steady_clock::now() < deadline, diff --git a/tests/kafka/entry.cpp b/tests/kafka/entry.cpp index a72464d22..79c31e5fa 100644 --- a/tests/kafka/entry.cpp +++ b/tests/kafka/entry.cpp @@ -10,8 +10,7 @@ namespace { void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { std::cerr << message << std::endl; std::_Exit(1); } diff --git a/tests/kafka/entry_factory.cpp b/tests/kafka/entry_factory.cpp index 3c6c3a35f..fad4df7e1 100644 --- a/tests/kafka/entry_factory.cpp +++ b/tests/kafka/entry_factory.cpp @@ -11,8 +11,7 @@ unsigned created{}; unsigned destroyed{}; unsigned updated{}; -class entry_kafka final : public ark::module_base -{ +class entry_kafka final : public ark::module_base { public: entry_kafka() { ++created; @@ -51,8 +50,7 @@ std::unique_ptr make_kafka_module() { } // namespace ark::detail ARK_EXPORT_FUNC unsigned kafka_entry_events(unsigned event) { - switch (event) - { + switch (event) { case 0: return created; case 1: diff --git a/tests/kafka/exports.cpp b/tests/kafka/exports.cpp index 238f8f035..04727b996 100644 --- a/tests/kafka/exports.cpp +++ b/tests/kafka/exports.cpp @@ -8,8 +8,7 @@ namespace { void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { std::cerr << message << std::endl; std::_Exit(1); } diff --git a/tests/kernel_json/model.cpp b/tests/kernel_json/model.cpp index 7acf7b1c6..c6d1e0bd7 100644 --- a/tests/kernel_json/model.cpp +++ b/tests/kernel_json/model.cpp @@ -35,13 +35,10 @@ std::string replaced(std::string input, const std::string& old, const std::strin } void invalid(const std::string& input, const std::string& expected_pointer) { - try - { + try { static_cast(parse(input, "resource/meta/example.json")); FAIL("invalid JSON definition was accepted"); - } - catch (const error& error) - { + } catch (const error& error) { CHECK(error.source() == "resource/meta/example.json"); CHECK(error.pointer() == expected_pointer); CHECK(std::string(error.what()).find(expected_pointer) != std::string::npos); @@ -112,8 +109,7 @@ TEST_CASE("Entity JSON typed scalars preserve full integer ranges and reject coe {"bool", "true", "1"}, {"int32", "-2147483648", "2147483648"}, {"uint32", "4294967295", "-1"}, {"int64", "-9223372036854775808", "9223372036854775808"}, {"uint64", "18446744073709551615", "-1"}, {"float", "1.25", "1e99"}, {"double", "1.2345678901234567", "\"1.0\""}, {"string", "\"内容\"", "false"}, - {"guid", "\"9223372036854775807\"", "\"9223372036854775808\""}}) - { + {"guid", "\"9223372036854775807\"", "\"9223372036854775808\""}}) { auto input = replaced(sample(), "\"name\":\"hp\",\"index\":104,\"type\":\"uint32\"", "\"name\":\"hp\",\"index\":104,\"type\":\"" + type + "\""); CHECK_NOTHROW(parse(replaced(input, "\"hp\":100", "\"hp\":" + good))); @@ -133,8 +129,7 @@ TEST_CASE("Entity JSON plain-model validation shares the canonical parser and ca } TEST_CASE("Entity JSON loads UTF-8 input paths and retains them in diagnostics") { - struct temporary_directory - { + struct temporary_directory { std::filesystem::path path = std::filesystem::temp_directory_path() / ("ark-json-path-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); @@ -162,13 +157,10 @@ TEST_CASE("Entity JSON loads UTF-8 input paths and retains them in diagnostics") REQUIRE(output.good()); output << "{"; } - try - { + try { static_cast(load(utf8)); FAIL("invalid JSON at the UTF-8 path was accepted"); - } - catch (const error& error) - { + } catch (const error& error) { CHECK(error.source() == utf8); CHECK(std::string(error.what()).find(utf8) != std::string::npos); } diff --git a/tests/network/body_limit_header.hpp b/tests/network/body_limit_header.hpp index f5637a483..56598ae79 100644 --- a/tests/network/body_limit_header.hpp +++ b/tests/network/body_limit_header.hpp @@ -6,8 +6,7 @@ namespace ark::test { template -class large_body_header : public base -{ +class large_body_header : public base { public: std::uint32_t max_body_size() const override { return 8192; diff --git a/tests/network/endpoint_lifetime.cpp b/tests/network/endpoint_lifetime.cpp index 7052f0bcb..c66fba18c 100644 --- a/tests/network/endpoint_lifetime.cpp +++ b/tests/network/endpoint_lifetime.cpp @@ -21,8 +21,7 @@ namespace { using namespace std::chrono_literals; -struct receiver -{ +struct receiver { void on_message(const ark::net_msg*, ark::conv_id_t) { } @@ -33,8 +32,7 @@ struct receiver } }; -class releasing_header final : public ark::s_msg_header -{ +class releasing_header final : public ark::s_msg_header { public: explicit releasing_header(std::function release) : release_(std::move(release)) { @@ -61,13 +59,10 @@ void release_server_from_receive() { }); asio::io_context context; const auto port = [&] { - if constexpr (std::is_same_v) - { + if constexpr (std::is_same_v) { asio::ip::udp::socket listener(context, {asio::ip::udp::v4(), 0}); return listener.local_endpoint().port(); - } - else - { + } else { asio::ip::tcp::acceptor listener(context, {asio::ip::tcp::v4(), 0}); return listener.local_endpoint().port(); } @@ -89,8 +84,8 @@ void release_server_from_receive() { frame += "test"; REQUIRE(client.async_send(frame)); const auto deadline = std::chrono::steady_clock::now() + 5s; - while ((!released.load() || !weak.expired() || client.is_started()) && std::chrono::steady_clock::now() < deadline) - { + while ( + (!released.load() || !weak.expired() || client.is_started()) && std::chrono::steady_clock::now() < deadline) { std::this_thread::sleep_for(1ms); } CHECK(released.load()); @@ -103,12 +98,9 @@ template void release_client_from_receive() { receiver receiver; std::shared_ptr client; - if constexpr (std::is_same_v) - { + if constexpr (std::is_same_v) { client = std::make_shared(&receiver, &receiver::on_websocket_message, &receiver::on_event); - } - else - { + } else { client = std::make_shared(&receiver, &receiver::on_message, &receiver::on_event); } std::atomic released{}; @@ -130,16 +122,14 @@ void release_client_from_receive() { REQUIRE(client->start_client(header, 11, "127.0.0.1", server.listen_port())); const std::weak_ptr weak = client; const auto connected = std::chrono::steady_clock::now() + 5s; - while (server.get_session_count() == 0 && std::chrono::steady_clock::now() < connected) - { + while (server.get_session_count() == 0 && std::chrono::steady_clock::now() < connected) { std::this_thread::sleep_for(1ms); } REQUIRE(server.get_session_count() == 1); server.foreach_session([&](auto& session) { session->async_send(frame); }); const auto deadline = std::chrono::steady_clock::now() + 5s; while ((!released.load() || !weak.expired() || server.get_session_count() != 0) && - std::chrono::steady_clock::now() < deadline) - { + std::chrono::steady_clock::now() < deadline) { std::this_thread::sleep_for(1ms); } CHECK(released.load()); diff --git a/tests/network/framing.cpp b/tests/network/framing.cpp index 315d1f1be..a287820f1 100644 --- a/tests/network/framing.cpp +++ b/tests/network/framing.cpp @@ -86,8 +86,7 @@ TEST_CASE("Framing retains a partial body after complete frames are consumed") { CHECK(message->get_msg_id() == 7); ark::net_msg::release(message); CHECK_FALSE(session.pop_net_msg(message)); - for (std::size_t i = second.size() - 3; i < second.size(); ++i) - { + for (std::size_t i = second.size() - 3; i < second.size(); ++i) { session.add_buffer(second.data() + i, 1); CHECK(session.parse_buffer_to_msg()); } @@ -125,8 +124,7 @@ TEST_CASE("Receive buffer capacity is configurable independently of the message auto header = std::make_shared(); ark::tcp_client_session defaults(header, 1); CHECK(defaults.get_buffer_capacity() == 4096); - for (size_t capacity : {size_t{64}, size_t{64 * 1024}, size_t{512 * 1024}}) - { + for (size_t capacity : {size_t{64}, size_t{64 * 1024}, size_t{512 * 1024}}) { ark::tcp_client_session session(header, 2, nullptr, capacity); CHECK(session.get_buffer_capacity() == capacity); const auto frame = make_frame(7, std::string(ark::ark_msg_max_length, 'x')); @@ -144,31 +142,27 @@ TEST_CASE("Framing uses local header body limits and retains native CS and SS bo for (const auto header : std::vector>{std::make_shared(), std::make_shared(), std::make_shared>(), - std::make_shared>()}) - { + std::make_shared>()}) { const auto limit = header->max_body_size(); CHECK((limit == 4096 || limit == 8192)); std::unique_ptr created(header->create()); std::unique_ptr cloned(header->clone()); CHECK(created->max_body_size() == limit); CHECK(cloned->max_body_size() == limit); - for (const auto size : {limit, limit + 1}) - { + for (const auto size : {limit, limit + 1}) { INFO("limit=", limit, ", length=", size); header->set_message_id(7); header->set_message_length(size); std::string bytes; header->serialize_to_string(bytes); - if (size == limit) - { + if (size == limit) { bytes.append(size, 'x'); } ark::tcp_client_session session(header, 1, nullptr, 16); session.add_buffer(bytes); CHECK(session.parse_buffer_to_msg() == (size == limit)); ark::net_msg* message = nullptr; - if (size == limit) - { + if (size == limit) { REQUIRE(session.pop_net_msg(message)); CHECK(message->get_msg_length() == size); ark::net_msg::release(message); @@ -180,8 +174,7 @@ TEST_CASE("Framing uses local header body limits and retains native CS and SS bo } TEST_CASE("A decoded wire header cannot raise the configured receive limit") { - class wire_limit_header final : public ark::s_msg_header - { + class wire_limit_header final : public ark::s_msg_header { public: std::uint32_t max_body_size() const override { return limit; @@ -220,8 +213,7 @@ TEST_CASE_TEMPLATE("Native framing retains every truncated header until its bina header.serialize_to_string(bytes); const auto header_size = bytes.size(); bytes += payload; - for (std::size_t split = 0; split < header_size; ++split) - { + for (std::size_t split = 0; split < header_size; ++split) { INFO("split=", split, ", header_size=", header_size); ark::tcp_client_session session(std::make_shared(), 1, nullptr, 1); REQUIRE(session.add_buffer(bytes.data(), split) >= 0); @@ -247,8 +239,7 @@ TEST_CASE_TEMPLATE("Native framing retains every truncated header until its bina TEST_CASE_TEMPLATE("Native framing rejects high-bit and maximum wire body lengths before waiting for a body", header_type, ark::s_msg_header, ark::ss_msg_header) { for (const std::uint32_t length : {std::uint32_t{ark::ark_msg_max_length + 1}, std::uint32_t{0x7fffffff}, - std::uint32_t{0x80000000}, std::numeric_limits::max()}) - { + std::uint32_t{0x80000000}, std::numeric_limits::max()}) { INFO("length=", length); header_type header; header.set_message_length(length); @@ -267,8 +258,7 @@ TEST_CASE_TEMPLATE("Native framing rejects high-bit and maximum wire body length TEST_CASE_TEMPLATE("Native framing preserves maximum binary and empty bodies in a coalesced batch", header_type, ark::s_msg_header, ark::ss_msg_header) { std::string payload(ark::ark_msg_max_length, '\0'); - for (std::size_t index = 0; index < payload.size(); ++index) - { + for (std::size_t index = 0; index < payload.size(); ++index) { payload[index] = static_cast(index % 256); } header_type header; diff --git a/tests/network/http.cpp b/tests/network/http.cpp index f4150118e..c2bff4a02 100644 --- a/tests/network/http.cpp +++ b/tests/network/http.cpp @@ -30,8 +30,7 @@ using http_request = arknet::http_request::request_type; using http_response = arknet::http_request::response_type; using http_result = std::pair; -class http_plugin_configuration -{ +class http_plugin_configuration { public: explicit http_plugin_configuration(const std::string& text) : previous_(ark::http_plugin::get_plugin_conf()) @@ -60,11 +59,9 @@ class http_plugin_configuration template bool wait_http(predicate_type predicate, pump_type pump, std::chrono::milliseconds timeout = 5s) { const auto deadline = std::chrono::steady_clock::now() + timeout; - do - { + do { pump(); - if (predicate()) - { + if (predicate()) { return true; } std::this_thread::sleep_for(1ms); @@ -82,8 +79,7 @@ http_result await_http(std::future& future) { return future.get(); } -class http_peer -{ +class http_peer { public: explicit http_peer(bool reply = true) : reply_(reply) { @@ -91,27 +87,21 @@ class http_peer auto reply = [this, session, request] { http_response response(arknet::http::status::ok, request.version()); response.keep_alive(request.keep_alive()); - if (respond) - { + if (respond) { respond(request, response); - } - else - { + } else { response.body() = request.body(); } response.prepare_payload(); session->async_send(std::move(response)); }; - if (reply_) - { + if (reply_) { { std::lock_guard lock(mutex_); requests_.push_back(request); } reply(); - } - else - { + } else { std::lock_guard lock(mutex_); replies_.push_back(std::move(reply)); requests_.push_back(request); @@ -148,8 +138,7 @@ class http_peer std::lock_guard lock(mutex_); replies.swap(replies_); } - for (auto& reply : replies) - { + for (auto& reply : replies) { reply(); } } @@ -164,11 +153,9 @@ class http_peer arknet::http_server server_{1024, 16 * 1024 * 1024, 2}; }; -struct http_callbacks -{ +struct http_callbacks { void receive(http_result result) { - if (std::this_thread::get_id() != update_thread) - { + if (std::this_thread::get_id() != update_thread) { wrong_thread.store(true); } std::lock_guard lock(mutex); @@ -217,23 +204,18 @@ TEST_CASE("HTTP concurrent futures keep each request and response independent") auto& client = *owned_client; std::vector> futures; std::vector expected; - for (int index = 0; index < 48; ++index) - { + for (int index = 0; index < 48; ++index) { const auto target = "/request/" + std::to_string(index); - if (index % 2 == 0) - { + if (index % 2 == 0) { const auto body = "body-" + std::to_string(index); futures.push_back(client.post("localhost", peer.port(), target, nullptr, &body)); expected.push_back("POST:" + target + ":" + body); - } - else - { + } else { futures.push_back(client.get("localhost", peer.port(), target)); expected.push_back("GET:" + target + ":"); } } - for (std::size_t index = 0; index < futures.size(); ++index) - { + for (std::size_t index = 0; index < futures.size(); ++index) { const auto result = await_http(futures[index]); CHECK(result.first); CHECK(result.second == expected[index]); @@ -286,15 +268,11 @@ TEST_CASE("HTTP callbacks run once on the Update thread for both service overloa auto owned_client = ark::detail::make_http_client_module(); auto& client = *owned_client; const std::string body = "callback-body"; - for (int index = 0; index < 12; ++index) - { + for (int index = 0; index < 12; ++index) { auto callback = [&](http_result result) { callbacks.receive(std::move(result)); }; - if (index % 2 == 0) - { + if (index % 2 == 0) { client.post(callback, "localhost", peer.port(), "/callback", nullptr, &body); - } - else - { + } else { client.post(callback, "localhost", std::to_string(peer.port()), "/callback", nullptr, &body); } } @@ -302,14 +280,12 @@ TEST_CASE("HTTP callbacks run once on the Update thread for both service overloa std::this_thread::sleep_for(100ms); CHECK(callbacks.result_snapshot().empty()); REQUIRE(wait_http([&] { return callbacks.result_snapshot().size() == 12; }, [&] { client.update(); })); - for (const auto& result : callbacks.result_snapshot()) - { + for (const auto& result : callbacks.result_snapshot()) { CHECK(result.first); CHECK(result.second == body); } CHECK_FALSE(callbacks.wrong_thread.load()); - for (int index = 0; index < 3; ++index) - { + for (int index = 0; index < 3; ++index) { client.update(); } CHECK(callbacks.result_snapshot().size() == 12); @@ -328,8 +304,7 @@ TEST_CASE("HTTP preserves non-200 failure reasons and arbitrary request verbs") auto missing = client.get("127.0.0.1", peer.port(), "/missing"); auto put = client.async_request(arknet::http::verb::put, "127.0.0.1", peer.port(), "/put"); auto remove = client.async_request(arknet::http::verb::delete_, "127.0.0.1", peer.port(), "/delete"); - for (auto* future : {&missing, &put, &remove}) - { + for (auto* future : {&missing, &put, &remove}) { const auto result = await_http(*future); CHECK_FALSE(result.first); CHECK(result.second == "Missing business route"); @@ -369,12 +344,10 @@ TEST_CASE("HTTP shutdown cancels all pending requests and settles futures withou auto owned_client = ark::detail::make_http_client_module(); auto& client = *owned_client; std::vector> futures; - for (int index = 0; index < 24; ++index) - { + for (int index = 0; index < 24; ++index) { futures.push_back(client.get("127.0.0.1", peer.port(), "/pending")); } - for (int index = 0; index < 8; ++index) - { + for (int index = 0; index < 8; ++index) { client.post( [&](http_result result) { callbacks.receive(std::move(result)); }, "127.0.0.1", peer.port(), "/pending"); } @@ -384,8 +357,7 @@ TEST_CASE("HTTP shutdown cancels all pending requests and settles futures withou CHECK(std::chrono::steady_clock::now() - start < 2s); CHECK(callbacks.result_snapshot().empty()); const auto aborted = arknet::error_code(asio::error::operation_aborted).message(); - for (auto& future : futures) - { + for (auto& future : futures) { CHECK(future.wait_for(0ms) == std::future_status::ready); const auto result = await_http(future); CHECK_FALSE(result.first); @@ -393,8 +365,7 @@ TEST_CASE("HTTP shutdown cancels all pending requests and settles futures withou } client.update(); REQUIRE(callbacks.result_snapshot().size() == 8); - for (const auto& result : callbacks.result_snapshot()) - { + for (const auto& result : callbacks.result_snapshot()) { CHECK_FALSE(result.first); CHECK(result.second == aborted); } @@ -522,8 +493,7 @@ TEST_CASE("HTTP manager timeout retains requests and callback owners for later u } TEST_CASE("HTTP manager failure retains IO results and callback receivers without automatic dispatch") { - struct failed_readiness : ark::module - { + struct failed_readiness : ark::module { bool ready_to_shut() const override { throw std::runtime_error("readiness failure"); } @@ -631,10 +601,11 @@ TEST_CASE("HTTP callback exceptions release active ownership without sealing the bool caught = false; REQUIRE(wait_http([&] { return caught; }, [&] { - try - { client.update(); } - catch (const std::runtime_error&) - { caught = true; } + try { + client.update(); + } catch (const std::runtime_error&) { + caught = true; + } })); CHECK(delivered == 1); CHECK(retained.expired()); @@ -657,8 +628,7 @@ TEST_CASE("HTTP validates host headers target and timeout before network IO") { const std::string trace_body = "trace-body"; auto trace = client.async_request(arknet::http::verb::trace, "127.0.0.1", peer.port(), "/", nullptr, nullptr, &trace_body); - for (auto* future : {&host, &header, &target, &timeout, &trace}) - { + for (auto* future : {&host, &header, &target, &timeout, &trace}) { const auto result = await_http(*future); CHECK_FALSE(result.first); CHECK(result.second == arknet::error_code(asio::error::invalid_argument).message()); diff --git a/tests/network/http_client_startup_access.hpp b/tests/network/http_client_startup_access.hpp index 93da8d7c6..c98b2b433 100644 --- a/tests/network/http_client_startup_access.hpp +++ b/tests/network/http_client_startup_access.hpp @@ -5,8 +5,7 @@ #include "../../src/plugins/net/http_client_module_impl.cpp" namespace ark { -struct http_client_startup_test_access -{ +struct http_client_startup_test_access { static arknet::io_pool& runtime(http_client_module& module) { return static_cast(module).state_->runtime; } diff --git a/tests/network/http_client_startup_cleanup.cpp b/tests/network/http_client_startup_cleanup.cpp index e18497b27..1de88eae6 100644 --- a/tests/network/http_client_startup_cleanup.cpp +++ b/tests/network/http_client_startup_cleanup.cpp @@ -36,10 +36,8 @@ thread_local bool fail_allocations{}; } // namespace void* operator new(std::size_t size) { - if (!fail_allocations) - { - if (auto* pointer = std::malloc(size ? size : 1)) - { + if (!fail_allocations) { + if (auto* pointer = std::malloc(size ? size : 1)) { return pointer; } } @@ -67,17 +65,19 @@ void operator delete[](void* pointer, std::size_t) noexcept { } void* operator new(std::size_t size, const std::nothrow_t&) noexcept { - try - { return ::operator new(size); } - catch (...) - { return nullptr; } + try { + return ::operator new(size); + } catch (...) { + return nullptr; + } } void* operator new[](std::size_t size, const std::nothrow_t&) noexcept { - try - { return ::operator new[](size); } - catch (...) - { return nullptr; } + try { + return ::operator new[](size); + } catch (...) { + return nullptr; + } } void operator delete(void* pointer, const std::nothrow_t&) noexcept { @@ -104,19 +104,16 @@ using access = ark::http_client_startup_test_access; #endif } -struct failing_module : ark::module -{ +struct failing_module : ark::module { unsigned phase{}; bool throws{}; unsigned ordinary_cleanup{}; bool step(unsigned current) const { - if (phase != current) - { + if (phase != current) { return true; } - if (throws) - { + if (throws) { throw std::runtime_error("controlled later HTTP startup failure"); } return false; @@ -157,10 +154,8 @@ ark::startup_cleanup_result release_older(void* pointer) { template bool eventually(predicate&& ready) { const auto deadline = std::chrono::steady_clock::now() + 5s; - while (!ready()) - { - if (std::chrono::steady_clock::now() >= deadline) - { + while (!ready()) { + if (std::chrono::steady_clock::now() >= deadline) { return false; } std::this_thread::yield(); @@ -168,8 +163,7 @@ bool eventually(predicate&& ready) { return true; } -class http_peer -{ +class http_peer { public: http_peer() { server_.bind_recv([this](auto& session, auto&) { @@ -197,8 +191,7 @@ class http_peer std::lock_guard lock(mutex_); pending.swap(pending_); } - for (const auto& session : pending) - { + for (const auto& session : pending) { arknet::http_request::response_type response(arknet::http::status::ok, 11); response.body() = "accepted"; response.prepare_payload(); @@ -217,10 +210,8 @@ class http_peer } // namespace TEST_CASE("Failed startup retires the idle constructor-started Net HTTP runtime") { - for (unsigned phase{}; phase < 4; ++phase) - { - for (bool throws : {false, true}) - { + for (unsigned phase{}; phase < 4; ++phase) { + for (bool throws : {false, true}) { ark::plugin_manager manager; auto older = std::make_shared(0); REQUIRE(manager.prepare_startup_cleanup("older", "test", older, release_older)); @@ -231,12 +222,9 @@ TEST_CASE("Failed startup retires the idle constructor-started Net HTTP runtime" REQUIRE(access::runtime(*client).started()); REQUIRE(manager.add_module("http", client.get())); REQUIRE(manager.add_module("failure", &failure)); - if (throws) - { + if (throws) { CHECK_THROWS_AS(manager.start(0, {}, {}, {}), std::runtime_error); - } - else - { + } else { CHECK_FALSE(manager.start(0, {}, {}, {})); } CHECK(manager.cleanup_failed_startup() == ark::startup_cleanup_result::done); @@ -272,10 +260,11 @@ TEST_CASE("Net HTTP factory allocation failure acquires no worker") { REQUIRE(manager.prepare_startup_cleanup("older", "test", older, release_older)); bool rejected{}; fail_allocations = true; - try - { auto client = ark::detail::make_http_client_module(&manager); } - catch (const std::bad_alloc&) - { rejected = true; } + try { + auto client = ark::detail::make_http_client_module(&manager); + } catch (const std::bad_alloc&) { + rejected = true; + } fail_allocations = false; CHECK(rejected); failing_module failure; @@ -401,12 +390,10 @@ TEST_CASE("Executing startup HTTP callbacks retain their active frame") { } int main(int argc, char** argv) { - if (argc == 2 && std::string_view(argv[1]) == "--allocation-failure") - { + if (argc == 2 && std::string_view(argv[1]) == "--allocation-failure") { ark::plugin_manager manager; auto older = std::make_shared(0); - if (!manager.prepare_startup_cleanup("older", "test", older, release_older)) - { + if (!manager.prepare_startup_cleanup("older", "test", older, release_older)) { exit_startup_probe(2); } auto client = ark::detail::make_http_client_module(&manager); @@ -414,21 +401,18 @@ int main(int argc, char** argv) { auto* runtime = &access::runtime(*client); failing_module failure; manager.add_module("failure", &failure); - if (manager.start(0, {}, {}, {})) - { + if (manager.start(0, {}, {}, {})) { exit_startup_probe(2); } fail_allocations = true; client.reset(); // Candidate unwinding must leave the enrolled owner intact. - if (capsule.expired() || !runtime->started()) - { + if (capsule.expired() || !runtime->started()) { exit_startup_probe(2); } const auto result = manager.cleanup_failed_startup(); const auto repeated = manager.cleanup_failed_startup(); if (result != ark::startup_cleanup_result::done || repeated != result || !runtime->stopped() || *older != 1 || - capsule.expired()) - { + capsule.expired()) { std::fprintf(stderr, "HTTP allocation probe: result=%d repeated=%d stopped=%d older=%u\n", static_cast(result), static_cast(repeated), runtime->stopped(), *older); exit_startup_probe(2); @@ -436,8 +420,7 @@ int main(int argc, char** argv) { std::fputs("HTTP startup allocation failure: idle runtime joined; candidate gone; exit 1\n", stderr); exit_startup_probe(1); // Failure cleanup never becomes same-process recovery. } - if (argc == 3 && std::string_view(argv[1]) == "--install-failure") - { + if (argc == 3 && std::string_view(argv[1]) == "--install-failure") { ark::logger log; log.set_log_func([](spdlog::level::level_enum, const std::string& message) { std::fprintf(stderr, "%s\n", message.c_str()); @@ -447,22 +430,21 @@ int main(int argc, char** argv) { const std::string directory = std::string(argv[2]) + "/"; constexpr auto name = "ark_http_startup_install_fixture"; bool failed{}; - try - { manager.start(0, directory, {}, {{name, ""}}); } - catch (const std::runtime_error&) - { failed = true; } + try { + manager.start(0, directory, {}, {{name, ""}}); + } catch (const std::runtime_error&) { + failed = true; + } ark::dynamic_library library(name); if (!failed || std::string_view(manager.get_startup_call().phase.data()) != "install" || - !library.load(directory)) - { + !library.load(directory)) { exit_startup_probe(2); } const auto started = reinterpret_cast(library.get_symbol("http_fixture_runtime_started")); const auto stopped = reinterpret_cast(library.get_symbol("http_fixture_runtime_stopped")); if (!started || !stopped || !started() || manager.cleanup_failed_startup() != ark::startup_cleanup_result::done || !stopped() || - manager.cleanup_failed_startup() != ark::startup_cleanup_result::done) - { + manager.cleanup_failed_startup() != ark::startup_cleanup_result::done) { exit_startup_probe(2); } std::fputs("HTTP install failure: idle runtime joined once; retained DSO and owners; exit 1\n", stderr); diff --git a/tests/network/http_client_startup_install.cpp b/tests/network/http_client_startup_install.cpp index c207f848a..703636ebe 100644 --- a/tests/network/http_client_startup_install.cpp +++ b/tests/network/http_client_startup_install.cpp @@ -5,15 +5,13 @@ namespace { ark::http_client_module* installed_client{}; -struct detach_guard -{ +struct detach_guard { ~detach_guard() { std::fputs("forbidden HTTP fixture destruction\n", stderr); } } retained_dso; -class install_failure_plugin final : public ark::plugin_base -{ +class install_failure_plugin final : public ark::plugin_base { public: void install() override { client_ = ark::detail::make_http_client_module(get_plugin_manager()); diff --git a/tests/network/http_resource_cleanup.cpp b/tests/network/http_resource_cleanup.cpp index bddd93325..a223206eb 100644 --- a/tests/network/http_resource_cleanup.cpp +++ b/tests/network/http_resource_cleanup.cpp @@ -27,8 +27,7 @@ std::uint16_t resource_port() { return acceptor.local_endpoint().port(); } -class release_route -{ +class release_route { public: explicit release_route(std::promise& promise) : promise_(promise) { @@ -39,8 +38,7 @@ class release_route } void release() { - if (!released_) - { + if (!released_) { promise_.set_value(); released_ = true; } @@ -53,8 +51,7 @@ class release_route bool wait_for_resource_readiness(const ark::http_server_module& server) { const auto deadline = std::chrono::steady_clock::now() + 5s; - while (!server.ready_to_shut() && std::chrono::steady_clock::now() < deadline) - { + while (!server.ready_to_shut() && std::chrono::steady_clock::now() < deadline) { std::this_thread::yield(); } return server.ready_to_shut(); @@ -71,8 +68,7 @@ TEST_CASE("HTTP resource retirement seals native route dispatch and waits for ac std::atomic route_timed_out{false}; auto server = ark::detail::make_http_server_module(); server->get_router().add(arknet::http::verb::get, "/accepted", [&](const auto&, auto& response) { - if (++routed == 1) - { + if (++routed == 1) { entered.set_value(); route_timed_out = released.wait_for(5s) != std::future_status::ready; } @@ -103,8 +99,7 @@ TEST_CASE("HTTP resource retirement seals native route dispatch and waits for ac CHECK(response.second == "accepted"); CHECK_FALSE(route_timed_out.load()); const auto deadline = std::chrono::steady_clock::now() + 5s; - while (!server->ready_to_shut() && std::chrono::steady_clock::now() < deadline) - { + while (!server->ready_to_shut() && std::chrono::steady_clock::now() < deadline) { std::this_thread::sleep_for(1ms); } REQUIRE(server->ready_to_shut()); @@ -147,8 +142,7 @@ TEST_CASE("HTTP resource readiness waits for a route after its peer disconnects" socket.close(); route_guard.release(); const auto deadline = std::chrono::steady_clock::now() + 5s; - while (!server->ready_to_shut() && std::chrono::steady_clock::now() < deadline) - { + while (!server->ready_to_shut() && std::chrono::steady_clock::now() < deadline) { std::this_thread::sleep_for(1ms); } REQUIRE(server->ready_to_shut()); @@ -168,8 +162,7 @@ TEST_CASE("HTTP server manager timeout retains its listener and active route") { std::weak_ptr retained = lifetime; auto server = ark::detail::make_http_server_module(); server->get_router().add(arknet::http::verb::get, "/timeout", [&, lifetime](const auto&, auto& response) { - if (++routed == 1) - { + if (++routed == 1) { entered.set_value(); route_timed_out = released.wait_for(5s) != std::future_status::ready; } @@ -215,8 +208,7 @@ TEST_CASE("HTTP server manager timeout retains its listener and active route") { } TEST_CASE("HTTP server manager readiness failure retains its listener and active route") { - struct failed_readiness : ark::module - { + struct failed_readiness : ark::module { bool ready_to_shut() const override { throw std::runtime_error("HTTP resource readiness failure"); } @@ -232,8 +224,7 @@ TEST_CASE("HTTP server manager readiness failure retains its listener and active std::weak_ptr retained = lifetime; auto server = ark::detail::make_http_server_module(); server->get_router().add(arknet::http::verb::get, "/failure", [&, lifetime](const auto&, auto& response) { - if (++routed == 1) - { + if (++routed == 1) { entered.set_value(); route_timed_out = released.wait_for(5s) != std::future_status::ready; } diff --git a/tests/network/http_server_startup_install.cpp b/tests/network/http_server_startup_install.cpp index 597b944d1..15acb41f0 100644 --- a/tests/network/http_server_startup_install.cpp +++ b/tests/network/http_server_startup_install.cpp @@ -7,8 +7,7 @@ namespace ark { -struct http_server_startup_test_access -{ +struct http_server_startup_test_access { static auto state(http_server_module& module) { return static_cast(module).state_; } @@ -22,22 +21,19 @@ std::weak_ptr retained_state; std::weak_ptr retained_capture; arknet::http_server* retained_native{}; -struct destruction_marker -{ +struct destruction_marker { ~destruction_marker() { std::fputs("forbidden HTTP ownership fixture capture destruction\n", stderr); } }; -struct detach_marker -{ +struct detach_marker { ~detach_marker() { std::fputs("forbidden HTTP ownership fixture DSO destruction\n", stderr); } } retained_dso; -class http_ownership_install_failure final : public ark::plugin_base -{ +class http_ownership_install_failure final : public ark::plugin_base { public: void install() override { auto candidate = ark::detail::make_http_server_module(get_plugin_manager()); @@ -46,8 +42,7 @@ class http_ownership_install_failure final : public ark::plugin_baseget_router().add(arknet::http::verb::get, "/retained", [capture](auto&, auto& response) { response.body() = "retained DSO route"; }); capture.reset(); - if (!candidate->start_server("127.0.0.1", 0, 2)) - { + if (!candidate->start_server("127.0.0.1", 0, 2)) { throw std::runtime_error("HTTP ownership fixture could not start native listener"); } auto state = ark::http_server_startup_test_access::state(*candidate); diff --git a/tests/network/http_server_startup_ownership.cpp b/tests/network/http_server_startup_ownership.cpp index 6952e51e2..1eb85186e 100644 --- a/tests/network/http_server_startup_ownership.cpp +++ b/tests/network/http_server_startup_ownership.cpp @@ -40,23 +40,19 @@ thread_local bool reject_after_workers{}; bool failure_observed_workers{}; bool reject_new() { - if (reject_allocations) - { + if (reject_allocations) { return true; } auto* native = arknet::startup_observed_server; - if (reject_after_workers && native) - { + if (reject_after_workers && native) { // Pool construction/start can allocate while holding its lifecycle // mutex. Observe lane identities instead of reentering started(). All // workers have initialized before start_iopool posts its first work. bool initialized = native->iopool().size() != 0; - for (std::size_t index{}; index < native->iopool().size(); ++index) - { + for (std::size_t index{}; index < native->iopool().size(); ++index) { initialized = initialized && native->iopool().get(index)->get_thread_id() != std::thread::id{}; } - if (initialized) - { + if (initialized) { failure_observed_workers = true; reject_allocations = true; return true; @@ -67,10 +63,8 @@ bool reject_new() { } // namespace void* operator new(std::size_t size) { - if (!reject_new()) - { - if (auto* pointer = std::malloc(size ? size : 1)) - { + if (!reject_new()) { + if (auto* pointer = std::malloc(size ? size : 1)) { return pointer; } } @@ -98,17 +92,19 @@ void operator delete[](void* pointer, std::size_t) noexcept { } void* operator new(std::size_t size, const std::nothrow_t&) noexcept { - try - { return ::operator new(size); } - catch (...) - { return nullptr; } + try { + return ::operator new(size); + } catch (...) { + return nullptr; + } } void* operator new[](std::size_t size, const std::nothrow_t&) noexcept { - try - { return ::operator new[](size); } - catch (...) - { return nullptr; } + try { + return ::operator new[](size); + } catch (...) { + return nullptr; + } } void operator delete(void* pointer, const std::nothrow_t&) noexcept { @@ -121,8 +117,7 @@ void operator delete[](void* pointer, const std::nothrow_t&) noexcept { namespace ark { -struct http_server_startup_test_access -{ +struct http_server_startup_test_access { static auto state(http_server_module& module) { return static_cast(module).state_; } @@ -144,19 +139,16 @@ using access = ark::http_server_startup_test_access; #endif } -struct failing_module final : ark::module -{ +struct failing_module final : ark::module { unsigned phase{}; bool throws{}; unsigned ordinary_cleanup{}; bool step(unsigned current) const { - if (phase != current) - { + if (phase != current) { return true; } - if (throws) - { + if (throws) { throw std::runtime_error("controlled HTTP listener startup failure"); } return false; @@ -198,10 +190,8 @@ template void retire_test_owner(const State& state) { // Explicit fixture-owner teardown, after retention evidence. The failed // manager never retries cleanup or invokes ordinary stop on these owners. - for (auto* owner = state->owners.get(); owner; owner = owner->next.get()) - { - if (owner->server) - { + for (auto* owner = state->owners.get(); owner; owner = owner->next.get()) { + if (owner->server) { owner->server->stop(); owner->server.reset(); } @@ -226,8 +216,7 @@ std::string request(std::uint16_t port) { return output.body(); } -struct allocation_start_module final : ark::module -{ +struct allocation_start_module final : ark::module { ark::http_server_module* server{}; std::string ip{"127.0.0.1"}; @@ -240,10 +229,8 @@ struct allocation_start_module final : ark::module } // namespace TEST_CASE("HTTP empty startup ownership seals safely after each false or exception") { - for (unsigned phase{}; phase < 4; ++phase) - { - for (bool throws : {false, true}) - { + for (unsigned phase{}; phase < 4; ++phase) { + for (bool throws : {false, true}) { CAPTURE(phase); CAPTURE(throws); ark::plugin_manager manager; @@ -254,12 +241,9 @@ TEST_CASE("HTTP empty startup ownership seals safely after each false or excepti failure.phase = phase; failure.throws = throws; REQUIRE(manager.add_module("failure", &failure)); - if (throws) - { + if (throws) { CHECK_THROWS_AS(manager.start(0, {}, {}, {}), std::runtime_error); - } - else - { + } else { CHECK_FALSE(manager.start(0, {}, {}, {})); } CHECK(manager.cleanup_failed_startup() == ark::startup_cleanup_result::done); @@ -272,10 +256,8 @@ TEST_CASE("HTTP empty startup ownership seals safely after each false or excepti } TEST_CASE("HTTP native owners stay unsafe after every later false or exception") { - for (unsigned phase{}; phase < 4; ++phase) - { - for (bool throws : {false, true}) - { + for (unsigned phase{}; phase < 4; ++phase) { + for (bool throws : {false, true}) { CAPTURE(phase); CAPTURE(throws); ark::plugin_manager manager; @@ -288,12 +270,9 @@ TEST_CASE("HTTP native owners stay unsafe after every later false or exception") failure.phase = phase; failure.throws = throws; REQUIRE(manager.add_module("failure", &failure)); - if (throws) - { + if (throws) { CHECK_THROWS_AS(manager.start(0, {}, {}, {}), std::runtime_error); - } - else - { + } else { CHECK_FALSE(manager.start(0, {}, {}, {})); } CHECK(manager.cleanup_failed_startup() == ark::startup_cleanup_result::unsafe); @@ -383,8 +362,7 @@ TEST_CASE("HTTP successful startup disarms enrollment and restores ordinary dest TEST_CASE("HTTP full startup registry rejects ownership before native acquisition") { ark::plugin_manager manager; auto older = std::make_shared(0); - for (std::size_t index{}; index < ark::startup_cleanup_capacity; ++index) - { + for (std::size_t index{}; index < ark::startup_cleanup_capacity; ++index) { REQUIRE(manager.prepare_startup_cleanup("owner-" + std::to_string(index), "test", older, release_older)); } const auto constructed = arknet::startup_native_constructions; @@ -426,8 +404,7 @@ TEST_CASE("HTTP managed native listen rejection preserves ordinary same-endpoint } TEST_CASE("HTTP ordinary listen failures do not accumulate native attempt owners") { - for (bool managed : {false, true}) - { + for (bool managed : {false, true}) { CAPTURE(managed); asio::io_context context; asio::ip::tcp::acceptor occupied(context); @@ -442,13 +419,11 @@ TEST_CASE("HTTP ordinary listen failures do not accumulate native attempt owners const auto port = occupied.local_endpoint().port(); ark::plugin_manager manager; auto server = ark::detail::make_http_server_module(managed ? &manager : nullptr); - if (managed) - { + if (managed) { REQUIRE(manager.start(0, {}, {}, {})); } auto state = access::state(*server); - for (unsigned attempt{}; attempt < 4; ++attempt) - { + for (unsigned attempt{}; attempt < 4; ++attempt) { CHECK_FALSE(server->start_server("127.0.0.1", port, 1)); CHECK(state->owners == nullptr); } @@ -460,8 +435,7 @@ TEST_CASE("HTTP ordinary listen failures do not accumulate native attempt owners } int main(int argc, char** argv) { - if (argc == 3 && std::string_view(argv[1]) == "--install-failure") - { + if (argc == 3 && std::string_view(argv[1]) == "--install-failure") { ark::logger log; log.set_log_func([](spdlog::level::level_enum, const std::string& message) { std::fprintf(stderr, "%s\n", message.c_str()); @@ -473,25 +447,22 @@ int main(int argc, char** argv) { const std::string directory = std::string(argv[2]) + "/"; constexpr auto name = "ark_http_server_startup_install_fixture"; bool threw{}; - try - { manager.start(0, directory, {}, {{name, ""}}); } - catch (const std::runtime_error& exception) - { + try { + manager.start(0, directory, {}, {{name, ""}}); + } catch (const std::runtime_error& exception) { threw = true; std::fprintf(stderr, "HTTP ownership install exception: %s\n", exception.what()); } ark::dynamic_library library(name); if (!threw || std::string_view(manager.get_startup_call().phase.data()) != "install" || - !library.load(directory)) - { + !library.load(directory)) { std::fprintf(stderr, "HTTP ownership install probe: threw=%d phase=%s\n", threw, manager.get_startup_call().phase.data()); exit_probe(2); } const auto retained = reinterpret_cast(library.get_symbol("http_ownership_fixture_retained")); if (!retained || !retained() || manager.cleanup_failed_startup() != ark::startup_cleanup_result::unsafe || - manager.cleanup_failed_startup() != ark::startup_cleanup_result::unsafe || !retained() || *older != 0) - { + manager.cleanup_failed_startup() != ark::startup_cleanup_result::unsafe || !retained() || *older != 0) { std::fprintf(stderr, "HTTP ownership install probe: symbol=%d retained=%d older=%u\n", retained != nullptr, retained ? retained() : false, *older); exit_probe(2); @@ -500,8 +471,7 @@ int main(int argc, char** argv) { "HTTP ownership install failure: candidate gone; native, captures and DSO retained; exit 1\n", stderr); exit_probe(1); } - if (argc == 2 && std::string_view(argv[1]) == "--allocation-failure") - { + if (argc == 2 && std::string_view(argv[1]) == "--allocation-failure") { std::set_terminate([] { std::fputs("forbidden native destruction before HTTP failure runner\n", stderr); exit_probe(2); @@ -519,13 +489,13 @@ int main(int argc, char** argv) { const std::string configuration; const std::unordered_map plugins; bool threw{}; - try - { manager.start(0, directory, configuration, plugins); } - catch (const std::bad_alloc&) - { threw = true; } + try { + manager.start(0, directory, configuration, plugins); + } catch (const std::bad_alloc&) { + threw = true; + } if (!threw || !failure_observed_workers || !reject_allocations || !state->owners || !state->owners->server || - !state->owners->server->iopool().started()) - { + !state->owners->server->iopool().started()) { exit_probe(2); } std::weak_ptr retained = state; @@ -535,8 +505,7 @@ int main(int argc, char** argv) { if (!state || manager.cleanup_failed_startup() != ark::startup_cleanup_result::unsafe || manager.cleanup_failed_startup() != ark::startup_cleanup_result::unsafe || *older != 0 || !state->owners->server->iopool().started() || - state->owners->server->iopool().get(0)->get_thread_id() == std::thread::id{}) - { + state->owners->server->iopool().get(0)->get_thread_id() == std::thread::id{}) { exit_probe(2); } std::fputs("HTTP ownership failure runner reached: native workers and older owners retained; exit 1\n", stderr); diff --git a/tests/network/http_server_startup_probe.hpp b/tests/network/http_server_startup_probe.hpp index 7d98ae8b6..4a4686c70 100644 --- a/tests/network/http_server_startup_probe.hpp +++ b/tests/network/http_server_startup_probe.hpp @@ -10,8 +10,7 @@ inline unsigned startup_native_constructions{}; // The production translation unit uses this derived probe only to publish the // completion of native construction. All start/stop/IO behavior is inherited. -class startup_probe_http_server final : public http_server -{ +class startup_probe_http_server final : public http_server { public: startup_probe_http_server(std::size_t initial, std::size_t maximum, std::size_t workers) : http_server(initial, maximum, workers) { diff --git a/tests/network/http_startup_failure.cpp b/tests/network/http_startup_failure.cpp index dc68a263d..743c41aa0 100644 --- a/tests/network/http_startup_failure.cpp +++ b/tests/network/http_startup_failure.cpp @@ -21,8 +21,7 @@ bool fail_next_allocation{}; bool fail_allocations{}; bool fail_after_reservation(std::size_t size) { - if (observed_endpoint && ark::http_endpoints.contains(*observed_endpoint)) - { + if (observed_endpoint && ark::http_endpoints.contains(*observed_endpoint)) { observed_endpoint = nullptr; failed_size = size; fail_allocations = true; @@ -40,13 +39,11 @@ std::uint16_t unused_http_port() { } // namespace void* operator new(std::size_t size) { - if (fail_allocations || fail_next_allocation || fail_after_reservation(size)) - { + if (fail_allocations || fail_next_allocation || fail_after_reservation(size)) { fail_next_allocation = false; throw std::bad_alloc{}; } - if (auto* value = std::malloc(size ? size : 1)) - { + if (auto* value = std::malloc(size ? size : 1)) { return value; } throw std::bad_alloc{}; @@ -62,10 +59,11 @@ void operator delete(void* value, std::size_t) noexcept { // Match the scalar nothrow allocation family when a native constructor unwinds. void* operator new(std::size_t size, const std::nothrow_t&) noexcept { - try - { return ::operator new(size); } - catch (...) - { return nullptr; } + try { + return ::operator new(size); + } catch (...) { + return nullptr; + } } void operator delete(void* value, const std::nothrow_t&) noexcept { @@ -79,10 +77,11 @@ TEST_CASE("HTTP allocation failure after reservation releases only its endpoint auto server = ark::detail::make_http_server_module(); bool threw{}; observed_endpoint = &endpoint; - try - { server->start_server(ip, port, 1); } - catch (const std::bad_alloc&) - { threw = true; } + try { + server->start_server(ip, port, 1); + } catch (const std::bad_alloc&) { + threw = true; + } observed_endpoint = nullptr; fail_allocations = false; CHECK(threw); diff --git a/tests/network/logging.cpp b/tests/network/logging.cpp index e41067bef..98be6e2b5 100644 --- a/tests/network/logging.cpp +++ b/tests/network/logging.cpp @@ -16,8 +16,7 @@ namespace { -struct log_directory -{ +struct log_directory { const std::filesystem::path path = std::filesystem::temp_directory_path() / ("ark-logging-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); diff --git a/tests/network/message_failure.cpp b/tests/network/message_failure.cpp index 9e33a66e1..d9e4b45c8 100644 --- a/tests/network/message_failure.cpp +++ b/tests/network/message_failure.cpp @@ -11,8 +11,7 @@ namespace { bool fail_next_receive_array{}; char* allocate_receive_bytes(std::size_t size) { - if (fail_next_receive_array) - { + if (fail_next_receive_array) { fail_next_receive_array = false; return nullptr; } @@ -33,8 +32,7 @@ bool fail_next_array{}; bool fail_next_object{}; int live_headers{}; -class test_header final : public ark::s_msg_header -{ +class test_header final : public ark::s_msg_header { public: test_header() { ++live_headers; @@ -56,8 +54,7 @@ class test_header final : public ark::s_msg_header } ark::msg_header* clone() const override { - if (throw_clone) - { + if (throw_clone) { throw std::bad_alloc{}; } return fail_clone ? nullptr : new (std::nothrow) test_header(*this); @@ -87,13 +84,11 @@ message_owner make_message(const std::string& body) { // Each hook fails exactly one small request; ordinary doctest allocations are unaffected. void* operator new[](std::size_t size) { - if (fail_next_array) - { + if (fail_next_array) { fail_next_array = false; throw std::bad_alloc{}; } - if (auto* value = std::malloc(size ? size : 1)) - { + if (auto* value = std::malloc(size ? size : 1)) { return value; } throw std::bad_alloc{}; @@ -108,15 +103,15 @@ void operator delete[](void* value, std::size_t) noexcept { } void* operator new(std::size_t size, const std::nothrow_t&) noexcept { - if (fail_next_object) - { + if (fail_next_object) { fail_next_object = false; return nullptr; } - try - { return ::operator new(size); } - catch (...) - { return nullptr; } + try { + return ::operator new(size); + } catch (...) { + return nullptr; + } } void operator delete(void* value, const std::nothrow_t&) noexcept { @@ -193,8 +188,7 @@ TEST_CASE("Event and native header factories return null on nothrow allocation f CHECK_FALSE(fail_next_object); ark::s_msg_header cs; ark::ss_msg_header ss; - for (ark::msg_header* header : {static_cast(&cs), static_cast(&ss)}) - { + for (ark::msg_header* header : {static_cast(&cs), static_cast(&ss)}) { fail_next_object = true; auto* created = header->create(); CHECK(created == nullptr); @@ -207,8 +201,7 @@ TEST_CASE("Event and native header factories return null on nothrow allocation f } TEST_CASE("Receive parsing rejects failed header, message and body allocations without queueing") { - for (int failure = 0; failure != 3; ++failure) - { + for (int failure = 0; failure != 3; ++failure) { INFO("failure=", failure); auto prototype = std::make_shared(); ark::tcp_client_session session(prototype, 1); diff --git a/tests/network/message_ownership.cpp b/tests/network/message_ownership.cpp index d4a8fddb8..2f95fbcfc 100644 --- a/tests/network/message_ownership.cpp +++ b/tests/network/message_ownership.cpp @@ -133,8 +133,7 @@ TEST_CASE("Native header factories preserve CS and SS serialization sizes") { ark::ss_msg_header ss; CHECK(cs.header_length() == sizeof(ark::msg_id_t) + sizeof(uint32_t) + sizeof(uint8_t)); CHECK(ss.header_length() == cs.header_length() + sizeof(ark::guid_t) + 2 * sizeof(ark::bus_id_t)); - for (ark::msg_header* header : {static_cast(&cs), static_cast(&ss)}) - { + for (ark::msg_header* header : {static_cast(&cs), static_cast(&ss)}) { header->set_message_id(3); header->set_message_length(5); std::unique_ptr created(header->create()); diff --git a/tests/network/net_listener_startup.cpp b/tests/network/net_listener_startup.cpp index 4c7d263e1..4be33368a 100644 --- a/tests/network/net_listener_startup.cpp +++ b/tests/network/net_listener_startup.cpp @@ -18,8 +18,7 @@ #include "../../src/plugins/net/net_service_manager_module_impl.cpp" namespace ark { -struct net_listener_startup_test_access -{ +struct net_listener_startup_test_access { static auto* candidate(net_service_manager_module& module) { auto& impl = static_cast(module); return impl.server_services_.empty() ? nullptr : &impl.server_services_.begin()->second; @@ -27,18 +26,15 @@ struct net_listener_startup_test_access static bool native_started(net_service_manager_module& module) { const auto* entry = candidate(module); - if (!entry) - { + if (!entry) { return false; } auto network = entry->service->get_net(); - if (auto* tcp = dynamic_cast(network.get())) - { + if (auto* tcp = dynamic_cast(network.get())) { return tcp->server_ && tcp->server_->iopool().started() && tcp->server_->iopool().get(0)->get_thread_id() != std::thread::id{}; } - if (auto* rudp = dynamic_cast(network.get())) - { + if (auto* rudp = dynamic_cast(network.get())) { return rudp->server_ && rudp->server_->iopool().started() && rudp->server_->iopool().get(0)->get_thread_id() != std::thread::id{}; } @@ -47,19 +43,16 @@ struct net_listener_startup_test_access static bool worker_initialized(net_service_manager_module& module) { const auto* entry = candidate(module); - if (!entry) - { + if (!entry) { return false; } // operator new may be reached while io_pool::start holds its lifecycle // mutex. Observe the fixture's single lane without reentering started(). auto network = entry->service->get_net(); - if (auto* tcp = dynamic_cast(network.get())) - { + if (auto* tcp = dynamic_cast(network.get())) { return tcp->server_ && tcp->server_->iopool().get(0)->get_thread_id() != std::thread::id{}; } - if (auto* rudp = dynamic_cast(network.get())) - { + if (auto* rudp = dynamic_cast(network.get())) { return rudp->server_ && rudp->server_->iopool().get(0)->get_thread_id() != std::thread::id{}; } return false; @@ -67,12 +60,10 @@ struct net_listener_startup_test_access static std::uint16_t port(net_server_service& service) { auto network = service.get_net(); - if (auto* tcp = dynamic_cast(network.get())) - { + if (auto* tcp = dynamic_cast(network.get())) { return tcp->server_->listen_port(); } - if (auto* rudp = dynamic_cast(network.get())) - { + if (auto* rudp = dynamic_cast(network.get())) { return rudp->server_->listen_port(); } return 0; @@ -89,22 +80,19 @@ std::weak_ptr observed_service; bool failure_child{}; void before_allocation() { - if (fail_after_worker && observed_module && access::worker_initialized(*observed_module)) - { + if (fail_after_worker && observed_module && access::worker_initialized(*observed_module)) { // Keep only a weak observation: the test must not rescue a missing owner. observed_service = access::candidate(*observed_module)->service; fail_after_worker = false; fail_allocations = true; } - if (fail_allocations) - { + if (fail_allocations) { throw std::bad_alloc(); } } void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { ark::app_detail::write_native_stderr(message); ark::app_detail::write_native_stderr("\n"); std::_Exit(2); @@ -112,14 +100,12 @@ void require(bool condition, const char* message) { } void forbidden_cleanup() { - if (failure_child) - { + if (failure_child) { ark::app_detail::write_native_stderr("forbidden Net listener ordinary cleanup\n"); } } -struct fixture_bus final : ark::module_base -{ +struct fixture_bus final : ark::module_base { ark::proc_config proc; ark::reg_center registry; std::string name{"fixture"}; @@ -173,8 +159,7 @@ struct fixture_bus final : ark::module_base } }; -struct fixture_timer final : ark::module_base -{ +struct fixture_timer final : ark::module_base { bool remove_timer(std::uint64_t) override { forbidden_cleanup(); return true; @@ -190,8 +175,7 @@ struct fixture_timer final : ark::module_base } }; -struct fixture_msg final : ark::module_base -{ +struct fixture_msg final : ark::module_base { bool send_def_cs_msg_by_app_type(ark::app_type, ark::msg_id_t, const google::protobuf::Message&) override { return false; } @@ -222,17 +206,13 @@ struct fixture_msg final : ark::module_base } }; -struct consumer_interface : ark::module -{ -}; +struct consumer_interface : ark::module {}; -struct consumer final : ark::module_base -{ +struct consumer final : ark::module_base { ark::net_service_manager_module* network{}; bool init() override { - if (failure_child) - { + if (failure_child) { observed_module = network; fail_after_worker = true; return network->create_server(60000, ark::s_msg_header{}, ark::ss_msg_header{}); @@ -260,8 +240,7 @@ struct consumer final : ark::module_base -{ +struct fixture_plugin final : ark::plugin_base { fixture_bus* bus{}; ark::net_service_manager_module* network{}; @@ -340,12 +319,9 @@ void rejected(ark::proto_type protocol) { asio::ip::tcp::acceptor tcp(context); asio::ip::udp::socket udp(context); const bool stream = protocol == ark::proto_type::tcp; - if (stream) - { + if (stream) { tcp.open(asio::ip::tcp::v4()); - } - else - { + } else { udp.open(asio::ip::udp::v4()); } #if defined(_WIN32) @@ -355,25 +331,19 @@ void rejected(ark::proto_type protocol) { sizeof(exclusive)) == 0, "exclusive fixture endpoint"); #endif - if (stream) - { + if (stream) { tcp.bind({asio::ip::address_v4::loopback(), 0}); tcp.listen(); - } - else - { + } else { udp.bind({asio::ip::address_v4::loopback(), 0}); } plugin.bus->proc.server_ep.set_port(stream ? tcp.local_endpoint().port() : udp.local_endpoint().port()); require(!create(*plugin.network), "occupied listener must return false"); require(!plugin.network->get_inter_net_server() && !access::candidate(*plugin.network), "false candidate removed after ordinary cleanup"); - if (stream) - { + if (stream) { tcp.close(); - } - else - { + } else { udp.close(); } require(create(*plugin.network), "same slot retries after ordinary false"); @@ -392,10 +362,11 @@ void rejected(ark::proto_type protocol) { // Prepare owning call arguments before injection; manager.start is never retried. const std::string directory; const std::unordered_map plugins; - try - { manager.start(0, directory, directory, plugins); } - catch (const std::bad_alloc&) - { caught = true; } + try { + manager.start(0, directory, directory, plugins); + } catch (const std::bad_alloc&) { + caught = true; + } require(caught && fail_allocations && !fail_after_worker, "start did not propagate persistent allocation failure after native workers"); const auto* entry = access::candidate(*plugin.network); @@ -403,8 +374,7 @@ void rejected(ark::proto_type protocol) { require(access::native_started(*plugin.network), "native worker owner lost before runner"); require(!plugin.network->get_inter_net_server() && !plugin.network->get_intra_net_server(), "unpublished candidate escaped getter"); - if (retry_probe) - { + if (retry_probe) { // Separate compatibility child: allow the API's new owning header copies // to test slot rejection, then restore failure for the emergency exit. fail_allocations = false; @@ -421,8 +391,7 @@ void rejected(ark::proto_type protocol) { void* operator new(std::size_t size) { before_allocation(); - if (void* pointer = std::malloc(size ? size : 1)) - { + if (void* pointer = std::malloc(size ? size : 1)) { return pointer; } throw std::bad_alloc(); @@ -449,10 +418,11 @@ void operator delete[](void* pointer, std::size_t) noexcept { } void* operator new(std::size_t size, const std::nothrow_t&) noexcept { - try - { return ::operator new(size); } - catch (...) - { return nullptr; } + try { + return ::operator new(size); + } catch (...) { + return nullptr; + } } void* operator new[](std::size_t size, const std::nothrow_t&) noexcept { @@ -478,10 +448,8 @@ int main(int argc, char** argv) { #endif std::_Exit(86); }); - if (argc == 2 && std::strcmp(argv[1], "normal") == 0) - { - for (const auto protocol : {ark::proto_type::tcp, ark::proto_type::udp}) - { + if (argc == 2 && std::strcmp(argv[1], "normal") == 0) { + for (const auto protocol : {ark::proto_type::tcp, ark::proto_type::udp}) { successful(protocol, false); successful(protocol, true); rejected(protocol); @@ -489,14 +457,11 @@ int main(int argc, char** argv) { std::fputs("Net listener normal controls passed\n", stderr); return 0; } - if (argc == 3 && (std::strcmp(argv[1], "exception") == 0 || std::strcmp(argv[1], "retry") == 0)) - { - if (std::strcmp(argv[2], "tcp") == 0) - { + if (argc == 3 && (std::strcmp(argv[1], "exception") == 0 || std::strcmp(argv[1], "retry") == 0)) { + if (std::strcmp(argv[2], "tcp") == 0) { allocation_failure(ark::proto_type::tcp, std::strcmp(argv[1], "retry") == 0); } - if (std::strcmp(argv[2], "rudp") == 0) - { + if (std::strcmp(argv[2], "rudp") == 0) { allocation_failure(ark::proto_type::udp, std::strcmp(argv[1], "retry") == 0); } } diff --git a/tests/network/rudp.cpp b/tests/network/rudp.cpp index a46afc6ec..ed585043d 100644 --- a/tests/network/rudp.cpp +++ b/tests/network/rudp.cpp @@ -21,8 +21,7 @@ namespace { using namespace std::chrono_literals; -struct rudp_message -{ +struct rudp_message { ark::msg_id_t id; ark::conv_id_t session; std::string body; @@ -32,16 +31,14 @@ struct rudp_message bool compressed; }; -struct rudp_event -{ +struct rudp_event { ark::net_event_type type; ark::conv_id_t session; ark::bus_id_t bus; std::string ip; }; -class rudp_receiver -{ +class rudp_receiver { public: void receive(const ark::net_msg* message, ark::conv_id_t session) { { @@ -52,8 +49,7 @@ class rudp_receiver : std::string{}, message->get_actor_id(), message->get_src_bus(), message->get_dst_bus(), message->get_compress() != 0}); } - if (on_receive) - { + if (on_receive) { on_receive(message, session); } } @@ -104,11 +100,9 @@ std::uint16_t reserve_rudp_port() { template bool await_rudp(predicate_type&& predicate, update_type&& update, std::chrono::milliseconds timeout = 5s) { const auto deadline = std::chrono::steady_clock::now() + timeout; - do - { + do { update(); - if (predicate()) - { + if (predicate()) { return true; } std::this_thread::sleep_for(1ms); @@ -118,8 +112,7 @@ bool await_rudp(predicate_type&& predicate, update_type&& update, std::chrono::m std::string rudp_payload(std::size_t size) { std::string result(size, '\0'); - for (std::size_t index = 0; index < size; ++index) - { + for (std::size_t index = 0; index < size; ++index) { result[index] = static_cast((index * 19 + 37) & 0xff); } return result; @@ -143,13 +136,11 @@ std::shared_ptr rudp_server(rudp_receiver& receiver) { return std::make_shared(&receiver, &rudp_receiver::receive, &rudp_receiver::event); } -class rudp_serialization_header : public ark::s_msg_header -{ +class rudp_serialization_header : public ark::s_msg_header { public: void serialize_to_string(std::string& buffer) override { ark::s_msg_header::serialize_to_string(buffer); - if (auto callback = std::exchange(on_serialize, {})) - { + if (auto callback = std::exchange(on_serialize, {})) { callback(); } } @@ -189,14 +180,12 @@ TEST_CASE_TEMPLATE("RUDP preserves ARK framing and dispatches on Update", header header_type response(*header); response.set_message_id(message->get_msg_id()); response.set_message_length(message->get_msg_length()); - if (!server->send_msg(&response, message->get_msg_length() ? message->get_msg_data() : "", session)) - { + if (!server->send_msg(&response, message->get_msg_length() ? message->get_msg_data() : "", session)) { ++rejected_echoes; } }; const std::vector sizes{0, 1, 23, 511, 1024, header->max_body_size()}; - for (std::size_t index = 0; index < sizes.size(); ++index) - { + for (std::size_t index = 0; index < sizes.size(); ++index) { header_type request(*header); request.set_message_id(static_cast(40 + index)); request.set_message_length(static_cast(sizes[index])); @@ -214,8 +203,7 @@ TEST_CASE_TEMPLATE("RUDP preserves ARK framing and dispatches on Update", header CHECK(rejected_echoes == 0); const auto sent = server_receiver.messages(); const auto echoed = client_receiver.messages(); - for (std::size_t index = 0; index < sizes.size(); ++index) - { + for (std::size_t index = 0; index < sizes.size(); ++index) { CHECK(sent[index].id == 40 + index); CHECK(echoed[index].id == sent[index].id); CHECK(sent[index].body == rudp_payload(sizes[index])); @@ -445,8 +433,7 @@ TEST_CASE("RUDP closes malformed business frames through the Update event path") arknet::rudp_server server; std::atomic rejected = false; server.bind_connect([&](auto& session) { - if (!session->async_send(wire)) - { + if (!session->async_send(wire)) { rejected = true; } }); @@ -482,14 +469,12 @@ TEST_CASE("RUDP rejects an old-session send after reconnect during serialization // Release before either transport is destroyed, including a failed REQUIRE. // The latch itself outlives server callbacks and their joined IO threads. - struct publication_release - { + struct publication_release { std::latch& allowed; bool released{}; void release() { - if (!released) - { + if (!released) { allowed.count_down(); released = true; } @@ -501,8 +486,7 @@ TEST_CASE("RUDP rejects an old-session send after reconnect during serialization } publication{publication_allowed}; server.bind_connect([&, delay_peer_publication](auto& session) { - if (delay_peer_publication) - { + if (delay_peer_publication) { publication_allowed.wait(); } std::lock_guard lock(peer_mutex); @@ -517,8 +501,7 @@ TEST_CASE("RUDP rejects an old-session send after reconnect during serialization REQUIRE(await_rudp( [&] { const auto connected = receiver.event_count(ark::net_event_type::connect) == 1; - if (connected) - { + if (connected) { publication.release(); } // Native ACK precedes bind_connect: client readiness alone does not @@ -539,8 +522,7 @@ TEST_CASE("RUDP rejects an old-session send after reconnect during serialization std::lock_guard lock(peer_mutex); old_peer = peer; } - if (!old_peer) - { + if (!old_peer) { return; } old_peer->stop(); diff --git a/tests/network/tcp_websocket.cpp b/tests/network/tcp_websocket.cpp index eca211a36..671d40b04 100644 --- a/tests/network/tcp_websocket.cpp +++ b/tests/network/tcp_websocket.cpp @@ -28,8 +28,7 @@ namespace { using namespace std::chrono_literals; -struct message -{ +struct message { ark::msg_id_t id; ark::conv_id_t session; std::string body; @@ -38,14 +37,12 @@ struct message ark::bus_id_t destination; }; -struct event -{ +struct event { ark::net_event_type type; ark::conv_id_t session; }; -struct receiver -{ +struct receiver { const std::thread::id dispatch_thread = std::this_thread::get_id(); std::atomic wrong_thread{false}; std::mutex mutex; @@ -56,8 +53,7 @@ struct receiver ark::conv_id_t websocket_reference_session{}; void receive_message(const ark::net_msg* message, ark::conv_id_t session) { - if (std::this_thread::get_id() != dispatch_thread) - { + if (std::this_thread::get_id() != dispatch_thread) { wrong_thread.store(true); } { @@ -67,8 +63,7 @@ struct receiver : std::string(message->get_msg_data(), message->get_msg_length()), message->get_actor_id(), message->get_src_bus(), message->get_dst_bus()}); } - if (on_message) - { + if (on_message) { on_message(session); } } @@ -80,8 +75,7 @@ struct receiver } void on_event(const ark::net_event* event) { - if (std::this_thread::get_id() != dispatch_thread) - { + if (std::this_thread::get_id() != dispatch_thread) { wrong_thread.store(true); } std::lock_guard guard(mutex); @@ -109,11 +103,9 @@ template requires std::invocable bool wait(predicate_type predicate, pump_type pump, std::chrono::milliseconds timeout = 3000ms) { const auto deadline = std::chrono::steady_clock::now() + timeout; - do - { + do { pump(); - if (predicate()) - { + if (predicate()) { return true; } std::this_thread::sleep_for(2ms); @@ -143,12 +135,9 @@ std::string encode_frame(ark::msg_header& header, ark::msg_id_t id, const std::s template std::shared_ptr create_client(receiver& receiver) { - if constexpr (std::is_same_v) - { + if constexpr (std::is_same_v) { return std::make_shared(&receiver, &receiver::on_websocket_message, &receiver::on_event); - } - else - { + } else { return std::make_shared(&receiver, &receiver::receive_message, &receiver::on_event); } } @@ -196,19 +185,16 @@ void reentrant_close() { receiver receiver; auto server = std::make_shared(&receiver, &receiver::receive_message, &receiver::on_event); receiver.on_message = [weak = std::weak_ptr(server)](ark::conv_id_t session) { - if (const auto owner = weak.lock()) - { + if (const auto owner = weak.lock()) { owner->close_session(session); } }; const auto port = available_port(); REQUIRE(server->start_server(std::make_shared(), 11, "127.0.0.1", port, 2, 10, 30000)); transport_type client; - if constexpr (std::is_same_v) - { + if constexpr (std::is_same_v) { client.bind_connect([&] { - if (!arknet::get_last_error()) - { + if (!arknet::get_last_error()) { client.ws_stream().binary(true); } }); @@ -251,11 +237,9 @@ void reject_oversized_frame() { const auto port = available_port(); REQUIRE(server->start_server(std::make_shared(), 11, "127.0.0.1", port, 2, 10, 30000)); transport_type client; - if constexpr (std::is_same_v) - { + if constexpr (std::is_same_v) { client.bind_connect([&] { - if (!arknet::get_last_error()) - { + if (!arknet::get_last_error()) { client.ws_stream().binary(true); } }); @@ -272,8 +256,7 @@ void reject_oversized_frame() { REQUIRE(wait([&] { return !client.is_started(); })); } -class reconnect_during_serialization : public ark::s_msg_header -{ +class reconnect_during_serialization : public ark::s_msg_header { public: explicit reconnect_during_serialization(std::function reconnect) : reconnect_(std::move(reconnect)) { @@ -298,8 +281,7 @@ void stale_session_cannot_send_or_close_replacement() { std::atomic connections{0}; transport_type server(1024, 1024 * 1024, 2); server.bind_connect([&](auto& session) { - if constexpr (std::is_same_v) - { + if constexpr (std::is_same_v) { session->ws_stream().binary(true); } std::lock_guard guard(peer_mutex); @@ -451,8 +433,7 @@ TEST_CASE("WebSocket server sends binary ARK frames") { std::string reply; arknet::ws_client client; client.bind_connect([&] { - if (!arknet::get_last_error()) - { + if (!arknet::get_last_error()) { client.ws_stream().binary(true); } }); diff --git a/tests/osssdk/entry.cpp b/tests/osssdk/entry.cpp index d32165f9a..535df85c2 100644 --- a/tests/osssdk/entry.cpp +++ b/tests/osssdk/entry.cpp @@ -10,8 +10,7 @@ namespace { void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { std::cerr << message << std::endl; std::_Exit(1); } diff --git a/tests/osssdk/entry_factory.cpp b/tests/osssdk/entry_factory.cpp index b51dad2e7..d889805e2 100644 --- a/tests/osssdk/entry_factory.cpp +++ b/tests/osssdk/entry_factory.cpp @@ -11,8 +11,7 @@ unsigned created{}; unsigned destroyed{}; unsigned updated{}; -class entry_oss_sdk final : public ark::module_base -{ +class entry_oss_sdk final : public ark::module_base { public: entry_oss_sdk() { ++created; @@ -43,8 +42,7 @@ std::unique_ptr make_oss_sdk_module() { } // namespace ark::detail ARK_EXPORT_FUNC unsigned oss_sdk_entry_events(unsigned event) { - switch (event) - { + switch (event) { case 0: return created; case 1: diff --git a/tests/osssdk/exports.cpp b/tests/osssdk/exports.cpp index 118770b0b..649697b85 100644 --- a/tests/osssdk/exports.cpp +++ b/tests/osssdk/exports.cpp @@ -8,8 +8,7 @@ namespace { void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { std::cerr << message << std::endl; std::_Exit(1); } diff --git a/tests/proto/naming.cpp b/tests/proto/naming.cpp index cdbf2c32f..963786892 100644 --- a/tests/proto/naming.cpp +++ b/tests/proto/naming.cpp @@ -18,15 +18,13 @@ bool lower_snake_case(const std::string& name) { void check_enum(const google::protobuf::EnumDescriptorProto& definition) { DOCTEST_INFO(definition.name()); DOCTEST_CHECK(lower_snake_case(definition.name())); - for (const auto& value : definition.value()) - { + for (const auto& value : definition.value()) { DOCTEST_INFO(value.name()); DOCTEST_CHECK(lower_snake_case(value.name())); } } -struct counts -{ +struct counts { unsigned messages{}; unsigned fields{}; unsigned map_entries{}; @@ -35,8 +33,7 @@ struct counts void check_message(const google::protobuf::DescriptorProto& definition, counts& checked) { // Map entry type names belong to protoc, not hand-written schema declarations. - if (definition.options().map_entry()) - { + if (definition.options().map_entry()) { ++checked.map_entries; return; } @@ -46,33 +43,27 @@ void check_message(const google::protobuf::DescriptorProto& definition, counts& std::set synthetic_oneofs; static const std::set retired_fields{ "selfid", "self_serverid", "target_serverid", "gate_serverid", "nreqid", "logid"}; - for (const auto& field : definition.field()) - { + for (const auto& field : definition.field()) { DOCTEST_INFO(field.name()); DOCTEST_CHECK(lower_snake_case(field.name())); DOCTEST_CHECK_FALSE(retired_fields.contains(field.name())); ++checked.fields; - if (field.proto3_optional()) - { + if (field.proto3_optional()) { synthetic_oneofs.insert(field.oneof_index()); } } - for (int index = 0; index < definition.oneof_decl_size(); ++index) - { - if (synthetic_oneofs.contains(index)) - { + for (int index = 0; index < definition.oneof_decl_size(); ++index) { + if (synthetic_oneofs.contains(index)) { ++checked.optional_oneofs; continue; } DOCTEST_INFO(definition.oneof_decl(index).name()); DOCTEST_CHECK(lower_snake_case(definition.oneof_decl(index).name())); } - for (const auto& nested : definition.nested_type()) - { + for (const auto& nested : definition.nested_type()) { check_message(nested, checked); } - for (const auto& enumeration : definition.enum_type()) - { + for (const auto& enumeration : definition.enum_type()) { check_enum(enumeration); } } @@ -92,19 +83,16 @@ DOCTEST_TEST_CASE("Protoc descriptors enforce source snake-case names across eve DOCTEST_REQUIRE(descriptors.file_size() == ARK_PROTO_SOURCE_COUNT); counts checked; std::set packages; - for (const auto& file : descriptors.file()) - { + for (const auto& file : descriptors.file()) { DOCTEST_INFO(file.name()); const auto path = std::filesystem::path(file.name()); DOCTEST_CHECK(path.extension() == ".proto"); DOCTEST_CHECK(lower_snake_case(path.stem().string())); packages.insert(file.package()); - for (const auto& message : file.message_type()) - { + for (const auto& message : file.message_type()) { check_message(message, checked); } - for (const auto& enumeration : file.enum_type()) - { + for (const auto& enumeration : file.enum_type()) { check_enum(enumeration); } } @@ -119,8 +107,7 @@ DOCTEST_TEST_CASE("Protoc descriptors enforce source snake-case names across eve DOCTEST_TEST_CASE("Renamed ID descriptors keep original field numbers types and JSON spelling") { using field_type = google::protobuf::FieldDescriptorProto; - struct preserved_field - { + struct preserved_field { const char* package; const char* message; const char* name; @@ -141,26 +128,19 @@ DOCTEST_TEST_CASE("Renamed ID descriptors keep original field numbers types and {"ark.protobuf", "mysql_parameters", "request_id", "nreqid", 6, field_type::TYPE_INT64}, {"osslog", "login", "log_id", "logid", 1, field_type::TYPE_STRING}}; const auto descriptors = read_descriptors(); - for (const auto& preserved : expected) - { + for (const auto& preserved : expected) { DOCTEST_INFO(preserved.package << "." << preserved.message << "." << preserved.name); const field_type* found = nullptr; - for (const auto& file : descriptors.file()) - { - if (file.package() != preserved.package) - { + for (const auto& file : descriptors.file()) { + if (file.package() != preserved.package) { continue; } - for (const auto& message : file.message_type()) - { - if (message.name() != preserved.message) - { + for (const auto& message : file.message_type()) { + if (message.name() != preserved.message) { continue; } - for (const auto& field : message.field()) - { - if (field.name() == preserved.name) - { + for (const auto& field : message.field()) { + if (field.name() == preserved.name) { found = &field; } } diff --git a/tests/server/construction.cpp b/tests/server/construction.cpp index a4f32edba..a11e43142 100644 --- a/tests/server/construction.cpp +++ b/tests/server/construction.cpp @@ -18,8 +18,7 @@ static_assert(std::same_asget_name()); bool rejected = false; - try - { owner.install(); } - catch (const std::runtime_error&) - { rejected = true; } + try { + owner.install(); + } catch (const std::runtime_error&) { + rejected = true; + } require( rejected && manager.find_module() == instance, "Duplicate install replaced the owned module"); owner.uninstall(); diff --git a/tests/server/entry.cpp b/tests/server/entry.cpp index 4c2f324fa..6c6785d84 100644 --- a/tests/server/entry.cpp +++ b/tests/server/entry.cpp @@ -11,8 +11,7 @@ namespace { void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { std::cerr << message << std::endl; std::_Exit(1); } diff --git a/tests/server/entry_factory.cpp b/tests/server/entry_factory.cpp index 0fdb9769c..0b64eb8db 100644 --- a/tests/server/entry_factory.cpp +++ b/tests/server/entry_factory.cpp @@ -10,8 +10,7 @@ unsigned created{}; unsigned destroyed{}; unsigned updated{}; -class entry_login final : public ark::module_base -{ +class entry_login final : public ark::module_base { public: entry_login() { ++created; @@ -38,8 +37,7 @@ std::unique_ptr make_login_net_module() { } // namespace ark::detail ARK_EXPORT_FUNC unsigned server_entry_events(unsigned event) { - switch (event) - { + switch (event) { case 0: return created; case 1: diff --git a/tests/server/exports.cpp b/tests/server/exports.cpp index 58b4e45ce..5f55377c6 100644 --- a/tests/server/exports.cpp +++ b/tests/server/exports.cpp @@ -8,8 +8,7 @@ namespace { void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { std::cerr << message << std::endl; std::_Exit(1); } diff --git a/tests/server/game_initialization.cpp b/tests/server/game_initialization.cpp index b7f85c8f3..5bb417837 100644 --- a/tests/server/game_initialization.cpp +++ b/tests/server/game_initialization.cpp @@ -27,8 +27,7 @@ namespace { // Control only listener creation. Kernel and every metadata provider below are // production implementations; the separate DSO suite owns real loopback IO. -class listener_probe final : public ark::module_base -{ +class listener_probe final : public ark::module_base { public: unsigned create_calls{}; @@ -78,8 +77,7 @@ class listener_probe final : public ark::module_base game_provider_keys() { typeid(ark::class_meta_module).name()}; } -class quiet_logger -{ +class quiet_logger { public: quiet_logger() : previous_(ark::logger::instance()) { @@ -128,8 +125,7 @@ class quiet_logger ark::logger log_; }; -class game_world -{ +class game_world { public: explicit game_world(bool with_player = true) : previous_directory_(std::filesystem::current_path()) @@ -164,8 +160,7 @@ class game_world } ~game_world() { - if (providers_initialized_) - { + if (providers_initialized_) { kernel_.pre_shut(); maps_.shut(); config_.shut(); @@ -186,8 +181,7 @@ class game_world REQUIRE(metadata.init()); providers_initialized_ = true; REQUIRE(config_.post_init()); - if (kernel_post_init_first) - { + if (kernel_post_init_first) { post_initialize_kernel(); } } @@ -233,8 +227,7 @@ class game_world } // namespace TEST_CASE("Game init precedes Kernel initialization without registering callbacks") { - for (const bool kernel_post_init_first : {false, true}) - { + for (const bool kernel_post_init_first : {false, true}) { CAPTURE(kernel_post_init_first); game_world world; INFO("Fixture directory: " << world.runtime_directory().string()); @@ -248,8 +241,7 @@ TEST_CASE("Game init precedes Kernel initialization without registering callback CHECK(world.player_online_calls() == 0); CHECK_FALSE(world.game->post_init()); // Deliberate listener failure after registration. CHECK(world.network.create_calls == 1); - if (!kernel_post_init_first) - { + if (!kernel_post_init_first) { world.post_initialize_kernel(); } REQUIRE(world.metadata.do_class_event( @@ -271,8 +263,7 @@ TEST_CASE("Game missing Player metadata fails before registering callbacks or cr TEST_CASE("Game factory rejects each missing provider before any startup hook") { quiet_logger log; const auto keys = game_provider_keys(); - for (const auto& missing : keys) - { + for (const auto& missing : keys) { CAPTURE(missing); ark::plugin_manager manager; auto game = ark::detail::make_game_net_module(); @@ -286,10 +277,8 @@ TEST_CASE("Game factory rejects each missing provider before any startup hook") provider_hook_probe observer; REQUIRE(manager.add_module("!independent-startup-observer", &observer)); std::vector providers(keys.size()); - for (size_t i = 0; i < keys.size(); ++i) - { - if (keys[i] != missing) - { + for (size_t i = 0; i < keys.size(); ++i) { + if (keys[i] != missing) { REQUIRE(manager.add_module(keys[i], &providers[i])); } } @@ -299,8 +288,7 @@ TEST_CASE("Game factory rejects each missing provider before any startup hook") CHECK(std::string(manager.get_startup_call().phase.data()) == "dependencies"); CHECK(observer.init_calls == 0); CHECK(observer.later_calls == 0); - for (const auto& provider : providers) - { + for (const auto& provider : providers) { CHECK(provider.init_calls == 0); CHECK(provider.later_calls == 0); } @@ -317,14 +305,12 @@ TEST_CASE("Game factory orders every declared provider before its init hook") { REQUIRE(manager.add_module("!game-consumer", game.get())); const auto keys = game_provider_keys(); std::vector providers(keys.size()); - for (size_t i = keys.size(); i-- > 0;) - { + for (size_t i = keys.size(); i-- > 0;) { REQUIRE(manager.add_module(keys[i], &providers[i])); } CHECK_FALSE(manager.start(0, {}, {}, {})); CHECK(manager.get_startup_failure() == "init: !game-consumer"); - for (const auto& provider : providers) - { + for (const auto& provider : providers) { CHECK(provider.init_calls == 1); CHECK(provider.later_calls == 0); } diff --git a/tests/server/launcher.cpp b/tests/server/launcher.cpp index 28c922ec5..31694e97e 100644 --- a/tests/server/launcher.cpp +++ b/tests/server/launcher.cpp @@ -21,35 +21,29 @@ namespace { using namespace std::chrono_literals; void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { throw std::runtime_error(message); } } -struct socket_owner -{ +struct socket_owner { int value = ::socket(AF_INET, SOCK_STREAM, 0); ~socket_owner() { - if (value >= 0) - { + if (value >= 0) { ::close(value); } } }; -struct child_owner -{ +struct child_owner { pid_t pid = -1; ~child_owner() { - if (pid > 0) - { + if (pid > 0) { // Only this helper's unreaped child is eligible for cleanup. ::kill(pid, SIGKILL); - while (::waitpid(pid, nullptr, 0) < 0 && errno == EINTR) - { + while (::waitpid(pid, nullptr, 0) < 0 && errno == EINTR) { } } } @@ -67,19 +61,16 @@ int connect_to(int socket, unsigned short port) { require(socket >= 0, "socket creation failed"); require(::fcntl(socket, F_SETFL, O_NONBLOCK) == 0, "nonblocking socket setup failed"); const auto endpoint = address(port); - if (::connect(socket, reinterpret_cast(&endpoint), sizeof(endpoint)) == 0) - { + if (::connect(socket, reinterpret_cast(&endpoint), sizeof(endpoint)) == 0) { return 0; } - if (errno != EINPROGRESS) - { + if (errno != EINPROGRESS) { return errno; } pollfd pending{socket, POLLOUT, 0}; const auto ready = ::poll(&pending, 1, 100); require(ready >= 0, "connection poll failed"); - if (ready == 0) - { + if (ready == 0) { return ETIMEDOUT; } int error = 0; @@ -97,8 +88,7 @@ std::string read_log(const std::filesystem::path& path) { int main(int argc, char** argv) { std::filesystem::path child_log; int observed_status = -1; - try - { + try { require(argc == 5 || argc == 7, "Expected launcher, plugin directory, source root, fresh runtime directory and optional role/scenario"); const std::string role = argc == 7 ? argv[5] : "login"; @@ -134,19 +124,15 @@ int main(int argc, char** argv) { "Ephemeral loopback port lookup failed"); port = ntohs(allocated.sin_port); } - if (scenario == "occupied") - { + if (scenario == "occupied") { require(::listen(reservation.value, 1) == 0, "Owned collision listener could not start"); - } - else - { + } else { ::close(reservation.value); reservation.value = -1; } // Healthy startup releases the ephemeral reservation before the launcher // binds. The collision scenario retains only this helper's own listener. - if (with_kernel) - { + if (with_kernel) { std::filesystem::create_directories(runtime / "resource/meta"); std::ofstream schema(runtime / "resource/meta/entity_schema.json"); schema.exceptions(std::ios::failbit | std::ios::badbit); @@ -161,8 +147,7 @@ int main(int argc, char** argv) { << "[[plugins]]\nname = 'ark_utility_plugin'\nconfig = ''\n" << "[[plugins]]\nname = 'ark_bus_plugin'\nconfig = 'bus.toml'\n" << "[[plugins]]\nname = 'ark_net_plugin'\nconfig = ''\n"; - if (with_kernel) - { + if (with_kernel) { manifest << "[[plugins]]\nname = 'ark_kernel_plugin'\nconfig = ''\n"; } manifest << "[[plugins]]\nname = 'ark_" << role << "_plugin'\nconfig = ''\n"; @@ -179,15 +164,12 @@ int main(int argc, char** argv) { child_owner child; child.pid = ::fork(); require(child.pid >= 0, "fork failed"); - if (child.pid == 0) - { - if (::chdir(runtime.c_str()) != 0) - { + if (child.pid == 0) { + if (::chdir(runtime.c_str()) != 0) { std::_Exit(125); } const auto output = ::open(log_path.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0600); - if (output < 0 || ::dup2(output, STDOUT_FILENO) < 0 || ::dup2(output, STDERR_FILENO) < 0) - { + if (output < 0 || ::dup2(output, STDOUT_FILENO) < 0 || ::dup2(output, STDERR_FILENO) < 0) { std::_Exit(125); } ::close(output); @@ -196,12 +178,10 @@ int main(int argc, char** argv) { std::_Exit(126); } const auto startup_deadline = std::chrono::steady_clock::now() + 10s; - for (;;) - { + for (;;) { int status = 0; const auto waited = ::waitpid(child.pid, &status, WNOHANG); - if (waited == child.pid) - { + if (waited == child.pid) { observed_status = status; child.pid = -1; require(scenario == "occupied", "Launcher exited before readiness"); @@ -221,8 +201,7 @@ int main(int argc, char** argv) { return 0; } require(waited == 0, "Launcher startup wait failed"); - if (read_log(log_path).find("Start net server successful") != std::string::npos) - { + if (read_log(log_path).find("Start net server successful") != std::string::npos) { require(scenario == "healthy", "Role accepted an occupied endpoint"); break; } @@ -242,12 +221,10 @@ int main(int argc, char** argv) { // process before replying to its FIN would wait for its native deadline. ::shutdown(peer.value, SHUT_WR); int status = 0; - for (;;) - { + for (;;) { const auto waited = ::waitpid(child.pid, &status, WNOHANG); require(waited >= 0, "Launcher wait failed"); - if (waited == child.pid) - { + if (waited == child.pid) { child.pid = -1; break; } @@ -267,25 +244,18 @@ int main(int argc, char** argv) { : ": actual Utility/Bus/Net/role DSOs: ") << "loopback connection, signal shutdown, peer closure, " "listener refusal and exit 0 passed; no business handler claimed\n"; - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { std::cerr << error.what() << '\n'; - if (observed_status >= 0) - { - if (WIFSIGNALED(observed_status)) - { + if (observed_status >= 0) { + if (WIFSIGNALED(observed_status)) { std::cerr << "Child terminated by signal " << WTERMSIG(observed_status) << '\n'; - } - else if (WIFEXITED(observed_status)) - { + } else if (WIFEXITED(observed_status)) { std::cerr << "Child exit code " << WEXITSTATUS(observed_status) << '\n'; } } std::ifstream diagnostic(child_log, std::ios::binary | std::ios::ate); const auto end = diagnostic.tellg(); - if (end > 0) - { + if (end > 0) { const auto count = end > 16384 ? std::streamoff{16384} : std::streamoff{end}; diagnostic.seekg(end - count); std::string tail(static_cast(count), '\0'); diff --git a/tests/server/registration.cpp b/tests/server/registration.cpp index d7e060b99..e87fc9a91 100644 --- a/tests/server/registration.cpp +++ b/tests/server/registration.cpp @@ -16,8 +16,7 @@ unsigned created{}; unsigned destroyed{}; unsigned updated{}; -class counted_login final : public ark::module_base -{ +class counted_login final : public ark::module_base { public: counted_login() { ++created; @@ -34,18 +33,18 @@ class counted_login final : public ark::module_base }; void require(bool condition, const char* message) { - if (!condition) - { + if (!condition) { std::cerr << message << std::endl; std::_Exit(1); } } bool rejects(ark::login_plugin& owner) { - try - { owner.install(); } - catch (const std::runtime_error&) - { return true; } + try { + owner.install(); + } catch (const std::runtime_error&) { + return true; + } return false; } diff --git a/tests/server/startup_checks.hpp b/tests/server/startup_checks.hpp index 7ce4afec2..ae32b6be9 100644 --- a/tests/server/startup_checks.hpp +++ b/tests/server/startup_checks.hpp @@ -14,8 +14,7 @@ namespace { void require_startup(bool condition, const char* message) { - if (!condition) - { + if (!condition) { throw std::runtime_error(message); } } @@ -23,8 +22,7 @@ void require_startup(bool condition, const char* message) { // These providers control only startup outcomes. The role factory, public // assembly and manager lifecycle under test are the production implementations. template -class startup_provider : public ark::module_base -{ +class startup_provider : public ark::module_base { public: std::vector get_dependencies() const override { return dependencies; @@ -60,8 +58,7 @@ class startup_provider : public ark::module_base const bool* dependent_stopped{}; }; -class startup_bus final : public startup_provider -{ +class startup_bus final : public startup_provider { public: const std::string get_app_whole_name(ark::bus_id_t) override { return "startup-test"; @@ -117,8 +114,7 @@ class startup_bus final : public startup_provider ark::reg_center registry_{}; }; -class startup_service final : public ark::net_server_service -{ +class startup_service final : public ark::net_server_service { public: bool start(std::shared_ptr, ark::bus_id_t, const ark::endpoint&, uint8_t, uint32_t, const size_t) override { @@ -153,8 +149,7 @@ class startup_service final : public ark::net_server_service } }; -class startup_net final : public startup_provider -{ +class startup_net final : public startup_provider { public: bool created = true; unsigned create_calls{}; @@ -219,16 +214,13 @@ void check_startup(bool with_bus, bool with_net, bool created, bool has_service, startup_bus bus; startup_net net; net.created = created; - if (!has_service) - { + if (!has_service) { net.service.reset(); } - if (with_bus) - { + if (with_bus) { require_startup(manager.add_module(typeid(ark::bus_module).name(), &bus), "Bus fixture registration failed"); } - if (with_net) - { + if (with_net) { require_startup(manager.add_module(typeid(ark::net_service_manager_module).name(), &net), "Net fixture registration failed"); } @@ -246,8 +238,7 @@ void check_startup(bool with_bus, bool with_net, bool created, bool has_service, const bool expected_start = expected_init && created && has_service; require_startup(manager.start(42, {}, {}, {}) == expected_start, "Real role startup result was lost"); const auto failure = manager.get_startup_failure(); - if (rejected_dependencies) - { + if (rejected_dependencies) { require_startup(failure == std::string("dependencies: ") + typeid(server_module).name() + " requires missing module '" + *missing + "'", "Manager did not reject the missing declared role provider"); @@ -265,18 +256,15 @@ void check_startup(bool with_bus, bool with_net, bool created, bool has_service, require_startup( net.late_calls == (expected_start ? 1u : 0u), "Manager continued to pre_update after startup failure"); owner.uninstall(); - if (with_bus) - { + if (with_bus) { manager.remove_module(typeid(ark::bus_module).name()); } - if (with_net) - { + if (with_net) { manager.remove_module(typeid(ark::net_service_manager_module).name()); } } -class startup_dependent final : public ark::module -{ +class startup_dependent final : public ark::module { public: startup_dependent(startup_bus& bus, startup_net& net) : bus_(bus) @@ -361,8 +349,7 @@ void check_role_startup(const std::string& role) { const bool game = role == "ark_game_plugin"; const bool declared = role == "ark_login_plugin" || role == "ark_master_plugin" || role == "ark_proxy_plugin" || role == "ark_world_plugin" || role == "ark_dir_plugin" || role == "ark_router_plugin"; - if (declared) - { + if (declared) { check_declared_role_order(); require_startup( make_server_module()->get_dependencies() == std::vector{typeid(ark::bus_module).name(), @@ -372,14 +359,11 @@ void check_role_startup(const std::string& role) { check_startup(false, false, true, true, game); check_startup(false, true, true, true, game); check_startup(true, false, true, true, game); - if (game) - { + if (game) { // Game validates Kernel in init and registers its callbacks in post_init. // This dependency fixture does not simulate Kernel. check_startup(true, true, true, true, true); - } - else - { + } else { check_startup(true, true, false, true, false); check_startup(true, true, true, false, false); check_startup(true, true, true, true, false); diff --git a/tests/test_datetime.cpp b/tests/test_datetime.cpp index ae947b8f2..c469a7c13 100644 --- a/tests/test_datetime.cpp +++ b/tests/test_datetime.cpp @@ -300,12 +300,9 @@ void test_week_of_year(int y, int m, int d) { TEST_CASE("return week_of_year", "int GetWeekOfYear(int firstDayOfWeek = MONDAY) const") { int days_of_month_table[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - for (int y = 2017; y <= 2019; y++) - { - for (int i = 1; i <= 12; i++) - { - for (int j = 1; j <= days_of_month_table[i]; j++) - { + for (int y = 2017; y <= 2019; y++) { + for (int i = 1; i <= 12; i++) { + for (int j = 1; j <= days_of_month_table[i]; j++) { test_week_of_year(y, i, j); } } @@ -339,12 +336,9 @@ TEST_CASE("return hour of day in am/pm format", "int GethourAMPM() const") { int tzd = 8; p->tm_hour -= tzd; - if (p->tm_hour < 1) - { + if (p->tm_hour < 1) { p->tm_hour = 12; - } - else if (p->tm_hour > 12) - { + } else if (p->tm_hour > 12) { p->tm_hour -= 12; } REQUIRE(date_time_instance.get_hour() == p->tm_hour); @@ -360,8 +354,7 @@ TEST_CASE("return hour of day whether in am", "bool IsAM() const") { int tzd = 8; p->tm_hour -= tzd; bool isam = false; - if (p->tm_hour < 12) - { + if (p->tm_hour < 12) { isam = true; } REQUIRE(date_time_instance.is_am() == isam); @@ -377,8 +370,7 @@ TEST_CASE("return hour of day whether in pm", "bool IsPM() const") { int tzd = 8; p->tm_hour -= tzd; bool ispm = false; - if (p->tm_hour >= 12) - { + if (p->tm_hour >= 12) { ispm = true; } REQUIRE(date_time_instance.is_pm() == ispm); @@ -468,8 +460,7 @@ TEST_CASE("return days of month by parameter year and month", "static int GetDay auto year = date_time_provider.get_year(); auto month = date_time_provider.get_month(); int days_of_month_table[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - if (month == 2 && date_time_provider.is_leap_year()) - { + if (month == 2 && date_time_provider.is_leap_year()) { days_of_month_table[2] = 29; } REQUIRE(ark::date_time::get_days_of_month(year, month) == days_of_month_table[month]); diff --git a/tests/test_random.cpp b/tests/test_random.cpp index c22e8e778..56980941b 100644 --- a/tests/test_random.cpp +++ b/tests/test_random.cpp @@ -28,10 +28,8 @@ using namespace ark; template void print_vec(stream_type& os, const std::vector& vec) { os << "[ "; - for (size_t i = 0; i < vec.size(); ++i) - { - if (i > 0) - { + for (size_t i = 0; i < vec.size(); ++i) { + if (i > 0) { os << ", "; } @@ -48,8 +46,7 @@ TEST_CASE("xoroshiro128_starstar", "[xoroshiro128_starstar]") { uint32_t checked1[] = {0x6baaab3a, 0x9385fdbb, 0x99ae85fe, 0x88e2358c, 0x6592b0ce, 0x20eadc84, 0x6a8d80b7, 0xa676abb7, 0x726ef19a, 0xd4e33183}; - for (size_t i = 0; i < sizeof(checked1) / sizeof(checked1[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked1) / sizeof(checked1[0]); ++i) { REQUIRE(gen1.random() == checked1[i]); } @@ -57,8 +54,7 @@ TEST_CASE("xoroshiro128_starstar", "[xoroshiro128_starstar]") { uint32_t checked2[] = {0xb40ef1a3, 0xeaf5f926, 0xdaedd531, 0xd75a0342, 0xf5cd493d, 0x4081f259, 0x92a08a09, 0x8e7856ff, 0x3eecdb2, 0x34cd820c}; - for (size_t i = 0; i < sizeof(checked2) / sizeof(checked2[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked2) / sizeof(checked2[0]); ++i) { REQUIRE(gen1.random() == checked2[i]); } @@ -69,8 +65,7 @@ TEST_CASE("xoroshiro128_starstar", "[xoroshiro128_starstar]") { uint32_t checked3[] = {0x483919e4, 0xa90f4ce8, 0xe55d1499, 0x17c2185e, 0xdb11c3f7, 0x63557f98, 0xc7ad6874, 0x4a4a45ca, 0x74dec471, 0xf7e82f2a}; - for (size_t i = 0; i < sizeof(checked3) / sizeof(checked3[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked3) / sizeof(checked3[0]); ++i) { REQUIRE(gen1.random() == checked3[i]); } @@ -78,14 +73,12 @@ TEST_CASE("xoroshiro128_starstar", "[xoroshiro128_starstar]") { uint32_t checked4[] = {0xf30187c0, 0xe533ff68, 0x628920df, 0xa998b9e7, 0xcac83081, 0xe23e175b, 0x8aef7f7a, 0x43e56ba2, 0x59dc108b, 0x35b5536c}; - for (size_t i = 0; i < sizeof(checked4) / sizeof(checked4[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked4) / sizeof(checked4[0]); ++i) { REQUIRE(gen1.random() == checked4[i]); } std::vector shuffle_arr; - for (int i = 0; i < 10; ++i) - { + for (int i = 0; i < 10; ++i) { shuffle_arr.push_back(gen1.random()); } gen1.shuffle(shuffle_arr.begin(), shuffle_arr.end()); @@ -99,8 +92,7 @@ TEST_CASE("xoroshiro128_plus", "[xoroshiro128_plus]") { uint32_t checked1[] = {0xf1c950fb, 0x3c9b4647, 0x212ab3fb, 0x9930ad20, 0xe891a595, 0x5f3d9875, 0x264dd138, 0xb23b09e7, 0xb351ccd6, 0xf6342d85}; - for (size_t i = 0; i < sizeof(checked1) / sizeof(checked1[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked1) / sizeof(checked1[0]); ++i) { REQUIRE(gen1.random() == checked1[i]); } @@ -108,8 +100,7 @@ TEST_CASE("xoroshiro128_plus", "[xoroshiro128_plus]") { uint32_t checked2[] = {0x65981904, 0x2d406a8b, 0xf722cc27, 0xd93f4e0, 0xc8c324e, 0x47adc6fc, 0x2e331b89, 0x2de59177, 0x68298f16, 0x3c1f786}; - for (size_t i = 0; i < sizeof(checked2) / sizeof(checked2[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked2) / sizeof(checked2[0]); ++i) { REQUIRE(gen1.random() == checked2[i]); } @@ -120,8 +111,7 @@ TEST_CASE("xoroshiro128_plus", "[xoroshiro128_plus]") { uint32_t checked3[] = {0x6ba5dc24, 0x1f1d11fa, 0xfa4932ff, 0x86a802af, 0x784c234, 0xbabe3a02, 0x77ad7d11, 0x7ebe938, 0x44211069, 0x2a5ba899}; - for (size_t i = 0; i < sizeof(checked3) / sizeof(checked3[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked3) / sizeof(checked3[0]); ++i) { REQUIRE(gen1.random() == checked3[i]); } @@ -129,14 +119,12 @@ TEST_CASE("xoroshiro128_plus", "[xoroshiro128_plus]") { uint32_t checked4[] = {0x4956e25b, 0x1637a896, 0xc303f2ef, 0x9f3f6ac7, 0x8048281d, 0xfd181cdb, 0xd50c6ccb, 0xa1e5dc16, 0xe2e6feed, 0xe8901128}; - for (size_t i = 0; i < sizeof(checked4) / sizeof(checked4[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked4) / sizeof(checked4[0]); ++i) { REQUIRE(gen1.random() == checked4[i]); } std::vector shuffle_arr; - for (int i = 0; i < 10; ++i) - { + for (int i = 0; i < 10; ++i) { shuffle_arr.push_back(gen1.random()); } gen1.shuffle(shuffle_arr.begin(), shuffle_arr.end()); @@ -151,8 +139,7 @@ TEST_CASE("xoshiro256_starstar", "[xoshiro256_starstar]") { 0x5c35ba435d92ab9b, 0x45202e3b4085a2cc, 0xa1e9410f7f528e4e, 0x48eb35365566f0b2, 0x90412e6e9ae131c3, 0xba4a1df61ca0b237}; - for (size_t i = 0; i < sizeof(checked1) / sizeof(checked1[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked1) / sizeof(checked1[0]); ++i) { REQUIRE(gen1.random() == checked1[i]); } @@ -161,8 +148,7 @@ TEST_CASE("xoshiro256_starstar", "[xoshiro256_starstar]") { 0x9d6eaac62ce6a4f4, 0x8b2cb439dc19fadd, 0xb749c288597ceac4, 0x92da83e146fdff1d, 0x110d38c051cededc, 0xadab1aacca67bd98}; - for (size_t i = 0; i < sizeof(checked2) / sizeof(checked2[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked2) / sizeof(checked2[0]); ++i) { REQUIRE(gen1.random() == checked2[i]); } @@ -171,8 +157,7 @@ TEST_CASE("xoshiro256_starstar", "[xoshiro256_starstar]") { 0x8e4c39858e961d77, 0x54ef99ad7133b336, 0x507e39520e592971, 0xf17538afb5568bf2, 0x9b12bf7bc0ad1cb, 0xe30b952ddb0edc22}; - for (size_t i = 0; i < sizeof(checked3) / sizeof(checked3[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked3) / sizeof(checked3[0]); ++i) { REQUIRE(gen1.random() == checked3[i]); } @@ -184,8 +169,7 @@ TEST_CASE("xoshiro256_starstar", "[xoshiro256_starstar]") { 0xa369742bfe107109, 0xa10057c6cbaaf5b7, 0xed9d205bdc0671c4, 0x36379ae97a7e84fc, 0x68a4d0807b200c28, 0x1178895e2d328ef3}; - for (size_t i = 0; i < sizeof(checked4) / sizeof(checked4[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked4) / sizeof(checked4[0]); ++i) { REQUIRE(gen1.random() == checked4[i]); } @@ -194,8 +178,7 @@ TEST_CASE("xoshiro256_starstar", "[xoshiro256_starstar]") { 0x49c783132a986f0f, 0x228581842db7c171, 0x575b41c3f6bafa53, 0xd54e667c5bdc8331, 0xd16f385b2194a5ee, 0xd35320c4a01add19}; - for (size_t i = 0; i < sizeof(checked5) / sizeof(checked5[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked5) / sizeof(checked5[0]); ++i) { REQUIRE(gen1.random() == checked5[i]); } @@ -204,14 +187,12 @@ TEST_CASE("xoshiro256_starstar", "[xoshiro256_starstar]") { 0xcbe33255433c267a, 0x1aeb5a580f8b97f7, 0xee0b16ebb05cc830, 0x1951fff956477d9e, 0xd586fc5de6068234, 0xb77c43707de92854}; - for (size_t i = 0; i < sizeof(checked6) / sizeof(checked6[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked6) / sizeof(checked6[0]); ++i) { REQUIRE(gen1.random() == checked6[i]); } std::vector shuffle_arr; - for (int i = 0; i < 10; ++i) - { + for (int i = 0; i < 10; ++i) { shuffle_arr.push_back(gen1.random()); } gen1.shuffle(shuffle_arr.begin(), shuffle_arr.end()); @@ -226,8 +207,7 @@ TEST_CASE("xoshiro256_plus", "[xoshiro256_plus]") { 0xb55425c32b032ae, 0x4f5b510e66ed35c3, 0x86364d228b55294e, 0x15fee24568b9f2e4, 0x79172607cb7639c8, 0x380558a4c62a5df3}; - for (size_t i = 0; i < sizeof(checked1) / sizeof(checked1[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked1) / sizeof(checked1[0]); ++i) { REQUIRE(gen1.random() == checked1[i]); } @@ -236,8 +216,7 @@ TEST_CASE("xoshiro256_plus", "[xoshiro256_plus]") { 0x532d4519bc355dff, 0x4fd9664f92848fd0, 0xe871531860e04f51, 0x9f66375cd3511195, 0xedb2c3bd1fad482d, 0xabd051255c4a95a4}; - for (size_t i = 0; i < sizeof(checked2) / sizeof(checked2[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked2) / sizeof(checked2[0]); ++i) { REQUIRE(gen1.random() == checked2[i]); } @@ -246,8 +225,7 @@ TEST_CASE("xoshiro256_plus", "[xoshiro256_plus]") { 0x7c5604182a5e5c, 0xfe2b1a4e6cc03509, 0x3cc13d59418b58b6, 0xee043f7276571ff3, 0xb0cefcacf43f423d, 0x2c06bd7d4b2a7b61}; - for (size_t i = 0; i < sizeof(checked3) / sizeof(checked3[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked3) / sizeof(checked3[0]); ++i) { REQUIRE(gen1.random() == checked3[i]); } @@ -259,8 +237,7 @@ TEST_CASE("xoshiro256_plus", "[xoshiro256_plus]") { 0x1a8b65873ac842c9, 0xd15befe036b53136, 0x8f8ff0898e5cca09, 0xf287e57ae52130ec, 0x4b93d1235a7a9687, 0x4a1e76c36a3f44f9}; - for (size_t i = 0; i < sizeof(checked4) / sizeof(checked4[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked4) / sizeof(checked4[0]); ++i) { REQUIRE(gen1.random() == checked4[i]); } @@ -269,8 +246,7 @@ TEST_CASE("xoshiro256_plus", "[xoshiro256_plus]") { 0xfef4edb4819f165e, 0xecd2f9db3f6911a3, 0xaa21cb67c76ca6cf, 0x26a7e2345c58b741, 0xaf507d5180f1070c, 0x5c635df444a4f1}; - for (size_t i = 0; i < sizeof(checked5) / sizeof(checked5[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked5) / sizeof(checked5[0]); ++i) { REQUIRE(gen1.random() == checked5[i]); } @@ -279,14 +255,12 @@ TEST_CASE("xoshiro256_plus", "[xoshiro256_plus]") { 0xa4de52d9b1d5e2e5, 0xa8790f06ce0d31de, 0x5d0eb9a768b4700f, 0xa4fbadd2392670bd, 0xc7b31a2f3b7819ee, 0xcca74cb594188bcd}; - for (size_t i = 0; i < sizeof(checked6) / sizeof(checked6[0]); ++i) - { + for (size_t i = 0; i < sizeof(checked6) / sizeof(checked6[0]); ++i) { REQUIRE(gen1.random() == checked6[i]); } std::vector shuffle_arr; - for (int i = 0; i < 10; ++i) - { + for (int i = 0; i < 10; ++i) { shuffle_arr.push_back(gen1.random()); } gen1.shuffle(shuffle_arr.begin(), shuffle_arr.end()); diff --git a/tests/test_singleton.cpp b/tests/test_singleton.cpp index 6aad037d3..07ad3dc45 100644 --- a/tests/test_singleton.cpp +++ b/tests/test_singleton.cpp @@ -39,8 +39,7 @@ namespace { // Flush independent progress before the process guard can terminate a hung case. -class singleton_progress : public doctest::IReporter -{ +class singleton_progress : public doctest::IReporter { public: explicit singleton_progress(const doctest::ContextOptions&) { } @@ -89,8 +88,7 @@ class singleton_progress : public doctest::IReporter DOCTEST_REGISTER_LISTENER("singleton-progress", 0, singleton_progress); -class concurrent_singleton : public ark::singleton -{ +class concurrent_singleton : public ark::singleton { public: inline static std::atomic constructions{}; @@ -100,8 +98,7 @@ class concurrent_singleton : public ark::singleton }; template -class test_singleton : public ark::singleton> -{ +class test_singleton : public ark::singleton> { public: inline static int constructions = 0; inline static int destructions = 0; @@ -116,15 +113,13 @@ class test_singleton : public ark::singleton> } }; -class throwing_singleton : public ark::singleton -{ +class throwing_singleton : public ark::singleton { public: inline static int attempts = 0; inline static int destructions = 0; throwing_singleton() { - if (++attempts == 1) - { + if (++attempts == 1) { throw std::runtime_error("singleton construction failed"); } } @@ -134,8 +129,7 @@ class throwing_singleton : public ark::singleton } }; -class allocation_failure_singleton : public ark::singleton -{ +class allocation_failure_singleton : public ark::singleton { public: inline static int allocations = 0; @@ -154,17 +148,15 @@ int probe_call_once() { unsigned calls{}; bool caught{}; std::cerr << "[call_once probe] first-begin" << std::endl; - try - { + try { std::call_once(flag, [&] { ++calls; throw std::runtime_error("expected call_once diagnostic exception"); }); + } catch (const std::runtime_error&) { + caught = true; } - catch (const std::runtime_error&) - { caught = true; } - if (!caught || calls != 1) - { + if (!caught || calls != 1) { std::cerr << "[call_once probe] unexpected first-call result" << std::endl; return 1; } @@ -177,8 +169,7 @@ int probe_call_once() { } // namespace int main(int argc, char** argv) { - if (argc == 2 && std::string_view(argv[1]) == "--probe-call-once") - { + if (argc == 2 && std::string_view(argv[1]) == "--probe-call-once") { return probe_call_once(); } return doctest::Context(argc, argv).run(); @@ -211,8 +202,7 @@ TEST_CASE("singleton shutdown borrows injected storage without deleting it") { single::shutdown(); CHECK(single::destructions == 0); - if (single::destructions != 0) - { + if (single::destructions != 0) { // Keep the regression safe when run against the old deleting implementation. external.release(); } @@ -331,20 +321,17 @@ TEST_CASE("singleton synchronizes concurrent lazy initialization") { std::array results{}; std::array threads; std::cerr << "[singleton] starting concurrent instance calls and joining all callers" << std::endl; - for (std::size_t i = 0; i < count; ++i) - { + for (std::size_t i = 0; i < count; ++i) { threads[i] = std::thread([&, i] { start.arrive_and_wait(); results[i] = concurrent_singleton::instance(); }); } - for (auto& thread : threads) - { + for (auto& thread : threads) { thread.join(); } REQUIRE(results[0] != nullptr); - for (auto* result : results) - { + for (auto* result : results) { CHECK(result == results[0]); } CHECK(concurrent_singleton::constructions.load() == 1); diff --git a/tools/entity_config/exporter.hpp b/tools/entity_config/exporter.hpp index 574a73a6d..a8b692969 100644 --- a/tools/entity_config/exporter.hpp +++ b/tools/entity_config/exporter.hpp @@ -14,8 +14,7 @@ namespace ark::entity_export { inline std::filesystem::path utf8_path(std::string_view value) { std::u8string text; text.reserve(value.size()); - for (unsigned char c : value) - { + for (unsigned char c : value) { text.push_back(static_cast(c)); } return std::filesystem::path(text); @@ -26,22 +25,19 @@ inline std::string utf8_string(const std::filesystem::path& value) { return std::string(reinterpret_cast(text.data()), text.size()); } -enum class cell_kind -{ +enum class cell_kind { text, number, boolean, empty }; -struct cell -{ +struct cell { std::string text; cell_kind kind{cell_kind::text}; }; -struct table -{ +struct table { std::string source; std::vector> rows; }; diff --git a/tools/entity_config/main.cpp b/tools/entity_config/main.cpp index bc8a9b206..04801eccb 100644 --- a/tools/entity_config/main.cpp +++ b/tools/entity_config/main.cpp @@ -27,62 +27,47 @@ void help() { } // namespace int main(int argc, char** argv) { - try - { + try { #ifdef _WIN32 boost::nowide::args utf8_arguments(argc, argv); #endif std::map options; std::map data; bool replace = false, code = true; - for (int i = 1; i < argc; ++i) - { + for (int i = 1; i < argc; ++i) { const std::string argument = argv[i]; - if (argument == "--help" || argument == "-h") - { + if (argument == "--help" || argument == "-h") { help(); return 0; } - if (argument == "--replace" || argument == "--no-code") - { - if (argument == "--replace") - { + if (argument == "--replace" || argument == "--no-code") { + if (argument == "--replace") { replace = true; - } - else - { + } else { code = false; } continue; } if (argument != "--workbook" && argument != "--schema" && argument != "--schema-sheet" && - argument != "--data" && argument != "--input" && argument != "--output" && argument != "--validate") - { + argument != "--data" && argument != "--input" && argument != "--output" && argument != "--validate") { throw std::invalid_argument("unknown option " + argument); } - if (++i == argc) - { + if (++i == argc) { throw std::invalid_argument("missing value for " + argument); } const std::string value = argv[i]; - if (argument == "--data") - { + if (argument == "--data") { const auto equal = value.find('='); if (equal == 0 || equal == std::string::npos || equal + 1 == value.size() || - !data.emplace(value.substr(0, equal), value.substr(equal + 1)).second) - { + !data.emplace(value.substr(0, equal), value.substr(equal + 1)).second) { throw std::invalid_argument("expected a unique --data Class=FILE"); } - } - else if (!options.emplace(argument, value).second) - { + } else if (!options.emplace(argument, value).second) { throw std::invalid_argument("duplicate option " + argument); } } - if (options.contains("--validate")) - { - if (options.size() != 1 || !data.empty() || replace || !code) - { + if (options.contains("--validate")) { + if (options.size() != 1 || !data.empty() || replace || !code) { throw std::invalid_argument("--validate must be used on its own"); } const auto document = ark::entity_json::load(options.at("--validate")); @@ -94,39 +79,29 @@ int main(int argc, char** argv) { static_cast(options.contains("--schema")) + static_cast(options.contains("--input")); if (modes != 1 || !options.contains("--output") || - (!options.contains("--schema") && (options.contains("--schema-sheet") || !data.empty()))) - { + (!options.contains("--schema") && (options.contains("--schema-sheet") || !data.empty()))) { throw std::invalid_argument("choose one input mode and an --output directory; use --help"); } ark::entity_json::document document; - if (options.contains("--input")) - { + if (options.contains("--input")) { document = ark::entity_json::load(options.at("--input")); - } - else if (options.contains("--schema")) - { + } else if (options.contains("--schema")) { document = ark::entity_export::read_fields( ark::entity_export::read_table(ark::entity_export::utf8_path(options.at("--schema")), options.contains("--schema-sheet") ? options.at("--schema-sheet") : "")); - for (const auto& [name, path] : data) - { + for (const auto& [name, path] : data) { ark::entity_export::add_config( document, name, ark::entity_export::read_table(ark::entity_export::utf8_path(path))); } - } - else - { + } else { auto sheets = ark::entity_export::read_workbook(ark::entity_export::utf8_path(options.at("--workbook"))); const auto fields = sheets.find("fields"); - if (fields == sheets.end()) - { + if (fields == sheets.end()) { throw std::runtime_error("combined workbook requires a worksheet named fields"); } document = ark::entity_export::read_fields(fields->second); - for (const auto& [name, sheet] : sheets) - { - if (name != "fields") - { + for (const auto& [name, sheet] : sheets) { + if (name != "fields") { ark::entity_export::add_config(document, name, sheet); } } @@ -136,14 +111,10 @@ int main(int argc, char** argv) { std::cout << "Exported " << document.classes.size() << " classes and " << document.configs.size() << " configuration tables to " << options.at("--output") << '\n'; return 0; - } - catch (const std::invalid_argument& error) - { + } catch (const std::invalid_argument& error) { std::cerr << "Usage error: " << error.what() << '\n'; return 2; - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { std::cerr << "Export failed: " << error.what() << '\n'; return 1; } diff --git a/tools/entity_config/model.cpp b/tools/entity_config/model.cpp index 6a6f066a7..5dcc69d9c 100644 --- a/tools/entity_config/model.cpp +++ b/tools/entity_config/model.cpp @@ -15,8 +15,7 @@ namespace { std::string trim(std::string value) { const auto begin = value.find_first_not_of(" \t\r\n"); - if (begin == std::string::npos) - { + if (begin == std::string::npos) { return {}; } return value.substr(begin, value.find_last_not_of(" \t\r\n") - begin + 1); @@ -25,53 +24,40 @@ std::string trim(std::string value) { std::vector split(const std::string& text) { std::vector output; std::size_t start = 0; - while (start < text.size()) - { + while (start < text.size()) { const auto end = text.find('|', start); auto item = trim(text.substr(start, end == std::string::npos ? end : end - start)); - if (item.empty()) - { + if (item.empty()) { throw std::runtime_error("empty item in | separated list"); } output.push_back(std::move(item)); - if (end == std::string::npos) - { + if (end == std::string::npos) { break; } start = end + 1; - if (start == text.size()) - { + if (start == text.size()) { throw std::runtime_error("trailing empty item in | separated list"); } } return output; } -struct columns -{ +struct columns { explicit columns(const table& input, bool schema_aliases = false) { - if (input.rows.empty()) - { + if (input.rows.empty()) { throw std::runtime_error(input.source + ": empty table"); } width = input.rows.front().size(); - for (std::size_t i = 0; i < width; ++i) - { + for (std::size_t i = 0; i < width; ++i) { auto name = trim(input.rows.front()[i].text); - if (schema_aliases && name == "field_name") - { + if (schema_aliases && name == "field_name") { name = "name"; - } - else if (schema_aliases && name == "field_index") - { + } else if (schema_aliases && name == "field_index") { name = "index"; - } - else if (schema_aliases && name == "type_class") - { + } else if (schema_aliases && name == "type_class") { name = "reference"; } - if (name.empty() || !indices.emplace(name, i).second) - { + if (name.empty() || !indices.emplace(name, i).second) { throw std::runtime_error(input.source + ": blank or duplicate column " + name); } } @@ -95,8 +81,7 @@ number integer(std::string text) { text = trim(std::move(text)); number result{}; const auto parsed = std::from_chars(text.data(), text.data() + text.size(), result); - if (text.empty() || parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size()) - { + if (text.empty() || parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size()) { throw std::runtime_error("expected an in-range decimal integer"); } return result; @@ -107,12 +92,10 @@ bool boolean(std::string text) { std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) { return c >= 'A' && c <= 'Z' ? static_cast(c + ('a' - 'A')) : static_cast(c); }); - if (text == "true" || text == "1") - { + if (text == "true" || text == "1") { return true; } - if (text == "false" || text == "0") - { + if (text == "false" || text == "0") { return false; } throw std::runtime_error("expected true/false or 1/0"); @@ -120,36 +103,28 @@ bool boolean(std::string text) { entity_json::value value(const cell& input, entity_json::value_type type) { using enum entity_json::value_type; - if (type == string || type == guid) - { - if (input.kind != cell_kind::text && input.kind != cell_kind::empty) - { + if (type == string || type == guid) { + if (input.kind != cell_kind::text && input.kind != cell_kind::empty) { throw std::runtime_error("string/GUID values require text cells in XLSX"); } return input.text; } - if (type == boolean) - { + if (type == boolean) { return entity_export::boolean(input.text); } - if (input.kind == cell_kind::boolean) - { + if (input.kind == cell_kind::boolean) { throw std::runtime_error("boolean spreadsheet cell is not a numeric value"); } - if (type == int32 || type == int64) - { + if (type == int32 || type == int64) { const auto result = integer(input.text); - if (input.kind == cell_kind::number && (result > 9007199254740991LL || result < -9007199254740991LL)) - { + if (input.kind == cell_kind::number && (result > 9007199254740991LL || result < -9007199254740991LL)) { throw std::runtime_error("wide integer must be an XLSX text cell to preserve its exact value"); } return result; } - if (type == uint32 || type == uint64) - { + if (type == uint32 || type == uint64) { const auto result = integer(input.text); - if (input.kind == cell_kind::number && result > 9007199254740991ULL) - { + if (input.kind == cell_kind::number && result > 9007199254740991ULL) { throw std::runtime_error("wide integer must be an XLSX text cell to preserve its exact value"); } return result; @@ -157,8 +132,7 @@ entity_json::value value(const cell& input, entity_json::value_type type) { const auto text = trim(input.text); double result = 0; const auto parsed = std::from_chars(text.data(), text.data() + text.size(), result); - if (text.empty() || parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size() || !std::isfinite(result)) - { + if (text.empty() || parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size() || !std::isfinite(result)) { throw std::runtime_error("expected a finite number"); } return result; @@ -166,27 +140,21 @@ entity_json::value value(const cell& input, entity_json::value_type type) { std::bitset<16> mask(const columns& header, const std::vector& row) { std::bitset<16> output; - for (const auto& name : split(header.get(row, "mask").text)) - { + for (const auto& name : split(header.get(row, "mask").text)) { const auto it = std::find(entity_json::mask_names.begin(), entity_json::mask_names.end(), name); - if (it == entity_json::mask_names.end()) - { + if (it == entity_json::mask_names.end()) { throw std::runtime_error("unknown mask " + name); } const auto bit = static_cast(it - entity_json::mask_names.begin()); - if (output.test(bit)) - { + if (output.test(bit)) { throw std::runtime_error("duplicate mask " + name); } output.set(bit); } - for (std::size_t i = 0; i < entity_json::mask_names.size(); ++i) - { + for (std::size_t i = 0; i < entity_json::mask_names.size(); ++i) { const auto text = header.get(row, std::string(entity_json::mask_names[i])).text; - if (!text.empty() && boolean(text)) - { - if (output.test(i)) - { + if (!text.empty() && boolean(text)) { + if (output.test(i)) { throw std::runtime_error("mask specified twice: " + std::string(entity_json::mask_names[i])); } output.set(i); @@ -207,16 +175,12 @@ bool same(const entity_json::relation& a, const entity_json::relation& b) { template void inherit(std::vector& into, const std::vector& from) { - for (const auto& item : from) - { + for (const auto& item : from) { const auto existing = std::find_if(into.begin(), into.end(), [&](const auto& candidate) { return candidate.name == item.name || candidate.index == item.index; }); - if (existing == into.end()) - { + if (existing == into.end()) { into.push_back(item); - } - else if (!same(*existing, item)) - { + } else if (!same(*existing, item)) { throw std::runtime_error("conflicting inherited name/index: " + item.name); } } @@ -226,21 +190,17 @@ void inherit(std::vector& into, const std::vector& from) { entity_json::document read_fields(const table& input) { const columns header(input, true); - for (const auto* required : {"class", "index", "name", "type"}) - { - if (!header.indices.contains(required)) - { + for (const auto* required : {"class", "index", "name", "type"}) { + if (!header.indices.contains(required)) { throw std::runtime_error( input.source + ": missing required column " + required + "; field indices must be explicit and stable"); } } - for (const auto& [name, index] : header.indices) - { + for (const auto& [name, index] : header.indices) { if (name != "class" && name != "index" && name != "name" && name != "type" && name != "reference" && name != "mask" && name != "description" && std::find(entity_json::mask_names.begin(), entity_json::mask_names.end(), name) == - entity_json::mask_names.end()) - { + entity_json::mask_names.end()) { throw std::runtime_error(input.source + ": unknown field-table column " + name); } } @@ -248,26 +208,20 @@ entity_json::document read_fields(const table& input) { std::map indices; std::map> parents; std::set declarations; - for (std::size_t i = 1; i < input.rows.size(); ++i) - { + for (std::size_t i = 1; i < input.rows.size(); ++i) { const auto& row = input.rows[i]; - if (empty(row)) - { + if (empty(row)) { continue; } - try - { - if (row.size() > header.width) - { + try { + if (row.size() > header.width) { throw std::runtime_error("row has more cells than the header"); } const auto name = trim(header.get(row, "class").text); - if (name.empty()) - { + if (name.empty()) { throw std::runtime_error("class must not be blank"); } - if (!indices.contains(name)) - { + if (!indices.contains(name)) { indices.emplace(name, result.classes.size()); result.classes.push_back({name, {}, {}, {}, {}}); } @@ -275,11 +229,9 @@ entity_json::document read_fields(const table& input) { const auto type = trim(header.get(row, "type").text); const auto reference = trim(header.get(row, "reference").text); const auto description = header.get(row, "description").text; - if (type == "class") - { + if (type == "class") { if (!declarations.insert(name).second || !header.get(row, "index").text.empty() || - !header.get(row, "name").text.empty() || mask(header, row).any()) - { + !header.get(row, "name").text.empty() || mask(header, row).any()) { throw std::runtime_error("invalid or duplicate class declaration"); } definition.description = description; @@ -288,36 +240,29 @@ entity_json::document read_fields(const table& input) { } const auto field_name = trim(header.get(row, "name").text); const auto index = integer(header.get(row, "index").text); - if (type == "table" || type == "container") - { + if (type == "table" || type == "container") { auto& destination = type == "table" ? definition.tables : definition.containers; destination.push_back({field_name, index, reference, mask(header, row), description}); - } - else - { - if (!reference.empty()) - { + } else { + if (!reference.empty()) { throw std::runtime_error("only class/table/container rows accept a reference"); } const auto normalized = type == "int" ? "int32" : type == "object" ? "guid" : type; definition.fields.push_back({field_name, index, entity_json::parse_type(normalized, input.source), mask(header, row), description}); } + } catch (const std::exception& error) { + throw std::runtime_error(input.source + ": row " + std::to_string(i + 1) + ": " + error.what()); } - catch (const std::exception& error) - { throw std::runtime_error(input.source + ": row " + std::to_string(i + 1) + ": " + error.what()); } } // Validate local declarations before flattening so duplicate source rows cannot disappear. entity_json::validate(result, input.source); std::vector> children(result.classes.size()); std::vector remaining(result.classes.size(), 0); - for (const auto& [child, bases] : parents) - { + for (const auto& [child, bases] : parents) { std::set seen; - for (const auto& base : bases) - { - if (!indices.contains(base) || !seen.insert(base).second) - { + for (const auto& base : bases) { + if (!indices.contains(base) || !seen.insert(base).second) { throw std::runtime_error(input.source + ": missing or duplicate parent " + base); } children[indices.at(base)].push_back(indices.at(child)); @@ -325,37 +270,30 @@ entity_json::document read_fields(const table& input) { } } std::deque ready; - for (std::size_t i = 0; i < remaining.size(); ++i) - { - if (remaining[i] == 0) - { + for (std::size_t i = 0; i < remaining.size(); ++i) { + if (remaining[i] == 0) { ready.push_back(i); } } std::size_t processed = 0; - while (!ready.empty()) - { + while (!ready.empty()) { const auto index = ready.front(); ready.pop_front(); auto& definition = result.classes[index]; - for (const auto& base : parents[definition.name]) - { + for (const auto& base : parents[definition.name]) { const auto& inherited = result.classes[indices.at(base)]; inherit(definition.fields, inherited.fields); inherit(definition.tables, inherited.tables); inherit(definition.containers, inherited.containers); } ++processed; - for (const auto child : children[index]) - { - if (--remaining[child] == 0) - { + for (const auto child : children[index]) { + if (--remaining[child] == 0) { ready.push_back(child); } } } - if (processed != result.classes.size()) - { + if (processed != result.classes.size()) { throw std::runtime_error(input.source + ": class inheritance cycle"); } entity_json::validate(result, input.source); @@ -365,48 +303,36 @@ entity_json::document read_fields(const table& input) { void add_config(entity_json::document& output, const std::string& class_name, const table& input) { const auto definition = std::find_if( output.classes.begin(), output.classes.end(), [&](const auto& item) { return item.name == class_name; }); - if (definition == output.classes.end()) - { + if (definition == output.classes.end()) { throw std::runtime_error(input.source + ": unknown config class " + class_name); } const columns header(input); - if (header.indices.size() != definition->fields.size()) - { + if (header.indices.size() != definition->fields.size()) { throw std::runtime_error(input.source + ": data columns must match every scalar field exactly"); } - for (const auto& field : definition->fields) - { - if (!header.indices.contains(field.name)) - { + for (const auto& field : definition->fields) { + if (!header.indices.contains(field.name)) { throw std::runtime_error(input.source + ": missing data column " + field.name); } } entity_json::config_definition config{class_name, {}}; - for (std::size_t i = 1; i < input.rows.size(); ++i) - { + for (std::size_t i = 1; i < input.rows.size(); ++i) { const auto& row = input.rows[i]; - if (empty(row)) - { + if (empty(row)) { continue; } - if (row.size() > header.width) - { + if (row.size() > header.width) { throw std::runtime_error(input.source + ": extra data cells at row " + std::to_string(i + 1)); } entity_json::row values; - for (const auto& field : definition->fields) - { - try - { + for (const auto& field : definition->fields) { + try { const auto column = header.indices.at(field.name); - if (column >= row.size()) - { + if (column >= row.size()) { throw std::runtime_error("missing data cell"); } values.emplace(field.name, value(row[column], field.type)); - } - catch (const std::exception& error) - { + } catch (const std::exception& error) { throw std::runtime_error( input.source + ": row " + std::to_string(i + 1) + ", field " + field.name + ": " + error.what()); } @@ -414,10 +340,9 @@ void add_config(entity_json::document& output, const std::string& class_name, co config.rows.push_back(std::move(values)); } output.configs.push_back(std::move(config)); - try - { entity_json::validate(output, input.source); } - catch (...) - { + try { + entity_json::validate(output, input.source); + } catch (...) { output.configs.pop_back(); throw; } diff --git a/tools/entity_config/output.cpp b/tools/entity_config/output.cpp index b53870fa4..7ef329175 100644 --- a/tools/entity_config/output.cpp +++ b/tools/entity_config/output.cpp @@ -21,47 +21,37 @@ bool lower(char c) { } std::string identifier(const std::string& source, bool pascal) { - if (source.empty()) - { + if (source.empty()) { throw std::runtime_error("empty binding identifier"); } std::string result; bool capitalize = true; - for (std::size_t i = 0; i < source.size(); ++i) - { + for (std::size_t i = 0; i < source.size(); ++i) { const char c = source[i]; - if (c != '_' && !upper(c) && !lower(c) && !(c >= '0' && c <= '9')) - { + if (c != '_' && !upper(c) && !lower(c) && !(c >= '0' && c <= '9')) { throw std::runtime_error("binding identifier requires ASCII letters/digits/underscores: " + source + "; use --no-code to export JSON only"); } - if (pascal) - { - if (c == '_') - { + if (pascal) { + if (c == '_') { capitalize = true; continue; } result += capitalize && lower(c) ? static_cast(c - ('a' - 'A')) : c; capitalize = false; - } - else - { + } else { if (upper(c) && i > 0 && source[i - 1] != '_' && - (lower(source[i - 1]) || (i + 1 < source.size() && lower(source[i + 1])))) - { + (lower(source[i - 1]) || (i + 1 < source.size() && lower(source[i + 1])))) { result += '_'; } result += upper(c) ? static_cast(c + ('a' - 'A')) : c; } } if (result.empty() || (result.front() >= '0' && result.front() <= '9') || result.find("__") != std::string::npos || - (!pascal && result.starts_with("_"))) - { + (!pascal && result.starts_with("_"))) { throw std::runtime_error("reserved or invalid binding identifier: " + source + "; use --no-code"); } - if (!pascal) - { + if (!pascal) { static const std::set keywords{"alignas", "alignof", "and", "and_eq", "asm", "atomic_cancel", "atomic_commit", "atomic_noexcept", "auto", "bitand", "bitor", "bool", "break", "case", "catch", "char", "char8_t", "char16_t", "char32_t", "class", "compl", "concept", "const", "consteval", "constexpr", @@ -73,8 +63,7 @@ std::string identifier(const std::string& source, bool pascal) { "static_cast", "struct", "switch", "synchronized", "template", "this", "thread_local", "throw", "true", "try", "typedef", "typeid", "typename", "union", "unsigned", "using", "virtual", "void", "volatile", "wchar_t", "while", "xor", "xor_eq"}; - if (keywords.contains(result)) - { + if (keywords.contains(result)) { result += '_'; } } @@ -85,44 +74,35 @@ std::string bindings(const entity_json::document& input, bool csharp) { entity_json::validate(input); std::ostringstream text; text << "// Generated by ark_config_tool. Edit the source field table, not this file.\n"; - if (csharp) - { + if (csharp) { text << "namespace Ark.Generated\n{\n"; - } - else - { + } else { text << "#pragma once\n\n#include \n\nnamespace ark::generated {\n\n"; } std::set types; - for (const auto& definition : input.classes) - { + for (const auto& definition : input.classes) { const auto base = identifier(definition.name, csharp); const auto type = base + (csharp ? "Fields" : base.ends_with('_') ? "fields" : "_fields"); - if (!types.insert(type).second) - { + if (!types.insert(type).second) { throw std::runtime_error("binding class-name collision: " + definition.name); } text << (csharp ? " public static class " : "struct ") << type << "\n" << (csharp ? " {\n" : "{\n"); std::set members; const auto write = [&](const auto& field) { const auto name = identifier(field.name, csharp); - if (name == type || !members.insert(name).second) - { + if (name == type || !members.insert(name).second) { throw std::runtime_error("binding field-name collision: " + definition.name + "." + field.name); } text << (csharp ? " public const uint " : " static constexpr std::uint32_t ") << name << " = " << field.index << (csharp ? "u;\n" : "u;\n"); }; - for (const auto& field : definition.fields) - { + for (const auto& field : definition.fields) { write(field); } - for (const auto& table : definition.tables) - { + for (const auto& table : definition.tables) { write(table); } - for (const auto& container : definition.containers) - { + for (const auto& container : definition.containers) { write(container); } text << (csharp ? " }\n\n" : "};\n\n"); @@ -135,25 +115,21 @@ void write_file(const std::filesystem::path& path, const std::string& text) { std::ofstream output(path, std::ios::binary | std::ios::trunc); output.write(text.data(), static_cast(text.size())); output.flush(); - if (!output) - { + if (!output) { throw std::runtime_error(utf8_string(path) + ": export write failed"); } output.close(); - if (!output) - { + if (!output) { throw std::runtime_error(utf8_string(path) + ": export close failed"); } } std::filesystem::path staging_directory(const std::filesystem::path& parent) { std::random_device random; - for (int attempt = 0; attempt < 16; ++attempt) - { + for (int attempt = 0; attempt < 16; ++attempt) { const auto name = ".ark-entity-export-" + std::to_string(random()) + "-" + std::to_string(random()); const auto path = parent / name; - if (std::filesystem::create_directory(path)) - { + if (std::filesystem::create_directory(path)) { return path; } } @@ -177,15 +153,12 @@ void export_bundle( const auto cpp = generate_code ? cpp_bindings(input) : std::string{}; const auto cs = generate_code ? csharp_bindings(input) : std::string{}; const auto destination = std::filesystem::absolute(output).lexically_normal(); - if (destination.filename().empty() || destination == destination.root_path()) - { + if (destination.filename().empty() || destination == destination.root_path()) { throw std::runtime_error("export destination must be a dedicated directory"); } const std::string marker = "ark.entity-config-export 1\n"; - if (std::filesystem::exists(destination)) - { - if (!replace || std::filesystem::is_symlink(destination) || !std::filesystem::is_directory(destination)) - { + if (std::filesystem::exists(destination)) { + if (!replace || std::filesystem::is_symlink(destination) || !std::filesystem::is_directory(destination)) { throw std::runtime_error( utf8_string(destination) + ": destination exists; --replace requires a tool-owned bundle"); } @@ -193,8 +166,7 @@ void export_bundle( std::string existing(marker.size() + 1, '\0'); file.read(existing.data(), static_cast(existing.size())); existing.resize(static_cast(file.gcount())); - if (existing != marker) - { + if (existing != marker) { throw std::runtime_error( utf8_string(destination) + ": refusing to replace a directory without the export marker"); } @@ -202,42 +174,34 @@ void export_bundle( std::filesystem::create_directories(destination.parent_path()); const auto stage = staging_directory(destination.parent_path()); std::filesystem::path backup; - try - { + try { std::filesystem::create_directory(stage / "meta"); write_file(stage / "meta/entity_schema.json", json); write_file(stage / ".ark-entity-export", marker); - if (generate_code) - { + if (generate_code) { std::filesystem::create_directory(stage / "code"); write_file(stage / "code/entity_fields.hpp", cpp); write_file(stage / "code/EntityFields.cs", cs); } - if (std::filesystem::exists(destination)) - { + if (std::filesystem::exists(destination)) { backup = staging_directory(destination.parent_path()); std::filesystem::remove(backup); std::filesystem::rename(destination, backup); } - try - { std::filesystem::rename(stage, destination); } - catch (...) - { - if (!backup.empty()) - { + try { + std::filesystem::rename(stage, destination); + } catch (...) { + if (!backup.empty()) { std::filesystem::rename(backup, destination); backup.clear(); } throw; } - if (!backup.empty()) - { + if (!backup.empty()) { std::error_code ignored; std::filesystem::remove_all(backup, ignored); } - } - catch (...) - { + } catch (...) { std::error_code ignored; std::filesystem::remove_all(stage, ignored); throw; diff --git a/tools/entity_config/tables.cpp b/tools/entity_config/tables.cpp index 52d5712d7..4662c580a 100644 --- a/tools/entity_config/tables.cpp +++ b/tools/entity_config/tables.cpp @@ -14,14 +14,12 @@ namespace ark::entity_export { namespace { std::string decimal(double value) { - if (!std::isfinite(value)) - { + if (!std::isfinite(value)) { throw std::runtime_error("non-finite spreadsheet number"); } char buffer[64]; const auto result = std::to_chars(buffer, buffer + sizeof(buffer), value); - if (result.ec != std::errc{}) - { + if (result.ec != std::errc{}) { throw std::runtime_error("could not represent spreadsheet number"); } return std::string(buffer, result.ptr); @@ -31,20 +29,16 @@ table worksheet(OpenXLSX::XLWorksheet sheet, const std::string& source) { table output{source + "[" + sheet.name() + "]", {}}; const auto columns = sheet.columnCount(); const auto rows = sheet.rowCount(); - for (std::uint32_t row = 1; row <= rows; ++row) - { + for (std::uint32_t row = 1; row <= rows; ++row) { std::vector values; - for (std::uint32_t column = 1; column <= columns; ++column) - { + for (std::uint32_t column = 1; column <= columns; ++column) { auto item = sheet.cell(row, static_cast(column)); - if (item.hasFormula()) - { + if (item.hasFormula()) { throw std::runtime_error(output.source + ": row " + std::to_string(row) + " contains a formula; export evaluated values or CSV instead"); } const auto& value = item.value(); - switch (value.type()) - { + switch (value.type()) { case OpenXLSX::XLValueType::Empty: values.push_back({"", cell_kind::empty}); break; @@ -54,16 +48,12 @@ table worksheet(OpenXLSX::XLWorksheet sheet, const std::string& source) { case OpenXLSX::XLValueType::Integer: values.push_back({std::to_string(value.get()), cell_kind::number}); break; - case OpenXLSX::XLValueType::Float: - { + case OpenXLSX::XLValueType::Float: { const auto number = value.get(); // Small integral values should retain integer spelling for typed integer columns. - if (std::isfinite(number) && std::trunc(number) == number && std::abs(number) <= 9007199254740991.0) - { + if (std::isfinite(number) && std::trunc(number) == number && std::abs(number) <= 9007199254740991.0) { values.push_back({std::to_string(static_cast(number)), cell_kind::number}); - } - else - { + } else { values.push_back({decimal(number), cell_kind::number}); } break; @@ -84,8 +74,7 @@ table worksheet(OpenXLSX::XLWorksheet sheet, const std::string& source) { } // namespace table parse_csv(std::string_view input, std::string source) { - if (input.starts_with("\xef\xbb\xbf")) - { + if (input.starts_with("\xef\xbb\xbf")) { input.remove_prefix(3); } table output{std::move(source), {}}; @@ -98,54 +87,37 @@ table parse_csv(std::string_view input, std::string source) { closed = false; pending = false; }; - for (std::size_t i = 0; i < input.size(); ++i) - { + for (std::size_t i = 0; i < input.size(); ++i) { const char c = input[i]; - if (quoted) - { - if (c == '"') - { - if (i + 1 < input.size() && input[i + 1] == '"') - { + if (quoted) { + if (c == '"') { + if (i + 1 < input.size() && input[i + 1] == '"') { field += '"'; ++i; - } - else - { + } else { quoted = false; closed = true; } - } - else - { + } else { field += c; } continue; } - if (c == ',') - { + if (c == ',') { finish_field(); pending = true; - } - else if (c == '\r' || c == '\n') - { + } else if (c == '\r' || c == '\n') { finish_field(); output.rows.push_back(std::move(row)); row.clear(); - if (c == '\r' && i + 1 < input.size() && input[i + 1] == '\n') - { + if (c == '\r' && i + 1 < input.size() && input[i + 1] == '\n') { ++i; } - } - else if (c == '"' && field.empty() && !closed) - { + } else if (c == '"' && field.empty() && !closed) { quoted = true; pending = true; - } - else - { - if (closed || c == '"') - { + } else { + if (closed || c == '"') { throw std::runtime_error( output.source + ": malformed CSV quoting near record " + std::to_string(output.rows.size() + 1)); } @@ -153,12 +125,10 @@ table parse_csv(std::string_view input, std::string source) { pending = true; } } - if (quoted) - { + if (quoted) { throw std::runtime_error(output.source + ": unterminated CSV quoted field"); } - if (pending || closed || !row.empty() || !field.empty()) - { + if (pending || closed || !row.empty() || !field.empty()) { finish_field(); output.rows.push_back(std::move(row)); } @@ -169,8 +139,7 @@ std::map read_workbook(const std::filesystem::path& path) { OpenXLSX::XLDocument document; document.open(utf8_string(path)); std::map result; - for (const auto& name : document.workbook().worksheetNames()) - { + for (const auto& name : document.workbook().worksheetNames()) { result.emplace(name, worksheet(document.workbook().worksheet(name), utf8_string(path))); } document.close(); @@ -179,47 +148,37 @@ std::map read_workbook(const std::filesystem::path& path) { table read_table(const std::filesystem::path& path, const std::string& sheet) { auto extension = utf8_string(path.extension()); - for (auto& c : extension) - { - if (c >= 'A' && c <= 'Z') - { + for (auto& c : extension) { + if (c >= 'A' && c <= 'Z') { c = static_cast(c + ('a' - 'A')); } } - if (extension == ".xlsx") - { + if (extension == ".xlsx") { auto workbook = read_workbook(path); - if (!sheet.empty()) - { + if (!sheet.empty()) { const auto it = workbook.find(sheet); - if (it == workbook.end()) - { + if (it == workbook.end()) { throw std::runtime_error(utf8_string(path) + ": missing worksheet " + sheet); } return std::move(it->second); } - if (workbook.size() != 1) - { + if (workbook.size() != 1) { throw std::runtime_error(utf8_string(path) + ": select an explicit worksheet for a multi-sheet input"); } return std::move(workbook.begin()->second); } - if (extension != ".csv") - { + if (extension != ".csv") { throw std::runtime_error(utf8_string(path) + ": expected .csv or .xlsx input"); } - if (!sheet.empty()) - { + if (!sheet.empty()) { throw std::runtime_error(utf8_string(path) + ": a CSV file has no worksheets"); } std::ifstream file(path, std::ios::binary); - if (!file) - { + if (!file) { throw std::runtime_error(utf8_string(path) + ": cannot open input"); } const std::string text{std::istreambuf_iterator(file), std::istreambuf_iterator()}; - if (file.bad()) - { + if (file.bad()) { throw std::runtime_error(utf8_string(path) + ": input read failed"); } return parse_csv(text, utf8_string(path));