feat(daemon,platform): add Unix-socket daemon core, split Linux platform backends, and fix CMake feature-carrier translation
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 7s
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 7s
This commit is contained in:
1 parent
55ea305528
commit
0bde74f739
20 files changed
+1194
-21
No files matched your search
+3
-2
@@ -36,8 +36,8 @@ target_compile_definitions(VoidBuild_Sdk PRIVATE VBS_HAS_VOID_UNICODE=1)
|
||||
|
||||
add_library(VoidBuild_Core STATIC
|
||||
src/Util/Sha256.cpp
|
||||
src/Platform/FileOps.cpp
|
||||
src/Platform/ProcessSupervisor.cpp
|
||||
src/Platform/Linux/FileOps.cpp
|
||||
src/Platform/Linux/ProcessSupervisor.cpp
|
||||
src/Toolchain/Driver.cpp
|
||||
src/Snapshot/Snapshot.cpp
|
||||
src/State/StateStore.cpp
|
||||
@@ -45,6 +45,7 @@ add_library(VoidBuild_Core STATIC
|
||||
src/Graph/Graph.cpp
|
||||
src/Execution/Scheduler.cpp
|
||||
src/Config/Frontend.cpp
|
||||
src/Daemon/Daemon.cpp
|
||||
src/Editor/CompDb.cpp
|
||||
src/Watch/Watcher.cpp
|
||||
src/Package/Toml.cpp
|
||||
|
||||
@@ -105,6 +105,7 @@ All CLI help text (`vbs --help`, `vbs <command> --help`, `vbs compdb --help`, `v
|
||||
- `vbs publish --registry URL --name PKG --version X.Y.Z [--project DIR] [--description TEXT] [--token-env VAR] [--private]`
|
||||
- `vbs bridge --request FILE --output FILE` (backend for [cmake/bridge/VbsDeps.cmake](cmake/bridge/VbsDeps.cmake))
|
||||
- `vbs gc [--build-dir DIR] [--max-bytes N]`
|
||||
- `vbs daemon run|status|stop|gc|recover [--project DIR] [--build-dir DIR] [--socket PATH]` (Unix-socket daemon holding a warm state store and project watcher; `run` serves in the foreground, the rest are client requests)
|
||||
- `vbs gen-tests --input FILE --output-dir DIR`
|
||||
- `vbs-registry --data-dir DIR --web-root DIR [--bind ADDR] [--port PORT] ...`
|
||||
|
||||
|
||||
@@ -24,8 +24,8 @@ void build(Void::Build::Project &project) {
|
||||
core.cxx_standard(Void::Build::CxxStandard::Cxx26)
|
||||
.sources({
|
||||
"src/Util/Sha256.cpp",
|
||||
"src/Platform/FileOps.cpp",
|
||||
"src/Platform/ProcessSupervisor.cpp",
|
||||
"src/Platform/Linux/FileOps.cpp",
|
||||
"src/Platform/Linux/ProcessSupervisor.cpp",
|
||||
"src/Toolchain/Driver.cpp",
|
||||
"src/Snapshot/Snapshot.cpp",
|
||||
"src/State/StateStore.cpp",
|
||||
@@ -33,6 +33,7 @@ void build(Void::Build::Project &project) {
|
||||
"src/Graph/Graph.cpp",
|
||||
"src/Execution/Scheduler.cpp",
|
||||
"src/Config/Frontend.cpp",
|
||||
"src/Daemon/Daemon.cpp",
|
||||
"src/Editor/CompDb.cpp",
|
||||
"src/Watch/Watcher.cpp",
|
||||
"src/Package/Toml.cpp",
|
||||
@@ -150,7 +151,7 @@ void build(Void::Build::Project &project) {
|
||||
|
||||
auto v1_tests = project.test("vbs_v1_tests");
|
||||
v1_tests.cxx_standard(Void::Build::CxxStandard::Cxx26)
|
||||
.sources({"tests/FullV1Tests.cpp"})
|
||||
.sources({"tests/FullV1Tests.cpp", "tests/DaemonTests.cpp"})
|
||||
.depends_on(bootstrap_cfg)
|
||||
.depends_on(cli)
|
||||
.include_directory("$GEN/include", Void::Build::Visibility::Private)
|
||||
|
||||
@@ -6,7 +6,7 @@ Pinned VoidLibrary revision: `3e254055e081a104f08df68dde39711bc7813518` (merged
|
||||
|
||||
| ID | Capability | Upstream Status (`3e254055...`) | VBS Adoption Status |
|
||||
| --- | --- | --- | --- |
|
||||
| `VL-001` | Process group supervision (`Void::Process::spawn`, `communicate_blocking`, `enable_subreaper`) | Implemented | **Adopted** (`src/Platform/ProcessSupervisor.cpp`) |
|
||||
| `VL-001` | Process group supervision (`Void::Process::spawn`, `communicate_blocking`, `enable_subreaper`) | Implemented | **Adopted** (`src/Platform/Linux/ProcessSupervisor.cpp`) |
|
||||
| `VL-002` | TOML 1.0 parser & serializer (`Void::Data::Toml`) | Implemented | **Adopted** (`src/Package/Toml.cpp`) |
|
||||
| `VL-003` | Kernel `inotify` recursive directory watcher (`Void::FileSystem::DirectoryWatcher`) | Implemented | **Adopted** (`src/Watch/Watcher.cpp`, `include/Void/Build/Watch/Watcher.hpp`) |
|
||||
| `VL-004` | Concrete HTTP/1.1 server (`Void::Net::HttpServer`) | Implemented (requires Boost + OpenSSL) | Local loopback POSIX adapter retained for minimal `dev cpp-gcc` (no Boost/OpenSSL) |
|
||||
@@ -15,7 +15,7 @@ Pinned VoidLibrary revision: `3e254055e081a104f08df68dde39711bc7813518` (merged
|
||||
| `VL-007` | Zero-dependency built-in SHA-256 / BLAKE2b (`Void::Crypto::Hasher`) | Implemented (zero external deps when OpenSSL absent) | **Adopted** (`include/Void/Build/Util/Sha256.hpp`, `src/Util/Sha256.cpp`, always linked via `Void::Crypto`) |
|
||||
| `VL-008` | Strict UTF-8 validation (`Void::Json::Strict`, `Void::Unicode::validate_utf8`) | Implemented | **Adopted** (`src/Util/Json.cpp`, `Void::Json::Strict` throughout) |
|
||||
| `VL-009` | Native non-CMake `Void::Testing` registration API | Implemented | **Adopted** (supported alongside `vbs gen-tests` in `src/SelfHost/TestRegistryGen.cpp`) |
|
||||
| `VL-010` | Advisory `FileLock`, `reflink_copy_file`, `set_canonical_mtime`, `atomic_symlink_swap` (`Void::FileSystem`) | Implemented | **Adopted** (`include/Void/Build/Platform/FileOps.hpp`, `src/Platform/FileOps.cpp`) |
|
||||
| `VL-010` | Advisory `FileLock`, `reflink_copy_file`, `set_canonical_mtime`, `atomic_symlink_swap` (`Void::FileSystem`) | Implemented | **Adopted** (`include/Void/Build/Platform/FileOps.hpp`, `src/Platform/Linux/FileOps.cpp`) |
|
||||
| `VL-011a` | Subcommands, `option_many`, `positional_many`, `ParseOutcome::Help` (`Void::Argparse::Parser`) | Implemented | **Adopted** (`src/Main.cpp`, `src/Describe.cpp`, `registry/service/Main.cpp`, `benchmarks/EngineBenchmarks.cpp` — 100% auto-generated help) |
|
||||
| `VL-011b` | Optional SQLite3 FetchContent (`Void::Sqlite`) | Implemented (`VOID_FETCH_SQLITE3`) | Opportunistic when system `SQLite3` is installed (`VOID_FETCH_SQLITE3=OFF` to keep offline configures fast); journaled atomic CAS store retained |
|
||||
| `VL-012` | Naming consistency observation | Noted | VBS strictly uses `Void::Build`, `PascalCase` types/enums/paths, `snake_case` functions/methods |
|
||||
@@ -28,13 +28,13 @@ Pinned VoidLibrary revision: `3e254055e081a104f08df68dde39711bc7813518` (merged
|
||||
|
||||
### Adopted Upstream Capabilities (`VL-001`, `VL-002`, `VL-003`, `VL-006`, `VL-007`, `VL-008`, `VL-009`, `VL-010`, `VL-011a`, `VL-013`)
|
||||
|
||||
- **`VL-001` (`Void::Process`)**: `src/Platform/ProcessSupervisor.cpp` delegates process spawning, pipe multiplexing, timeouts, cancellation, `PR_SET_CHILD_SUBREAPER`, and `-pgid` `SIGTERM -> SIGKILL` termination to `Void::Process::spawn`, `Void::Process::communicate_blocking`, and `Void::Process::enable_subreaper`, adding post-leader process-group drain supervision for detached grandchildren with redirected stdio.
|
||||
- **`VL-001` (`Void::Process`)**: `src/Platform/Linux/ProcessSupervisor.cpp` delegates process spawning, pipe multiplexing, timeouts, cancellation, `PR_SET_CHILD_SUBREAPER`, and `-pgid` `SIGTERM -> SIGKILL` termination to `Void::Process::spawn`, `Void::Process::communicate_blocking`, and `Void::Process::enable_subreaper`, adding post-leader process-group drain supervision for detached grandchildren with redirected stdio.
|
||||
- **`VL-002` (`Void::Data::Toml`)**: `src/Package/Toml.cpp` delegates all TOML 1.0 parsing and canonical table serialization to `Void::Data::Toml::parse` and `Void::Data::Toml::serialize_table`.
|
||||
- **`VL-003` (`Void::FileSystem::DirectoryWatcher`)**: `src/Watch/Watcher.cpp` wraps `Void::FileSystem::DirectoryWatcher` for recursive Linux `inotify` observation, ignore predicates, and `RescanRequired` overflow handling.
|
||||
- **`VL-006` (`Void::Archive`)**: `CMakeLists.txt`, `cmake/VoidDependency.cmake`, `recipes/VoidLibrary/VoidLibraryRecipe.cpp`, and `recipes/SelfHost/VbsSelfHostRecipe.cpp` unconditionally enable `Void::Archive` (`VOID_ARCHIVE_HAS_LIBARCHIVE=0` built-in USTAR/PAX tar), and `src/Package/Archive.cpp` delegates archive creation and staged security-checked extraction to `Void::Archive::create` and `Void::Archive::extract_staged` + `StagedTree::publish`.
|
||||
- **`VL-007` (`Void::Crypto`)**: `Void::Crypto` (`VOID_CRYPTO_HAS_OPENSSL=0` built-in FIPS 180-4 SHA-256) is unconditionally linked, and `src/Util/Sha256.cpp` delegates directly to `Void::Crypto::Hasher`, `Void::Crypto::sha256`, and `Void::Crypto::sha256_file`.
|
||||
- **`VL-008` (`Void::Json::Strict` / `Void::Unicode`)**: Strict UTF-8 validation is active across `Void::Json::Strict` and `src/Util/Json.cpp`.
|
||||
- **`VL-010` (`Void::FileSystem`)**: `src/Platform/FileOps.cpp` delegates `FileLock`, `copy_isolated`, `set_canonical_mtime`, and `atomic_swap_symlink` directly to `Void::FileSystem::FileLock`, `reflink_copy_file`, `set_canonical_mtime`, and `atomic_symlink_swap`.
|
||||
- **`VL-010` (`Void::FileSystem`)**: `src/Platform/Linux/FileOps.cpp` delegates `FileLock`, `copy_isolated`, `set_canonical_mtime`, and `atomic_swap_symlink` directly to `Void::FileSystem::FileLock`, `reflink_copy_file`, `set_canonical_mtime`, and `atomic_symlink_swap`.
|
||||
- **`VL-011a` (`Void::Argparse::Parser`)**: Every VBS executable (`vbs`, `vbs-registry`, `vbs_describe`, `vbs_benchmarks`) uses `Void::Argparse::Parser::parse_detailed()` with native `subcommand()`, `option_many()`, `positional_many()`, and `require_subcommand()` — eliminating all custom help strings, manual `--help` checks, and manual repeatable-argument slicing.
|
||||
- **`VL-013` (`Void::Semver::parse_range`)**: `src/Package/Solver.cpp` calls `Void::Semver::parse_range()` directly without local range normalization.
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Updated: 2026-12-03
|
||||
Branch: main
|
||||
Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B1–B3) + Track E1 + `vbs ide` & `build.cpp` CompDB integration + Track D1/D2 + Track E2 + Track D3 SBOM (Docker GCC 16) complete
|
||||
Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B1–B3) + Track E1 + `vbs ide` & `build.cpp` CompDB integration + Track D1/D2 + Track E2 + Track D3 SBOM (Docker GCC 16) + Track E3 daemon core + Track C1 Linux platform split complete
|
||||
|
||||
## Completed delivery waves
|
||||
|
||||
@@ -11,7 +11,7 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B
|
||||
- Documented 13 reusable VoidLibrary gaps and swappable local adapters in [VOIDLIBRARY_UPSTREAM_REQUESTS.md](../VOIDLIBRARY_UPSTREAM_REQUESTS.md).
|
||||
- **Wave 1 (Plans 01–07 — SDK & Core Native Engine)**:
|
||||
- Expanded declaration SDK (`build.cpp`, `build.profiles.cpp`, `include/Void/Build.hpp`, `src/Build.cpp`).
|
||||
- Built out-of-process host configuration frontend (`src/Config/Frontend.cpp`), dependency-propagating graph lowering (`src/Graph/Graph.cpp`), GCC/Clang toolchain discovery & capability probing (`src/Toolchain/Driver.cpp`), content-verified immutable snapshots (`src/Snapshot/Snapshot.cpp`), process group supervisor (`src/Platform/ProcessSupervisor.cpp`), isolated file ops (`src/Platform/FileOps.cpp`), CAS durable state store (`src/State/StateStore.cpp`), and parallel DAG scheduler (`src/Execution/Scheduler.cpp`).
|
||||
- Built out-of-process host configuration frontend (`src/Config/Frontend.cpp`), dependency-propagating graph lowering (`src/Graph/Graph.cpp`), GCC/Clang toolchain discovery & capability probing (`src/Toolchain/Driver.cpp`), content-verified immutable snapshots (`src/Snapshot/Snapshot.cpp`), process group supervisor (`src/Platform/Linux/ProcessSupervisor.cpp`), isolated file ops (`src/Platform/Linux/FileOps.cpp`), CAS durable state store (`src/State/StateStore.cpp`), and parallel DAG scheduler (`src/Execution/Scheduler.cpp`).
|
||||
- **Wave 2 (Plans 09–10 — Editor CompDB & Watchers)**:
|
||||
- Implemented per-profile `compile_commands.json` projection with monotonic selection tickets, crash recovery, and unrelated root file preservation (`src/Editor/CompDb.cpp`).
|
||||
- Implemented recursive Linux `inotify` watcher (`src/Watch/Watcher.cpp`) with overflow rescan and strict `MetadataOnly` boundary vs `FullBuild`.
|
||||
@@ -70,9 +70,14 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B
|
||||
- Ed25519 package/binary signing remains blocked on an upstream `Void::Crypto` primitive, filed as [Void/Library#36](https://git.faumaray.com/Void/Library/issues/36) and tracked as `VL-014`.
|
||||
- **Docker verification**: `FullV1Tests.sbom_spdx_and_cyclonedx_are_deterministic_and_valid_json` plus a CLI `--sbom` assertion in the workspace test; full CTest suite passes.
|
||||
|
||||
- **Wave 14 (Track E3 Unix-Socket Daemon Core, Track C1 Linux Platform Backend Split, & CMake 4.5 Feature-Carrier Translation Fix)**:
|
||||
- Implemented `Void::Build::Daemon` in `include/Void/Build/Daemon/Daemon.hpp` and `src/Daemon/Daemon.cpp`: a bounded single-threaded Unix-domain-socket daemon that holds a warm `StateStore` and project `InotifyWatcher`, serves strict newline-delimited JSON requests (`ping`, `status`, `gc`, `recover`, `shutdown`), probes and replaces stale sockets, binds with `0600` permissions, recovers watcher overflow via rescan, and removes only its own socket (device/inode checked). Wired `vbs daemon run|status|stop|gc|recover` into `src/Main.cpp` and added `tests/DaemonTests.cpp` (`VOID_TEST(Daemon, ...)`) plus CLI contracts.
|
||||
- Split OS-specific platform implementations into `src/Platform/Linux/` and added `include/Void/Build/Platform/Host.hpp` (`HostOs`, `host_os()`, `host_supported()`); macOS/Windows backends remain planned Track C2/C3 scope.
|
||||
- Fixed bounded CMake translation for CMake 4.5's synthesized `@cmake_cxx_std@(synth_N)` `INTERFACE_LIBRARY` feature carriers in `src/Provider/Translator.cpp`: their standard flag is already lowered from compile groups, so they are skipped instead of reported as untranslated dependency edges. Restored `FullV1Tests.track_b3_foreign_cmake_cxx20_modules_native_translation` on CMake 4.5.
|
||||
|
||||
## 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))**: Live `conan` CLI verification (Track B3), Track C (macOS/Windows ports + dual-profile cross-compilation), Track D3 signing (SBOM done; upstream Ed25519 pending), Track E3 (`vbs daemon` local socket server + external editor plugins), and Track E4 (`Void::Net`/`Void::Sqlite` alignment) remain planned 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))**: Live `conan` CLI verification (Track B3), Track C (macOS/Windows ports + dual-profile cross-compilation), Track D3 signing (SBOM done; upstream Ed25519 available in pin but needs an OpenSSL-enabled verification environment), Track E3 (daemon core done; build-serving requests and external editor plugins remain), and Track E4 (`Void::Net`/`Void::Sqlite` alignment) remain planned scope.
|
||||
|
||||
## Environment notes & upstream boundaries
|
||||
|
||||
|
||||
@@ -20,4 +20,5 @@ Base HEAD: `fe0d1a6`
|
||||
| Wave 11 (Track D1–D2) | Shared HTTP CAS action cache (`/api/v1/cas/{blobs,actions}`, bearer auth, digest verification, portable action keys, `--remote-cache`) + parallel snapshot revalidation hashing | COMPLETE & VERIFIED (Docker GCC 16.0.1, pinned VoidLibrary, 8/8 CTest suites; D1 cross-build-dir 100% cache hit; D2 5,001-file warm no-op 374 ms) | `include/Void/Build/State/RemoteCache.hpp`, `src/State/RemoteCache.cpp`, `StateStore.{hpp,cpp}`, `Scheduler.cpp`, `Snapshot.cpp`, `registry/service/RegistryService.cpp`, `src/Main.cpp`, `tests/RegistryTests.cpp`, docs |
|
||||
| Wave 12 (Track E2 Workspaces) | `workspace.cpp` member declaration/evaluation, shared root `vbs.lock` + `build/.vbs` CAS, `workspace_dependency()` cross-member native linking, `--member` and `--changed-since` selection | COMPLETE & VERIFIED (Docker GCC 16.0.1, 8/8 CTest suites; 3-member fixture with unified lockfile) | `include/Void/Build.hpp`, `src/Build.cpp`, `Config/Frontend.{hpp,cpp}`, `src/Main.cpp`, `src/Package/Fetch.cpp`, `tests/FullV1Tests.cpp`, docs |
|
||||
| Wave 13 (Track D3 SBOM) | Deterministic SPDX 2.3 / CycloneDX 1.5 SBOM from `vbs.lock` packages + `BuildGraph` outputs; `vbs build\|test --sbom FILE --sbom-format spdx\|cyclonedx`; Ed25519 signing blocked upstream | SBOM COMPLETE & VERIFIED (Docker GCC 16, 8/8 CTest suites); signing pending [Void/Library#36](https://git.faumaray.com/Void/Library/issues/36) | `include/Void/Build/Provenance/Sbom.hpp`, `src/Provenance/Sbom.cpp`, `src/Main.cpp`, `tests/FullV1Tests.cpp`, docs |
|
||||
| Future (Plan 20 Slice 3 / Tracks C, D3 signing, E3 daemon, E4, live `conan`) | Live `conan` CLI verification; macOS/Windows/cross-compile; signed provenance; `vbs daemon`, `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) |
|
||||
| Wave 14 (Track E3 daemon core + Track C1 platform split) | Unix-socket `vbs daemon` holding warm `StateStore`/`InotifyWatcher` with `ping/status/gc/recover/shutdown`, CLI + tests; `src/Platform/Linux/` backend split with `HostOs` boundary; CMake 4.5 `@cmake_cxx_std@` feature-carrier translation fix | COMPLETE & VERIFIED (GCC 16.2, pinned VoidLibrary `3e25405`, 8/8 CTest suites) | `include/Void/Build/Daemon/Daemon.hpp`, `src/Daemon/Daemon.cpp`, `tests/DaemonTests.cpp`, `include/Void/Build/Platform/Host.hpp`, `src/Platform/Linux/`, `src/Main.cpp`, `src/Provider/Translator.cpp`, `tests/CliContracts.cmake`, docs |
|
||||
| Future (Plan 20 Slice 3 / Tracks C, D3 signing, E3 daemon build serving, E4, live `conan`) | Live `conan` CLI verification; macOS/Windows/cross-compile; signed provenance; `vbs daemon`, `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) |
|
||||
@@ -191,10 +191,39 @@ Ed25519 package/binary signing is **not** implemented: `Void::Crypto` has no Ed2
|
||||
It is requested upstream as [Void/Library#36](https://git.faumaray.com/Void/Library/issues/36)
|
||||
(`VL-014`) rather than faked with a weaker scheme.
|
||||
|
||||
## Track E3 Daemon Core & Track C1 Platform Split (2026-12-03, `dev cpp-gcc`)
|
||||
|
||||
Environment: GCC 16.2.0, CMake 4.5.0, Ninja 1.13.2. VoidLibrary was exported read-only from the
|
||||
local checkout at the pinned commit `3e254055e081a104f08df68dde39711bc7813518` into
|
||||
`/tmp/opencode/vl-pin` with `git archive` (the working checkout was mid-edit by another agent and
|
||||
was never modified).
|
||||
|
||||
```sh
|
||||
dev cpp-gcc -c cmake -S . -B build/bootstrap -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DVBS_VOID_SOURCE_DIR=/tmp/opencode/vl-pin
|
||||
dev cpp-gcc -c cmake --build build/bootstrap --parallel 8
|
||||
dev cpp-gcc -c ctest --test-dir build/bootstrap --output-on-failure
|
||||
```
|
||||
|
||||
- Build: exit 0.
|
||||
- CTest: **8 / 8 passed (100%) in 169.44 s** (`vbs_core_tests` 12.03 s, `vbs_v1_tests` 58.94 s,
|
||||
`vbs_registry_tests` 9.46 s, `vbs_selfhost_tests` 88.86 s, `vbs_cli_contract` 0.06 s).
|
||||
- `DaemonTests.lifecycle_ping_status_gc_shutdown_and_unknown_op` and
|
||||
`DaemonTests.second_create_reports_already_running` pass inside `vbs_v1_tests`.
|
||||
- Manual CLI smoke: `vbs daemon run` in a temporary project, then `vbs daemon status`, `gc`,
|
||||
`recover`, and `stop` each exited 0 with `{"ok":true,...}` JSON responses; the socket is removed
|
||||
on shutdown. The daemon core does not yet serve build requests.
|
||||
- `src/Provider/Translator.cpp`: CMake 4.5 synthesizes `@cmake_cxx_std@synth_0` INTERFACE_LIBRARY
|
||||
feature carriers. Their standard is already lowered from each consumer's compile groups, so
|
||||
they are skipped instead of reported as untranslated dependency edges.
|
||||
`FullV1Tests.track_b3_foreign_cmake_cxx20_modules_native_translation` passes in 1.68 s after the
|
||||
fix; it failed deterministically before it.
|
||||
- `clang-format --dry-run --Werror` passes on all new/changed C++ files.
|
||||
|
||||
## 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).
|
||||
2. **Conan2 live installation**: `conan` is absent in `dev cpp-gcc`; automated testing verified explicit missing-prerequisite failure (`FullV1Tests.cpp`). Live `conan` container verification (Track B3) remains unrun.
|
||||
3. **Optional external VoidLibrary modules (`Void::Net`, `Void::Sqlite`)**: `Boost`, `OpenSSL`, and `SQLite3` are not installed in `dev cpp-gcc`, so VBS continues using its pure-C++/POSIX loopback HTTP adapters (`HttpServer`, `RegistryClient`) and journaled atomic CAS store (`StateStore`), while retaining optional `Void::Sqlite` CMake detection.
|
||||
4. **CI workflow & Web UI browser**: [.github/workflows/ci.yml](../../.github/workflows/ci.yml) has not been executed on remote GitHub Actions runners, and `registry/web/` was verified via HTTP/header/static-serving/API/XSS/CSRF tests without a headless browser runner.
|
||||
5. **Remaining Post-v1 Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Live `conan` container verification, Track C (Windows/MSVC, macOS/Apple Clang, dual-profile cross-compilation), Track D1/D2 acceptance scenarios (unit/integration suites pass in Docker; see above), Track D3 (SBOM/signatures), Track E2 (`workspace.cpp`), Track E3 (`vbs daemon` local socket server + external editor plugins), and Track E4 (`Void::Net`/`Void::Sqlite` alignment) remain planned scope.
|
||||
5. **Remaining Post-v1 Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Live `conan` container verification, Track C (Windows/MSVC, macOS/Apple Clang, dual-profile cross-compilation), Track D1/D2 acceptance scenarios (unit/integration suites pass in Docker; see above), Track D3 (SBOM/signatures), Track E2 (`workspace.cpp`), Track E3 (daemon core is done; build-serving requests and external editor plugins remain), and Track E4 (`Void::Net`/`Void::Sqlite` alignment) remain planned scope.
|
||||
6. **Track D3 signing / Track C ports**: the pinned VoidLibrary exposes Ed25519 in `Void::Crypto`, but it requires the OpenSSL backend, which is not available in `dev cpp-gcc`; macOS/Windows platform backends are also unverified because no such hosts are available. Both remain unrun rather than claimed.
|
||||
@@ -1,6 +1,6 @@
|
||||
# 21 — Post-v1 Expansion Roadmap
|
||||
|
||||
Status: Active execution guide (Plans **01–19**, **Plan 20 Slices 1–2C**, **Track A [A1–A3]**, **Track B [B1–B3, except live `conan` CLI container]**, **Track E1**, and **Track E3 IDE config/query tooling** are implemented and verified; **Track D1/D2** are implemented and verified in Docker GCC 16 (D1 cross-build-directory 100% cache hit; D2 5,001-file warm no-op 374 ms); **Track E2 (`workspace.cpp`)** is implemented and verified in Docker GCC 16; **Track D3** SBOM emission is implemented (Ed25519 signing pending [Void/Library#36](https://git.faumaray.com/Void/Library/issues/36)); **Track C**, **Track E3 (`vbs daemon`)**, **Track E4**, and live `conan` CLI verification remain planned; see [STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)).
|
||||
Status: Active execution guide (Plans **01–19**, **Plan 20 Slices 1–2C**, **Track A [A1–A3]**, **Track B [B1–B3, except live `conan` CLI container]**, **Track E1**, and **Track E3 IDE config/query tooling** are implemented and verified; **Track D1/D2** are implemented and verified in Docker GCC 16 (D1 cross-build-directory 100% cache hit; D2 5,001-file warm no-op 374 ms); **Track E2 (`workspace.cpp`)** is implemented and verified in Docker GCC 16; **Track D3** SBOM emission is implemented (Ed25519 signing pending [Void/Library#36](https://git.faumaray.com/Void/Library/issues/36)); **Track C** (beyond the Linux backend split), **Track E3 build-serving daemon/editor extensions**, **Track E4**, and live `conan` CLI verification remain planned; see [STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)).
|
||||
|
||||
This roadmap defines five orthogonal expansion tracks for taking VoidBuildSystem from a verified self-hosting Linux C++26 build system into a multi-platform, distributed, daily-driver ecosystem. Each track preserves core architectural invariants: ordinary C++ descriptions, hermetic content-verified snapshots, isolated profiles, immutable CAS publication, and explicit diagnostics over silent approximation.
|
||||
|
||||
@@ -46,7 +46,7 @@ flowchart LR
|
||||
|
||||
| Phase | Concrete Scope | Acceptance Gate |
|
||||
| --- | --- | --- |
|
||||
| **C1 — Platform Backend Split** | Split `src/Platform/` into `Linux/`, `MacOS/`, and `Windows/` behind clean interfaces (`FileOps`, `ProcessSupervisor`, `DirectoryWatcher`), delegating to `Void::System` as upstream adds OS backends. | 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/` with an explicit `HostOs`/`host_supported()` boundary in `include/Void/Build/Platform/Host.hpp`; macOS/Windows backends await real hosts. | 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. |
|
||||
@@ -73,7 +73,7 @@ flowchart LR
|
||||
| --- | --- | --- |
|
||||
| **E1 — Everyday CLI Ergonomics (Implemented in Wave 8)** | `vbs init` project scaffolding, `vbs clean`, `vbs doctor` environment diagnostics, `vbs graph --format dot|json`, and `vbs build --native-foreign`. | End-to-end CLI & integration tests passing in `vbs_cli_contract` and `vbs_v1_tests`. |
|
||||
| **E2 — Multi-Package Workspaces (`workspace.cpp`)** *(verified in Docker GCC 16)* | Shared root `vbs.lock` and `build/.vbs` CAS, `workspace_dependency()` cross-member native linking, and affected-member selection (`vbs build/test --member <pkg>` / `--changed-since <ref>`). | 3-package workspace fixture (shared library + app + tests) builds/tests with one root lockfile; member selection and `--changed-since` verified in `FullV1Tests.workspace_members_shared_build_and_member_selection`. |
|
||||
| **E3 — IDE Config/Query & Background Daemon** | `build.cpp`/`build.profiles.cpp`/`build-support/` SDK entries in `compile_commands.json` + `vbs ide generate` (`.clangd`, `.vscode/`, `.zed/`, `.idea/customTargets.xml`) & `vbs ide query` (**Implemented & Verified in Wave 10**); optional Unix-socket `vbs daemon` holding warm `StateStore`/`RunDigestCache`/`DirectoryWatcher` (**Planned**). | `vbs ide` & `build.cpp` syntax-check verified in `FullV1Tests.cpp`; `vbs daemon` & dedicated editor extensions pending. |
|
||||
| **E3 — IDE Config/Query & Background Daemon** | `build.cpp`/`build.profiles.cpp`/`build-support/` SDK entries in `compile_commands.json` + `vbs ide generate` (`.clangd`, `.vscode/`, `.zed/`, `.idea/customTargets.xml`) & `vbs ide query` (**Implemented & Verified in Wave 10**); Unix-socket daemon core holding a warm `StateStore` + project `DirectoryWatcher` with `vbs daemon run\|status\|stop\|gc\|recover` (**Implemented & Verified in Wave 14**). Build-serving daemon requests and dedicated editor extensions remain planned. | `vbs ide` & `build.cpp` syntax-check verified in `FullV1Tests.cpp`; daemon lifecycle/status/gc/shutdown verified in `DaemonTests.cpp` and CLI contracts. |
|
||||
| **E4 — Transport & Storage Upstream Alignment** | Adopt `Void::Net` (`VL-004`/`VL-005`) and `Void::Sqlite` (`VL-011b`) when lightweight/bundled builds become available in minimal Nix toolchains, reducing VBS transport code further. | All `vbs_registry_tests` and `vbs_core_tests` pass on both minimal and full toolchains. |
|
||||
|
||||
---
|
||||
|
||||
@@ -17,7 +17,7 @@ Authority: [requirements](REQUIREMENTS.md), [architecture](ARCHITECTURE.md),
|
||||
| [03 — Targets, usage requirements and action graph](03-targets-action-graph.md) | Implemented & Verified | [Graph.cpp](../../src/Graph/Graph.cpp) |
|
||||
| [04 — Profiles, target selection and toolchains](04-profiles-toolchains.md) | Implemented & Verified | [Driver.cpp](../../src/Toolchain/Driver.cpp) |
|
||||
| [05 — Immutable snapshots and mutation tracking](05-snapshots-invalidation.md) | Implemented & Verified | [Snapshot.cpp](../../src/Snapshot/Snapshot.cpp) |
|
||||
| [06 — Native execution, scheduling and process lifecycle](06-execution-scheduling.md) | Implemented & Verified | [Scheduler.cpp](../../src/Execution/Scheduler.cpp), [ProcessSupervisor.cpp](../../src/Platform/ProcessSupervisor.cpp) |
|
||||
| [06 — Native execution, scheduling and process lifecycle](06-execution-scheduling.md) | Implemented & Verified | [Scheduler.cpp](../../src/Execution/Scheduler.cpp), [ProcessSupervisor.cpp](../../src/Platform/Linux/ProcessSupervisor.cpp) |
|
||||
| [07 — Transactional state and local artifact cache](07-state-local-cache.md) | Implemented & Verified | [StateStore.cpp](../../src/State/StateStore.cpp) |
|
||||
| [08 — Modules, header units and compiler features](08-modern-cpp.md) | Implemented & Verified | [ModuleScanner.cpp](../../src/Modules/ModuleScanner.cpp) |
|
||||
| [09 — Compilation databases and editor selection](09-compilation-database.md) | Implemented & Verified | [CompDb.cpp](../../src/Editor/CompDb.cpp) |
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Build::Daemon {
|
||||
|
||||
struct DaemonOptions {
|
||||
std::filesystem::path project_root;
|
||||
std::filesystem::path build_root;
|
||||
std::filesystem::path socket_path; // empty => build_root/".vbs/vbs-daemon.sock"
|
||||
std::chrono::milliseconds poll_interval{200};
|
||||
std::size_t max_requests{0}; // 0 => unlimited
|
||||
};
|
||||
|
||||
struct DaemonStatus {
|
||||
std::uint64_t pid{};
|
||||
std::uint64_t uptime_ms{};
|
||||
std::size_t recorded_actions{};
|
||||
std::size_t watched_directories{};
|
||||
std::uint64_t watch_events{};
|
||||
std::string last_event_path;
|
||||
std::uint64_t sequence{};
|
||||
};
|
||||
|
||||
// Bounded single-threaded Unix-domain-socket daemon holding a warm StateStore and
|
||||
// InotifyWatcher for the project root (Track E3). Requests are one JSON object per
|
||||
// line; responses are one JSON object per line.
|
||||
class DaemonServer {
|
||||
public:
|
||||
~DaemonServer();
|
||||
DaemonServer(const DaemonServer &) = delete;
|
||||
DaemonServer &operator=(const DaemonServer &) = delete;
|
||||
DaemonServer(DaemonServer &&) noexcept;
|
||||
DaemonServer &operator=(DaemonServer &&) noexcept;
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<DaemonServer, Void::Result::Error>
|
||||
create(DaemonOptions options);
|
||||
|
||||
// Serves until `stop` is requested, a `shutdown` request arrives, or max_requests is hit.
|
||||
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> run(std::stop_token stop = {});
|
||||
|
||||
[[nodiscard]] const std::filesystem::path &socket_path() const noexcept;
|
||||
[[nodiscard]] DaemonStatus status() const;
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
explicit DaemonServer(std::unique_ptr<Impl> impl) noexcept;
|
||||
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
// Sends one newline-delimited JSON request and returns the response line.
|
||||
[[nodiscard]] Void::Result::Result<std::string, Void::Result::Error>
|
||||
request(const std::filesystem::path &socket_path, std::string_view request_json,
|
||||
std::chrono::milliseconds timeout = std::chrono::milliseconds{2000});
|
||||
|
||||
} // namespace Void::Build::Daemon
|
||||
@@ -0,0 +1,40 @@
|
||||
#pragma once
|
||||
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Build::Platform {
|
||||
|
||||
// The host operating system this build of VoidBuildSystem runs on.
|
||||
enum class HostOs { Linux, MacOS, Windows, Unknown };
|
||||
|
||||
[[nodiscard]] constexpr HostOs host_os() noexcept {
|
||||
#if defined(__linux__)
|
||||
return HostOs::Linux;
|
||||
#elif defined(__APPLE__)
|
||||
return HostOs::MacOS;
|
||||
#elif defined(_WIN32)
|
||||
return HostOs::Windows;
|
||||
#else
|
||||
return HostOs::Unknown;
|
||||
#endif
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::string_view host_os_name(HostOs os) noexcept {
|
||||
switch (os) {
|
||||
case HostOs::Linux:
|
||||
return "Linux";
|
||||
case HostOs::MacOS:
|
||||
return "macOS";
|
||||
case HostOs::Windows:
|
||||
return "Windows";
|
||||
case HostOs::Unknown:
|
||||
break;
|
||||
}
|
||||
return "Unknown";
|
||||
}
|
||||
|
||||
// macOS/Windows ports are planned (Track C2/C3); the process and file backends
|
||||
// currently support Linux hosts only.
|
||||
[[nodiscard]] constexpr bool host_supported() noexcept { return host_os() == HostOs::Linux; }
|
||||
|
||||
} // namespace Void::Build::Platform
|
||||
@@ -76,8 +76,8 @@ add_vbs_selfhost_native(Project &project, const VbsSelfHostConfig &config) {
|
||||
|
||||
const std::vector<std::string> core_sources = {
|
||||
"src/Util/Sha256.cpp",
|
||||
"src/Platform/FileOps.cpp",
|
||||
"src/Platform/ProcessSupervisor.cpp",
|
||||
"src/Platform/Linux/FileOps.cpp",
|
||||
"src/Platform/Linux/ProcessSupervisor.cpp",
|
||||
"src/Toolchain/Driver.cpp",
|
||||
"src/Snapshot/Snapshot.cpp",
|
||||
"src/State/StateStore.cpp",
|
||||
@@ -85,6 +85,7 @@ add_vbs_selfhost_native(Project &project, const VbsSelfHostConfig &config) {
|
||||
"src/Graph/Graph.cpp",
|
||||
"src/Execution/Scheduler.cpp",
|
||||
"src/Config/Frontend.cpp",
|
||||
"src/Daemon/Daemon.cpp",
|
||||
"src/Editor/CompDb.cpp",
|
||||
"src/Watch/Watcher.cpp",
|
||||
"src/Package/Toml.cpp",
|
||||
|
||||
@@ -0,0 +1,691 @@
|
||||
#include <Void/Build/Daemon/Daemon.hpp>
|
||||
|
||||
#include <Void/Build/State/StateStore.hpp>
|
||||
#include <Void/Build/Watch/Watcher.hpp>
|
||||
#include <Void/Data/StrictJson.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <fcntl.h>
|
||||
#include <format>
|
||||
#include <limits>
|
||||
#include <poll.h>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/un.h>
|
||||
#include <system_error>
|
||||
#include <unistd.h>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
|
||||
namespace Void::Build::Daemon {
|
||||
namespace {
|
||||
|
||||
using JsonValue = Void::Json::Strict::Value;
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
constexpr std::size_t kMaxRequestBytes = 64U * 1024U;
|
||||
constexpr std::size_t kMaxJsonDepth = 16U;
|
||||
constexpr int kListenBacklog = 8;
|
||||
constexpr auto kClientIoTimeout = std::chrono::milliseconds{2000};
|
||||
constexpr auto kProbeTimeout = std::chrono::milliseconds{1000};
|
||||
|
||||
Void::Result::Error make_error(Void::Result::ErrorKind kind, std::string message,
|
||||
int system_errno = 0) {
|
||||
std::error_code sys{};
|
||||
if (system_errno != 0) {
|
||||
sys = std::error_code{system_errno, std::system_category()};
|
||||
}
|
||||
return Void::Result::Error{kind, std::move(message), {}, sys};
|
||||
}
|
||||
|
||||
int poll_timeout_ms(std::chrono::milliseconds timeout) noexcept {
|
||||
if (timeout.count() <= 0) {
|
||||
return 0;
|
||||
}
|
||||
const auto maximum = static_cast<long long>(std::numeric_limits<int>::max());
|
||||
return timeout.count() > maximum ? std::numeric_limits<int>::max()
|
||||
: static_cast<int>(timeout.count());
|
||||
}
|
||||
|
||||
class UniqueFd {
|
||||
public:
|
||||
UniqueFd() = default;
|
||||
explicit UniqueFd(int fd) noexcept : fd_{fd} {}
|
||||
~UniqueFd() { reset(); }
|
||||
|
||||
UniqueFd(const UniqueFd &) = delete;
|
||||
UniqueFd &operator=(const UniqueFd &) = delete;
|
||||
|
||||
UniqueFd(UniqueFd &&other) noexcept : fd_{std::exchange(other.fd_, -1)} {}
|
||||
UniqueFd &operator=(UniqueFd &&other) noexcept {
|
||||
if (this != &other) {
|
||||
reset(std::exchange(other.fd_, -1));
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
[[nodiscard]] int get() const noexcept { return fd_; }
|
||||
[[nodiscard]] bool valid() const noexcept { return fd_ >= 0; }
|
||||
|
||||
int release() noexcept { return std::exchange(fd_, -1); }
|
||||
|
||||
void reset(int fd = -1) noexcept {
|
||||
if (fd_ >= 0) {
|
||||
::close(fd_);
|
||||
}
|
||||
fd_ = fd;
|
||||
}
|
||||
|
||||
private:
|
||||
int fd_{-1};
|
||||
};
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error> set_close_on_exec(int fd) {
|
||||
const int flags = ::fcntl(fd, F_GETFD);
|
||||
if (flags < 0) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: fcntl(F_GETFD) failed", errno)};
|
||||
}
|
||||
if (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::io,
|
||||
"daemon: fcntl(F_SETFD, FD_CLOEXEC) failed", errno)};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<sockaddr_un, Void::Result::Error>
|
||||
make_address(const std::filesystem::path &socket_path) {
|
||||
const std::string text = socket_path.string();
|
||||
if (text.empty()) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: socket path must not be empty")};
|
||||
}
|
||||
sockaddr_un address{};
|
||||
address.sun_family = AF_UNIX;
|
||||
if (text.size() >= sizeof(address.sun_path)) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::invalid_argument,
|
||||
std::format("daemon: socket path '{}' is {} bytes; a Unix socket address holds at "
|
||||
"most {} bytes including the terminator",
|
||||
text, text.size(), sizeof(address.sun_path) - 1))};
|
||||
}
|
||||
std::memcpy(address.sun_path, text.c_str(), text.size() + 1);
|
||||
return address;
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error> write_all(int fd, std::string_view data) {
|
||||
while (!data.empty()) {
|
||||
const ssize_t written = ::send(fd, data.data(), data.size(), MSG_NOSIGNAL);
|
||||
if (written < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: send failed", errno)};
|
||||
}
|
||||
data.remove_prefix(static_cast<std::size_t>(written));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string, Void::Result::Error>
|
||||
read_line(int fd, std::chrono::milliseconds timeout) {
|
||||
const auto deadline = Clock::now() + timeout;
|
||||
std::string line;
|
||||
line.reserve(256);
|
||||
char buffer[4096];
|
||||
|
||||
while (true) {
|
||||
if (const auto newline = line.find('\n'); newline != std::string::npos) {
|
||||
line.resize(newline);
|
||||
if (!line.empty() && line.back() == '\r') {
|
||||
line.pop_back();
|
||||
}
|
||||
return line;
|
||||
}
|
||||
if (line.size() > kMaxRequestBytes) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: request exceeds 64 KiB")};
|
||||
}
|
||||
|
||||
auto remaining =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(deadline - Clock::now());
|
||||
if (remaining.count() < 0) {
|
||||
remaining = std::chrono::milliseconds{0};
|
||||
}
|
||||
pollfd descriptor{fd, POLLIN, 0};
|
||||
const int ready = ::poll(&descriptor, 1, poll_timeout_ms(remaining));
|
||||
if (ready < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: poll failed", errno)};
|
||||
}
|
||||
if (ready == 0) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::timeout,
|
||||
"daemon: timed out waiting for request line")};
|
||||
}
|
||||
|
||||
const ssize_t count = ::read(fd, buffer, sizeof(buffer));
|
||||
if (count < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: read failed", errno)};
|
||||
}
|
||||
if (count == 0) {
|
||||
if (line.empty()) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::io,
|
||||
"daemon: connection closed before request")};
|
||||
}
|
||||
return line;
|
||||
}
|
||||
line.append(buffer, static_cast<std::size_t>(count));
|
||||
if (line.size() > kMaxRequestBytes) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: request exceeds 64 KiB")};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<UniqueFd, Void::Result::Error>
|
||||
connect_socket(const std::filesystem::path &socket_path, std::chrono::milliseconds timeout) {
|
||||
auto address = make_address(socket_path);
|
||||
if (!address) {
|
||||
return std::unexpected{std::move(address.error())};
|
||||
}
|
||||
|
||||
UniqueFd fd{::socket(AF_UNIX, SOCK_STREAM, 0)};
|
||||
if (!fd.valid()) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: socket() failed", errno)};
|
||||
}
|
||||
if (auto cloexec = set_close_on_exec(fd.get()); !cloexec) {
|
||||
return std::unexpected{std::move(cloexec.error())};
|
||||
}
|
||||
|
||||
const int flags = ::fcntl(fd.get(), F_GETFL);
|
||||
if (flags < 0 || ::fcntl(fd.get(), F_SETFL, flags | O_NONBLOCK) < 0) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: fcntl(F_SETFL) failed", errno)};
|
||||
}
|
||||
|
||||
int result =
|
||||
::connect(fd.get(), reinterpret_cast<const sockaddr *>(&*address), sizeof(sockaddr_un));
|
||||
if (result < 0 && errno != EINPROGRESS) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot connect to '{}'", socket_path.string()), errno)};
|
||||
}
|
||||
if (result < 0) {
|
||||
pollfd descriptor{fd.get(), POLLOUT, 0};
|
||||
const int ready = ::poll(&descriptor, 1, poll_timeout_ms(timeout));
|
||||
if (ready < 0) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: poll failed", errno)};
|
||||
}
|
||||
if (ready == 0) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::timeout,
|
||||
"daemon: timed out connecting to socket")};
|
||||
}
|
||||
int socket_error = 0;
|
||||
socklen_t length = sizeof(socket_error);
|
||||
if (::getsockopt(fd.get(), SOL_SOCKET, SO_ERROR, &socket_error, &length) < 0) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: getsockopt failed", errno)};
|
||||
}
|
||||
if (socket_error != 0) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot connect to '{}'", socket_path.string()), socket_error)};
|
||||
}
|
||||
}
|
||||
|
||||
if (::fcntl(fd.get(), F_SETFL, flags) < 0) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: fcntl restore failed", errno)};
|
||||
}
|
||||
return fd;
|
||||
}
|
||||
|
||||
std::string serialize_response(const JsonValue &value) {
|
||||
auto serialized = Void::Json::Strict::serialize(value);
|
||||
if (serialized) {
|
||||
return *serialized;
|
||||
}
|
||||
return R"({"ok":false,"error":"daemon: response serialization failed"})";
|
||||
}
|
||||
|
||||
std::string error_response(std::string_view message) {
|
||||
JsonValue::Object object;
|
||||
object.emplace("ok", JsonValue{false});
|
||||
object.emplace("error", JsonValue{std::string{message}});
|
||||
return serialize_response(JsonValue{std::move(object)});
|
||||
}
|
||||
|
||||
std::string ok_response(std::string_view op) {
|
||||
JsonValue::Object object;
|
||||
object.emplace("ok", JsonValue{true});
|
||||
object.emplace("op", JsonValue{std::string{op}});
|
||||
return serialize_response(JsonValue{std::move(object)});
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
struct DaemonServer::Impl {
|
||||
struct DispatchResult {
|
||||
std::string response;
|
||||
bool shutdown{false};
|
||||
};
|
||||
|
||||
Impl(DaemonOptions daemon_options, std::filesystem::path path, State::StateStore state,
|
||||
Watch::InotifyWatcher project_watcher)
|
||||
: options{std::move(daemon_options)}, socket_path{std::move(path)},
|
||||
state_store{std::move(state)}, watcher{std::move(project_watcher)},
|
||||
started{Clock::now()} {}
|
||||
|
||||
~Impl() { close_socket(); }
|
||||
|
||||
Impl(const Impl &) = delete;
|
||||
Impl &operator=(const Impl &) = delete;
|
||||
|
||||
[[nodiscard]] DaemonStatus current_status() const;
|
||||
[[nodiscard]] std::string status_response() const;
|
||||
DispatchResult dispatch(std::string_view line);
|
||||
|
||||
void close_socket() noexcept {
|
||||
if (listen_fd >= 0) {
|
||||
::close(listen_fd);
|
||||
listen_fd = -1;
|
||||
}
|
||||
if (!created_socket) {
|
||||
return;
|
||||
}
|
||||
created_socket = false;
|
||||
struct stat current{};
|
||||
if (::lstat(socket_path.c_str(), ¤t) == 0 && current.st_dev == socket_device &&
|
||||
current.st_ino == socket_inode) {
|
||||
::unlink(socket_path.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
DaemonOptions options;
|
||||
std::filesystem::path socket_path;
|
||||
State::StateStore state_store;
|
||||
Watch::InotifyWatcher watcher;
|
||||
Clock::time_point started;
|
||||
int listen_fd{-1};
|
||||
bool created_socket{false};
|
||||
dev_t socket_device{};
|
||||
ino_t socket_inode{};
|
||||
std::uint64_t watch_events{0};
|
||||
std::string last_event_path;
|
||||
std::uint64_t sequence{0};
|
||||
};
|
||||
|
||||
DaemonStatus DaemonServer::Impl::current_status() const {
|
||||
DaemonStatus status;
|
||||
status.pid = static_cast<std::uint64_t>(::getpid());
|
||||
status.uptime_ms = static_cast<std::uint64_t>(
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - started).count());
|
||||
status.recorded_actions = state_store.recorded_action_count();
|
||||
status.watched_directories = watcher.watched_directory_count();
|
||||
status.watch_events = watch_events;
|
||||
status.last_event_path = last_event_path;
|
||||
status.sequence = sequence;
|
||||
return status;
|
||||
}
|
||||
|
||||
std::string DaemonServer::Impl::status_response() const {
|
||||
const DaemonStatus status = current_status();
|
||||
JsonValue::Object object;
|
||||
object.emplace("ok", JsonValue{true});
|
||||
object.emplace("op", JsonValue{std::string{"status"}});
|
||||
object.emplace("pid", JsonValue{static_cast<std::int64_t>(status.pid)});
|
||||
object.emplace("uptime_ms", JsonValue{static_cast<std::int64_t>(status.uptime_ms)});
|
||||
object.emplace("recorded_actions",
|
||||
JsonValue{static_cast<std::int64_t>(status.recorded_actions)});
|
||||
object.emplace("watched_directories",
|
||||
JsonValue{static_cast<std::int64_t>(status.watched_directories)});
|
||||
object.emplace("watch_events", JsonValue{static_cast<std::int64_t>(status.watch_events)});
|
||||
object.emplace("last_event_path", JsonValue{status.last_event_path});
|
||||
object.emplace("sequence", JsonValue{static_cast<std::int64_t>(status.sequence)});
|
||||
return serialize_response(JsonValue{std::move(object)});
|
||||
}
|
||||
|
||||
DaemonServer::Impl::DispatchResult DaemonServer::Impl::dispatch(std::string_view line) {
|
||||
auto parsed = Void::Json::Strict::parse(line, kMaxJsonDepth);
|
||||
if (!parsed) {
|
||||
return {error_response(std::format("malformed JSON: {}", parsed.error().message)), false};
|
||||
}
|
||||
const auto *object = std::get_if<JsonValue::Object>(&parsed->value);
|
||||
if (object == nullptr) {
|
||||
return {error_response("request must be a JSON object"), false};
|
||||
}
|
||||
const auto op = object->find("op");
|
||||
if (op == object->end()) {
|
||||
return {error_response("request is missing \"op\""), false};
|
||||
}
|
||||
const auto *name = std::get_if<std::string>(&op->second.value);
|
||||
if (name == nullptr) {
|
||||
return {error_response("\"op\" must be a string"), false};
|
||||
}
|
||||
|
||||
if (*name == "ping") {
|
||||
return {ok_response("ping"), false};
|
||||
}
|
||||
if (*name == "status") {
|
||||
return {status_response(), false};
|
||||
}
|
||||
if (*name == "shutdown") {
|
||||
return {ok_response("shutdown"), true};
|
||||
}
|
||||
if (*name == "gc") {
|
||||
std::uint64_t max_bytes = 0;
|
||||
if (const auto entry = object->find("max_bytes"); entry != object->end()) {
|
||||
const auto *value = std::get_if<std::int64_t>(&entry->second.value);
|
||||
if (value == nullptr) {
|
||||
return {error_response("\"max_bytes\" must be an integer"), false};
|
||||
}
|
||||
if (*value < 0) {
|
||||
return {error_response("\"max_bytes\" must be non-negative"), false};
|
||||
}
|
||||
max_bytes = static_cast<std::uint64_t>(*value);
|
||||
}
|
||||
auto stats = state_store.gc(max_bytes);
|
||||
if (!stats) {
|
||||
return {error_response(stats.error().format()), false};
|
||||
}
|
||||
JsonValue::Object response;
|
||||
response.emplace("ok", JsonValue{true});
|
||||
response.emplace("op", JsonValue{std::string{"gc"}});
|
||||
response.emplace("removed_blobs",
|
||||
JsonValue{static_cast<std::int64_t>(stats->removed_blobs)});
|
||||
response.emplace("freed_bytes", JsonValue{static_cast<std::int64_t>(stats->freed_bytes)});
|
||||
response.emplace("retained_blobs",
|
||||
JsonValue{static_cast<std::int64_t>(stats->retained_blobs)});
|
||||
response.emplace("cleaned_staging_files",
|
||||
JsonValue{static_cast<std::int64_t>(stats->cleaned_staging_files)});
|
||||
return {serialize_response(JsonValue{std::move(response)}), false};
|
||||
}
|
||||
if (*name == "recover") {
|
||||
auto recovered = state_store.recover();
|
||||
if (!recovered) {
|
||||
return {error_response(recovered.error().format()), false};
|
||||
}
|
||||
JsonValue::Object response;
|
||||
response.emplace("ok", JsonValue{true});
|
||||
response.emplace("op", JsonValue{std::string{"recover"}});
|
||||
response.emplace("recovered", JsonValue{static_cast<std::int64_t>(*recovered)});
|
||||
return {serialize_response(JsonValue{std::move(response)}), false};
|
||||
}
|
||||
|
||||
return {error_response(std::format("unknown op '{}'", *name)), false};
|
||||
}
|
||||
|
||||
DaemonServer::DaemonServer(std::unique_ptr<Impl> impl) noexcept : impl_{std::move(impl)} {}
|
||||
|
||||
DaemonServer::~DaemonServer() = default;
|
||||
DaemonServer::DaemonServer(DaemonServer &&) noexcept = default;
|
||||
DaemonServer &DaemonServer::operator=(DaemonServer &&) noexcept = default;
|
||||
|
||||
Void::Result::Result<DaemonServer, Void::Result::Error>
|
||||
DaemonServer::create(DaemonOptions options) {
|
||||
if (options.project_root.empty()) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: project_root must not be empty")};
|
||||
}
|
||||
if (options.build_root.empty()) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: build_root must not be empty")};
|
||||
}
|
||||
if (options.poll_interval.count() < 0) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: poll_interval must be non-negative")};
|
||||
}
|
||||
|
||||
std::filesystem::path socket_path = options.socket_path;
|
||||
if (socket_path.empty()) {
|
||||
socket_path = options.build_root / ".vbs" / "vbs-daemon.sock";
|
||||
}
|
||||
auto address = make_address(socket_path);
|
||||
if (!address) {
|
||||
return std::unexpected{std::move(address.error())};
|
||||
}
|
||||
|
||||
auto state_store = State::StateStore::open(options.build_root / ".vbs");
|
||||
if (!state_store) {
|
||||
return std::unexpected{state_store.error().with_context("daemon: opening state store")};
|
||||
}
|
||||
auto watcher = Watch::InotifyWatcher::create(options.project_root);
|
||||
if (!watcher) {
|
||||
return std::unexpected{watcher.error().with_context("daemon: creating project watcher")};
|
||||
}
|
||||
|
||||
std::error_code ec;
|
||||
if (socket_path.has_parent_path()) {
|
||||
std::filesystem::create_directories(socket_path.parent_path(), ec);
|
||||
if (ec) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot create socket directory '{}': {}",
|
||||
socket_path.parent_path().string(), ec.message()))};
|
||||
}
|
||||
}
|
||||
|
||||
const auto existing = std::filesystem::symlink_status(socket_path, ec);
|
||||
if (ec && ec != std::errc::no_such_file_or_directory) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot inspect socket path '{}': {}",
|
||||
socket_path.string(), ec.message()))};
|
||||
}
|
||||
if (!ec && std::filesystem::exists(existing)) {
|
||||
const auto probe = request(socket_path, R"({"op":"ping"})", kProbeTimeout);
|
||||
bool live = false;
|
||||
if (probe) {
|
||||
auto parsed = Void::Json::Strict::parse(*probe, kMaxJsonDepth);
|
||||
if (parsed) {
|
||||
if (const auto *object = std::get_if<JsonValue::Object>(&parsed->value)) {
|
||||
if (const auto ok = object->find("ok");
|
||||
ok != object->end() && std::get_if<bool>(&ok->second.value) != nullptr &&
|
||||
std::get<bool>(ok->second.value)) {
|
||||
live = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (live) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::conflict,
|
||||
std::format("daemon: already running at '{}'", socket_path.string()))};
|
||||
}
|
||||
if (!std::filesystem::is_socket(existing)) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::conflict,
|
||||
std::format("daemon: '{}' exists and is not a socket", socket_path.string()))};
|
||||
}
|
||||
std::filesystem::remove(socket_path, ec);
|
||||
if (ec) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot remove stale socket '{}': {}",
|
||||
socket_path.string(), ec.message()))};
|
||||
}
|
||||
}
|
||||
|
||||
UniqueFd listen_fd{::socket(AF_UNIX, SOCK_STREAM, 0)};
|
||||
if (!listen_fd.valid()) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: socket() failed", errno)};
|
||||
}
|
||||
if (auto cloexec = set_close_on_exec(listen_fd.get()); !cloexec) {
|
||||
return std::unexpected{std::move(cloexec.error())};
|
||||
}
|
||||
|
||||
bool bound = false;
|
||||
const auto unlink_if_bound = [&]() noexcept {
|
||||
if (bound) {
|
||||
::unlink(socket_path.c_str());
|
||||
}
|
||||
};
|
||||
|
||||
if (::bind(listen_fd.get(), reinterpret_cast<const sockaddr *>(&*address),
|
||||
sizeof(sockaddr_un)) < 0) {
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot bind '{}'", socket_path.string()), errno)};
|
||||
}
|
||||
bound = true;
|
||||
|
||||
if (::chmod(socket_path.c_str(), 0600) < 0) {
|
||||
const int saved = errno;
|
||||
unlink_if_bound();
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot chmod socket '{}'", socket_path.string()), saved)};
|
||||
}
|
||||
if (::listen(listen_fd.get(), kListenBacklog) < 0) {
|
||||
const int saved = errno;
|
||||
unlink_if_bound();
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot listen on '{}'", socket_path.string()), saved)};
|
||||
}
|
||||
|
||||
struct stat socket_stat{};
|
||||
if (::lstat(socket_path.c_str(), &socket_stat) != 0) {
|
||||
const int saved = errno;
|
||||
unlink_if_bound();
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::io,
|
||||
std::format("daemon: cannot stat socket '{}'", socket_path.string()), saved)};
|
||||
}
|
||||
|
||||
auto impl = std::make_unique<Impl>(std::move(options), socket_path, std::move(*state_store),
|
||||
std::move(*watcher));
|
||||
impl->listen_fd = listen_fd.release();
|
||||
impl->created_socket = true;
|
||||
impl->socket_device = socket_stat.st_dev;
|
||||
impl->socket_inode = socket_stat.st_ino;
|
||||
return DaemonServer{std::move(impl)};
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error> DaemonServer::run(std::stop_token stop) {
|
||||
if (!impl_) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: server has been moved from")};
|
||||
}
|
||||
auto &impl = *impl_;
|
||||
if (impl.listen_fd < 0) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: server is not listening")};
|
||||
}
|
||||
|
||||
std::size_t served = 0;
|
||||
bool shutdown_requested = false;
|
||||
while (!stop.stop_requested() && !shutdown_requested &&
|
||||
(impl.options.max_requests == 0 || served < impl.options.max_requests)) {
|
||||
pollfd descriptor{impl.listen_fd, POLLIN, 0};
|
||||
const int ready = ::poll(&descriptor, 1, poll_timeout_ms(impl.options.poll_interval));
|
||||
if (ready < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
impl.close_socket();
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: poll failed", errno)};
|
||||
}
|
||||
|
||||
if (ready > 0 && (descriptor.revents & POLLIN) != 0) {
|
||||
sockaddr_un peer{};
|
||||
socklen_t peer_length = sizeof(peer);
|
||||
const int client =
|
||||
::accept(impl.listen_fd, reinterpret_cast<sockaddr *>(&peer), &peer_length);
|
||||
if (client < 0) {
|
||||
if (errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK) {
|
||||
impl.close_socket();
|
||||
return std::unexpected{
|
||||
make_error(Void::Result::ErrorKind::io, "daemon: accept failed", errno)};
|
||||
}
|
||||
} else {
|
||||
UniqueFd client_fd{client};
|
||||
if (auto cloexec = set_close_on_exec(client_fd.get()); !cloexec) {
|
||||
continue;
|
||||
}
|
||||
auto line = read_line(client_fd.get(), kClientIoTimeout);
|
||||
if (line) {
|
||||
Impl::DispatchResult result = impl.dispatch(*line);
|
||||
static_cast<void>(write_all(client_fd.get(), result.response + "\n"));
|
||||
++served;
|
||||
shutdown_requested = result.shutdown;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto batch =
|
||||
impl.watcher.poll_events(std::chrono::milliseconds{0}, std::chrono::milliseconds{0});
|
||||
if (!batch) {
|
||||
// Watcher failures are surfaced through the next scan; the daemon stays alive.
|
||||
continue;
|
||||
}
|
||||
if (batch->overflowed || batch->rescan_required) {
|
||||
static_cast<void>(impl.watcher.rescan_watches());
|
||||
++impl.sequence;
|
||||
}
|
||||
if (!batch->changed_paths.empty()) {
|
||||
impl.watch_events += batch->changed_paths.size();
|
||||
impl.last_event_path = batch->changed_paths.back().string();
|
||||
++impl.sequence;
|
||||
}
|
||||
}
|
||||
impl.close_socket();
|
||||
return {};
|
||||
}
|
||||
|
||||
const std::filesystem::path &DaemonServer::socket_path() const noexcept {
|
||||
static const std::filesystem::path empty;
|
||||
return impl_ ? impl_->socket_path : empty;
|
||||
}
|
||||
|
||||
DaemonStatus DaemonServer::status() const {
|
||||
if (!impl_) {
|
||||
return {};
|
||||
}
|
||||
return impl_->current_status();
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string, Void::Result::Error>
|
||||
request(const std::filesystem::path &socket_path, std::string_view request_json,
|
||||
std::chrono::milliseconds timeout) {
|
||||
if (request_json.find('\n') != std::string_view::npos ||
|
||||
request_json.find('\r') != std::string_view::npos) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: request must be a single JSON line")};
|
||||
}
|
||||
if (request_json.size() > kMaxRequestBytes) {
|
||||
return std::unexpected{make_error(Void::Result::ErrorKind::invalid_argument,
|
||||
"daemon: request exceeds 64 KiB")};
|
||||
}
|
||||
|
||||
auto fd = connect_socket(socket_path, timeout);
|
||||
if (!fd) {
|
||||
return std::unexpected{std::move(fd.error())};
|
||||
}
|
||||
std::string payload{request_json};
|
||||
payload.push_back('\n');
|
||||
if (auto written = write_all(fd->get(), payload); !written) {
|
||||
return std::unexpected{std::move(written.error())};
|
||||
}
|
||||
return read_line(fd->get(), timeout);
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Daemon
|
||||
+132
@@ -2,6 +2,7 @@
|
||||
#include <Void/Build/BootstrapConfig.hpp>
|
||||
#include <Void/Build/Bridge/CMakeBridge.hpp>
|
||||
#include <Void/Build/Config/Frontend.hpp>
|
||||
#include <Void/Build/Daemon/Daemon.hpp>
|
||||
#include <Void/Build/Editor/CompDb.hpp>
|
||||
#include <Void/Build/Execution/Scheduler.hpp>
|
||||
#include <Void/Build/Graph/Graph.hpp>
|
||||
@@ -26,6 +27,7 @@
|
||||
#include <Void/Build/Watch/Watcher.hpp>
|
||||
#include <Void/Configuration/Argparse.hpp>
|
||||
#include <Void/Configuration/Env.hpp>
|
||||
#include <Void/Data/StrictJson.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/System/SignalWatcher.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
@@ -1529,6 +1531,109 @@ int execute_gc_command(const GcCmdOptions &opts) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct DaemonCmdOptions {
|
||||
std::string project_arg;
|
||||
std::optional<std::string> build_arg;
|
||||
std::optional<std::string> socket_arg;
|
||||
std::string max_bytes_arg{"0"};
|
||||
std::string max_requests_arg{"0"};
|
||||
};
|
||||
|
||||
std::filesystem::path resolve_daemon_socket(const DaemonCmdOptions &opts,
|
||||
const std::filesystem::path &build_root) {
|
||||
return opts.socket_arg ? std::filesystem::path{*opts.socket_arg}
|
||||
: build_root / ".vbs" / "vbs-daemon.sock";
|
||||
}
|
||||
|
||||
int execute_daemon_command(std::string_view sub, const DaemonCmdOptions &opts) {
|
||||
const std::filesystem::path project_root{opts.project_arg};
|
||||
const std::filesystem::path build_root =
|
||||
opts.build_arg ? std::filesystem::path{*opts.build_arg} : (project_root / "build");
|
||||
const auto socket_path = resolve_daemon_socket(opts, build_root);
|
||||
|
||||
if (sub == "run") {
|
||||
std::size_t max_requests = 0;
|
||||
const auto [ptr, ec] = std::from_chars(
|
||||
opts.max_requests_arg.data(),
|
||||
opts.max_requests_arg.data() + opts.max_requests_arg.size(), max_requests);
|
||||
if (ec != std::errc{} ||
|
||||
ptr != opts.max_requests_arg.data() + opts.max_requests_arg.size()) {
|
||||
std::cerr << "vbs daemon run: invalid --max-requests value '" << opts.max_requests_arg
|
||||
<< "'\n";
|
||||
return 2;
|
||||
}
|
||||
Daemon::DaemonOptions daemon_opts;
|
||||
daemon_opts.project_root = project_root;
|
||||
daemon_opts.build_root = build_root;
|
||||
daemon_opts.socket_path = socket_path;
|
||||
daemon_opts.max_requests = max_requests;
|
||||
auto server = Daemon::DaemonServer::create(std::move(daemon_opts));
|
||||
if (!server) {
|
||||
std::cerr << "vbs daemon: " << server.error().message() << '\n';
|
||||
return 1;
|
||||
}
|
||||
Void::Log::info("Daemon", "Serving '{}' (Ctrl+C to stop)...", socket_path.string());
|
||||
std::stop_source stop_src;
|
||||
auto sig = Void::Process::SignalWatcher::create();
|
||||
std::jthread sig_thread([&] {
|
||||
if (sig) {
|
||||
(void)sig->wait();
|
||||
stop_src.request_stop();
|
||||
}
|
||||
});
|
||||
auto result = server->run(stop_src.get_token());
|
||||
if (!result) {
|
||||
std::cerr << "vbs daemon: " << result.error().message() << '\n';
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::string request_json;
|
||||
if (sub == "status") {
|
||||
request_json = R"({"op":"status"})";
|
||||
} else if (sub == "stop") {
|
||||
request_json = R"({"op":"shutdown"})";
|
||||
} else if (sub == "recover") {
|
||||
request_json = R"({"op":"recover"})";
|
||||
} else if (sub == "gc") {
|
||||
std::uint64_t max_bytes = 0;
|
||||
const auto [ptr, ec] =
|
||||
std::from_chars(opts.max_bytes_arg.data(),
|
||||
opts.max_bytes_arg.data() + opts.max_bytes_arg.size(), max_bytes);
|
||||
if (ec != std::errc{} || ptr != opts.max_bytes_arg.data() + opts.max_bytes_arg.size()) {
|
||||
std::cerr << "vbs daemon gc: invalid --max-bytes value '" << opts.max_bytes_arg
|
||||
<< "'\n";
|
||||
return 2;
|
||||
}
|
||||
request_json = std::format(R"({{"op":"gc","max_bytes":{}}})", max_bytes);
|
||||
} else {
|
||||
std::cerr << "vbs daemon: unknown command '" << sub << "'\n";
|
||||
return 2;
|
||||
}
|
||||
|
||||
auto response = Daemon::request(socket_path, request_json);
|
||||
if (!response) {
|
||||
std::cerr << "vbs daemon: " << response.error().message() << '\n';
|
||||
return 1;
|
||||
}
|
||||
std::cout << *response << '\n';
|
||||
const auto parsed = Void::Json::Strict::parse(*response);
|
||||
if (!parsed) {
|
||||
return 1;
|
||||
}
|
||||
const auto *object = std::get_if<Void::Json::Strict::Value::Object>(&parsed->value);
|
||||
if (object == nullptr) {
|
||||
return 1;
|
||||
}
|
||||
const auto ok = object->find("ok");
|
||||
if (ok == object->end()) {
|
||||
return 1;
|
||||
}
|
||||
const auto *flag = std::get_if<bool>(&ok->second.value);
|
||||
return (flag != nullptr && *flag) ? 0 : 1;
|
||||
}
|
||||
|
||||
struct GenTestsCmdOptions {
|
||||
std::optional<std::string> input_arg;
|
||||
std::optional<std::string> out_arg;
|
||||
@@ -2185,6 +2290,8 @@ int main(int argc, char **argv) {
|
||||
graph_opts.project_arg = cwd;
|
||||
IdeCmdOptions ide_opts;
|
||||
ide_opts.project_arg = cwd;
|
||||
DaemonCmdOptions daemon_opts;
|
||||
daemon_opts.project_arg = cwd;
|
||||
|
||||
auto add_log_flags = [&](Void::Argparse::Parser &p, bool allow_short_v = true) {
|
||||
p.flag("--verbose", allow_short_v ? "-v" : "", "Enable verbose debug logs", verbose)
|
||||
@@ -2406,6 +2513,28 @@ int main(int argc, char **argv) {
|
||||
configure_ide_common(
|
||||
ide_cmd.subcommand("query", "Emit versioned JSON workspace, target, and compdb metadata"));
|
||||
|
||||
auto &daemon_cmd = root.subcommand("daemon", "Run or control the persistent build daemon");
|
||||
auto configure_daemon_common = [&](Void::Argparse::Parser &p) {
|
||||
p.option_default("--project", "-C", "Project directory", daemon_opts.project_arg, cwd)
|
||||
.option("--build-dir", "-B", "Build output directory", daemon_opts.build_arg)
|
||||
.option("--socket", "", "Unix socket path (default: <build>/.vbs/vbs-daemon.sock)",
|
||||
daemon_opts.socket_arg);
|
||||
add_log_flags(p);
|
||||
};
|
||||
auto &daemon_run_cmd = daemon_cmd.subcommand("run", "Run the daemon in the foreground");
|
||||
configure_daemon_common(daemon_run_cmd);
|
||||
daemon_run_cmd.option_default("--max-requests", "", "Stop after N requests (0 = unlimited)",
|
||||
daemon_opts.max_requests_arg, "0");
|
||||
configure_daemon_common(daemon_cmd.subcommand("status", "Query the running daemon's status"));
|
||||
configure_daemon_common(daemon_cmd.subcommand("stop", "Ask the running daemon to shut down"));
|
||||
configure_daemon_common(
|
||||
daemon_cmd.subcommand("recover", "Run interrupted-state recovery in the daemon"));
|
||||
auto &daemon_gc_cmd = daemon_cmd.subcommand("gc", "Run CAS garbage collection in the daemon");
|
||||
configure_daemon_common(daemon_gc_cmd);
|
||||
daemon_gc_cmd.option_default("--max-bytes", "",
|
||||
"Target maximum retained CAS bytes (0=unreferenced only)",
|
||||
daemon_opts.max_bytes_arg, "0");
|
||||
|
||||
const auto parsed = root.parse_detailed(argc, argv);
|
||||
if (parsed.is_help()) {
|
||||
std::cout << parsed.message;
|
||||
@@ -2496,6 +2625,9 @@ int main(int argc, char **argv) {
|
||||
if (cmd == "ide") {
|
||||
return execute_ide_command(parsed.matched_command_path.at(1), ide_opts);
|
||||
}
|
||||
if (cmd == "daemon") {
|
||||
return execute_daemon_command(parsed.matched_command_path.at(1), daemon_opts);
|
||||
}
|
||||
|
||||
std::cerr << "vbs: unhandled subcommand '" << cmd << "'\n";
|
||||
return 2;
|
||||
|
||||
@@ -10,6 +10,11 @@
|
||||
#include <unistd.h>
|
||||
#include <utility>
|
||||
|
||||
#if !defined(__linux__)
|
||||
#error \
|
||||
"VoidBuildSystem's process and file backends currently support Linux hosts only (Track C2/C3 ports are planned)"
|
||||
#endif
|
||||
|
||||
namespace Void::Build::Platform {
|
||||
namespace {
|
||||
|
||||
@@ -11,6 +11,11 @@
|
||||
#include <thread>
|
||||
#include <unistd.h>
|
||||
|
||||
#if !defined(__linux__)
|
||||
#error \
|
||||
"VoidBuildSystem's process and file backends currently support Linux hosts only (Track C2/C3 ports are planned)"
|
||||
#endif
|
||||
|
||||
namespace Void::Build::Platform {
|
||||
namespace {
|
||||
|
||||
@@ -1152,6 +1152,12 @@ load_and_audit_codemodel(const std::filesystem::path &configure_dir) {
|
||||
done_utility:
|
||||
continue;
|
||||
}
|
||||
// CMake synthesizes @cmake_cxx_std@(synth_N) INTERFACE_LIBRARY carriers for
|
||||
// target_compile_features standards. The -std flag is already lowered from each
|
||||
// consumer's compile groups, so these feature-only targets have no graph effect.
|
||||
if (pt.type == "INTERFACE_LIBRARY" && pt.name.starts_with("@cmake_cxx_std")) {
|
||||
continue;
|
||||
}
|
||||
if (pt.type == "GLOBAL_TARGET") {
|
||||
add_unsupported(
|
||||
pt.name, "utility_target",
|
||||
@@ -1551,6 +1557,9 @@ load_and_audit_codemodel(const std::filesystem::path &configure_dir) {
|
||||
}
|
||||
} else if (out.targets_by_id.contains(dep_id)) {
|
||||
link_deps.push_back(dep_id);
|
||||
} else if (dep_id.starts_with("@cmake_cxx_std")) {
|
||||
// Feature-only INTERFACE_LIBRARY carrier skipped above; the standard is
|
||||
// already encoded in the consumer's compile options.
|
||||
} else {
|
||||
add_unsupported(pt.name, "untranslated_dependency_edge",
|
||||
std::format("target '{}' depends on untranslated CMake target '{}'",
|
||||
|
||||
@@ -12,7 +12,7 @@ set_target_properties(vbs_core_tests PROPERTIES
|
||||
RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin")
|
||||
add_test(NAME vbs_core_tests COMMAND "$<TARGET_FILE:vbs_core_tests>" --no-color)
|
||||
|
||||
add_executable(vbs_v1_tests FullV1Tests.cpp)
|
||||
add_executable(vbs_v1_tests FullV1Tests.cpp DaemonTests.cpp)
|
||||
target_include_directories(vbs_v1_tests PRIVATE "${PROJECT_BINARY_DIR}/generated")
|
||||
target_link_libraries(vbs_v1_tests PRIVATE Void::BuildCore Void::Testing)
|
||||
set_target_properties(vbs_v1_tests PROPERTIES
|
||||
|
||||
@@ -45,6 +45,9 @@ check_process(2 "" "--prefix is required" uninstall)
|
||||
check_process(2 "" "--input and --output-dir are required" gen-tests)
|
||||
check_process(0 "Usage: vbs publish " "" publish --help)
|
||||
check_process(2 "" "--registry, --name, and --version are required" publish)
|
||||
check_process(0 "Usage: vbs daemon <command>.*Commands:.*run.*status.*stop.*recover.*gc" "" daemon --help)
|
||||
check_process(0 "Usage: vbs daemon run " "" daemon run --help)
|
||||
check_process(2 "" "missing subcommand for 'vbs daemon'" daemon)
|
||||
check_process(0 "Usage: vbs ide <command>.*Commands:.*generate.*query" "" ide --help)
|
||||
check_process(0 "Usage: vbs ide generate " "" ide generate --help)
|
||||
check_process(0 "Usage: vbs ide query " "" ide query --help)
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
#include <Void/Build/Daemon/Daemon.hpp>
|
||||
#include <Void/Data/StrictJson.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <system_error>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
|
||||
namespace {
|
||||
|
||||
using JsonValue = Void::Json::Strict::Value;
|
||||
using JsonObject = JsonValue::Object;
|
||||
|
||||
std::optional<JsonValue> parse_json(const std::string &line) {
|
||||
auto parsed = Void::Json::Strict::parse(line, 16);
|
||||
if (!parsed) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return std::move(*parsed);
|
||||
}
|
||||
|
||||
const JsonObject *as_object(const JsonValue &value) {
|
||||
return std::get_if<JsonObject>(&value.value);
|
||||
}
|
||||
|
||||
const JsonValue *field(const JsonObject &object, std::string_view name) {
|
||||
const auto entry = object.find(name);
|
||||
return entry == object.end() ? nullptr : &entry->second;
|
||||
}
|
||||
|
||||
bool bool_field(const JsonObject &object, std::string_view name, bool fallback = false) {
|
||||
const auto *value = field(object, name);
|
||||
if (value == nullptr) {
|
||||
return fallback;
|
||||
}
|
||||
const auto *flag = std::get_if<bool>(&value->value);
|
||||
return flag != nullptr ? *flag : fallback;
|
||||
}
|
||||
|
||||
std::int64_t int_field(const JsonObject &object, std::string_view name) {
|
||||
const auto *value = field(object, name);
|
||||
if (value == nullptr) {
|
||||
return -1;
|
||||
}
|
||||
const auto *number = std::get_if<std::int64_t>(&value->value);
|
||||
return number != nullptr ? *number : -1;
|
||||
}
|
||||
|
||||
std::string str_field(const JsonObject &object, std::string_view name) {
|
||||
const auto *value = field(object, name);
|
||||
if (value == nullptr) {
|
||||
return {};
|
||||
}
|
||||
const auto *text = std::get_if<std::string>(&value->value);
|
||||
return text != nullptr ? *text : std::string{};
|
||||
}
|
||||
|
||||
bool wait_for_path(const std::filesystem::path &path, std::chrono::milliseconds timeout) {
|
||||
const auto deadline = std::chrono::steady_clock::now() + timeout;
|
||||
while (std::chrono::steady_clock::now() < deadline) {
|
||||
if (std::filesystem::exists(path)) {
|
||||
return true;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{10});
|
||||
}
|
||||
return std::filesystem::exists(path);
|
||||
}
|
||||
|
||||
Void::Build::Daemon::DaemonOptions make_options(const std::filesystem::path &root) {
|
||||
Void::Build::Daemon::DaemonOptions options;
|
||||
options.project_root = root / "project";
|
||||
options.build_root = root / "build";
|
||||
options.poll_interval = std::chrono::milliseconds{10};
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(options.project_root, ec);
|
||||
std::filesystem::create_directories(options.build_root, ec);
|
||||
return options;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
VOID_TEST(Daemon, lifecycle_ping_status_gc_shutdown_and_unknown_op) {
|
||||
auto temp = Void::FileSystem::TempDir::open("vbs_daemon_");
|
||||
Void::Testing::require(temp.has_value());
|
||||
const auto options = make_options(temp->path());
|
||||
|
||||
auto server = Void::Build::Daemon::DaemonServer::create(options);
|
||||
Void::Testing::require(server.has_value());
|
||||
const auto socket = server->socket_path();
|
||||
Void::Testing::expect_eq(socket, options.build_root / ".vbs" / "vbs-daemon.sock");
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error> run_result;
|
||||
std::jthread worker{[&] { run_result = server->run(); }};
|
||||
|
||||
Void::Testing::require(wait_for_path(socket, std::chrono::seconds{5}));
|
||||
|
||||
auto ping = Void::Build::Daemon::request(socket, R"({"op":"ping"})");
|
||||
Void::Testing::require(ping.has_value());
|
||||
const auto ping_json = parse_json(*ping);
|
||||
Void::Testing::require(ping_json.has_value());
|
||||
const auto *ping_object = as_object(*ping_json);
|
||||
Void::Testing::require(ping_object != nullptr);
|
||||
Void::Testing::expect(bool_field(*ping_object, "ok"));
|
||||
Void::Testing::expect_eq(str_field(*ping_object, "op"), std::string{"ping"});
|
||||
|
||||
auto status = Void::Build::Daemon::request(socket, R"({"op":"status"})");
|
||||
Void::Testing::require(status.has_value());
|
||||
const auto status_json = parse_json(*status);
|
||||
Void::Testing::require(status_json.has_value());
|
||||
const auto *status_object = as_object(*status_json);
|
||||
Void::Testing::require(status_object != nullptr);
|
||||
Void::Testing::expect(bool_field(*status_object, "ok"));
|
||||
Void::Testing::expect(int_field(*status_object, "pid") > 0);
|
||||
Void::Testing::expect(int_field(*status_object, "watched_directories") >= 1);
|
||||
Void::Testing::expect(int_field(*status_object, "sequence") >= 0);
|
||||
|
||||
auto gc = Void::Build::Daemon::request(socket, R"({"op":"gc","max_bytes":0})");
|
||||
Void::Testing::require(gc.has_value());
|
||||
const auto gc_json = parse_json(*gc);
|
||||
Void::Testing::require(gc_json.has_value());
|
||||
const auto *gc_object = as_object(*gc_json);
|
||||
Void::Testing::require(gc_object != nullptr);
|
||||
Void::Testing::expect(bool_field(*gc_object, "ok"));
|
||||
Void::Testing::expect(int_field(*gc_object, "removed_blobs") >= 0);
|
||||
Void::Testing::expect(int_field(*gc_object, "retained_blobs") >= 0);
|
||||
|
||||
auto unknown = Void::Build::Daemon::request(socket, R"({"op":"not-an-op"})");
|
||||
Void::Testing::require(unknown.has_value());
|
||||
const auto unknown_json = parse_json(*unknown);
|
||||
Void::Testing::require(unknown_json.has_value());
|
||||
const auto *unknown_object = as_object(*unknown_json);
|
||||
Void::Testing::require(unknown_object != nullptr);
|
||||
Void::Testing::expect(!bool_field(*unknown_object, "ok", true));
|
||||
Void::Testing::expect(field(*unknown_object, "error") != nullptr);
|
||||
|
||||
auto shutdown = Void::Build::Daemon::request(socket, R"({"op":"shutdown"})");
|
||||
Void::Testing::require(shutdown.has_value());
|
||||
const auto shutdown_json = parse_json(*shutdown);
|
||||
Void::Testing::require(shutdown_json.has_value());
|
||||
const auto *shutdown_object = as_object(*shutdown_json);
|
||||
Void::Testing::require(shutdown_object != nullptr);
|
||||
Void::Testing::expect(bool_field(*shutdown_object, "ok"));
|
||||
|
||||
worker.join();
|
||||
Void::Testing::expect(run_result.has_value());
|
||||
Void::Testing::expect(!std::filesystem::exists(socket));
|
||||
}
|
||||
|
||||
VOID_TEST(Daemon, second_create_reports_already_running) {
|
||||
auto temp = Void::FileSystem::TempDir::open("vbs_daemon_");
|
||||
Void::Testing::require(temp.has_value());
|
||||
const auto options = make_options(temp->path());
|
||||
|
||||
auto first = Void::Build::Daemon::DaemonServer::create(options);
|
||||
Void::Testing::require(first.has_value());
|
||||
const auto socket = first->socket_path();
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error> run_result;
|
||||
std::jthread worker{[&] { run_result = first->run(); }};
|
||||
Void::Testing::require(wait_for_path(socket, std::chrono::seconds{5}));
|
||||
|
||||
auto second = Void::Build::Daemon::DaemonServer::create(options);
|
||||
Void::Testing::expect(!second.has_value());
|
||||
if (!second) {
|
||||
Void::Testing::expect(second.error().message().find("already running") !=
|
||||
std::string::npos);
|
||||
}
|
||||
|
||||
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::expect(!std::filesystem::exists(socket));
|
||||
}
|
||||
Reference in new issue
Block a user