From 624016d9046736ba2d6d798512f11cc1dedfcc57 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Fri, 4 Dec 2026 04:38:05 +0300 Subject: [PATCH] feat(daemon): report per-unit compile arguments; deepen registry search tests --- docs/agent-workflow/STATE.md | 2 + docs/agent-workflow/TASKS.md | 1 + docs/agent-workflow/VERIFICATION.md | 12 +++ docs/roadmap/21-expansion-roadmap.md | 2 +- src/Daemon/Daemon.cpp | 141 ++++++++++++++++++++++----- src/Main.cpp | 23 +++++ tests/CliContracts.cmake | 1 + tests/DaemonTests.cpp | 69 +++++++++++++ tests/RegistryTests.cpp | 111 +++++++++++++++++++++ 9 files changed, 335 insertions(+), 27 deletions(-) diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 54440c9..9f67134 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -235,6 +235,8 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B - **Wave 71 (Member-Filtered Daemon `describe` & Test Executable-Path Cleanup)**: `describe` accepts an optional `member` (workspace roots only; unknown members rejected) so one member can be described without evaluating the others. A swarm worker replaced the remaining `/proc/self/exe` lookups in `tests/{Registry,FullV1,SelfHost}Tests.cpp` with `Platform::current_executable_path()` (5/5 substantive tasks; its final build task was stopped and re-run by the orchestrator). +- **Wave 72 (Daemon Target Flags & Registry Search Test Depth)**: added the `target_flags` daemon request (`vbs daemon target flags --name [--file] [--profile] [--member]`) returning each compilation unit's bounded arguments, defines, and compile options (unknown targets rejected, file-suffix filter). A swarm worker extended `RegistryTests` with search `q` filtering (name and description), offset pagination envelope assertions, far-offset empty pages, and invalid offset/limit rejection (4/4 substantive tasks; its final build task was stopped and re-run by the orchestrator). + ## Remaining future scope - **Post-v1 Expansion Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Track C (macOS/Windows ports + dual-profile cross-compilation) and dedicated external editor plugins remain planned; Track D3 signing (SBOM, Ed25519 primitives, trusted-key enforcement/distribution, binary-variant signing/distribution) and Track E3 daemon capabilities are implemented, and Track E4 now uses `Void::Net` for the registry client/server and remote cache plus `Void::Sqlite` for the StateStore when available. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 2e2dccf..3ce3f68 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -75,4 +75,5 @@ Base HEAD: `fe0d1a6` | Wave 69 (RegistryClient owners helper, via swarm) | `fetch_package_owners` in RegistryClient + RegistryTests coverage (owners list, missing package 404, anonymous private 401) | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Registry 7/7, full CTest 8/8) | `include/Void/Build/Package/RegistryClient.hpp`, `src/Package/RegistryClient.cpp`, `tests/RegistryTests.cpp`, docs | | Wave 70 (Track C1 executable path + daemon host info) | `Platform::current_executable_path()` replacing `/proc/self/exe` in Main.cpp; daemon `info` reports `host_os`/`host_supported`/`backends` (swarm, 5/5 tasks) | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Core and Daemon suites pass, full CTest 8/8) | `include/Void/Build/Platform/FileOps.hpp`, `src/Platform/Linux/FileOps.cpp`, `src/Main.cpp`, `src/Daemon/Daemon.cpp`, `tests/{CoreEngineTests,DaemonTests}.cpp`, docs | | Wave 71 (Member-filtered describe + test path cleanup) | `describe` `member` filter in the daemon; swarm replaced `/proc/self/exe` in three test files | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Daemon suite and full CTest 8/8) | `src/Daemon/Daemon.cpp`, `src/Main.cpp`, `tests/{DaemonTests,RegistryTests,FullV1Tests,SelfHostTests}.cpp`, docs | +| Wave 72 (Daemon target flags + registry search tests) | `target_flags` daemon request + `vbs daemon target flags`; swarm deepened RegistryTests search/pagination coverage | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Daemon and Registry suites pass, full CTest 8/8) | `src/Daemon/Daemon.cpp`, `src/Main.cpp`, `tests/{DaemonTests,RegistryTests}.cpp`, `tests/CliContracts.cmake`, docs | | Future (Plan 20 Slice 3 / Tracks C, E3 editor extensions) |"}] Live `conan` CLI verification; macOS/Windows/cross-compile; binary-variant signing and key distribution; daemon-side dependency materialization and editor plugins; `Void::Net`/`Void::Sqlite` alignment | PLANNED (unimplemented) | [21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md), [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md) | diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index 23f0682..df3f512 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -1139,6 +1139,18 @@ dev cpp-gcc -c build/pinned/bin/vbs_v1_tests --suite Daemon --no-color substantive tasks; its last build task was stopped and re-run by the orchestrator). - Full CTest: **8 / 8 passed** in 241.04 s. +## Daemon Target Flags & Registry Search Test Depth (GCC 16.2, pin `0002e74`) + +- `Daemon.target_flags_reports_compile_units`: target `app` returns a compile unit for + `main.cpp` with a non-empty `arguments` array, `file:"nope.cpp"` returns no units, and an unknown + target is rejected. +- Swarm `swarm_mx8b201o_acox` (one worker) extended `RegistryTests` with `q` name/description + filtering, offset pagination envelope checks, far-offset empty pages, and invalid + offset/limit rejection (4/4 substantive tasks; the final build task was stopped and re-run by + the orchestrator). +- `registry_rbac_immutability_csrf_xss_web_and_backup_restore` passes (975 ms) with the extended + assertions; full CTest: **8 / 8 passed** in 243.47 s. + ## Limits and Unrun Checks 1. **HTTPS git fetch**: the host shell is proxy-restricted, but the Docker container could clone `https://git.faumaray.com/Void/VoidLibrary.git`; the pinned commit `3e254055e081a104f08df68dde39711bc7813518` was fetched directly for the verification above. A separate configure against the local `/home/faumaray/Projects/Library` checkout via `VBS_VOID_SOURCE_DIR` also succeeded (development-only override, checkout unmodified). diff --git a/docs/roadmap/21-expansion-roadmap.md b/docs/roadmap/21-expansion-roadmap.md index 25796e7..101d5a2 100644 --- a/docs/roadmap/21-expansion-roadmap.md +++ b/docs/roadmap/21-expansion-roadmap.md @@ -46,7 +46,7 @@ flowchart LR | Phase | Concrete Scope | Acceptance Gate | | --- | --- | --- | -| **C1 — Platform Backend Split** *(Linux backend split implemented; macOS/Windows pending)* | Split `src/Platform/` into `Linux/`, `MacOS/`, and `Windows/` behind clean interfaces (`FileOps`, `ProcessSupervisor`, `DirectoryWatcher`), delegating to `Void::System` as upstream adds OS backends. Linux implementations now live under `src/Platform/Linux/` and `src/Watch/Linux/` (inotify watcher) with an explicit `HostOs`/`host_supported()` boundary in `include/Void/Build/Platform/Host.hpp`; macOS/Windows backends await real hosts (`vbs doctor` and the daemon `info` request report the detected host and enabled backends, `Platform::current_executable_path()` isolates the executable-path lookup across sources and tests, and the daemon `describe` request can be scoped to one workspace member). | Zero Linux regressions; clean platform abstraction boundary. | +| **C1 — Platform Backend Split** *(Linux backend split implemented; macOS/Windows pending)* | Split `src/Platform/` into `Linux/`, `MacOS/`, and `Windows/` behind clean interfaces (`FileOps`, `ProcessSupervisor`, `DirectoryWatcher`), delegating to `Void::System` as upstream adds OS backends. Linux implementations now live under `src/Platform/Linux/` and `src/Watch/Linux/` (inotify watcher) with an explicit `HostOs`/`host_supported()` boundary in `include/Void/Build/Platform/Host.hpp`; macOS/Windows backends await real hosts (`vbs doctor` and the daemon `info` request report the detected host and enabled backends, `Platform::current_executable_path()` isolates the executable-path lookup across sources and tests, the daemon `describe` request can be scoped to one workspace member, and `vbs daemon target flags` serves per-unit compile arguments). | Zero Linux regressions; clean platform abstraction boundary. | | **C2 — macOS / Apple Clang & `ld64`** | Apple Clang toolchain probes, `.dylib` + `@rpath`/`@loader_path` install-name lowering, `FSEvents` watcher, Mach-O deterministic timestamps. | Real macOS CI runner passing all SDK, core, module, and install tests. | | **C3 — Windows / MSVC & `clang-cl`** | MSVC (`cl.exe`, `lib.exe`, `link.exe`, `/showIncludes`, `.pdb`, `/FS`, `.dll`/`.lib` import libraries), Job Object process-tree kill, `ReadDirectoryChangesW` watcher, case-insensitive path conflict detection. | Real Windows CI runner passing process-tree kill, header-shadowing, and install relocation tests. | | **C4 — True Host-vs-Target Cross-Compilation** | Dual-context evaluation (`host` profile for code generators and `build_dependency` tools vs `target` profile for cross-compiled products), sysroot & `--target=` triple propagation. | `linux-x86_64` host cross-compiling `linux-aarch64` fixture while executing host-compiled generator natively. | diff --git a/src/Daemon/Daemon.cpp b/src/Daemon/Daemon.cpp index dc25085..60648d3 100644 --- a/src/Daemon/Daemon.cpp +++ b/src/Daemon/Daemon.cpp @@ -1194,6 +1194,102 @@ std::string compdb_generations_project(const DaemonOptions &options, return serialize_response(JsonValue{std::move(object)}); } +std::string_view action_kind_label(Graph::ActionKind kind) noexcept { + switch (kind) { + case Graph::ActionKind::Compile: + return "compile"; + case Graph::ActionKind::PrecompiledHeader: + return "pch"; + case Graph::ActionKind::HeaderUnit: + return "header_unit"; + case Graph::ActionKind::ModuleScan: + return "module_scan"; + case Graph::ActionKind::ModuleBmi: + return "module_bmi"; + case Graph::ActionKind::Archive: + return "archive"; + case Graph::ActionKind::Link: + return "link"; + case Graph::ActionKind::Custom: + return "custom"; + } + return "unknown"; +} + + +// Reports the bounded compile arguments of one target's compilation units. +std::string target_flags_project(const DaemonOptions &options, std::string_view profile_name, + std::optional compiler_override, + std::string_view target_name, std::string_view file_filter, + std::string_view member) { + auto effective_result = resolve_member_options(options, member); + if (!effective_result) { + return error_response(std::format("target_flags: {}", effective_result.error())); + } + auto evaluated = + evaluate_project_graph(*effective_result, profile_name, compiler_override, "target_flags"); + if (!evaluated) { + return error_response(evaluated.error()); + } + auto graph = lower_graph(*effective_result, *evaluated, {}, "target_flags"); + if (!graph) { + return error_response(graph.error()); + } + if (std::ranges::none_of( + graph->targets, + [&](const Graph::ResolvedTargetSummary &node) { return node.name == target_name; })) { + return error_response(std::format("target_flags: unknown target '{}'", target_name)); + } + + const auto bounded_strings = [](const std::vector &values) { + JsonValue::Array array; + for (const auto &value : values) { + if (array.size() >= kMaxCompdbArguments) { + break; + } + array.emplace_back(value.size() > kMaxCompdbArgumentBytes + ? value.substr(0, kMaxCompdbArgumentBytes) + : value); + } + return array; + }; + + JsonValue::Array units; + for (const auto &action : graph->actions) { + if (action.kind != Graph::ActionKind::Compile && + action.kind != Graph::ActionKind::PrecompiledHeader && + action.kind != Graph::ActionKind::HeaderUnit) { + continue; + } + if (action.target_name != target_name) { + continue; + } + const std::string source = action.logical_source_file.string(); + if (!file_filter.empty() && !std::string_view{source}.ends_with(file_filter)) { + continue; + } + if (units.size() >= kMaxActionLimit) { + break; + } + JsonValue::Object unit; + unit.emplace("source", JsonValue{source}); + unit.emplace("kind", JsonValue{std::string{action_kind_label(action.kind)}}); + unit.emplace("is_c_source", JsonValue{action.is_c_source}); + unit.emplace("arguments", JsonValue{bounded_strings(action.arguments)}); + unit.emplace("defines", JsonValue{bounded_strings(action.defines)}); + unit.emplace("compile_options", JsonValue{bounded_strings(action.compile_options)}); + units.emplace_back(std::move(unit)); + } + + JsonValue::Object object; + object.emplace("ok", JsonValue{true}); + object.emplace("op", JsonValue{std::string{"target_flags"}}); + object.emplace("profile", JsonValue{evaluated->context.name}); + object.emplace("target", JsonValue{std::string{target_name}}); + object.emplace("units", JsonValue{std::move(units)}); + return serialize_response(JsonValue{std::move(object)}); +} + // Reports one target's metadata (kind, sources, outputs, runtime libraries) from the lowered graph. std::string target_info_project(const DaemonOptions &options, std::string_view profile_name, std::optional compiler_override, @@ -1242,28 +1338,6 @@ std::string target_info_project(const DaemonOptions &options, std::string_view p return serialize_response(JsonValue{std::move(object)}); } -std::string_view action_kind_label(Graph::ActionKind kind) noexcept { - switch (kind) { - case Graph::ActionKind::Compile: - return "compile"; - case Graph::ActionKind::PrecompiledHeader: - return "pch"; - case Graph::ActionKind::HeaderUnit: - return "header_unit"; - case Graph::ActionKind::ModuleScan: - return "module_scan"; - case Graph::ActionKind::ModuleBmi: - return "module_bmi"; - case Graph::ActionKind::Archive: - return "archive"; - case Graph::ActionKind::Link: - return "link"; - case Graph::ActionKind::Custom: - return "custom"; - } - return "unknown"; -} - // Lists the lowered graph's actions (bounded) for editor extensions and diagnostics. std::string actions_project(const DaemonOptions &options, std::string_view profile_name, std::optional compiler_override, @@ -2182,7 +2256,8 @@ DaemonServer::Impl::DispatchResult DaemonServer::Impl::dispatch(std::string_view } if (*name == "describe" || *name == "build" || *name == "test" || *name == "ide_query" || *name == "ide_generate" || *name == "compdb_export" || *name == "graph" || - *name == "deps" || *name == "target_info" || *name == "actions" || *name == "install") { + *name == "deps" || *name == "target_info" || *name == "target_flags" || + *name == "actions" || *name == "install") { std::string profile_name{"debug"}; if (const auto entry = object->find("profile"); entry != object->end()) { const auto *value = std::get_if(&entry->second.value); @@ -2312,16 +2387,30 @@ DaemonServer::Impl::DispatchResult DaemonServer::Impl::dispatch(std::string_view member), false}; } - if (*name == "target_info") { + if (*name == "target_info" || *name == "target_flags") { const auto entry = object->find("target"); if (entry == object->end()) { - return {error_response("target_info requires \"target\""), false}; + return {error_response("\"target\" is required"), false}; } const auto *value = std::get_if(&entry->second.value); if (value == nullptr || value->empty() || value->size() > kMaxDescribeTargetNameBytes) { return {error_response("\"target\" must be a bounded non-empty string"), false}; } - return {target_info_project(options, profile_name, compiler_override, *value, member), + if (*name == "target_info") { + return {target_info_project(options, profile_name, compiler_override, *value, + member), + false}; + } + std::string file_filter; + if (const auto file_entry = object->find("file"); file_entry != object->end()) { + const auto *file_value = std::get_if(&file_entry->second.value); + if (file_value == nullptr || file_value->size() > 4096) { + return {error_response("\"file\" must be a bounded string"), false}; + } + file_filter = *file_value; + } + return {target_flags_project(options, profile_name, compiler_override, *value, + file_filter, member), false}; } if (*name == "graph") { diff --git a/src/Main.cpp b/src/Main.cpp index 0cf2d37..615aae0 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1636,6 +1636,17 @@ int execute_daemon_command(std::string_view sub, const DaemonCmdOptions &opts) { } else if (sub == "actions") { request_json = std::format(R"({{"op":"actions","profile":{},"limit":{}}})", Util::json_quote(opts.profile_arg), opts.limit_arg); + } else if (sub == "target_flags") { + if (!opts.target_arg || opts.target_arg->empty()) { + std::cerr << "vbs daemon target flags: --name must not be empty\n"; + return 2; + } + request_json = std::format( + R"({{"op":"target_flags","profile":{},"target":{}{}}})", + Util::json_quote(opts.profile_arg), Util::json_quote(*opts.target_arg), + opts.file_filter_arg + ? std::format(",\"file\":{}", Util::json_quote(*opts.file_filter_arg)) + : std::string{}); } else if (sub == "target_info") { if (!opts.target_arg || opts.target_arg->empty()) { std::cerr << "vbs daemon target: --name must not be empty\n"; @@ -2764,6 +2775,15 @@ int main(int argc, char **argv) { daemon_target_info_cmd .option_default("--profile", "-p", "Profile to evaluate", daemon_opts.profile_arg, "debug") .option("--name", "-n", "Target name", daemon_opts.target_arg); + auto &daemon_target_flags_cmd = daemon_target_cmd.subcommand( + "flags", "Report one target's bounded compile arguments per unit"); + configure_daemon_common(daemon_target_flags_cmd); + daemon_target_flags_cmd + .option_default("--profile", "-p", "Profile to evaluate", daemon_opts.profile_arg, + "debug") + .option("--name", "-n", "Target name", daemon_opts.target_arg) + .option("--file", "", "Only units whose source path ends with this value", + daemon_opts.file_filter_arg); auto &daemon_workspace_cmd = daemon_cmd.subcommand("workspace", "Workspace metadata served by the daemon"); auto &daemon_workspace_members_cmd = @@ -2953,6 +2973,9 @@ int main(int argc, char **argv) { } else if (daemon_sub == "target" && parsed.matched_command_path.size() > 2 && parsed.matched_command_path[2] == "info") { daemon_sub = "target_info"; + } else if (daemon_sub == "target" && parsed.matched_command_path.size() > 2 && + parsed.matched_command_path[2] == "flags") { + daemon_sub = "target_flags"; } return execute_daemon_command(daemon_sub, daemon_opts); } diff --git a/tests/CliContracts.cmake b/tests/CliContracts.cmake index 01454e8..12b19e9 100644 --- a/tests/CliContracts.cmake +++ b/tests/CliContracts.cmake @@ -76,6 +76,7 @@ check_process(0 "Usage: vbs daemon deps .*--profile" "" daemon deps --help) check_process(0 "Usage: vbs daemon info " "" daemon info --help) check_process(0 "Usage: vbs daemon clean " "" daemon clean --help) check_process(0 "Usage: vbs daemon target info .*--name" "" daemon target info --help) +check_process(0 "Usage: vbs daemon target flags .*--name.*--file" "" daemon target flags --help) check_process(0 "Usage: vbs daemon pack .*--output" "" daemon pack --help) check_process(0 "Usage: vbs daemon actions .*--limit" "" daemon actions --help) check_process(0 "Usage: vbs daemon install .*--prefix" "" daemon install --help) diff --git a/tests/DaemonTests.cpp b/tests/DaemonTests.cpp index 16447cc..86ba345 100644 --- a/tests/DaemonTests.cpp +++ b/tests/DaemonTests.cpp @@ -1631,6 +1631,75 @@ VOID_TEST(Daemon, init_scaffolds_project_confined_to_root) { Void::Testing::expect(!bool_field(*escaped, "ok", true)); } +VOID_TEST(Daemon, target_flags_reports_compile_units) { + auto temp = Void::FileSystem::TempDir::open("vbs_daemon_"); + Void::Testing::require(temp.has_value()); + const auto options = make_options(temp->path()); + + { + std::ofstream descriptor{options.project_root / "build.cpp"}; + descriptor << R"cpp(#include + +void build(Void::Build::Project &project) { + auto app = project.executable("app"); + app.sources({"main.cpp"}); +} +)cpp"; + Void::Testing::require(descriptor.good()); + } + { + std::ofstream source{options.project_root / "main.cpp"}; + source << "int main() { return 0; }\n"; + Void::Testing::require(source.good()); + } + + auto server = Void::Build::Daemon::DaemonServer::create(options); + Void::Testing::require(server.has_value()); + const auto socket = server->socket_path(); + + Void::Result::Result run_result; + std::jthread worker{[&] { run_result = server->run(); }}; + Void::Testing::require(wait_for_path(socket, std::chrono::seconds{5})); + + auto all = request_object(socket, R"({"op":"target_flags","target":"app"})", + std::chrono::seconds{120}); + auto filtered = request_object( + socket, R"({"op":"target_flags","target":"app","file":"nope.cpp"})", + std::chrono::seconds{120}); + auto unknown = request_object(socket, R"({"op":"target_flags","target":"nope"})", + std::chrono::seconds{120}); + auto shutdown = Void::Build::Daemon::request(socket, R"({"op":"shutdown"})"); + Void::Testing::expect(shutdown.has_value()); + worker.join(); + Void::Testing::expect(run_result.has_value()); + + Void::Testing::require(all.has_value()); + Void::Testing::expect(bool_field(*all, "ok")); + Void::Testing::expect_eq(str_field(*all, "target"), std::string{"app"}); + const auto *units = field(*all, "units"); + Void::Testing::require(units != nullptr); + const auto *unit_array = std::get_if(&units->value); + Void::Testing::require(unit_array != nullptr && !unit_array->empty()); + const auto *first = std::get_if(&unit_array->front().value); + Void::Testing::require(first != nullptr); + Void::Testing::expect(str_field(*first, "source").find("main.cpp") != std::string::npos); + const auto *arguments = field(*first, "arguments"); + Void::Testing::require(arguments != nullptr); + const auto *argument_array = std::get_if(&arguments->value); + Void::Testing::require(argument_array != nullptr && !argument_array->empty()); + + Void::Testing::require(filtered.has_value()); + Void::Testing::expect(bool_field(*filtered, "ok")); + const auto *filtered_units = field(*filtered, "units"); + Void::Testing::require(filtered_units != nullptr); + const auto *filtered_array = std::get_if(&filtered_units->value); + Void::Testing::require(filtered_array != nullptr); + Void::Testing::expect(filtered_array->empty()); + + Void::Testing::require(unknown.has_value()); + Void::Testing::expect(!bool_field(*unknown, "ok", true)); +} + VOID_TEST(Daemon, describe_empty_project_reports_zero_targets) { auto temp = Void::FileSystem::TempDir::open("vbs_daemon_"); Void::Testing::require(temp.has_value()); diff --git a/tests/RegistryTests.cpp b/tests/RegistryTests.cpp index eb66a23..baef954 100644 --- a/tests/RegistryTests.cpp +++ b/tests/RegistryTests.cpp @@ -320,6 +320,117 @@ VOID_TEST(RegistryTests, registry_rbac_immutability_csrf_xss_web_and_backup_rest } Void::Testing::expect(name_occurrences == 1); } + + const auto first_package_name = [](const std::string &body) { + const std::string key = "\"name\":\""; + const auto start = body.find(key); + if (start == std::string::npos) { + return std::string{}; + } + const auto value_start = start + key.size(); + const auto end = body.find('"', value_start); + return end == std::string::npos ? std::string{} + : body.substr(value_start, end - value_start); + }; + const auto envelope_value = [](const std::string &body, const std::string &key) { + const std::string token = "\"" + key + "\":"; + const auto start = body.find(token); + if (start == std::string::npos) { + return std::string{}; + } + const auto value_start = start + token.size(); + const auto end = body.find_first_of(",}", value_start); + return body.substr(value_start, end - value_start); + }; + const auto count_occurrences = [](const std::string &body, const std::string &token) { + std::size_t count = 0; + for (std::size_t pos = body.find(token); pos != std::string::npos; + pos = body.find(token, pos + 1)) { + ++count; + } + return count; + }; + + // Offset pagination moves to a different package while preserving the total. + auto page_first = send_loopback_http(port, "GET", "/api/v1/packages?limit=1&offset=0"); + auto page_second = send_loopback_http(port, "GET", "/api/v1/packages?limit=1&offset=1"); + Void::Testing::expect(page_first.has_value() && page_first->status == 200); + Void::Testing::expect(page_second.has_value() && page_second->status == 200); + if (page_first && page_second) { + const auto first_name = first_package_name(page_first->body); + const auto second_name = first_package_name(page_second->body); + Void::Testing::expect(!first_name.empty() && !second_name.empty()); + Void::Testing::expect(first_name != second_name); + Void::Testing::expect_eq(envelope_value(page_first->body, "total"), std::string{"2"}); + Void::Testing::expect_eq(envelope_value(page_first->body, "limit"), std::string{"1"}); + Void::Testing::expect_eq(envelope_value(page_first->body, "offset"), std::string{"0"}); + Void::Testing::expect_eq(envelope_value(page_second->body, "total"), std::string{"2"}); + Void::Testing::expect_eq(envelope_value(page_second->body, "limit"), std::string{"1"}); + Void::Testing::expect_eq(envelope_value(page_second->body, "offset"), std::string{"1"}); + Void::Testing::expect(count_occurrences(page_first->body, "\"name\":") == 1); + Void::Testing::expect(count_occurrences(page_second->body, "\"name\":") == 1); + } + + // Search filtering matches the package name... + auto name_search = + send_loopback_http(port, "GET", "/api/v1/packages?q=secret", {{"Cookie", cookie}}); + Void::Testing::expect(name_search.has_value() && name_search->status == 200); + if (name_search) { + Void::Testing::expect(name_search->body.find("secret-pkg") != std::string::npos); + Void::Testing::expect(name_search->body.find("demo-pkg") == std::string::npos); + Void::Testing::expect(name_search->body.find("\"total\":") != std::string::npos); + } + auto public_name_search = send_loopback_http(port, "GET", "/api/v1/packages?q=signed"); + Void::Testing::expect(public_name_search.has_value() && public_name_search->status == 200); + if (public_name_search) { + Void::Testing::expect(public_name_search->body.find("signed-pkg") != std::string::npos); + Void::Testing::expect(public_name_search->body.find("\"total\":1") != std::string::npos); + std::size_t name_occurrences = 0; + for (std::size_t pos = public_name_search->body.find("\"name\":"); pos != std::string::npos; + pos = public_name_search->body.find("\"name\":", pos + 1)) { + ++name_occurrences; + } + Void::Testing::expect(name_occurrences == 1); + } + // ...and the package description. + auto description_search = + send_loopback_http(port, "GET", "/api/v1/packages?q=alert", {{"Cookie", cookie}}); + Void::Testing::expect(description_search.has_value() && description_search->status == 200); + if (description_search) { + Void::Testing::expect(description_search->body.find("secret-pkg") != std::string::npos); + Void::Testing::expect(description_search->body.find("\"total\":1") != std::string::npos); + } + // A query matching neither a name nor a description yields an empty page. + auto no_match_search = send_loopback_http(port, "GET", "/api/v1/packages?q=does-not-exist"); + Void::Testing::expect(no_match_search.has_value() && no_match_search->status == 200); + if (no_match_search) { + Void::Testing::expect(no_match_search->body.find("\"packages\":[]") != std::string::npos); + Void::Testing::expect(no_match_search->body.find("\"total\":0") != std::string::npos); + } + + // An offset past the last package yields an empty page with the total intact. + auto far_page = send_loopback_http(port, "GET", "/api/v1/packages?offset=99"); + Void::Testing::expect(far_page.has_value() && far_page->status == 200); + if (far_page) { + Void::Testing::expect(far_page->body.find("\"packages\":[]") != std::string::npos); + Void::Testing::expect_eq(envelope_value(far_page->body, "total"), std::string{"2"}); + Void::Testing::expect_eq(envelope_value(far_page->body, "offset"), std::string{"99"}); + } + for (const std::string bad_offset_url : + {"/api/v1/packages?offset=abc", "/api/v1/packages?offset=-1", + "/api/v1/packages?offset=1000001"}) { + auto bad_offset = send_loopback_http(port, "GET", bad_offset_url); + Void::Testing::expect(bad_offset.has_value() && bad_offset->status == 400); + if (bad_offset) { + Void::Testing::expect(bad_offset->body.find("invalid_offset") != std::string::npos); + } + } + auto bad_limit_text = send_loopback_http(port, "GET", "/api/v1/packages?limit=abc"); + Void::Testing::expect(bad_limit_text.has_value() && bad_limit_text->status == 400); + if (bad_limit_text) { + Void::Testing::expect(bad_limit_text->body.find("invalid_limit") != std::string::npos); + } + auto bad_limit = send_loopback_http(port, "GET", "/api/v1/packages?limit=501"); Void::Testing::expect(bad_limit.has_value() && bad_limit->status == 400);