Compare commits
122
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
103523f04a | ||
|
|
a1308a41f8 | ||
|
|
7e5cf7379a | ||
|
|
7eaa96f9da | ||
|
|
797ea630a1 | ||
|
|
0e8ee1848d | ||
|
|
a29c9475f2 | ||
|
|
54d143be93 | ||
|
|
0002e74a7d | ||
|
|
0751a4155b | ||
|
|
86cb94c844 | ||
|
|
f8c62c9851 | ||
|
|
7d25251e21 | ||
|
|
06641947bd | ||
|
|
f0820b778f | ||
|
|
62df9b3d7f | ||
|
|
92d60231e5 | ||
|
|
2c8d853af0 | ||
|
|
1ba60d5d6a | ||
|
|
b1933d9906 | ||
|
|
9f8c56a7ee | ||
|
|
08a40ad5fc | ||
|
|
35774f18cc | ||
|
|
5d4589056a | ||
|
|
df4103700e | ||
|
|
4bc8a7c59b | ||
|
|
898968d7c6 | ||
|
|
6e636d23e3 | ||
|
|
77a2bce73f | ||
|
|
32569bbfef | ||
|
|
65185f251c | ||
|
|
fe231b0149 | ||
|
|
1335fa86c3 | ||
|
|
2501c4d7ac | ||
|
|
430deab07a | ||
|
|
7b3258a450 | ||
|
|
d51dd171ef | ||
|
|
44686a4444 | ||
|
|
f158d7b1cc | ||
|
|
62c2082fb3 | ||
|
|
29b46839fd | ||
|
|
72148da7b2 | ||
|
|
a6dd7fd927 | ||
|
|
7cfd30e550 | ||
|
|
9b773a4553 | ||
|
|
540c3d9117 | ||
|
|
74bd01aac5 | ||
|
|
a14d063598 | ||
|
|
a535f352d6 | ||
|
|
9ccfbf7838 | ||
|
|
963aface67 | ||
|
|
a40882522a | ||
|
|
ae7bedb755 | ||
|
|
be8dd73607 | ||
|
|
4ad13ce94f | ||
|
|
f146df97f4 | ||
|
|
f5842b97c8 | ||
|
|
add599917c | ||
|
|
2eb3bd230a | ||
|
|
b3c566ed4d | ||
|
|
d5cfd9cd7a | ||
|
|
aebc38791a | ||
|
|
c8f0113d48 | ||
|
|
12ba8d8e2c | ||
|
|
496d9fc582 | ||
|
|
5a74233a4d | ||
|
|
774df0fd1e | ||
|
|
f8e183b7ab | ||
|
|
216a14e6fa | ||
|
|
7686be1b23 | ||
|
|
71fcad80d3 | ||
|
|
905e44635e | ||
|
|
5d5a8bf345 | ||
|
|
fe6e2124ad | ||
|
|
f9bde1d19f | ||
|
|
65595362e2 | ||
|
|
43d94e2837 | ||
|
|
f6002c1996 | ||
|
|
706383e13f | ||
|
|
81e1d54ac3 | ||
|
|
f57b508b0a | ||
|
|
b381d682c8 | ||
|
|
8c576fdcbf | ||
|
|
63eecc32c7 | ||
|
|
86bde8b172 | ||
|
|
a0e4bfa941 | ||
|
|
6c5c2dcd93 | ||
|
|
86510f99f0 | ||
|
|
a5f21c6374 | ||
|
|
2474292462 | ||
|
|
34cfd9cb39 | ||
|
|
72733e2b93 | ||
|
|
dc18d64b18 | ||
|
|
caebb7f7f1 | ||
|
|
df2ed107e2 | ||
|
|
e8565c6857 | ||
|
|
2c6e4eab82 | ||
|
|
359e0630c7 | ||
|
|
025d97c6f6 | ||
|
|
08038000cc | ||
|
|
ba49098798 | ||
|
|
60860d167a | ||
|
|
5a076cd8f2 | ||
|
|
82c3558524 | ||
|
|
3953891511 | ||
|
|
ba3c5a6734 | ||
|
|
00eefe0521 | ||
|
|
b062e759ba | ||
|
|
dddcc2b2f0 | ||
|
|
7d0ed43f76 | ||
|
|
acd4ff40f0 | ||
|
|
f100b4c89e | ||
|
|
4f67fd2b93 | ||
|
|
2e8afc471b | ||
|
|
f3176c2b54 | ||
|
|
a4851c2c20 | ||
|
|
f2b002eb26 | ||
|
|
afd4d99a2d | ||
|
|
37c3cd4383 | ||
|
|
d30384d981 | ||
|
|
51ceb081ac | ||
|
|
7b0fea6095 |
No files matched your search
@@ -0,0 +1,29 @@
|
|||||||
|
{
|
||||||
|
"name": "VoidLibrary (GCC 16, CMake 4, Ninja)",
|
||||||
|
"build": {
|
||||||
|
"dockerfile": "../Dockerfile",
|
||||||
|
"context": ".."
|
||||||
|
},
|
||||||
|
"workspaceFolder": "/src",
|
||||||
|
"workspaceMount": "source=${localWorkspaceFolder},target=/src,type=bind",
|
||||||
|
"remoteUser": "root",
|
||||||
|
"customizations": {
|
||||||
|
"vscode": {
|
||||||
|
"extensions": [
|
||||||
|
"ms-vscode.cpptools",
|
||||||
|
"ms-vscode.cmake-tools",
|
||||||
|
"twxs.cmake"
|
||||||
|
],
|
||||||
|
"settings": {
|
||||||
|
"cmake.generator": "Ninja",
|
||||||
|
"cmake.configureSettings": {
|
||||||
|
"CMAKE_CXX_COMPILER": "g++-16",
|
||||||
|
"CMAKE_C_COMPILER": "gcc-16",
|
||||||
|
"CMAKE_BUILD_TYPE": "Debug"
|
||||||
|
},
|
||||||
|
"C_Cpp.default.cppStandard": "c++26"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"postCreateCommand": "cmake --version && g++-16 --version && ninja --version"
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
# Windows builds: MSYS2 (native) and MinGW-w64 (cross)
|
||||||
|
|
||||||
|
## MSYS2 (native Windows, recommended for a full build)
|
||||||
|
|
||||||
|
Install the MINGW64 toolchain and the optional libraries used by the modules:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pacman -S --needed base-devel \
|
||||||
|
mingw-w64-x86_64-toolchain \
|
||||||
|
mingw-w64-x86_64-cmake \
|
||||||
|
mingw-w64-x86_64-ninja \
|
||||||
|
mingw-w64-x86_64-boost \
|
||||||
|
mingw-w64-x86_64-openssl \
|
||||||
|
mingw-w64-x86_64-libsodium \
|
||||||
|
mingw-w64-x86_64-libarchive \
|
||||||
|
mingw-w64-x86_64-sqlite3 \
|
||||||
|
mingw-w64-x86_64-lua
|
||||||
|
```
|
||||||
|
|
||||||
|
Then, from a **MINGW64** shell (not the MSYS shell):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cmake -B build -S . -G Ninja -DCMAKE_BUILD_TYPE=Debug
|
||||||
|
cmake --build build
|
||||||
|
ctest --test-dir build --output-on-failure
|
||||||
|
```
|
||||||
|
|
||||||
|
Notes:
|
||||||
|
|
||||||
|
- C++26 reflection requires GCC 16 or newer (`-freflection`). The build
|
||||||
|
probes for it; on older GCC some reflection-only tests are skipped.
|
||||||
|
- `Void::IO` currently has a POSIX (epoll) backend only; select the modules
|
||||||
|
you need with `-DVOID_ENABLED_MODULES=...` if a module is not yet available
|
||||||
|
on Windows.
|
||||||
|
- The Windows branches of `Void::System` (paths, bounded reads, audio) are
|
||||||
|
compiled by this configuration.
|
||||||
|
|
||||||
|
## MinGW-w64 cross build (Linux container)
|
||||||
|
|
||||||
|
`Dockerfile.mingw` uses the LLVM-MinGW toolchain (Clang + libc++ + the
|
||||||
|
MinGW-w64 runtime) on top of Ubuntu, together with CMake 4 and Ninja. The
|
||||||
|
matching devcontainer is in `.devcontainer/mingw/`.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build -f Dockerfile.mingw -t voidlibrary-mingw .
|
||||||
|
docker run --rm -v "$PWD:/src" -w /src voidlibrary-mingw bash -lc '
|
||||||
|
cmake -B build-mingw -S . -G Ninja \
|
||||||
|
-DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/mingw-w64.cmake \
|
||||||
|
-DCMAKE_BUILD_TYPE=Debug \
|
||||||
|
-DVOID_ENABLE_TESTING=OFF \
|
||||||
|
-DVOID_ENABLED_MODULES="Core;Functional;Containers;Math;Text;Algorithms;Unicode;Time;LogState"
|
||||||
|
cmake --build build-mingw
|
||||||
|
'
|
||||||
|
```
|
||||||
|
|
||||||
|
Cross-compiling cannot use the host's Boost/OpenSSL/libsodium/libarchive/SQLite/
|
||||||
|
Lua libraries. Modules that need them (or the POSIX-only IO backend) are
|
||||||
|
therefore excluded from a cross build; use MSYS2 on Windows for those.
|
||||||
|
|
||||||
|
- The toolchain file accepts GCC- or Clang-based MinGW prefixes and picks
|
||||||
|
whichever compiler exists.
|
||||||
|
- `CMAKE_CXX_STANDARD` can be pinned for older toolchains
|
||||||
|
(`-DCMAKE_CXX_STANDARD=23`); the build probes capabilities against the
|
||||||
|
selected standard.
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
{
|
||||||
|
"name": "VoidLibrary (MinGW-w64 cross build)",
|
||||||
|
"build": {
|
||||||
|
"dockerfile": "../../Dockerfile.mingw",
|
||||||
|
"context": "../.."
|
||||||
|
},
|
||||||
|
"workspaceFolder": "/src",
|
||||||
|
"workspaceMount": "source=${localWorkspaceFolder},target=/src,type=bind",
|
||||||
|
"remoteUser": "root",
|
||||||
|
"customizations": {
|
||||||
|
"vscode": {
|
||||||
|
"extensions": [
|
||||||
|
"ms-vscode.cpptools",
|
||||||
|
"ms-vscode.cmake-tools",
|
||||||
|
"twxs.cmake"
|
||||||
|
],
|
||||||
|
"settings": {
|
||||||
|
"cmake.generator": "Ninja",
|
||||||
|
"cmake.configureSettings": {
|
||||||
|
"CMAKE_TOOLCHAIN_FILE": "cmake/toolchains/mingw-w64.cmake",
|
||||||
|
"CMAKE_BUILD_TYPE": "Debug"
|
||||||
|
},
|
||||||
|
"C_Cpp.default.cppStandard": "c++26"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"postCreateCommand": "cmake --version && x86_64-w64-mingw32-g++ --version && ninja --version"
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
build*
|
||||||
|
.git
|
||||||
|
.gitea
|
||||||
|
.github
|
||||||
|
.dockerignore
|
||||||
|
Dockerfile
|
||||||
+30
-4
@@ -14,11 +14,23 @@ option(VOID_ENABLE_ASAN "Enable AddressSanitizer (Clang/GCC)" OFF)
|
|||||||
option(VOID_ENABLE_UBSAN "Enable UndefinedBehaviorSanitizer (Clang/GCC)" OFF)
|
option(VOID_ENABLE_UBSAN "Enable UndefinedBehaviorSanitizer (Clang/GCC)" OFF)
|
||||||
option(VOID_ENABLE_TSAN "Enable ThreadSanitizer (Clang/GCC)" OFF)
|
option(VOID_ENABLE_TSAN "Enable ThreadSanitizer (Clang/GCC)" OFF)
|
||||||
option(VOID_ENABLE_COVERAGE "Enable code coverage instrumentation" OFF)
|
option(VOID_ENABLE_COVERAGE "Enable code coverage instrumentation" OFF)
|
||||||
|
option(VOID_SCRIPT_ENABLE_LUA "Build the optional bounded Lua adapter" ON)
|
||||||
|
option(VOID_FETCH_LUA "Fetch Lua 5.4 when no system package is found" ON)
|
||||||
|
|
||||||
set(CMAKE_CXX_STANDARD 26)
|
# C++26 is the default. Cross/toolchain-limited builds (e.g. MinGW-w64
|
||||||
|
# with an older GCC) may pin a lower standard explicitly.
|
||||||
|
if(NOT DEFINED CMAKE_CXX_STANDARD)
|
||||||
|
set(CMAKE_CXX_STANDARD 26)
|
||||||
|
endif()
|
||||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||||
set(CMAKE_CXX_MODULE_MAP_FORMAT "gcc")
|
if(NOT DEFINED CMAKE_CXX_MODULE_MAP_FORMAT)
|
||||||
|
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
|
||||||
|
set(CMAKE_CXX_MODULE_MAP_FORMAT "clang")
|
||||||
|
else()
|
||||||
|
set(CMAKE_CXX_MODULE_MAP_FORMAT "gcc")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
set(CXX_SCAN_FOR_MODULES OFF)
|
set(CXX_SCAN_FOR_MODULES OFF)
|
||||||
# <Void/Data/Reflect.hpp>, <Void/Configuration/Bind.hpp>, etc.
|
# <Void/Data/Reflect.hpp>, <Void/Configuration/Bind.hpp>, etc.
|
||||||
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16)
|
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16)
|
||||||
@@ -33,6 +45,7 @@ set(EXPORT_SET_NAME ${PROJECT_NAME}Targets)
|
|||||||
include(cmake/Capabilities.cmake)
|
include(cmake/Capabilities.cmake)
|
||||||
void_probe_capabilities()
|
void_probe_capabilities()
|
||||||
include(cmake/Module.cmake)
|
include(cmake/Module.cmake)
|
||||||
|
include(cmake/Targets.cmake)
|
||||||
|
|
||||||
# Modules to configure, with the modules they need (INTERNAL_DEPS, followed
|
# Modules to configure, with the modules they need (INTERNAL_DEPS, followed
|
||||||
# transitively); empty configures every module. OPTIONAL_DEPS are used only
|
# transitively); empty configures every module. OPTIONAL_DEPS are used only
|
||||||
@@ -56,11 +69,14 @@ if(VOID_ENABLED_MODULES)
|
|||||||
list(APPEND _void_selected ${_void_module})
|
list(APPEND _void_selected ${_void_module})
|
||||||
if(EXISTS "${_void_module_file}")
|
if(EXISTS "${_void_module_file}")
|
||||||
file(READ "${_void_module_file}" _void_text)
|
file(READ "${_void_module_file}" _void_text)
|
||||||
# The words after INTERNAL_DEPS up to the next keyword or ')'.
|
# Drop comments so prose between keywords is never parsed as a
|
||||||
|
# dependency name, then read the words after INTERNAL_DEPS up to
|
||||||
|
# the next keyword or ')'.
|
||||||
|
string(REGEX REPLACE "#[^\n]*" "" _void_text "${_void_text}")
|
||||||
if(_void_text MATCHES "INTERNAL_DEPS([^)]*)")
|
if(_void_text MATCHES "INTERNAL_DEPS([^)]*)")
|
||||||
separate_arguments(_void_words UNIX_COMMAND "${CMAKE_MATCH_1}")
|
separate_arguments(_void_words UNIX_COMMAND "${CMAKE_MATCH_1}")
|
||||||
foreach(_void_word IN LISTS _void_words)
|
foreach(_void_word IN LISTS _void_words)
|
||||||
if(_void_word MATCHES "^(INTERNAL_DEPS|EXTERNAL_DEPS|OPTIONAL_DEPS|DEPS_WIN32|DEPS_UNIX|OPTIONS_WIN32|OPTIONS_UNIX|EXTRA_HEADERS|EXCLUDE_HEADERS)$")
|
if(_void_word MATCHES "^(INTERNAL_DEPS|EXTERNAL_DEPS|OPTIONAL_DEPS|DEPS_WIN32|DEPS_UNIX|OPTIONS_WIN32|OPTIONS_UNIX|EXTRA_HEADERS|EXCLUDE_HEADERS|EXCLUDE_SOURCES_WIN32|EXCLUDE_SOURCES_UNIX)$")
|
||||||
break()
|
break()
|
||||||
endif()
|
endif()
|
||||||
list(APPEND _void_pending ${_void_word})
|
list(APPEND _void_pending ${_void_word})
|
||||||
@@ -71,6 +87,12 @@ if(VOID_ENABLED_MODULES)
|
|||||||
endif()
|
endif()
|
||||||
|
|
||||||
file(GLOB children RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/src/*)
|
file(GLOB children RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/src/*)
|
||||||
|
if(_void_selected)
|
||||||
|
# Fail on unsupported target/module combinations before resolving any
|
||||||
|
# dependency, so a browser engine requesting native networking gets the
|
||||||
|
# target message instead of a Boost/OpenSSL one.
|
||||||
|
void_validate_target_modules(${_void_selected})
|
||||||
|
endif()
|
||||||
foreach(module_path ${children})
|
foreach(module_path ${children})
|
||||||
if(_void_selected AND NOT module_path IN_LIST _void_selected)
|
if(_void_selected AND NOT module_path IN_LIST _void_selected)
|
||||||
continue()
|
continue()
|
||||||
@@ -84,6 +106,9 @@ foreach(module_path ${children})
|
|||||||
endif()
|
endif()
|
||||||
endforeach()
|
endforeach()
|
||||||
void_finalize_modules()
|
void_finalize_modules()
|
||||||
|
void_validate_target_modules()
|
||||||
|
void_write_target_manifest(
|
||||||
|
"${CMAKE_CURRENT_BINARY_DIR}/void-target-manifest.cmake")
|
||||||
void_report_capabilities()
|
void_report_capabilities()
|
||||||
if(VOID_ENABLE_TESTING)
|
if(VOID_ENABLE_TESTING)
|
||||||
|
|
||||||
@@ -132,6 +157,7 @@ install(EXPORT ${EXPORT_SET_NAME}
|
|||||||
install(FILES
|
install(FILES
|
||||||
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
|
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
|
||||||
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake"
|
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake"
|
||||||
|
"${CMAKE_CURRENT_BINARY_DIR}/void-target-manifest.cmake"
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/VoidTesting.cmake"
|
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/VoidTesting.cmake"
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/VoidTestScanner.cmake"
|
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/VoidTestScanner.cmake"
|
||||||
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
|
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
|
||||||
|
|||||||
+52
@@ -0,0 +1,52 @@
|
|||||||
|
# Development image for VoidLibrary.
|
||||||
|
#
|
||||||
|
# Toolchain: GCC 16 (C++26 reflection), CMake 4, Ninja.
|
||||||
|
# Optional dependencies used by the modules: Boost, OpenSSL, libsodium,
|
||||||
|
# libarchive, SQLite3 and Lua 5.4.
|
||||||
|
#
|
||||||
|
# The image does not copy or build the sources: mount the repository at /src
|
||||||
|
# (the devcontainer does this) and configure/build there.
|
||||||
|
|
||||||
|
FROM ubuntu:24.04
|
||||||
|
|
||||||
|
ARG DEBIAN_FRONTEND=noninteractive
|
||||||
|
ARG GCC_VERSION=16
|
||||||
|
ARG CMAKE_VERSION=4.2.3
|
||||||
|
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends \
|
||||||
|
build-essential \
|
||||||
|
ca-certificates \
|
||||||
|
curl \
|
||||||
|
git \
|
||||||
|
gnupg \
|
||||||
|
ninja-build \
|
||||||
|
pkg-config \
|
||||||
|
software-properties-common \
|
||||||
|
libboost-all-dev \
|
||||||
|
libssl-dev \
|
||||||
|
libsodium-dev \
|
||||||
|
libarchive-dev \
|
||||||
|
libsqlite3-dev \
|
||||||
|
liblua5.4-dev \
|
||||||
|
zlib1g-dev \
|
||||||
|
&& add-apt-repository -y ppa:ubuntu-toolchain-r/test \
|
||||||
|
&& apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends \
|
||||||
|
gcc-${GCC_VERSION} \
|
||||||
|
g++-${GCC_VERSION} \
|
||||||
|
&& update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-${GCC_VERSION} 100 \
|
||||||
|
&& update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-${GCC_VERSION} 100 \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
RUN curl -fsSL -o /tmp/cmake.tar.gz \
|
||||||
|
"https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \
|
||||||
|
&& tar -xzf /tmp/cmake.tar.gz -C /opt \
|
||||||
|
&& ln -s "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/cmake" /usr/local/bin/cmake \
|
||||||
|
&& ln -s "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/ctest" /usr/local/bin/ctest \
|
||||||
|
&& ln -s "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/cpack" /usr/local/bin/cpack \
|
||||||
|
&& rm /tmp/cmake.tar.gz
|
||||||
|
|
||||||
|
WORKDIR /src
|
||||||
|
|
||||||
|
CMD ["bash"]
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# MinGW-w64 cross-build environment for VoidLibrary (Windows x64 from Linux).
|
||||||
|
#
|
||||||
|
# Uses the LLVM-MinGW toolchain (Clang + libc++ + MinGW-w64 runtime), which is
|
||||||
|
# new enough for the C++26 features this project uses. Reflection is not
|
||||||
|
# available on Clang, so the reflection-only tests are skipped exactly as on
|
||||||
|
# any non-reflecting compiler.
|
||||||
|
|
||||||
|
FROM mstorsjo/llvm-mingw:latest
|
||||||
|
|
||||||
|
ARG CMAKE_VERSION=4.2.3
|
||||||
|
|
||||||
|
# The base image is Ubuntu 24.04 with CMake 3.28; Void requires CMake 4.
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends ca-certificates curl git \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
RUN curl -fsSL -o /tmp/cmake.tar.gz \
|
||||||
|
"https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \
|
||||||
|
&& tar -xzf /tmp/cmake.tar.gz -C /opt \
|
||||||
|
&& ln -sf "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/cmake" /usr/local/bin/cmake \
|
||||||
|
&& ln -sf "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/ctest" /usr/local/bin/ctest \
|
||||||
|
&& ln -sf "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/cpack" /usr/local/bin/cpack \
|
||||||
|
&& rm /tmp/cmake.tar.gz
|
||||||
|
|
||||||
|
ENV PATH="/opt/llvm-mingw/bin:${PATH}"
|
||||||
|
|
||||||
|
WORKDIR /src
|
||||||
|
|
||||||
|
CMD ["bash"]
|
||||||
@@ -48,6 +48,15 @@ ctest --test-dir build-asan
|
|||||||
|
|
||||||
Format code with `clang-format -i <file>`.
|
Format code with `clang-format -i <file>`.
|
||||||
|
|
||||||
|
## Supported targets
|
||||||
|
|
||||||
|
Void is qualified per target profile: Linux (reference), Linux/musl, the
|
||||||
|
Windows client subset, and a browser/Wasm subset of the pure computation
|
||||||
|
modules. The profile is detected from the toolchain, validated against the
|
||||||
|
selected modules, and recorded in `void-target-manifest.cmake`. See
|
||||||
|
[docs/targets.md](docs/targets.md) for the exact compiler/standard-library
|
||||||
|
tuples, module allowlists and qualification status.
|
||||||
|
|
||||||
## Modules
|
## Modules
|
||||||
|
|
||||||
Functionality is grouped into umbrella modules (one CMake target each).
|
Functionality is grouped into umbrella modules (one CMake target each).
|
||||||
@@ -101,4 +110,7 @@ Tests are free functions or methods on a `Void::Testing::Fixture` subclass
|
|||||||
returning `Void::Testing::Test` (or `Void::Testing::DisabledTest`).
|
returning `Void::Testing::Test` (or `Void::Testing::DisabledTest`).
|
||||||
Registration is automatic — the CMake test scanner parses each `.cpp` at
|
Registration is automatic — the CMake test scanner parses each `.cpp` at
|
||||||
configure time and generates the registration shim. Free-function tests can
|
configure time and generates the registration shim. Free-function tests can
|
||||||
use `// @tag` and `// @skip` comment metadata.
|
use `// @tag` and `// @skip` comment metadata. A file whose tests all need
|
||||||
|
C++26 reflection can declare `// @requires-reflection`; it is skipped when
|
||||||
|
the compiler lacks the `VOID_HAS_CXX26_REFLECTION` capability, because the
|
||||||
|
scanner cannot evaluate `#ifdef` guards around test functions.
|
||||||
@@ -33,7 +33,7 @@ function(void_probe_capabilities)
|
|||||||
endif()
|
endif()
|
||||||
|
|
||||||
cmake_push_check_state(RESET)
|
cmake_push_check_state(RESET)
|
||||||
set(CMAKE_REQUIRED_FLAGS "-std=c++26")
|
set(CMAKE_REQUIRED_FLAGS "-std=c++${CMAKE_CXX_STANDARD}")
|
||||||
check_cxx_source_compiles(
|
check_cxx_source_compiles(
|
||||||
"#include <expected>\nint main() { std::expected<int, int> e{0}; return *e; }\n"
|
"#include <expected>\nint main() { std::expected<int, int> e{0}; return *e; }\n"
|
||||||
VOID_HAS_STD_EXPECTED
|
VOID_HAS_STD_EXPECTED
|
||||||
@@ -46,10 +46,12 @@ function(void_probe_capabilities)
|
|||||||
endif()
|
endif()
|
||||||
|
|
||||||
cmake_push_check_state(RESET)
|
cmake_push_check_state(RESET)
|
||||||
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16)
|
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND
|
||||||
set(CMAKE_REQUIRED_FLAGS "-std=c++26 -freflection")
|
CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16 AND
|
||||||
|
CMAKE_CXX_STANDARD GREATER_EQUAL 26)
|
||||||
|
set(CMAKE_REQUIRED_FLAGS "-std=c++${CMAKE_CXX_STANDARD} -freflection")
|
||||||
else()
|
else()
|
||||||
set(CMAKE_REQUIRED_FLAGS "-std=c++26")
|
set(CMAKE_REQUIRED_FLAGS "-std=c++${CMAKE_CXX_STANDARD}")
|
||||||
endif()
|
endif()
|
||||||
check_cxx_source_compiles(
|
check_cxx_source_compiles(
|
||||||
"#include <meta>\nconsteval bool probe() { constexpr auto r = ^^int; return std::meta::is_type(r); }\nstatic_assert(probe());\nint main() { return 0; }\n"
|
"#include <meta>\nconsteval bool probe() { constexpr auto r = ^^int; return std::meta::is_type(r); }\nstatic_assert(probe());\nint main() { return 0; }\n"
|
||||||
|
|||||||
@@ -265,6 +265,47 @@ function(void_fetch_dependency DEP_NAME)
|
|||||||
endif()
|
endif()
|
||||||
return()
|
return()
|
||||||
endif()
|
endif()
|
||||||
|
if(DEP_NAME STREQUAL "Lua")
|
||||||
|
if(TARGET Lua::Lua)
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
|
# Prefer a system Lua 5.4 development package.
|
||||||
|
find_package(Lua 5.4 QUIET)
|
||||||
|
if(LUA_FOUND)
|
||||||
|
add_library(Lua::Lua INTERFACE IMPORTED)
|
||||||
|
set_property(TARGET Lua::Lua PROPERTY
|
||||||
|
INTERFACE_INCLUDE_DIRECTORIES "${LUA_INCLUDE_DIR}")
|
||||||
|
set_property(TARGET Lua::Lua PROPERTY
|
||||||
|
INTERFACE_LINK_LIBRARIES "${LUA_LIBRARIES}")
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(NOT VOID_FETCH_LUA)
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"[Void] Lua 5.4 not found and VOID_FETCH_LUA=OFF")
|
||||||
|
endif()
|
||||||
|
message(STATUS "[Void] Lua 5.4 not found - falling back to FetchContent")
|
||||||
|
FetchContent_Declare(Lua
|
||||||
|
URL https://www.lua.org/ftp/lua-5.4.9.tar.gz
|
||||||
|
URL_HASH SHA256=2335b6c582a52654f94612bf10d2f4672805d05329aa6568b1d8cd9e5c6fb8e6
|
||||||
|
SYSTEM
|
||||||
|
)
|
||||||
|
FetchContent_MakeAvailable(Lua)
|
||||||
|
file(GLOB _void_lua_sources "${lua_SOURCE_DIR}/src/*.c")
|
||||||
|
list(REMOVE_ITEM _void_lua_sources
|
||||||
|
"${lua_SOURCE_DIR}/src/lua.c"
|
||||||
|
"${lua_SOURCE_DIR}/src/luac.c")
|
||||||
|
add_library(void_lua STATIC ${_void_lua_sources})
|
||||||
|
set_target_properties(void_lua PROPERTIES
|
||||||
|
POSITION_INDEPENDENT_CODE ON
|
||||||
|
C_STANDARD 99
|
||||||
|
SYSTEM TRUE)
|
||||||
|
target_include_directories(void_lua SYSTEM PUBLIC
|
||||||
|
"${lua_SOURCE_DIR}/src")
|
||||||
|
add_library(Lua::Lua ALIAS void_lua)
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
|
|
||||||
# FIXME: Add if needed external
|
# FIXME: Add if needed external
|
||||||
# if(DEP_NAME STREQUAL "glaze")
|
# if(DEP_NAME STREQUAL "glaze")
|
||||||
# if(NOT glaze_POPULATED)
|
# if(NOT glaze_POPULATED)
|
||||||
|
|||||||
+18
-4
@@ -5,13 +5,27 @@ set_property(GLOBAL PROPERTY VOID_ACTIVE_PUBLIC_HEADERS "")
|
|||||||
|
|
||||||
function(void_add_module MODULE_NAME)
|
function(void_add_module MODULE_NAME)
|
||||||
cmake_parse_arguments(ARG "" ""
|
cmake_parse_arguments(ARG "" ""
|
||||||
"INTERNAL_DEPS;EXTERNAL_DEPS;OPTIONAL_DEPS;DEPS_WIN32;DEPS_UNIX;OPTIONS_WIN32;OPTIONS_UNIX;EXTRA_HEADERS;EXCLUDE_HEADERS"
|
"INTERNAL_DEPS;EXTERNAL_DEPS;OPTIONAL_DEPS;DEPS_WIN32;DEPS_UNIX;OPTIONS_WIN32;OPTIONS_UNIX;EXTRA_HEADERS;EXCLUDE_HEADERS;EXCLUDE_SOURCES_WIN32;EXCLUDE_SOURCES_UNIX"
|
||||||
${ARGN})
|
${ARGN})
|
||||||
|
|
||||||
set(TGT ${PROJECT_NAME}_${MODULE_NAME})
|
set(TGT ${PROJECT_NAME}_${MODULE_NAME})
|
||||||
set(ALIAS ${PROJECT_NAME}::${MODULE_NAME})
|
set(ALIAS ${PROJECT_NAME}::${MODULE_NAME})
|
||||||
|
|
||||||
file(GLOB_RECURSE SRC CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/${MODULE_NAME}/*.cpp")
|
file(GLOB_RECURSE SRC CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/${MODULE_NAME}/*.cpp")
|
||||||
|
# Platform-specific source selection: a module may be fully portable at the
|
||||||
|
# header level while some translation units only build on one platform.
|
||||||
|
# Exclusions are relative to the module directory so callers do not depend
|
||||||
|
# on the global source layout.
|
||||||
|
if(WIN32 AND ARG_EXCLUDE_SOURCES_WIN32)
|
||||||
|
foreach(_excl IN LISTS ARG_EXCLUDE_SOURCES_WIN32)
|
||||||
|
list(REMOVE_ITEM SRC "${CMAKE_CURRENT_SOURCE_DIR}/${_excl}")
|
||||||
|
endforeach()
|
||||||
|
endif()
|
||||||
|
if(NOT WIN32 AND ARG_EXCLUDE_SOURCES_UNIX)
|
||||||
|
foreach(_excl IN LISTS ARG_EXCLUDE_SOURCES_UNIX)
|
||||||
|
list(REMOVE_ITEM SRC "${CMAKE_CURRENT_SOURCE_DIR}/${_excl}")
|
||||||
|
endforeach()
|
||||||
|
endif()
|
||||||
file(GLOB_RECURSE HDR CONFIGURE_DEPENDS
|
file(GLOB_RECURSE HDR CONFIGURE_DEPENDS
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.hpp"
|
"${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.hpp"
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.h")
|
"${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.h")
|
||||||
@@ -33,7 +47,7 @@ function(void_add_module MODULE_NAME)
|
|||||||
set(LIB_TYPE "INTERFACE")
|
set(LIB_TYPE "INTERFACE")
|
||||||
set(SCOPE "INTERFACE")
|
set(SCOPE "INTERFACE")
|
||||||
add_library(${TGT} INTERFACE)
|
add_library(${TGT} INTERFACE)
|
||||||
target_compile_features(${TGT} INTERFACE cxx_std_26)
|
target_compile_features(${TGT} INTERFACE cxx_std_${CMAKE_CXX_STANDARD})
|
||||||
else()
|
else()
|
||||||
set(SCOPE "PUBLIC")
|
set(SCOPE "PUBLIC")
|
||||||
if (MODULE_NAME STREQUAL "Testing")
|
if (MODULE_NAME STREQUAL "Testing")
|
||||||
@@ -45,7 +59,7 @@ function(void_add_module MODULE_NAME)
|
|||||||
add_library(${TGT})
|
add_library(${TGT})
|
||||||
endif()
|
endif()
|
||||||
target_sources(${TGT} PRIVATE ${SRC})
|
target_sources(${TGT} PRIVATE ${SRC})
|
||||||
target_compile_features(${TGT} PUBLIC cxx_std_26)
|
target_compile_features(${TGT} PUBLIC cxx_std_${CMAKE_CXX_STANDARD})
|
||||||
endif()
|
endif()
|
||||||
get_target_property(_module_target_type ${TGT} TYPE)
|
get_target_property(_module_target_type ${TGT} TYPE)
|
||||||
if(_module_target_type STREQUAL "SHARED_LIBRARY" OR
|
if(_module_target_type STREQUAL "SHARED_LIBRARY" OR
|
||||||
@@ -221,7 +235,7 @@ function(void_add_module MODULE_NAME)
|
|||||||
endif()
|
endif()
|
||||||
|
|
||||||
set_target_properties(${TGT} PROPERTIES
|
set_target_properties(${TGT} PROPERTIES
|
||||||
CXX_STANDARD 26
|
CXX_STANDARD ${CMAKE_CXX_STANDARD}
|
||||||
CXX_STANDARD_REQUIRED ON
|
CXX_STANDARD_REQUIRED ON
|
||||||
CXX_EXTENSIONS OFF
|
CXX_EXTENSIONS OFF
|
||||||
EXPORT_NAME ${MODULE_NAME}
|
EXPORT_NAME ${MODULE_NAME}
|
||||||
|
|||||||
@@ -0,0 +1,241 @@
|
|||||||
|
# Target qualification for VoidLibrary.
|
||||||
|
#
|
||||||
|
# A "target" is a platform profile with a known compiler/standard-library
|
||||||
|
# tuple and an explicit set of modules that are expected to work there. The
|
||||||
|
# profile is detected from the toolchain, can be overridden for
|
||||||
|
# qualification runs with -DVOID_TARGET=..., and is validated against the
|
||||||
|
# selected modules so unsupported combinations fail at configure time with a
|
||||||
|
# useful message instead of deep inside a cross build.
|
||||||
|
#
|
||||||
|
# See docs/targets.md for the recorded tuples and their qualification status.
|
||||||
|
|
||||||
|
set(VOID_KNOWN_TARGETS linux linux-musl windows wasm)
|
||||||
|
|
||||||
|
set(VOID_TARGET "auto" CACHE STRING
|
||||||
|
"Target profile: auto (detect from the toolchain), ${VOID_KNOWN_TARGETS}")
|
||||||
|
set_property(CACHE VOID_TARGET PROPERTY STRINGS auto ${VOID_KNOWN_TARGETS})
|
||||||
|
|
||||||
|
# Browser/Wasm subset: pure computation modules only. Nothing here performs
|
||||||
|
# native I/O, spawns processes, loads shared libraries, uses SQLite, or needs
|
||||||
|
# C++26 reflection. Keep this list fail-closed: a module is added only after
|
||||||
|
# it has been configured and compiled for wasm32-unknown-emscripten.
|
||||||
|
# Qualified with Emscripten 6.0.9 (Clang 22, libc++) for configure, build,
|
||||||
|
# install, consume and run under Node, including the test suite with
|
||||||
|
# -pthread (see docs/targets.md).
|
||||||
|
set(VOID_WASM_MODULES
|
||||||
|
Algorithms
|
||||||
|
Binary
|
||||||
|
Containers
|
||||||
|
Core
|
||||||
|
Data
|
||||||
|
Functional
|
||||||
|
LogState
|
||||||
|
Math
|
||||||
|
Memory
|
||||||
|
Testing
|
||||||
|
TestingMock
|
||||||
|
Text
|
||||||
|
Time
|
||||||
|
Unicode
|
||||||
|
)
|
||||||
|
|
||||||
|
# Windows client subset: modules qualified with x86_64-w64-mingw32 (MinGW-w64).
|
||||||
|
# Filled from the cross-build and Wine runtime observations in
|
||||||
|
# docs/targets.md. IO is deliberately absent: it builds on Windows but its
|
||||||
|
# native backend is Linux-only (EpollBackend), so only the mock backend works.
|
||||||
|
set(VOID_WINDOWS_MODULES
|
||||||
|
Algorithms
|
||||||
|
Async
|
||||||
|
Binary
|
||||||
|
Containers
|
||||||
|
Core
|
||||||
|
Data
|
||||||
|
Discovery
|
||||||
|
Fsm
|
||||||
|
Functional
|
||||||
|
IO
|
||||||
|
Log
|
||||||
|
LogState
|
||||||
|
Math
|
||||||
|
Memory
|
||||||
|
Messaging
|
||||||
|
Observability
|
||||||
|
ObservabilityHooks
|
||||||
|
Scheduler
|
||||||
|
Service
|
||||||
|
Testing
|
||||||
|
TestingMock
|
||||||
|
Text
|
||||||
|
Time
|
||||||
|
Unicode
|
||||||
|
)
|
||||||
|
|
||||||
|
function(void_detect_target out_var)
|
||||||
|
if(NOT VOID_TARGET STREQUAL "auto")
|
||||||
|
set(${out_var} "${VOID_TARGET}" PARENT_SCOPE)
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(EMSCRIPTEN OR CMAKE_SYSTEM_NAME STREQUAL "Emscripten")
|
||||||
|
set(_target wasm)
|
||||||
|
elseif(WIN32)
|
||||||
|
set(_target windows)
|
||||||
|
elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||||
|
execute_process(
|
||||||
|
COMMAND "${CMAKE_C_COMPILER}" -dumpmachine
|
||||||
|
OUTPUT_VARIABLE _triple
|
||||||
|
ERROR_QUIET
|
||||||
|
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||||
|
if(_triple MATCHES "musl" OR
|
||||||
|
CMAKE_C_LIBRARY_ARCHITECTURE MATCHES "musl" OR
|
||||||
|
CMAKE_C_FLAGS MATCHES "musl")
|
||||||
|
set(_target linux-musl)
|
||||||
|
else()
|
||||||
|
set(_target linux)
|
||||||
|
endif()
|
||||||
|
else()
|
||||||
|
set(_target unsupported)
|
||||||
|
endif()
|
||||||
|
set(${out_var} "${_target}" PARENT_SCOPE)
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
function(_void_target_allowlist target out_var)
|
||||||
|
if(target STREQUAL "wasm")
|
||||||
|
set(${out_var} "${VOID_WASM_MODULES}" PARENT_SCOPE)
|
||||||
|
elseif(target STREQUAL "windows")
|
||||||
|
set(${out_var} "${VOID_WINDOWS_MODULES}" PARENT_SCOPE)
|
||||||
|
else()
|
||||||
|
# Linux and Linux/musl qualify every module: platform-specific code is
|
||||||
|
# selected inside the module sources.
|
||||||
|
set(${out_var} "" PARENT_SCOPE)
|
||||||
|
endif()
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
# Validate the detected/forced target against a module selection. Called
|
||||||
|
# from the top-level CMakeLists as soon as the selection is expanded (before
|
||||||
|
# any module dependency is resolved, so an unsupported browser-engine
|
||||||
|
# combination fails with the target message, not a missing-package error),
|
||||||
|
# and again after void_finalize_modules() for the all-modules default.
|
||||||
|
# With no arguments the configured module list is validated.
|
||||||
|
function(void_validate_target_modules)
|
||||||
|
void_detect_target(_target)
|
||||||
|
|
||||||
|
if(_target STREQUAL "unsupported")
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"[Void] Unsupported target '${CMAKE_SYSTEM_NAME} "
|
||||||
|
"${CMAKE_SYSTEM_PROCESSOR}'. Known targets: ${VOID_KNOWN_TARGETS}. "
|
||||||
|
"Pass -DVOID_TARGET=<target> only for a qualification run; "
|
||||||
|
"see docs/targets.md.")
|
||||||
|
endif()
|
||||||
|
if(NOT _target IN_LIST VOID_KNOWN_TARGETS)
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"[Void] Unknown VOID_TARGET='${_target}'. Known targets: "
|
||||||
|
"${VOID_KNOWN_TARGETS}.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(_target STREQUAL "wasm" AND VOID_ENABLE_TSAN)
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"[Void] ThreadSanitizer is not supported on the wasm target; "
|
||||||
|
"run native sanitizer builds separately (docs/targets.md).")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(ARGN)
|
||||||
|
set(_modules ${ARGN})
|
||||||
|
else()
|
||||||
|
get_property(_modules GLOBAL PROPERTY VOID_MODULES)
|
||||||
|
endif()
|
||||||
|
_void_target_allowlist(${_target} _allowed)
|
||||||
|
if(_allowed)
|
||||||
|
set(_rejected "")
|
||||||
|
foreach(_module IN LISTS _modules)
|
||||||
|
if(NOT _module IN_LIST _allowed)
|
||||||
|
list(APPEND _rejected ${_module})
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
if(_rejected)
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"[Void] Modules not supported on target '${_target}': "
|
||||||
|
"${_rejected}. Supported modules: ${_allowed}. "
|
||||||
|
"Select a supported subset with -DVOID_ENABLED_MODULES=... "
|
||||||
|
"or use a native target (docs/targets.md).")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(NOT DEFINED VOID_TARGET_DETECTED OR
|
||||||
|
NOT VOID_TARGET_DETECTED STREQUAL _target)
|
||||||
|
set(VOID_TARGET_DETECTED "${_target}" CACHE INTERNAL
|
||||||
|
"Detected or forced Void target profile" FORCE)
|
||||||
|
if(NOT VOID_TARGET STREQUAL "auto")
|
||||||
|
message(STATUS "[Void] Target forced to '${_target}' by VOID_TARGET")
|
||||||
|
else()
|
||||||
|
message(STATUS "[Void] Target: ${_target}")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
# Record the exact tuple this build was configured with. The manifest is
|
||||||
|
# installed next to VoidConfig.cmake so consumers can inspect what they got,
|
||||||
|
# and the qualification fixtures assert on it.
|
||||||
|
function(void_write_target_manifest path)
|
||||||
|
get_property(_modules GLOBAL PROPERTY VOID_MODULES)
|
||||||
|
list(JOIN _modules ";" _modules_value)
|
||||||
|
|
||||||
|
if(VOID_HAS_CXX26_REFLECTION)
|
||||||
|
set(_reflection yes)
|
||||||
|
else()
|
||||||
|
set(_reflection no)
|
||||||
|
endif()
|
||||||
|
if(VOID_HAS_STD_EXPECTED)
|
||||||
|
set(_expected yes)
|
||||||
|
else()
|
||||||
|
set(_expected no)
|
||||||
|
endif()
|
||||||
|
if(BUILD_SHARED_LIBS)
|
||||||
|
set(_linkage shared)
|
||||||
|
else()
|
||||||
|
set(_linkage static)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(_sanitizers "")
|
||||||
|
if(VOID_ENABLE_ASAN)
|
||||||
|
list(APPEND _sanitizers ASan)
|
||||||
|
endif()
|
||||||
|
if(VOID_ENABLE_UBSAN)
|
||||||
|
list(APPEND _sanitizers UBSan)
|
||||||
|
endif()
|
||||||
|
if(VOID_ENABLE_TSAN)
|
||||||
|
list(APPEND _sanitizers TSan)
|
||||||
|
endif()
|
||||||
|
if(NOT _sanitizers)
|
||||||
|
set(_sanitizers none)
|
||||||
|
else()
|
||||||
|
string(REPLACE ";" "+" _sanitizers "${_sanitizers}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
execute_process(
|
||||||
|
COMMAND "${CMAKE_C_COMPILER}" -dumpmachine
|
||||||
|
OUTPUT_VARIABLE _triple
|
||||||
|
ERROR_QUIET
|
||||||
|
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||||
|
|
||||||
|
set(_content
|
||||||
|
"# Generated by VoidLibrary's build system (cmake/Targets.cmake).
|
||||||
|
# Describes the exact target tuple this build was configured with.
|
||||||
|
set(VOID_TARGET_MANIFEST_TARGET \"${VOID_TARGET_DETECTED}\")
|
||||||
|
set(VOID_TARGET_MANIFEST_TARGET_ORIGIN \"${VOID_TARGET}\")
|
||||||
|
set(VOID_TARGET_MANIFEST_TRIPLE \"${_triple}\")
|
||||||
|
set(VOID_TARGET_MANIFEST_SYSTEM_NAME \"${CMAKE_SYSTEM_NAME}\")
|
||||||
|
set(VOID_TARGET_MANIFEST_SYSTEM_PROCESSOR \"${CMAKE_SYSTEM_PROCESSOR}\")
|
||||||
|
set(VOID_TARGET_MANIFEST_COMPILER_ID \"${CMAKE_CXX_COMPILER_ID}\")
|
||||||
|
set(VOID_TARGET_MANIFEST_COMPILER_VERSION \"${CMAKE_CXX_COMPILER_VERSION}\")
|
||||||
|
set(VOID_TARGET_MANIFEST_CXX_STANDARD \"${CMAKE_CXX_STANDARD}\")
|
||||||
|
set(VOID_TARGET_MANIFEST_LINKAGE \"${_linkage}\")
|
||||||
|
set(VOID_TARGET_MANIFEST_REFLECTION \"${_reflection}\")
|
||||||
|
set(VOID_TARGET_MANIFEST_STD_EXPECTED \"${_expected}\")
|
||||||
|
set(VOID_TARGET_MANIFEST_SANITIZERS \"${_sanitizers}\")
|
||||||
|
set(VOID_TARGET_MANIFEST_TESTING \"${VOID_ENABLE_TESTING}\")
|
||||||
|
set(VOID_TARGET_MANIFEST_WARNINGS_AS_ERRORS \"${VOID_WARNINGS_AS_ERRORS}\")
|
||||||
|
set(VOID_TARGET_MANIFEST_MODULES \"${_modules_value}\")
|
||||||
|
")
|
||||||
|
file(WRITE "${path}" "${_content}")
|
||||||
|
endfunction()
|
||||||
@@ -22,6 +22,15 @@ set(fixture_class_name "")
|
|||||||
set(fixture_indent "")
|
set(fixture_indent "")
|
||||||
set(line_number 0)
|
set(line_number 0)
|
||||||
|
|
||||||
|
# A Test/DisabledTest declaration may wrap across lines. These patterns let
|
||||||
|
# the loop join such a declaration into one logical line instead of silently
|
||||||
|
# dropping it (X-QA-03).
|
||||||
|
set(_test_decl_regex "(Void::Testing::)?(Test|DisabledTest)[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*\\(\\s*\\)")
|
||||||
|
set(_test_decl_start_regex "^[ \t]*(Void::Testing::)?(Test|DisabledTest)([ \t]|$)")
|
||||||
|
set(_test_decl_partial_regex "^[ \t]*(Void::Testing::)?(Test|DisabledTest)([ \t]+[A-Za-z_][A-Za-z0-9_]*)?[ \t]*\\(?[ \t]*$")
|
||||||
|
set(pending_decl "")
|
||||||
|
set(pending_decl_line 0)
|
||||||
|
|
||||||
# Accumulators for preceding comments
|
# Accumulators for preceding comments
|
||||||
set(current_tags "")
|
set(current_tags "")
|
||||||
set(current_skip "")
|
set(current_skip "")
|
||||||
@@ -33,6 +42,32 @@ foreach(line IN LISTS lines)
|
|||||||
string(REPLACE "__VOID_SCAN_SC__" ";" line "${line}")
|
string(REPLACE "__VOID_SCAN_SC__" ";" line "${line}")
|
||||||
string(REPLACE "__VOID_SCAN_BS__" "\\" line "${line}")
|
string(REPLACE "__VOID_SCAN_BS__" "\\" line "${line}")
|
||||||
|
|
||||||
|
# Join a wrapped test declaration before any other per-line handling so
|
||||||
|
# tags/skip comments that precede it stay associated with it.
|
||||||
|
set(registration_line ${line_number})
|
||||||
|
if(pending_decl)
|
||||||
|
string(APPEND pending_decl " ${line}")
|
||||||
|
if(pending_decl MATCHES "${_test_decl_regex}")
|
||||||
|
# Complete: process the joined declaration as one logical line.
|
||||||
|
set(line "${pending_decl}")
|
||||||
|
set(registration_line ${pending_decl_line})
|
||||||
|
set(pending_decl "")
|
||||||
|
elseif(pending_decl MATCHES "${_test_decl_partial_regex}")
|
||||||
|
continue()
|
||||||
|
else()
|
||||||
|
# Not a wrapped test declaration after all; handle this line
|
||||||
|
# normally and drop the accumulated prefix.
|
||||||
|
set(pending_decl "")
|
||||||
|
endif()
|
||||||
|
elseif(line MATCHES "${_test_decl_start_regex}" AND NOT line MATCHES "${_test_decl_regex}")
|
||||||
|
set(pending_decl "${line}")
|
||||||
|
set(pending_decl_line ${line_number})
|
||||||
|
if(pending_decl MATCHES "${_test_decl_partial_regex}")
|
||||||
|
continue()
|
||||||
|
endif()
|
||||||
|
set(pending_decl "")
|
||||||
|
endif()
|
||||||
|
|
||||||
# Parse preceding comments for @tag and @skip
|
# Parse preceding comments for @tag and @skip
|
||||||
string(REGEX MATCH "//[ \t]*@tag[ \t]+(.*)" _tag_match "${line}")
|
string(REGEX MATCH "//[ \t]*@tag[ \t]+(.*)" _tag_match "${line}")
|
||||||
if(_tag_match)
|
if(_tag_match)
|
||||||
@@ -129,11 +164,11 @@ foreach(line IN LISTS lines)
|
|||||||
|
|
||||||
if(in_fixture_class)
|
if(in_fixture_class)
|
||||||
string(APPEND registrations
|
string(APPEND registrations
|
||||||
"static Void::Testing::Detail::test_registrar<&${fixture_class_name}::${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${line_number}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
|
"static Void::Testing::Detail::test_registrar<&${fixture_class_name}::${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${registration_line}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
|
||||||
)
|
)
|
||||||
else()
|
else()
|
||||||
string(APPEND registrations
|
string(APPEND registrations
|
||||||
"static Void::Testing::Detail::test_registrar<&${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${line_number}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
|
"static Void::Testing::Detail::test_registrar<&${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${registration_line}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
|
||||||
)
|
)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# CMake toolchain for cross-compiling to Windows x64 with MinGW-w64.
|
||||||
|
#
|
||||||
|
# Works with the GCC-based mingw-w64 package and with the LLVM-MinGW
|
||||||
|
# toolchain (Dockerfile.mingw). Override the compiler paths for your install.
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
# cmake -B build-mingw -S . -G Ninja \
|
||||||
|
# -DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/mingw-w64.cmake \
|
||||||
|
# -DCMAKE_BUILD_TYPE=Debug
|
||||||
|
|
||||||
|
set(CMAKE_SYSTEM_NAME Windows)
|
||||||
|
set(CMAKE_SYSTEM_PROCESSOR x86_64)
|
||||||
|
|
||||||
|
if(NOT DEFINED VOID_MINGW_PREFIX)
|
||||||
|
set(VOID_MINGW_PREFIX x86_64-w64-mingw32)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
find_program(VOID_MINGW_CXX NAMES "${VOID_MINGW_PREFIX}-clang++"
|
||||||
|
"${VOID_MINGW_PREFIX}-g++" REQUIRED)
|
||||||
|
find_program(VOID_MINGW_C NAMES "${VOID_MINGW_PREFIX}-clang"
|
||||||
|
"${VOID_MINGW_PREFIX}-gcc" REQUIRED)
|
||||||
|
find_program(VOID_MINGW_RC NAMES "${VOID_MINGW_PREFIX}-windres")
|
||||||
|
|
||||||
|
set(CMAKE_CXX_COMPILER "${VOID_MINGW_CXX}")
|
||||||
|
set(CMAKE_C_COMPILER "${VOID_MINGW_C}")
|
||||||
|
if(VOID_MINGW_RC)
|
||||||
|
set(CMAKE_RC_COMPILER "${VOID_MINGW_RC}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
|
||||||
|
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
|
||||||
|
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
|
||||||
|
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
|
||||||
@@ -189,9 +189,9 @@ specs' observed baselines (D-035); not separately scheduled.
|
|||||||
|
|
||||||
| ID | Finding | Source | State |
|
| ID | Finding | Source | State |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| X-QA-01 | `VOID_WARNINGS_AS_ERRORS=ON` does not reach the generated `VoidTests` translation units, so test code is not compiled with `-Werror` | M-FUNCTIONAL-03 implementer report | PLANNED (verify, then fix in `tests/CMakeLists.txt`) |
|
| X-QA-01 | `VOID_WARNINGS_AS_ERRORS=ON` does not reach the generated `VoidTests` translation units, so test code is not compiled with `-Werror` | M-FUNCTIONAL-03 implementer report | VERIFIED (`77a2bce`): `tests/CMakeLists.txt` applies `-Wall -Wextra -Wpedantic -Werror` to `VoidTests` (with `-Wno-subobject-linkage` for GCC coroutine-frame noise); exposed warnings fixed in `Core/Meta.hpp` and `Time/Bench.cpp` |
|
||||||
| X-QA-02 | `src/Testing/Runner.cpp` recomputes pass/fail from only the first 1,000 retained assertions per test (`kMaxRetainedAssertionsPerTest`); later failures in one test can pass silently | M-FUNCTIONAL-03 implementer report | PLANNED (verify, then count failures independently of retention) |
|
| X-QA-02 | `src/Testing/Runner.cpp` recomputes pass/fail from only the first 1,000 retained assertions per test (`kMaxRetainedAssertionsPerTest`); later failures in one test can pass silently | M-FUNCTIONAL-03 implementer report | VERIFIED (`430deab`, merged `2501c4d`): `TestResult::failed_assertions` is counted in `Assert.cpp` at record time and both Runner paths use it, keeping the bounded retention for reporting; regression test `testing_runner_counts_failure_after_retention_cap` failed before and passes after; follow-up `898968d` resets the tally in the TestingMock failure-capture helper |
|
||||||
| X-QA-03 | Test scanner is line-anchored; a wrapped test declaration is silently dropped | M-FUNCTIONAL-03 implementer report | PLANNED (scanner hardening or lint) |
|
| X-QA-03 | Test scanner is line-anchored; a wrapped test declaration is silently dropped | M-FUNCTIONAL-03 implementer report | VERIFIED (`4bc8a7c`, merged `df41037`): `VoidTestScanner.cmake` joins wrapped `Test`/`DisabledTest` declarations; `ScannerWrapped` fixture covers wrapped return type, name and fixture member (4/4 discovered) |
|
||||||
| X-WF-01 | Agent `isolation: worktree` checkouts start at `main` (`38436b1`), not the wave branch tip; dispatches must fast-forward the worktree to the stated HEAD first | Observed in A1 | RECORDED (dispatch rule) |
|
| X-WF-01 | Agent `isolation: worktree` checkouts start at `main` (`38436b1`), not the wave branch tip; dispatches must fast-forward the worktree to the stated HEAD first | Observed in A1 | RECORDED (dispatch rule) |
|
||||||
|
|
||||||
## VoidForge upstream requests — M04 identity batch (received 2026-11-29; D-041)
|
## VoidForge upstream requests — M04 identity batch (received 2026-11-29; D-041)
|
||||||
@@ -202,4 +202,4 @@ specs' observed baselines (D-035); not separately scheduled.
|
|||||||
| VL-CRYPTO-02 | P1 | `pbkdf2_hmac_sha256(password, salt, iterations, out_len)` (RFC 8018 §5.2) on the builtin HMAC path; RFC 7914 §11 vectors; bounded iterations/output | PLANNED |
|
| VL-CRYPTO-02 | P1 | `pbkdf2_hmac_sha256(password, salt, iterations, out_len)` (RFC 8018 §5.2) on the builtin HMAC path; RFC 7914 §11 vectors; bounded iterations/output | PLANNED |
|
||||||
| VL-NET-02 | P1 (blocks Forge production email) | Public TLS client stream (TCP+TLS, CA + hostname verification, STARTTLS upgrade) + minimal SMTP submission client (EHLO, STARTTLS-required or implicit TLS, AUTH PLAIN over TLS only, MAIL/RCPT/DATA with dot-stuffing, bounded size, deadlines) | PLANNED |
|
| VL-NET-02 | P1 (blocks Forge production email) | Public TLS client stream (TCP+TLS, CA + hostname verification, STARTTLS upgrade) + minimal SMTP submission client (EHLO, STARTTLS-required or implicit TLS, AUTH PLAIN over TLS only, MAIL/RCPT/DATA with dot-stuffing, bounded size, deadlines) | PLANNED |
|
||||||
| VL-TEXT-01 | P2 | RFC 4648 base32 + Crockford base32 encode/decode | PLANNED |
|
| VL-TEXT-01 | P2 | RFC 4648 base32 + Crockford base32 encode/decode | PLANNED |
|
||||||
| X-QA-04 | AsyncRetry follow-ups from W11-REVIEW-B1b: race test only exercises the late-stop interleaving (add handshake/alternation); add direct checks of `detail::retry_backoff_stop_reason`; add a throwing-classifier test | W11-REVIEW-B1b P3-1/2/4 | PLANNED |
|
| X-QA-04 | AsyncRetry follow-ups from W11-REVIEW-B1b: race test only exercises the late-stop interleaving (add handshake/alternation); add direct checks of `detail::retry_backoff_stop_reason`; add a throwing-classifier test | W11-REVIEW-B1b P3-1/2/4 | VERIFIED (`65185f2`): added `async_retry_backoff_stop_reason_mapping`, `async_retry_stop_poll_handshake_alternation` (stop-first and poll-first orders) and `async_retry_throwing_classifier_propagates` |
|
||||||
+249
@@ -0,0 +1,249 @@
|
|||||||
|
# Target support
|
||||||
|
|
||||||
|
VoidLibrary is qualified per **target profile**: a platform, a compiler and
|
||||||
|
standard library, the external dependencies that are expected to exist, and
|
||||||
|
the set of modules that are expected to build there. The profile is detected
|
||||||
|
from the toolchain at configure time, validated against the selected modules,
|
||||||
|
and recorded in `void-target-manifest.cmake` (installed next to
|
||||||
|
`VoidConfig.cmake`).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Native Linux (default)
|
||||||
|
cmake -S . -B build -G Ninja -DVOID_ENABLE_TESTING=ON
|
||||||
|
|
||||||
|
# Force a profile for a qualification run (normally auto-detected)
|
||||||
|
cmake -S . -B build-wasm -G Ninja -DVOID_TARGET=wasm \
|
||||||
|
-DVOID_ENABLED_MODULES="Core;Functional;Text;Data"
|
||||||
|
|
||||||
|
# Cross build (Windows client example)
|
||||||
|
cmake -S . -B build-mingw -G Ninja \
|
||||||
|
-DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/mingw-w64.cmake \
|
||||||
|
-DVOID_ENABLED_MODULES="Core;Functional;Text;Data"
|
||||||
|
```
|
||||||
|
|
||||||
|
`VOID_TARGET` is `auto` by default. The recognized values are `linux`,
|
||||||
|
`linux-musl`, `windows` and `wasm`; anything else fails at configure time with
|
||||||
|
the list of known targets. `cmake/Targets.cmake` holds the allowlists and the
|
||||||
|
validation rules.
|
||||||
|
|
||||||
|
## Manifest
|
||||||
|
|
||||||
|
Every configure writes `void-target-manifest.cmake`:
|
||||||
|
|
||||||
|
| Field | Meaning |
|
||||||
|
|-------|---------|
|
||||||
|
| `VOID_TARGET_MANIFEST_TARGET` | detected/forced profile (`linux`, `linux-musl`, `windows`, `wasm`) |
|
||||||
|
| `VOID_TARGET_MANIFEST_TARGET_ORIGIN` | `auto` or the forced `VOID_TARGET` value |
|
||||||
|
| `VOID_TARGET_MANIFEST_TRIPLE` | `CMAKE_C_COMPILER -dumpmachine` |
|
||||||
|
| `VOID_TARGET_MANIFEST_SYSTEM_NAME` / `..._SYSTEM_PROCESSOR` | CMake system identification |
|
||||||
|
| `VOID_TARGET_MANIFEST_COMPILER_ID` / `..._COMPILER_VERSION` | compiler tuple |
|
||||||
|
| `VOID_TARGET_MANIFEST_CXX_STANDARD` | language standard |
|
||||||
|
| `VOID_TARGET_MANIFEST_LINKAGE` | `shared` or `static` |
|
||||||
|
| `VOID_TARGET_MANIFEST_REFLECTION` | C++26 reflection available (`yes`/`no`) |
|
||||||
|
| `VOID_TARGET_MANIFEST_STD_EXPECTED` | `<expected>` available |
|
||||||
|
| `VOID_TARGET_MANIFEST_SANITIZERS` | `none`, `ASan`, `UBSan`, `TSan` or a combination |
|
||||||
|
| `VOID_TARGET_MANIFEST_TESTING` | `VOID_ENABLE_TESTING` |
|
||||||
|
| `VOID_TARGET_MANIFEST_MODULES` | configured modules |
|
||||||
|
|
||||||
|
Consumers can read it after `find_package(Void)`:
|
||||||
|
|
||||||
|
```cmake
|
||||||
|
include("${Void_DIR}/void-target-manifest.cmake")
|
||||||
|
message(STATUS "Void target: ${VOID_TARGET_MANIFEST_TARGET}")
|
||||||
|
```
|
||||||
|
|
||||||
|
## Qualified tuples
|
||||||
|
|
||||||
|
### Linux (qualified)
|
||||||
|
|
||||||
|
| Item | Value |
|
||||||
|
|------|-------|
|
||||||
|
| Triple | `x86_64-unknown-linux-gnu` (NixOS, glibc) |
|
||||||
|
| Compiler | GCC 16.2.0 (`dev cpp-gcc`) |
|
||||||
|
| Standard library | libstdc++ 16 |
|
||||||
|
| CMake / generator | CMake 4.5.0, Ninja 1.13.2 |
|
||||||
|
| Language | C++26, reflection `yes` (`-freflection`) |
|
||||||
|
| Dependencies | Boost (headers/url/beast/asio), OpenSSL, SQLite3, Lua 5.4 (optional) |
|
||||||
|
| Modules | all |
|
||||||
|
| Observed | `Testing;Core` configure/build clean; `ctest` 3/3 (VoidTests, installed consumers, target qualification) |
|
||||||
|
|
||||||
|
The Linux profile is the reference target: every module is allowed and the
|
||||||
|
per-module platform code selects the native implementation.
|
||||||
|
|
||||||
|
### Linux / musl (configure/build/install/consume qualified)
|
||||||
|
|
||||||
|
| Item | Value |
|
||||||
|
|------|-------|
|
||||||
|
| Triple | `x86_64-alpine-linux-musl` (Alpine 3.23.8, musl 1.2.5-r24) |
|
||||||
|
| Compiler | Alpine GCC 15.2.0 (Clang accepted by the allowlist) |
|
||||||
|
| Standard library | libstdc++ with musl 1.2.5 |
|
||||||
|
| CMake / generator | CMake 4.1.3, Ninja 1.13.2 |
|
||||||
|
| Dependencies | `boost-dev` 1.84.0, `openssl-dev` 3.5.10, `sqlite-dev` 3.53.4, `lua5.4-dev` 5.4.8, `linux-headers` from apk |
|
||||||
|
| Language | C++26, reflection `no` (GCC 15), `<expected>` `yes` |
|
||||||
|
| Modules | `Async Binary Containers Core Crypto Data Functional FunctionalCoreFormatting IO IPC LogState Math Memory Net ObservabilityHooks Resilience Sqlite System SystemAsync Text Time` |
|
||||||
|
| Observed | RelWithDebInfo with `-DVOID_WARNINGS_AS_ERRORS=ON` and `-DVOID_ENABLE_TESTING=OFF`: configure detected `linux-musl`, build passed, `cmake --install` to a prefix succeeded, and the isolated `TargetProfile` consumer configured, linked, and ran (`VoidTargetProfileConsumer` 1/1) recording `target=linux-musl triple=x86_64-alpine-linux-musl compiler=GNU-15.2.0 linkage=shared reflection=no`. Test suite with `-DVOID_ENABLE_TESTING=ON`: 1226 tests, 1221 passed, 5 skipped, 0 failed |
|
||||||
|
|
||||||
|
The test suite is qualified too: with `VOID_ENABLE_TESTING=ON` (modules
|
||||||
|
`Async Binary Containers Core Crypto Data Functional FunctionalCoreFormatting
|
||||||
|
IO IPC LogState Math Memory Net ObservabilityHooks Resilience Sqlite System
|
||||||
|
SystemAsync Testing Text Time`) the Alpine 3.23 container build ran
|
||||||
|
**1226 tests: 1221 passed, 5 skipped, 0 failed**. Reflection-only tests are
|
||||||
|
skipped through `// @requires-reflection`. The run also exposed a test bug in
|
||||||
|
`Net/HttpDuplex.cpp` (`recv_until` consumed body bytes past the header
|
||||||
|
marker); the helper now reads byte-wise and the duplex tests pass on musl and
|
||||||
|
glibc.
|
||||||
|
|
||||||
|
Detection uses `CMAKE_C_COMPILER -dumpmachine` (or
|
||||||
|
`CMAKE_C_LIBRARY_ARCHITECTURE`/`CMAKE_C_FLAGS`) matching `musl`. The profile is
|
||||||
|
recognized and configured like Linux; musl-specific behaviour (subprocess
|
||||||
|
`/proc`, `dl`, locale) must still be verified before claiming full support.
|
||||||
|
|
||||||
|
### Windows client (compile/install/consume + Wine runtime qualified)
|
||||||
|
|
||||||
|
| Item | Value |
|
||||||
|
|------|-------|
|
||||||
|
| Triple | `x86_64-w64-mingw32` |
|
||||||
|
| Compiler | MinGW-w64 GCC 16.2.0 |
|
||||||
|
| Standard library | libstdc++ + mingw-w64 CRT (mcfgthread threading in the Nix wrapper) |
|
||||||
|
| CMake / generator | CMake 4.5.0, Ninja 1.13.2 |
|
||||||
|
| Language | C++26, reflection `yes` |
|
||||||
|
| Runtime | Wine 11.0 (`wine64`), no native Windows runner available |
|
||||||
|
| Modules | `Algorithms Async Binary Containers Core Data Discovery Fsm Functional Log LogState Math Memory Messaging Observability ObservabilityHooks Scheduler Service Testing TestingMock Text Time Unicode` |
|
||||||
|
| Observed | configure, compile, `cmake --install`, consume (`TargetProfile.exe` linked); `VoidTests.exe` under Wine: **1364 tests, 1360 passed, 4 skipped, 0 failed** |
|
||||||
|
|
||||||
|
Notes from the runtime run:
|
||||||
|
|
||||||
|
- `IO` is **not** in the Windows allowlist. It builds, but its native backend
|
||||||
|
is Linux-only (`EpollBackend`); on Windows `Driver::create` returns
|
||||||
|
`IoErrorCode::unsupported` unless the mock backend is selected. A Windows
|
||||||
|
IO backend (IOCP) is a separate task.
|
||||||
|
- `Observability` links after replacing the namespace-scope
|
||||||
|
`inline thread_local` hook stack with a function-local `thread_local`
|
||||||
|
accessor (MinGW emitted duplicate TLS init functions).
|
||||||
|
- Test code is portable: POSIX-only descriptor assertions are guarded, the
|
||||||
|
Log hardening test closes its `ifstream` before removing the file, and the
|
||||||
|
subprocess-isolation test skips when `current_executable_path()` is not
|
||||||
|
implemented (Windows has no subprocess isolation yet).
|
||||||
|
- MinGW test builds need `-Wa,-mbig-obj`: the Fsm hardening test TU exceeds
|
||||||
|
the COFF section limit with the default object format.
|
||||||
|
- Runtime observations come from Wine, not a native Windows runner; a
|
||||||
|
Windows CI runner should confirm them.
|
||||||
|
|
||||||
|
The Nix MinGW wrapper needs the mcfgthread include/library paths explicitly:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
MINGW=/nix/store/...-x86_64-w64-mingw32-gcc-wrapper-16.2.0/bin
|
||||||
|
MCFG=/nix/store/...-mcfgthread-x86_64-w64-mingw32-2.5.1/lib
|
||||||
|
MCFGINC=/nix/store/...-mcfgthread-x86_64-w64-mingw32-2.5.1-dev/include
|
||||||
|
cmake -S . -B build-mingw -G Ninja \
|
||||||
|
-DCMAKE_SYSTEM_NAME=Windows \
|
||||||
|
-DCMAKE_C_COMPILER="$MINGW/x86_64-w64-mingw32-gcc" \
|
||||||
|
-DCMAKE_CXX_COMPILER="$MINGW/x86_64-w64-mingw32-g++" \
|
||||||
|
-DCMAKE_C_FLAGS="-I$MCFGINC" -DCMAKE_CXX_FLAGS="-I$MCFGINC" \
|
||||||
|
-DCMAKE_EXE_LINKER_FLAGS="-L$MCFG" \
|
||||||
|
-DCMAKE_SHARED_LINKER_FLAGS="-L$MCFG"
|
||||||
|
```
|
||||||
|
|
||||||
|
A regular MinGW-w64 installation with winpthreads does not need those extra
|
||||||
|
flags.
|
||||||
|
|
||||||
|
### Browser / Wasm subset (qualified)
|
||||||
|
|
||||||
|
| Item | Value |
|
||||||
|
|------|-------|
|
||||||
|
| Triple | `wasm32-unknown-emscripten` |
|
||||||
|
| Compiler | Emscripten 6.0.9 (Clang 22.1.8) |
|
||||||
|
| Standard library | libc++ + Emscripten libc |
|
||||||
|
| CMake / generator | CMake 4.5 via `emcmake`, Ninja, Node 24.22.3 as the test emulator |
|
||||||
|
| Language | C++26 without reflection (`VOID_HAS_CXX26_REFLECTION=no`) |
|
||||||
|
| Modules | `Algorithms Binary Containers Core Data Functional LogState Math Memory Testing TestingMock Text Time Unicode` |
|
||||||
|
| Observed | library: configure, compile, install, consume and run under Node; tests: **901 tests, 895 passed, 6 skipped, 0 failed** under Node |
|
||||||
|
|
||||||
|
The allowlist is fail-closed: native networking (`Net`, `RPC`), processes and
|
||||||
|
filesystem (`System`, `SystemAsync`), IPC, SQLite, plugins and anything that
|
||||||
|
needs threads or reflection stay out. Do not add a module until it has been
|
||||||
|
configured and compiled with `emcmake`.
|
||||||
|
|
||||||
|
Verified commands:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Library subset
|
||||||
|
emcmake cmake -S . -B build-wasm -G Ninja -DCMAKE_BUILD_TYPE=Debug \
|
||||||
|
-DCMAKE_CXX_SCAN_FOR_MODULES=OFF \
|
||||||
|
-DVOID_ENABLE_TESTING=OFF \
|
||||||
|
-DVOID_ENABLED_MODULES="Algorithms;Binary;Containers;Core;Data;Functional;LogState;Math;Memory;Testing;TestingMock;Text;Time;Unicode"
|
||||||
|
cmake --build build-wasm
|
||||||
|
cmake --install build-wasm --prefix "$PWD/build-wasm-install"
|
||||||
|
|
||||||
|
# Consumer (the install lives outside the Emscripten sysroot)
|
||||||
|
emcmake cmake -S tests/package/TargetProfile -B build-wasm-consumer -G Ninja \
|
||||||
|
-DCMAKE_PREFIX_PATH="$PWD/build-wasm-install" \
|
||||||
|
-DCMAKE_FIND_ROOT_PATH_MODE_PACKAGE=BOTH \
|
||||||
|
-DCMAKE_CXX_SCAN_FOR_MODULES=OFF \
|
||||||
|
-DVOID_EXPECTED_TARGET=wasm
|
||||||
|
cmake --build build-wasm-consumer
|
||||||
|
node build-wasm-consumer/void_target_profile_consumer.js
|
||||||
|
```
|
||||||
|
|
||||||
|
`CMAKE_CXX_SCAN_FOR_MODULES=OFF` avoids CMake's C++20 module dependency
|
||||||
|
scanner calling Emscripten's `emscan-deps`, which is not shipped by every
|
||||||
|
Emscripten package. `CMAKE_FIND_ROOT_PATH_MODE_PACKAGE=BOTH` is needed
|
||||||
|
because the Emscripten toolchain restricts package lookup to its sysroot.
|
||||||
|
|
||||||
|
The **test suite** is qualified with pthreads, exception handling and a
|
||||||
|
larger stack:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
emcmake cmake -S . -B build-wasm-tests -G Ninja -DCMAKE_BUILD_TYPE=Debug \
|
||||||
|
-DCMAKE_CXX_SCAN_FOR_MODULES=OFF \
|
||||||
|
-DBUILD_SHARED_LIBS=OFF \
|
||||||
|
-DCMAKE_CXX_FLAGS="-fexceptions -pthread" \
|
||||||
|
-DCMAKE_EXE_LINKER_FLAGS="-fexceptions -pthread -sSTACK_SIZE=16777216 \
|
||||||
|
-sINITIAL_MEMORY=134217728 -sALLOW_MEMORY_GROWTH=1 -sMAXIMUM_MEMORY=1073741824" \
|
||||||
|
-DVOID_ENABLE_TESTING=ON \
|
||||||
|
-DVOID_ENABLED_MODULES="Algorithms;Binary;Containers;Core;Data;Functional;LogState;Math;Memory;Testing;TestingMock;Text;Time;Unicode"
|
||||||
|
cmake --build build-wasm-tests
|
||||||
|
node build-wasm-tests/tests/VoidTests.js --no-color
|
||||||
|
```
|
||||||
|
|
||||||
|
Static linking (`BUILD_SHARED_LIBS=OFF`) is required for exception handling
|
||||||
|
across the test binary; `-fexceptions` enables catching, `-pthread` enables
|
||||||
|
the threading tests, and the stack/memory flags accommodate the deepest
|
||||||
|
recursive tests.
|
||||||
|
|
||||||
|
Portable fallbacks added for libc++ without the C++23/26 pieces:
|
||||||
|
`Core/Publication` uses a mutex-protected `shared_ptr` when
|
||||||
|
`__cpp_lib_atomic_shared_ptr` is absent, and `TestingMock` uses an internal
|
||||||
|
move-only function wrapper when `__cpp_lib_move_only_function` is absent.
|
||||||
|
|
||||||
|
Reflection-dependent test files are gated with `// @requires-reflection`
|
||||||
|
(Core/Meta, Core/FlagsReflect, Data/CsvReflect, Data/Reflect*,
|
||||||
|
Functional/ResultReflectionFormat, Testing/ContainerFixture,
|
||||||
|
TestingMock/Reflect, Configuration/Fsm annotation tests) and are skipped when
|
||||||
|
`VOID_HAS_CXX26_REFLECTION` is false, so a non-reflecting compiler no longer
|
||||||
|
fails on scanner-generated registrations for functions hidden by `#ifdef`.
|
||||||
|
|
||||||
|
Runtime observations use Node; a browser runner should confirm them.
|
||||||
|
|
||||||
|
## Sanitizers
|
||||||
|
|
||||||
|
Sanitizer builds are native-only qualification configurations, not target
|
||||||
|
profiles: `VOID_ENABLE_ASAN`, `VOID_ENABLE_UBSAN` and `VOID_ENABLE_TSAN`
|
||||||
|
instrument the host build and are recorded in the manifest. Production
|
||||||
|
packages are built with sanitizers off. ASan+TSan is rejected; TSan is
|
||||||
|
rejected on `wasm`.
|
||||||
|
|
||||||
|
## Qualification test
|
||||||
|
|
||||||
|
`tests/package/TargetQualification.cmake` (ctest
|
||||||
|
`VoidTargetQualification`) installs the build tree and:
|
||||||
|
|
||||||
|
1. Consumes the install through `tests/package/TargetProfile`, asserting the
|
||||||
|
manifest target/triple/compiler/linkage/reflection fields and running one
|
||||||
|
Core behaviour.
|
||||||
|
2. Rejects an unknown `VOID_TARGET`.
|
||||||
|
3. Rejects a native module (`IPC`) and native networking (`Net`) on the
|
||||||
|
`wasm` profile.
|
||||||
|
4. Rejects a missing external dependency (`Sqlite` without SQLite3).
|
||||||
|
5. Configures the pure wasm subset and asserts the manifest records
|
||||||
|
`wasm`.
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Math/Vec.hpp>
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <cmath>
|
||||||
|
#include <compare>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <limits>
|
||||||
|
#include <optional>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::Algorithms
|
||||||
|
{
|
||||||
|
|
||||||
|
/// Integer cell index in the voxel grid.
|
||||||
|
struct GridCell {
|
||||||
|
std::int64_t x{0};
|
||||||
|
std::int64_t y{0};
|
||||||
|
std::int64_t z{0};
|
||||||
|
|
||||||
|
[[nodiscard]] auto operator<=>(const GridCell&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool operator==(const GridCell&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class GridAxis : std::uint8_t {
|
||||||
|
none = 0,
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
z,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Face crossed when entering a cell.
|
||||||
|
///
|
||||||
|
/// `sign` is the direction of travel along `axis`: `+1` means the ray crossed
|
||||||
|
/// the lower boundary (entered through the cell's negative face), `-1` means
|
||||||
|
/// it crossed the upper boundary. `axis == none` is the starting cell.
|
||||||
|
struct GridFace {
|
||||||
|
GridAxis axis{GridAxis::none};
|
||||||
|
int sign{0};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const GridFace&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct GridRayOptions {
|
||||||
|
/// Maximum number of cells yielded, including the start cell.
|
||||||
|
std::size_t max_steps{1024};
|
||||||
|
/// Maximum ray parameter for entering a cell. The start cell (t = 0) is
|
||||||
|
/// always yielded; a later cell is yielded only when its entry t is
|
||||||
|
/// `<= max_distance`.
|
||||||
|
double max_distance{std::numeric_limits<double>::infinity()};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct GridRayVisit {
|
||||||
|
GridCell cell;
|
||||||
|
GridFace face;
|
||||||
|
/// Ray parameter at which the cell was entered (0 for the start cell).
|
||||||
|
double t{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class GridRayStatus : std::uint8_t {
|
||||||
|
/// More cells may be produced.
|
||||||
|
running = 0,
|
||||||
|
exhausted_steps,
|
||||||
|
exhausted_distance,
|
||||||
|
/// The direction was exactly (0, 0, 0); the start cell was still yielded.
|
||||||
|
zero_direction,
|
||||||
|
nonfinite_input,
|
||||||
|
/// A cell index would leave the int64 range.
|
||||||
|
out_of_range,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Bounded 3D grid traversal (Amanatides-Woo DDA) over integer cells.
|
||||||
|
///
|
||||||
|
/// Policy:
|
||||||
|
/// - The start cell is `floor(origin)` per axis, so a coordinate exactly on a
|
||||||
|
/// boundary belongs to the cell on the positive side.
|
||||||
|
/// - Zero direction components never cross that axis (axis-parallel rays work).
|
||||||
|
/// - At simultaneous axis crossings (edge/corner ties) the axis with the lowest
|
||||||
|
/// index is stepped first: x, then y, then z. The traversal may therefore
|
||||||
|
/// visit the intermediate edge/corner cell; each visit reports the face it
|
||||||
|
/// crossed to enter.
|
||||||
|
/// - Nonfinite origin/direction is rejected before any visit. An all-zero
|
||||||
|
/// direction yields the start cell once and then reports `zero_direction`.
|
||||||
|
/// - The work is bounded by `max_steps` and `max_distance`.
|
||||||
|
class GridRayIterator
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
GridRayIterator(Void::Math::Vec3d origin,
|
||||||
|
Void::Math::Vec3d direction,
|
||||||
|
GridRayOptions options = {})
|
||||||
|
: options_(options)
|
||||||
|
{
|
||||||
|
if (!std::isfinite(origin.x) || !std::isfinite(origin.y) ||
|
||||||
|
!std::isfinite(origin.z) || !std::isfinite(direction.x) ||
|
||||||
|
!std::isfinite(direction.y) ||
|
||||||
|
!std::isfinite(direction.z) ||
|
||||||
|
std::isnan(options.max_distance)) {
|
||||||
|
status_ = GridRayStatus::nonfinite_input;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const double origin_axis[3] = {origin.x, origin.y, origin.z};
|
||||||
|
const double direction_axis[3] = {direction.x, direction.y,
|
||||||
|
direction.z};
|
||||||
|
bool any_direction = false;
|
||||||
|
for (int axis = 0; axis < 3; ++axis) {
|
||||||
|
const double coordinate = std::floor(origin_axis[axis]);
|
||||||
|
if (coordinate <
|
||||||
|
static_cast<double>(
|
||||||
|
std::numeric_limits<std::int64_t>::min()) ||
|
||||||
|
coordinate >
|
||||||
|
static_cast<double>(
|
||||||
|
std::numeric_limits<std::int64_t>::max())) {
|
||||||
|
status_ = GridRayStatus::out_of_range;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
cell_[axis] = static_cast<std::int64_t>(coordinate);
|
||||||
|
|
||||||
|
const double direction_value = direction_axis[axis];
|
||||||
|
if (direction_value == 0.0) {
|
||||||
|
step_[axis] = 0;
|
||||||
|
t_max_[axis] =
|
||||||
|
std::numeric_limits<double>::infinity();
|
||||||
|
t_delta_[axis] =
|
||||||
|
std::numeric_limits<double>::infinity();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
any_direction = true;
|
||||||
|
step_[axis] = direction_value > 0.0 ? 1 : -1;
|
||||||
|
const double boundary =
|
||||||
|
step_[axis] > 0
|
||||||
|
? static_cast<double>(cell_[axis]) + 1.0
|
||||||
|
: static_cast<double>(cell_[axis]);
|
||||||
|
t_max_[axis] =
|
||||||
|
(boundary - origin_axis[axis]) / direction_value;
|
||||||
|
t_delta_[axis] =
|
||||||
|
1.0 / std::abs(direction_value);
|
||||||
|
}
|
||||||
|
zero_direction_ = !any_direction;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::optional<GridRayVisit> next()
|
||||||
|
{
|
||||||
|
if (status_ != GridRayStatus::running) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
if (!started_) {
|
||||||
|
if (options_.max_steps == 0) {
|
||||||
|
status_ = GridRayStatus::exhausted_steps;
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
started_ = true;
|
||||||
|
visited_ = 1;
|
||||||
|
const GridRayVisit visit{.cell = GridCell{cell_[0], cell_[1],
|
||||||
|
cell_[2]},
|
||||||
|
.face = {},
|
||||||
|
.t = 0.0};
|
||||||
|
if (zero_direction_) {
|
||||||
|
status_ = GridRayStatus::zero_direction;
|
||||||
|
} else if (visited_ >= options_.max_steps) {
|
||||||
|
status_ = GridRayStatus::exhausted_steps;
|
||||||
|
}
|
||||||
|
return visit;
|
||||||
|
}
|
||||||
|
|
||||||
|
int axis = 0;
|
||||||
|
if (t_max_[1] < t_max_[axis]) {
|
||||||
|
axis = 1;
|
||||||
|
}
|
||||||
|
if (t_max_[2] < t_max_[axis]) {
|
||||||
|
axis = 2;
|
||||||
|
}
|
||||||
|
const double t = t_max_[axis];
|
||||||
|
if (t > options_.max_distance) {
|
||||||
|
status_ = GridRayStatus::exhausted_distance;
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
if ((step_[axis] > 0 &&
|
||||||
|
cell_[axis] == std::numeric_limits<std::int64_t>::max()) ||
|
||||||
|
(step_[axis] < 0 &&
|
||||||
|
cell_[axis] == std::numeric_limits<std::int64_t>::min())) {
|
||||||
|
status_ = GridRayStatus::out_of_range;
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
cell_[axis] += step_[axis];
|
||||||
|
t_max_[axis] += t_delta_[axis];
|
||||||
|
++visited_;
|
||||||
|
const GridRayVisit visit{
|
||||||
|
.cell = GridCell{cell_[0], cell_[1], cell_[2]},
|
||||||
|
.face = GridFace{
|
||||||
|
.axis = axis == 0 ? GridAxis::x
|
||||||
|
: axis == 1 ? GridAxis::y : GridAxis::z,
|
||||||
|
.sign = step_[axis]},
|
||||||
|
.t = t};
|
||||||
|
if (visited_ >= options_.max_steps) {
|
||||||
|
status_ = GridRayStatus::exhausted_steps;
|
||||||
|
}
|
||||||
|
return visit;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] GridRayStatus status() const noexcept
|
||||||
|
{
|
||||||
|
return status_;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] GridCell cell() const noexcept
|
||||||
|
{
|
||||||
|
return GridCell{cell_[0], cell_[1], cell_[2]};
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
GridRayOptions options_;
|
||||||
|
std::array<std::int64_t, 3> cell_{};
|
||||||
|
std::array<int, 3> step_{};
|
||||||
|
std::array<double, 3> t_max_{};
|
||||||
|
std::array<double, 3> t_delta_{};
|
||||||
|
GridRayStatus status_{GridRayStatus::running};
|
||||||
|
std::size_t visited_{0};
|
||||||
|
bool started_{false};
|
||||||
|
bool zero_direction_{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct GridRaycastResult {
|
||||||
|
std::optional<GridRayVisit> hit;
|
||||||
|
GridRayStatus status{GridRayStatus::running};
|
||||||
|
std::size_t visited{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Traverse until `occupied(cell)` is true, then return that cell and the face
|
||||||
|
/// it was entered through (the start cell reports `GridFace{}`).
|
||||||
|
template <typename Occupancy>
|
||||||
|
[[nodiscard]] GridRaycastResult
|
||||||
|
raycast_grid(Void::Math::Vec3d origin,
|
||||||
|
Void::Math::Vec3d direction,
|
||||||
|
Occupancy&& occupied,
|
||||||
|
GridRayOptions options = {})
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{origin, direction, options};
|
||||||
|
GridRaycastResult result;
|
||||||
|
while (const auto visit = iterator.next()) {
|
||||||
|
++result.visited;
|
||||||
|
if (occupied(visit->cell)) {
|
||||||
|
result.hit = *visit;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result.status = iterator.status();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Algorithms
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::Algorithms
|
||||||
|
{
|
||||||
|
|
||||||
|
enum class ReadSetStatus : std::uint8_t {
|
||||||
|
/// A new key/revision pair was recorded.
|
||||||
|
recorded = 0,
|
||||||
|
/// The same key with the same revision was already recorded.
|
||||||
|
unchanged,
|
||||||
|
/// The same key was observed with a different revision.
|
||||||
|
conflicting,
|
||||||
|
/// The entry bound is reached; nothing was recorded.
|
||||||
|
capacity_exceeded,
|
||||||
|
/// The key is empty.
|
||||||
|
invalid_key,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class ReadSetValidation : std::uint8_t {
|
||||||
|
valid = 0,
|
||||||
|
/// A recorded key is missing or has a different revision.
|
||||||
|
invalidated,
|
||||||
|
/// The validating view belongs to another epoch.
|
||||||
|
epoch_changed,
|
||||||
|
/// A conflicting observation was reported; the set cannot be published.
|
||||||
|
conflicted,
|
||||||
|
/// An observation was rejected for capacity; the set is incomplete.
|
||||||
|
incomplete,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ReadSetLimits {
|
||||||
|
std::size_t max_entries{256};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Bounded set of distinct key/revision pairs consulted while computing a
|
||||||
|
/// result, qualified by an epoch.
|
||||||
|
///
|
||||||
|
/// Repeated reads of one unchanged key consume one entry. Observing the same
|
||||||
|
/// key with a different revision is reported as a conflict, and an entry over
|
||||||
|
/// the bound as capacity exhaustion; `validate` refuses to report a conflicted
|
||||||
|
/// or incomplete set as valid so a result cannot be published from it.
|
||||||
|
///
|
||||||
|
/// Validation compares the recorded set against a stable read view supplied by
|
||||||
|
/// the caller (a revision lookup per key plus the view's epoch). An epoch
|
||||||
|
/// change invalidates the set even when every numeric revision matches. Keys
|
||||||
|
/// not in the set (unrelated edits) do not affect the result.
|
||||||
|
class RevisionReadSet
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
using Limits = ReadSetLimits;
|
||||||
|
|
||||||
|
explicit RevisionReadSet(std::uint64_t epoch, Limits limits = {})
|
||||||
|
: epoch_(epoch)
|
||||||
|
, limits_(limits)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::uint64_t epoch() const noexcept { return epoch_; }
|
||||||
|
|
||||||
|
[[nodiscard]] ReadSetStatus observe(std::string key,
|
||||||
|
std::uint64_t revision)
|
||||||
|
{
|
||||||
|
if (key.empty()) {
|
||||||
|
return ReadSetStatus::invalid_key;
|
||||||
|
}
|
||||||
|
if (const auto found = entries_.find(key);
|
||||||
|
found != entries_.end()) {
|
||||||
|
if (found->second == revision) {
|
||||||
|
return ReadSetStatus::unchanged;
|
||||||
|
}
|
||||||
|
conflicted_ = true;
|
||||||
|
return ReadSetStatus::conflicting;
|
||||||
|
}
|
||||||
|
if (entries_.size() >= limits_.max_entries) {
|
||||||
|
incomplete_ = true;
|
||||||
|
return ReadSetStatus::capacity_exceeded;
|
||||||
|
}
|
||||||
|
entries_.emplace(std::move(key), revision);
|
||||||
|
return ReadSetStatus::recorded;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool contains(std::string_view key) const
|
||||||
|
{
|
||||||
|
return entries_.contains(std::string{key});
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::optional<std::uint64_t>
|
||||||
|
revision_of(std::string_view key) const
|
||||||
|
{
|
||||||
|
const auto found = entries_.find(std::string{key});
|
||||||
|
if (found == entries_.end()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return found->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::size_t size() const noexcept
|
||||||
|
{
|
||||||
|
return entries_.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool conflicted() const noexcept { return conflicted_; }
|
||||||
|
[[nodiscard]] bool incomplete() const noexcept { return incomplete_; }
|
||||||
|
|
||||||
|
/// Recorded observations, sorted by key.
|
||||||
|
[[nodiscard]] const std::map<std::string, std::uint64_t>&
|
||||||
|
entries() const noexcept
|
||||||
|
{
|
||||||
|
return entries_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validate against a stable read view.
|
||||||
|
///
|
||||||
|
/// `lookup(key)` returns the current revision of `key`, or `nullopt`
|
||||||
|
/// when it no longer exists. `view_epoch` is the epoch of the view.
|
||||||
|
template <typename Lookup>
|
||||||
|
[[nodiscard]] ReadSetValidation
|
||||||
|
validate(std::uint64_t view_epoch, Lookup&& lookup) const
|
||||||
|
{
|
||||||
|
if (view_epoch != epoch_) {
|
||||||
|
return ReadSetValidation::epoch_changed;
|
||||||
|
}
|
||||||
|
if (conflicted_) {
|
||||||
|
return ReadSetValidation::conflicted;
|
||||||
|
}
|
||||||
|
if (incomplete_) {
|
||||||
|
return ReadSetValidation::incomplete;
|
||||||
|
}
|
||||||
|
for (const auto& [key, revision] : entries_) {
|
||||||
|
const auto current = lookup(key);
|
||||||
|
if (!current.has_value() || *current != revision) {
|
||||||
|
return ReadSetValidation::invalidated;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ReadSetValidation::valid;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
std::uint64_t epoch_{0};
|
||||||
|
Limits limits_{};
|
||||||
|
std::map<std::string, std::uint64_t> entries_;
|
||||||
|
bool conflicted_{false};
|
||||||
|
bool incomplete_{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Algorithms
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <deque>
|
||||||
|
#include <mutex>
|
||||||
|
#include <optional>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::Async
|
||||||
|
{
|
||||||
|
|
||||||
|
/// Bounded work queue whose admission is conditioned on an exact retained
|
||||||
|
/// publication token.
|
||||||
|
///
|
||||||
|
/// A producer validates a publication (and may retain its value elsewhere),
|
||||||
|
/// then submits work with that token. Comparison against the current token and
|
||||||
|
/// the capacity reservation happen under one lock, so a replacement published
|
||||||
|
/// between validation and submission is detected: the work is not moved and
|
||||||
|
/// the queue is unchanged.
|
||||||
|
///
|
||||||
|
/// Refusal outcomes are distinct: `publication_changed`, `saturated` and
|
||||||
|
/// `closed` (checked in that order). The payload is moved only when the result
|
||||||
|
/// is `admitted`. Admitted work is popped exactly once.
|
||||||
|
///
|
||||||
|
/// Thread-safe.
|
||||||
|
template <typename Work, typename Token = std::uint64_t>
|
||||||
|
class PublicationGatedQueue
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
struct Limits {
|
||||||
|
std::size_t capacity{64};
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class Status : std::uint8_t {
|
||||||
|
admitted = 0,
|
||||||
|
/// The current token differs from the expected one.
|
||||||
|
publication_changed,
|
||||||
|
/// The queue is at capacity.
|
||||||
|
saturated,
|
||||||
|
/// The queue no longer accepts submissions.
|
||||||
|
closed,
|
||||||
|
};
|
||||||
|
|
||||||
|
explicit PublicationGatedQueue(Token initial,
|
||||||
|
Limits limits = Limits{})
|
||||||
|
: token_(std::move(initial))
|
||||||
|
, limits_(limits)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
PublicationGatedQueue(const PublicationGatedQueue&) = delete;
|
||||||
|
PublicationGatedQueue& operator=(const PublicationGatedQueue&) =
|
||||||
|
delete;
|
||||||
|
|
||||||
|
/// Publish a replacement token. Returns false once closed.
|
||||||
|
bool publish(Token next)
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
if (closed_) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
token_ = std::move(next);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Token current() const
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
return token_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Admit `work` only if `expected` is still the current publication and
|
||||||
|
/// capacity is available. `work` is moved only on `admitted`.
|
||||||
|
[[nodiscard]] Status try_submit(const Token& expected, Work&& work)
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
if (closed_) {
|
||||||
|
return Status::closed;
|
||||||
|
}
|
||||||
|
if (!(token_ == expected)) {
|
||||||
|
return Status::publication_changed;
|
||||||
|
}
|
||||||
|
if (queue_.size() >= limits_.capacity) {
|
||||||
|
return Status::saturated;
|
||||||
|
}
|
||||||
|
queue_.push_back(std::move(work));
|
||||||
|
return Status::admitted;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove one admitted item, if any.
|
||||||
|
[[nodiscard]] std::optional<Work> try_pop()
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
if (queue_.empty()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
Work work = std::move(queue_.front());
|
||||||
|
queue_.pop_front();
|
||||||
|
return work;
|
||||||
|
}
|
||||||
|
|
||||||
|
void close()
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
closed_ = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool closed() const
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
return closed_;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::size_t size() const
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
return queue_.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Limits limits() const
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
return limits_;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
mutable std::mutex mutex_;
|
||||||
|
Token token_;
|
||||||
|
Limits limits_{};
|
||||||
|
std::deque<Work> queue_;
|
||||||
|
bool closed_{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Async
|
||||||
@@ -0,0 +1,416 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <compare>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <limits>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Containers
|
||||||
|
{
|
||||||
|
|
||||||
|
using LedgerQuantity = std::uint64_t;
|
||||||
|
using LedgerAccountKey = std::string;
|
||||||
|
using LedgerOperationId = std::string;
|
||||||
|
|
||||||
|
struct LedgerDebit {
|
||||||
|
LedgerAccountKey account;
|
||||||
|
LedgerQuantity quantity{0};
|
||||||
|
|
||||||
|
[[nodiscard]] auto operator<=>(const LedgerDebit&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool operator==(const LedgerDebit&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class LedgerStatus : std::uint8_t {
|
||||||
|
committed = 0,
|
||||||
|
/// The operation already committed; the recorded outcome is returned.
|
||||||
|
replayed,
|
||||||
|
insufficient_balance,
|
||||||
|
capacity_exhausted,
|
||||||
|
overflow,
|
||||||
|
unknown_operation,
|
||||||
|
unknown_account,
|
||||||
|
/// Operation id reused with a different request or a forbidden phase.
|
||||||
|
invalid_state,
|
||||||
|
/// A released reservation cannot be delivered.
|
||||||
|
released,
|
||||||
|
limit_exceeded,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class ReservationPhase : std::uint8_t {
|
||||||
|
held = 0,
|
||||||
|
delivered,
|
||||||
|
released,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct LedgerResult {
|
||||||
|
LedgerStatus status{LedgerStatus::unknown_operation};
|
||||||
|
ReservationPhase phase{ReservationPhase::held};
|
||||||
|
LedgerOperationId operation;
|
||||||
|
|
||||||
|
[[nodiscard]] bool committed() const noexcept
|
||||||
|
{
|
||||||
|
return status == LedgerStatus::committed ||
|
||||||
|
status == LedgerStatus::replayed;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const LedgerResult&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct LedgerLimits {
|
||||||
|
std::size_t max_accounts{1024};
|
||||||
|
std::size_t max_operations{4096};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// In-memory, restorable account ledger with atomic multi-account
|
||||||
|
/// reservations and repeatable transfers.
|
||||||
|
///
|
||||||
|
/// Accounts are caller-keyed and carry an owner, a balance and a capacity.
|
||||||
|
/// `reserve` debits one or more accounts atomically into a held reservation;
|
||||||
|
/// `transfer` gives the reserved quantity to a destination account (the next
|
||||||
|
/// owner); `release` returns it to the sources without changing ownership.
|
||||||
|
///
|
||||||
|
/// Every committed phase is recorded under its operation id, so repeating the
|
||||||
|
/// same request returns the recorded outcome instead of applying it twice.
|
||||||
|
/// The state is a plain value: `save()` can be persisted and `restore()`d, and
|
||||||
|
/// a replay after restoring a partially completed transfer still applies once.
|
||||||
|
/// Failed attempts (insufficient balance, capacity, overflow) change nothing
|
||||||
|
/// and are not recorded, so they can be retried after conditions change.
|
||||||
|
///
|
||||||
|
/// Single-threaded by contract; callers synchronize concurrent access.
|
||||||
|
class AccountLedger
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
using Limits = LedgerLimits;
|
||||||
|
|
||||||
|
struct AccountState {
|
||||||
|
std::string owner;
|
||||||
|
LedgerQuantity balance{0};
|
||||||
|
LedgerQuantity capacity{
|
||||||
|
std::numeric_limits<LedgerQuantity>::max()};
|
||||||
|
|
||||||
|
[[nodiscard]] auto
|
||||||
|
operator<=>(const AccountState&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const AccountState&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct OperationState {
|
||||||
|
/// Normalized (aggregated and sorted) debits of the reservation.
|
||||||
|
std::vector<LedgerDebit> sources;
|
||||||
|
ReservationPhase phase{ReservationPhase::held};
|
||||||
|
LedgerAccountKey destination;
|
||||||
|
|
||||||
|
[[nodiscard]] auto
|
||||||
|
operator<=>(const OperationState&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const OperationState&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct State {
|
||||||
|
std::map<LedgerAccountKey, AccountState> accounts;
|
||||||
|
std::map<LedgerOperationId, OperationState> operations;
|
||||||
|
|
||||||
|
[[nodiscard]] auto
|
||||||
|
operator<=>(const State&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const State&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
explicit AccountLedger(Limits limits = Limits{}) : limits_(limits) {}
|
||||||
|
|
||||||
|
[[nodiscard]] const Limits& limits() const noexcept { return limits_; }
|
||||||
|
|
||||||
|
[[nodiscard]] bool create_account(const LedgerAccountKey& key,
|
||||||
|
std::string owner,
|
||||||
|
LedgerQuantity balance = 0,
|
||||||
|
LedgerQuantity capacity =
|
||||||
|
std::numeric_limits<
|
||||||
|
LedgerQuantity>::max())
|
||||||
|
{
|
||||||
|
if (balance > capacity ||
|
||||||
|
accounts_.size() >= limits_.max_accounts ||
|
||||||
|
accounts_.contains(key)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
accounts_.emplace(key,
|
||||||
|
AccountState{.owner = std::move(owner),
|
||||||
|
.balance = balance,
|
||||||
|
.capacity = capacity});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool set_capacity(const LedgerAccountKey& key,
|
||||||
|
LedgerQuantity capacity)
|
||||||
|
{
|
||||||
|
const auto found = accounts_.find(key);
|
||||||
|
if (found == accounts_.end() ||
|
||||||
|
found->second.balance > capacity) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
found->second.capacity = capacity;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::optional<AccountState>
|
||||||
|
account(const LedgerAccountKey& key) const
|
||||||
|
{
|
||||||
|
const auto found = accounts_.find(key);
|
||||||
|
if (found == accounts_.end()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return found->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sum of all balances plus quantities held in reservations.
|
||||||
|
[[nodiscard]] LedgerQuantity total() const
|
||||||
|
{
|
||||||
|
LedgerQuantity sum = 0;
|
||||||
|
for (const auto& [key, account] : accounts_) {
|
||||||
|
(void)key;
|
||||||
|
sum += account.balance;
|
||||||
|
}
|
||||||
|
for (const auto& [id, operation] : operations_) {
|
||||||
|
(void)id;
|
||||||
|
if (operation.phase == ReservationPhase::held) {
|
||||||
|
for (const auto& debit : operation.sources) {
|
||||||
|
sum += debit.quantity;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sum;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::size_t account_count() const noexcept
|
||||||
|
{
|
||||||
|
return accounts_.size();
|
||||||
|
}
|
||||||
|
[[nodiscard]] std::size_t operation_count() const noexcept
|
||||||
|
{
|
||||||
|
return operations_.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Atomically debit every source into a held reservation.
|
||||||
|
[[nodiscard]] LedgerResult
|
||||||
|
reserve(const LedgerOperationId& operation,
|
||||||
|
std::vector<LedgerDebit> debits)
|
||||||
|
{
|
||||||
|
for (const auto& debit : debits) {
|
||||||
|
if (debit.account.empty() || debit.quantity == 0) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::invalid_state,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
auto normalized = normalize(std::move(debits));
|
||||||
|
if (!normalized.has_value()) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::overflow,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (const auto existing = operations_.find(operation);
|
||||||
|
existing != operations_.end()) {
|
||||||
|
if (existing->second.sources != *normalized) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::invalid_state,
|
||||||
|
.phase = existing->second.phase,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
return LedgerResult{.status = LedgerStatus::replayed,
|
||||||
|
.phase = existing->second.phase,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (operations_.size() >= limits_.max_operations) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::limit_exceeded,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const auto& debit : *normalized) {
|
||||||
|
const auto found = accounts_.find(debit.account);
|
||||||
|
if (found == accounts_.end()) {
|
||||||
|
return LedgerResult{
|
||||||
|
.status = LedgerStatus::unknown_account,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
if (found->second.balance < debit.quantity) {
|
||||||
|
return LedgerResult{
|
||||||
|
.status = LedgerStatus::insufficient_balance,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// All preconditions hold: apply every debit.
|
||||||
|
for (const auto& debit : *normalized) {
|
||||||
|
accounts_.at(debit.account).balance -= debit.quantity;
|
||||||
|
}
|
||||||
|
operations_.emplace(operation,
|
||||||
|
OperationState{.sources = std::move(*normalized),
|
||||||
|
.phase = ReservationPhase::held,
|
||||||
|
.destination = {}});
|
||||||
|
return LedgerResult{.status = LedgerStatus::committed,
|
||||||
|
.phase = ReservationPhase::held,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return a held reservation to its sources. Ownership is unchanged.
|
||||||
|
[[nodiscard]] LedgerResult release(const LedgerOperationId& operation)
|
||||||
|
{
|
||||||
|
const auto found = operations_.find(operation);
|
||||||
|
if (found == operations_.end()) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::unknown_operation,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
if (found->second.phase == ReservationPhase::released) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::replayed,
|
||||||
|
.phase = ReservationPhase::released,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
if (found->second.phase == ReservationPhase::delivered) {
|
||||||
|
return LedgerResult{
|
||||||
|
.status = LedgerStatus::invalid_state,
|
||||||
|
.phase = ReservationPhase::delivered,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
for (const auto& debit : found->second.sources) {
|
||||||
|
accounts_.at(debit.account).balance += debit.quantity;
|
||||||
|
}
|
||||||
|
found->second.phase = ReservationPhase::released;
|
||||||
|
return LedgerResult{.status = LedgerStatus::committed,
|
||||||
|
.phase = ReservationPhase::released,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deliver a held reservation to `destination` (the next owner).
|
||||||
|
/// On capacity/overflow failure nothing changes and the reservation
|
||||||
|
/// stays held, so the caller can retry or release it.
|
||||||
|
[[nodiscard]] LedgerResult
|
||||||
|
transfer(const LedgerOperationId& operation,
|
||||||
|
const LedgerAccountKey& destination)
|
||||||
|
{
|
||||||
|
const auto found = operations_.find(operation);
|
||||||
|
if (found == operations_.end()) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::unknown_operation,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
if (found->second.phase == ReservationPhase::released) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::released,
|
||||||
|
.phase = ReservationPhase::released,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
if (found->second.phase == ReservationPhase::delivered) {
|
||||||
|
return LedgerResult{
|
||||||
|
.status = found->second.destination == destination
|
||||||
|
? LedgerStatus::replayed
|
||||||
|
: LedgerStatus::invalid_state,
|
||||||
|
.phase = ReservationPhase::delivered,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto target = accounts_.find(destination);
|
||||||
|
if (target == accounts_.end()) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::unknown_account,
|
||||||
|
.phase = ReservationPhase::held,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
LedgerQuantity quantity = 0;
|
||||||
|
for (const auto& debit : found->second.sources) {
|
||||||
|
if (debit.quantity >
|
||||||
|
std::numeric_limits<LedgerQuantity>::max() - quantity) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::overflow,
|
||||||
|
.phase = ReservationPhase::held,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
quantity += debit.quantity;
|
||||||
|
}
|
||||||
|
if (quantity >
|
||||||
|
target->second.capacity - target->second.balance) {
|
||||||
|
return LedgerResult{.status = LedgerStatus::capacity_exhausted,
|
||||||
|
.phase = ReservationPhase::held,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
target->second.balance += quantity;
|
||||||
|
found->second.phase = ReservationPhase::delivered;
|
||||||
|
found->second.destination = destination;
|
||||||
|
return LedgerResult{.status = LedgerStatus::committed,
|
||||||
|
.phase = ReservationPhase::delivered,
|
||||||
|
.operation = operation};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] State save() const
|
||||||
|
{
|
||||||
|
return State{.accounts = accounts_, .operations = operations_};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rebuild a ledger from `save()` output. Rejects states that violate
|
||||||
|
/// the limits or the balance/capacity and reservation invariants.
|
||||||
|
[[nodiscard]] static std::optional<AccountLedger>
|
||||||
|
restore(State state, Limits limits = Limits{})
|
||||||
|
{
|
||||||
|
if (state.accounts.size() > limits.max_accounts ||
|
||||||
|
state.operations.size() > limits.max_operations) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
for (const auto& [key, account] : state.accounts) {
|
||||||
|
(void)key;
|
||||||
|
if (account.balance > account.capacity) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto& [id, operation] : state.operations) {
|
||||||
|
(void)id;
|
||||||
|
if (operation.sources.empty()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
for (const auto& debit : operation.sources) {
|
||||||
|
if (!state.accounts.contains(debit.account)) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (operation.phase == ReservationPhase::delivered &&
|
||||||
|
!state.accounts.contains(operation.destination)) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AccountLedger ledger{limits};
|
||||||
|
ledger.accounts_ = std::move(state.accounts);
|
||||||
|
ledger.operations_ = std::move(state.operations);
|
||||||
|
return ledger;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
[[nodiscard]] static std::optional<std::vector<LedgerDebit>>
|
||||||
|
normalize(std::vector<LedgerDebit> debits)
|
||||||
|
{
|
||||||
|
std::map<LedgerAccountKey, LedgerQuantity> aggregated;
|
||||||
|
for (const auto& debit : debits) {
|
||||||
|
LedgerQuantity& sum = aggregated[debit.account];
|
||||||
|
if (debit.quantity >
|
||||||
|
std::numeric_limits<LedgerQuantity>::max() - sum) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
sum += debit.quantity;
|
||||||
|
}
|
||||||
|
std::vector<LedgerDebit> normalized;
|
||||||
|
normalized.reserve(aggregated.size());
|
||||||
|
for (auto& [account, quantity] : aggregated) {
|
||||||
|
normalized.push_back(
|
||||||
|
LedgerDebit{.account = std::move(account),
|
||||||
|
.quantity = quantity});
|
||||||
|
}
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
Limits limits_{};
|
||||||
|
std::map<LedgerAccountKey, AccountState> accounts_;
|
||||||
|
std::map<LedgerOperationId, OperationState> operations_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Containers
|
||||||
@@ -0,0 +1,323 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <limits>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <set>
|
||||||
|
#include <span>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Containers
|
||||||
|
{
|
||||||
|
|
||||||
|
/// Finite sparse 3D page table with revision-checked atomic edit batches.
|
||||||
|
///
|
||||||
|
/// Cells are grouped into fixed `PageSize`-cubed pages. Pages are allocated on
|
||||||
|
/// demand (a missing page reads as `empty` with revision 0) and bounded by
|
||||||
|
/// `Limits::max_pages`. `apply` validates every precondition, budget and
|
||||||
|
/// revision before touching the table; on failure nothing changes.
|
||||||
|
///
|
||||||
|
/// Batch semantics:
|
||||||
|
/// - Duplicate cell addresses in one batch are rejected.
|
||||||
|
/// - An edit whose value equals the current cell does not allocate a page and
|
||||||
|
/// does not bump a revision.
|
||||||
|
/// - `expected_revision` is checked against the page revision at batch start
|
||||||
|
/// (0 for a missing page).
|
||||||
|
/// - A changed page whose revision is already the maximum fails the batch.
|
||||||
|
/// - The result lists changed pages sorted by page identity with their new
|
||||||
|
/// revisions.
|
||||||
|
///
|
||||||
|
/// Single-threaded by contract; callers synchronize concurrent access.
|
||||||
|
template <typename Cell, std::size_t PageSize = 32> class SparsePageTable
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
static_assert(PageSize > 0);
|
||||||
|
|
||||||
|
static constexpr std::size_t kPageSize = PageSize;
|
||||||
|
static constexpr std::size_t kCellsPerPage =
|
||||||
|
PageSize * PageSize * PageSize;
|
||||||
|
|
||||||
|
using Revision = std::uint64_t;
|
||||||
|
|
||||||
|
struct PageId {
|
||||||
|
std::int64_t x{0};
|
||||||
|
std::int64_t y{0};
|
||||||
|
std::int64_t z{0};
|
||||||
|
|
||||||
|
[[nodiscard]] auto
|
||||||
|
operator<=>(const PageId&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const PageId&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct CellAddress {
|
||||||
|
std::int64_t x{0};
|
||||||
|
std::int64_t y{0};
|
||||||
|
std::int64_t z{0};
|
||||||
|
|
||||||
|
[[nodiscard]] auto
|
||||||
|
operator<=>(const CellAddress&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const CellAddress&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Edit {
|
||||||
|
CellAddress address;
|
||||||
|
Cell value;
|
||||||
|
std::optional<Revision> expected_revision{};
|
||||||
|
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const Edit&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Limits {
|
||||||
|
std::size_t max_pages{1024};
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class EditStatus : std::uint8_t {
|
||||||
|
committed = 0,
|
||||||
|
/// A page's expected revision did not match the current one.
|
||||||
|
stale_revision,
|
||||||
|
/// A changed page already has the maximum revision.
|
||||||
|
revision_exhausted,
|
||||||
|
/// The batch would allocate more pages than the budget allows.
|
||||||
|
page_budget_exceeded,
|
||||||
|
/// The same cell address appears twice in the batch.
|
||||||
|
duplicate_edit,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ChangedPage {
|
||||||
|
PageId page;
|
||||||
|
Revision revision{0};
|
||||||
|
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const ChangedPage&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct EditResult {
|
||||||
|
EditStatus status{EditStatus::committed};
|
||||||
|
std::vector<ChangedPage> changed{};
|
||||||
|
|
||||||
|
[[nodiscard]] bool committed() const noexcept
|
||||||
|
{
|
||||||
|
return status == EditStatus::committed;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct PageState {
|
||||||
|
PageId page;
|
||||||
|
Revision revision{0};
|
||||||
|
std::array<Cell, kCellsPerPage> cells{};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const PageState&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct State {
|
||||||
|
std::vector<PageState> pages;
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const State&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
explicit SparsePageTable(Limits limits = Limits{},
|
||||||
|
Cell empty = Cell{})
|
||||||
|
: limits_(limits)
|
||||||
|
, empty_(std::move(empty))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] const Limits& limits() const noexcept { return limits_; }
|
||||||
|
[[nodiscard]] const Cell& empty_value() const noexcept
|
||||||
|
{
|
||||||
|
return empty_;
|
||||||
|
}
|
||||||
|
[[nodiscard]] std::size_t page_count() const noexcept
|
||||||
|
{
|
||||||
|
return pages_.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cell value; a missing page yields `empty_value()`.
|
||||||
|
[[nodiscard]] Cell get(CellAddress address) const
|
||||||
|
{
|
||||||
|
const auto [id, offset] = locate(address);
|
||||||
|
const auto found = pages_.find(id);
|
||||||
|
if (found == pages_.end()) {
|
||||||
|
return empty_;
|
||||||
|
}
|
||||||
|
return found->second.cells[offset];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Page revision, or `nullopt` when the page is not allocated.
|
||||||
|
[[nodiscard]] std::optional<Revision>
|
||||||
|
page_revision(PageId page) const
|
||||||
|
{
|
||||||
|
const auto found = pages_.find(page);
|
||||||
|
if (found == pages_.end()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return found->second.revision;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply all edits or none.
|
||||||
|
[[nodiscard]] EditResult apply(std::span<const Edit> edits)
|
||||||
|
{
|
||||||
|
if (edits.empty()) {
|
||||||
|
return EditResult{};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::set<CellAddress> seen;
|
||||||
|
std::map<PageId, std::vector<const Edit*>> grouped;
|
||||||
|
for (const auto& edit : edits) {
|
||||||
|
if (!seen.insert(edit.address).second) {
|
||||||
|
return EditResult{.status =
|
||||||
|
EditStatus::duplicate_edit};
|
||||||
|
}
|
||||||
|
grouped[page_of(edit.address)].push_back(&edit);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::map<PageId, bool> changes;
|
||||||
|
std::size_t new_pages = 0;
|
||||||
|
for (const auto& [id, page_edits] : grouped) {
|
||||||
|
const auto found = pages_.find(id);
|
||||||
|
const Page* page =
|
||||||
|
found == pages_.end() ? nullptr : &found->second;
|
||||||
|
const Revision revision = page == nullptr ? 0
|
||||||
|
: page->revision;
|
||||||
|
for (const Edit* edit : page_edits) {
|
||||||
|
if (edit->expected_revision.has_value() &&
|
||||||
|
*edit->expected_revision != revision) {
|
||||||
|
return EditResult{
|
||||||
|
.status = EditStatus::stale_revision};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bool changed = false;
|
||||||
|
for (const Edit* edit : page_edits) {
|
||||||
|
const auto offset = offset_of(edit->address);
|
||||||
|
const Cell& current =
|
||||||
|
page == nullptr ? empty_ : page->cells[offset];
|
||||||
|
if (!(current == edit->value)) {
|
||||||
|
changed = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!changed) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (revision ==
|
||||||
|
std::numeric_limits<Revision>::max()) {
|
||||||
|
return EditResult{
|
||||||
|
.status = EditStatus::revision_exhausted};
|
||||||
|
}
|
||||||
|
changes.emplace(id, true);
|
||||||
|
if (page == nullptr) {
|
||||||
|
++new_pages;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pages_.size() + new_pages > limits_.max_pages) {
|
||||||
|
return EditResult{.status =
|
||||||
|
EditStatus::page_budget_exceeded};
|
||||||
|
}
|
||||||
|
|
||||||
|
EditResult result;
|
||||||
|
for (const auto& [id, changed] : changes) {
|
||||||
|
(void)changed;
|
||||||
|
auto& page = pages_[id];
|
||||||
|
for (const Edit* edit : grouped.at(id)) {
|
||||||
|
page.cells[offset_of(edit->address)] = edit->value;
|
||||||
|
}
|
||||||
|
++page.revision;
|
||||||
|
result.changed.push_back(
|
||||||
|
ChangedPage{.page = id, .revision = page.revision});
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] State save() const
|
||||||
|
{
|
||||||
|
State state;
|
||||||
|
state.pages.reserve(pages_.size());
|
||||||
|
for (const auto& [id, page] : pages_) {
|
||||||
|
state.pages.push_back(PageState{
|
||||||
|
.page = id, .revision = page.revision, .cells = page.cells});
|
||||||
|
}
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Restore saved pages. Rejects duplicate page ids, more pages than the
|
||||||
|
/// limit, or a page with no revision left for an edit.
|
||||||
|
[[nodiscard]] static std::optional<SparsePageTable>
|
||||||
|
restore(State state, Limits limits = Limits{},
|
||||||
|
Cell empty = Cell{})
|
||||||
|
{
|
||||||
|
if (state.pages.size() > limits.max_pages) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
SparsePageTable table{limits, std::move(empty)};
|
||||||
|
for (auto& saved : state.pages) {
|
||||||
|
if (!table.pages_
|
||||||
|
.emplace(saved.page,
|
||||||
|
Page{.cells = saved.cells,
|
||||||
|
.revision = saved.revision})
|
||||||
|
.second) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct Page {
|
||||||
|
std::array<Cell, kCellsPerPage> cells{};
|
||||||
|
Revision revision{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] static std::pair<std::int64_t, std::size_t>
|
||||||
|
split(std::int64_t coordinate)
|
||||||
|
{
|
||||||
|
constexpr auto size = static_cast<std::int64_t>(PageSize);
|
||||||
|
std::int64_t page = coordinate / size;
|
||||||
|
std::int64_t offset = coordinate % size;
|
||||||
|
if (offset < 0) {
|
||||||
|
--page;
|
||||||
|
offset += size;
|
||||||
|
}
|
||||||
|
return {page, static_cast<std::size_t>(offset)};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] static PageId page_of(CellAddress address)
|
||||||
|
{
|
||||||
|
return PageId{.x = split(address.x).first,
|
||||||
|
.y = split(address.y).first,
|
||||||
|
.z = split(address.z).first};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] static std::size_t offset_of(CellAddress address)
|
||||||
|
{
|
||||||
|
const auto [px, ox] = split(address.x);
|
||||||
|
const auto [py, oy] = split(address.y);
|
||||||
|
const auto [pz, oz] = split(address.z);
|
||||||
|
(void)px;
|
||||||
|
(void)py;
|
||||||
|
(void)pz;
|
||||||
|
return (oz * PageSize + oy) * PageSize + ox;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] static std::pair<PageId, std::size_t>
|
||||||
|
locate(CellAddress address)
|
||||||
|
{
|
||||||
|
return {page_of(address), offset_of(address)};
|
||||||
|
}
|
||||||
|
|
||||||
|
Limits limits_{};
|
||||||
|
Cell empty_{};
|
||||||
|
std::map<PageId, Page> pages_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Containers
|
||||||
@@ -253,7 +253,9 @@ namespace Void::Meta
|
|||||||
out += "?";
|
out += "?";
|
||||||
}
|
}
|
||||||
out += '{';
|
out += '{';
|
||||||
bool first = true;
|
// Reflectable types with no members (e.g. std::optional) leave this
|
||||||
|
// unread; the diagnostic is about a deliberately empty loop body.
|
||||||
|
[[maybe_unused]] bool first = true;
|
||||||
template for (constexpr auto m : members_v<T>)
|
template for (constexpr auto m : members_v<T>)
|
||||||
{
|
{
|
||||||
if (!first) {
|
if (!first) {
|
||||||
|
|||||||
@@ -0,0 +1,280 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <compare>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <memory>
|
||||||
|
#include <optional>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
#if !defined(__cpp_lib_atomic_shared_ptr)
|
||||||
|
#include <mutex>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace Void::Core
|
||||||
|
{
|
||||||
|
|
||||||
|
/// Identity of a published snapshot: an epoch (session/domain) and a revision
|
||||||
|
/// that increases within that epoch.
|
||||||
|
struct PublicationVersion {
|
||||||
|
std::uint64_t epoch{0};
|
||||||
|
std::uint64_t revision{0};
|
||||||
|
|
||||||
|
[[nodiscard]] auto operator<=>(const PublicationVersion&) const noexcept =
|
||||||
|
default;
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const PublicationVersion&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Single-writer, multi-reader publication of immutable values.
|
||||||
|
///
|
||||||
|
/// A producer prepares a complete immutable value and calls `publish` with its
|
||||||
|
/// version; readers call `acquire` and keep the returned `Snapshot` alive for
|
||||||
|
/// as long as they need a coherent view. Publishing swaps one fully built state
|
||||||
|
/// atomically: a reader sees either the previous or the next snapshot, never a
|
||||||
|
/// mixture, and a retained snapshot stays valid across any number of later
|
||||||
|
/// publications.
|
||||||
|
///
|
||||||
|
/// `publish` is compare-and-publish: when `expected_epoch` is supplied it must
|
||||||
|
/// equal the current epoch, and the new version must advance the current one
|
||||||
|
/// (higher epoch, or same epoch with a higher revision). A rejected publish
|
||||||
|
/// leaves the last good publication untouched, so a failed preparation that
|
||||||
|
/// never calls `publish` cannot corrupt readers.
|
||||||
|
///
|
||||||
|
/// The value is released when the publication and the last reader holding it
|
||||||
|
/// drop their snapshots.
|
||||||
|
template <typename T> class Publication
|
||||||
|
{
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct State {
|
||||||
|
std::shared_ptr<const T> value;
|
||||||
|
PublicationVersion version;
|
||||||
|
};
|
||||||
|
|
||||||
|
public:
|
||||||
|
|
||||||
|
using Value = T;
|
||||||
|
|
||||||
|
/// Retained, immutable view of one publication.
|
||||||
|
class Snapshot
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
Snapshot() noexcept = default;
|
||||||
|
|
||||||
|
[[nodiscard]] explicit operator bool() const noexcept
|
||||||
|
{
|
||||||
|
return state_ != nullptr && state_->value != nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] const T& operator*() const noexcept
|
||||||
|
{
|
||||||
|
return *state_->value;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] const T* operator->() const noexcept
|
||||||
|
{
|
||||||
|
return state_->value.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] const T* get() const noexcept
|
||||||
|
{
|
||||||
|
return state_ != nullptr ? state_->value.get()
|
||||||
|
: nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] PublicationVersion version() const noexcept
|
||||||
|
{
|
||||||
|
return state_ != nullptr ? state_->version
|
||||||
|
: PublicationVersion{};
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
friend class Publication;
|
||||||
|
|
||||||
|
explicit Snapshot(std::shared_ptr<const State> state) noexcept
|
||||||
|
: state_(std::move(state))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
std::shared_ptr<const State> state_{};
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class PublishStatus : std::uint8_t {
|
||||||
|
published = 0,
|
||||||
|
/// The supplied or expected epoch is obsolete.
|
||||||
|
stale_epoch,
|
||||||
|
/// Same epoch, but the revision does not advance.
|
||||||
|
stale_revision,
|
||||||
|
/// The value is null.
|
||||||
|
invalid_value,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct PublishResult {
|
||||||
|
PublishStatus status{PublishStatus::invalid_value};
|
||||||
|
PublicationVersion version{};
|
||||||
|
|
||||||
|
[[nodiscard]] bool published() const noexcept
|
||||||
|
{
|
||||||
|
return status == PublishStatus::published;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
explicit Publication(std::shared_ptr<const T> initial,
|
||||||
|
PublicationVersion version = {})
|
||||||
|
: current_{std::make_shared<State>(
|
||||||
|
State{std::move(initial), version})}
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
Publication(const Publication&) = delete;
|
||||||
|
Publication& operator=(const Publication&) = delete;
|
||||||
|
|
||||||
|
/// Current snapshot; the returned handle keeps the value alive.
|
||||||
|
[[nodiscard]] Snapshot acquire() const
|
||||||
|
{
|
||||||
|
return Snapshot{
|
||||||
|
current_.load(std::memory_order_acquire)};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] PublicationVersion version() const
|
||||||
|
{
|
||||||
|
return current_.load(std::memory_order_acquire)->version;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::uint64_t epoch() const
|
||||||
|
{
|
||||||
|
return version().epoch;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The version that `publish_next` would use: same epoch, next revision.
|
||||||
|
[[nodiscard]] PublicationVersion next_version() const
|
||||||
|
{
|
||||||
|
PublicationVersion next = version();
|
||||||
|
++next.revision;
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Publish `value` as `next`, optionally requiring `expected_epoch`.
|
||||||
|
///
|
||||||
|
/// The whole state (value and version) is swapped with one atomic
|
||||||
|
/// compare-exchange; on rejection nothing changes.
|
||||||
|
[[nodiscard]] PublishResult
|
||||||
|
publish(std::shared_ptr<const T> value,
|
||||||
|
PublicationVersion next,
|
||||||
|
std::optional<std::uint64_t> expected_epoch = std::nullopt)
|
||||||
|
{
|
||||||
|
if (value == nullptr) {
|
||||||
|
return PublishResult{.status = PublishStatus::invalid_value,
|
||||||
|
.version = version()};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::shared_ptr<State> current =
|
||||||
|
current_.load(std::memory_order_acquire);
|
||||||
|
for (;;) {
|
||||||
|
const PublicationVersion& observed = current->version;
|
||||||
|
if (expected_epoch.has_value() &&
|
||||||
|
*expected_epoch != observed.epoch) {
|
||||||
|
return PublishResult{.status = PublishStatus::stale_epoch,
|
||||||
|
.version = observed};
|
||||||
|
}
|
||||||
|
if (next.epoch < observed.epoch) {
|
||||||
|
return PublishResult{.status = PublishStatus::stale_epoch,
|
||||||
|
.version = observed};
|
||||||
|
}
|
||||||
|
if (next.epoch == observed.epoch &&
|
||||||
|
next.revision <= observed.revision) {
|
||||||
|
return PublishResult{
|
||||||
|
.status = PublishStatus::stale_revision,
|
||||||
|
.version = observed};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::shared_ptr<State> desired =
|
||||||
|
std::make_shared<State>(State{value, next});
|
||||||
|
if (current_.compare_exchange_weak(
|
||||||
|
current,
|
||||||
|
std::move(desired),
|
||||||
|
std::memory_order_acq_rel,
|
||||||
|
std::memory_order_acquire)) {
|
||||||
|
return PublishResult{.status = PublishStatus::published,
|
||||||
|
.version = next};
|
||||||
|
}
|
||||||
|
// `current` now holds the state that won the race; retry the
|
||||||
|
// validation and the exchange against it.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convenience for the common case: same epoch, next revision.
|
||||||
|
[[nodiscard]] PublishResult
|
||||||
|
publish_next(std::shared_ptr<const T> value,
|
||||||
|
std::optional<std::uint64_t> expected_epoch =
|
||||||
|
std::nullopt)
|
||||||
|
{
|
||||||
|
return publish(std::move(value), next_version(), expected_epoch);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start a new epoch at revision 0, optionally requiring the previous
|
||||||
|
/// epoch.
|
||||||
|
[[nodiscard]] PublishResult
|
||||||
|
publish_epoch(std::shared_ptr<const T> value,
|
||||||
|
std::uint64_t epoch,
|
||||||
|
std::optional<std::uint64_t> expected_epoch =
|
||||||
|
std::nullopt)
|
||||||
|
{
|
||||||
|
return publish(std::move(value),
|
||||||
|
PublicationVersion{.epoch = epoch, .revision = 0},
|
||||||
|
expected_epoch);
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
#if defined(__cpp_lib_atomic_shared_ptr)
|
||||||
|
std::atomic<std::shared_ptr<State>> current_;
|
||||||
|
#else
|
||||||
|
// Older libc++ (e.g. Emscripten) does not implement the
|
||||||
|
// atomic<shared_ptr> specialization. Keep the same load /
|
||||||
|
// compare-exchange surface with a mutex-protected pointer; the
|
||||||
|
// publication is still coherent for single-writer/multi-reader use.
|
||||||
|
class AtomicStatePtr
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
explicit AtomicStatePtr(std::shared_ptr<State> initial)
|
||||||
|
: current_(std::move(initial))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::shared_ptr<State>
|
||||||
|
load(std::memory_order) const
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
return current_;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool compare_exchange_weak(std::shared_ptr<State>& expected,
|
||||||
|
std::shared_ptr<State> desired,
|
||||||
|
std::memory_order,
|
||||||
|
std::memory_order)
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
if (current_ != expected) {
|
||||||
|
expected = current_;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
current_ = std::move(desired);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
mutable std::mutex mutex_;
|
||||||
|
std::shared_ptr<State> current_;
|
||||||
|
};
|
||||||
|
|
||||||
|
AtomicStatePtr current_;
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Core
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <compare>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <expected>
|
||||||
|
#include <limits>
|
||||||
|
#include <optional>
|
||||||
|
|
||||||
|
namespace Void::Core
|
||||||
|
{
|
||||||
|
|
||||||
|
enum class SequenceErrorKind : std::uint8_t {
|
||||||
|
/// The requested id or batch does not fit in the remaining range.
|
||||||
|
exhausted = 0,
|
||||||
|
/// A batch of zero ids was requested.
|
||||||
|
zero_count,
|
||||||
|
/// The supplied saved state is not a valid sequence state.
|
||||||
|
invalid_state,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SequenceError {
|
||||||
|
SequenceErrorKind kind{SequenceErrorKind::exhausted};
|
||||||
|
/// How many ids were still available when the request failed.
|
||||||
|
std::uint64_t available{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Instance-owned, restorable id sequence with checked exhaustion.
|
||||||
|
///
|
||||||
|
/// Unlike `Void::Counted::SeqId<Tag>` (one process-wide atomic per tag), each
|
||||||
|
/// `IdSequence` owns its own state. It can be copied at a completed boundary,
|
||||||
|
/// saved and restored, and several instances (e.g. two worlds in one process)
|
||||||
|
/// allocate independently.
|
||||||
|
///
|
||||||
|
/// Ids start at 1. A removed record never gives its id back: the high-water
|
||||||
|
/// mark only moves forward, including across save/restore. `next()` and
|
||||||
|
/// `next_batch()` return `exhausted` *before* changing state when the request
|
||||||
|
/// does not fit, so a failed allocation leaves both the sequence and any
|
||||||
|
/// application record untouched.
|
||||||
|
///
|
||||||
|
/// `Rep` is the fixed-width representation used in saved state (default
|
||||||
|
/// `std::uint64_t`), making cross-platform saves reproducible. `Tag` keeps
|
||||||
|
/// unrelated id domains from being confused at compile time.
|
||||||
|
///
|
||||||
|
/// The class is not thread-safe; callers synchronize concurrent access to one
|
||||||
|
/// instance.
|
||||||
|
template <typename Tag = void, typename Rep = std::uint64_t> class IdSequence
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
using value_type = Rep;
|
||||||
|
|
||||||
|
/// Serializable position. `exhausted` distinguishes "max is still
|
||||||
|
/// available" (`next == max`) from "max was already handed out".
|
||||||
|
struct State {
|
||||||
|
value_type next{1};
|
||||||
|
bool exhausted{false};
|
||||||
|
|
||||||
|
[[nodiscard]] auto
|
||||||
|
operator<=>(const State&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const State&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Batch {
|
||||||
|
value_type first{0};
|
||||||
|
value_type count{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
constexpr IdSequence() noexcept = default;
|
||||||
|
|
||||||
|
explicit constexpr IdSequence(value_type first) noexcept
|
||||||
|
: state_{.next = first == 0 ? value_type{1} : first}
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Allocate one id.
|
||||||
|
[[nodiscard]] std::expected<value_type, SequenceError> next()
|
||||||
|
{
|
||||||
|
if (state_.exhausted) {
|
||||||
|
return fail(SequenceErrorKind::exhausted);
|
||||||
|
}
|
||||||
|
const value_type id = state_.next;
|
||||||
|
if (id == maximum()) {
|
||||||
|
state_.exhausted = true;
|
||||||
|
} else {
|
||||||
|
state_.next = static_cast<value_type>(id + 1);
|
||||||
|
}
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reserve a contiguous batch atomically: either all `count` ids are
|
||||||
|
/// reserved or none are.
|
||||||
|
[[nodiscard]] std::expected<Batch, SequenceError>
|
||||||
|
next_batch(std::size_t count)
|
||||||
|
{
|
||||||
|
if (count == 0) {
|
||||||
|
return fail(SequenceErrorKind::zero_count);
|
||||||
|
}
|
||||||
|
if (state_.exhausted) {
|
||||||
|
return fail(SequenceErrorKind::exhausted);
|
||||||
|
}
|
||||||
|
const auto remaining = static_cast<std::uintmax_t>(available());
|
||||||
|
if (static_cast<std::uintmax_t>(count) > remaining) {
|
||||||
|
return fail(SequenceErrorKind::exhausted);
|
||||||
|
}
|
||||||
|
const value_type first = state_.next;
|
||||||
|
const auto step = static_cast<value_type>(count);
|
||||||
|
if (static_cast<std::uintmax_t>(step) == remaining) {
|
||||||
|
state_.exhausted = true;
|
||||||
|
} else {
|
||||||
|
state_.next = static_cast<value_type>(first + step);
|
||||||
|
}
|
||||||
|
return Batch{.first = first, .count = step};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many ids can still be allocated.
|
||||||
|
[[nodiscard]] value_type available() const noexcept
|
||||||
|
{
|
||||||
|
if (state_.exhausted) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return static_cast<value_type>(maximum() - state_.next + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool exhausted() const noexcept
|
||||||
|
{
|
||||||
|
return state_.exhausted;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The next id that would be handed out (or max once exhausted).
|
||||||
|
[[nodiscard]] value_type peek() const noexcept { return state_.next; }
|
||||||
|
|
||||||
|
/// Highest id ever handed out (0 before the first allocation).
|
||||||
|
[[nodiscard]] value_type high_water() const noexcept
|
||||||
|
{
|
||||||
|
if (state_.exhausted) {
|
||||||
|
return maximum();
|
||||||
|
}
|
||||||
|
return state_.next == 1 ? value_type{0}
|
||||||
|
: static_cast<value_type>(state_.next - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] State state() const noexcept { return state_; }
|
||||||
|
|
||||||
|
/// Restore a saved state. Rejects non-canonical or impossible states;
|
||||||
|
/// on success the sequence continues exactly after the saved position.
|
||||||
|
[[nodiscard]] static std::expected<IdSequence, SequenceError>
|
||||||
|
restore(State state)
|
||||||
|
{
|
||||||
|
if (state.next == 0) {
|
||||||
|
return std::unexpected{SequenceError{
|
||||||
|
.kind = SequenceErrorKind::invalid_state, .available = 0}};
|
||||||
|
}
|
||||||
|
if (state.exhausted && state.next != maximum()) {
|
||||||
|
return std::unexpected{SequenceError{
|
||||||
|
.kind = SequenceErrorKind::invalid_state,
|
||||||
|
.available = 0}};
|
||||||
|
}
|
||||||
|
IdSequence sequence;
|
||||||
|
sequence.state_ = state;
|
||||||
|
return sequence;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] static constexpr value_type maximum() noexcept
|
||||||
|
{
|
||||||
|
return std::numeric_limits<value_type>::max();
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
[[nodiscard]] std::unexpected<SequenceError>
|
||||||
|
fail(SequenceErrorKind kind) const
|
||||||
|
{
|
||||||
|
return std::unexpected{SequenceError{
|
||||||
|
.kind = kind,
|
||||||
|
.available = static_cast<std::uint64_t>(available())}};
|
||||||
|
}
|
||||||
|
|
||||||
|
State state_{};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Core
|
||||||
@@ -5,6 +5,7 @@
|
|||||||
#include <Void/Functional/Result.hpp>
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <span>
|
#include <span>
|
||||||
@@ -166,6 +167,48 @@ namespace Void::Crypto
|
|||||||
const Ed25519PublicKey& public_key,
|
const Ed25519PublicKey& public_key,
|
||||||
const ProviderOptions& provider = {});
|
const ProviderOptions& provider = {});
|
||||||
|
|
||||||
|
/// Convenience key pair returned by ed25519_keypair(). The secret seed is
|
||||||
|
/// a move-only, self-wiping handle; prefer the typed Ed25519PrivateKey APIs
|
||||||
|
/// when the key can stay inside an owning handle.
|
||||||
|
struct Ed25519KeyPair {
|
||||||
|
Ed25519Seed secret_key;
|
||||||
|
Ed25519PublicKey public_key;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Generate a fresh Ed25519 key pair. Requires the OpenSSL backend.
|
||||||
|
[[nodiscard]] Void::Result::Result<Ed25519KeyPair>
|
||||||
|
ed25519_keypair(const ProviderOptions& provider = {});
|
||||||
|
|
||||||
|
/// Sign exact message bytes with a 32-byte Ed25519 seed/secret key. The
|
||||||
|
/// temporary private-key handle is wiped when it goes out of scope; prefer
|
||||||
|
/// sign_ed25519() when the caller already owns an Ed25519PrivateKey.
|
||||||
|
[[nodiscard]] Void::Result::Result<Ed25519Signature>
|
||||||
|
ed25519_sign(std::span<const std::byte> secret_key,
|
||||||
|
std::span<const std::byte> message,
|
||||||
|
const ProviderOptions& provider = {});
|
||||||
|
|
||||||
|
/// Verify a detached Ed25519 signature over exact message bytes.
|
||||||
|
/// Malformed key/signature sizes are errors; a well-formed but invalid
|
||||||
|
/// signature returns false.
|
||||||
|
[[nodiscard]] Void::Result::Result<bool>
|
||||||
|
ed25519_verify(std::span<const std::byte> public_key,
|
||||||
|
std::span<const std::byte> message,
|
||||||
|
std::span<const std::byte> signature,
|
||||||
|
const ProviderOptions& provider = {});
|
||||||
|
|
||||||
|
/// Compute HMAC-SHA-1 (RFC 2104) into a caller-owned 20-byte buffer.
|
||||||
|
/// Wipes output on backend failure and rejects overlapping buffers.
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
hmac_sha1_into(std::span<const std::byte> secret_key,
|
||||||
|
std::span<const std::byte> message,
|
||||||
|
std::span<std::byte> output,
|
||||||
|
const ProviderOptions& provider = {});
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<Digest>
|
||||||
|
hmac_sha1(std::span<const std::byte> secret_key,
|
||||||
|
std::span<const std::byte> message,
|
||||||
|
const ProviderOptions& provider = {});
|
||||||
|
|
||||||
/// Compute HMAC-SHA-256 into a caller-owned 32-byte buffer.
|
/// Compute HMAC-SHA-256 into a caller-owned 32-byte buffer.
|
||||||
/// Wipes output on backend failure and rejects overlapping buffers.
|
/// Wipes output on backend failure and rejects overlapping buffers.
|
||||||
[[nodiscard]] Void::Result::Result<void>
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
@@ -179,6 +222,25 @@ namespace Void::Crypto
|
|||||||
std::span<const std::byte> message,
|
std::span<const std::byte> message,
|
||||||
const ProviderOptions& provider = {});
|
const ProviderOptions& provider = {});
|
||||||
|
|
||||||
|
/// Derive key material with RFC 8018 PBKDF2-HMAC-SHA-256 into a
|
||||||
|
/// caller-owned buffer. iterations must be 1..kMaxPbkdf2Iterations, salt
|
||||||
|
/// at most kMaxPbkdf2SaltBytes and output 1..kMaxPbkdf2OutputBytes.
|
||||||
|
/// Rejects overlapping buffers and wipes output on any failure after
|
||||||
|
/// validation.
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
pbkdf2_hmac_sha256_into(std::span<const std::byte> password,
|
||||||
|
std::span<const std::byte> salt,
|
||||||
|
std::uint32_t iterations,
|
||||||
|
std::span<std::byte> output,
|
||||||
|
const ProviderOptions& provider = {});
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<Digest>
|
||||||
|
pbkdf2_hmac_sha256(std::span<const std::byte> password,
|
||||||
|
std::span<const std::byte> salt,
|
||||||
|
std::uint32_t iterations,
|
||||||
|
std::size_t output_length,
|
||||||
|
const ProviderOptions& provider = {});
|
||||||
|
|
||||||
/// Derive key material with RFC 5869 HKDF-SHA-256 into a caller-owned
|
/// Derive key material with RFC 5869 HKDF-SHA-256 into a caller-owned
|
||||||
/// buffer (1..CryptoLimits::kMaxHkdfOutputBytes). Rejects overlapping
|
/// buffer (1..CryptoLimits::kMaxHkdfOutputBytes). Rejects overlapping
|
||||||
/// buffers and wipes secret_output on any failure after validation.
|
/// buffers and wipes secret_output on any failure after validation.
|
||||||
|
|||||||
@@ -16,12 +16,16 @@ namespace Void::Crypto
|
|||||||
inline constexpr std::size_t Ed25519PublicKeySize = 32;
|
inline constexpr std::size_t Ed25519PublicKeySize = 32;
|
||||||
inline constexpr std::size_t Ed25519SignatureSize = 64;
|
inline constexpr std::size_t Ed25519SignatureSize = 64;
|
||||||
inline constexpr std::size_t Ed25519SeedSize = 32;
|
inline constexpr std::size_t Ed25519SeedSize = 32;
|
||||||
|
inline constexpr std::size_t HmacSha1Size = 20;
|
||||||
inline constexpr std::size_t HmacSha256Size = 32;
|
inline constexpr std::size_t HmacSha256Size = 32;
|
||||||
|
|
||||||
struct CryptoLimits {
|
struct CryptoLimits {
|
||||||
static constexpr std::size_t kMaxOneShotMessageBytes =
|
static constexpr std::size_t kMaxOneShotMessageBytes =
|
||||||
16ULL * 1024ULL * 1024ULL;
|
16ULL * 1024ULL * 1024ULL;
|
||||||
static constexpr std::size_t kMaxHkdfOutputBytes = 4ULL * 1024ULL;
|
static constexpr std::size_t kMaxHkdfOutputBytes = 4ULL * 1024ULL;
|
||||||
|
static constexpr std::uint32_t kMaxPbkdf2Iterations = 10'000'000U;
|
||||||
|
static constexpr std::size_t kMaxPbkdf2SaltBytes = 64ULL * 1024ULL;
|
||||||
|
static constexpr std::size_t kMaxPbkdf2OutputBytes = 1024ULL;
|
||||||
static constexpr std::size_t kStreamChunkBytes = 64ULL * 1024ULL;
|
static constexpr std::size_t kStreamChunkBytes = 64ULL * 1024ULL;
|
||||||
static constexpr std::size_t kDefaultMaxConcurrentFileHashes = 8;
|
static constexpr std::size_t kDefaultMaxConcurrentFileHashes = 8;
|
||||||
static constexpr std::size_t kDefaultMaxWaitingFileHashes = 32;
|
static constexpr std::size_t kDefaultMaxWaitingFileHashes = 32;
|
||||||
@@ -256,7 +260,8 @@ namespace Void::Crypto
|
|||||||
ed25519_sign,
|
ed25519_sign,
|
||||||
ed25519_verify,
|
ed25519_verify,
|
||||||
hmac,
|
hmac,
|
||||||
hkdf
|
hkdf,
|
||||||
|
pbkdf2
|
||||||
};
|
};
|
||||||
|
|
||||||
struct FaultConfig {
|
struct FaultConfig {
|
||||||
|
|||||||
@@ -347,8 +347,17 @@ namespace Void::Data::Toml
|
|||||||
};
|
};
|
||||||
|
|
||||||
struct ParseOptions {
|
struct ParseOptions {
|
||||||
|
/// Maximum nesting level reached from the document root. It is
|
||||||
|
/// enforced uniformly for values (arrays, inline tables), dotted key
|
||||||
|
/// paths, table headers and array-of-tables headers.
|
||||||
std::size_t max_depth{64};
|
std::size_t max_depth{64};
|
||||||
std::size_t max_input_bytes{16ULL * 1024ULL * 1024ULL};
|
std::size_t max_input_bytes{16ULL * 1024ULL * 1024ULL};
|
||||||
|
/// Maximum number of document nodes (table entries, array elements
|
||||||
|
/// and array-of-tables entries plus their tables). Zero disables the
|
||||||
|
/// limit, preserving the historical behaviour. `max_input_bytes`
|
||||||
|
/// already bounds node count linearly; this knob bounds the constant
|
||||||
|
/// memory factor for untrusted input.
|
||||||
|
std::size_t max_nodes{0};
|
||||||
};
|
};
|
||||||
|
|
||||||
namespace Detail
|
namespace Detail
|
||||||
@@ -534,7 +543,7 @@ namespace Void::Data::Toml
|
|||||||
parse_table_header(doc);
|
parse_table_header(doc);
|
||||||
} else {
|
} else {
|
||||||
parse_key_value_into(*current_table_, *current_meta_,
|
parse_key_value_into(*current_table_, *current_meta_,
|
||||||
false, 0U);
|
false, table_depth_);
|
||||||
skip_ws();
|
skip_ws();
|
||||||
skip_comment_to_eol();
|
skip_comment_to_eol();
|
||||||
if (pos_ < input_.size() && !consume_newline()) {
|
if (pos_ < input_.size() && !consume_newline()) {
|
||||||
@@ -914,11 +923,19 @@ namespace Void::Data::Toml
|
|||||||
return KeyPart{std::move(bare), start};
|
return KeyPart{std::move(bare), start};
|
||||||
}
|
}
|
||||||
|
|
||||||
[[nodiscard]] std::vector<KeyPart> parse_key_path()
|
/// Parse a dotted key path, rejecting it as soon as it grows past
|
||||||
|
/// `max_segments`. Checking while parsing keeps a pathologically
|
||||||
|
/// long path from being materialised before the depth limit applies.
|
||||||
|
[[nodiscard]] std::vector<KeyPart>
|
||||||
|
parse_key_path(std::size_t max_segments)
|
||||||
{
|
{
|
||||||
std::vector<KeyPart> path;
|
std::vector<KeyPart> path;
|
||||||
path.push_back(parse_simple_key());
|
path.push_back(parse_simple_key());
|
||||||
while (true) {
|
while (true) {
|
||||||
|
if (path.size() > max_segments) {
|
||||||
|
fail("key path exceeds max_depth",
|
||||||
|
path.back().origin);
|
||||||
|
}
|
||||||
skip_ws();
|
skip_ws();
|
||||||
if (pos_ < input_.size() && input_[pos_] == '.') {
|
if (pos_ < input_.size() && input_[pos_] == '.') {
|
||||||
(void)advance_byte();
|
(void)advance_byte();
|
||||||
@@ -931,6 +948,32 @@ namespace Void::Data::Toml
|
|||||||
return path;
|
return path;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A dotted key of N segments nests its value N-1 levels below the
|
||||||
|
/// current base depth, so it may hold one more segment than a table
|
||||||
|
/// header at the same limit.
|
||||||
|
[[nodiscard]] std::size_t
|
||||||
|
key_path_budget(std::size_t depth) const noexcept
|
||||||
|
{
|
||||||
|
if (depth > options_.max_depth) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const std::size_t remaining = options_.max_depth - depth;
|
||||||
|
if (remaining == std::numeric_limits<std::size_t>::max()) {
|
||||||
|
return remaining;
|
||||||
|
}
|
||||||
|
return remaining + 1U;
|
||||||
|
}
|
||||||
|
|
||||||
|
void note_node()
|
||||||
|
{
|
||||||
|
++node_count_;
|
||||||
|
if (options_.max_nodes != 0 &&
|
||||||
|
node_count_ > options_.max_nodes) {
|
||||||
|
fail(std::format("TOML document exceeds max_nodes ({})",
|
||||||
|
options_.max_nodes));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void parse_table_header(Document& doc)
|
void parse_table_header(Document& doc)
|
||||||
{
|
{
|
||||||
const Origin hdr_origin = here();
|
const Origin hdr_origin = here();
|
||||||
@@ -941,7 +984,8 @@ namespace Void::Data::Toml
|
|||||||
(void)advance_byte();
|
(void)advance_byte();
|
||||||
}
|
}
|
||||||
skip_ws();
|
skip_ws();
|
||||||
auto path = parse_key_path();
|
auto path = parse_key_path(options_.max_depth);
|
||||||
|
table_depth_ = path.size();
|
||||||
skip_ws();
|
skip_ws();
|
||||||
if (pos_ >= input_.size() || input_[pos_] != ']') {
|
if (pos_ >= input_.size() || input_[pos_] != ']') {
|
||||||
fail("expected ']' closing table header", hdr_origin);
|
fail("expected ']' closing table header", hdr_origin);
|
||||||
@@ -975,6 +1019,7 @@ namespace Void::Data::Toml
|
|||||||
auto [mit, mok] = cur_meta->children.emplace(
|
auto [mit, mok] = cur_meta->children.emplace(
|
||||||
seg.name, std::move(meta_ptr));
|
seg.name, std::move(meta_ptr));
|
||||||
static_cast<void>(mok);
|
static_cast<void>(mok);
|
||||||
|
note_node();
|
||||||
cur_tbl = it->second.as_table();
|
cur_tbl = it->second.as_table();
|
||||||
cur_meta = mit->second.get();
|
cur_meta = mit->second.get();
|
||||||
} else {
|
} else {
|
||||||
@@ -1014,6 +1059,7 @@ namespace Void::Data::Toml
|
|||||||
auto [mit, mok] = cur_meta->children.emplace(
|
auto [mit, mok] = cur_meta->children.emplace(
|
||||||
leaf.name, std::move(meta_ptr));
|
leaf.name, std::move(meta_ptr));
|
||||||
static_cast<void>(mok);
|
static_cast<void>(mok);
|
||||||
|
note_node();
|
||||||
current_table_ = it->second.as_table();
|
current_table_ = it->second.as_table();
|
||||||
current_meta_ = mit->second.get();
|
current_meta_ = mit->second.get();
|
||||||
return;
|
return;
|
||||||
@@ -1046,6 +1092,8 @@ namespace Void::Data::Toml
|
|||||||
MetaNode* next_meta = meta_ptr->aot_items.back().get();
|
MetaNode* next_meta = meta_ptr->aot_items.back().get();
|
||||||
cur_meta->children.emplace(leaf.name,
|
cur_meta->children.emplace(leaf.name,
|
||||||
std::move(meta_ptr));
|
std::move(meta_ptr));
|
||||||
|
note_node(); // the array-of-tables value
|
||||||
|
note_node(); // its first table
|
||||||
current_table_ =
|
current_table_ =
|
||||||
&it->second.as_array_of_tables()->tables.back();
|
&it->second.as_array_of_tables()->tables.back();
|
||||||
current_meta_ = next_meta;
|
current_meta_ = next_meta;
|
||||||
@@ -1061,6 +1109,7 @@ namespace Void::Data::Toml
|
|||||||
}
|
}
|
||||||
auto* aot = existing->as_array_of_tables();
|
auto* aot = existing->as_array_of_tables();
|
||||||
aot->tables.push_back(Table{});
|
aot->tables.push_back(Table{});
|
||||||
|
note_node();
|
||||||
auto elem_meta = std::make_unique<MetaNode>();
|
auto elem_meta = std::make_unique<MetaNode>();
|
||||||
elem_meta->state = NodeState::ExplicitTable;
|
elem_meta->state = NodeState::ExplicitTable;
|
||||||
leaf_meta->aot_items.push_back(std::move(elem_meta));
|
leaf_meta->aot_items.push_back(std::move(elem_meta));
|
||||||
@@ -1072,14 +1121,15 @@ namespace Void::Data::Toml
|
|||||||
void parse_key_value_into(Table& root_tbl, MetaNode& root_meta,
|
void parse_key_value_into(Table& root_tbl, MetaNode& root_meta,
|
||||||
bool in_inline, std::size_t depth)
|
bool in_inline, std::size_t depth)
|
||||||
{
|
{
|
||||||
auto path = parse_key_path();
|
auto path = parse_key_path(key_path_budget(depth));
|
||||||
|
const std::size_t value_depth = depth + path.size() - 1U;
|
||||||
skip_ws();
|
skip_ws();
|
||||||
if (pos_ >= input_.size() || input_[pos_] != '=') {
|
if (pos_ >= input_.size() || input_[pos_] != '=') {
|
||||||
fail("expected '=' after key");
|
fail("expected '=' after key");
|
||||||
}
|
}
|
||||||
(void)advance_byte();
|
(void)advance_byte();
|
||||||
skip_ws();
|
skip_ws();
|
||||||
Value val = parse_value(depth);
|
Value val = parse_value(value_depth);
|
||||||
|
|
||||||
Table* cur_tbl = &root_tbl;
|
Table* cur_tbl = &root_tbl;
|
||||||
MetaNode* cur_meta = &root_meta;
|
MetaNode* cur_meta = &root_meta;
|
||||||
@@ -1097,6 +1147,7 @@ namespace Void::Data::Toml
|
|||||||
auto [mit, mok] = cur_meta->children.emplace(
|
auto [mit, mok] = cur_meta->children.emplace(
|
||||||
seg.name, std::move(meta_ptr));
|
seg.name, std::move(meta_ptr));
|
||||||
static_cast<void>(mok);
|
static_cast<void>(mok);
|
||||||
|
note_node();
|
||||||
cur_tbl = it->second.as_table();
|
cur_tbl = it->second.as_table();
|
||||||
cur_meta = mit->second.get();
|
cur_meta = mit->second.get();
|
||||||
} else {
|
} else {
|
||||||
@@ -1134,6 +1185,7 @@ namespace Void::Data::Toml
|
|||||||
meta_ptr->state = val_state;
|
meta_ptr->state = val_state;
|
||||||
cur_meta->children.emplace(leaf.name, std::move(meta_ptr));
|
cur_meta->children.emplace(leaf.name, std::move(meta_ptr));
|
||||||
cur_tbl->entries.emplace(leaf.name, std::move(val));
|
cur_tbl->entries.emplace(leaf.name, std::move(val));
|
||||||
|
note_node();
|
||||||
}
|
}
|
||||||
|
|
||||||
[[nodiscard]] Value parse_value(std::size_t depth)
|
[[nodiscard]] Value parse_value(std::size_t depth)
|
||||||
@@ -1173,6 +1225,7 @@ namespace Void::Data::Toml
|
|||||||
return Value{std::move(arr), start};
|
return Value{std::move(arr), start};
|
||||||
}
|
}
|
||||||
arr.elements.push_back(parse_value(depth + 1U));
|
arr.elements.push_back(parse_value(depth + 1U));
|
||||||
|
note_node();
|
||||||
skip_ws_and_comments(true);
|
skip_ws_and_comments(true);
|
||||||
if (pos_ >= input_.size()) {
|
if (pos_ >= input_.size()) {
|
||||||
fail("unterminated array", start);
|
fail("unterminated array", start);
|
||||||
@@ -1681,6 +1734,8 @@ namespace Void::Data::Toml
|
|||||||
MetaNode root_meta_{};
|
MetaNode root_meta_{};
|
||||||
Table* current_table_{nullptr};
|
Table* current_table_{nullptr};
|
||||||
MetaNode* current_meta_{nullptr};
|
MetaNode* current_meta_{nullptr};
|
||||||
|
std::size_t table_depth_{0};
|
||||||
|
std::size_t node_count_{0};
|
||||||
};
|
};
|
||||||
|
|
||||||
inline void append_escaped_basic(std::string& out, std::string_view s)
|
inline void append_escaped_basic(std::string& out, std::string_view s)
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
#include <Void/MCP/Types.hpp>
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
namespace Void::MCP
|
||||||
|
{
|
||||||
|
/// Newline-delimited JSON-RPC framing used by the stdio transport
|
||||||
|
/// (and any custom transport built on a reliable byte stream).
|
||||||
|
///
|
||||||
|
/// A frame is one JSON-RPC message followed by `\n`; embedded newlines
|
||||||
|
/// are not allowed. A trailing `\r` is tolerated before the newline.
|
||||||
|
class LineFramer
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
explicit LineFramer(McpLimits limits = {});
|
||||||
|
|
||||||
|
/// Append bytes from the stream. Fails when the unterminated
|
||||||
|
/// tail exceeds `limits.max_line_bytes`.
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
append(std::string_view bytes);
|
||||||
|
|
||||||
|
/// Pop the next complete line (without the newline). Empty
|
||||||
|
/// lines are skipped. `nullopt` means more bytes are needed.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::optional<std::string>>
|
||||||
|
next();
|
||||||
|
|
||||||
|
[[nodiscard]] std::size_t buffered() const noexcept;
|
||||||
|
void reset() noexcept;
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
McpLimits m_limits;
|
||||||
|
std::string m_buffer;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// One Server-Sent Events event used by Streamable HTTP responses.
|
||||||
|
struct SseEvent {
|
||||||
|
std::string event{};
|
||||||
|
std::string data{};
|
||||||
|
std::string id{};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Serialize one SSE event (`event:`/`id:`/`data:` lines terminated by
|
||||||
|
/// a blank line). Multi-line data is split into multiple `data:` lines.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::string>
|
||||||
|
encode_sse_event(const SseEvent& event, const McpLimits& limits = {});
|
||||||
|
|
||||||
|
/// Bounded incremental SSE parser. Comment lines and unknown fields
|
||||||
|
/// are ignored; `data` lines are joined with `\n`.
|
||||||
|
class SseParser
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
explicit SseParser(McpLimits limits = {});
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
append(std::string_view bytes);
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::optional<SseEvent>>
|
||||||
|
next();
|
||||||
|
|
||||||
|
[[nodiscard]] std::size_t buffered() const noexcept;
|
||||||
|
void reset() noexcept;
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
McpLimits m_limits;
|
||||||
|
std::string m_buffer;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Append the stdio frame terminator and validate the line bound.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::string>
|
||||||
|
frame_line(std::string_view json, const McpLimits& limits = {});
|
||||||
|
|
||||||
|
} // namespace Void::MCP
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Data/StrictJson.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
#include <Void/MCP/Types.hpp>
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <variant>
|
||||||
|
|
||||||
|
namespace Void::MCP
|
||||||
|
{
|
||||||
|
using JsonValue = Void::Json::Strict::Value;
|
||||||
|
|
||||||
|
/// JSON-RPC request id: null, an integer, or a string.
|
||||||
|
struct JsonRpcId {
|
||||||
|
std::variant<std::monostate, std::int64_t, std::string> value{};
|
||||||
|
|
||||||
|
[[nodiscard]] bool is_null() const noexcept
|
||||||
|
{
|
||||||
|
return std::holds_alternative<std::monostate>(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const JsonRpcId&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ErrorObject {
|
||||||
|
std::int32_t code{0};
|
||||||
|
std::string message{};
|
||||||
|
std::optional<JsonValue> data{};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Request {
|
||||||
|
JsonRpcId id{};
|
||||||
|
std::string method{};
|
||||||
|
std::optional<JsonValue> params{};
|
||||||
|
RequestMetadata metadata{};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Notification {
|
||||||
|
std::string method{};
|
||||||
|
std::optional<JsonValue> params{};
|
||||||
|
RequestMetadata metadata{};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Response {
|
||||||
|
JsonRpcId id{};
|
||||||
|
std::optional<JsonValue> result{};
|
||||||
|
std::optional<ErrorObject> error{};
|
||||||
|
};
|
||||||
|
|
||||||
|
using Message = std::variant<Request, Notification, Response>;
|
||||||
|
|
||||||
|
/// Encode one JSON-RPC message. Request/notification metadata is merged
|
||||||
|
/// into `params._meta`; responses carry exactly one of result or error.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::string>
|
||||||
|
encode_message(const Message& message, const McpLimits& limits = {});
|
||||||
|
|
||||||
|
/// Decode exactly one JSON-RPC message, rejecting malformed envelopes,
|
||||||
|
/// duplicate keys, unknown id types, and limit violations.
|
||||||
|
[[nodiscard]] Void::Result::Result<Message>
|
||||||
|
decode_message(std::string_view text, const McpLimits& limits = {});
|
||||||
|
|
||||||
|
/// Parse `_meta` metadata out of a params object (or a `_meta` object).
|
||||||
|
[[nodiscard]] Void::Result::Result<RequestMetadata>
|
||||||
|
parse_metadata(const JsonValue& params, const McpLimits& limits = {});
|
||||||
|
|
||||||
|
/// Build the `_meta` object for a request metadata value.
|
||||||
|
[[nodiscard]] Void::Result::Result<JsonValue>
|
||||||
|
metadata_to_json(const RequestMetadata& metadata,
|
||||||
|
const McpLimits& limits = {});
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::string>
|
||||||
|
encode_json(const JsonValue& value, const McpLimits& limits = {});
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<JsonValue>
|
||||||
|
decode_json(std::string_view text, const McpLimits& limits = {});
|
||||||
|
|
||||||
|
/// Error response helper (null id is used for transport-level failures).
|
||||||
|
[[nodiscard]] Response
|
||||||
|
make_error_response(const JsonRpcId& id, std::int32_t code,
|
||||||
|
std::string message,
|
||||||
|
std::optional<JsonValue> data = {});
|
||||||
|
|
||||||
|
} // namespace Void::MCP
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
#include <Void/MCP/Codec.hpp>
|
||||||
|
#include <Void/MCP/Envelope.hpp>
|
||||||
|
#include <Void/MCP/Types.hpp>
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <functional>
|
||||||
|
#include <map>
|
||||||
|
#include <memory>
|
||||||
|
#include <optional>
|
||||||
|
#include <stop_token>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::MCP
|
||||||
|
{
|
||||||
|
struct HttpHeader {
|
||||||
|
std::string name{};
|
||||||
|
std::string value{};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct HttpRequest {
|
||||||
|
std::string method{};
|
||||||
|
std::string target{};
|
||||||
|
std::vector<HttpHeader> headers{};
|
||||||
|
std::string body{};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct HttpResponse {
|
||||||
|
int status{200};
|
||||||
|
std::vector<HttpHeader> headers{};
|
||||||
|
std::string body{};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Case-insensitive header lookup. Returns the first match.
|
||||||
|
[[nodiscard]] std::optional<std::string_view>
|
||||||
|
header_value(const HttpRequest& request, std::string_view name);
|
||||||
|
|
||||||
|
/// Authorization boundary: validate the bearer token (or any scheme the
|
||||||
|
/// application chooses) and return an authenticated principal. MCP does
|
||||||
|
/// not implement OAuth, consent, or scope mapping itself.
|
||||||
|
using AuthorizationCallback =
|
||||||
|
std::function<Void::Result::Result<AuthContext>(const HttpRequest&)>;
|
||||||
|
|
||||||
|
using RequestHandler =
|
||||||
|
std::function<Void::Result::Result<Message>(const Request&)>;
|
||||||
|
using NotificationHandler =
|
||||||
|
std::function<Void::Result::Result<void>(const Notification&)>;
|
||||||
|
|
||||||
|
struct StreamableHttpOptions {
|
||||||
|
McpLimits limits{};
|
||||||
|
/// Called for every POST before the message is dispatched.
|
||||||
|
AuthorizationCallback authorize{};
|
||||||
|
bool require_authorization{false};
|
||||||
|
/// Respond to requests with `text/event-stream` instead of a
|
||||||
|
/// single `application/json` object.
|
||||||
|
bool prefer_sse{false};
|
||||||
|
/// Protocol revisions accepted in `_meta`/headers.
|
||||||
|
std::vector<std::string> supported_versions{
|
||||||
|
std::string{kProtocolVersion}};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Streamable HTTP binding for the 2026-07-28 revision: one MCP endpoint
|
||||||
|
/// accepting POST only (GET/DELETE answer 405), protocol/method/name
|
||||||
|
/// header validation, JSON or request-scoped SSE responses, and no
|
||||||
|
/// session ids or resumability.
|
||||||
|
class StreamableHttpEndpoint
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
StreamableHttpEndpoint(RequestHandler requests,
|
||||||
|
NotificationHandler notifications,
|
||||||
|
StreamableHttpOptions options = {});
|
||||||
|
~StreamableHttpEndpoint();
|
||||||
|
StreamableHttpEndpoint(const StreamableHttpEndpoint&) = delete;
|
||||||
|
StreamableHttpEndpoint&
|
||||||
|
operator=(const StreamableHttpEndpoint&) = delete;
|
||||||
|
|
||||||
|
[[nodiscard]] HttpResponse
|
||||||
|
handle(const HttpRequest& request) const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct Impl;
|
||||||
|
std::unique_ptr<Impl> m_impl;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Newline-delimited stdio (or any reliable bidirectional byte stream)
|
||||||
|
/// transport. Reads are bounded by `McpLimits::max_line_bytes`; writes
|
||||||
|
/// honour cancellation and a bounded timeout on non-blocking fds.
|
||||||
|
class StdioTransport
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
StdioTransport(int read_fd, int write_fd,
|
||||||
|
RequestHandler requests,
|
||||||
|
NotificationHandler notifications,
|
||||||
|
McpLimits limits = {},
|
||||||
|
std::chrono::milliseconds io_timeout =
|
||||||
|
std::chrono::seconds{30});
|
||||||
|
~StdioTransport();
|
||||||
|
StdioTransport(const StdioTransport&) = delete;
|
||||||
|
StdioTransport& operator=(const StdioTransport&) = delete;
|
||||||
|
|
||||||
|
/// Read one message. `nullopt` means clean end of stream.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::optional<Message>>
|
||||||
|
read_message(std::stop_token stop = {});
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
write_message(const Message& message,
|
||||||
|
std::stop_token stop = {});
|
||||||
|
|
||||||
|
/// Read-dispatch-write until EOF, cancellation, or an I/O error.
|
||||||
|
/// Malformed JSON frames are answered with a parse-error
|
||||||
|
/// response and do not terminate the loop.
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
run(std::stop_token stop = {});
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct Impl;
|
||||||
|
std::unique_ptr<Impl> m_impl;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct LegacySession {
|
||||||
|
std::string id{};
|
||||||
|
std::string protocol_version{};
|
||||||
|
bool initialized{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct LegacySessionOptions {
|
||||||
|
/// Revisions of the initialize/session era this adapter accepts,
|
||||||
|
/// newest first.
|
||||||
|
std::vector<std::string> supported_versions{
|
||||||
|
"2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"};
|
||||||
|
std::string server_name{"Void MCP"};
|
||||||
|
std::string server_version{"1.0"};
|
||||||
|
std::function<std::string()> session_id_factory{};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Explicit compatibility adapter for the pre-2026-07-28
|
||||||
|
/// initialization/session semantics: `initialize` negotiation,
|
||||||
|
/// `initialized` notification, and session ids. Kept separate from the
|
||||||
|
/// modern transport so the two behaviors cannot bleed into each other.
|
||||||
|
class LegacySessionAdapter
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
explicit LegacySessionAdapter(LegacySessionOptions options = {});
|
||||||
|
~LegacySessionAdapter();
|
||||||
|
LegacySessionAdapter(const LegacySessionAdapter&) = delete;
|
||||||
|
LegacySessionAdapter&
|
||||||
|
operator=(const LegacySessionAdapter&) = delete;
|
||||||
|
|
||||||
|
/// Handle one inbound message. `initialize` creates a session and
|
||||||
|
/// returns the negotiated response; `initialized` marks it ready and
|
||||||
|
/// returns no reply; everything else is rejected until a session is
|
||||||
|
/// initialized.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::optional<Message>>
|
||||||
|
handle(const Message& inbound,
|
||||||
|
std::string_view session_id = {});
|
||||||
|
|
||||||
|
[[nodiscard]] const LegacySession*
|
||||||
|
find(std::string_view session_id) const;
|
||||||
|
|
||||||
|
bool terminate(std::string_view session_id);
|
||||||
|
|
||||||
|
[[nodiscard]] std::size_t session_count() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct Impl;
|
||||||
|
std::unique_ptr<Impl> m_impl;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::MCP
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::MCP
|
||||||
|
{
|
||||||
|
/// Protocol revision this module pins its modern behavior to.
|
||||||
|
inline constexpr std::string_view kProtocolVersion{"2026-07-28"};
|
||||||
|
inline constexpr std::string_view kJsonRpcVersion{"2.0"};
|
||||||
|
|
||||||
|
/// `_meta` keys defined by the MCP 2026-07-28 revision.
|
||||||
|
inline constexpr std::string_view kMetaProtocolVersion{
|
||||||
|
"io.modelcontextprotocol/protocolVersion"};
|
||||||
|
inline constexpr std::string_view kMetaClientInfo{
|
||||||
|
"io.modelcontextprotocol/clientInfo"};
|
||||||
|
inline constexpr std::string_view kMetaClientCapabilities{
|
||||||
|
"io.modelcontextprotocol/clientCapabilities"};
|
||||||
|
inline constexpr std::string_view kMetaServerInfo{
|
||||||
|
"io.modelcontextprotocol/serverInfo"};
|
||||||
|
inline constexpr std::string_view kMetaSubscriptionId{
|
||||||
|
"io.modelcontextprotocol/subscriptionId"};
|
||||||
|
inline constexpr std::string_view kMetaProgressToken{"progressToken"};
|
||||||
|
|
||||||
|
/// Streamable HTTP request metadata headers (2026-07-28).
|
||||||
|
inline constexpr std::string_view kProtocolHeader{"MCP-Protocol-Version"};
|
||||||
|
inline constexpr std::string_view kMethodHeader{"Mcp-Method"};
|
||||||
|
inline constexpr std::string_view kNameHeader{"Mcp-Name"};
|
||||||
|
/// Legacy session/resumption headers; ignored by the modern transport.
|
||||||
|
inline constexpr std::string_view kSessionHeader{"Mcp-Session-Id"};
|
||||||
|
inline constexpr std::string_view kLastEventIdHeader{"Last-Event-ID"};
|
||||||
|
|
||||||
|
inline constexpr std::string_view kJsonContentType{"application/json"};
|
||||||
|
inline constexpr std::string_view kSseContentType{"text/event-stream"};
|
||||||
|
|
||||||
|
/// Error domain owned by the MCP module.
|
||||||
|
inline constexpr std::int32_t kMcpErrorDomain{33};
|
||||||
|
|
||||||
|
enum class McpErrorCode : std::int32_t {
|
||||||
|
none = 0,
|
||||||
|
parse_error = 1,
|
||||||
|
invalid_request = 2,
|
||||||
|
method_not_found = 3,
|
||||||
|
invalid_params = 4,
|
||||||
|
internal_error = 5,
|
||||||
|
header_mismatch = 6,
|
||||||
|
unsupported_protocol_version = 7,
|
||||||
|
unauthorized = 8,
|
||||||
|
forbidden = 9,
|
||||||
|
not_acceptable = 10,
|
||||||
|
unsupported_media_type = 11,
|
||||||
|
method_not_allowed = 12,
|
||||||
|
payload_too_large = 13,
|
||||||
|
cancelled = 14,
|
||||||
|
timeout = 15,
|
||||||
|
transport_closed = 16,
|
||||||
|
protocol_error = 17,
|
||||||
|
session_not_found = 18,
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] inline Void::Result::Error
|
||||||
|
make_mcp_error(McpErrorCode code, std::string message)
|
||||||
|
{
|
||||||
|
using Void::Result::Error;
|
||||||
|
using Void::Result::ErrorCode;
|
||||||
|
using Void::Result::ErrorKind;
|
||||||
|
|
||||||
|
ErrorKind kind = ErrorKind::internal;
|
||||||
|
switch (code) {
|
||||||
|
case McpErrorCode::none:
|
||||||
|
case McpErrorCode::internal_error:
|
||||||
|
kind = ErrorKind::internal;
|
||||||
|
break;
|
||||||
|
case McpErrorCode::parse_error:
|
||||||
|
case McpErrorCode::invalid_request:
|
||||||
|
case McpErrorCode::invalid_params:
|
||||||
|
case McpErrorCode::header_mismatch:
|
||||||
|
case McpErrorCode::protocol_error:
|
||||||
|
kind = ErrorKind::corrupt;
|
||||||
|
break;
|
||||||
|
case McpErrorCode::method_not_found:
|
||||||
|
kind = ErrorKind::not_found;
|
||||||
|
break;
|
||||||
|
case McpErrorCode::unsupported_protocol_version:
|
||||||
|
case McpErrorCode::not_acceptable:
|
||||||
|
case McpErrorCode::unsupported_media_type:
|
||||||
|
case McpErrorCode::method_not_allowed:
|
||||||
|
kind = ErrorKind::unsupported;
|
||||||
|
break;
|
||||||
|
case McpErrorCode::unauthorized:
|
||||||
|
case McpErrorCode::forbidden:
|
||||||
|
kind = ErrorKind::invalid_argument;
|
||||||
|
break;
|
||||||
|
case McpErrorCode::payload_too_large:
|
||||||
|
kind = ErrorKind::exhausted;
|
||||||
|
break;
|
||||||
|
case McpErrorCode::cancelled:
|
||||||
|
kind = ErrorKind::cancelled;
|
||||||
|
break;
|
||||||
|
case McpErrorCode::timeout:
|
||||||
|
kind = ErrorKind::timeout;
|
||||||
|
break;
|
||||||
|
case McpErrorCode::transport_closed:
|
||||||
|
case McpErrorCode::session_not_found:
|
||||||
|
kind = ErrorKind::conflict;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return Error{kind, std::move(message),
|
||||||
|
ErrorCode{kMcpErrorDomain,
|
||||||
|
static_cast<std::int32_t>(code)}};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// JSON-RPC 2.0 error code emitted for an MCP error.
|
||||||
|
[[nodiscard]] inline std::int32_t
|
||||||
|
json_rpc_error_code(McpErrorCode code) noexcept
|
||||||
|
{
|
||||||
|
switch (code) {
|
||||||
|
case McpErrorCode::parse_error:
|
||||||
|
return -32700;
|
||||||
|
case McpErrorCode::invalid_request:
|
||||||
|
return -32600;
|
||||||
|
case McpErrorCode::method_not_found:
|
||||||
|
return -32601;
|
||||||
|
case McpErrorCode::invalid_params:
|
||||||
|
return -32602;
|
||||||
|
case McpErrorCode::header_mismatch:
|
||||||
|
return -32020;
|
||||||
|
case McpErrorCode::unsupported_protocol_version:
|
||||||
|
return -32022;
|
||||||
|
case McpErrorCode::unauthorized:
|
||||||
|
return -32001;
|
||||||
|
default:
|
||||||
|
return -32603;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct MetadataEntry {
|
||||||
|
std::string key{};
|
||||||
|
std::string value{};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(
|
||||||
|
const MetadataEntry&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ClientInfo {
|
||||||
|
std::string name{};
|
||||||
|
std::string version{};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(
|
||||||
|
const ClientInfo&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Per-request metadata carried inline in `_meta` (stdio) or mirrored in
|
||||||
|
/// HTTP headers (Streamable HTTP). Unknown entries are preserved as
|
||||||
|
/// bounded key/value strings.
|
||||||
|
struct RequestMetadata {
|
||||||
|
std::string protocol_version{std::string{kProtocolVersion}};
|
||||||
|
ClientInfo client_info{};
|
||||||
|
std::optional<std::string> progress_token{};
|
||||||
|
std::optional<std::string> subscription_id{};
|
||||||
|
/// Compact JSON object for `clientCapabilities` (empty when
|
||||||
|
/// absent). Kept as text so Types.hpp stays independent of Data.
|
||||||
|
std::string client_capabilities_json{};
|
||||||
|
std::vector<MetadataEntry> extra{};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(
|
||||||
|
const RequestMetadata&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ServerInfo {
|
||||||
|
std::string name{};
|
||||||
|
std::string version{};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(
|
||||||
|
const ServerInfo&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Authenticated principal produced by the authorization callback. The
|
||||||
|
/// MCP module only defines the boundary; token validation, scopes, and
|
||||||
|
/// consent remain application concerns.
|
||||||
|
struct AuthContext {
|
||||||
|
std::string subject{};
|
||||||
|
std::vector<std::string> scopes{};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(
|
||||||
|
const AuthContext&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct McpLimits {
|
||||||
|
/// Maximum bytes in one encoded JSON-RPC message.
|
||||||
|
std::size_t max_message_bytes{4ULL * 1024 * 1024};
|
||||||
|
/// Maximum bytes in one newline-delimited stdio frame.
|
||||||
|
std::size_t max_line_bytes{1ULL * 1024 * 1024};
|
||||||
|
/// Maximum metadata entries accepted from `_meta`.
|
||||||
|
std::size_t max_metadata_entries{16};
|
||||||
|
/// Maximum bytes in one metadata key or value.
|
||||||
|
std::size_t max_metadata_value_bytes{4096};
|
||||||
|
/// Maximum bytes in one SSE event.
|
||||||
|
std::size_t max_sse_event_bytes{1ULL * 1024 * 1024};
|
||||||
|
/// Maximum compiled SSE events buffered by the parser.
|
||||||
|
std::size_t max_sse_events{1024};
|
||||||
|
/// Maximum JSON nesting depth accepted by the codec.
|
||||||
|
std::size_t max_json_depth{64};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::MCP
|
||||||
@@ -298,6 +298,47 @@ template <std::integral T>
|
|||||||
return a / b;
|
return a / b;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Euclidean quotient and remainder for a strictly positive divisor:
|
||||||
|
/// `a == quotient * divisor + remainder` and `0 <= remainder < divisor`.
|
||||||
|
template <std::integral T> struct EuclideanDivision {
|
||||||
|
T quotient{};
|
||||||
|
T remainder{};
|
||||||
|
|
||||||
|
[[nodiscard]] constexpr bool
|
||||||
|
operator==(const EuclideanDivision&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Checked Euclidean division. Unlike C++ integer division (which truncates
|
||||||
|
/// toward zero), this floors toward negative infinity so the remainder is
|
||||||
|
/// always nonnegative, e.g. (-1, 32) -> (-1, 31).
|
||||||
|
///
|
||||||
|
/// `divisor == 0` reports `DivisionByZero`; a negative divisor reports
|
||||||
|
/// `InvalidInput`. The signed minimum is handled without negating it, so no
|
||||||
|
/// intermediate overflows.
|
||||||
|
template <std::integral T>
|
||||||
|
[[nodiscard]] constexpr std::expected<EuclideanDivision<T>, Error>
|
||||||
|
checked_euclidean_div(T a, T divisor) noexcept
|
||||||
|
{
|
||||||
|
if (divisor == T{0}) {
|
||||||
|
return std::unexpected{Error::DivisionByZero};
|
||||||
|
}
|
||||||
|
if constexpr (std::is_signed_v<T>) {
|
||||||
|
if (divisor < T{0}) {
|
||||||
|
return std::unexpected{Error::InvalidInput};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
T quotient = static_cast<T>(a / divisor);
|
||||||
|
T remainder = static_cast<T>(a % divisor);
|
||||||
|
if constexpr (std::is_signed_v<T>) {
|
||||||
|
if (remainder < T{0}) {
|
||||||
|
// Truncated division rounded toward zero: step one page down.
|
||||||
|
quotient = static_cast<T>(quotient - T{1});
|
||||||
|
remainder = static_cast<T>(remainder + divisor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return EuclideanDivision<T>{.quotient = quotient, .remainder = remainder};
|
||||||
|
}
|
||||||
|
|
||||||
template <std::integral T>
|
template <std::integral T>
|
||||||
[[nodiscard]] constexpr std::expected<T, Error>
|
[[nodiscard]] constexpr std::expected<T, Error>
|
||||||
checked_neg(T a) noexcept
|
checked_neg(T a) noexcept
|
||||||
|
|||||||
@@ -1,10 +1,15 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
|
#include <compare>
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
|
#include <expected>
|
||||||
|
#include <limits>
|
||||||
#include <random>
|
#include <random>
|
||||||
#include <span>
|
#include <span>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace Void::Random
|
namespace Void::Random
|
||||||
@@ -57,6 +62,91 @@ public:
|
|||||||
while (n--) operator()();
|
while (n--) operator()();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Versioned deterministic state ────────────────────────────────────────
|
||||||
|
|
||||||
|
/// Algorithm identity for saved-stream metadata. The state schema is
|
||||||
|
/// versioned separately so a future algorithm change cannot silently
|
||||||
|
/// reinterpret old saves.
|
||||||
|
static constexpr std::string_view algorithm = "xoshiro256**";
|
||||||
|
static constexpr std::uint32_t state_version = 1;
|
||||||
|
|
||||||
|
/// Portable state: version plus the four words in xoshiro order s0..s3.
|
||||||
|
/// Consumers choose their own wire format (endianness, framing); this
|
||||||
|
/// struct defines only the identity and word order.
|
||||||
|
struct State {
|
||||||
|
std::uint32_t version{state_version};
|
||||||
|
std::array<std::uint64_t, 4> words{};
|
||||||
|
|
||||||
|
[[nodiscard]] auto operator<=>(const State&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool operator==(const State&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class StateErrorKind : std::uint8_t {
|
||||||
|
unknown_version = 0,
|
||||||
|
/// Xoshiro's all-zero state is absorbing and therefore invalid.
|
||||||
|
invalid_state,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct StateError {
|
||||||
|
StateErrorKind kind{StateErrorKind::invalid_state};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const StateError&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] State state() const noexcept
|
||||||
|
{
|
||||||
|
return State{.version = state_version,
|
||||||
|
.words = {s_[0], s_[1], s_[2], s_[3]}};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replace the stream with `state` only if it is valid. On failure the
|
||||||
|
/// current stream is unchanged (the caller can keep drawing).
|
||||||
|
[[nodiscard]] std::expected<void, StateError> restore(State state) noexcept
|
||||||
|
{
|
||||||
|
if (state.version != state_version) {
|
||||||
|
return std::unexpected{StateError{StateErrorKind::unknown_version}};
|
||||||
|
}
|
||||||
|
if (state.words[0] == 0 && state.words[1] == 0 &&
|
||||||
|
state.words[2] == 0 && state.words[3] == 0) {
|
||||||
|
return std::unexpected{StateError{StateErrorKind::invalid_state}};
|
||||||
|
}
|
||||||
|
s_[0] = state.words[0];
|
||||||
|
s_[1] = state.words[1];
|
||||||
|
s_[2] = state.words[2];
|
||||||
|
s_[3] = state.words[3];
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] static std::expected<Xoshiro256, StateError>
|
||||||
|
from_state(State state) noexcept
|
||||||
|
{
|
||||||
|
Xoshiro256 rng;
|
||||||
|
if (auto restored = rng.restore(state); !restored.has_value()) {
|
||||||
|
return std::unexpected{restored.error()};
|
||||||
|
}
|
||||||
|
return rng;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Uniform integer in [0, bound) by rejection sampling (unbiased).
|
||||||
|
///
|
||||||
|
/// Zero-bound policy: `bound == 0` and `bound == 1` return 0 without
|
||||||
|
/// consuming any randomness, so callers need not special-case them and a
|
||||||
|
/// saved stream stays aligned.
|
||||||
|
[[nodiscard]] std::uint64_t bounded(std::uint64_t bound) noexcept
|
||||||
|
{
|
||||||
|
if (bound <= 1) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
// 2^64 mod bound: values below it are rejected to remove modulo bias.
|
||||||
|
const std::uint64_t threshold = (0ULL - bound) % bound;
|
||||||
|
for (;;) {
|
||||||
|
const std::uint64_t value = operator()();
|
||||||
|
if (value >= threshold) {
|
||||||
|
return value % bound;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
static constexpr std::uint64_t rotl(std::uint64_t x, int k) noexcept
|
static constexpr std::uint64_t rotl(std::uint64_t x, int k) noexcept
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,183 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <compare>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <functional>
|
||||||
|
#include <map>
|
||||||
|
#include <mutex>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::Messaging
|
||||||
|
{
|
||||||
|
|
||||||
|
/// Epoch-scoped idempotency ledger for host request dispatch.
|
||||||
|
///
|
||||||
|
/// A key is `(epoch, trusted client, request id)`. The ledger records the
|
||||||
|
/// caller-defined payload of the first admission and, once the operation
|
||||||
|
/// finishes, its caller-defined result (including a rejected outcome). An exact
|
||||||
|
/// repeat returns the recorded result instead of executing again; reusing the
|
||||||
|
/// key with a different payload, or after its epoch became obsolete, fails
|
||||||
|
/// before any side effect.
|
||||||
|
///
|
||||||
|
/// Capacity, admission and archival:
|
||||||
|
/// - Entries are never evicted within an epoch. When `capacity` is reached new
|
||||||
|
/// keys are rejected with `capacity_exceeded`; the caller can retry later or
|
||||||
|
/// raise the capacity. Completed entries keep occupying a slot so a delayed
|
||||||
|
/// retry can still be answered.
|
||||||
|
/// - Advancing the epoch clears every entry. Requests from an older (or
|
||||||
|
/// future) epoch are then rejected as `stale_epoch`, so an old request number
|
||||||
|
/// can never execute a second time after memory cleanup.
|
||||||
|
template <typename Payload,
|
||||||
|
typename Result,
|
||||||
|
typename PayloadEqual = std::equal_to<Payload>>
|
||||||
|
class RequestLedger
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
struct Key {
|
||||||
|
std::uint64_t epoch{0};
|
||||||
|
std::string client;
|
||||||
|
std::uint64_t request_id{0};
|
||||||
|
|
||||||
|
[[nodiscard]] auto
|
||||||
|
operator<=>(const Key&) const noexcept = default;
|
||||||
|
[[nodiscard]] bool
|
||||||
|
operator==(const Key&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class Status : std::uint8_t {
|
||||||
|
/// First admission: the caller may execute and must record a result.
|
||||||
|
admitted = 0,
|
||||||
|
/// Exact repeat of a completed request; `result` is the recorded one.
|
||||||
|
replay,
|
||||||
|
/// Exact repeat while the operation is still in flight.
|
||||||
|
in_progress,
|
||||||
|
/// Same key, different payload: reject before side effects.
|
||||||
|
payload_conflict,
|
||||||
|
/// The key's epoch is not the current epoch.
|
||||||
|
stale_epoch,
|
||||||
|
/// The ledger is full; nothing was admitted.
|
||||||
|
capacity_exceeded,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Decision {
|
||||||
|
Status status{Status::capacity_exceeded};
|
||||||
|
std::optional<Result> result{};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Snapshot {
|
||||||
|
std::size_t size{0};
|
||||||
|
std::size_t capacity{0};
|
||||||
|
std::size_t in_flight{0};
|
||||||
|
std::size_t completed{0};
|
||||||
|
std::uint64_t epoch{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
explicit RequestLedger(std::size_t capacity = 1024,
|
||||||
|
std::uint64_t epoch = 0,
|
||||||
|
PayloadEqual equal = {})
|
||||||
|
: capacity_(capacity)
|
||||||
|
, epoch_(epoch)
|
||||||
|
, equal_(std::move(equal))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
RequestLedger(const RequestLedger&) = delete;
|
||||||
|
RequestLedger& operator=(const RequestLedger&) = delete;
|
||||||
|
|
||||||
|
/// Admit or classify `key` with `payload`.
|
||||||
|
[[nodiscard]] Decision check(const Key& key, const Payload& payload)
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
if (key.epoch != epoch_) {
|
||||||
|
return Decision{.status = Status::stale_epoch};
|
||||||
|
}
|
||||||
|
const auto found = entries_.find(key);
|
||||||
|
if (found != entries_.end()) {
|
||||||
|
if (!equal_(found->second.payload, payload)) {
|
||||||
|
return Decision{.status = Status::payload_conflict};
|
||||||
|
}
|
||||||
|
if (found->second.result.has_value()) {
|
||||||
|
return Decision{.status = Status::replay,
|
||||||
|
.result = found->second.result};
|
||||||
|
}
|
||||||
|
return Decision{.status = Status::in_progress};
|
||||||
|
}
|
||||||
|
if (entries_.size() >= capacity_) {
|
||||||
|
return Decision{.status = Status::capacity_exceeded};
|
||||||
|
}
|
||||||
|
entries_.emplace(key, Entry{.payload = payload, .result = {}});
|
||||||
|
return Decision{.status = Status::admitted};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Record the outcome for an admitted key. Returns false when the key is
|
||||||
|
/// unknown, belongs to another epoch or already has a result (results
|
||||||
|
/// are never overwritten).
|
||||||
|
[[nodiscard]] bool record(const Key& key, Result result)
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
if (key.epoch != epoch_) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const auto found = entries_.find(key);
|
||||||
|
if (found == entries_.end() || found->second.result.has_value()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
found->second.result = std::move(result);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Advance to `next` and clear all entries. Only a strictly newer epoch
|
||||||
|
/// is accepted; returns false otherwise.
|
||||||
|
[[nodiscard]] bool advance_epoch(std::uint64_t next)
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
if (next <= epoch_) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
epoch_ = next;
|
||||||
|
entries_.clear();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::uint64_t epoch() const
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
return epoch_;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Snapshot snapshot() const
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
Snapshot out{.size = entries_.size(),
|
||||||
|
.capacity = capacity_,
|
||||||
|
.epoch = epoch_};
|
||||||
|
for (const auto& [key, entry] : entries_) {
|
||||||
|
(void)key;
|
||||||
|
if (entry.result.has_value()) {
|
||||||
|
++out.completed;
|
||||||
|
} else {
|
||||||
|
++out.in_flight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct Entry {
|
||||||
|
Payload payload;
|
||||||
|
std::optional<Result> result;
|
||||||
|
};
|
||||||
|
|
||||||
|
mutable std::mutex mutex_;
|
||||||
|
std::map<Key, Entry> entries_;
|
||||||
|
std::size_t capacity_{1024};
|
||||||
|
std::uint64_t epoch_{0};
|
||||||
|
PayloadEqual equal_{};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Messaging
|
||||||
@@ -31,7 +31,10 @@ namespace Void::Net
|
|||||||
io_error = 9,
|
io_error = 9,
|
||||||
redirect_blocked = 10,
|
redirect_blocked = 10,
|
||||||
payload_too_large = 11,
|
payload_too_large = 11,
|
||||||
headers_too_large = 12
|
headers_too_large = 12,
|
||||||
|
smtp_rejected = 13,
|
||||||
|
auth_failed = 14,
|
||||||
|
tls_required = 15
|
||||||
};
|
};
|
||||||
|
|
||||||
[[nodiscard]] inline Void::Result::Error
|
[[nodiscard]] inline Void::Result::Error
|
||||||
@@ -71,6 +74,13 @@ namespace Void::Net
|
|||||||
case NetErrorCode::headers_too_large:
|
case NetErrorCode::headers_too_large:
|
||||||
kind = ErrorKind::exhausted;
|
kind = ErrorKind::exhausted;
|
||||||
break;
|
break;
|
||||||
|
case NetErrorCode::smtp_rejected:
|
||||||
|
case NetErrorCode::auth_failed:
|
||||||
|
kind = ErrorKind::conflict;
|
||||||
|
break;
|
||||||
|
case NetErrorCode::tls_required:
|
||||||
|
kind = ErrorKind::invalid_argument;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
return Error{kind, std::move(message),
|
return Error{kind, std::move(message),
|
||||||
ErrorCode{Void::Result::kNetErrorDomain,
|
ErrorCode{Void::Result::kNetErrorDomain,
|
||||||
|
|||||||
@@ -13,7 +13,9 @@
|
|||||||
#include <memory>
|
#include <memory>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
#include <span>
|
#include <span>
|
||||||
|
#include <stop_token>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
namespace Void::Net
|
namespace Void::Net
|
||||||
{
|
{
|
||||||
@@ -27,6 +29,10 @@ namespace Void::Net
|
|||||||
std::size_t max_concurrent_connections{64};
|
std::size_t max_concurrent_connections{64};
|
||||||
std::chrono::milliseconds read_timeout{std::chrono::seconds{30}};
|
std::chrono::milliseconds read_timeout{std::chrono::seconds{30}};
|
||||||
std::chrono::milliseconds write_timeout{std::chrono::seconds{30}};
|
std::chrono::milliseconds write_timeout{std::chrono::seconds{30}};
|
||||||
|
/// Bounded per-exchange output buffer used by duplex response
|
||||||
|
/// writers. Producers block (or observe a short accepted count)
|
||||||
|
/// once this much framed data is pending.
|
||||||
|
std::size_t duplex_write_buffer_bytes{64ULL * 1024};
|
||||||
int listen_backlog{128};
|
int listen_backlog{128};
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -64,6 +70,83 @@ namespace Void::Net
|
|||||||
using StreamingRouteHandler =
|
using StreamingRouteHandler =
|
||||||
std::function<RouteResult(const ServerRequest&, BodyReader&)>;
|
std::function<RouteResult(const ServerRequest&, BodyReader&)>;
|
||||||
|
|
||||||
|
/// Scoped, move-only writer for a live duplex HTTP exchange.
|
||||||
|
///
|
||||||
|
/// Exactly one writer may be active at a time (`begin`, `write_some` and
|
||||||
|
/// `finish` fail with `overloaded` if another thread is inside the
|
||||||
|
/// writer). `write_some` returns how many payload bytes it accepted; the
|
||||||
|
/// writer applies bounded buffering and downstream backpressure. Fixed
|
||||||
|
/// length, chunked and bodyless responses are selected by `begin`.
|
||||||
|
///
|
||||||
|
/// After the exchange returns the writer is invalidated. A moved-from or
|
||||||
|
/// retained writer observes `valid() == false` and every operation fails
|
||||||
|
/// with `invalid_argument` instead of touching the connection.
|
||||||
|
class ResponseWriter
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
struct State;
|
||||||
|
|
||||||
|
ResponseWriter() noexcept = default;
|
||||||
|
~ResponseWriter() = default;
|
||||||
|
ResponseWriter(const ResponseWriter&) = delete;
|
||||||
|
ResponseWriter& operator=(const ResponseWriter&) = delete;
|
||||||
|
ResponseWriter(ResponseWriter&&) noexcept = default;
|
||||||
|
ResponseWriter& operator=(ResponseWriter&&) noexcept = default;
|
||||||
|
|
||||||
|
[[nodiscard]] bool valid() const noexcept;
|
||||||
|
[[nodiscard]] bool begun() const noexcept;
|
||||||
|
[[nodiscard]] bool finished() const noexcept;
|
||||||
|
[[nodiscard]] bool cancelled() const noexcept;
|
||||||
|
[[nodiscard]] bool chunked() const noexcept;
|
||||||
|
[[nodiscard]] std::optional<std::uint64_t>
|
||||||
|
content_length() const noexcept;
|
||||||
|
[[nodiscard]] std::uint64_t bytes_accepted() const noexcept;
|
||||||
|
[[nodiscard]] std::uint64_t bytes_sent() const noexcept;
|
||||||
|
[[nodiscard]] std::size_t buffered_bytes() const noexcept;
|
||||||
|
|
||||||
|
/// Token cancelled by `cancel()`, peer disconnect, server shutdown
|
||||||
|
/// or the end of the exchange.
|
||||||
|
[[nodiscard]] std::stop_token stop_token() const noexcept;
|
||||||
|
void cancel() noexcept;
|
||||||
|
void set_write_timeout(std::chrono::milliseconds timeout) noexcept;
|
||||||
|
[[nodiscard]] std::chrono::milliseconds
|
||||||
|
write_timeout() const noexcept;
|
||||||
|
|
||||||
|
/// Send the response head. Chooses fixed length when a
|
||||||
|
/// `Content-Length` header is supplied, chunked otherwise (HTTP/1.1),
|
||||||
|
/// and a bodyless frame for HEAD, 1xx, 204 and 304 responses.
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
begin(std::uint16_t status, std::vector<Header> headers = {});
|
||||||
|
|
||||||
|
/// Accept up to `bytes.size()` payload bytes, bounded by the
|
||||||
|
/// configured write buffer. Returns the accepted count.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||||
|
write_some(std::span<const std::byte> bytes);
|
||||||
|
|
||||||
|
/// Terminate the framed response. Fails if a fixed-length body was
|
||||||
|
/// not fully written.
|
||||||
|
[[nodiscard]] Void::Result::Result<void> finish();
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
friend struct ResponseWriterAccess;
|
||||||
|
|
||||||
|
explicit ResponseWriter(std::shared_ptr<State> state) noexcept
|
||||||
|
: m_state{std::move(state)}
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
std::shared_ptr<State> m_state;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Handler for a duplex route: the request body can be read while the
|
||||||
|
/// response is produced. Returning an error before `begin` lets the server
|
||||||
|
/// emit an error response; after `begin` the stream is terminated without
|
||||||
|
/// reporting success.
|
||||||
|
using DuplexRouteHandler = std::function<Void::Result::Result<void>(
|
||||||
|
const ServerRequest&, BodyReader&, ResponseWriter&)>;
|
||||||
|
|
||||||
/// Concrete POSIX TCP HTTP/1.1 listener dispatching buffered routes through
|
/// Concrete POSIX TCP HTTP/1.1 listener dispatching buffered routes through
|
||||||
/// `Void::Net::Router` and streaming routes via `BodyReader`.
|
/// `Void::Net::Router` and streaming routes via `BodyReader`.
|
||||||
class HttpServer
|
class HttpServer
|
||||||
@@ -90,6 +173,10 @@ namespace Void::Net
|
|||||||
add_streaming_route(Method method, std::string pattern,
|
add_streaming_route(Method method, std::string pattern,
|
||||||
StreamingRouteHandler handler);
|
StreamingRouteHandler handler);
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
add_duplex_route(Method method, std::string pattern,
|
||||||
|
DuplexRouteHandler handler);
|
||||||
|
|
||||||
/// Register a RFC 6455 WebSocket upgrade endpoint backed by
|
/// Register a RFC 6455 WebSocket upgrade endpoint backed by
|
||||||
/// `sessions` (caller must keep `sessions` alive until after
|
/// `sessions` (caller must keep `sessions` alive until after
|
||||||
/// `shutdown()`).
|
/// `shutdown()`).
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <memory>
|
||||||
|
#include <optional>
|
||||||
|
#include <stop_token>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Net
|
||||||
|
{
|
||||||
|
enum class SmtpSecurity {
|
||||||
|
/// TLS from the first byte (typically port 465).
|
||||||
|
implicit_tls,
|
||||||
|
/// Plaintext greeting/EHLO, then a required STARTTLS upgrade
|
||||||
|
/// (typically port 587 or 25).
|
||||||
|
starttls_required,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SmtpCredentials {
|
||||||
|
std::string username{};
|
||||||
|
std::string password{};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SmtpLimits {
|
||||||
|
/// Maximum raw message body accepted by `send()`.
|
||||||
|
std::uint64_t max_message_bytes{10ULL * 1024ULL * 1024ULL};
|
||||||
|
/// Maximum bytes in one complete (possibly multi-line) reply.
|
||||||
|
std::uint64_t max_response_bytes{64ULL * 1024ULL};
|
||||||
|
/// Maximum bytes in one reply line.
|
||||||
|
std::size_t max_line_bytes{4096};
|
||||||
|
/// Maximum recipients accepted by `send()`.
|
||||||
|
std::size_t max_recipients{100};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SmtpOptions {
|
||||||
|
std::string host{};
|
||||||
|
std::uint16_t port{587};
|
||||||
|
SmtpSecurity security{SmtpSecurity::starttls_required};
|
||||||
|
/// Identity verified against the server certificate; defaults
|
||||||
|
/// to `host`. Peer and hostname verification are always on.
|
||||||
|
std::string server_name{};
|
||||||
|
/// PEM trust store; empty uses the system default store.
|
||||||
|
std::string ca_file{};
|
||||||
|
/// Credentials are sent with AUTH PLAIN and only over TLS.
|
||||||
|
std::optional<SmtpCredentials> credentials{};
|
||||||
|
/// Name announced in EHLO.
|
||||||
|
std::string client_domain{"localhost"};
|
||||||
|
std::chrono::milliseconds connect_timeout{
|
||||||
|
std::chrono::seconds{10}};
|
||||||
|
std::chrono::milliseconds io_timeout{std::chrono::seconds{30}};
|
||||||
|
SmtpLimits limits{};
|
||||||
|
std::stop_token stop{};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SmtpMessage {
|
||||||
|
std::string from{};
|
||||||
|
std::vector<std::string> recipients{};
|
||||||
|
std::string data{};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Synchronous SMTP submission client over a verified TLS connection.
|
||||||
|
///
|
||||||
|
/// Supports implicit TLS and STARTTLS-required dialogue, AUTH PLAIN
|
||||||
|
/// (TLS only), MAIL/RCPT/DATA with CRLF normalization and dot-stuffing,
|
||||||
|
/// bounded replies, bounded message size, deadlines, and cancellation.
|
||||||
|
/// A failed send invalidates the client.
|
||||||
|
class SmtpClient final
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
SmtpClient() noexcept;
|
||||||
|
~SmtpClient() noexcept;
|
||||||
|
SmtpClient(SmtpClient&&) noexcept;
|
||||||
|
SmtpClient& operator=(SmtpClient&&) noexcept;
|
||||||
|
SmtpClient(const SmtpClient&) = delete;
|
||||||
|
SmtpClient& operator=(const SmtpClient&) = delete;
|
||||||
|
|
||||||
|
/// Connect, greet, negotiate TLS (when required), authenticate
|
||||||
|
/// (when credentials are configured), and prepare submission.
|
||||||
|
[[nodiscard]] static Void::Result::Result<SmtpClient>
|
||||||
|
connect(SmtpOptions options);
|
||||||
|
|
||||||
|
/// Convenience: connect, send one message, then QUIT.
|
||||||
|
[[nodiscard]] static Void::Result::Result<void>
|
||||||
|
submit(SmtpOptions options, const SmtpMessage& message);
|
||||||
|
|
||||||
|
[[nodiscard]] bool valid() const noexcept;
|
||||||
|
[[nodiscard]] bool secure() const noexcept;
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
send(const SmtpMessage& message);
|
||||||
|
|
||||||
|
/// Send QUIT (best effort) and close the connection.
|
||||||
|
[[nodiscard]] Void::Result::Result<void> quit();
|
||||||
|
|
||||||
|
void close() noexcept;
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct Impl;
|
||||||
|
std::unique_ptr<Impl> m_impl;
|
||||||
|
explicit SmtpClient(std::unique_ptr<Impl> impl) noexcept;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Net
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <memory>
|
||||||
|
#include <span>
|
||||||
|
#include <stop_token>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
namespace Void::Net
|
||||||
|
{
|
||||||
|
/// Options for a verified TLS client stream.
|
||||||
|
///
|
||||||
|
/// Peer and hostname verification are always enabled; there is no
|
||||||
|
/// insecure mode and no fallback to plaintext when the handshake fails.
|
||||||
|
/// `server_name` is the identity checked against the peer certificate
|
||||||
|
/// (and sent as SNI when it is a DNS name); it defaults to `host`.
|
||||||
|
/// `ca_file` selects an explicit PEM trust store; when empty the system
|
||||||
|
/// default trust store is used.
|
||||||
|
struct TlsClientOptions {
|
||||||
|
std::string host{};
|
||||||
|
std::uint16_t port{443};
|
||||||
|
std::string server_name{};
|
||||||
|
std::string ca_file{};
|
||||||
|
std::chrono::milliseconds connect_timeout{
|
||||||
|
std::chrono::seconds{10}};
|
||||||
|
std::chrono::milliseconds handshake_timeout{
|
||||||
|
std::chrono::seconds{10}};
|
||||||
|
std::chrono::milliseconds io_timeout{std::chrono::seconds{30}};
|
||||||
|
std::stop_token stop{};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Synchronous TLS client stream over a TCP socket (POSIX, OpenSSL).
|
||||||
|
///
|
||||||
|
/// `connect()` establishes TCP and completes a verified TLS handshake.
|
||||||
|
/// `connect_plain()` establishes TCP only, for protocols that negotiate
|
||||||
|
/// TLS in-band (SMTP STARTTLS, IMAP STARTTLS, ...); call `start_tls()`
|
||||||
|
/// after the plaintext negotiation. A failed `start_tls()` closes the
|
||||||
|
/// stream, so a caller can never continue on an unauthenticated channel.
|
||||||
|
///
|
||||||
|
/// Reads and writes accept an optional per-operation timeout (zero uses
|
||||||
|
/// `TlsClientOptions::io_timeout`) and an optional stop token (empty uses
|
||||||
|
/// `TlsClientOptions::stop`). Timeouts and cancellation interrupt the
|
||||||
|
/// operation without closing the stream.
|
||||||
|
class TlsClientStream final
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
TlsClientStream() noexcept;
|
||||||
|
~TlsClientStream() noexcept;
|
||||||
|
TlsClientStream(TlsClientStream&&) noexcept;
|
||||||
|
TlsClientStream& operator=(TlsClientStream&&) noexcept;
|
||||||
|
TlsClientStream(const TlsClientStream&) = delete;
|
||||||
|
TlsClientStream& operator=(const TlsClientStream&) = delete;
|
||||||
|
|
||||||
|
/// Resolve, connect, and complete a verified TLS handshake.
|
||||||
|
[[nodiscard]] static Void::Result::Result<TlsClientStream>
|
||||||
|
connect(TlsClientOptions options);
|
||||||
|
|
||||||
|
/// Connect TCP without starting TLS (STARTTLS plaintext phase).
|
||||||
|
[[nodiscard]] static Void::Result::Result<TlsClientStream>
|
||||||
|
connect_plain(TlsClientOptions options);
|
||||||
|
|
||||||
|
/// Take ownership of an already connected socket and start TLS
|
||||||
|
/// immediately. `native_socket` must be a connected TCP socket.
|
||||||
|
[[nodiscard]] static Void::Result::Result<TlsClientStream>
|
||||||
|
adopt(int native_socket, TlsClientOptions options);
|
||||||
|
|
||||||
|
/// Complete the verified TLS handshake on a stream created by
|
||||||
|
/// `connect_plain()` (or a plaintext `adopt()`). On failure the
|
||||||
|
/// stream is closed and `valid()` becomes false.
|
||||||
|
[[nodiscard]] Void::Result::Result<void> start_tls();
|
||||||
|
|
||||||
|
[[nodiscard]] bool valid() const noexcept;
|
||||||
|
[[nodiscard]] bool secure() const noexcept;
|
||||||
|
[[nodiscard]] int native_handle() const noexcept;
|
||||||
|
|
||||||
|
/// Read up to `destination.size()` bytes. Returns 0 on orderly EOF.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||||
|
read(std::span<std::byte> destination,
|
||||||
|
std::chrono::milliseconds timeout = {},
|
||||||
|
std::stop_token stop = {});
|
||||||
|
|
||||||
|
/// Write up to `source.size()` bytes (a positive result may be a
|
||||||
|
/// partial write).
|
||||||
|
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||||
|
write(std::span<const std::byte> source,
|
||||||
|
std::chrono::milliseconds timeout = {},
|
||||||
|
std::stop_token stop = {});
|
||||||
|
|
||||||
|
/// Write every byte, retrying partial writes.
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
write_all(std::span<const std::byte> source,
|
||||||
|
std::chrono::milliseconds timeout = {},
|
||||||
|
std::stop_token stop = {});
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
write_all(std::string_view text,
|
||||||
|
std::chrono::milliseconds timeout = {},
|
||||||
|
std::stop_token stop = {});
|
||||||
|
|
||||||
|
/// Send TLS close_notify (best effort) and close the socket.
|
||||||
|
[[nodiscard]] Void::Result::Result<void> shutdown();
|
||||||
|
void close() noexcept;
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct Impl;
|
||||||
|
std::unique_ptr<Impl> m_impl;
|
||||||
|
explicit TlsClientStream(std::unique_ptr<Impl> impl) noexcept;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Net
|
||||||
@@ -97,7 +97,16 @@ struct HookControl {
|
|||||||
std::condition_variable drain_cv;
|
std::condition_variable drain_cv;
|
||||||
};
|
};
|
||||||
|
|
||||||
inline thread_local std::vector<const HookControl*> t_active_hook_controls;
|
// Per-thread stack of hook controls currently executing. A function-local
|
||||||
|
// thread_local keeps a single definition across TUs; a namespace-scope
|
||||||
|
// `inline thread_local` makes MinGW emit one TLS init function per TU and
|
||||||
|
// fails to link with duplicate symbols.
|
||||||
|
[[nodiscard]] inline std::vector<const HookControl*>&
|
||||||
|
active_hook_controls() noexcept
|
||||||
|
{
|
||||||
|
static thread_local std::vector<const HookControl*> controls;
|
||||||
|
return controls;
|
||||||
|
}
|
||||||
|
|
||||||
struct HookCallScope {
|
struct HookCallScope {
|
||||||
const HookControl* control{nullptr};
|
const HookControl* control{nullptr};
|
||||||
@@ -105,14 +114,15 @@ struct HookCallScope {
|
|||||||
explicit HookCallScope(const HookControl* ctrl) : control(ctrl)
|
explicit HookCallScope(const HookControl* ctrl) : control(ctrl)
|
||||||
{
|
{
|
||||||
if (control != nullptr) {
|
if (control != nullptr) {
|
||||||
t_active_hook_controls.push_back(control);
|
active_hook_controls().push_back(control);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
~HookCallScope() noexcept
|
~HookCallScope() noexcept
|
||||||
{
|
{
|
||||||
if (control != nullptr && !t_active_hook_controls.empty()) {
|
auto& controls = active_hook_controls();
|
||||||
t_active_hook_controls.pop_back();
|
if (control != nullptr && !controls.empty()) {
|
||||||
|
controls.pop_back();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,7 +131,7 @@ struct HookCallScope {
|
|||||||
|
|
||||||
[[nodiscard]] static bool is_active_on_thread(const HookControl* ctrl) noexcept
|
[[nodiscard]] static bool is_active_on_thread(const HookControl* ctrl) noexcept
|
||||||
{
|
{
|
||||||
for (const auto* entry : t_active_hook_controls) {
|
for (const auto* entry : active_hook_controls()) {
|
||||||
if (entry == ctrl) {
|
if (entry == ctrl) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Script/Types.hpp>
|
||||||
|
|
||||||
|
#include <expected>
|
||||||
|
#include <functional>
|
||||||
|
#include <span>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Script
|
||||||
|
{
|
||||||
|
|
||||||
|
// The adapter's public interface is always declared so consumers can compile
|
||||||
|
// against it regardless of the build configuration. When Void is built without
|
||||||
|
// Lua (`VOID_SCRIPT_HAS_LUA` undefined), `LuaEvaluator::evaluate` returns a
|
||||||
|
// structured `Error` instead of running the chunk.
|
||||||
|
|
||||||
|
/// Host function: receives integer arguments, returns an integer or an error
|
||||||
|
/// message. It must not commit externally visible state itself; the evaluator
|
||||||
|
/// records each call in `Result::host_calls` so the caller can commit after a
|
||||||
|
/// successful evaluation.
|
||||||
|
using HostFunction = std::function<std::expected<Integer, std::string>(
|
||||||
|
std::span<const Integer>)>;
|
||||||
|
|
||||||
|
struct Host {
|
||||||
|
std::string name;
|
||||||
|
HostFunction function;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Standard Lua libraries the evaluator may open. Every library is opt-in
|
||||||
|
/// through this explicit allow-list; `os`, `io`, `package` and `debug` are
|
||||||
|
/// never opened, and even the base library has `load`, `loadfile`, `dofile`,
|
||||||
|
/// `collectgarbage` and `print` removed so a script cannot reach the ambient
|
||||||
|
/// filesystem, process, dynamic loader or host output.
|
||||||
|
struct Bindings {
|
||||||
|
bool base{true};
|
||||||
|
bool table{true};
|
||||||
|
bool string{true};
|
||||||
|
bool math{true};
|
||||||
|
bool coroutine{true};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const Bindings&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Returns true when evaluation must stop. It is polled from the instruction
|
||||||
|
/// hook and before every host call, so a long-running or host-heavy script is
|
||||||
|
/// interrupted cooperatively. An exception thrown by the callback is treated
|
||||||
|
/// as a cancellation request.
|
||||||
|
using CancelFunction = std::function<bool()>;
|
||||||
|
|
||||||
|
/// Complete evaluator policy. The defaults are a small, safe allow-list: no
|
||||||
|
/// host functions, no cancellation source, and only the hardened standard
|
||||||
|
/// libraries selected by `Bindings`.
|
||||||
|
struct Configuration {
|
||||||
|
Limits limits{};
|
||||||
|
Bindings bindings{};
|
||||||
|
std::vector<Host> hosts{};
|
||||||
|
CancelFunction cancelled{};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Bounded Lua text evaluator.
|
||||||
|
///
|
||||||
|
/// Each `evaluate` call creates a fresh, isolated Lua state, applies the
|
||||||
|
/// allocator, instruction, host-call and cancellation limits, exposes the
|
||||||
|
/// integer-keyed inputs as `input[key]`, registers the host functions as
|
||||||
|
/// globals, and runs the chunk with a protected call. Only integer return
|
||||||
|
/// values are accepted and collected into an owned result. On failure the
|
||||||
|
/// state is discarded, so inputs and the caller's host state are untouched; a
|
||||||
|
/// later valid evaluation starts clean.
|
||||||
|
///
|
||||||
|
/// The Lua state alone is not a security boundary: run untrusted scripts in a
|
||||||
|
/// separately isolated process. This evaluator only removes the obvious
|
||||||
|
/// ambient capabilities and enforces resource budgets.
|
||||||
|
class LuaEvaluator
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
explicit LuaEvaluator(Limits limits = Limits{},
|
||||||
|
std::vector<Host> hosts = {})
|
||||||
|
: configuration_{
|
||||||
|
.limits = limits,
|
||||||
|
.bindings = Bindings{},
|
||||||
|
.hosts = std::move(hosts),
|
||||||
|
.cancelled = CancelFunction{}}
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
explicit LuaEvaluator(Configuration configuration)
|
||||||
|
: configuration_(std::move(configuration))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] const Limits& limits() const noexcept
|
||||||
|
{
|
||||||
|
return configuration_.limits;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] const Bindings& bindings() const noexcept
|
||||||
|
{
|
||||||
|
return configuration_.bindings;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::expected<Result, Error>
|
||||||
|
evaluate(std::string_view source,
|
||||||
|
std::span<const Input> inputs = {}) const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
Configuration configuration_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Script
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <compare>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Script
|
||||||
|
{
|
||||||
|
|
||||||
|
using Integer = std::int64_t;
|
||||||
|
|
||||||
|
enum class ErrorKind : std::uint8_t {
|
||||||
|
compile = 0,
|
||||||
|
runtime,
|
||||||
|
allocator_limit,
|
||||||
|
instruction_limit,
|
||||||
|
host_call_limit,
|
||||||
|
result_limit,
|
||||||
|
host_error,
|
||||||
|
invalid_input,
|
||||||
|
cancelled,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Error {
|
||||||
|
ErrorKind kind{ErrorKind::runtime};
|
||||||
|
std::string message;
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const Error&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Limits {
|
||||||
|
/// Total bytes the VM may allocate (including the state and libraries).
|
||||||
|
std::size_t max_allocator_bytes{1ULL * 1024ULL * 1024ULL};
|
||||||
|
/// VM instructions before evaluation is aborted.
|
||||||
|
std::size_t max_instructions{100'000};
|
||||||
|
/// Host function invocations before evaluation is aborted.
|
||||||
|
std::size_t max_host_calls{1'000};
|
||||||
|
/// Maximum number of integer results collected.
|
||||||
|
std::size_t max_result_integers{1'024};
|
||||||
|
/// Maximum number of integer-keyed inputs.
|
||||||
|
std::size_t max_inputs{256};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Integer-keyed input exposed to the script as `input[key]`.
|
||||||
|
struct Input {
|
||||||
|
Integer key{0};
|
||||||
|
Integer value{0};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const Input&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// One host function call observed during a successful evaluation. The caller
|
||||||
|
/// may commit these effects after `evaluate` returns; the evaluator itself
|
||||||
|
/// never commits host state.
|
||||||
|
struct HostInvocation {
|
||||||
|
std::string host;
|
||||||
|
std::vector<Integer> arguments;
|
||||||
|
Integer result{0};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const HostInvocation&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Owned result of a successful evaluation.
|
||||||
|
struct Result {
|
||||||
|
/// Integer values returned by the chunk, in order.
|
||||||
|
std::vector<Integer> integers;
|
||||||
|
/// Host calls made by the script, in order.
|
||||||
|
std::vector<HostInvocation> host_calls;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Script
|
||||||
@@ -37,6 +37,12 @@ namespace Void::Security
|
|||||||
[[nodiscard]] Void::Result::Result<std::string>
|
[[nodiscard]] Void::Result::Result<std::string>
|
||||||
random_token(std::size_t entropy_bytes = default_token_entropy_bytes);
|
random_token(std::size_t entropy_bytes = default_token_entropy_bytes);
|
||||||
|
|
||||||
|
/// Fill `buffer` with cryptographically secure random bytes from the
|
||||||
|
/// platform CSPRNG. An empty buffer is a successful no-op; on failure the
|
||||||
|
/// destination is wiped so no partial randomness is left behind.
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
random_bytes(std::span<unsigned char> buffer);
|
||||||
|
|
||||||
/// Produce a deterministic lowercase hexadecimal BLAKE2b-256 digest.
|
/// Produce a deterministic lowercase hexadecimal BLAKE2b-256 digest.
|
||||||
/// Store this digest instead of the bearer token itself.
|
/// Store this digest instead of the bearer token itself.
|
||||||
[[nodiscard]] Void::Result::Result<std::string>
|
[[nodiscard]] Void::Result::Result<std::string>
|
||||||
|
|||||||
@@ -140,6 +140,12 @@ namespace Void::Sqlite
|
|||||||
}
|
}
|
||||||
return Void::Result::fail(std::move(c).error());
|
return Void::Result::fail(std::move(c).error());
|
||||||
}
|
}
|
||||||
|
} else if (tx->state() != TransactionState::Committed) {
|
||||||
|
// SQLite may end the transaction on its own (FULL, interrupt,
|
||||||
|
// IO error). Never report the callback's success as durable.
|
||||||
|
return Void::Result::fail(make_sqlite_error(
|
||||||
|
SqliteErrorCode::misuse,
|
||||||
|
"AsyncPool: transaction ended before commit (automatically rolled back)"));
|
||||||
}
|
}
|
||||||
return res;
|
return res;
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -181,7 +181,10 @@ namespace Void::Sqlite
|
|||||||
};
|
};
|
||||||
|
|
||||||
/// RAII transaction retaining shared ConnectionState. Never marks Committed
|
/// RAII transaction retaining shared ConnectionState. Never marks Committed
|
||||||
/// before COMMIT succeeds; inspects sqlite3_get_autocommit on error.
|
/// before COMMIT succeeds; inspects sqlite3_get_autocommit on error and after
|
||||||
|
/// statements so an automatic rollback is reported as RolledBack. A failed
|
||||||
|
/// COMMIT whose outcome cannot be proven (WAL I/O error) is reported as
|
||||||
|
/// Unknown, never as RolledBack.
|
||||||
class Transaction
|
class Transaction
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
@@ -192,22 +195,29 @@ namespace Void::Sqlite
|
|||||||
Transaction(const Transaction&) = delete;
|
Transaction(const Transaction&) = delete;
|
||||||
Transaction& operator=(const Transaction&) = delete;
|
Transaction& operator=(const Transaction&) = delete;
|
||||||
|
|
||||||
[[nodiscard]] TransactionState state() const noexcept { return m_state; }
|
/// Observes the native autocommit state; returns RolledBack when SQLite
|
||||||
[[nodiscard]] bool is_active() const noexcept
|
/// already ended this transaction (for example SQLITE_FULL or an
|
||||||
{
|
/// interrupt inside the transaction).
|
||||||
return m_state == TransactionState::Active;
|
[[nodiscard]] TransactionState state() const noexcept;
|
||||||
}
|
[[nodiscard]] bool is_active() const noexcept;
|
||||||
|
|
||||||
|
/// Commits the transaction. On failure state() is Active (SQLite kept
|
||||||
|
/// the transaction open; retry or roll back), RolledBack (SQLite ended
|
||||||
|
/// it and it was not committed), or Unknown (SQLite ended it but a WAL
|
||||||
|
/// I/O error means the commit may have taken effect).
|
||||||
Result<void> commit();
|
Result<void> commit();
|
||||||
[[nodiscard]] Result<void> rollback_checked();
|
[[nodiscard]] Result<void> rollback_checked();
|
||||||
void rollback() noexcept;
|
void rollback() noexcept;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
friend class Database;
|
friend class Database;
|
||||||
explicit Transaction(std::shared_ptr<detail::ConnectionState> conn) noexcept;
|
explicit Transaction(std::shared_ptr<detail::ConnectionState> conn,
|
||||||
|
std::uint64_t id) noexcept;
|
||||||
|
void refresh_state() const noexcept;
|
||||||
|
|
||||||
std::shared_ptr<detail::ConnectionState> m_conn{};
|
std::shared_ptr<detail::ConnectionState> m_conn{};
|
||||||
TransactionState m_state{TransactionState::RolledBack};
|
std::uint64_t m_id{0};
|
||||||
|
mutable TransactionState m_state{TransactionState::RolledBack};
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Separately owned nested savepoint scope.
|
/// Separately owned nested savepoint scope.
|
||||||
@@ -238,6 +248,40 @@ namespace Void::Sqlite
|
|||||||
bool m_active{false};
|
bool m_active{false};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// Scoped per-call override of the connection busy timeout.
|
||||||
|
///
|
||||||
|
/// The previous timeout is restored when this object is destroyed (or
|
||||||
|
/// explicitly via restore()), so a single statement or transaction can use
|
||||||
|
/// a tighter or looser bound without permanently changing the connection.
|
||||||
|
class BusyTimeoutOverride
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
BusyTimeoutOverride() noexcept = default;
|
||||||
|
~BusyTimeoutOverride();
|
||||||
|
BusyTimeoutOverride(BusyTimeoutOverride&&) noexcept;
|
||||||
|
BusyTimeoutOverride& operator=(BusyTimeoutOverride&&) noexcept;
|
||||||
|
BusyTimeoutOverride(const BusyTimeoutOverride&) = delete;
|
||||||
|
BusyTimeoutOverride& operator=(const BusyTimeoutOverride&) = delete;
|
||||||
|
|
||||||
|
[[nodiscard]] bool is_active() const noexcept { return m_active; }
|
||||||
|
[[nodiscard]] std::chrono::milliseconds previous() const noexcept
|
||||||
|
{
|
||||||
|
return m_previous;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Restore the previous timeout early. Idempotent.
|
||||||
|
void restore() noexcept;
|
||||||
|
|
||||||
|
private:
|
||||||
|
friend class Database;
|
||||||
|
BusyTimeoutOverride(std::shared_ptr<detail::ConnectionState> conn,
|
||||||
|
std::chrono::milliseconds previous) noexcept;
|
||||||
|
|
||||||
|
std::shared_ptr<detail::ConnectionState> m_conn{};
|
||||||
|
std::chrono::milliseconds m_previous{0};
|
||||||
|
bool m_active{false};
|
||||||
|
};
|
||||||
|
|
||||||
/// A single forward schema migration applied when the database's
|
/// A single forward schema migration applied when the database's
|
||||||
/// user_version is below `version`.
|
/// user_version is below `version`.
|
||||||
struct Migration {
|
struct Migration {
|
||||||
@@ -296,6 +340,12 @@ namespace Void::Sqlite
|
|||||||
std::size_t max_rows = 0,
|
std::size_t max_rows = 0,
|
||||||
std::size_t max_bytes = 0);
|
std::size_t max_bytes = 0);
|
||||||
|
|
||||||
|
/// Temporarily override the connection busy timeout for the next
|
||||||
|
/// calls. The previous value is restored when the returned scope is
|
||||||
|
/// destroyed. A negative timeout is rejected.
|
||||||
|
[[nodiscard]] Result<BusyTimeoutOverride>
|
||||||
|
override_busy_timeout(std::chrono::milliseconds timeout);
|
||||||
|
|
||||||
/// Explicitly close the connection. Stops admission and returns
|
/// Explicitly close the connection. Stops admission and returns
|
||||||
/// SqliteErrorCode::busy while live statements/transactions/savepoints
|
/// SqliteErrorCode::busy while live statements/transactions/savepoints
|
||||||
/// remain open.
|
/// remain open.
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
#include <span>
|
#include <span>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
|
#include <system_error>
|
||||||
#include <variant>
|
#include <variant>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
@@ -49,10 +50,22 @@ namespace Void::Sqlite
|
|||||||
};
|
};
|
||||||
|
|
||||||
enum class TransactionState : std::uint8_t {
|
enum class TransactionState : std::uint8_t {
|
||||||
|
/// The transaction is open; statements execute inside it.
|
||||||
Active,
|
Active,
|
||||||
|
/// COMMIT succeeded and the transaction is durable.
|
||||||
Committed,
|
Committed,
|
||||||
|
/// SQLite ended the transaction without committing it (explicit or
|
||||||
|
/// automatic rollback, or the transaction never started).
|
||||||
RolledBack,
|
RolledBack,
|
||||||
RecoveryRequired
|
/// The connection or rollback state is unusable; the application must
|
||||||
|
/// recover before continuing.
|
||||||
|
RecoveryRequired,
|
||||||
|
/// COMMIT failed and SQLite ended the transaction, but the wrapper cannot
|
||||||
|
/// prove whether the commit took effect. A WAL I/O error can be reported
|
||||||
|
/// after the commit record became durable, so this must never be treated
|
||||||
|
/// as a definite rollback: inspect the database before assuming either
|
||||||
|
/// outcome.
|
||||||
|
Unknown
|
||||||
};
|
};
|
||||||
|
|
||||||
enum class ColumnType : std::uint8_t {
|
enum class ColumnType : std::uint8_t {
|
||||||
@@ -91,6 +104,56 @@ namespace Void::Sqlite
|
|||||||
sqlite_error = 24
|
sqlite_error = 24
|
||||||
};
|
};
|
||||||
|
|
||||||
|
namespace Detail
|
||||||
|
{
|
||||||
|
/// std::error_category carrying SQLite's native primary/extended result
|
||||||
|
/// codes without widening Void::Result::ErrorCode.
|
||||||
|
class SqliteNativeErrorCategory final : public std::error_category
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
[[nodiscard]] const char* name() const noexcept override
|
||||||
|
{
|
||||||
|
return "void.sqlite.native";
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::string message(int code) const override
|
||||||
|
{
|
||||||
|
return "sqlite native result code " + std::to_string(code);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} // namespace Detail
|
||||||
|
|
||||||
|
/// The SQLite error category used for native primary/extended codes.
|
||||||
|
[[nodiscard]] inline const std::error_category&
|
||||||
|
sqlite_native_error_category() noexcept
|
||||||
|
{
|
||||||
|
static const Detail::SqliteNativeErrorCategory category{};
|
||||||
|
return category;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// SQLite's native result code split into its primary and extended parts.
|
||||||
|
struct SqliteNativeCode {
|
||||||
|
int primary{0};
|
||||||
|
int extended{0};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const SqliteNativeCode&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Recover the native SQLite codes from an error, if it came from SQLite.
|
||||||
|
/// The extended code keeps the fine-grained reason (for example UNIQUE vs
|
||||||
|
/// FOREIGN KEY constraint failures, or BUSY vs LOCKED).
|
||||||
|
[[nodiscard]] inline std::optional<SqliteNativeCode>
|
||||||
|
sqlite_native_code(const Error& error) noexcept
|
||||||
|
{
|
||||||
|
const std::error_code system = error.system_code();
|
||||||
|
if (system.category() != sqlite_native_error_category()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const int extended = system.value();
|
||||||
|
return SqliteNativeCode{extended & 0xff, extended};
|
||||||
|
}
|
||||||
|
|
||||||
[[nodiscard]] inline Error make_sqlite_error(
|
[[nodiscard]] inline Error make_sqlite_error(
|
||||||
SqliteErrorCode code,
|
SqliteErrorCode code,
|
||||||
std::string message,
|
std::string message,
|
||||||
@@ -161,11 +224,19 @@ namespace Void::Sqlite
|
|||||||
message += ")";
|
message += ")";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::error_code native{};
|
||||||
|
if (primary_code != 0 || extended_code != 0) {
|
||||||
|
native = std::error_code{
|
||||||
|
extended_code != 0 ? extended_code : primary_code,
|
||||||
|
sqlite_native_error_category()};
|
||||||
|
}
|
||||||
|
|
||||||
return Error{
|
return Error{
|
||||||
kind,
|
kind,
|
||||||
std::move(message),
|
std::move(message),
|
||||||
ErrorCode{Void::Result::kSqliteErrorDomain,
|
ErrorCode{Void::Result::kSqliteErrorDomain,
|
||||||
static_cast<std::int32_t>(code)}};
|
static_cast<std::int32_t>(code)},
|
||||||
|
native};
|
||||||
}
|
}
|
||||||
|
|
||||||
struct SqliteLimits {
|
struct SqliteLimits {
|
||||||
@@ -177,6 +248,8 @@ namespace Void::Sqlite
|
|||||||
std::size_t max_cached_statements{64};
|
std::size_t max_cached_statements{64};
|
||||||
std::size_t max_cache_bytes{8ULL * 1024ULL * 1024ULL};
|
std::size_t max_cache_bytes{8ULL * 1024ULL * 1024ULL};
|
||||||
std::chrono::milliseconds busy_timeout{5000};
|
std::chrono::milliseconds busy_timeout{5000};
|
||||||
|
/// WAL thresholds are measured in un-checkpointed frames (converted to
|
||||||
|
/// bytes with the database page size), not the raw on-disk WAL size.
|
||||||
std::uint64_t wal_checkpoint_threshold_bytes{16ULL * 1024ULL * 1024ULL};
|
std::uint64_t wal_checkpoint_threshold_bytes{16ULL * 1024ULL * 1024ULL};
|
||||||
std::uint64_t wal_warn_threshold_bytes{64ULL * 1024ULL * 1024ULL};
|
std::uint64_t wal_warn_threshold_bytes{64ULL * 1024ULL * 1024ULL};
|
||||||
std::uint64_t wal_stop_writes_threshold_bytes{256ULL * 1024ULL * 1024ULL};
|
std::uint64_t wal_stop_writes_threshold_bytes{256ULL * 1024ULL * 1024ULL};
|
||||||
@@ -335,6 +408,8 @@ namespace Void::Sqlite
|
|||||||
struct CheckpointReport {
|
struct CheckpointReport {
|
||||||
int log_frames{0};
|
int log_frames{0};
|
||||||
int checkpointed_frames{0};
|
int checkpointed_frames{0};
|
||||||
|
/// Frames written to the WAL but not yet copied back into the database.
|
||||||
|
int uncheckpointed_frames{0};
|
||||||
bool busy{false};
|
bool busy{false};
|
||||||
std::uint64_t wal_size_bytes{0};
|
std::uint64_t wal_size_bytes{0};
|
||||||
};
|
};
|
||||||
@@ -364,6 +439,14 @@ namespace Void::Sqlite
|
|||||||
bool active_transaction{false};
|
bool active_transaction{false};
|
||||||
std::size_t open_savepoints{0};
|
std::size_t open_savepoints{0};
|
||||||
std::uint64_t wal_size_bytes{0};
|
std::uint64_t wal_size_bytes{0};
|
||||||
|
/// Whether the frame counts below were obtained from the WAL index. When
|
||||||
|
/// false, `wal_uncheckpointed_bytes` is a conservative upper bound (the
|
||||||
|
/// on-disk WAL size) and the frame counts are zero.
|
||||||
|
bool wal_frames_known{false};
|
||||||
|
int wal_log_frames{0};
|
||||||
|
int wal_checkpointed_frames{0};
|
||||||
|
int wal_uncheckpointed_frames{0};
|
||||||
|
std::uint64_t wal_uncheckpointed_bytes{0};
|
||||||
bool wal_checkpoint_recommended{false};
|
bool wal_checkpoint_recommended{false};
|
||||||
bool wal_warn_exceeded{false};
|
bool wal_warn_exceeded{false};
|
||||||
bool wal_write_admission_blocked{false};
|
bool wal_write_admission_blocked{false};
|
||||||
@@ -382,6 +465,10 @@ namespace Void::Sqlite
|
|||||||
/// If true along with fail_next_commit_rc, simulates SQLite
|
/// If true along with fail_next_commit_rc, simulates SQLite
|
||||||
/// auto-rollback before returning the error.
|
/// auto-rollback before returning the error.
|
||||||
bool auto_rollback_on_faulted_commit{false};
|
bool auto_rollback_on_faulted_commit{false};
|
||||||
|
/// If true along with fail_next_commit_rc, the COMMIT is executed and
|
||||||
|
/// committed first, and the error is reported afterwards. Models a lost
|
||||||
|
/// commit acknowledgement, where the outcome is genuinely unknown.
|
||||||
|
bool commit_applied_before_error{false};
|
||||||
/// If non-zero, next explicit close() returns this SQLite error code.
|
/// If non-zero, next explicit close() returns this SQLite error code.
|
||||||
int fail_next_close_rc{0};
|
int fail_next_close_rc{0};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,410 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <expected>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
#include <string>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
#ifndef WIN32_LEAN_AND_MEAN
|
||||||
|
#define WIN32_LEAN_AND_MEAN
|
||||||
|
#endif
|
||||||
|
#ifndef NOMINMAX
|
||||||
|
#define NOMINMAX
|
||||||
|
#endif
|
||||||
|
#include <mmsystem.h>
|
||||||
|
#include <windows.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace Void::System
|
||||||
|
{
|
||||||
|
|
||||||
|
using PcmSample = std::int16_t;
|
||||||
|
|
||||||
|
struct PcmFormat {
|
||||||
|
std::uint32_t sample_rate{44100};
|
||||||
|
std::uint16_t channels{2};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const PcmFormat&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Owned PCM sample data. The device keeps it alive for as long as a voice
|
||||||
|
/// references it; callers may release their handle right after submission.
|
||||||
|
struct PcmBuffer {
|
||||||
|
PcmFormat format;
|
||||||
|
std::vector<PcmSample> samples;
|
||||||
|
|
||||||
|
[[nodiscard]] std::chrono::microseconds duration() const noexcept
|
||||||
|
{
|
||||||
|
const std::uint64_t frames =
|
||||||
|
format.channels == 0
|
||||||
|
? 0
|
||||||
|
: samples.size() / format.channels;
|
||||||
|
if (format.sample_rate == 0) {
|
||||||
|
return std::chrono::microseconds{0};
|
||||||
|
}
|
||||||
|
return std::chrono::microseconds{
|
||||||
|
static_cast<std::int64_t>(frames) * 1'000'000 /
|
||||||
|
format.sample_rate};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class AudioStatus : std::uint8_t {
|
||||||
|
ok = 0,
|
||||||
|
/// No output device is available; the caller can continue silently.
|
||||||
|
device_unavailable,
|
||||||
|
voice_limit,
|
||||||
|
invalid_buffer,
|
||||||
|
backend_error,
|
||||||
|
closed,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct AudioError {
|
||||||
|
AudioStatus status{AudioStatus::backend_error};
|
||||||
|
std::string message;
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const AudioError&) const = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class VoiceState : std::uint8_t {
|
||||||
|
playing = 0,
|
||||||
|
stopped,
|
||||||
|
finished,
|
||||||
|
unknown,
|
||||||
|
};
|
||||||
|
|
||||||
|
using VoiceId = std::uint64_t;
|
||||||
|
|
||||||
|
struct AudioLimits {
|
||||||
|
std::size_t max_voices{8};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Bounded PCM playback with owned samples and explicit voice lifetimes.
|
||||||
|
///
|
||||||
|
/// `play` transfers a shared handle to the device; the caller may drop its
|
||||||
|
/// handle immediately and the samples stay alive until the voice is stopped,
|
||||||
|
/// finishes or the device closes. `stop` ends a voice (including a loop),
|
||||||
|
/// `state` reports and reaps finished voices, and the destructor tears every
|
||||||
|
/// voice down. A missing device is reported as `device_unavailable` so an
|
||||||
|
/// application can continue without audio; `open_silent` provides the same
|
||||||
|
/// lifetime semantics without a device (used for tests and headless runs).
|
||||||
|
///
|
||||||
|
/// Thread-safe.
|
||||||
|
class AudioDevice
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
static std::expected<AudioDevice, AudioError>
|
||||||
|
open(AudioLimits limits = {})
|
||||||
|
{
|
||||||
|
auto impl = std::make_unique<Impl>();
|
||||||
|
impl->limits = limits;
|
||||||
|
#ifdef _WIN32
|
||||||
|
impl->silent = false;
|
||||||
|
#else
|
||||||
|
impl->silent = true;
|
||||||
|
#endif
|
||||||
|
return AudioDevice{std::move(impl)};
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::expected<AudioDevice, AudioError>
|
||||||
|
open_silent(AudioLimits limits = {})
|
||||||
|
{
|
||||||
|
auto impl = std::make_unique<Impl>();
|
||||||
|
impl->limits = limits;
|
||||||
|
impl->silent = true;
|
||||||
|
return AudioDevice{std::move(impl)};
|
||||||
|
}
|
||||||
|
|
||||||
|
AudioDevice(AudioDevice&&) noexcept = default;
|
||||||
|
AudioDevice& operator=(AudioDevice&&) noexcept = default;
|
||||||
|
|
||||||
|
AudioDevice(const AudioDevice&) = delete;
|
||||||
|
AudioDevice& operator=(const AudioDevice&) = delete;
|
||||||
|
|
||||||
|
~AudioDevice() { close(); }
|
||||||
|
|
||||||
|
[[nodiscard]] bool available() const
|
||||||
|
{
|
||||||
|
std::lock_guard lock{impl_->mutex};
|
||||||
|
return !impl_->closed && impl_->available;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Submit owned samples. On success the device owns a reference; on
|
||||||
|
/// failure the caller's handle is untouched.
|
||||||
|
[[nodiscard]] std::expected<VoiceId, AudioError>
|
||||||
|
play(std::shared_ptr<const PcmBuffer> buffer, bool loop = false)
|
||||||
|
{
|
||||||
|
Impl& impl = *impl_;
|
||||||
|
std::lock_guard lock{impl.mutex};
|
||||||
|
reap(impl);
|
||||||
|
if (impl.closed) {
|
||||||
|
return std::unexpected{
|
||||||
|
AudioError{AudioStatus::closed, "audio device is closed"}};
|
||||||
|
}
|
||||||
|
if (!impl.available) {
|
||||||
|
return std::unexpected{AudioError{
|
||||||
|
AudioStatus::device_unavailable,
|
||||||
|
"no audio output device"}};
|
||||||
|
}
|
||||||
|
if (buffer == nullptr || buffer->format.channels == 0 ||
|
||||||
|
buffer->samples.empty()) {
|
||||||
|
return std::unexpected{AudioError{
|
||||||
|
AudioStatus::invalid_buffer, "empty PCM buffer"}};
|
||||||
|
}
|
||||||
|
if (impl.voices.size() >= impl.limits.max_voices) {
|
||||||
|
return std::unexpected{AudioError{
|
||||||
|
AudioStatus::voice_limit, "voice limit reached"}};
|
||||||
|
}
|
||||||
|
|
||||||
|
Voice voice;
|
||||||
|
voice.id = impl.next_id++;
|
||||||
|
voice.buffer = std::move(buffer);
|
||||||
|
voice.loop = loop;
|
||||||
|
voice.state = VoiceState::playing;
|
||||||
|
voice.started = std::chrono::steady_clock::now();
|
||||||
|
#ifdef _WIN32
|
||||||
|
if (!impl.silent) {
|
||||||
|
if (const auto error = start_win32(voice); !error.has_value()) {
|
||||||
|
return std::unexpected{error.error()};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
const VoiceId id = voice.id;
|
||||||
|
impl.voices.emplace(id, std::move(voice));
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stop a voice (including a loop) and release its samples.
|
||||||
|
bool stop(VoiceId id)
|
||||||
|
{
|
||||||
|
Impl& impl = *impl_;
|
||||||
|
std::lock_guard lock{impl.mutex};
|
||||||
|
const auto found = impl.voices.find(id);
|
||||||
|
if (found == impl.voices.end()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
found->second.state = VoiceState::stopped;
|
||||||
|
release(impl, found->second);
|
||||||
|
impl.voices.erase(found);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Current state; finished voices are reaped and their samples
|
||||||
|
/// released.
|
||||||
|
[[nodiscard]] VoiceState state(VoiceId id)
|
||||||
|
{
|
||||||
|
Impl& impl = *impl_;
|
||||||
|
std::lock_guard lock{impl.mutex};
|
||||||
|
const auto found = impl.voices.find(id);
|
||||||
|
if (found == impl.voices.end()) {
|
||||||
|
return VoiceState::unknown;
|
||||||
|
}
|
||||||
|
Voice& voice = found->second;
|
||||||
|
#ifdef _WIN32
|
||||||
|
if (!impl.silent) {
|
||||||
|
service_win32(voice);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
if (voice.state == VoiceState::playing && !voice.loop &&
|
||||||
|
std::chrono::steady_clock::now() - voice.started >=
|
||||||
|
voice.buffer->duration()) {
|
||||||
|
voice.state = VoiceState::finished;
|
||||||
|
}
|
||||||
|
const VoiceState result = voice.state;
|
||||||
|
if (result == VoiceState::finished ||
|
||||||
|
result == VoiceState::stopped) {
|
||||||
|
release(impl, voice);
|
||||||
|
impl.voices.erase(found);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::size_t active_voices()
|
||||||
|
{
|
||||||
|
Impl& impl = *impl_;
|
||||||
|
std::lock_guard lock{impl.mutex};
|
||||||
|
reap(impl);
|
||||||
|
return impl.voices.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
void close()
|
||||||
|
{
|
||||||
|
if (impl_ == nullptr) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Impl& impl = *impl_;
|
||||||
|
std::lock_guard lock{impl.mutex};
|
||||||
|
for (auto& [id, voice] : impl.voices) {
|
||||||
|
(void)id;
|
||||||
|
stop_backend(voice);
|
||||||
|
voice.buffer.reset();
|
||||||
|
}
|
||||||
|
impl.voices.clear();
|
||||||
|
impl.closed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct Voice {
|
||||||
|
VoiceId id{0};
|
||||||
|
std::shared_ptr<const PcmBuffer> buffer;
|
||||||
|
bool loop{false};
|
||||||
|
VoiceState state{VoiceState::playing};
|
||||||
|
std::chrono::steady_clock::time_point started{};
|
||||||
|
#ifdef _WIN32
|
||||||
|
HWAVEOUT wave{};
|
||||||
|
WAVEHDR header{};
|
||||||
|
WAVEFORMATEX format{};
|
||||||
|
std::vector<PcmSample> playback;
|
||||||
|
bool prepared{false};
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Impl {
|
||||||
|
mutable std::mutex mutex;
|
||||||
|
AudioLimits limits{};
|
||||||
|
std::unordered_map<VoiceId, Voice> voices;
|
||||||
|
VoiceId next_id{1};
|
||||||
|
bool silent{true};
|
||||||
|
bool available{true};
|
||||||
|
bool closed{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
explicit AudioDevice(std::unique_ptr<Impl> impl)
|
||||||
|
: impl_(std::move(impl))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
static void release(Impl& impl, Voice& voice)
|
||||||
|
{
|
||||||
|
(void)impl;
|
||||||
|
#ifdef _WIN32
|
||||||
|
stop_backend(voice);
|
||||||
|
#endif
|
||||||
|
voice.buffer.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reap voices that finished. Silent non-loop voices finish after
|
||||||
|
/// their duration; looping voices stay until stopped.
|
||||||
|
static void reap(Impl& impl)
|
||||||
|
{
|
||||||
|
const auto now = std::chrono::steady_clock::now();
|
||||||
|
for (auto iterator = impl.voices.begin();
|
||||||
|
iterator != impl.voices.end();) {
|
||||||
|
Voice& voice = iterator->second;
|
||||||
|
#ifdef _WIN32
|
||||||
|
if (!impl.silent) {
|
||||||
|
service_win32(voice);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
if (voice.state == VoiceState::playing && !voice.loop &&
|
||||||
|
now - voice.started >= voice.buffer->duration()) {
|
||||||
|
voice.state = VoiceState::finished;
|
||||||
|
}
|
||||||
|
if (voice.state == VoiceState::finished ||
|
||||||
|
voice.state == VoiceState::stopped) {
|
||||||
|
release(impl, voice);
|
||||||
|
iterator = impl.voices.erase(iterator);
|
||||||
|
} else {
|
||||||
|
++iterator;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
static std::expected<void, AudioError> start_win32(Voice& voice)
|
||||||
|
{
|
||||||
|
voice.format.wFormatTag = WAVE_FORMAT_PCM;
|
||||||
|
voice.format.nChannels =
|
||||||
|
static_cast<WORD>(voice.buffer->format.channels);
|
||||||
|
voice.format.nSamplesPerSec =
|
||||||
|
static_cast<DWORD>(voice.buffer->format.sample_rate);
|
||||||
|
voice.format.wBitsPerSample = 16;
|
||||||
|
voice.format.nBlockAlign =
|
||||||
|
static_cast<WORD>(voice.format.nChannels * 2);
|
||||||
|
voice.format.nAvgBytesPerSec =
|
||||||
|
voice.format.nSamplesPerSec * voice.format.nBlockAlign;
|
||||||
|
voice.format.cbSize = 0;
|
||||||
|
|
||||||
|
const MMRESULT opened = ::waveOutOpen(
|
||||||
|
&voice.wave, WAVE_MAPPER, &voice.format, 0, 0,
|
||||||
|
CALLBACK_NULL);
|
||||||
|
if (opened != MMSYSERR_NOERROR) {
|
||||||
|
voice.wave = nullptr;
|
||||||
|
return std::unexpected{AudioError{
|
||||||
|
AudioStatus::device_unavailable,
|
||||||
|
"waveOutOpen failed"}};
|
||||||
|
}
|
||||||
|
voice.header = WAVEHDR{};
|
||||||
|
// waveOut only reads the samples, but WAVEHDR exposes a mutable
|
||||||
|
// buffer; keep an owned mutable copy instead of casting away
|
||||||
|
// constness of the shared buffer.
|
||||||
|
voice.playback = voice.buffer->samples;
|
||||||
|
voice.header.lpData =
|
||||||
|
reinterpret_cast<LPSTR>(voice.playback.data());
|
||||||
|
voice.header.dwBufferLength = static_cast<DWORD>(
|
||||||
|
voice.playback.size() * sizeof(PcmSample));
|
||||||
|
if (::waveOutPrepareHeader(voice.wave, &voice.header,
|
||||||
|
sizeof(WAVEHDR)) !=
|
||||||
|
MMSYSERR_NOERROR) {
|
||||||
|
::waveOutClose(voice.wave);
|
||||||
|
voice.wave = nullptr;
|
||||||
|
return std::unexpected{AudioError{
|
||||||
|
AudioStatus::backend_error,
|
||||||
|
"waveOutPrepareHeader failed"}};
|
||||||
|
}
|
||||||
|
voice.prepared = true;
|
||||||
|
if (::waveOutWrite(voice.wave, &voice.header, sizeof(WAVEHDR)) !=
|
||||||
|
MMSYSERR_NOERROR) {
|
||||||
|
stop_backend(voice);
|
||||||
|
return std::unexpected{AudioError{
|
||||||
|
AudioStatus::backend_error, "waveOutWrite failed"}};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
static void service_win32(Voice& voice)
|
||||||
|
{
|
||||||
|
if (voice.wave == nullptr ||
|
||||||
|
(voice.header.dwFlags & WHDR_DONE) == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (voice.loop) {
|
||||||
|
// Re-queue the same prepared header for another pass.
|
||||||
|
voice.header.dwFlags &= ~WHDR_DONE;
|
||||||
|
(void)::waveOutWrite(voice.wave, &voice.header,
|
||||||
|
sizeof(WAVEHDR));
|
||||||
|
} else {
|
||||||
|
voice.state = VoiceState::finished;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void stop_backend(Voice& voice)
|
||||||
|
{
|
||||||
|
if (voice.wave != nullptr) {
|
||||||
|
(void)::waveOutReset(voice.wave);
|
||||||
|
if (voice.prepared) {
|
||||||
|
(void)::waveOutUnprepareHeader(
|
||||||
|
voice.wave, &voice.header, sizeof(WAVEHDR));
|
||||||
|
voice.prepared = false;
|
||||||
|
}
|
||||||
|
(void)::waveOutClose(voice.wave);
|
||||||
|
voice.wave = nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
static void stop_backend(Voice&) {}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
std::unique_ptr<Impl> impl_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::System
|
||||||
+545
-20
@@ -36,6 +36,14 @@
|
|||||||
#include <linux/fs.h>
|
#include <linux/fs.h>
|
||||||
#endif
|
#endif
|
||||||
#endif
|
#endif
|
||||||
|
#else
|
||||||
|
#ifndef WIN32_LEAN_AND_MEAN
|
||||||
|
#define WIN32_LEAN_AND_MEAN
|
||||||
|
#endif
|
||||||
|
#ifndef NOMINMAX
|
||||||
|
#define NOMINMAX
|
||||||
|
#endif
|
||||||
|
#include <windows.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace Void::FileSystem
|
namespace Void::FileSystem
|
||||||
@@ -45,6 +53,38 @@ struct ReadFileOptions {
|
|||||||
std::size_t max_bytes{16ULL * 1024ULL * 1024ULL};
|
std::size_t max_bytes{16ULL * 1024ULL * 1024ULL};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// How much `replace_file` guarantees before reporting success.
|
||||||
|
///
|
||||||
|
/// - `atomic_visibility`: publication is a single atomic directory-entry
|
||||||
|
/// replacement. A concurrent reader opens either the complete old file or the
|
||||||
|
/// complete new file, never a partial one. This survives an application
|
||||||
|
/// (process) crash: whatever rename already happened remains. It does *not*
|
||||||
|
/// promise that the new directory entry survives a power loss without a
|
||||||
|
/// subsequent `durable_sync`.
|
||||||
|
/// - `durable_sync`: additionally flushes the staged data before publication and
|
||||||
|
/// the parent directory after it. A successful return means the new contents
|
||||||
|
/// and their directory entry have reached stable storage (subject to the
|
||||||
|
/// device honoring flush requests).
|
||||||
|
///
|
||||||
|
/// Windows x64 notes:
|
||||||
|
/// - Staging uses an exclusively created (`CREATE_NEW`, share mode 0) temporary
|
||||||
|
/// file in the destination directory, so names never collide and no other
|
||||||
|
/// process can observe partial contents.
|
||||||
|
/// - Publication uses `MoveFileExW(MOVEFILE_REPLACE_EXISTING)`. On NTFS this is
|
||||||
|
/// one atomic directory-entry replacement, so readers observe old-or-new.
|
||||||
|
/// - `durable_sync` adds `MOVEFILE_WRITE_THROUGH`, `FlushFileBuffers` on the
|
||||||
|
/// staged file, and `FlushFileBuffers` on the parent directory handle. If the
|
||||||
|
/// flush after the rename fails the result is `ReplacePhase::sync_parent`
|
||||||
|
/// with `visible_on_disk = true` and `durability_unknown = true`: the new file
|
||||||
|
/// is visible but may not survive power loss.
|
||||||
|
/// - Application crash vs power loss: a crash keeps the rename that already
|
||||||
|
/// happened (atomic_visibility is enough); power loss may lose it unless
|
||||||
|
/// durable_sync succeeded. Even durable_sync depends on the volume and its
|
||||||
|
/// filter drivers honoring flushes (NTFS does; some network/antivirus layers
|
||||||
|
/// do not).
|
||||||
|
/// - Replacing a destination that another process opened without
|
||||||
|
/// `FILE_SHARE_DELETE` fails in the rename phase and leaves the destination
|
||||||
|
/// intact.
|
||||||
enum class ReplaceDurability {
|
enum class ReplaceDurability {
|
||||||
atomic_visibility,
|
atomic_visibility,
|
||||||
durable_sync,
|
durable_sync,
|
||||||
@@ -110,7 +150,152 @@ namespace detail
|
|||||||
|
|
||||||
} // namespace detail
|
} // namespace detail
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
namespace detail
|
||||||
|
{
|
||||||
|
|
||||||
|
/// Owning wrapper for a Win32 HANDLE (INVALID_HANDLE_VALUE is the empty state).
|
||||||
|
class OwnedHandle
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
OwnedHandle() noexcept = default;
|
||||||
|
explicit OwnedHandle(HANDLE handle) noexcept : handle_(handle) {}
|
||||||
|
~OwnedHandle() noexcept { reset(); }
|
||||||
|
|
||||||
|
OwnedHandle(const OwnedHandle&) = delete;
|
||||||
|
OwnedHandle& operator=(const OwnedHandle&) = delete;
|
||||||
|
|
||||||
|
OwnedHandle(OwnedHandle&& other) noexcept
|
||||||
|
: handle_(std::exchange(other.handle_, INVALID_HANDLE_VALUE))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
OwnedHandle& operator=(OwnedHandle&& other) noexcept
|
||||||
|
{
|
||||||
|
if (this != &other) {
|
||||||
|
reset();
|
||||||
|
handle_ = std::exchange(other.handle_, INVALID_HANDLE_VALUE);
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool valid() const noexcept
|
||||||
|
{
|
||||||
|
return handle_ != INVALID_HANDLE_VALUE && handle_ != nullptr;
|
||||||
|
}
|
||||||
|
[[nodiscard]] HANDLE get() const noexcept { return handle_; }
|
||||||
|
|
||||||
|
void reset(HANDLE handle = INVALID_HANDLE_VALUE) noexcept
|
||||||
|
{
|
||||||
|
const HANDLE old = std::exchange(handle_, handle);
|
||||||
|
if (old != INVALID_HANDLE_VALUE && old != nullptr) {
|
||||||
|
(void)::CloseHandle(old);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close explicitly, reporting whether CloseHandle succeeded.
|
||||||
|
[[nodiscard]] bool close() noexcept
|
||||||
|
{
|
||||||
|
const HANDLE old = std::exchange(handle_, INVALID_HANDLE_VALUE);
|
||||||
|
if (old == INVALID_HANDLE_VALUE || old == nullptr) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return ::CloseHandle(old) != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
HANDLE handle_{INVALID_HANDLE_VALUE};
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] inline std::string win32_message(DWORD error)
|
||||||
|
{
|
||||||
|
std::array<char, 512> buffer{};
|
||||||
|
const DWORD length = ::FormatMessageA(
|
||||||
|
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
|
||||||
|
nullptr,
|
||||||
|
error,
|
||||||
|
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
|
||||||
|
buffer.data(),
|
||||||
|
static_cast<DWORD>(buffer.size()),
|
||||||
|
nullptr);
|
||||||
|
std::string message = length != 0
|
||||||
|
? std::string{buffer.data(), length}
|
||||||
|
: std::string{"unknown error"};
|
||||||
|
while (!message.empty() &&
|
||||||
|
(message.back() == '\n' || message.back() == '\r' ||
|
||||||
|
message.back() == ' ' || message.back() == '.')) {
|
||||||
|
message.pop_back();
|
||||||
|
}
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] inline Void::System::SystemErrorCode
|
||||||
|
map_win32_error(DWORD error) noexcept
|
||||||
|
{
|
||||||
|
switch (error) {
|
||||||
|
case ERROR_FILE_NOT_FOUND:
|
||||||
|
case ERROR_PATH_NOT_FOUND:
|
||||||
|
case ERROR_INVALID_DRIVE:
|
||||||
|
return Void::System::SystemErrorCode::not_found;
|
||||||
|
case ERROR_ACCESS_DENIED:
|
||||||
|
case ERROR_WRITE_PROTECT:
|
||||||
|
case ERROR_SHARING_VIOLATION:
|
||||||
|
case ERROR_LOCK_VIOLATION:
|
||||||
|
return Void::System::SystemErrorCode::permission_denied;
|
||||||
|
case ERROR_FILE_EXISTS:
|
||||||
|
case ERROR_ALREADY_EXISTS:
|
||||||
|
return Void::System::SystemErrorCode::already_exists;
|
||||||
|
case ERROR_INVALID_NAME:
|
||||||
|
case ERROR_INVALID_PARAMETER:
|
||||||
|
case ERROR_BAD_PATHNAME:
|
||||||
|
case ERROR_FILENAME_EXCED_RANGE:
|
||||||
|
return Void::System::SystemErrorCode::invalid_argument;
|
||||||
|
case ERROR_DISK_FULL:
|
||||||
|
case ERROR_HANDLE_DISK_FULL:
|
||||||
|
return Void::System::SystemErrorCode::limit_exceeded;
|
||||||
|
case ERROR_NOT_SUPPORTED:
|
||||||
|
case ERROR_CALL_NOT_IMPLEMENTED:
|
||||||
|
case ERROR_INVALID_FUNCTION:
|
||||||
|
return Void::System::SystemErrorCode::unsupported;
|
||||||
|
case ERROR_BUSY:
|
||||||
|
case ERROR_RETRY:
|
||||||
|
return Void::System::SystemErrorCode::busy;
|
||||||
|
case ERROR_OPERATION_ABORTED:
|
||||||
|
return Void::System::SystemErrorCode::cancelled;
|
||||||
|
case ERROR_TIMEOUT:
|
||||||
|
return Void::System::SystemErrorCode::timed_out;
|
||||||
|
case ERROR_NOT_ENOUGH_MEMORY:
|
||||||
|
case ERROR_OUTOFMEMORY:
|
||||||
|
return Void::System::SystemErrorCode::unavailable;
|
||||||
|
default:
|
||||||
|
return Void::System::SystemErrorCode::io_error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] inline Void::Result::Error make_win32_error(
|
||||||
|
Void::System::SystemErrorCode code, std::string_view what, DWORD error)
|
||||||
|
{
|
||||||
|
return Void::System::make_system_error(
|
||||||
|
code,
|
||||||
|
std::format("{} (win32={}: {})", what, error, win32_message(error)));
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace detail
|
||||||
|
#endif
|
||||||
|
|
||||||
/// Read up to `options.max_bytes` from `path` cleanly with typed errors.
|
/// Read up to `options.max_bytes` from `path` cleanly with typed errors.
|
||||||
|
///
|
||||||
|
/// The file is opened once and read through that single handle. The size is
|
||||||
|
/// checked before allocation and every chunk is checked again while reading,
|
||||||
|
/// so a file that grows after the initial size check still fails with
|
||||||
|
/// `limit_exceeded` and never returns partial contents.
|
||||||
|
///
|
||||||
|
/// Sharing: POSIX opens read-only; Windows opens with
|
||||||
|
/// `FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE`, so another process
|
||||||
|
/// may append, rename or replace the path while a background read is pending.
|
||||||
|
/// The read continues from the already opened handle and sees one coherent
|
||||||
|
/// version of the file (the one that was opened), not a mixture with the
|
||||||
|
/// replacement. On both platforms the path is resolved once at open time.
|
||||||
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
|
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
|
||||||
read_file_bounded(const std::filesystem::path& path,
|
read_file_bounded(const std::filesystem::path& path,
|
||||||
ReadFileOptions options = {})
|
ReadFileOptions options = {})
|
||||||
@@ -177,11 +362,73 @@ namespace detail
|
|||||||
content.size());
|
content.size());
|
||||||
return content;
|
return content;
|
||||||
#else
|
#else
|
||||||
(void)path;
|
const HANDLE raw = ::CreateFileW(path.c_str(),
|
||||||
(void)options;
|
GENERIC_READ,
|
||||||
return std::unexpected{Void::System::make_system_error(
|
FILE_SHARE_READ | FILE_SHARE_WRITE |
|
||||||
Void::System::SystemErrorCode::unsupported,
|
FILE_SHARE_DELETE,
|
||||||
"FileSystem::read_file: unsupported platform")};
|
nullptr,
|
||||||
|
OPEN_EXISTING,
|
||||||
|
FILE_ATTRIBUTE_NORMAL,
|
||||||
|
nullptr);
|
||||||
|
if (raw == INVALID_HANDLE_VALUE) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
Void::Log::warn(
|
||||||
|
"FileSystem", "read_file: cannot open '{}'", path.string());
|
||||||
|
return std::unexpected{detail::make_win32_error(
|
||||||
|
detail::map_win32_error(err),
|
||||||
|
std::format("FileSystem::read_file: cannot open '{}'",
|
||||||
|
path.string()),
|
||||||
|
err)};
|
||||||
|
}
|
||||||
|
detail::OwnedHandle handle{raw};
|
||||||
|
|
||||||
|
LARGE_INTEGER size{};
|
||||||
|
if (::GetFileSizeEx(handle.get(), &size) != 0 && size.QuadPart >= 0 &&
|
||||||
|
static_cast<std::uint64_t>(size.QuadPart) > options.max_bytes) {
|
||||||
|
return std::unexpected{Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::limit_exceeded,
|
||||||
|
std::format("FileSystem::read_file: '{}' ({} bytes) exceeds limit ({})",
|
||||||
|
path.string(),
|
||||||
|
static_cast<std::uint64_t>(size.QuadPart),
|
||||||
|
options.max_bytes))};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string content;
|
||||||
|
std::array<char, 8192> buffer{};
|
||||||
|
for (;;) {
|
||||||
|
DWORD read = 0;
|
||||||
|
if (::ReadFile(handle.get(),
|
||||||
|
buffer.data(),
|
||||||
|
static_cast<DWORD>(buffer.size()),
|
||||||
|
&read,
|
||||||
|
nullptr) == 0) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
Void::Log::warn(
|
||||||
|
"FileSystem", "read_file: I/O error reading '{}'", path.string());
|
||||||
|
return std::unexpected{detail::make_win32_error(
|
||||||
|
detail::map_win32_error(err),
|
||||||
|
std::format("FileSystem::read_file: I/O error reading '{}'",
|
||||||
|
path.string()),
|
||||||
|
err)};
|
||||||
|
}
|
||||||
|
if (read == 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const auto count = static_cast<std::size_t>(read);
|
||||||
|
if (count > options.max_bytes - content.size()) {
|
||||||
|
return std::unexpected{Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::limit_exceeded,
|
||||||
|
std::format("FileSystem::read_file: '{}' exceeded limit ({})",
|
||||||
|
path.string(),
|
||||||
|
options.max_bytes))};
|
||||||
|
}
|
||||||
|
content.append(buffer.data(), count);
|
||||||
|
}
|
||||||
|
Void::Log::debug("FileSystem",
|
||||||
|
"read_file: '{}' ({} bytes)",
|
||||||
|
path.string(),
|
||||||
|
content.size());
|
||||||
|
return content;
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -233,11 +480,58 @@ namespace detail
|
|||||||
}
|
}
|
||||||
return guard.close();
|
return guard.close();
|
||||||
#else
|
#else
|
||||||
(void)path;
|
const HANDLE raw = ::CreateFileW(path.c_str(),
|
||||||
(void)content;
|
GENERIC_WRITE,
|
||||||
return std::unexpected{Void::System::make_system_error(
|
FILE_SHARE_READ | FILE_SHARE_WRITE |
|
||||||
Void::System::SystemErrorCode::unsupported,
|
FILE_SHARE_DELETE,
|
||||||
"FileSystem::write_file: unsupported platform")};
|
nullptr,
|
||||||
|
CREATE_ALWAYS,
|
||||||
|
FILE_ATTRIBUTE_NORMAL,
|
||||||
|
nullptr);
|
||||||
|
if (raw == INVALID_HANDLE_VALUE) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
Void::Log::warn(
|
||||||
|
"FileSystem", "write_file: cannot open '{}'", path.string());
|
||||||
|
return std::unexpected{detail::make_win32_error(
|
||||||
|
detail::map_win32_error(err),
|
||||||
|
std::format("FileSystem::write_file: cannot open '{}'",
|
||||||
|
path.string()),
|
||||||
|
err)};
|
||||||
|
}
|
||||||
|
detail::OwnedHandle handle{raw};
|
||||||
|
|
||||||
|
std::size_t offset = 0;
|
||||||
|
while (offset < content.size()) {
|
||||||
|
const auto remaining = content.size() - offset;
|
||||||
|
constexpr std::size_t kMaxChunk = 0x4000'0000;
|
||||||
|
const DWORD chunk = static_cast<DWORD>(
|
||||||
|
remaining < kMaxChunk ? remaining : kMaxChunk);
|
||||||
|
DWORD written = 0;
|
||||||
|
if (::WriteFile(handle.get(),
|
||||||
|
content.data() + offset,
|
||||||
|
chunk,
|
||||||
|
&written,
|
||||||
|
nullptr) == 0) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
Void::Log::warn(
|
||||||
|
"FileSystem", "write_file: I/O error writing '{}'", path.string());
|
||||||
|
return std::unexpected{detail::make_win32_error(
|
||||||
|
detail::map_win32_error(err),
|
||||||
|
std::format("FileSystem::write_file: I/O error writing '{}'",
|
||||||
|
path.string()),
|
||||||
|
err)};
|
||||||
|
}
|
||||||
|
offset += written;
|
||||||
|
}
|
||||||
|
if (!handle.close()) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
return std::unexpected{detail::make_win32_error(
|
||||||
|
detail::map_win32_error(err),
|
||||||
|
std::format("FileSystem::write_file: close failed for '{}'",
|
||||||
|
path.string()),
|
||||||
|
err)};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -469,16 +763,247 @@ namespace detail
|
|||||||
bytes.size());
|
bytes.size());
|
||||||
return {};
|
return {};
|
||||||
#else
|
#else
|
||||||
(void)path;
|
auto check_fault = [&](ReplacePhase phase,
|
||||||
(void)bytes;
|
bool visible,
|
||||||
(void)options;
|
bool unknown) -> std::optional<ReplaceFailure> {
|
||||||
return std::unexpected{ReplaceFailure{
|
if (options.fault_hook) {
|
||||||
Void::System::make_system_error(
|
if (const auto injected = options.fault_hook(phase)) {
|
||||||
Void::System::SystemErrorCode::unsupported,
|
return ReplaceFailure{
|
||||||
"FileSystem::replace_file: unsupported platform"),
|
Void::System::make_system_error(
|
||||||
ReplacePhase::validation,
|
unknown
|
||||||
false,
|
? Void::System::SystemErrorCode::durability_unknown
|
||||||
false}};
|
: Void::System::map_errno_to_system_code(*injected),
|
||||||
|
std::format("FileSystem::replace_file: injected fault for '{}'",
|
||||||
|
path.string()),
|
||||||
|
*injected),
|
||||||
|
phase,
|
||||||
|
visible,
|
||||||
|
unknown};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (auto f = check_fault(ReplacePhase::validation, false, false)) {
|
||||||
|
return std::unexpected{std::move(*f)};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (path.empty() || !path.has_filename()) {
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"FileSystem::replace_file: empty path or missing filename"),
|
||||||
|
ReplacePhase::validation,
|
||||||
|
false,
|
||||||
|
false}};
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::filesystem::path parent =
|
||||||
|
path.parent_path().empty() ? std::filesystem::path{"."}
|
||||||
|
: path.parent_path();
|
||||||
|
const std::wstring target_name = path.filename().wstring();
|
||||||
|
if (target_name == L"." || target_name == L"..") {
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"FileSystem::replace_file: invalid target filename"),
|
||||||
|
ReplacePhase::validation,
|
||||||
|
false,
|
||||||
|
false}};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (auto f = check_fault(ReplacePhase::create_stage, false, false)) {
|
||||||
|
return std::unexpected{std::move(*f)};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::filesystem::path temp_path;
|
||||||
|
detail::OwnedHandle temp_handle;
|
||||||
|
DWORD last_err = 0;
|
||||||
|
for (int attempt = 0; attempt < 32; ++attempt) {
|
||||||
|
const auto entropy = detail::next_temp_entropy();
|
||||||
|
const std::string tail = std::format("{:016x}", entropy);
|
||||||
|
std::wstring name = L".";
|
||||||
|
name += target_name;
|
||||||
|
name += L".void_tmp_";
|
||||||
|
name.append(tail.begin(), tail.end());
|
||||||
|
temp_path = parent / name;
|
||||||
|
const HANDLE raw = ::CreateFileW(temp_path.c_str(),
|
||||||
|
GENERIC_WRITE,
|
||||||
|
0,
|
||||||
|
nullptr,
|
||||||
|
CREATE_NEW,
|
||||||
|
FILE_ATTRIBUTE_NORMAL,
|
||||||
|
nullptr);
|
||||||
|
if (raw != INVALID_HANDLE_VALUE) {
|
||||||
|
temp_handle.reset(raw);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
last_err = ::GetLastError();
|
||||||
|
if (last_err != ERROR_FILE_EXISTS && last_err != ERROR_ALREADY_EXISTS) {
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
detail::make_win32_error(
|
||||||
|
detail::map_win32_error(last_err),
|
||||||
|
std::format(
|
||||||
|
"FileSystem::replace_file: cannot create temp in '{}'",
|
||||||
|
parent.string()),
|
||||||
|
last_err),
|
||||||
|
ReplacePhase::create_stage,
|
||||||
|
false,
|
||||||
|
false}};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!temp_handle.valid()) {
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::already_exists,
|
||||||
|
"FileSystem::replace_file: exhausted temp names",
|
||||||
|
static_cast<int>(last_err)),
|
||||||
|
ReplacePhase::create_stage,
|
||||||
|
false,
|
||||||
|
false}};
|
||||||
|
}
|
||||||
|
|
||||||
|
bool cleanup_temp = true;
|
||||||
|
struct TempCleanup {
|
||||||
|
const std::filesystem::path* path{nullptr};
|
||||||
|
bool* active{nullptr};
|
||||||
|
~TempCleanup() noexcept
|
||||||
|
{
|
||||||
|
if (active != nullptr && *active && path != nullptr) {
|
||||||
|
(void)::DeleteFileW(path->c_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} temp_guard{&temp_path, &cleanup_temp};
|
||||||
|
|
||||||
|
if (auto f = check_fault(ReplacePhase::write_stage, false, false)) {
|
||||||
|
return std::unexpected{std::move(*f)};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t offset = 0;
|
||||||
|
while (offset < bytes.size()) {
|
||||||
|
const auto remaining = bytes.size() - offset;
|
||||||
|
constexpr std::size_t kMaxChunk = 0x4000'0000;
|
||||||
|
const DWORD chunk = static_cast<DWORD>(
|
||||||
|
remaining < kMaxChunk ? remaining : kMaxChunk);
|
||||||
|
DWORD written = 0;
|
||||||
|
if (::WriteFile(temp_handle.get(),
|
||||||
|
bytes.data() + offset,
|
||||||
|
chunk,
|
||||||
|
&written,
|
||||||
|
nullptr) == 0) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
detail::make_win32_error(
|
||||||
|
detail::map_win32_error(err),
|
||||||
|
std::format(
|
||||||
|
"FileSystem::replace_file: write failed for '{}'",
|
||||||
|
path.string()),
|
||||||
|
err),
|
||||||
|
ReplacePhase::write_stage,
|
||||||
|
false,
|
||||||
|
false}};
|
||||||
|
}
|
||||||
|
offset += written;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.durability == ReplaceDurability::durable_sync) {
|
||||||
|
if (auto f = check_fault(ReplacePhase::sync_stage, false, false)) {
|
||||||
|
return std::unexpected{std::move(*f)};
|
||||||
|
}
|
||||||
|
if (::FlushFileBuffers(temp_handle.get()) == 0) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
detail::make_win32_error(
|
||||||
|
Void::System::SystemErrorCode::sync_failed,
|
||||||
|
std::format(
|
||||||
|
"FileSystem::replace_file: stage flush failed for '{}'",
|
||||||
|
path.string()),
|
||||||
|
err),
|
||||||
|
ReplacePhase::sync_stage,
|
||||||
|
false,
|
||||||
|
false}};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!temp_handle.close()) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
detail::make_win32_error(
|
||||||
|
detail::map_win32_error(err),
|
||||||
|
std::format(
|
||||||
|
"FileSystem::replace_file: close failed for '{}'",
|
||||||
|
path.string()),
|
||||||
|
err),
|
||||||
|
ReplacePhase::write_stage,
|
||||||
|
false,
|
||||||
|
false}};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (auto f = check_fault(ReplacePhase::rename, false, false)) {
|
||||||
|
return std::unexpected{std::move(*f)};
|
||||||
|
}
|
||||||
|
|
||||||
|
DWORD move_flags = MOVEFILE_REPLACE_EXISTING;
|
||||||
|
if (options.durability == ReplaceDurability::durable_sync) {
|
||||||
|
move_flags |= MOVEFILE_WRITE_THROUGH;
|
||||||
|
}
|
||||||
|
if (::MoveFileExW(temp_path.c_str(), path.c_str(), move_flags) == 0) {
|
||||||
|
const DWORD err = ::GetLastError();
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
detail::make_win32_error(
|
||||||
|
detail::map_win32_error(err),
|
||||||
|
std::format("FileSystem::replace_file: rename failed for '{}'",
|
||||||
|
path.string()),
|
||||||
|
err),
|
||||||
|
ReplacePhase::rename,
|
||||||
|
false,
|
||||||
|
false}};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rename succeeded: target is now visible on disk; never delete target!
|
||||||
|
cleanup_temp = false;
|
||||||
|
|
||||||
|
if (options.durability == ReplaceDurability::durable_sync) {
|
||||||
|
if (auto f = check_fault(ReplacePhase::sync_parent, true, true)) {
|
||||||
|
return std::unexpected{std::move(*f)};
|
||||||
|
}
|
||||||
|
bool flushed = false;
|
||||||
|
DWORD err = 0;
|
||||||
|
const HANDLE dir_raw = ::CreateFileW(parent.c_str(),
|
||||||
|
GENERIC_READ,
|
||||||
|
FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||||
|
nullptr,
|
||||||
|
OPEN_EXISTING,
|
||||||
|
FILE_FLAG_BACKUP_SEMANTICS,
|
||||||
|
nullptr);
|
||||||
|
if (dir_raw != INVALID_HANDLE_VALUE) {
|
||||||
|
detail::OwnedHandle dir_handle{dir_raw};
|
||||||
|
flushed = ::FlushFileBuffers(dir_handle.get()) != 0;
|
||||||
|
if (!flushed) {
|
||||||
|
err = ::GetLastError();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
err = ::GetLastError();
|
||||||
|
}
|
||||||
|
if (!flushed) {
|
||||||
|
return std::unexpected{ReplaceFailure{
|
||||||
|
detail::make_win32_error(
|
||||||
|
Void::System::SystemErrorCode::durability_unknown,
|
||||||
|
std::format(
|
||||||
|
"FileSystem::replace_file: parent dir flush failed after rename for '{}'",
|
||||||
|
path.string()),
|
||||||
|
err),
|
||||||
|
ReplacePhase::sync_parent,
|
||||||
|
true,
|
||||||
|
true}};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Log::debug("FileSystem",
|
||||||
|
"replace_file: '{}' committed ({} bytes)",
|
||||||
|
path.string(),
|
||||||
|
bytes.size());
|
||||||
|
return {};
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,20 +4,36 @@
|
|||||||
#include <Void/Functional/Result.hpp>
|
#include <Void/Functional/Result.hpp>
|
||||||
#include <Void/System/Types.hpp>
|
#include <Void/System/Types.hpp>
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
|
#include <span>
|
||||||
#include <stop_token>
|
#include <stop_token>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
#include <memory>
|
||||||
|
#endif
|
||||||
|
|
||||||
namespace Void::Process
|
namespace Void::Process
|
||||||
{
|
{
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
namespace Detail
|
||||||
|
{
|
||||||
|
/// Opaque owner of the native Windows process, job and pipe state. Defined by
|
||||||
|
/// the System module implementation; it is never an integer descriptor.
|
||||||
|
struct WindowsProcess;
|
||||||
|
struct ChildAccess;
|
||||||
|
} // namespace Detail
|
||||||
|
#endif
|
||||||
|
|
||||||
inline constexpr std::size_t kMaxSpawnInputBytes = 256ULL * 1024ULL;
|
inline constexpr std::size_t kMaxSpawnInputBytes = 256ULL * 1024ULL;
|
||||||
inline constexpr std::size_t kDefaultMaxStdoutBytes = 1024ULL * 1024ULL;
|
inline constexpr std::size_t kDefaultMaxStdoutBytes = 1024ULL * 1024ULL;
|
||||||
inline constexpr std::size_t kDefaultMaxStderrBytes = 1024ULL * 1024ULL;
|
inline constexpr std::size_t kDefaultMaxStderrBytes = 1024ULL * 1024ULL;
|
||||||
@@ -98,7 +114,7 @@ struct CommunicateResult {
|
|||||||
class Child
|
class Child
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
Child() noexcept = default;
|
Child() noexcept;
|
||||||
Child(long long pid,
|
Child(long long pid,
|
||||||
long long pgid,
|
long long pgid,
|
||||||
bool owns_process_group,
|
bool owns_process_group,
|
||||||
@@ -155,12 +171,172 @@ private:
|
|||||||
Void::System::OwnedFd stderr_{};
|
Void::System::OwnedFd stderr_{};
|
||||||
std::chrono::milliseconds kill_grace_{std::chrono::milliseconds{2000}};
|
std::chrono::milliseconds kill_grace_{std::chrono::milliseconds{2000}};
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
std::unique_ptr<Detail::WindowsProcess> windows_;
|
||||||
|
friend struct Detail::ChildAccess;
|
||||||
|
friend class BinarySession;
|
||||||
|
#endif
|
||||||
|
|
||||||
void reset_and_reap() noexcept;
|
void reset_and_reap() noexcept;
|
||||||
};
|
};
|
||||||
|
|
||||||
[[nodiscard]] Void::Result::Result<Child, Void::Result::Error>
|
[[nodiscard]] Void::Result::Result<Child, Void::Result::Error>
|
||||||
spawn(const SpawnOptions& options);
|
spawn(const SpawnOptions& options);
|
||||||
|
|
||||||
|
inline constexpr std::size_t kDefaultBinaryOutputBufferBytes = 1024ULL * 1024ULL;
|
||||||
|
|
||||||
|
/// Why a BinarySession operation stopped before completing.
|
||||||
|
enum class BinaryFailureCode : std::int32_t {
|
||||||
|
none = 0,
|
||||||
|
timeout = 1,
|
||||||
|
cancelled = 2,
|
||||||
|
truncated = 3,
|
||||||
|
closed = 4,
|
||||||
|
buffer_full = 5,
|
||||||
|
io_error = 6,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Successful (possibly partial) BinarySession operation.
|
||||||
|
struct BinaryTransfer {
|
||||||
|
std::size_t bytes{0};
|
||||||
|
bool eof{false}; ///< the stream reached end-of-file
|
||||||
|
bool exited{false}; ///< the child exit status is known (see status)
|
||||||
|
bool truncated{false}; ///< output was discarded because a buffer was full
|
||||||
|
ExitStatus status{};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Structured BinarySession failure. `bytes_transferred` lets callers resume
|
||||||
|
/// from the exact offset that was not transferred.
|
||||||
|
struct BinaryError {
|
||||||
|
std::size_t bytes_transferred{0};
|
||||||
|
bool eof{false};
|
||||||
|
BinaryFailureCode failure{BinaryFailureCode::io_error};
|
||||||
|
Void::Result::Error error{};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct BinarySessionOptions {
|
||||||
|
std::size_t max_stdout_buffer{kDefaultBinaryOutputBufferBytes};
|
||||||
|
std::size_t max_stderr_buffer{kDefaultBinaryOutputBufferBytes};
|
||||||
|
/// When true, output beyond a buffer cap is drained and discarded (marked
|
||||||
|
/// truncated) instead of applying backpressure to the child.
|
||||||
|
bool truncate_output_on_overflow{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Incremental binary I/O session over a spawned child's pipes.
|
||||||
|
///
|
||||||
|
/// Each call drives both output directions: while stdout is being read,
|
||||||
|
/// stderr is drained into its bounded buffer (and vice versa), so a child
|
||||||
|
/// flooding one stream cannot block the other as long as buffering allows.
|
||||||
|
/// Pipes are non-blocking; operations are poll-driven and bounded by an
|
||||||
|
/// optional timeout and a stop token (or cancel()).
|
||||||
|
class BinarySession
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
BinarySession() noexcept = default;
|
||||||
|
explicit BinarySession(Child child, BinarySessionOptions options = {});
|
||||||
|
~BinarySession() noexcept;
|
||||||
|
|
||||||
|
BinarySession(const BinarySession&) = delete;
|
||||||
|
BinarySession& operator=(const BinarySession&) = delete;
|
||||||
|
BinarySession(BinarySession&& other) noexcept;
|
||||||
|
BinarySession& operator=(BinarySession&& other) noexcept;
|
||||||
|
|
||||||
|
[[nodiscard]] static Void::Result::Result<BinarySession, Void::Result::Error>
|
||||||
|
spawn(const SpawnOptions& options, BinarySessionOptions session_options = {});
|
||||||
|
|
||||||
|
[[nodiscard]] bool valid() const noexcept;
|
||||||
|
[[nodiscard]] Child& child() noexcept { return child_; }
|
||||||
|
[[nodiscard]] const Child& child() const noexcept { return child_; }
|
||||||
|
[[nodiscard]] long long pid() const noexcept { return child_.pid(); }
|
||||||
|
|
||||||
|
/// Writes as much of `data` as the child accepts. Returns the transferred
|
||||||
|
/// count; on timeout/cancellation/closure the BinaryError reports it.
|
||||||
|
[[nodiscard]] Void::Result::Result<BinaryTransfer, BinaryError> write_stdin(
|
||||||
|
std::span<const std::byte> data,
|
||||||
|
std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
|
||||||
|
std::stop_token stop = {});
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<BinaryTransfer, BinaryError> read_stdout(
|
||||||
|
std::span<std::byte> out,
|
||||||
|
std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
|
||||||
|
std::stop_token stop = {});
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<BinaryTransfer, BinaryError> read_stderr(
|
||||||
|
std::span<std::byte> out,
|
||||||
|
std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
|
||||||
|
std::stop_token stop = {});
|
||||||
|
|
||||||
|
/// Closes the child's stdin (flush-free half-close). Idempotent.
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> close_stdin();
|
||||||
|
|
||||||
|
/// Waits for the child while continuing to drain both output streams.
|
||||||
|
[[nodiscard]] Void::Result::Result<ExitStatus, Void::Result::Error> wait(
|
||||||
|
std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
|
||||||
|
std::stop_token stop = {});
|
||||||
|
|
||||||
|
/// Terminates the child (and its process group) with the configured grace.
|
||||||
|
[[nodiscard]] Void::Result::Result<ExitStatus, Void::Result::Error> terminate(
|
||||||
|
std::chrono::milliseconds grace = std::chrono::milliseconds{-1});
|
||||||
|
|
||||||
|
/// Requests cancellation of the next/current operation. Safe to call from
|
||||||
|
/// another thread.
|
||||||
|
void cancel() noexcept { cancelled_.store(true, std::memory_order_release); }
|
||||||
|
[[nodiscard]] bool cancelled() const noexcept
|
||||||
|
{
|
||||||
|
return cancelled_.load(std::memory_order_acquire);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool stdout_eof() const noexcept { return stdout_eof_; }
|
||||||
|
[[nodiscard]] bool stderr_eof() const noexcept { return stderr_eof_; }
|
||||||
|
[[nodiscard]] bool stdout_truncated() const noexcept { return stdout_truncated_; }
|
||||||
|
[[nodiscard]] bool stderr_truncated() const noexcept { return stderr_truncated_; }
|
||||||
|
[[nodiscard]] std::size_t buffered_stdout() const noexcept
|
||||||
|
{
|
||||||
|
return stdout_buffer_.size() - stdout_offset_;
|
||||||
|
}
|
||||||
|
[[nodiscard]] std::size_t buffered_stderr() const noexcept
|
||||||
|
{
|
||||||
|
return stderr_buffer_.size() - stderr_offset_;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
struct PollFill {
|
||||||
|
bool stdin_broken{false};
|
||||||
|
bool idle{false};
|
||||||
|
BinaryFailureCode failure{BinaryFailureCode::none};
|
||||||
|
Void::Result::Error error{};
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] PollFill poll_fill(int timeout_ms,
|
||||||
|
std::span<const std::byte> stdin_data,
|
||||||
|
std::size_t& stdin_written,
|
||||||
|
bool discard_on_full);
|
||||||
|
[[nodiscard]] Void::Result::Result<BinaryTransfer, BinaryError> read_stream(
|
||||||
|
bool is_stdout,
|
||||||
|
std::span<std::byte> out,
|
||||||
|
std::chrono::milliseconds timeout,
|
||||||
|
std::stop_token stop);
|
||||||
|
void note_exit() noexcept;
|
||||||
|
|
||||||
|
Child child_{};
|
||||||
|
Void::System::OwnedFd stdin_{};
|
||||||
|
Void::System::OwnedFd stdout_{};
|
||||||
|
Void::System::OwnedFd stderr_{};
|
||||||
|
std::vector<std::byte> stdout_buffer_{};
|
||||||
|
std::size_t stdout_offset_{0};
|
||||||
|
std::vector<std::byte> stderr_buffer_{};
|
||||||
|
std::size_t stderr_offset_{0};
|
||||||
|
bool stdout_eof_{true};
|
||||||
|
bool stderr_eof_{true};
|
||||||
|
bool stdin_closed_{true};
|
||||||
|
bool stdout_truncated_{false};
|
||||||
|
bool stderr_truncated_{false};
|
||||||
|
BinarySessionOptions options_{};
|
||||||
|
std::atomic<bool> cancelled_{false};
|
||||||
|
ExitStatus status_{};
|
||||||
|
bool reaped_{false};
|
||||||
|
};
|
||||||
|
|
||||||
[[nodiscard]] Void::Result::Result<CommunicateResult, Void::Result::Error>
|
[[nodiscard]] Void::Result::Result<CommunicateResult, Void::Result::Error>
|
||||||
communicate_blocking(Child& child,
|
communicate_blocking(Child& child,
|
||||||
std::string_view stdin_data = {},
|
std::string_view stdin_data = {},
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <concepts>
|
||||||
|
#include <condition_variable>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <functional>
|
||||||
|
#include <mutex>
|
||||||
|
#include <type_traits>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::Testing
|
||||||
|
{
|
||||||
|
|
||||||
|
/// Small synchronization gate for deterministic completion-order tests.
|
||||||
|
///
|
||||||
|
/// Participants call `arrive()` after a computation returned and can then
|
||||||
|
/// block in `wait_release()`. The test thread can wait for a number of
|
||||||
|
/// arrivals (`wait_for`) and release blocked participants explicitly, on
|
||||||
|
/// failure, or after a timeout. All waits are bounded.
|
||||||
|
class CompletionGate
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
using Clock = std::chrono::steady_clock;
|
||||||
|
|
||||||
|
CompletionGate() = default;
|
||||||
|
|
||||||
|
CompletionGate(const CompletionGate&) = delete;
|
||||||
|
CompletionGate& operator=(const CompletionGate&) = delete;
|
||||||
|
|
||||||
|
/// Record one completed invocation and wake `wait_for` waiters.
|
||||||
|
void arrive() noexcept
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
++arrivals_;
|
||||||
|
condition_.notify_all();
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::size_t arrivals() const noexcept
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
return arrivals_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wait until at least `count` invocations arrived. Returns false on
|
||||||
|
/// timeout.
|
||||||
|
[[nodiscard]] bool wait_for(std::size_t count,
|
||||||
|
std::chrono::milliseconds timeout)
|
||||||
|
{
|
||||||
|
std::unique_lock lock{mutex_};
|
||||||
|
return condition_.wait_for(
|
||||||
|
lock, timeout, [&] { return arrivals_ >= count; });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unblock every current and future `wait_release` caller.
|
||||||
|
void release() noexcept
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
released_ = true;
|
||||||
|
condition_.notify_all();
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool released() const noexcept
|
||||||
|
{
|
||||||
|
std::lock_guard lock{mutex_};
|
||||||
|
return released_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Block until `release()`; returns false on timeout so a failing test
|
||||||
|
/// can still finish.
|
||||||
|
[[nodiscard]] bool wait_release(std::chrono::milliseconds timeout)
|
||||||
|
{
|
||||||
|
std::unique_lock lock{mutex_};
|
||||||
|
return condition_.wait_for(lock, timeout,
|
||||||
|
[&] { return released_; });
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
mutable std::mutex mutex_;
|
||||||
|
std::condition_variable condition_;
|
||||||
|
std::size_t arrivals_{0};
|
||||||
|
bool released_{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Callable adapter that runs an observer exactly once after a successful
|
||||||
|
/// invocation returns, and before the enclosing future is fulfilled.
|
||||||
|
///
|
||||||
|
/// The observer is *not* called when the callable throws; the exception is
|
||||||
|
/// forwarded unchanged. Void, value, reference and move-only results are
|
||||||
|
/// preserved. The observer itself must not throw; an exception from it
|
||||||
|
/// propagates instead of the result.
|
||||||
|
template <typename Fn, typename Observer> class ObservedCallable
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
template <typename F, typename O>
|
||||||
|
ObservedCallable(F&& fn, O&& observer)
|
||||||
|
: fn_(std::forward<F>(fn))
|
||||||
|
, observer_(std::forward<O>(observer))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename... Args>
|
||||||
|
requires std::invocable<Fn&, Args...>
|
||||||
|
decltype(auto) operator()(Args&&... args)
|
||||||
|
{
|
||||||
|
using Result = std::invoke_result_t<Fn&, Args...>;
|
||||||
|
if constexpr (std::is_void_v<Result>) {
|
||||||
|
std::invoke(fn_, std::forward<Args>(args)...);
|
||||||
|
std::invoke(observer_);
|
||||||
|
return;
|
||||||
|
} else if constexpr (std::is_reference_v<Result>) {
|
||||||
|
Result result =
|
||||||
|
std::invoke(fn_, std::forward<Args>(args)...);
|
||||||
|
std::invoke(observer_);
|
||||||
|
return std::forward<Result>(result);
|
||||||
|
} else {
|
||||||
|
Result result =
|
||||||
|
std::invoke(fn_, std::forward<Args>(args)...);
|
||||||
|
std::invoke(observer_);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
Fn fn_;
|
||||||
|
Observer observer_;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename Fn, typename Observer>
|
||||||
|
[[nodiscard]] auto observe_completion(Fn&& fn, Observer&& observer)
|
||||||
|
{
|
||||||
|
return ObservedCallable<std::decay_t<Fn>, std::decay_t<Observer>>(
|
||||||
|
std::forward<Fn>(fn), std::forward<Observer>(observer));
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Testing
|
||||||
@@ -60,6 +60,9 @@ namespace Void::Testing
|
|||||||
std::vector<std::string> tags;
|
std::vector<std::string> tags;
|
||||||
bool assertions_truncated{false};
|
bool assertions_truncated{false};
|
||||||
std::size_t dropped_assertions{0};
|
std::size_t dropped_assertions{0};
|
||||||
|
// Counted at record time, so failures beyond the bounded assertion
|
||||||
|
// retention still determine the test outcome.
|
||||||
|
std::size_t failed_assertions{0};
|
||||||
std::size_t diagnostic_bytes{0};
|
std::size_t diagnostic_bytes{0};
|
||||||
std::string cleanup_error;
|
std::string cleanup_error;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <Void/Core/Meta.hpp>
|
#include <Void/Core/Meta.hpp>
|
||||||
#include <Void/Testing/Annotations.hpp>
|
|
||||||
#include <Void/Testing/Config.hpp>
|
#include <Void/Testing/Config.hpp>
|
||||||
#include <Void/Testing/Detail/Registry.hpp>
|
#include <Void/Testing/Detail/Registry.hpp>
|
||||||
#include <Void/Testing/Test.hpp>
|
#include <Void/Testing/Test.hpp>
|
||||||
@@ -11,6 +10,7 @@
|
|||||||
|
|
||||||
#if __has_include(<meta>)
|
#if __has_include(<meta>)
|
||||||
#include <meta>
|
#include <meta>
|
||||||
|
#include <Void/Testing/Annotations.hpp>
|
||||||
#define VOID_TESTING_HAS_REFLECTION 1
|
#define VOID_TESTING_HAS_REFLECTION 1
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
@@ -95,6 +95,13 @@ namespace Void::Testing
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Non-capturing thunk: a template argument is a constant
|
||||||
|
/// expression, unlike a reflected member captured by a lambda.
|
||||||
|
template <meta::info M> static void run_method_thunk()
|
||||||
|
{
|
||||||
|
run_method<M>();
|
||||||
|
}
|
||||||
|
|
||||||
static std::string suite_label()
|
static std::string suite_label()
|
||||||
{
|
{
|
||||||
if constexpr (constexpr auto n =
|
if constexpr (constexpr auto n =
|
||||||
@@ -138,12 +145,17 @@ namespace Void::Testing
|
|||||||
skip_reason = std::string{s->reason.view()};
|
skip_reason = std::string{s->reason.view()};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
constexpr auto name = meta::identifier_of(m);
|
||||||
|
constexpr const char* file = loc.file_name();
|
||||||
|
constexpr int line =
|
||||||
|
static_cast<int>(loc.line());
|
||||||
|
constexpr auto run = &run_method_thunk<m>;
|
||||||
reg.add(TestCase{
|
reg.add(TestCase{
|
||||||
.run = [] { run_method<m>(); },
|
.run = run,
|
||||||
.name = std::string{meta::identifier_of(m)},
|
.name = std::string{name},
|
||||||
.suite = suite,
|
.suite = suite,
|
||||||
.file = loc.file_name(),
|
.file = file,
|
||||||
.line = static_cast<int>(loc.line()),
|
.line = line,
|
||||||
.disabled = disabled,
|
.disabled = disabled,
|
||||||
.skip_reason = std::move(skip_reason),
|
.skip_reason = std::move(skip_reason),
|
||||||
.tags = std::move(tags),
|
.tags = std::move(tags),
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <Void/TestingMock/Matcher.hpp>
|
#include <Void/TestingMock/Matcher.hpp>
|
||||||
|
#include <Void/TestingMock/MoveOnlyFunction.hpp>
|
||||||
#include <Void/TestingMock/Session.hpp>
|
#include <Void/TestingMock/Session.hpp>
|
||||||
|
|
||||||
#include <concepts>
|
#include <concepts>
|
||||||
@@ -30,7 +31,11 @@ namespace Void::TestingMock::Detail
|
|||||||
std::tuple<MatcherHolder<std::decay_t<Args>>...>;
|
std::tuple<MatcherHolder<std::decay_t<Args>>...>;
|
||||||
/// Move-only function — supports unique_ptr-capturing lambdas,
|
/// Move-only function — supports unique_ptr-capturing lambdas,
|
||||||
/// move-only arguments, and move-only return values.
|
/// move-only arguments, and move-only return values.
|
||||||
|
#if defined(__cpp_lib_move_only_function)
|
||||||
using Action = std::move_only_function<R(Args...)>;
|
using Action = std::move_only_function<R(Args...)>;
|
||||||
|
#else
|
||||||
|
using Action = MoveOnlyFunction<R(Args...)>;
|
||||||
|
#endif
|
||||||
|
|
||||||
Expectation(MatcherTuple matchers, std::source_location loc)
|
Expectation(MatcherTuple matchers, std::source_location loc)
|
||||||
: m_matchers(std::move(matchers)), m_location(loc)
|
: m_matchers(std::move(matchers)), m_location(loc)
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <concepts>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <functional>
|
||||||
|
#include <memory>
|
||||||
|
#include <type_traits>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::TestingMock::Detail
|
||||||
|
{
|
||||||
|
/// Minimal move-only type-erased callable with the subset of
|
||||||
|
/// std::move_only_function used by TestingMock. Only needed on standard
|
||||||
|
/// libraries that do not implement std::move_only_function (older libc++,
|
||||||
|
/// e.g. Emscripten).
|
||||||
|
template <typename Signature> class MoveOnlyFunction;
|
||||||
|
|
||||||
|
template <typename R, typename... Args>
|
||||||
|
class MoveOnlyFunction<R(Args...)>
|
||||||
|
{
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct Base {
|
||||||
|
virtual ~Base() = default;
|
||||||
|
virtual R invoke(Args&&... args) = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename F> struct Model final : Base {
|
||||||
|
explicit Model(F callable) : fn(std::move(callable)) {}
|
||||||
|
|
||||||
|
R invoke(Args&&... args) override
|
||||||
|
{
|
||||||
|
return std::invoke(fn, std::forward<Args>(args)...);
|
||||||
|
}
|
||||||
|
|
||||||
|
F fn;
|
||||||
|
};
|
||||||
|
|
||||||
|
public:
|
||||||
|
|
||||||
|
MoveOnlyFunction() noexcept = default;
|
||||||
|
MoveOnlyFunction(std::nullptr_t) noexcept {}
|
||||||
|
|
||||||
|
template <typename F>
|
||||||
|
requires std::invocable<F&, Args...> &&
|
||||||
|
(!std::same_as<std::remove_cvref_t<F>,
|
||||||
|
MoveOnlyFunction>)
|
||||||
|
MoveOnlyFunction(F&& callable)
|
||||||
|
: impl_(std::make_unique<Model<std::remove_cvref_t<F>>>(
|
||||||
|
std::forward<F>(callable)))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
MoveOnlyFunction(MoveOnlyFunction&&) noexcept = default;
|
||||||
|
MoveOnlyFunction& operator=(MoveOnlyFunction&&) noexcept = default;
|
||||||
|
MoveOnlyFunction(const MoveOnlyFunction&) = delete;
|
||||||
|
MoveOnlyFunction& operator=(const MoveOnlyFunction&) = delete;
|
||||||
|
|
||||||
|
[[nodiscard]] explicit operator bool() const noexcept
|
||||||
|
{
|
||||||
|
return impl_ != nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
R operator()(Args... args)
|
||||||
|
{
|
||||||
|
return impl_->invoke(std::forward<Args>(args)...);
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
std::unique_ptr<Base> impl_;
|
||||||
|
};
|
||||||
|
} // namespace Void::TestingMock::Detail
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Text/Bounded.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <optional>
|
||||||
|
#include <span>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Encoding::Base32
|
||||||
|
{
|
||||||
|
|
||||||
|
namespace Detail
|
||||||
|
{
|
||||||
|
/// RFC 4648 section 6 alphabet.
|
||||||
|
constexpr std::string_view alphabet =
|
||||||
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
||||||
|
|
||||||
|
/// Crockford alphabet: no I, L, O or U.
|
||||||
|
constexpr std::string_view alphabet_crockford =
|
||||||
|
"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
||||||
|
|
||||||
|
constexpr char to_lower_ascii(char c) noexcept
|
||||||
|
{
|
||||||
|
return (c >= 'A' && c <= 'Z') ? static_cast<char>(c + ('a' - 'A')) : c;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] constexpr std::array<std::int8_t, 256>
|
||||||
|
make_rfc_table() noexcept
|
||||||
|
{
|
||||||
|
std::array<std::int8_t, 256> t{};
|
||||||
|
t.fill(-1);
|
||||||
|
for (std::size_t i = 0; i < 32; ++i) {
|
||||||
|
const char upper = alphabet[i];
|
||||||
|
t[static_cast<unsigned char>(upper)] =
|
||||||
|
static_cast<std::int8_t>(i);
|
||||||
|
t[static_cast<unsigned char>(to_lower_ascii(upper))] =
|
||||||
|
static_cast<std::int8_t>(i);
|
||||||
|
}
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] constexpr std::array<std::int8_t, 256>
|
||||||
|
make_crockford_table() noexcept
|
||||||
|
{
|
||||||
|
std::array<std::int8_t, 256> t{};
|
||||||
|
t.fill(-1);
|
||||||
|
for (std::size_t i = 0; i < 32; ++i) {
|
||||||
|
const char upper = alphabet_crockford[i];
|
||||||
|
t[static_cast<unsigned char>(upper)] =
|
||||||
|
static_cast<std::int8_t>(i);
|
||||||
|
t[static_cast<unsigned char>(to_lower_ascii(upper))] =
|
||||||
|
static_cast<std::int8_t>(i);
|
||||||
|
}
|
||||||
|
// Crockford aliases: I and L are 1, O is 0.
|
||||||
|
for (const char c : {'I', 'i', 'L', 'l'}) {
|
||||||
|
t[static_cast<unsigned char>(c)] = 1;
|
||||||
|
}
|
||||||
|
for (const char c : {'O', 'o'}) {
|
||||||
|
t[static_cast<unsigned char>(c)] = 0;
|
||||||
|
}
|
||||||
|
// U is deliberately absent (rejected).
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Overwrite partial output before discarding it so a failed decode
|
||||||
|
/// does not leave decoded plaintext behind in freed storage.
|
||||||
|
inline void wipe(std::string& out) noexcept
|
||||||
|
{
|
||||||
|
std::fill(out.begin(), out.end(), '\0');
|
||||||
|
out.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::string encode_with(std::span<const std::byte> data,
|
||||||
|
std::string_view alpha,
|
||||||
|
bool pad)
|
||||||
|
{
|
||||||
|
std::string out;
|
||||||
|
out.reserve(((data.size() + 4) / 5) * 8);
|
||||||
|
std::uint32_t buffer = 0;
|
||||||
|
int bits = 0;
|
||||||
|
for (const std::byte raw : data) {
|
||||||
|
buffer = (buffer << 8) |
|
||||||
|
static_cast<std::uint32_t>(
|
||||||
|
static_cast<std::uint8_t>(raw));
|
||||||
|
bits += 8;
|
||||||
|
while (bits >= 5) {
|
||||||
|
bits -= 5;
|
||||||
|
out += alpha[(buffer >> bits) & 0x1FU];
|
||||||
|
}
|
||||||
|
buffer &= bits == 0 ? 0U : ((1U << bits) - 1U);
|
||||||
|
}
|
||||||
|
if (bits != 0) {
|
||||||
|
out += alpha[(buffer << (5 - bits)) & 0x1FU];
|
||||||
|
}
|
||||||
|
if (pad) {
|
||||||
|
while (out.size() % 8 != 0) {
|
||||||
|
out += '=';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::optional<std::string>
|
||||||
|
decode_with(std::string_view s,
|
||||||
|
const std::array<std::int8_t, 256>& table,
|
||||||
|
bool allow_padding,
|
||||||
|
bool skip_separators,
|
||||||
|
Void::Text::TextLimits limits)
|
||||||
|
{
|
||||||
|
if (s.size() > limits.max_input) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string out;
|
||||||
|
out.reserve((s.size() * 5) / 8);
|
||||||
|
|
||||||
|
std::uint32_t buffer = 0;
|
||||||
|
int bits = 0;
|
||||||
|
std::size_t symbols = 0;
|
||||||
|
std::size_t padding = 0;
|
||||||
|
bool saw_padding = false;
|
||||||
|
|
||||||
|
for (const char encoded : s) {
|
||||||
|
const auto character = static_cast<unsigned char>(encoded);
|
||||||
|
if (skip_separators && encoded == '-') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (allow_padding && encoded == '=') {
|
||||||
|
saw_padding = true;
|
||||||
|
++padding;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (saw_padding) {
|
||||||
|
wipe(out);
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::int8_t value = table[character];
|
||||||
|
if (value < 0) {
|
||||||
|
wipe(out);
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer = (buffer << 5) | static_cast<std::uint32_t>(value);
|
||||||
|
bits += 5;
|
||||||
|
++symbols;
|
||||||
|
if (bits >= 8) {
|
||||||
|
bits -= 8;
|
||||||
|
out += static_cast<char>((buffer >> bits) & 0xFFU);
|
||||||
|
if (out.size() > limits.max_output) {
|
||||||
|
wipe(out);
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
buffer &= bits == 0 ? 0U : ((1U << bits) - 1U);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::size_t remainder = symbols % 8;
|
||||||
|
if (remainder == 1 || remainder == 3 || remainder == 6) {
|
||||||
|
wipe(out);
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const std::size_t expected_padding =
|
||||||
|
remainder == 0 ? 0 : 8 - remainder;
|
||||||
|
if (padding != 0 && padding != expected_padding) {
|
||||||
|
wipe(out);
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
// Non-zero trailing pad bits mean the text is not canonical.
|
||||||
|
if (bits != 0 && buffer != 0) {
|
||||||
|
wipe(out);
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
} // namespace Detail
|
||||||
|
|
||||||
|
/// Encode bytes to RFC 4648 Base32 (uppercase, with padding).
|
||||||
|
[[nodiscard]] inline std::string encode(std::span<const std::byte> data)
|
||||||
|
{
|
||||||
|
return Detail::encode_with(data, Detail::alphabet, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encode bytes to RFC 4648 Base32 with an explicit padding choice.
|
||||||
|
[[nodiscard]] inline std::string encode(std::span<const std::byte> data,
|
||||||
|
bool pad)
|
||||||
|
{
|
||||||
|
return Detail::encode_with(data, Detail::alphabet, pad);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encode an unsigned-byte view without forcing callers to reinterpret
|
||||||
|
/// their binary buffers as text.
|
||||||
|
[[nodiscard]] inline std::string encode(std::span<const std::uint8_t> data)
|
||||||
|
{
|
||||||
|
return encode(std::as_bytes(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encode a string_view to RFC 4648 Base32.
|
||||||
|
[[nodiscard]] inline std::string encode(std::string_view s)
|
||||||
|
{
|
||||||
|
return encode(std::as_bytes(std::span{s.data(), s.size()}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decode RFC 4648 Base32. Accepts padded or unpadded text and is
|
||||||
|
/// case-insensitive. Returns nullopt for invalid characters, impossible
|
||||||
|
/// lengths, malformed padding, non-zero trailing bits, or limits exceeded.
|
||||||
|
[[nodiscard]] inline std::optional<std::string>
|
||||||
|
decode(std::string_view s, Void::Text::TextLimits limits = {})
|
||||||
|
{
|
||||||
|
static constexpr auto table = Detail::make_rfc_table();
|
||||||
|
return Detail::decode_with(
|
||||||
|
s, table, /*allow_padding=*/true, /*skip_separators=*/false, limits);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decode RFC 4648 Base32 into an explicitly binary buffer.
|
||||||
|
[[nodiscard]] inline std::optional<std::vector<std::byte>>
|
||||||
|
decode_bytes(std::string_view s, Void::Text::TextLimits limits = {})
|
||||||
|
{
|
||||||
|
const auto decoded = decode(s, limits);
|
||||||
|
if (!decoded) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto bytes =
|
||||||
|
std::as_bytes(std::span{decoded->data(), decoded->size()});
|
||||||
|
return std::vector<std::byte>{bytes.begin(), bytes.end()};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encode bytes to Crockford Base32 (uppercase, no padding).
|
||||||
|
[[nodiscard]] inline std::string
|
||||||
|
encode_crockford(std::span<const std::byte> data)
|
||||||
|
{
|
||||||
|
return Detail::encode_with(data, Detail::alphabet_crockford, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] inline std::string
|
||||||
|
encode_crockford(std::span<const std::uint8_t> data)
|
||||||
|
{
|
||||||
|
return encode_crockford(std::as_bytes(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] inline std::string encode_crockford(std::string_view s)
|
||||||
|
{
|
||||||
|
return encode_crockford(std::as_bytes(std::span{s.data(), s.size()}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decode Crockford Base32. Case-insensitive; I/L map to 1, O maps to 0,
|
||||||
|
/// U is rejected, and '-' separators are skipped. Returns nullopt on
|
||||||
|
/// invalid input, impossible lengths, non-zero trailing bits, or limits
|
||||||
|
/// exceeded.
|
||||||
|
[[nodiscard]] inline std::optional<std::string>
|
||||||
|
decode_crockford(std::string_view s, Void::Text::TextLimits limits = {})
|
||||||
|
{
|
||||||
|
static constexpr auto table = Detail::make_crockford_table();
|
||||||
|
return Detail::decode_with(
|
||||||
|
s, table, /*allow_padding=*/false, /*skip_separators=*/true, limits);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decode Crockford Base32 into an explicitly binary buffer.
|
||||||
|
[[nodiscard]] inline std::optional<std::vector<std::byte>>
|
||||||
|
decode_crockford_bytes(std::string_view s,
|
||||||
|
Void::Text::TextLimits limits = {})
|
||||||
|
{
|
||||||
|
const auto decoded = decode_crockford(s, limits);
|
||||||
|
if (!decoded) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto bytes =
|
||||||
|
std::as_bytes(std::span{decoded->data(), decoded->size()});
|
||||||
|
return std::vector<std::byte>{bytes.begin(), bytes.end()};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Encoding::Base32
|
||||||
|
|
||||||
|
namespace Void::Text
|
||||||
|
{
|
||||||
|
/// Encode bytes as uppercase RFC 4648 Base32. Padding is emitted by
|
||||||
|
/// default and can be disabled for unpadded forms.
|
||||||
|
[[nodiscard]] inline std::string
|
||||||
|
base32_encode(std::span<const std::byte> data, bool pad = true)
|
||||||
|
{
|
||||||
|
return Void::Encoding::Base32::encode(data, pad);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decode RFC 4648 Base32 text. Case-insensitive, accepts padded or
|
||||||
|
/// unpadded input, and rejects invalid characters, impossible lengths,
|
||||||
|
/// malformed padding and non-zero trailing bits by returning nullopt.
|
||||||
|
[[nodiscard]] inline std::optional<std::string>
|
||||||
|
base32_decode(std::string_view text, TextLimits limits = {})
|
||||||
|
{
|
||||||
|
return Void::Encoding::Base32::decode(text, limits);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decode a byte view as RFC 4648 Base32 text.
|
||||||
|
[[nodiscard]] inline std::optional<std::string>
|
||||||
|
base32_decode(std::span<const std::byte> text, TextLimits limits = {})
|
||||||
|
{
|
||||||
|
return base32_decode(
|
||||||
|
std::string_view{reinterpret_cast<const char*>(text.data()),
|
||||||
|
text.size()},
|
||||||
|
limits);
|
||||||
|
}
|
||||||
|
} // namespace Void::Text
|
||||||
+271
-69
@@ -2,10 +2,15 @@
|
|||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <expected>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
|
#include <limits>
|
||||||
#include <span>
|
#include <span>
|
||||||
|
#include <stdexcept>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
|
#include <utility>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace Void::Diff
|
namespace Void::Diff
|
||||||
@@ -21,73 +26,226 @@ struct Edit {
|
|||||||
T value;
|
T value;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ── Bounded diff controls ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
struct DiffLimits
|
||||||
|
{
|
||||||
|
// Maximum number of elements across both inputs (a.size() + b.size()).
|
||||||
|
std::size_t max_input_elements = std::numeric_limits<std::size_t>::max();
|
||||||
|
// Maximum number of input bytes for line_diff_bounded.
|
||||||
|
std::size_t max_input_bytes = std::numeric_limits<std::size_t>::max();
|
||||||
|
// Maximum bytes retained by the Myers trace (backtracking snapshots).
|
||||||
|
std::size_t max_trace_memory = std::numeric_limits<std::size_t>::max();
|
||||||
|
// Maximum number of edits in the produced script.
|
||||||
|
std::size_t max_output = std::numeric_limits<std::size_t>::max();
|
||||||
|
// Maximum work units (diagonal steps plus snake comparisons).
|
||||||
|
std::size_t max_work = std::numeric_limits<std::size_t>::max();
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class DiffFailure : std::uint8_t
|
||||||
|
{
|
||||||
|
InputTooLarge,
|
||||||
|
TraceMemoryExhausted,
|
||||||
|
OutputTooLarge,
|
||||||
|
WorkExhausted,
|
||||||
|
Cancelled,
|
||||||
|
};
|
||||||
|
|
||||||
|
namespace Detail
|
||||||
|
{
|
||||||
|
// A cancellation checkpoint is any callable returning bool. An empty
|
||||||
|
// std::function (the default) means "never cancelled".
|
||||||
|
template <typename Cancel>
|
||||||
|
[[nodiscard]] inline bool cancellation_requested(const Cancel& cancel)
|
||||||
|
{
|
||||||
|
if constexpr (requires { static_cast<bool>(cancel); }) {
|
||||||
|
if (!static_cast<bool>(cancel)) return false;
|
||||||
|
}
|
||||||
|
return static_cast<bool>(cancel());
|
||||||
|
}
|
||||||
|
} // namespace Detail
|
||||||
|
|
||||||
// ── Myers diff ────────────────────────────────────────────────────────────────
|
// ── Myers diff ────────────────────────────────────────────────────────────────
|
||||||
// Returns the shortest edit script (SES) to transform `a` into `b`.
|
// Returns the shortest edit script (SES) to transform `a` into `b`.
|
||||||
// Uses Myers' O(ND) algorithm.
|
// Uses Myers' O(ND) algorithm, with checked size arithmetic and optional
|
||||||
|
// input/trace/output/work budgets plus cancellation checkpoints.
|
||||||
|
|
||||||
|
template <typename T, typename Eq = std::equal_to<T>,
|
||||||
|
typename Cancel = std::function<bool()>>
|
||||||
|
[[nodiscard]] std::expected<std::vector<Edit<T>>, DiffFailure>
|
||||||
|
diff_bounded(std::span<const T> a, std::span<const T> b,
|
||||||
|
DiffLimits limits = {}, Eq eq = {}, Cancel&& cancelled = {})
|
||||||
|
{
|
||||||
|
using Diff = std::ptrdiff_t;
|
||||||
|
constexpr Diff kMaxDiff = std::numeric_limits<Diff>::max();
|
||||||
|
|
||||||
|
const std::size_t n_size = a.size();
|
||||||
|
const std::size_t m_size = b.size();
|
||||||
|
|
||||||
|
if (n_size > limits.max_input_elements ||
|
||||||
|
m_size > limits.max_input_elements ||
|
||||||
|
n_size > limits.max_input_elements - m_size) {
|
||||||
|
return std::unexpected{DiffFailure::InputTooLarge};
|
||||||
|
}
|
||||||
|
const std::size_t max_diff_size = static_cast<std::size_t>(kMaxDiff);
|
||||||
|
if (n_size > max_diff_size || m_size > max_diff_size ||
|
||||||
|
n_size > max_diff_size - m_size) {
|
||||||
|
return std::unexpected{DiffFailure::InputTooLarge};
|
||||||
|
}
|
||||||
|
|
||||||
|
const Diff n = static_cast<Diff>(n_size);
|
||||||
|
const Diff m = static_cast<Diff>(m_size);
|
||||||
|
const Diff max_d = n + m;
|
||||||
|
|
||||||
|
if (max_d == 0) return std::vector<Edit<T>>{};
|
||||||
|
|
||||||
|
// Unsigned index math keeps max_d + k from overflowing signed ptrdiff_t.
|
||||||
|
const auto index = [max_d](Diff k) {
|
||||||
|
return static_cast<std::size_t>(max_d) + static_cast<std::size_t>(k);
|
||||||
|
};
|
||||||
|
|
||||||
|
const std::size_t v_size = static_cast<std::size_t>(max_d) * 2 + 1;
|
||||||
|
if (v_size > limits.max_trace_memory / sizeof(Diff)) {
|
||||||
|
return std::unexpected{DiffFailure::TraceMemoryExhausted};
|
||||||
|
}
|
||||||
|
const std::size_t snapshot_bytes = v_size * sizeof(Diff);
|
||||||
|
|
||||||
|
// v[k + max_d] = furthest-reaching x in diagonal k
|
||||||
|
std::vector<Diff> v(v_size, -1);
|
||||||
|
// trace[d] = snapshot of v at step d (for backtracking)
|
||||||
|
std::vector<std::vector<Diff>> trace;
|
||||||
|
std::size_t trace_bytes = 0;
|
||||||
|
std::size_t work = 0;
|
||||||
|
|
||||||
|
const auto spend = [&]() -> bool {
|
||||||
|
if (work >= limits.max_work) return false;
|
||||||
|
++work;
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
v[index(1)] = 0;
|
||||||
|
bool done = false;
|
||||||
|
Diff final_d = 0;
|
||||||
|
|
||||||
|
for (Diff d = 0; d <= max_d && !done; ++d) {
|
||||||
|
if (Detail::cancellation_requested(cancelled))
|
||||||
|
return std::unexpected{DiffFailure::Cancelled};
|
||||||
|
if (snapshot_bytes > limits.max_trace_memory - trace_bytes)
|
||||||
|
return std::unexpected{DiffFailure::TraceMemoryExhausted};
|
||||||
|
trace.push_back(v);
|
||||||
|
trace_bytes += snapshot_bytes;
|
||||||
|
|
||||||
|
for (Diff k = -d; k <= d; k += 2) {
|
||||||
|
if (!spend()) return std::unexpected{DiffFailure::WorkExhausted};
|
||||||
|
if (Detail::cancellation_requested(cancelled))
|
||||||
|
return std::unexpected{DiffFailure::Cancelled};
|
||||||
|
|
||||||
|
Diff x;
|
||||||
|
if (k == -d || (k != d && v[index(k - 1)] < v[index(k + 1)]))
|
||||||
|
x = v[index(k + 1)];
|
||||||
|
else
|
||||||
|
x = v[index(k - 1)] + 1;
|
||||||
|
Diff y = x - k;
|
||||||
|
while (x < n && y < m && eq(a[static_cast<std::size_t>(x)],
|
||||||
|
b[static_cast<std::size_t>(y)])) {
|
||||||
|
if (!spend()) return std::unexpected{DiffFailure::WorkExhausted};
|
||||||
|
if (Detail::cancellation_requested(cancelled))
|
||||||
|
return std::unexpected{DiffFailure::Cancelled};
|
||||||
|
++x;
|
||||||
|
++y;
|
||||||
|
}
|
||||||
|
v[index(k)] = x;
|
||||||
|
if (x == n && y == m) {
|
||||||
|
final_d = d;
|
||||||
|
done = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!done) return std::unexpected{DiffFailure::WorkExhausted};
|
||||||
|
|
||||||
|
// Backtrack to reconstruct the edit script.
|
||||||
|
std::vector<Edit<T>> script;
|
||||||
|
const auto push = [&](Op op, const T& value) -> bool {
|
||||||
|
if (script.size() >= limits.max_output) return false;
|
||||||
|
script.push_back(Edit<T>{op, value});
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
Diff x = n;
|
||||||
|
Diff y = m;
|
||||||
|
for (Diff d = final_d; d > 0; --d) {
|
||||||
|
if (!spend()) return std::unexpected{DiffFailure::WorkExhausted};
|
||||||
|
if (Detail::cancellation_requested(cancelled))
|
||||||
|
return std::unexpected{DiffFailure::Cancelled};
|
||||||
|
|
||||||
|
const auto& pv = trace[static_cast<std::size_t>(d)];
|
||||||
|
const Diff k = x - y;
|
||||||
|
Diff prev_k;
|
||||||
|
if (k == -d || (k != d && pv[index(k - 1)] < pv[index(k + 1)]))
|
||||||
|
prev_k = k + 1;
|
||||||
|
else
|
||||||
|
prev_k = k - 1;
|
||||||
|
const Diff prev_x = pv[index(prev_k)];
|
||||||
|
const Diff prev_y = prev_x - prev_k;
|
||||||
|
// snake (equal)
|
||||||
|
while (x > prev_x && y > prev_y) {
|
||||||
|
if (!spend()) return std::unexpected{DiffFailure::WorkExhausted};
|
||||||
|
if (Detail::cancellation_requested(cancelled))
|
||||||
|
return std::unexpected{DiffFailure::Cancelled};
|
||||||
|
--x;
|
||||||
|
--y;
|
||||||
|
if (!push(Op::Equal, a[static_cast<std::size_t>(x)]))
|
||||||
|
return std::unexpected{DiffFailure::OutputTooLarge};
|
||||||
|
}
|
||||||
|
if (d > 0) {
|
||||||
|
if (x == prev_x) {
|
||||||
|
--y;
|
||||||
|
if (!push(Op::Insert, b[static_cast<std::size_t>(y)]))
|
||||||
|
return std::unexpected{DiffFailure::OutputTooLarge};
|
||||||
|
} else {
|
||||||
|
--x;
|
||||||
|
if (!push(Op::Delete, a[static_cast<std::size_t>(x)]))
|
||||||
|
return std::unexpected{DiffFailure::OutputTooLarge};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
x = prev_x;
|
||||||
|
y = prev_y;
|
||||||
|
}
|
||||||
|
// Remaining snake at start
|
||||||
|
while (x > 0 && y > 0) {
|
||||||
|
if (!spend()) return std::unexpected{DiffFailure::WorkExhausted};
|
||||||
|
--x;
|
||||||
|
--y;
|
||||||
|
if (!push(Op::Equal, a[static_cast<std::size_t>(x)]))
|
||||||
|
return std::unexpected{DiffFailure::OutputTooLarge};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::reverse(script.begin(), script.end());
|
||||||
|
return script;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convenience overload for vectors
|
||||||
|
template <typename T, typename Eq = std::equal_to<T>,
|
||||||
|
typename Cancel = std::function<bool()>>
|
||||||
|
[[nodiscard]] std::expected<std::vector<Edit<T>>, DiffFailure>
|
||||||
|
diff_bounded(const std::vector<T>& a, const std::vector<T>& b,
|
||||||
|
DiffLimits limits = {}, Eq eq = {}, Cancel&& cancelled = {})
|
||||||
|
{
|
||||||
|
return diff_bounded<T, Eq>(std::span<const T>{a}, std::span<const T>{b},
|
||||||
|
limits, eq, std::forward<Cancel>(cancelled));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unbounded compatibility API. Default limits are effectively unlimited, so
|
||||||
|
// existing callers keep their behaviour.
|
||||||
template <typename T, typename Eq = std::equal_to<T>>
|
template <typename T, typename Eq = std::equal_to<T>>
|
||||||
[[nodiscard]] std::vector<Edit<T>>
|
[[nodiscard]] std::vector<Edit<T>>
|
||||||
diff(std::span<const T> a, std::span<const T> b, Eq eq = {})
|
diff(std::span<const T> a, std::span<const T> b, Eq eq = {})
|
||||||
{
|
{
|
||||||
const int n = static_cast<int>(a.size());
|
auto result = diff_bounded<T, Eq>(a, b, {}, eq);
|
||||||
const int m = static_cast<int>(b.size());
|
if (!result) throw std::length_error("Void::Diff: diff input too large");
|
||||||
const int max_d = n + m;
|
return *std::move(result);
|
||||||
|
|
||||||
if (max_d == 0) return {};
|
|
||||||
|
|
||||||
// v[k + max_d] = furthest-reaching x in diagonal k
|
|
||||||
std::vector<int> v(2 * max_d + 1, -1);
|
|
||||||
// trace[d] = snapshot of v at step d (for backtracking)
|
|
||||||
std::vector<std::vector<int>> trace;
|
|
||||||
|
|
||||||
v[max_d + 1] = 0;
|
|
||||||
bool done = false;
|
|
||||||
int final_d = 0;
|
|
||||||
|
|
||||||
for (int d = 0; d <= max_d && !done; ++d) {
|
|
||||||
trace.push_back(v);
|
|
||||||
for (int k = -d; k <= d; k += 2) {
|
|
||||||
int x;
|
|
||||||
if (k == -d || (k != d && v[max_d + k - 1] < v[max_d + k + 1]))
|
|
||||||
x = v[max_d + k + 1];
|
|
||||||
else
|
|
||||||
x = v[max_d + k - 1] + 1;
|
|
||||||
int y = x - k;
|
|
||||||
while (x < n && y < m && eq(a[x], b[y])) { ++x; ++y; }
|
|
||||||
v[max_d + k] = x;
|
|
||||||
if (x == n && y == m) { final_d = d; done = true; break; }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backtrack to reconstruct the edit script
|
|
||||||
std::vector<Edit<T>> script;
|
|
||||||
int x = n, y = m;
|
|
||||||
for (int d = final_d; d > 0; --d) {
|
|
||||||
const auto& pv = trace[d];
|
|
||||||
const int k = x - y;
|
|
||||||
int prev_k;
|
|
||||||
if (k == -d || (k != d && pv[max_d + k - 1] < pv[max_d + k + 1]))
|
|
||||||
prev_k = k + 1;
|
|
||||||
else
|
|
||||||
prev_k = k - 1;
|
|
||||||
const int prev_x = pv[max_d + prev_k];
|
|
||||||
const int prev_y = prev_x - prev_k;
|
|
||||||
// snake (equal)
|
|
||||||
while (x > prev_x && y > prev_y) {
|
|
||||||
--x; --y;
|
|
||||||
script.push_back({Op::Equal, a[x]});
|
|
||||||
}
|
|
||||||
if (d > 0) {
|
|
||||||
if (x == prev_x) { --y; script.push_back({Op::Insert, b[y]}); }
|
|
||||||
else { --x; script.push_back({Op::Delete, a[x]}); }
|
|
||||||
}
|
|
||||||
x = prev_x; y = prev_y;
|
|
||||||
}
|
|
||||||
// Remaining snake at start
|
|
||||||
while (x > 0 && y > 0) { --x; --y; script.push_back({Op::Equal, a[x]}); }
|
|
||||||
|
|
||||||
std::reverse(script.begin(), script.end());
|
|
||||||
return script;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convenience overload for vectors
|
// Convenience overload for vectors
|
||||||
@@ -104,22 +262,66 @@ diff(const std::vector<T>& a, const std::vector<T>& b, Eq eq = {})
|
|||||||
|
|
||||||
using LineDiff = Edit<std::string>;
|
using LineDiff = Edit<std::string>;
|
||||||
|
|
||||||
[[nodiscard]] inline std::vector<LineDiff>
|
namespace Detail
|
||||||
line_diff(std::string_view a, std::string_view b)
|
|
||||||
{
|
{
|
||||||
auto split = [](std::string_view s) {
|
[[nodiscard]] inline std::expected<std::vector<std::string_view>, DiffFailure>
|
||||||
std::vector<std::string> lines;
|
split_lines_bounded(std::string_view input, const DiffLimits& limits,
|
||||||
|
std::size_t& line_count)
|
||||||
|
{
|
||||||
|
std::vector<std::string_view> lines;
|
||||||
std::size_t pos = 0;
|
std::size_t pos = 0;
|
||||||
while (pos <= s.size()) {
|
while (pos <= input.size()) {
|
||||||
const auto nl = s.find('\n', pos);
|
if (line_count >= limits.max_input_elements) {
|
||||||
lines.emplace_back(s.substr(pos, nl == std::string_view::npos ? nl : nl - pos));
|
return std::unexpected{DiffFailure::InputTooLarge};
|
||||||
|
}
|
||||||
|
++line_count;
|
||||||
|
const std::size_t nl = input.find('\n', pos);
|
||||||
|
lines.emplace_back(
|
||||||
|
input.substr(pos, nl == std::string_view::npos ? nl : nl - pos));
|
||||||
if (nl == std::string_view::npos) break;
|
if (nl == std::string_view::npos) break;
|
||||||
pos = nl + 1;
|
pos = nl + 1;
|
||||||
}
|
}
|
||||||
return lines;
|
return lines;
|
||||||
};
|
}
|
||||||
|
} // namespace Detail
|
||||||
|
|
||||||
return diff(split(a), split(b));
|
template <typename Cancel = std::function<bool()>>
|
||||||
|
[[nodiscard]] inline std::expected<std::vector<LineDiff>, DiffFailure>
|
||||||
|
line_diff_bounded(std::string_view a, std::string_view b,
|
||||||
|
DiffLimits limits = {}, Cancel&& cancelled = {})
|
||||||
|
{
|
||||||
|
if (a.size() > limits.max_input_bytes ||
|
||||||
|
b.size() > limits.max_input_bytes ||
|
||||||
|
a.size() > limits.max_input_bytes - b.size()) {
|
||||||
|
return std::unexpected{DiffFailure::InputTooLarge};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t line_count = 0;
|
||||||
|
auto a_lines = Detail::split_lines_bounded(a, limits, line_count);
|
||||||
|
if (!a_lines) return std::unexpected{a_lines.error()};
|
||||||
|
auto b_lines = Detail::split_lines_bounded(b, limits, line_count);
|
||||||
|
if (!b_lines) return std::unexpected{b_lines.error()};
|
||||||
|
|
||||||
|
auto edits = diff_bounded(std::span<const std::string_view>{*a_lines},
|
||||||
|
std::span<const std::string_view>{*b_lines},
|
||||||
|
limits, std::equal_to<>{},
|
||||||
|
std::forward<Cancel>(cancelled));
|
||||||
|
if (!edits) return std::unexpected{edits.error()};
|
||||||
|
|
||||||
|
std::vector<LineDiff> lines;
|
||||||
|
lines.reserve(edits->size());
|
||||||
|
for (const auto& edit : *edits) {
|
||||||
|
lines.push_back(LineDiff{edit.op, std::string{edit.value}});
|
||||||
|
}
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] inline std::vector<LineDiff>
|
||||||
|
line_diff(std::string_view a, std::string_view b)
|
||||||
|
{
|
||||||
|
auto result = line_diff_bounded(a, b);
|
||||||
|
if (!result) throw std::length_error("Void::Diff: line diff input too large");
|
||||||
|
return *std::move(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── helpers ───────────────────────────────────────────────────────────────────
|
// ── helpers ───────────────────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -0,0 +1,634 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
#include <Void/Text/Semver.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <compare>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <expected>
|
||||||
|
#include <format>
|
||||||
|
#include <functional>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <set>
|
||||||
|
#include <span>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Update
|
||||||
|
{
|
||||||
|
|
||||||
|
inline constexpr std::size_t kDefaultMaxResolvedPackages = 64;
|
||||||
|
inline constexpr std::size_t kDefaultMaxResolvedEdges = 256;
|
||||||
|
inline constexpr std::size_t kDefaultMaxResolutionNodes = 100'000;
|
||||||
|
|
||||||
|
/// One dependency edge: the required package id and the accepted versions.
|
||||||
|
struct PackageDependency {
|
||||||
|
std::string id;
|
||||||
|
Void::Semver::VersionRange range;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Caller-supplied description of one installed package version.
|
||||||
|
///
|
||||||
|
/// Each entry in `capabilities` is *exclusive*: at most one resolved package
|
||||||
|
/// may provide a given capability. `content_digest` is opaque to the resolver
|
||||||
|
/// (for example `sha256:...`) but participates in the frozen identity.
|
||||||
|
struct PackageDescription {
|
||||||
|
std::string id;
|
||||||
|
Void::Semver::Version version;
|
||||||
|
std::string content_digest;
|
||||||
|
std::vector<std::string> capabilities;
|
||||||
|
std::vector<PackageDependency> dependencies;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Frozen identity of a resolved package.
|
||||||
|
///
|
||||||
|
/// Unlike `Void::Semver::Version::operator==`, equality (and ordering) here
|
||||||
|
/// includes SemVer build metadata and the content digest, so a rebuild that
|
||||||
|
/// only changes `+metadata` or the digest is never mistaken for the same
|
||||||
|
/// package even though its SemVer precedence is equal.
|
||||||
|
struct PackageIdentity {
|
||||||
|
std::string id;
|
||||||
|
Void::Semver::Version version;
|
||||||
|
std::string content_digest;
|
||||||
|
|
||||||
|
[[nodiscard]] std::strong_ordering
|
||||||
|
operator<=>(const PackageIdentity& other) const noexcept
|
||||||
|
{
|
||||||
|
if (const auto comparison = id <=> other.id; comparison != 0) {
|
||||||
|
return comparison;
|
||||||
|
}
|
||||||
|
// Precedence first, then build metadata, then digest: a total order.
|
||||||
|
if (const auto comparison = version <=> other.version;
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison;
|
||||||
|
}
|
||||||
|
if (const auto comparison = version.build <=> other.version.build;
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison;
|
||||||
|
}
|
||||||
|
return content_digest <=> other.content_digest;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const PackageIdentity& other) const noexcept
|
||||||
|
{
|
||||||
|
return (*this <=> other) == 0;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ResolvedPackage {
|
||||||
|
PackageIdentity identity;
|
||||||
|
std::vector<std::string> capabilities;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Resolution {
|
||||||
|
/// Sorted by frozen identity; capabilities are sorted and deduplicated.
|
||||||
|
std::vector<ResolvedPackage> packages;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class ResolutionErrorKind : std::uint8_t {
|
||||||
|
invalid_request = 0,
|
||||||
|
missing_dependency,
|
||||||
|
incompatible_version,
|
||||||
|
cyclic_dependency,
|
||||||
|
ambiguous_package,
|
||||||
|
exclusive_capability_conflict,
|
||||||
|
limit_exceeded,
|
||||||
|
search_exhausted,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Actionable failure. `package` names the input package (or requested id) and
|
||||||
|
/// `field` the exact field, e.g. `dependencies[1].range`.
|
||||||
|
struct ResolutionDiagnostic {
|
||||||
|
ResolutionErrorKind kind{ResolutionErrorKind::invalid_request};
|
||||||
|
std::string package;
|
||||||
|
std::string field;
|
||||||
|
std::string related;
|
||||||
|
std::string message;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ResolutionLimits {
|
||||||
|
std::size_t max_packages{kDefaultMaxResolvedPackages};
|
||||||
|
std::size_t max_edges{kDefaultMaxResolvedEdges};
|
||||||
|
std::size_t max_search_nodes{kDefaultMaxResolutionNodes};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ResolutionRequest {
|
||||||
|
std::span<const PackageDescription> installed;
|
||||||
|
/// Root package ids; each is resolved as `*`.
|
||||||
|
std::span<const std::string> selected;
|
||||||
|
ResolutionLimits limits{};
|
||||||
|
};
|
||||||
|
|
||||||
|
namespace Detail
|
||||||
|
{
|
||||||
|
|
||||||
|
struct Requirement {
|
||||||
|
std::string id;
|
||||||
|
Void::Semver::VersionRange range;
|
||||||
|
std::string requester;
|
||||||
|
std::string field;
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator<(const Requirement& other) const noexcept
|
||||||
|
{
|
||||||
|
if (const auto comparison = id <=> other.id; comparison != 0) {
|
||||||
|
return comparison < 0;
|
||||||
|
}
|
||||||
|
if (const auto comparison = requester <=> other.requester;
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison < 0;
|
||||||
|
}
|
||||||
|
return field < other.field;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SearchContext {
|
||||||
|
const std::map<std::string, std::vector<PackageDescription>>& available;
|
||||||
|
ResolutionLimits limits;
|
||||||
|
std::size_t nodes{0};
|
||||||
|
bool node_limit_hit{false};
|
||||||
|
std::optional<ResolutionDiagnostic> best;
|
||||||
|
std::size_t best_depth{0};
|
||||||
|
|
||||||
|
void record(ResolutionDiagnostic diagnostic, std::size_t depth)
|
||||||
|
{
|
||||||
|
const bool better = !best.has_value() || depth > best_depth ||
|
||||||
|
(depth == best_depth && diagnose_less(diagnostic, *best));
|
||||||
|
if (better) {
|
||||||
|
best = std::move(diagnostic);
|
||||||
|
best_depth = depth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool diagnose_less(const ResolutionDiagnostic& lhs,
|
||||||
|
const ResolutionDiagnostic& rhs) noexcept
|
||||||
|
{
|
||||||
|
if (const auto comparison =
|
||||||
|
static_cast<std::uint8_t>(lhs.kind) <=>
|
||||||
|
static_cast<std::uint8_t>(rhs.kind);
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison < 0;
|
||||||
|
}
|
||||||
|
if (const auto comparison = lhs.package <=> rhs.package;
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison < 0;
|
||||||
|
}
|
||||||
|
if (const auto comparison = lhs.field <=> rhs.field; comparison != 0) {
|
||||||
|
return comparison < 0;
|
||||||
|
}
|
||||||
|
return lhs.related < rhs.related;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
using Assignment = std::map<std::string, std::size_t>;
|
||||||
|
|
||||||
|
[[nodiscard]] inline std::optional<ResolutionDiagnostic>
|
||||||
|
check_capabilities(const Assignment& assignment,
|
||||||
|
const SearchContext& context)
|
||||||
|
{
|
||||||
|
std::map<std::string, std::vector<std::string>> providers;
|
||||||
|
for (const auto& [id, index] : assignment) {
|
||||||
|
const auto& package = context.available.at(id)[index];
|
||||||
|
std::vector<std::string> capabilities = package.capabilities;
|
||||||
|
std::sort(capabilities.begin(), capabilities.end());
|
||||||
|
capabilities.erase(
|
||||||
|
std::unique(capabilities.begin(), capabilities.end()),
|
||||||
|
capabilities.end());
|
||||||
|
for (const auto& capability : capabilities) {
|
||||||
|
providers[capability].push_back(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto& [capability, owners] : providers) {
|
||||||
|
if (owners.size() > 1) {
|
||||||
|
return ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::exclusive_capability_conflict,
|
||||||
|
.package = owners[0],
|
||||||
|
.field = "capabilities",
|
||||||
|
.related = owners[1],
|
||||||
|
.message = std::format(
|
||||||
|
"exclusive capability '{}' is provided by both '{}' and '{}'",
|
||||||
|
capability,
|
||||||
|
owners[0],
|
||||||
|
owners[1])};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] inline std::optional<ResolutionDiagnostic>
|
||||||
|
check_cycle(const Assignment& assignment, const SearchContext& context)
|
||||||
|
{
|
||||||
|
std::map<std::string, int> color; // 0 unseen, 1 on stack, 2 done
|
||||||
|
std::vector<std::string> stack;
|
||||||
|
|
||||||
|
const std::function<std::optional<ResolutionDiagnostic>(
|
||||||
|
const std::string&)>
|
||||||
|
visit = [&](const std::string& id)
|
||||||
|
-> std::optional<ResolutionDiagnostic> {
|
||||||
|
color[id] = 1;
|
||||||
|
stack.push_back(id);
|
||||||
|
const auto& package =
|
||||||
|
context.available.at(id)[assignment.at(id)];
|
||||||
|
std::vector<std::string> dependencies;
|
||||||
|
for (const auto& dependency : package.dependencies) {
|
||||||
|
if (assignment.contains(dependency.id)) {
|
||||||
|
dependencies.push_back(dependency.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::sort(dependencies.begin(), dependencies.end());
|
||||||
|
dependencies.erase(std::unique(dependencies.begin(),
|
||||||
|
dependencies.end()),
|
||||||
|
dependencies.end());
|
||||||
|
for (const auto& dependency : dependencies) {
|
||||||
|
if (color[dependency] == 1) {
|
||||||
|
std::string path;
|
||||||
|
const auto begin =
|
||||||
|
std::find(stack.begin(), stack.end(), dependency);
|
||||||
|
for (auto it = begin; it != stack.end(); ++it) {
|
||||||
|
path += *it;
|
||||||
|
path += " -> ";
|
||||||
|
}
|
||||||
|
path += dependency;
|
||||||
|
return ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::cyclic_dependency,
|
||||||
|
.package = dependency,
|
||||||
|
.field = "dependencies",
|
||||||
|
.related = path,
|
||||||
|
.message =
|
||||||
|
std::format("cyclic dependency detected: {}", path)};
|
||||||
|
}
|
||||||
|
if (color[dependency] == 0) {
|
||||||
|
if (auto diagnostic = visit(dependency)) {
|
||||||
|
return diagnostic;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stack.pop_back();
|
||||||
|
color[id] = 2;
|
||||||
|
return std::nullopt;
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const auto& [id, index] : assignment) {
|
||||||
|
(void)index;
|
||||||
|
if (color[id] == 0) {
|
||||||
|
if (auto diagnostic = visit(id)) {
|
||||||
|
return diagnostic;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] inline bool
|
||||||
|
solve(const Assignment& assignment,
|
||||||
|
std::vector<Requirement> pending,
|
||||||
|
SearchContext& context,
|
||||||
|
Assignment& solution)
|
||||||
|
{
|
||||||
|
if (context.node_limit_hit) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (++context.nodes > context.limits.max_search_nodes) {
|
||||||
|
context.node_limit_hit = true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (assignment.size() > context.limits.max_packages) {
|
||||||
|
context.record(
|
||||||
|
ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::limit_exceeded,
|
||||||
|
.field = "limits.max_packages",
|
||||||
|
.message = std::format(
|
||||||
|
"resolved package count exceeds the limit of {}",
|
||||||
|
context.limits.max_packages)},
|
||||||
|
assignment.size());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t edges = 0;
|
||||||
|
for (const auto& [id, index] : assignment) {
|
||||||
|
edges += context.available.at(id)[index].dependencies.size();
|
||||||
|
}
|
||||||
|
if (edges > context.limits.max_edges) {
|
||||||
|
context.record(
|
||||||
|
ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::limit_exceeded,
|
||||||
|
.field = "limits.max_edges",
|
||||||
|
.message = std::format(
|
||||||
|
"resolved dependency edge count exceeds the limit of {}",
|
||||||
|
context.limits.max_edges)},
|
||||||
|
assignment.size());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pending.empty()) {
|
||||||
|
if (auto diagnostic = check_capabilities(assignment, context)) {
|
||||||
|
context.record(std::move(*diagnostic), assignment.size());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (auto diagnostic = check_cycle(assignment, context)) {
|
||||||
|
context.record(std::move(*diagnostic), assignment.size());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
solution = assignment;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto next = std::min_element(pending.begin(), pending.end());
|
||||||
|
const Requirement requirement = *next;
|
||||||
|
pending.erase(next);
|
||||||
|
|
||||||
|
const auto found = context.available.find(requirement.id);
|
||||||
|
if (found == context.available.end()) {
|
||||||
|
context.record(
|
||||||
|
ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::missing_dependency,
|
||||||
|
.package = requirement.requester.empty()
|
||||||
|
? requirement.id
|
||||||
|
: requirement.requester,
|
||||||
|
.field = requirement.field,
|
||||||
|
.related = requirement.id,
|
||||||
|
.message = std::format(
|
||||||
|
"required package '{}' is not installed", requirement.id)},
|
||||||
|
assignment.size());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (const auto existing = assignment.find(requirement.id);
|
||||||
|
existing != assignment.end()) {
|
||||||
|
const auto& package = found->second[existing->second];
|
||||||
|
if (requirement.range.contains(package.version)) {
|
||||||
|
return solve(assignment, std::move(pending), context, solution);
|
||||||
|
}
|
||||||
|
context.record(
|
||||||
|
ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::incompatible_version,
|
||||||
|
.package = requirement.requester.empty()
|
||||||
|
? requirement.id
|
||||||
|
: requirement.requester,
|
||||||
|
.field = requirement.field,
|
||||||
|
.related = requirement.id,
|
||||||
|
.message = std::format(
|
||||||
|
"selected '{}' version {} does not satisfy the requested range",
|
||||||
|
requirement.id,
|
||||||
|
package.version.to_string())},
|
||||||
|
assignment.size());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool any_candidate = false;
|
||||||
|
for (std::size_t index = 0; index < found->second.size(); ++index) {
|
||||||
|
const auto& package = found->second[index];
|
||||||
|
if (!requirement.range.contains(package.version)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
any_candidate = true;
|
||||||
|
Assignment next_assignment = assignment;
|
||||||
|
next_assignment.emplace(requirement.id, index);
|
||||||
|
std::vector<Requirement> next_pending = pending;
|
||||||
|
for (std::size_t dependency_index = 0;
|
||||||
|
dependency_index < package.dependencies.size();
|
||||||
|
++dependency_index) {
|
||||||
|
const auto& dependency = package.dependencies[dependency_index];
|
||||||
|
next_pending.push_back(Requirement{
|
||||||
|
.id = dependency.id,
|
||||||
|
.range = dependency.range,
|
||||||
|
.requester = package.id,
|
||||||
|
.field = std::format("dependencies[{}].range",
|
||||||
|
dependency_index)});
|
||||||
|
}
|
||||||
|
if (solve(next_assignment,
|
||||||
|
std::move(next_pending),
|
||||||
|
context,
|
||||||
|
solution)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (context.node_limit_hit) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
context.record(
|
||||||
|
ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::incompatible_version,
|
||||||
|
.package = requirement.requester.empty() ? requirement.id
|
||||||
|
: requirement.requester,
|
||||||
|
.field = requirement.field,
|
||||||
|
.related = requirement.id,
|
||||||
|
.message = any_candidate
|
||||||
|
? std::format(
|
||||||
|
"no candidate for '{}' is consistent with the rest of the dependency set",
|
||||||
|
requirement.id)
|
||||||
|
: std::format(
|
||||||
|
"no installed version of '{}' satisfies the requested range",
|
||||||
|
requirement.id)},
|
||||||
|
assignment.size());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Detail
|
||||||
|
|
||||||
|
/// Resolve `request.selected` and their transitive dependencies into an exact,
|
||||||
|
/// deterministic package set.
|
||||||
|
///
|
||||||
|
/// The result is invariant under permutation of `installed` and `selected`.
|
||||||
|
/// Candidates are tried in descending SemVer precedence (ties broken by build
|
||||||
|
/// metadata and digest) and requirements are processed in a canonical order.
|
||||||
|
/// Caller-supplied content digests and versions are retained verbatim; no
|
||||||
|
/// game-specific schema is assumed.
|
||||||
|
[[nodiscard]] inline Void::Result::Result<Resolution, ResolutionDiagnostic>
|
||||||
|
resolve_packages(const ResolutionRequest& request)
|
||||||
|
{
|
||||||
|
using namespace Detail;
|
||||||
|
|
||||||
|
if (request.limits.max_packages == 0 ||
|
||||||
|
request.limits.max_edges == 0 ||
|
||||||
|
request.limits.max_search_nodes == 0) {
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::invalid_request,
|
||||||
|
.field = "limits",
|
||||||
|
.message = "resolution limits must be non-zero"}};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deterministic canonical input order: everything downstream is
|
||||||
|
// permutation-invariant.
|
||||||
|
std::vector<PackageDescription> installed{request.installed.begin(),
|
||||||
|
request.installed.end()};
|
||||||
|
std::sort(installed.begin(),
|
||||||
|
installed.end(),
|
||||||
|
[](const PackageDescription& lhs, const PackageDescription& rhs) {
|
||||||
|
const PackageIdentity left{lhs.id, lhs.version,
|
||||||
|
lhs.content_digest};
|
||||||
|
const PackageIdentity right{rhs.id, rhs.version,
|
||||||
|
rhs.content_digest};
|
||||||
|
return left < right;
|
||||||
|
});
|
||||||
|
|
||||||
|
std::map<std::string, std::vector<PackageDescription>> available;
|
||||||
|
for (const auto& package : installed) {
|
||||||
|
if (package.id.empty()) {
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::invalid_request,
|
||||||
|
.field = "id",
|
||||||
|
.message = "package id must not be empty"}};
|
||||||
|
}
|
||||||
|
if (package.content_digest.empty()) {
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::invalid_request,
|
||||||
|
.package = package.id,
|
||||||
|
.field = "content_digest",
|
||||||
|
.message = "package content digest must not be empty"}};
|
||||||
|
}
|
||||||
|
for (std::size_t index = 0; index < package.capabilities.size();
|
||||||
|
++index) {
|
||||||
|
if (package.capabilities[index].empty()) {
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::invalid_request,
|
||||||
|
.package = package.id,
|
||||||
|
.field = std::format("capabilities[{}]", index),
|
||||||
|
.message = "capability name must not be empty"}};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (std::size_t index = 0; index < package.dependencies.size();
|
||||||
|
++index) {
|
||||||
|
if (package.dependencies[index].id.empty()) {
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::invalid_request,
|
||||||
|
.package = package.id,
|
||||||
|
.field =
|
||||||
|
std::format("dependencies[{}].id", index),
|
||||||
|
.message = "dependency id must not be empty"}};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
available[package.id].push_back(package);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reject ambiguous inputs: same id and equal SemVer precedence but a
|
||||||
|
// different frozen identity (build metadata or digest).
|
||||||
|
for (auto& [id, candidates] : available) {
|
||||||
|
std::sort(candidates.begin(),
|
||||||
|
candidates.end(),
|
||||||
|
[](const PackageDescription& lhs,
|
||||||
|
const PackageDescription& rhs) {
|
||||||
|
if (const auto comparison = rhs.version <=> lhs.version;
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison < 0;
|
||||||
|
}
|
||||||
|
if (const auto comparison =
|
||||||
|
rhs.version.build <=> lhs.version.build;
|
||||||
|
comparison != 0) {
|
||||||
|
return comparison < 0;
|
||||||
|
}
|
||||||
|
return rhs.content_digest < lhs.content_digest;
|
||||||
|
});
|
||||||
|
for (std::size_t index = 1; index < candidates.size(); ++index) {
|
||||||
|
const auto& previous = candidates[index - 1];
|
||||||
|
const auto& current = candidates[index];
|
||||||
|
if ((previous.version <=> current.version) == 0 &&
|
||||||
|
!(PackageIdentity{previous.id, previous.version,
|
||||||
|
previous.content_digest} ==
|
||||||
|
PackageIdentity{current.id, current.version,
|
||||||
|
current.content_digest})) {
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::ambiguous_package,
|
||||||
|
.package = id,
|
||||||
|
.field = "version",
|
||||||
|
.related = current.content_digest,
|
||||||
|
.message = std::format(
|
||||||
|
"ambiguous installed '{}': {} and {} have equal SemVer precedence but different build metadata or digest",
|
||||||
|
id,
|
||||||
|
previous.version.to_string(),
|
||||||
|
current.version.to_string())}};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Identical frozen identities are the same package: keep one.
|
||||||
|
candidates.erase(
|
||||||
|
std::unique(candidates.begin(),
|
||||||
|
candidates.end(),
|
||||||
|
[](const PackageDescription& lhs,
|
||||||
|
const PackageDescription& rhs) {
|
||||||
|
return PackageIdentity{
|
||||||
|
lhs.id, lhs.version,
|
||||||
|
lhs.content_digest} ==
|
||||||
|
PackageIdentity{
|
||||||
|
rhs.id, rhs.version,
|
||||||
|
rhs.content_digest};
|
||||||
|
}),
|
||||||
|
candidates.end());
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto any_range = Void::Semver::VersionRange::parse("*");
|
||||||
|
if (!any_range.has_value()) {
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::invalid_request,
|
||||||
|
.field = "range",
|
||||||
|
.message = "the always-matching range could not be constructed"}};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<Requirement> pending;
|
||||||
|
std::set<std::string> roots;
|
||||||
|
for (std::size_t index = 0; index < request.selected.size(); ++index) {
|
||||||
|
const auto& id = request.selected[index];
|
||||||
|
if (id.empty()) {
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = ResolutionErrorKind::invalid_request,
|
||||||
|
.field = std::format("selected[{}]", index),
|
||||||
|
.message = "selected package id must not be empty"}};
|
||||||
|
}
|
||||||
|
if (!roots.insert(id).second) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
pending.push_back(Requirement{
|
||||||
|
.id = id,
|
||||||
|
.range = *any_range,
|
||||||
|
.requester = {},
|
||||||
|
.field = std::format("selected[{}]", index)});
|
||||||
|
}
|
||||||
|
|
||||||
|
SearchContext context{available, request.limits};
|
||||||
|
Assignment solution;
|
||||||
|
if (!solve(Assignment{}, std::move(pending), context, solution)) {
|
||||||
|
if (context.best.has_value()) {
|
||||||
|
return std::unexpected{std::move(*context.best)};
|
||||||
|
}
|
||||||
|
return std::unexpected{ResolutionDiagnostic{
|
||||||
|
.kind = context.node_limit_hit
|
||||||
|
? ResolutionErrorKind::search_exhausted
|
||||||
|
: ResolutionErrorKind::incompatible_version,
|
||||||
|
.field = "limits.max_search_nodes",
|
||||||
|
.message = "resolution search did not produce a package set"}};
|
||||||
|
}
|
||||||
|
|
||||||
|
Resolution resolution;
|
||||||
|
resolution.packages.reserve(solution.size());
|
||||||
|
for (const auto& [id, index] : solution) {
|
||||||
|
const auto& package = available.at(id)[index];
|
||||||
|
std::vector<std::string> capabilities = package.capabilities;
|
||||||
|
std::sort(capabilities.begin(), capabilities.end());
|
||||||
|
capabilities.erase(
|
||||||
|
std::unique(capabilities.begin(), capabilities.end()),
|
||||||
|
capabilities.end());
|
||||||
|
resolution.packages.push_back(ResolvedPackage{
|
||||||
|
.identity = PackageIdentity{package.id,
|
||||||
|
package.version,
|
||||||
|
package.content_digest},
|
||||||
|
.capabilities = std::move(capabilities)});
|
||||||
|
}
|
||||||
|
return resolution;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convenience: build a dependency from an id and a SemVer range expression.
|
||||||
|
[[nodiscard]] inline std::optional<PackageDependency>
|
||||||
|
make_package_dependency(std::string id, std::string_view range)
|
||||||
|
{
|
||||||
|
auto parsed = Void::Semver::VersionRange::parse(range);
|
||||||
|
if (!parsed.has_value()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return PackageDependency{.id = std::move(id), .range = std::move(*parsed)};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Update
|
||||||
@@ -0,0 +1,482 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
// Portable Ed25519 built on the module's own SHA-512 implementation.
|
||||||
|
//
|
||||||
|
// The field arithmetic follows the compact public-domain approach used by
|
||||||
|
// TweetNaCl: elements of GF(2^255-19) are 16 signed limbs of 16 bits and the
|
||||||
|
// group law is evaluated in extended coordinates. Secret scalars and the
|
||||||
|
// hash-derived key material are wiped before returning.
|
||||||
|
|
||||||
|
#include "BuiltinHash.hpp"
|
||||||
|
|
||||||
|
#include <Void/Crypto/Crypto.hpp>
|
||||||
|
#include <Void/Crypto/Types.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <cstring>
|
||||||
|
#include <initializer_list>
|
||||||
|
#include <span>
|
||||||
|
|
||||||
|
namespace Void::Crypto::Detail::Ed25519
|
||||||
|
{
|
||||||
|
using U8 = std::uint8_t;
|
||||||
|
using I64 = std::int64_t;
|
||||||
|
using Gf = std::array<I64, 16>;
|
||||||
|
using Point = std::array<Gf, 4>;
|
||||||
|
using Sha512 = std::array<U8, 64>;
|
||||||
|
|
||||||
|
inline constexpr Gf gf0{};
|
||||||
|
inline constexpr Gf gf1{1};
|
||||||
|
|
||||||
|
// Curve constants in 16-bit limbs (GF(2^255-19)).
|
||||||
|
inline constexpr Gf D{
|
||||||
|
0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070,
|
||||||
|
0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203};
|
||||||
|
inline constexpr Gf D2{
|
||||||
|
0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0,
|
||||||
|
0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406};
|
||||||
|
inline constexpr Gf I{
|
||||||
|
0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43,
|
||||||
|
0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83};
|
||||||
|
inline constexpr Gf base_x{
|
||||||
|
0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c,
|
||||||
|
0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169};
|
||||||
|
inline constexpr Gf base_y{
|
||||||
|
0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,
|
||||||
|
0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666};
|
||||||
|
|
||||||
|
// Group order L = 2^252 + 27742317777372353535851937790883648493.
|
||||||
|
inline constexpr std::array<I64, 32> L{
|
||||||
|
0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7,
|
||||||
|
0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||||
|
0, 0, 0, 0x10};
|
||||||
|
|
||||||
|
inline void wipe(std::span<U8> bytes) noexcept
|
||||||
|
{
|
||||||
|
builtin_secure_wipe(std::span<std::byte>{
|
||||||
|
reinterpret_cast<std::byte*>(bytes.data()), bytes.size()});
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void hash_sha512(std::initializer_list<std::span<const U8>> parts,
|
||||||
|
Sha512& out)
|
||||||
|
{
|
||||||
|
BuiltinHasher hasher;
|
||||||
|
if (!hasher.init(HashAlgorithm::Sha512)) {
|
||||||
|
out.fill(0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const auto part : parts) {
|
||||||
|
hasher.update(std::span<const std::byte>{
|
||||||
|
reinterpret_cast<const std::byte*>(part.data()), part.size()});
|
||||||
|
}
|
||||||
|
const Digest digest = hasher.finalize();
|
||||||
|
const std::size_t count = std::min<std::size_t>(digest.size(), out.size());
|
||||||
|
std::memcpy(out.data(), digest.data(), count);
|
||||||
|
if (count < out.size()) {
|
||||||
|
std::fill(out.begin() + static_cast<std::ptrdiff_t>(count), out.end(), 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] inline int verify_32(const U8* a, const U8* b) noexcept
|
||||||
|
{
|
||||||
|
unsigned int diff = 0;
|
||||||
|
for (int i = 0; i < 32; ++i) {
|
||||||
|
diff |= static_cast<unsigned int>(a[i] ^ b[i]);
|
||||||
|
}
|
||||||
|
return static_cast<int>((1 & ((diff - 1) >> 8)) - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void set25519(Gf& r, const Gf& a) noexcept
|
||||||
|
{
|
||||||
|
r = a;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void car25519(Gf& o) noexcept
|
||||||
|
{
|
||||||
|
for (int i = 0; i < 16; ++i) {
|
||||||
|
o[i] += I64{1} << 16;
|
||||||
|
const I64 c = o[i] >> 16;
|
||||||
|
o[(i + 1) * (i < 15)] += c - 1 + 37 * (c - 1) * (i == 15);
|
||||||
|
o[i] -= c << 16;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void sel25519(Gf& p, Gf& q, int b) noexcept
|
||||||
|
{
|
||||||
|
const I64 c = ~(static_cast<I64>(b) - 1);
|
||||||
|
for (int i = 0; i < 16; ++i) {
|
||||||
|
const I64 t = c & (p[i] ^ q[i]);
|
||||||
|
p[i] ^= t;
|
||||||
|
q[i] ^= t;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void pack25519(U8* o, const Gf& n) noexcept
|
||||||
|
{
|
||||||
|
Gf m{};
|
||||||
|
Gf t = n;
|
||||||
|
car25519(t);
|
||||||
|
car25519(t);
|
||||||
|
car25519(t);
|
||||||
|
for (int j = 0; j < 2; ++j) {
|
||||||
|
m[0] = t[0] - 0xffed;
|
||||||
|
for (int i = 1; i < 15; ++i) {
|
||||||
|
m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);
|
||||||
|
m[i - 1] &= 0xffff;
|
||||||
|
}
|
||||||
|
m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
|
||||||
|
const int b = static_cast<int>((m[15] >> 16) & 1);
|
||||||
|
m[14] &= 0xffff;
|
||||||
|
sel25519(t, m, 1 - b);
|
||||||
|
}
|
||||||
|
for (int i = 0; i < 16; ++i) {
|
||||||
|
o[2 * i] = static_cast<U8>(t[i] & 0xff);
|
||||||
|
o[2 * i + 1] = static_cast<U8>(t[i] >> 8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] inline int neq25519(const Gf& a, const Gf& b) noexcept
|
||||||
|
{
|
||||||
|
std::array<U8, 32> c{};
|
||||||
|
std::array<U8, 32> d{};
|
||||||
|
pack25519(c.data(), a);
|
||||||
|
pack25519(d.data(), b);
|
||||||
|
return verify_32(c.data(), d.data());
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] inline U8 par25519(const Gf& a) noexcept
|
||||||
|
{
|
||||||
|
std::array<U8, 32> d{};
|
||||||
|
pack25519(d.data(), a);
|
||||||
|
return d[0] & 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void unpack25519(Gf& o, const U8* n) noexcept
|
||||||
|
{
|
||||||
|
for (int i = 0; i < 16; ++i) {
|
||||||
|
o[i] = n[2 * i] + (static_cast<I64>(n[2 * i + 1]) << 8);
|
||||||
|
}
|
||||||
|
o[15] &= 0x7fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void add(Gf& o, const Gf& a, const Gf& b) noexcept
|
||||||
|
{
|
||||||
|
for (int i = 0; i < 16; ++i) {
|
||||||
|
o[i] = a[i] + b[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void sub(Gf& o, const Gf& a, const Gf& b) noexcept
|
||||||
|
{
|
||||||
|
for (int i = 0; i < 16; ++i) {
|
||||||
|
o[i] = a[i] - b[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void mul(Gf& o, const Gf& a, const Gf& b) noexcept
|
||||||
|
{
|
||||||
|
std::array<I64, 31> t{};
|
||||||
|
for (int i = 0; i < 16; ++i) {
|
||||||
|
for (int j = 0; j < 16; ++j) {
|
||||||
|
t[i + j] += a[i] * b[j];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int i = 0; i < 15; ++i) {
|
||||||
|
t[i] += 38 * t[i + 16];
|
||||||
|
}
|
||||||
|
for (int i = 0; i < 16; ++i) {
|
||||||
|
o[i] = t[i];
|
||||||
|
}
|
||||||
|
car25519(o);
|
||||||
|
car25519(o);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void square(Gf& o, const Gf& a) noexcept
|
||||||
|
{
|
||||||
|
mul(o, a, a);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void invert(Gf& o, const Gf& in) noexcept
|
||||||
|
{
|
||||||
|
Gf c = in;
|
||||||
|
for (int a = 253; a >= 0; --a) {
|
||||||
|
square(c, c);
|
||||||
|
if (a != 2 && a != 4) {
|
||||||
|
mul(c, c, in);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
o = c;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void pow2523(Gf& o, const Gf& in) noexcept
|
||||||
|
{
|
||||||
|
Gf c = in;
|
||||||
|
for (int a = 250; a >= 0; --a) {
|
||||||
|
square(c, c);
|
||||||
|
if (a != 1) {
|
||||||
|
mul(c, c, in);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
o = c;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void point_add(Point& p, const Point& q) noexcept
|
||||||
|
{
|
||||||
|
Gf a{};
|
||||||
|
Gf b{};
|
||||||
|
Gf c{};
|
||||||
|
Gf d{};
|
||||||
|
Gf e{};
|
||||||
|
Gf f{};
|
||||||
|
Gf g{};
|
||||||
|
Gf h{};
|
||||||
|
Gf t{};
|
||||||
|
sub(a, p[1], p[0]);
|
||||||
|
sub(t, q[1], q[0]);
|
||||||
|
mul(a, a, t);
|
||||||
|
add(b, p[0], p[1]);
|
||||||
|
add(t, q[0], q[1]);
|
||||||
|
mul(b, b, t);
|
||||||
|
mul(c, p[3], q[3]);
|
||||||
|
mul(c, c, D2);
|
||||||
|
mul(d, p[2], q[2]);
|
||||||
|
add(d, d, d);
|
||||||
|
sub(e, b, a);
|
||||||
|
sub(f, d, c);
|
||||||
|
add(g, d, c);
|
||||||
|
add(h, b, a);
|
||||||
|
mul(p[0], e, f);
|
||||||
|
mul(p[1], h, g);
|
||||||
|
mul(p[2], g, f);
|
||||||
|
mul(p[3], e, h);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void point_cswap(Point& p, Point& q, int b) noexcept
|
||||||
|
{
|
||||||
|
for (int i = 0; i < 4; ++i) {
|
||||||
|
sel25519(p[i], q[i], b);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void point_pack(U8* r, const Point& p) noexcept
|
||||||
|
{
|
||||||
|
Gf tx{};
|
||||||
|
Gf ty{};
|
||||||
|
Gf zi{};
|
||||||
|
invert(zi, p[2]);
|
||||||
|
mul(tx, p[0], zi);
|
||||||
|
mul(ty, p[1], zi);
|
||||||
|
pack25519(r, ty);
|
||||||
|
r[31] ^= static_cast<U8>(par25519(tx) << 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void scalarmult(Point& p, Point& q, const U8* s) noexcept
|
||||||
|
{
|
||||||
|
p[0].fill(0);
|
||||||
|
p[1].fill(0);
|
||||||
|
p[2].fill(0);
|
||||||
|
p[3].fill(0);
|
||||||
|
p[1][0] = 1;
|
||||||
|
p[2][0] = 1;
|
||||||
|
for (int i = 255; i >= 0; --i) {
|
||||||
|
const int b = (s[i / 8] >> (i & 7)) & 1;
|
||||||
|
point_cswap(p, q, b);
|
||||||
|
point_add(q, p);
|
||||||
|
point_add(p, p);
|
||||||
|
point_cswap(p, q, b);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void scalarbase(Point& p, const U8* s) noexcept
|
||||||
|
{
|
||||||
|
Point q{};
|
||||||
|
set25519(q[0], base_x);
|
||||||
|
set25519(q[1], base_y);
|
||||||
|
set25519(q[2], gf1);
|
||||||
|
mul(q[3], base_x, base_y);
|
||||||
|
scalarmult(p, q, s);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline int unpackneg(Point& r, const U8* p) noexcept
|
||||||
|
{
|
||||||
|
Gf t{};
|
||||||
|
Gf chk{};
|
||||||
|
Gf num{};
|
||||||
|
Gf den{};
|
||||||
|
Gf den2{};
|
||||||
|
Gf den4{};
|
||||||
|
Gf den6{};
|
||||||
|
set25519(r[2], gf1);
|
||||||
|
unpack25519(r[1], p);
|
||||||
|
square(num, r[1]);
|
||||||
|
mul(den, num, D);
|
||||||
|
sub(num, num, r[2]);
|
||||||
|
add(den, r[2], den);
|
||||||
|
|
||||||
|
square(den2, den);
|
||||||
|
square(den4, den2);
|
||||||
|
mul(den6, den4, den2);
|
||||||
|
mul(t, den6, num);
|
||||||
|
mul(t, t, den);
|
||||||
|
|
||||||
|
pow2523(t, t);
|
||||||
|
mul(t, t, num);
|
||||||
|
mul(t, t, den);
|
||||||
|
mul(t, t, den);
|
||||||
|
mul(r[0], t, den);
|
||||||
|
|
||||||
|
square(chk, r[0]);
|
||||||
|
mul(chk, chk, den);
|
||||||
|
if (neq25519(chk, num) != 0) {
|
||||||
|
mul(r[0], r[0], I);
|
||||||
|
}
|
||||||
|
|
||||||
|
square(chk, r[0]);
|
||||||
|
mul(chk, chk, den);
|
||||||
|
if (neq25519(chk, num) != 0) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (par25519(r[0]) == (p[31] >> 7)) {
|
||||||
|
sub(r[0], gf0, r[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
mul(r[3], r[0], r[1]);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void modL(U8* r, std::array<I64, 64>& x) noexcept
|
||||||
|
{
|
||||||
|
I64 carry = 0;
|
||||||
|
int i = 0;
|
||||||
|
int j = 0;
|
||||||
|
for (i = 63; i >= 32; --i) {
|
||||||
|
carry = 0;
|
||||||
|
for (j = i - 32; j < i - 12; ++j) {
|
||||||
|
x[j] += carry - 16 * x[i] * L[j - (i - 32)];
|
||||||
|
carry = (x[j] + 128) >> 8;
|
||||||
|
x[j] -= carry << 8;
|
||||||
|
}
|
||||||
|
x[j] += carry;
|
||||||
|
x[i] = 0;
|
||||||
|
}
|
||||||
|
carry = 0;
|
||||||
|
for (j = 0; j < 32; ++j) {
|
||||||
|
x[j] += carry - (x[31] >> 4) * L[j];
|
||||||
|
carry = x[j] >> 8;
|
||||||
|
x[j] &= 255;
|
||||||
|
}
|
||||||
|
for (j = 0; j < 32; ++j) {
|
||||||
|
x[j] -= carry * L[j];
|
||||||
|
}
|
||||||
|
for (i = 0; i < 32; ++i) {
|
||||||
|
x[i + 1] += x[i] >> 8;
|
||||||
|
r[i] = static_cast<U8>(x[i] & 255);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void reduce(U8* r) noexcept
|
||||||
|
{
|
||||||
|
std::array<I64, 64> x{};
|
||||||
|
for (int i = 0; i < 64; ++i) {
|
||||||
|
x[i] = r[i];
|
||||||
|
}
|
||||||
|
std::fill(r, r + 64, U8{0});
|
||||||
|
modL(r, x);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Derive the public key and the clamped secret scalar from a 32-byte seed.
|
||||||
|
inline void expand_seed(const U8* seed, Sha512& digest, U8* public_key) noexcept
|
||||||
|
{
|
||||||
|
hash_sha512({std::span<const U8>{seed, 32}}, digest);
|
||||||
|
digest[0] &= 248;
|
||||||
|
digest[31] &= 127;
|
||||||
|
digest[31] |= 64;
|
||||||
|
Point p{};
|
||||||
|
scalarbase(p, digest.data());
|
||||||
|
if (public_key != nullptr) {
|
||||||
|
point_pack(public_key, p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void sign(const U8* seed, const U8* public_key,
|
||||||
|
std::span<const std::byte> message, U8* signature) noexcept
|
||||||
|
{
|
||||||
|
Sha512 digest{};
|
||||||
|
Sha512 nonce{};
|
||||||
|
Sha512 challenge{};
|
||||||
|
Point p{};
|
||||||
|
expand_seed(seed, digest, nullptr);
|
||||||
|
|
||||||
|
const auto message_bytes = std::span<const U8>{
|
||||||
|
reinterpret_cast<const U8*>(message.data()), message.size()};
|
||||||
|
hash_sha512({std::span<const U8>{digest.data() + 32, 32}, message_bytes},
|
||||||
|
nonce);
|
||||||
|
reduce(nonce.data());
|
||||||
|
scalarbase(p, nonce.data());
|
||||||
|
point_pack(signature, p);
|
||||||
|
|
||||||
|
hash_sha512({std::span<const U8>{signature, 32},
|
||||||
|
std::span<const U8>{public_key, 32}, message_bytes},
|
||||||
|
challenge);
|
||||||
|
reduce(challenge.data());
|
||||||
|
|
||||||
|
std::array<I64, 64> x{};
|
||||||
|
for (int i = 0; i < 32; ++i) {
|
||||||
|
x[i] = nonce[i];
|
||||||
|
}
|
||||||
|
for (int i = 0; i < 32; ++i) {
|
||||||
|
for (int j = 0; j < 32; ++j) {
|
||||||
|
x[i + j] += static_cast<I64>(challenge[i]) * digest[j];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
modL(signature + 32, x);
|
||||||
|
|
||||||
|
wipe(digest);
|
||||||
|
wipe(nonce);
|
||||||
|
wipe(challenge);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] inline bool verify(const U8* public_key, const U8* signature,
|
||||||
|
std::span<const std::byte> message) noexcept
|
||||||
|
{
|
||||||
|
// Reject a non-canonical scalar S >= L (and the top three bits, which
|
||||||
|
// must be clear because L < 2^253).
|
||||||
|
if ((signature[63] & 224) != 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
std::array<U8, 64> s_wide{};
|
||||||
|
std::memcpy(s_wide.data(), signature + 32, 32);
|
||||||
|
reduce(s_wide.data());
|
||||||
|
if (verify_32(s_wide.data(), signature + 32) != 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Point q{};
|
||||||
|
Point p{};
|
||||||
|
if (unpackneg(q, public_key) != 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Sha512 challenge{};
|
||||||
|
hash_sha512({std::span<const U8>{signature, 32},
|
||||||
|
std::span<const U8>{public_key, 32},
|
||||||
|
std::span<const U8>{
|
||||||
|
reinterpret_cast<const U8*>(message.data()),
|
||||||
|
message.size()}},
|
||||||
|
challenge);
|
||||||
|
reduce(challenge.data());
|
||||||
|
|
||||||
|
scalarmult(p, q, challenge.data());
|
||||||
|
scalarbase(q, signature + 32);
|
||||||
|
point_add(p, q);
|
||||||
|
std::array<U8, 32> check{};
|
||||||
|
point_pack(check.data(), p);
|
||||||
|
const bool ok = verify_32(signature, check.data()) == 0;
|
||||||
|
wipe(challenge);
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
} // namespace Void::Crypto::Detail::Ed25519
|
||||||
@@ -789,6 +789,46 @@ namespace Void::Crypto::Detail
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void builtin_hmac_sha1(std::span<const std::byte> secret_key,
|
||||||
|
std::span<const std::byte> message,
|
||||||
|
std::span<std::byte> output_20) noexcept
|
||||||
|
{
|
||||||
|
std::array<std::byte, 64> key_block{};
|
||||||
|
if (secret_key.size() > 64) {
|
||||||
|
Sha1State kh;
|
||||||
|
kh.update(secret_key);
|
||||||
|
kh.finalize_into(std::span{key_block}.subspan(0, 20));
|
||||||
|
} else if (!secret_key.empty()) {
|
||||||
|
std::memcpy(key_block.data(), secret_key.data(), secret_key.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
std::array<std::byte, 64> ipad{};
|
||||||
|
std::array<std::byte, 64> opad{};
|
||||||
|
for (std::size_t i = 0; i < 64; ++i) {
|
||||||
|
ipad[i] = key_block[i] ^ std::byte{0x36};
|
||||||
|
opad[i] = key_block[i] ^ std::byte{0x5C};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::array<std::byte, 20> inner_hash{};
|
||||||
|
{
|
||||||
|
Sha1State inner;
|
||||||
|
inner.update(ipad);
|
||||||
|
inner.update(message);
|
||||||
|
inner.finalize_into(inner_hash);
|
||||||
|
}
|
||||||
|
{
|
||||||
|
Sha1State outer;
|
||||||
|
outer.update(opad);
|
||||||
|
outer.update(inner_hash);
|
||||||
|
outer.finalize_into(output_20);
|
||||||
|
}
|
||||||
|
|
||||||
|
builtin_secure_wipe(key_block);
|
||||||
|
builtin_secure_wipe(ipad);
|
||||||
|
builtin_secure_wipe(opad);
|
||||||
|
builtin_secure_wipe(inner_hash);
|
||||||
|
}
|
||||||
|
|
||||||
void builtin_hmac_sha256(std::span<const std::byte> secret_key,
|
void builtin_hmac_sha256(std::span<const std::byte> secret_key,
|
||||||
std::span<const std::byte> message,
|
std::span<const std::byte> message,
|
||||||
std::span<std::byte> output_32) noexcept
|
std::span<std::byte> output_32) noexcept
|
||||||
@@ -892,4 +932,95 @@ namespace Void::Crypto::Detail
|
|||||||
builtin_secure_wipe(t);
|
builtin_secure_wipe(t);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void builtin_pbkdf2_hmac_sha256(std::span<const std::byte> password,
|
||||||
|
std::span<const std::byte> salt,
|
||||||
|
std::uint32_t iterations,
|
||||||
|
std::span<std::byte> secret_output) noexcept
|
||||||
|
{
|
||||||
|
std::array<std::byte, 64> key_block{};
|
||||||
|
if (password.size() > 64) {
|
||||||
|
Sha256State kh;
|
||||||
|
kh.update(password);
|
||||||
|
kh.finalize_into(std::span{key_block}.subspan(0, 32));
|
||||||
|
} else if (!password.empty()) {
|
||||||
|
std::memcpy(key_block.data(), password.data(), password.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
std::array<std::byte, 64> ipad{};
|
||||||
|
std::array<std::byte, 64> opad{};
|
||||||
|
for (std::size_t i = 0; i < 64; ++i) {
|
||||||
|
ipad[i] = key_block[i] ^ std::byte{0x36};
|
||||||
|
opad[i] = key_block[i] ^ std::byte{0x5C};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto hmac = [&ipad, &opad](std::span<const std::byte> data,
|
||||||
|
std::span<std::byte> out) noexcept {
|
||||||
|
std::array<std::byte, 32> inner_hash{};
|
||||||
|
{
|
||||||
|
Sha256State inner;
|
||||||
|
inner.update(ipad);
|
||||||
|
inner.update(data);
|
||||||
|
inner.finalize_into(inner_hash);
|
||||||
|
}
|
||||||
|
{
|
||||||
|
Sha256State outer;
|
||||||
|
outer.update(opad);
|
||||||
|
outer.update(inner_hash);
|
||||||
|
outer.finalize_into(out);
|
||||||
|
}
|
||||||
|
builtin_secure_wipe(inner_hash);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Callers cap the output length, so this cannot overflow.
|
||||||
|
const std::size_t blocks = (secret_output.size() + 31) / 32;
|
||||||
|
std::size_t written = 0;
|
||||||
|
for (std::size_t block = 1; block <= blocks; ++block) {
|
||||||
|
std::array<std::byte, 4> counter{};
|
||||||
|
store_be32(counter.data(), static_cast<std::uint32_t>(block));
|
||||||
|
|
||||||
|
std::array<std::byte, 32> u{};
|
||||||
|
{
|
||||||
|
std::array<std::byte, 32> inner_hash{};
|
||||||
|
{
|
||||||
|
Sha256State inner;
|
||||||
|
inner.update(ipad);
|
||||||
|
inner.update(salt);
|
||||||
|
inner.update(counter);
|
||||||
|
inner.finalize_into(inner_hash);
|
||||||
|
}
|
||||||
|
{
|
||||||
|
Sha256State outer;
|
||||||
|
outer.update(opad);
|
||||||
|
outer.update(inner_hash);
|
||||||
|
outer.finalize_into(u);
|
||||||
|
}
|
||||||
|
builtin_secure_wipe(inner_hash);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::array<std::byte, 32> t = u;
|
||||||
|
for (std::uint32_t iteration = 1; iteration < iterations;
|
||||||
|
++iteration) {
|
||||||
|
std::array<std::byte, 32> next{};
|
||||||
|
hmac(u, next);
|
||||||
|
u = next;
|
||||||
|
for (std::size_t i = 0; i < t.size(); ++i) {
|
||||||
|
t[i] ^= u[i];
|
||||||
|
}
|
||||||
|
builtin_secure_wipe(next);
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::size_t copy_n =
|
||||||
|
std::min<std::size_t>(32, secret_output.size() - written);
|
||||||
|
std::memcpy(secret_output.data() + written, t.data(), copy_n);
|
||||||
|
written += copy_n;
|
||||||
|
|
||||||
|
builtin_secure_wipe(u);
|
||||||
|
builtin_secure_wipe(t);
|
||||||
|
}
|
||||||
|
|
||||||
|
builtin_secure_wipe(key_block);
|
||||||
|
builtin_secure_wipe(ipad);
|
||||||
|
builtin_secure_wipe(opad);
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace Void::Crypto::Detail
|
} // namespace Void::Crypto::Detail
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
#include <Void/Crypto/Types.hpp>
|
#include <Void/Crypto/Types.hpp>
|
||||||
|
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
#include <span>
|
#include <span>
|
||||||
|
|
||||||
namespace Void::Crypto::Detail
|
namespace Void::Crypto::Detail
|
||||||
@@ -37,10 +38,19 @@ namespace Void::Crypto::Detail
|
|||||||
void destroy() noexcept;
|
void destroy() noexcept;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
void builtin_hmac_sha1(std::span<const std::byte> secret_key,
|
||||||
|
std::span<const std::byte> message,
|
||||||
|
std::span<std::byte> output_20) noexcept;
|
||||||
|
|
||||||
void builtin_hmac_sha256(std::span<const std::byte> secret_key,
|
void builtin_hmac_sha256(std::span<const std::byte> secret_key,
|
||||||
std::span<const std::byte> message,
|
std::span<const std::byte> message,
|
||||||
std::span<std::byte> output_32) noexcept;
|
std::span<std::byte> output_32) noexcept;
|
||||||
|
|
||||||
|
void builtin_pbkdf2_hmac_sha256(std::span<const std::byte> password,
|
||||||
|
std::span<const std::byte> salt,
|
||||||
|
std::uint32_t iterations,
|
||||||
|
std::span<std::byte> secret_output) noexcept;
|
||||||
|
|
||||||
void builtin_hkdf_sha256(std::span<const std::byte> secret_input,
|
void builtin_hkdf_sha256(std::span<const std::byte> secret_input,
|
||||||
std::span<const std::byte> salt,
|
std::span<const std::byte> salt,
|
||||||
std::span<const std::byte> context,
|
std::span<const std::byte> context,
|
||||||
|
|||||||
+353
-68
@@ -1,7 +1,9 @@
|
|||||||
#include <Void/Crypto/Crypto.hpp>
|
#include <Void/Crypto/Crypto.hpp>
|
||||||
|
|
||||||
|
#include "BuiltinEd25519.hpp"
|
||||||
#include "BuiltinHash.hpp"
|
#include "BuiltinHash.hpp"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
#include <array>
|
#include <array>
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
@@ -9,6 +11,7 @@
|
|||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <limits>
|
#include <limits>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
|
#include <random>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||||
@@ -217,9 +220,138 @@ namespace Void::Crypto
|
|||||||
return result == 1;
|
return result == 1;
|
||||||
#else
|
#else
|
||||||
(void)provider;
|
(void)provider;
|
||||||
|
return Detail::Ed25519::verify(
|
||||||
|
reinterpret_cast<const std::uint8_t*>(public_key.data()),
|
||||||
|
reinterpret_cast<const std::uint8_t*>(signature.data()), message);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
[[maybe_unused]] [[nodiscard]] const char*
|
||||||
|
hmac_digest_name(HashAlgorithm algorithm) noexcept
|
||||||
|
{
|
||||||
|
switch (algorithm) {
|
||||||
|
case HashAlgorithm::Sha1:
|
||||||
|
return "SHA1";
|
||||||
|
case HashAlgorithm::Sha256:
|
||||||
|
return "SHA256";
|
||||||
|
default:
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
hmac_into_impl(HashAlgorithm algorithm,
|
||||||
|
std::span<const std::byte> secret_key,
|
||||||
|
std::span<const std::byte> message,
|
||||||
|
std::span<std::byte> output,
|
||||||
|
const ProviderOptions& provider,
|
||||||
|
std::string_view operation)
|
||||||
|
{
|
||||||
|
const std::size_t expected_size = algorithm == HashAlgorithm::Sha1
|
||||||
|
? HmacSha1Size
|
||||||
|
: HmacSha256Size;
|
||||||
|
if (output.size() != expected_size) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_crypto_error(CryptoErrorCode::invalid_argument,
|
||||||
|
std::format("{}: output must be {} bytes",
|
||||||
|
operation, expected_size))};
|
||||||
|
}
|
||||||
|
if (spans_overlap(secret_key, output) ||
|
||||||
|
spans_overlap(message, output)) {
|
||||||
|
return std::unexpected{make_crypto_error(
|
||||||
|
CryptoErrorCode::overlapping_buffers,
|
||||||
|
std::format("{}: output buffer overlaps input",
|
||||||
|
operation))};
|
||||||
|
}
|
||||||
|
if (auto fault =
|
||||||
|
maybe_inject_fault(FaultOperation::hmac, operation);
|
||||||
|
fault.has_value()) {
|
||||||
|
secure_wipe(output);
|
||||||
|
return std::unexpected{std::move(*fault)};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (use_builtin_hash(algorithm, provider)) {
|
||||||
|
if (!provider.property_query.empty()) {
|
||||||
|
secure_wipe(output);
|
||||||
|
return std::unexpected{make_crypto_error(
|
||||||
|
CryptoErrorCode::provider_error,
|
||||||
|
std::format("{}: property_query unavailable on "
|
||||||
|
"built-in backend",
|
||||||
|
operation))};
|
||||||
|
}
|
||||||
|
if (algorithm == HashAlgorithm::Sha1) {
|
||||||
|
Detail::builtin_hmac_sha1(secret_key, message, output);
|
||||||
|
} else {
|
||||||
|
Detail::builtin_hmac_sha256(secret_key, message, output);
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||||
|
const char* name = hmac_digest_name(algorithm);
|
||||||
|
if (name == nullptr) {
|
||||||
|
secure_wipe(output);
|
||||||
|
return std::unexpected{make_crypto_error(
|
||||||
|
CryptoErrorCode::unsupported_algorithm,
|
||||||
|
std::format("{}: unsupported HMAC algorithm", operation))};
|
||||||
|
}
|
||||||
|
ERR_clear_error();
|
||||||
|
EvpMacPtr mac{
|
||||||
|
EVP_MAC_fetch(nullptr, "HMAC", propq_or_null(provider)),
|
||||||
|
&EVP_MAC_free};
|
||||||
|
if (!mac) {
|
||||||
|
secure_wipe(output);
|
||||||
|
return std::unexpected{make_openssl_error(
|
||||||
|
CryptoErrorCode::provider_error,
|
||||||
|
std::format("{}: EVP_MAC_fetch failed", operation))};
|
||||||
|
}
|
||||||
|
EvpMacCtxPtr ctx{EVP_MAC_CTX_new(mac.get()), &EVP_MAC_CTX_free};
|
||||||
|
if (!ctx) {
|
||||||
|
secure_wipe(output);
|
||||||
|
return std::unexpected{make_openssl_error(
|
||||||
|
CryptoErrorCode::backend_error,
|
||||||
|
std::format("{}: EVP_MAC_CTX_new failed", operation))};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::array<char, 8> digest_name{};
|
||||||
|
std::strncpy(digest_name.data(), name, digest_name.size() - 1);
|
||||||
|
std::array<OSSL_PARAM, 2> params = {
|
||||||
|
OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
|
||||||
|
digest_name.data(), 0),
|
||||||
|
OSSL_PARAM_construct_end(),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (EVP_MAC_init(ctx.get(), non_null_bytes(secret_key),
|
||||||
|
secret_key.size(), params.data()) != 1) {
|
||||||
|
secure_wipe(output);
|
||||||
|
return std::unexpected{make_openssl_error(
|
||||||
|
CryptoErrorCode::provider_error,
|
||||||
|
std::format("{}: EVP_MAC_init failed", operation))};
|
||||||
|
}
|
||||||
|
if (!message.empty() &&
|
||||||
|
EVP_MAC_update(ctx.get(), non_null_bytes(message),
|
||||||
|
message.size()) != 1) {
|
||||||
|
secure_wipe(output);
|
||||||
|
return std::unexpected{make_openssl_error(
|
||||||
|
CryptoErrorCode::backend_error,
|
||||||
|
std::format("{}: EVP_MAC_update failed", operation))};
|
||||||
|
}
|
||||||
|
std::size_t out_len = 0;
|
||||||
|
if (EVP_MAC_final(ctx.get(),
|
||||||
|
reinterpret_cast<unsigned char*>(output.data()),
|
||||||
|
&out_len, output.size()) != 1 ||
|
||||||
|
out_len != expected_size) {
|
||||||
|
secure_wipe(output);
|
||||||
|
return std::unexpected{make_openssl_error(
|
||||||
|
CryptoErrorCode::backend_error,
|
||||||
|
std::format("{}: EVP_MAC_final failed", operation))};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
#else
|
||||||
|
secure_wipe(output);
|
||||||
return std::unexpected{make_crypto_error(
|
return std::unexpected{make_crypto_error(
|
||||||
CryptoErrorCode::unsupported_algorithm,
|
CryptoErrorCode::backend_error,
|
||||||
"Crypto::verifyEd25519: built without OpenSSL backend")};
|
std::format("{}: OpenSSL backend unavailable", operation))};
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
} // namespace
|
} // namespace
|
||||||
@@ -642,10 +774,27 @@ namespace Void::Crypto
|
|||||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||||
EvpPkeyPtr pkey{nullptr, &EVP_PKEY_free};
|
EvpPkeyPtr pkey{nullptr, &EVP_PKEY_free};
|
||||||
#else
|
#else
|
||||||
std::uint8_t unused{0};
|
std::array<std::byte, Ed25519SeedSize> seed{};
|
||||||
|
std::array<std::byte, Ed25519PublicKeySize> public_key{};
|
||||||
#endif
|
#endif
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#if !defined(VOID_CRYPTO_HAS_OPENSSL) || !VOID_CRYPTO_HAS_OPENSSL
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
void derive_ed25519_public_key(
|
||||||
|
const std::array<std::byte, Ed25519SeedSize>& seed,
|
||||||
|
std::array<std::byte, Ed25519PublicKeySize>& public_key)
|
||||||
|
{
|
||||||
|
Detail::Ed25519::Sha512 digest{};
|
||||||
|
Detail::Ed25519::expand_seed(
|
||||||
|
reinterpret_cast<const std::uint8_t*>(seed.data()), digest,
|
||||||
|
reinterpret_cast<std::uint8_t*>(public_key.data()));
|
||||||
|
Detail::Ed25519::wipe(digest);
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
#endif
|
||||||
|
|
||||||
Ed25519PrivateKey::Ed25519PrivateKey(std::unique_ptr<Impl> impl) noexcept
|
Ed25519PrivateKey::Ed25519PrivateKey(std::unique_ptr<Impl> impl) noexcept
|
||||||
: m_impl(std::move(impl))
|
: m_impl(std::move(impl))
|
||||||
{
|
{
|
||||||
@@ -661,7 +810,7 @@ namespace Void::Crypto
|
|||||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||||
return m_impl != nullptr && m_impl->pkey != nullptr;
|
return m_impl != nullptr && m_impl->pkey != nullptr;
|
||||||
#else
|
#else
|
||||||
return false;
|
return m_impl != nullptr;
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -693,10 +842,20 @@ namespace Void::Crypto
|
|||||||
return Ed25519PrivateKey{std::move(impl)};
|
return Ed25519PrivateKey{std::move(impl)};
|
||||||
#else
|
#else
|
||||||
(void)provider;
|
(void)provider;
|
||||||
return std::unexpected{make_crypto_error(
|
std::random_device random;
|
||||||
CryptoErrorCode::unsupported_algorithm,
|
std::array<std::byte, Ed25519SeedSize> seed{};
|
||||||
"Crypto::Ed25519PrivateKey::generate: built without OpenSSL "
|
for (std::size_t offset = 0; offset < seed.size();) {
|
||||||
"backend")};
|
const std::uint32_t word = random();
|
||||||
|
const std::size_t count =
|
||||||
|
std::min<std::size_t>(sizeof(word), seed.size() - offset);
|
||||||
|
std::memcpy(seed.data() + offset, &word, count);
|
||||||
|
offset += count;
|
||||||
|
}
|
||||||
|
auto impl = std::make_unique<Impl>();
|
||||||
|
impl->seed = seed;
|
||||||
|
derive_ed25519_public_key(impl->seed, impl->public_key);
|
||||||
|
secure_wipe(seed);
|
||||||
|
return Ed25519PrivateKey{std::move(impl)};
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -739,10 +898,10 @@ namespace Void::Crypto
|
|||||||
return Ed25519PrivateKey{std::move(impl)};
|
return Ed25519PrivateKey{std::move(impl)};
|
||||||
#else
|
#else
|
||||||
(void)provider;
|
(void)provider;
|
||||||
return std::unexpected{make_crypto_error(
|
auto impl = std::make_unique<Impl>();
|
||||||
CryptoErrorCode::unsupported_algorithm,
|
std::memcpy(impl->seed.data(), seed.data(), Ed25519SeedSize);
|
||||||
"Crypto::Ed25519PrivateKey::from_raw_seed: built without OpenSSL "
|
derive_ed25519_public_key(impl->seed, impl->public_key);
|
||||||
"backend")};
|
return Ed25519PrivateKey{std::move(impl)};
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -768,10 +927,10 @@ namespace Void::Crypto
|
|||||||
}
|
}
|
||||||
return pub;
|
return pub;
|
||||||
#else
|
#else
|
||||||
return std::unexpected{make_crypto_error(
|
Ed25519PublicKey pub;
|
||||||
CryptoErrorCode::unsupported_algorithm,
|
std::memcpy(pub.bytes.data(), m_impl->public_key.data(),
|
||||||
"Crypto::Ed25519PrivateKey::public_key: built without OpenSSL "
|
Ed25519PublicKeySize);
|
||||||
"backend")};
|
return pub;
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -799,10 +958,7 @@ namespace Void::Crypto
|
|||||||
secure_wipe(raw);
|
secure_wipe(raw);
|
||||||
return result;
|
return result;
|
||||||
#else
|
#else
|
||||||
return std::unexpected{make_crypto_error(
|
return Ed25519Seed::from_bytes(m_impl->seed);
|
||||||
CryptoErrorCode::unsupported_algorithm,
|
|
||||||
"Crypto::Ed25519PrivateKey::export_raw_seed: built without OpenSSL "
|
|
||||||
"backend")};
|
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -865,9 +1021,13 @@ namespace Void::Crypto
|
|||||||
return signature;
|
return signature;
|
||||||
#else
|
#else
|
||||||
(void)provider;
|
(void)provider;
|
||||||
return std::unexpected{make_crypto_error(
|
Ed25519Signature signature;
|
||||||
CryptoErrorCode::unsupported_algorithm,
|
Detail::Ed25519::sign(
|
||||||
"Crypto::sign_ed25519: built without OpenSSL backend")};
|
reinterpret_cast<const std::uint8_t*>(private_key.m_impl->seed.data()),
|
||||||
|
reinterpret_cast<const std::uint8_t*>(
|
||||||
|
private_key.m_impl->public_key.data()),
|
||||||
|
message, reinterpret_cast<std::uint8_t*>(signature.bytes.data()));
|
||||||
|
return signature;
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -891,26 +1051,146 @@ namespace Void::Crypto
|
|||||||
provider);
|
provider);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<Ed25519KeyPair>
|
||||||
|
ed25519_keypair(const ProviderOptions& provider)
|
||||||
|
{
|
||||||
|
auto private_key = Ed25519PrivateKey::generate(provider);
|
||||||
|
if (!private_key) {
|
||||||
|
return std::unexpected{std::move(private_key).error()};
|
||||||
|
}
|
||||||
|
auto public_key = private_key->public_key();
|
||||||
|
if (!public_key) {
|
||||||
|
return std::unexpected{std::move(public_key).error()};
|
||||||
|
}
|
||||||
|
auto secret_key = private_key->export_raw_seed();
|
||||||
|
if (!secret_key) {
|
||||||
|
return std::unexpected{std::move(secret_key).error()};
|
||||||
|
}
|
||||||
|
return Ed25519KeyPair{std::move(*secret_key), std::move(*public_key)};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<Ed25519Signature>
|
||||||
|
ed25519_sign(std::span<const std::byte> secret_key,
|
||||||
|
std::span<const std::byte> message,
|
||||||
|
const ProviderOptions& provider)
|
||||||
|
{
|
||||||
|
auto private_key = Ed25519PrivateKey::from_raw_seed(secret_key, provider);
|
||||||
|
if (!private_key) {
|
||||||
|
return std::unexpected{std::move(private_key).error()};
|
||||||
|
}
|
||||||
|
return sign_ed25519(message, *private_key, provider);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<bool>
|
||||||
|
ed25519_verify(std::span<const std::byte> public_key,
|
||||||
|
std::span<const std::byte> message,
|
||||||
|
std::span<const std::byte> signature,
|
||||||
|
const ProviderOptions& provider)
|
||||||
|
{
|
||||||
|
auto parsed_public_key = Ed25519PublicKey::from_bytes(public_key);
|
||||||
|
if (!parsed_public_key) {
|
||||||
|
return std::unexpected{std::move(parsed_public_key).error()};
|
||||||
|
}
|
||||||
|
auto parsed_signature = Ed25519Signature::from_bytes(signature);
|
||||||
|
if (!parsed_signature) {
|
||||||
|
return std::unexpected{std::move(parsed_signature).error()};
|
||||||
|
}
|
||||||
|
return verify_ed25519(message, *parsed_signature, *parsed_public_key,
|
||||||
|
provider);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void>
|
||||||
|
hmac_sha1_into(std::span<const std::byte> secret_key,
|
||||||
|
std::span<const std::byte>
|
||||||
|
message,
|
||||||
|
std::span<std::byte>
|
||||||
|
output,
|
||||||
|
const ProviderOptions& provider)
|
||||||
|
{
|
||||||
|
return hmac_into_impl(HashAlgorithm::Sha1, secret_key, message, output,
|
||||||
|
provider, "Crypto::hmac_sha1_into");
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<Digest>
|
||||||
|
hmac_sha1(std::span<const std::byte> secret_key,
|
||||||
|
std::span<const std::byte>
|
||||||
|
message,
|
||||||
|
const ProviderOptions& provider)
|
||||||
|
{
|
||||||
|
Digest out(HmacSha1Size);
|
||||||
|
if (auto res = hmac_sha1_into(secret_key, message, out, provider);
|
||||||
|
!res.has_value()) {
|
||||||
|
secure_wipe(out);
|
||||||
|
return std::unexpected{std::move(res.error())};
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
Void::Result::Result<void>
|
Void::Result::Result<void>
|
||||||
hmac_sha256_into(std::span<const std::byte> secret_key,
|
hmac_sha256_into(std::span<const std::byte> secret_key,
|
||||||
std::span<const std::byte> message,
|
std::span<const std::byte> message,
|
||||||
std::span<std::byte> output,
|
std::span<std::byte> output,
|
||||||
const ProviderOptions& provider)
|
const ProviderOptions& provider)
|
||||||
{
|
{
|
||||||
if (output.size() != HmacSha256Size) {
|
return hmac_into_impl(HashAlgorithm::Sha256, secret_key, message,
|
||||||
|
output, provider, "Crypto::hmac_sha256_into");
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<Digest> hmac_sha256(std::span<const std::byte> secret_key,
|
||||||
|
std::span<const std::byte> message,
|
||||||
|
const ProviderOptions& provider)
|
||||||
|
{
|
||||||
|
Digest out(HmacSha256Size);
|
||||||
|
if (auto res = hmac_sha256_into(secret_key, message, out, provider);
|
||||||
|
!res.has_value()) {
|
||||||
|
secure_wipe(out);
|
||||||
|
return std::unexpected{std::move(res.error())};
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void>
|
||||||
|
pbkdf2_hmac_sha256_into(std::span<const std::byte> password,
|
||||||
|
std::span<const std::byte> salt,
|
||||||
|
std::uint32_t iterations,
|
||||||
|
std::span<std::byte> output,
|
||||||
|
const ProviderOptions& provider)
|
||||||
|
{
|
||||||
|
if (iterations == 0 ||
|
||||||
|
iterations > CryptoLimits::kMaxPbkdf2Iterations) {
|
||||||
return std::unexpected{make_crypto_error(
|
return std::unexpected{make_crypto_error(
|
||||||
CryptoErrorCode::invalid_argument,
|
CryptoErrorCode::invalid_argument,
|
||||||
std::format("Crypto::hmac_sha256_into: output must be {} bytes",
|
std::format("Crypto::pbkdf2_hmac_sha256: iterations must be "
|
||||||
HmacSha256Size))};
|
"1..{}",
|
||||||
|
CryptoLimits::kMaxPbkdf2Iterations))};
|
||||||
}
|
}
|
||||||
if (spans_overlap(secret_key, output) ||
|
if (salt.size() > CryptoLimits::kMaxPbkdf2SaltBytes) {
|
||||||
spans_overlap(message, output)) {
|
return std::unexpected{make_crypto_error(
|
||||||
|
CryptoErrorCode::message_too_large,
|
||||||
|
std::format("Crypto::pbkdf2_hmac_sha256: salt exceeds {} byte "
|
||||||
|
"cap",
|
||||||
|
CryptoLimits::kMaxPbkdf2SaltBytes))};
|
||||||
|
}
|
||||||
|
if (output.empty()) {
|
||||||
|
return std::unexpected{make_crypto_error(
|
||||||
|
CryptoErrorCode::invalid_argument,
|
||||||
|
"Crypto::pbkdf2_hmac_sha256: output buffer must be non-empty")};
|
||||||
|
}
|
||||||
|
if (output.size() > CryptoLimits::kMaxPbkdf2OutputBytes) {
|
||||||
|
return std::unexpected{make_crypto_error(
|
||||||
|
CryptoErrorCode::output_too_large,
|
||||||
|
std::format(
|
||||||
|
"Crypto::pbkdf2_hmac_sha256: output size exceeds {} byte "
|
||||||
|
"cap",
|
||||||
|
CryptoLimits::kMaxPbkdf2OutputBytes))};
|
||||||
|
}
|
||||||
|
if (spans_overlap(password, output) || spans_overlap(salt, output)) {
|
||||||
return std::unexpected{make_crypto_error(
|
return std::unexpected{make_crypto_error(
|
||||||
CryptoErrorCode::overlapping_buffers,
|
CryptoErrorCode::overlapping_buffers,
|
||||||
"Crypto::hmac_sha256_into: output buffer overlaps input")};
|
"Crypto::pbkdf2_hmac_sha256: output buffer overlaps input")};
|
||||||
}
|
}
|
||||||
if (auto fault = maybe_inject_fault(FaultOperation::hmac,
|
if (auto fault = maybe_inject_fault(FaultOperation::pbkdf2,
|
||||||
"Crypto::hmac_sha256_into");
|
"Crypto::pbkdf2_hmac_sha256");
|
||||||
fault.has_value()) {
|
fault.has_value()) {
|
||||||
secure_wipe(output);
|
secure_wipe(output);
|
||||||
return std::unexpected{std::move(*fault)};
|
return std::unexpected{std::move(*fault)};
|
||||||
@@ -921,78 +1201,83 @@ namespace Void::Crypto
|
|||||||
secure_wipe(output);
|
secure_wipe(output);
|
||||||
return std::unexpected{make_crypto_error(
|
return std::unexpected{make_crypto_error(
|
||||||
CryptoErrorCode::provider_error,
|
CryptoErrorCode::provider_error,
|
||||||
"Crypto::hmac_sha256_into: property_query unavailable on "
|
"Crypto::pbkdf2_hmac_sha256: property_query unavailable on "
|
||||||
"built-in backend")};
|
"built-in backend")};
|
||||||
}
|
}
|
||||||
Detail::builtin_hmac_sha256(secret_key, message, output);
|
Detail::builtin_pbkdf2_hmac_sha256(password, salt, iterations,
|
||||||
|
output);
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||||
ERR_clear_error();
|
ERR_clear_error();
|
||||||
EvpMacPtr mac{EVP_MAC_fetch(nullptr, "HMAC", propq_or_null(provider)),
|
EvpKdfPtr kdf{EVP_KDF_fetch(nullptr, "PBKDF2", propq_or_null(provider)),
|
||||||
&EVP_MAC_free};
|
&EVP_KDF_free};
|
||||||
if (!mac) {
|
if (!kdf) {
|
||||||
secure_wipe(output);
|
secure_wipe(output);
|
||||||
return std::unexpected{make_openssl_error(
|
return std::unexpected{make_openssl_error(
|
||||||
CryptoErrorCode::provider_error,
|
CryptoErrorCode::provider_error,
|
||||||
"Crypto::hmac_sha256_into: EVP_MAC_fetch failed")};
|
"Crypto::pbkdf2_hmac_sha256: EVP_KDF_fetch failed")};
|
||||||
}
|
}
|
||||||
EvpMacCtxPtr ctx{EVP_MAC_CTX_new(mac.get()), &EVP_MAC_CTX_free};
|
EvpKdfCtxPtr ctx{EVP_KDF_CTX_new(kdf.get()), &EVP_KDF_CTX_free};
|
||||||
if (!ctx) {
|
if (!ctx) {
|
||||||
secure_wipe(output);
|
secure_wipe(output);
|
||||||
return std::unexpected{make_openssl_error(
|
return std::unexpected{make_openssl_error(
|
||||||
CryptoErrorCode::backend_error,
|
CryptoErrorCode::backend_error,
|
||||||
"Crypto::hmac_sha256_into: EVP_MAC_CTX_new failed")};
|
"Crypto::pbkdf2_hmac_sha256: EVP_KDF_CTX_new failed")};
|
||||||
}
|
}
|
||||||
|
|
||||||
char digest_name[] = "SHA256";
|
char digest_name[] = "SHA256";
|
||||||
std::array<OSSL_PARAM, 2> params = {
|
int iteration_count = static_cast<int>(iterations);
|
||||||
OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, digest_name,
|
std::array<OSSL_PARAM, 5> params = {
|
||||||
|
OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, digest_name,
|
||||||
0),
|
0),
|
||||||
|
OSSL_PARAM_construct_octet_string(
|
||||||
|
OSSL_KDF_PARAM_PASSWORD,
|
||||||
|
const_cast<unsigned char*>(non_null_bytes(password)),
|
||||||
|
password.size()),
|
||||||
|
OSSL_PARAM_construct_octet_string(
|
||||||
|
OSSL_KDF_PARAM_SALT,
|
||||||
|
const_cast<unsigned char*>(non_null_bytes(salt)), salt.size()),
|
||||||
|
OSSL_PARAM_construct_int(OSSL_KDF_PARAM_ITER, &iteration_count),
|
||||||
OSSL_PARAM_construct_end(),
|
OSSL_PARAM_construct_end(),
|
||||||
};
|
};
|
||||||
|
|
||||||
if (EVP_MAC_init(ctx.get(), non_null_bytes(secret_key),
|
if (EVP_KDF_derive(ctx.get(),
|
||||||
secret_key.size(), params.data()) != 1) {
|
reinterpret_cast<unsigned char*>(output.data()),
|
||||||
secure_wipe(output);
|
output.size(), params.data()) != 1) {
|
||||||
return std::unexpected{make_openssl_error(
|
|
||||||
CryptoErrorCode::provider_error,
|
|
||||||
"Crypto::hmac_sha256_into: EVP_MAC_init failed")};
|
|
||||||
}
|
|
||||||
if (!message.empty() &&
|
|
||||||
EVP_MAC_update(ctx.get(), non_null_bytes(message),
|
|
||||||
message.size()) != 1) {
|
|
||||||
secure_wipe(output);
|
secure_wipe(output);
|
||||||
return std::unexpected{make_openssl_error(
|
return std::unexpected{make_openssl_error(
|
||||||
CryptoErrorCode::backend_error,
|
CryptoErrorCode::backend_error,
|
||||||
"Crypto::hmac_sha256_into: EVP_MAC_update failed")};
|
"Crypto::pbkdf2_hmac_sha256: EVP_KDF_derive failed")};
|
||||||
}
|
|
||||||
std::size_t out_len = 0;
|
|
||||||
if (EVP_MAC_final(ctx.get(),
|
|
||||||
reinterpret_cast<unsigned char*>(output.data()),
|
|
||||||
&out_len, output.size()) != 1 ||
|
|
||||||
out_len != HmacSha256Size) {
|
|
||||||
secure_wipe(output);
|
|
||||||
return std::unexpected{make_openssl_error(
|
|
||||||
CryptoErrorCode::backend_error,
|
|
||||||
"Crypto::hmac_sha256_into: EVP_MAC_final failed")};
|
|
||||||
}
|
}
|
||||||
return {};
|
return {};
|
||||||
#else
|
#else
|
||||||
secure_wipe(output);
|
secure_wipe(output);
|
||||||
return std::unexpected{make_crypto_error(
|
return std::unexpected{make_crypto_error(
|
||||||
CryptoErrorCode::backend_error,
|
CryptoErrorCode::backend_error,
|
||||||
"Crypto::hmac_sha256_into: OpenSSL backend unavailable")};
|
"Crypto::pbkdf2_hmac_sha256: OpenSSL backend unavailable")};
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Result::Result<Digest> hmac_sha256(std::span<const std::byte> secret_key,
|
Void::Result::Result<Digest>
|
||||||
std::span<const std::byte> message,
|
pbkdf2_hmac_sha256(std::span<const std::byte> password,
|
||||||
const ProviderOptions& provider)
|
std::span<const std::byte> salt,
|
||||||
|
std::uint32_t iterations,
|
||||||
|
std::size_t output_length,
|
||||||
|
const ProviderOptions& provider)
|
||||||
{
|
{
|
||||||
Digest out(HmacSha256Size);
|
if (output_length > CryptoLimits::kMaxPbkdf2OutputBytes) {
|
||||||
if (auto res = hmac_sha256_into(secret_key, message, out, provider);
|
return std::unexpected{make_crypto_error(
|
||||||
|
CryptoErrorCode::output_too_large,
|
||||||
|
std::format(
|
||||||
|
"Crypto::pbkdf2_hmac_sha256: output size exceeds {} byte "
|
||||||
|
"cap",
|
||||||
|
CryptoLimits::kMaxPbkdf2OutputBytes))};
|
||||||
|
}
|
||||||
|
Digest out(output_length);
|
||||||
|
if (auto res = pbkdf2_hmac_sha256_into(password, salt, iterations, out,
|
||||||
|
provider);
|
||||||
!res.has_value()) {
|
!res.has_value()) {
|
||||||
secure_wipe(out);
|
secure_wipe(out);
|
||||||
return std::unexpected{std::move(res.error())};
|
return std::unexpected{std::move(res.error())};
|
||||||
|
|||||||
+877
-2
@@ -33,6 +33,19 @@
|
|||||||
#include <sys/socket.h>
|
#include <sys/socket.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
#ifndef WIN32_LEAN_AND_MEAN
|
||||||
|
#define WIN32_LEAN_AND_MEAN
|
||||||
|
#endif
|
||||||
|
#ifndef FD_SETSIZE
|
||||||
|
#define FD_SETSIZE 1024
|
||||||
|
#endif
|
||||||
|
#include <winsock2.h>
|
||||||
|
#include <ws2tcpip.h>
|
||||||
|
#include <windows.h>
|
||||||
|
#include <io.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
namespace Void::IO::detail
|
namespace Void::IO::detail
|
||||||
{
|
{
|
||||||
|
|
||||||
@@ -2814,7 +2827,861 @@ private:
|
|||||||
int wake_fd_{-1};
|
int wake_fd_{-1};
|
||||||
std::atomic<bool> wake_closed_{false};
|
std::atomic<bool> wake_closed_{false};
|
||||||
};
|
};
|
||||||
#endif // __linux__
|
|
||||||
|
#elif defined(_WIN32)
|
||||||
|
// ── Windows portable poll (select) backend ─────────────────────────────
|
||||||
|
//
|
||||||
|
// IOCP would require a full overlapped-operation rewrite of the driver.
|
||||||
|
// Instead this backend keeps the shared BaseBackend operation machinery and
|
||||||
|
// uses Winsock select() for readiness. Streams must be sockets (or CRT fds
|
||||||
|
// for blocking _read/_write); positional files use the shared worker pool.
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
[[nodiscard]] std::error_code win_error_code(int err) noexcept
|
||||||
|
{
|
||||||
|
return std::error_code{err, std::system_category()};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool ensure_winsock() noexcept
|
||||||
|
{
|
||||||
|
static const bool ready = [] {
|
||||||
|
WSADATA data{};
|
||||||
|
return ::WSAStartup(MAKEWORD(2, 2), &data) == 0;
|
||||||
|
}();
|
||||||
|
return ready;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] SOCKET socket_from_fd(int fd) noexcept
|
||||||
|
{
|
||||||
|
return static_cast<SOCKET>(static_cast<std::uintptr_t>(
|
||||||
|
static_cast<std::uint32_t>(fd)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] int fd_from_socket(SOCKET socket) noexcept
|
||||||
|
{
|
||||||
|
return static_cast<int>(static_cast<std::uint32_t>(socket));
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool is_socket_fd(SOCKET socket) noexcept
|
||||||
|
{
|
||||||
|
int type = 0;
|
||||||
|
int length = sizeof(type);
|
||||||
|
return ::getsockopt(socket, SOL_SOCKET, SO_TYPE,
|
||||||
|
reinterpret_cast<char*>(&type), &length) == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool set_nonblocking(SOCKET socket) noexcept
|
||||||
|
{
|
||||||
|
u_long mode = 1;
|
||||||
|
return ::ioctlsocket(socket, FIONBIO, &mode) == 0;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
class SelectBackend final : public BaseBackend
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
static Void::Result::Result<std::shared_ptr<SelectBackend>> create_select(
|
||||||
|
Async::Executor& executor,
|
||||||
|
IoLimits limits,
|
||||||
|
const Void::Time::MonotonicClock& clock,
|
||||||
|
std::shared_ptr<OwnedBufferTracker> buffer_tracker,
|
||||||
|
FileSyscalls* file_syscalls,
|
||||||
|
std::function<Void::Result::Result<void>(std::size_t)> worker_hook)
|
||||||
|
{
|
||||||
|
if (!ensure_winsock()) {
|
||||||
|
return std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::os_error, "WSAStartup failed",
|
||||||
|
win_error_code(::WSAGetLastError()))};
|
||||||
|
}
|
||||||
|
const SOCKET wake_recv = ::socket(AF_INET, SOCK_DGRAM, 0);
|
||||||
|
if (wake_recv == INVALID_SOCKET) {
|
||||||
|
return std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::os_error, "wake socket failed",
|
||||||
|
win_error_code(::WSAGetLastError()))};
|
||||||
|
}
|
||||||
|
sockaddr_in address{};
|
||||||
|
address.sin_family = AF_INET;
|
||||||
|
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||||
|
address.sin_port = 0;
|
||||||
|
if (::bind(wake_recv, reinterpret_cast<sockaddr*>(&address),
|
||||||
|
sizeof(address)) == SOCKET_ERROR) {
|
||||||
|
const int err = ::WSAGetLastError();
|
||||||
|
::closesocket(wake_recv);
|
||||||
|
return std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::os_error, "wake bind failed",
|
||||||
|
win_error_code(err))};
|
||||||
|
}
|
||||||
|
int length = sizeof(address);
|
||||||
|
if (::getsockname(wake_recv, reinterpret_cast<sockaddr*>(&address),
|
||||||
|
&length) == SOCKET_ERROR) {
|
||||||
|
const int err = ::WSAGetLastError();
|
||||||
|
::closesocket(wake_recv);
|
||||||
|
return std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::os_error, "wake getsockname failed",
|
||||||
|
win_error_code(err))};
|
||||||
|
}
|
||||||
|
const SOCKET wake_send = ::socket(AF_INET, SOCK_DGRAM, 0);
|
||||||
|
if (wake_send == INVALID_SOCKET ||
|
||||||
|
::connect(wake_send, reinterpret_cast<sockaddr*>(&address),
|
||||||
|
sizeof(address)) == SOCKET_ERROR ||
|
||||||
|
!set_nonblocking(wake_recv) || !set_nonblocking(wake_send)) {
|
||||||
|
const int err = ::WSAGetLastError();
|
||||||
|
if (wake_send != INVALID_SOCKET) {
|
||||||
|
::closesocket(wake_send);
|
||||||
|
}
|
||||||
|
::closesocket(wake_recv);
|
||||||
|
return std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::os_error, "wake socket setup failed",
|
||||||
|
win_error_code(err))};
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return std::shared_ptr<SelectBackend>(new SelectBackend(
|
||||||
|
executor, limits, clock, std::move(buffer_tracker),
|
||||||
|
file_syscalls, std::move(worker_hook), wake_recv, wake_send));
|
||||||
|
} catch (...) {
|
||||||
|
::closesocket(wake_send);
|
||||||
|
::closesocket(wake_recv);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
~SelectBackend() override
|
||||||
|
{
|
||||||
|
for (auto& slot : slots_) {
|
||||||
|
if (slot.in_use && !slot.is_file && slot.fd >= 0) {
|
||||||
|
::closesocket(socket_from_fd(slot.fd));
|
||||||
|
slot.fd = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (wake_send_ != INVALID_SOCKET) {
|
||||||
|
::closesocket(wake_send_);
|
||||||
|
wake_send_ = INVALID_SOCKET;
|
||||||
|
}
|
||||||
|
if (wake_recv_ != INVALID_SOCKET) {
|
||||||
|
::closesocket(wake_recv_);
|
||||||
|
wake_recv_ = INVALID_SOCKET;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] BackendPreference kind() const noexcept override
|
||||||
|
{
|
||||||
|
return BackendPreference::epoll;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::shared_ptr<StreamState>>
|
||||||
|
create_mock_stream() override
|
||||||
|
{
|
||||||
|
return std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::unsupported,
|
||||||
|
"SelectBackend does not create mock streams")};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::shared_ptr<StreamState>>
|
||||||
|
adopt_fd(int fd) override
|
||||||
|
{
|
||||||
|
if (fd < 0) {
|
||||||
|
return std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::invalid_argument,
|
||||||
|
"Invalid negative fd in adopt_fd")};
|
||||||
|
}
|
||||||
|
const SOCKET socket = socket_from_fd(fd);
|
||||||
|
if (!is_socket_fd(socket)) {
|
||||||
|
return std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::unsupported,
|
||||||
|
"Windows poll backend adopts sockets only")};
|
||||||
|
}
|
||||||
|
(void)set_nonblocking(socket);
|
||||||
|
DescriptorId id;
|
||||||
|
{
|
||||||
|
std::lock_guard lk{mu_};
|
||||||
|
if (control_queue_.size() >= limits_.max_control_submissions) {
|
||||||
|
return std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::overloaded, "IO Driver control queue full")};
|
||||||
|
}
|
||||||
|
auto res = allocate_slot_locked(fd);
|
||||||
|
if (!res.has_value()) {
|
||||||
|
return std::unexpected{std::move(res.error())};
|
||||||
|
}
|
||||||
|
id = *res;
|
||||||
|
control_queue_.push_back(
|
||||||
|
ControlAction{ControlAction::Type::register_fd, id});
|
||||||
|
}
|
||||||
|
wake();
|
||||||
|
return std::make_shared<StreamState>(this->shared_from_this(), id);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<
|
||||||
|
std::pair<std::shared_ptr<StreamState>, std::shared_ptr<StreamState>>>
|
||||||
|
create_socket_pair() override
|
||||||
|
{
|
||||||
|
const SOCKET listener = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||||
|
if (listener == INVALID_SOCKET) {
|
||||||
|
return std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::os_error, "socketpair listener failed",
|
||||||
|
win_error_code(::WSAGetLastError()))};
|
||||||
|
}
|
||||||
|
sockaddr_in address{};
|
||||||
|
address.sin_family = AF_INET;
|
||||||
|
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||||
|
address.sin_port = 0;
|
||||||
|
if (::bind(listener, reinterpret_cast<sockaddr*>(&address),
|
||||||
|
sizeof(address)) == SOCKET_ERROR ||
|
||||||
|
::listen(listener, 1) == SOCKET_ERROR) {
|
||||||
|
const int err = ::WSAGetLastError();
|
||||||
|
::closesocket(listener);
|
||||||
|
return std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::os_error, "socketpair bind/listen failed",
|
||||||
|
win_error_code(err))};
|
||||||
|
}
|
||||||
|
int length = sizeof(address);
|
||||||
|
(void)::getsockname(listener, reinterpret_cast<sockaddr*>(&address),
|
||||||
|
&length);
|
||||||
|
const SOCKET client = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||||
|
if (client == INVALID_SOCKET ||
|
||||||
|
::connect(client, reinterpret_cast<sockaddr*>(&address),
|
||||||
|
sizeof(address)) == SOCKET_ERROR) {
|
||||||
|
const int err = ::WSAGetLastError();
|
||||||
|
if (client != INVALID_SOCKET) {
|
||||||
|
::closesocket(client);
|
||||||
|
}
|
||||||
|
::closesocket(listener);
|
||||||
|
return std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::os_error, "socketpair connect failed",
|
||||||
|
win_error_code(err))};
|
||||||
|
}
|
||||||
|
const SOCKET server = ::accept(listener, nullptr, nullptr);
|
||||||
|
::closesocket(listener);
|
||||||
|
if (server == INVALID_SOCKET) {
|
||||||
|
const int err = ::WSAGetLastError();
|
||||||
|
::closesocket(client);
|
||||||
|
return std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::os_error, "socketpair accept failed",
|
||||||
|
win_error_code(err))};
|
||||||
|
}
|
||||||
|
(void)set_nonblocking(client);
|
||||||
|
(void)set_nonblocking(server);
|
||||||
|
auto first = adopt_fd(fd_from_socket(client));
|
||||||
|
if (!first.has_value()) {
|
||||||
|
::closesocket(client);
|
||||||
|
::closesocket(server);
|
||||||
|
return std::unexpected{std::move(first.error())};
|
||||||
|
}
|
||||||
|
auto second = adopt_fd(fd_from_socket(server));
|
||||||
|
if (!second.has_value()) {
|
||||||
|
on_stream_destroyed((*first)->id());
|
||||||
|
::closesocket(server);
|
||||||
|
return std::unexpected{std::move(second.error())};
|
||||||
|
}
|
||||||
|
return std::make_pair(std::move(*first), std::move(*second));
|
||||||
|
}
|
||||||
|
|
||||||
|
void wake() noexcept override
|
||||||
|
{
|
||||||
|
if (wake_closed_.load(std::memory_order_acquire)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
wakeups_.fetch_add(1, std::memory_order_acq_rel);
|
||||||
|
const char byte = 1;
|
||||||
|
(void)::send(wake_send_, &byte, 1, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected:
|
||||||
|
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||||
|
run_turn(std::optional<std::chrono::nanoseconds> max_wait) override
|
||||||
|
{
|
||||||
|
std::size_t work_done = 0;
|
||||||
|
std::vector<Async::ResumeTicket> tickets;
|
||||||
|
|
||||||
|
work_done += process_cancels_and_controls(tickets);
|
||||||
|
work_done += drain_file_completions(tickets);
|
||||||
|
work_done += scan_close_waiters(std::nullopt, tickets);
|
||||||
|
if (shutdown_begun_.load(std::memory_order_acquire)) {
|
||||||
|
work_done += abort_pending_socket_ops(tickets);
|
||||||
|
}
|
||||||
|
if (file_deadlines_pending()) {
|
||||||
|
const auto now = clock_.now();
|
||||||
|
work_done += expire_file_work_at(now, tickets);
|
||||||
|
work_done += drain_file_completions(tickets);
|
||||||
|
}
|
||||||
|
dispatch_tickets(tickets);
|
||||||
|
|
||||||
|
int timeout_ms = 0;
|
||||||
|
{
|
||||||
|
std::optional<Void::Time::MonotonicClock::time_point> earliest;
|
||||||
|
{
|
||||||
|
std::lock_guard lk{mu_};
|
||||||
|
for (const auto& slot : slots_) {
|
||||||
|
if (!slot.in_use) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const auto* op : {&slot.active_read, &slot.active_write}) {
|
||||||
|
if (*op && (*op)->deadline.has_value()) {
|
||||||
|
if (!earliest.has_value() || *(*op)->deadline < *earliest) {
|
||||||
|
earliest = *(*op)->deadline;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (const auto fdl = earliest_file_deadline(); fdl.has_value()) {
|
||||||
|
if (!earliest.has_value() || *fdl < *earliest) {
|
||||||
|
earliest = fdl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (max_wait.has_value()) {
|
||||||
|
auto wait_ns = *max_wait;
|
||||||
|
if (earliest.has_value()) {
|
||||||
|
const auto rem = Void::Time::remaining_until(clock_, *earliest);
|
||||||
|
if (rem < wait_ns) {
|
||||||
|
wait_ns = rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (wait_ns.count() <= 0) {
|
||||||
|
timeout_ms = 0;
|
||||||
|
} else {
|
||||||
|
const auto ms =
|
||||||
|
std::chrono::duration_cast<std::chrono::milliseconds>(wait_ns).count();
|
||||||
|
timeout_ms = static_cast<int>(
|
||||||
|
std::clamp<long long>(ms == 0 ? 1 : ms, 0, 5000));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (earliest.has_value()) {
|
||||||
|
const auto rem = Void::Time::remaining_until(clock_, *earliest);
|
||||||
|
const auto ms =
|
||||||
|
std::chrono::duration_cast<std::chrono::milliseconds>(rem).count();
|
||||||
|
timeout_ms = static_cast<int>(
|
||||||
|
std::clamp<long long>((rem.count() > 0 && ms == 0) ? 1 : ms, 0, 5000));
|
||||||
|
} else {
|
||||||
|
timeout_ms = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct PollEntry {
|
||||||
|
std::uint32_t slot{};
|
||||||
|
std::uint32_t generation{};
|
||||||
|
int fd{-1};
|
||||||
|
bool want_read{false};
|
||||||
|
bool want_write{false};
|
||||||
|
};
|
||||||
|
std::vector<PollEntry> entries;
|
||||||
|
fd_set read_set;
|
||||||
|
fd_set write_set;
|
||||||
|
fd_set error_set;
|
||||||
|
FD_ZERO(&read_set);
|
||||||
|
FD_ZERO(&write_set);
|
||||||
|
FD_ZERO(&error_set);
|
||||||
|
FD_SET(wake_recv_, &read_set);
|
||||||
|
{
|
||||||
|
std::lock_guard lk{mu_};
|
||||||
|
for (std::uint32_t index = 0; index < slots_.size(); ++index) {
|
||||||
|
auto& slot = slots_[index];
|
||||||
|
if (!slot.in_use || slot.is_file || slot.fd < 0 || slot.closing) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const bool want_read =
|
||||||
|
slot.active_read != nullptr && !slot.active_read->retired;
|
||||||
|
const bool want_write =
|
||||||
|
slot.active_write != nullptr && !slot.active_write->retired;
|
||||||
|
if (!want_read && !want_write) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (entries.size() + 1 >= static_cast<std::size_t>(FD_SETSIZE)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const SOCKET socket = socket_from_fd(slot.fd);
|
||||||
|
if (want_read) {
|
||||||
|
FD_SET(socket, &read_set);
|
||||||
|
}
|
||||||
|
if (want_write) {
|
||||||
|
FD_SET(socket, &write_set);
|
||||||
|
}
|
||||||
|
FD_SET(socket, &error_set);
|
||||||
|
entries.push_back(PollEntry{index, slot.id.generation, slot.fd,
|
||||||
|
want_read, want_write});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
timeval wait{};
|
||||||
|
timeval* wait_ptr = nullptr;
|
||||||
|
if (timeout_ms >= 0) {
|
||||||
|
wait.tv_sec = timeout_ms / 1000;
|
||||||
|
wait.tv_usec = (timeout_ms % 1000) * 1000;
|
||||||
|
wait_ptr = &wait;
|
||||||
|
} else if (shutdown_begun_.load(std::memory_order_acquire)) {
|
||||||
|
// Never block an unbounded shutdown slice on a lost wake.
|
||||||
|
wait.tv_sec = 0;
|
||||||
|
wait.tv_usec = 10000;
|
||||||
|
wait_ptr = &wait;
|
||||||
|
}
|
||||||
|
const int ready = ::select(0, &read_set, &write_set, &error_set, wait_ptr);
|
||||||
|
if (ready == SOCKET_ERROR) {
|
||||||
|
const int err = ::WSAGetLastError();
|
||||||
|
if (err == WSAEINTR) {
|
||||||
|
return work_done;
|
||||||
|
}
|
||||||
|
return std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::os_error, "select failed", win_error_code(err))};
|
||||||
|
}
|
||||||
|
if (FD_ISSET(wake_recv_, &read_set)) {
|
||||||
|
drain_wake();
|
||||||
|
}
|
||||||
|
for (const auto& entry : entries) {
|
||||||
|
const SOCKET socket = socket_from_fd(entry.fd);
|
||||||
|
std::uint32_t mask = 0;
|
||||||
|
if (entry.want_read && FD_ISSET(socket, &read_set)) {
|
||||||
|
mask |= kIn | kHup;
|
||||||
|
}
|
||||||
|
if (entry.want_write && FD_ISSET(socket, &write_set)) {
|
||||||
|
mask |= kOut;
|
||||||
|
}
|
||||||
|
if (FD_ISSET(socket, &error_set)) {
|
||||||
|
mask |= kErr | kHup;
|
||||||
|
}
|
||||||
|
if (mask == 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
std::shared_ptr<PendingOp> read_op;
|
||||||
|
std::shared_ptr<PendingOp> write_op;
|
||||||
|
{
|
||||||
|
std::lock_guard lk{mu_};
|
||||||
|
if (entry.slot >= slots_.size() || !slots_[entry.slot].in_use ||
|
||||||
|
slots_[entry.slot].is_file ||
|
||||||
|
slots_[entry.slot].id.generation != entry.generation ||
|
||||||
|
slots_[entry.slot].fd < 0 || slots_[entry.slot].closing) {
|
||||||
|
stale_events_ignored_.fetch_add(1, std::memory_order_acq_rel);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ((mask & (kIn | kHup | kErr)) != 0 &&
|
||||||
|
slots_[entry.slot].active_read &&
|
||||||
|
!slots_[entry.slot].active_read->retired) {
|
||||||
|
read_op = slots_[entry.slot].active_read;
|
||||||
|
}
|
||||||
|
if ((mask & (kOut | kHup | kErr)) != 0 &&
|
||||||
|
slots_[entry.slot].active_write &&
|
||||||
|
!slots_[entry.slot].active_write->retired) {
|
||||||
|
write_op = slots_[entry.slot].active_write;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (read_op) {
|
||||||
|
work_done += drive_read(entry.slot, entry.generation, entry.fd,
|
||||||
|
mask, read_op, tickets);
|
||||||
|
}
|
||||||
|
if (write_op) {
|
||||||
|
work_done += drive_write(entry.slot, entry.generation, entry.fd,
|
||||||
|
mask, write_op, tickets);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
work_done += process_cancels_and_controls(tickets);
|
||||||
|
work_done += drain_file_completions(tickets);
|
||||||
|
work_done += scan_close_waiters(std::nullopt, tickets);
|
||||||
|
work_done += expire_deadlines(tickets);
|
||||||
|
if (file_deadlines_pending()) {
|
||||||
|
const auto now = clock_.now();
|
||||||
|
work_done += expire_file_work_at(now, tickets);
|
||||||
|
work_done += drain_file_completions(tickets);
|
||||||
|
}
|
||||||
|
dispatch_tickets(tickets);
|
||||||
|
return work_done;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t drain_socket_queues(std::vector<Async::ResumeTicket>& tickets) override
|
||||||
|
{
|
||||||
|
drain_wake();
|
||||||
|
return process_cancels_and_controls(tickets);
|
||||||
|
}
|
||||||
|
|
||||||
|
void on_slot_abort_locked(DescriptorSlot& slot) noexcept override
|
||||||
|
{
|
||||||
|
slot.epoll_registered = false;
|
||||||
|
slot.epoll_in_armed = false;
|
||||||
|
slot.epoll_out_armed = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void on_op_retired_locked(DescriptorSlot&) noexcept override {}
|
||||||
|
|
||||||
|
[[nodiscard]] bool closes_native_fds() const noexcept override { return true; }
|
||||||
|
|
||||||
|
void on_slot_final_close_locked(DescriptorSlot& slot) noexcept override
|
||||||
|
{
|
||||||
|
if (slot.fd >= 0) {
|
||||||
|
::closesocket(socket_from_fd(slot.fd));
|
||||||
|
slot.fd = -1;
|
||||||
|
}
|
||||||
|
on_slot_abort_locked(slot);
|
||||||
|
}
|
||||||
|
|
||||||
|
void on_shutdown_complete() noexcept override
|
||||||
|
{
|
||||||
|
wake_closed_.store(true, std::memory_order_release);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
on_op_submitted_locked(DescriptorSlot&, Direction,
|
||||||
|
const std::shared_ptr<PendingOp>&) override
|
||||||
|
{
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
static constexpr std::uint32_t kIn = 0x0001;
|
||||||
|
static constexpr std::uint32_t kOut = 0x0004;
|
||||||
|
static constexpr std::uint32_t kErr = 0x0008;
|
||||||
|
static constexpr std::uint32_t kHup = 0x0010;
|
||||||
|
|
||||||
|
SelectBackend(Async::Executor& executor,
|
||||||
|
IoLimits limits,
|
||||||
|
const Void::Time::MonotonicClock& clock,
|
||||||
|
std::shared_ptr<OwnedBufferTracker> buffer_tracker,
|
||||||
|
FileSyscalls* file_syscalls,
|
||||||
|
std::function<Void::Result::Result<void>(std::size_t)> worker_hook,
|
||||||
|
SOCKET wake_recv,
|
||||||
|
SOCKET wake_send)
|
||||||
|
: BaseBackend(executor, limits, clock, std::move(buffer_tracker),
|
||||||
|
file_syscalls, std::move(worker_hook))
|
||||||
|
, wake_recv_(wake_recv)
|
||||||
|
, wake_send_(wake_send)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
void drain_wake() noexcept
|
||||||
|
{
|
||||||
|
char buffer[64];
|
||||||
|
while (::recv(wake_recv_, buffer, sizeof(buffer), 0) > 0) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t process_cancels_and_controls(
|
||||||
|
std::vector<Async::ResumeTicket>& tickets)
|
||||||
|
{
|
||||||
|
std::size_t done = 0;
|
||||||
|
std::vector<std::shared_ptr<PendingOp>> cancels;
|
||||||
|
std::vector<ControlAction> controls;
|
||||||
|
std::vector<CloseWaiter> close_waiters;
|
||||||
|
{
|
||||||
|
std::lock_guard lk{mu_};
|
||||||
|
cancels.swap(cancel_queue_);
|
||||||
|
controls.swap(control_queue_);
|
||||||
|
}
|
||||||
|
for (const auto& op : cancels) {
|
||||||
|
if (complete_op_and_collect_tickets(
|
||||||
|
op,
|
||||||
|
std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::cancelled, "IO operation cancelled")},
|
||||||
|
tickets, close_waiters,
|
||||||
|
/*skip_if_executing=*/true)) {
|
||||||
|
++done;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
{
|
||||||
|
std::lock_guard lk{mu_};
|
||||||
|
for (const auto& action : controls) {
|
||||||
|
if (!action.id.valid() || action.id.slot >= slots_.size()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
auto& slot = slots_[action.id.slot];
|
||||||
|
if (!slot.in_use || slot.is_file ||
|
||||||
|
slot.id.generation != action.id.generation) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (action.type == ControlAction::Type::close_fd) {
|
||||||
|
if (!slot.active_read && !slot.active_write) {
|
||||||
|
close_waiters.insert(
|
||||||
|
close_waiters.end(),
|
||||||
|
std::make_move_iterator(slot.close_waiters.begin()),
|
||||||
|
std::make_move_iterator(slot.close_waiters.end()));
|
||||||
|
slot.close_waiters.clear();
|
||||||
|
release_slot_locked(action.id.slot, true);
|
||||||
|
++done;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
commit_close_waiters(close_waiters, tickets);
|
||||||
|
return done;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t expire_deadlines(std::vector<Async::ResumeTicket>& tickets)
|
||||||
|
{
|
||||||
|
std::vector<std::shared_ptr<PendingOp>> expired;
|
||||||
|
const auto now = clock_.now();
|
||||||
|
{
|
||||||
|
std::lock_guard lk{mu_};
|
||||||
|
for (auto& slot : slots_) {
|
||||||
|
if (!slot.in_use || slot.is_file) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (slot.active_read && !slot.active_read->retired &&
|
||||||
|
!slot.active_read->in_execution &&
|
||||||
|
slot.active_read->deadline.has_value() &&
|
||||||
|
now >= *slot.active_read->deadline) {
|
||||||
|
expired.push_back(slot.active_read);
|
||||||
|
}
|
||||||
|
if (slot.active_write && !slot.active_write->retired &&
|
||||||
|
!slot.active_write->in_execution &&
|
||||||
|
slot.active_write->deadline.has_value() &&
|
||||||
|
now >= *slot.active_write->deadline) {
|
||||||
|
expired.push_back(slot.active_write);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::size_t done = 0;
|
||||||
|
std::vector<CloseWaiter> close_waiters;
|
||||||
|
for (const auto& op : expired) {
|
||||||
|
if (complete_op_and_collect_tickets(
|
||||||
|
op,
|
||||||
|
std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::timeout, "IO operation timed out")},
|
||||||
|
tickets, close_waiters,
|
||||||
|
/*skip_if_executing=*/true)) {
|
||||||
|
++done;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return done;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool begin_execution(const std::shared_ptr<PendingOp>& op) noexcept
|
||||||
|
{
|
||||||
|
std::lock_guard lk{mu_};
|
||||||
|
if (op->retired) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
op->in_execution = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void end_execution(const std::shared_ptr<PendingOp>& op) noexcept
|
||||||
|
{
|
||||||
|
std::lock_guard lk{mu_};
|
||||||
|
op->in_execution = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t drive_read(std::uint32_t slot_idx,
|
||||||
|
std::uint32_t gen,
|
||||||
|
int fd,
|
||||||
|
std::uint32_t ev_mask,
|
||||||
|
const std::shared_ptr<PendingOp>& op,
|
||||||
|
std::vector<Async::ResumeTicket>& tickets)
|
||||||
|
{
|
||||||
|
(void)slot_idx;
|
||||||
|
(void)gen;
|
||||||
|
if (op->op_state->stop_requested()) {
|
||||||
|
std::vector<CloseWaiter> close_waiters;
|
||||||
|
return complete_op_and_collect_tickets(
|
||||||
|
op,
|
||||||
|
std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::cancelled,
|
||||||
|
"Read cancelled before syscall")},
|
||||||
|
tickets, close_waiters)
|
||||||
|
? 1
|
||||||
|
: 0;
|
||||||
|
}
|
||||||
|
if (!begin_execution(op)) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const std::size_t to_read = std::min(op->len, limits_.max_bytes_per_turn);
|
||||||
|
const SOCKET socket = socket_from_fd(fd);
|
||||||
|
const bool is_socket = is_socket_fd(socket);
|
||||||
|
int n = -1;
|
||||||
|
int saved_error = 0;
|
||||||
|
for (;;) {
|
||||||
|
if (is_socket) {
|
||||||
|
n = ::recv(socket, reinterpret_cast<char*>(op->read_ptr),
|
||||||
|
static_cast<int>(to_read), 0);
|
||||||
|
saved_error = n < 0 ? ::WSAGetLastError() : 0;
|
||||||
|
if (n < 0 && saved_error == WSAEINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
n = ::_read(fd, op->read_ptr,
|
||||||
|
static_cast<unsigned int>(to_read));
|
||||||
|
saved_error = n < 0 ? errno : 0;
|
||||||
|
if (n < 0 && saved_error == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
int so_err = 0;
|
||||||
|
if (n < 0 && is_socket && saved_error == WSAEWOULDBLOCK &&
|
||||||
|
(ev_mask & kErr) != 0) {
|
||||||
|
int length = sizeof(so_err);
|
||||||
|
if (::getsockopt(socket, SOL_SOCKET, SO_ERROR,
|
||||||
|
reinterpret_cast<char*>(&so_err), &length) != 0) {
|
||||||
|
so_err = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
end_execution(op);
|
||||||
|
std::vector<CloseWaiter> close_waiters;
|
||||||
|
if (n > 0) {
|
||||||
|
return complete_op_and_collect_tickets(
|
||||||
|
op, Transfer{static_cast<std::size_t>(n), false},
|
||||||
|
tickets, close_waiters)
|
||||||
|
? 1
|
||||||
|
: 0;
|
||||||
|
}
|
||||||
|
if (n == 0) {
|
||||||
|
return complete_op_and_collect_tickets(
|
||||||
|
op, Transfer{0, true}, tickets, close_waiters)
|
||||||
|
? 1
|
||||||
|
: 0;
|
||||||
|
}
|
||||||
|
const bool would_block =
|
||||||
|
is_socket ? saved_error == WSAEWOULDBLOCK : saved_error == EAGAIN;
|
||||||
|
if (would_block) {
|
||||||
|
if (so_err != 0) {
|
||||||
|
return complete_op_and_collect_tickets(
|
||||||
|
op,
|
||||||
|
std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::os_error, "Socket error on read",
|
||||||
|
win_error_code(so_err))},
|
||||||
|
tickets, close_waiters)
|
||||||
|
? 1
|
||||||
|
: 0;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return complete_op_and_collect_tickets(
|
||||||
|
op,
|
||||||
|
std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::os_error, "read failed",
|
||||||
|
win_error_code(saved_error))},
|
||||||
|
tickets, close_waiters)
|
||||||
|
? 1
|
||||||
|
: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void disarm_write_locked(std::uint32_t slot_idx,
|
||||||
|
std::uint32_t gen,
|
||||||
|
const std::shared_ptr<PendingOp>& op) noexcept
|
||||||
|
{
|
||||||
|
if (slot_idx < slots_.size() && slots_[slot_idx].in_use &&
|
||||||
|
slots_[slot_idx].id.generation == gen) {
|
||||||
|
slots_[slot_idx].active_write.reset();
|
||||||
|
slots_[slot_idx].active_write = op;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t drive_write(std::uint32_t slot_idx,
|
||||||
|
std::uint32_t gen,
|
||||||
|
int fd,
|
||||||
|
std::uint32_t ev_mask,
|
||||||
|
const std::shared_ptr<PendingOp>& op,
|
||||||
|
std::vector<Async::ResumeTicket>& tickets)
|
||||||
|
{
|
||||||
|
if (op->op_state->stop_requested()) {
|
||||||
|
{
|
||||||
|
std::lock_guard lk{mu_};
|
||||||
|
if (!op->retired) {
|
||||||
|
disarm_write_locked(slot_idx, gen, op);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::vector<CloseWaiter> close_waiters;
|
||||||
|
return complete_op_and_collect_tickets(
|
||||||
|
op,
|
||||||
|
std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::cancelled,
|
||||||
|
"Write cancelled before syscall")},
|
||||||
|
tickets, close_waiters)
|
||||||
|
? 1
|
||||||
|
: 0;
|
||||||
|
}
|
||||||
|
if (!begin_execution(op)) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const std::size_t to_write =
|
||||||
|
std::min(op->len, limits_.max_bytes_per_turn);
|
||||||
|
const SOCKET socket = socket_from_fd(fd);
|
||||||
|
const bool is_socket = is_socket_fd(socket);
|
||||||
|
int n = -1;
|
||||||
|
int saved_error = 0;
|
||||||
|
for (;;) {
|
||||||
|
if (is_socket) {
|
||||||
|
n = ::send(socket, reinterpret_cast<const char*>(op->write_ptr),
|
||||||
|
static_cast<int>(to_write), 0);
|
||||||
|
saved_error = n < 0 ? ::WSAGetLastError() : 0;
|
||||||
|
if (n < 0 && saved_error == WSAEINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
n = ::_write(fd, op->write_ptr,
|
||||||
|
static_cast<unsigned int>(to_write));
|
||||||
|
saved_error = n < 0 ? errno : 0;
|
||||||
|
if (n < 0 && saved_error == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
int so_err = 0;
|
||||||
|
if (n < 0 && is_socket && saved_error == WSAEWOULDBLOCK &&
|
||||||
|
(ev_mask & kErr) != 0) {
|
||||||
|
int length = sizeof(so_err);
|
||||||
|
if (::getsockopt(socket, SOL_SOCKET, SO_ERROR,
|
||||||
|
reinterpret_cast<char*>(&so_err), &length) != 0) {
|
||||||
|
so_err = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
end_execution(op);
|
||||||
|
std::vector<CloseWaiter> close_waiters;
|
||||||
|
if (n >= 0) {
|
||||||
|
{
|
||||||
|
std::lock_guard lk{mu_};
|
||||||
|
if (!op->retired) {
|
||||||
|
disarm_write_locked(slot_idx, gen, op);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return complete_op_and_collect_tickets(
|
||||||
|
op, Transfer{static_cast<std::size_t>(n), false},
|
||||||
|
tickets, close_waiters)
|
||||||
|
? 1
|
||||||
|
: 0;
|
||||||
|
}
|
||||||
|
const bool would_block =
|
||||||
|
is_socket ? saved_error == WSAEWOULDBLOCK : saved_error == EAGAIN;
|
||||||
|
if (would_block) {
|
||||||
|
if (so_err != 0) {
|
||||||
|
{
|
||||||
|
std::lock_guard lk{mu_};
|
||||||
|
if (!op->retired) {
|
||||||
|
disarm_write_locked(slot_idx, gen, op);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return complete_op_and_collect_tickets(
|
||||||
|
op,
|
||||||
|
std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::os_error,
|
||||||
|
"Socket error on write",
|
||||||
|
win_error_code(so_err))},
|
||||||
|
tickets, close_waiters)
|
||||||
|
? 1
|
||||||
|
: 0;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
{
|
||||||
|
std::lock_guard lk{mu_};
|
||||||
|
if (!op->retired) {
|
||||||
|
disarm_write_locked(slot_idx, gen, op);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return complete_op_and_collect_tickets(
|
||||||
|
op,
|
||||||
|
std::unexpected{make_io_error(
|
||||||
|
IoErrorCode::os_error, "write failed",
|
||||||
|
win_error_code(saved_error))},
|
||||||
|
tickets, close_waiters)
|
||||||
|
? 1
|
||||||
|
: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
SOCKET wake_recv_{INVALID_SOCKET};
|
||||||
|
SOCKET wake_send_{INVALID_SOCKET};
|
||||||
|
std::atomic<bool> wake_closed_{false};
|
||||||
|
};
|
||||||
|
#endif // __linux__ / _WIN32
|
||||||
|
|
||||||
} // namespace Void::IO::detail
|
} // namespace Void::IO::detail
|
||||||
|
|
||||||
@@ -2949,10 +3816,18 @@ Void::Result::Result<std::unique_ptr<Driver>> Driver::create(
|
|||||||
return std::unexpected{std::move(ep.error())};
|
return std::unexpected{std::move(ep.error())};
|
||||||
}
|
}
|
||||||
backend = std::move(*ep);
|
backend = std::move(*ep);
|
||||||
|
#elif defined(_WIN32)
|
||||||
|
auto poll = detail::SelectBackend::create_select(
|
||||||
|
executor, options.limits, clock, tracker, options.file_syscalls,
|
||||||
|
std::move(options.before_file_worker_start));
|
||||||
|
if (!poll.has_value()) {
|
||||||
|
return std::unexpected{std::move(poll.error())};
|
||||||
|
}
|
||||||
|
backend = std::move(*poll);
|
||||||
#else
|
#else
|
||||||
return std::unexpected{make_io_error(
|
return std::unexpected{make_io_error(
|
||||||
IoErrorCode::unsupported,
|
IoErrorCode::unsupported,
|
||||||
"Epoll backend is only supported on Linux; use BackendPreference::mock")};
|
"No native IO backend for this platform; use BackendPreference::mock")};
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+6
-1
@@ -1,3 +1,8 @@
|
|||||||
void_add_module(IO
|
void_add_module(IO
|
||||||
INTERNAL_DEPS Core Functional Time Memory Async
|
INTERNAL_DEPS Core Functional Time Memory Async
|
||||||
)
|
# The native epoll driver only builds on Linux/Unix; Windows uses the
|
||||||
|
# select-based backend and needs winsock.
|
||||||
|
EXCLUDE_SOURCES_WIN32
|
||||||
|
EpollDriver.cpp
|
||||||
|
DEPS_WIN32 ws2_32
|
||||||
|
)
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
#include <Void/MCP/Codec.hpp>
|
||||||
|
|
||||||
|
#include <format>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::MCP
|
||||||
|
{
|
||||||
|
LineFramer::LineFramer(McpLimits limits) : m_limits(std::move(limits))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t LineFramer::buffered() const noexcept
|
||||||
|
{
|
||||||
|
return m_buffer.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
void LineFramer::reset() noexcept
|
||||||
|
{
|
||||||
|
m_buffer.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void>
|
||||||
|
LineFramer::append(std::string_view bytes)
|
||||||
|
{
|
||||||
|
m_buffer.append(bytes);
|
||||||
|
const std::size_t last_newline = m_buffer.rfind('\n');
|
||||||
|
const std::size_t tail =
|
||||||
|
last_newline == std::string::npos
|
||||||
|
? m_buffer.size()
|
||||||
|
: m_buffer.size() - last_newline - 1U;
|
||||||
|
if (tail > m_limits.max_line_bytes) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::payload_too_large,
|
||||||
|
std::format("MCP: stdio frame exceeds {} bytes",
|
||||||
|
m_limits.max_line_bytes))};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::optional<std::string>>
|
||||||
|
LineFramer::next()
|
||||||
|
{
|
||||||
|
for (;;) {
|
||||||
|
const std::size_t newline = m_buffer.find('\n');
|
||||||
|
if (newline == std::string::npos) {
|
||||||
|
return std::optional<std::string>{};
|
||||||
|
}
|
||||||
|
std::string line = m_buffer.substr(0, newline);
|
||||||
|
m_buffer.erase(0, newline + 1U);
|
||||||
|
if (!line.empty() && line.back() == '\r') {
|
||||||
|
line.pop_back();
|
||||||
|
}
|
||||||
|
if (line.empty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (line.size() > m_limits.max_line_bytes) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::payload_too_large,
|
||||||
|
std::format("MCP: stdio frame exceeds {} bytes",
|
||||||
|
m_limits.max_line_bytes))};
|
||||||
|
}
|
||||||
|
return std::optional<std::string>{std::move(line)};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::string>
|
||||||
|
frame_line(std::string_view json, const McpLimits& limits)
|
||||||
|
{
|
||||||
|
if (json.size() > limits.max_line_bytes) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::payload_too_large,
|
||||||
|
std::format("MCP: stdio frame {} bytes exceeds {}",
|
||||||
|
json.size(), limits.max_line_bytes))};
|
||||||
|
}
|
||||||
|
std::string frame{json};
|
||||||
|
frame.push_back('\n');
|
||||||
|
return frame;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::string>
|
||||||
|
encode_sse_event(const SseEvent& event, const McpLimits& limits)
|
||||||
|
{
|
||||||
|
std::string out;
|
||||||
|
if (!event.event.empty()) {
|
||||||
|
out += "event: ";
|
||||||
|
out += event.event;
|
||||||
|
out.push_back('\n');
|
||||||
|
}
|
||||||
|
if (!event.id.empty()) {
|
||||||
|
out += "id: ";
|
||||||
|
out += event.id;
|
||||||
|
out.push_back('\n');
|
||||||
|
}
|
||||||
|
std::size_t begin = 0;
|
||||||
|
for (;;) {
|
||||||
|
const std::size_t newline = event.data.find('\n', begin);
|
||||||
|
out += "data: ";
|
||||||
|
if (newline == std::string::npos) {
|
||||||
|
out.append(event.data, begin, std::string::npos);
|
||||||
|
out.push_back('\n');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
out.append(event.data, begin, newline - begin);
|
||||||
|
out.push_back('\n');
|
||||||
|
begin = newline + 1U;
|
||||||
|
}
|
||||||
|
out.push_back('\n');
|
||||||
|
if (out.size() > limits.max_sse_event_bytes) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::payload_too_large,
|
||||||
|
std::format("MCP: SSE event {} bytes exceeds {}",
|
||||||
|
out.size(), limits.max_sse_event_bytes))};
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
SseParser::SseParser(McpLimits limits) : m_limits(std::move(limits))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t SseParser::buffered() const noexcept
|
||||||
|
{
|
||||||
|
return m_buffer.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
void SseParser::reset() noexcept
|
||||||
|
{
|
||||||
|
m_buffer.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void>
|
||||||
|
SseParser::append(std::string_view bytes)
|
||||||
|
{
|
||||||
|
m_buffer.append(bytes);
|
||||||
|
if (m_buffer.size() > m_limits.max_sse_event_bytes &&
|
||||||
|
m_buffer.find("\n\n") == std::string::npos) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::payload_too_large,
|
||||||
|
std::format("MCP: SSE buffer exceeds {} bytes",
|
||||||
|
m_limits.max_sse_event_bytes))};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::optional<SseEvent>>
|
||||||
|
SseParser::next()
|
||||||
|
{
|
||||||
|
for (;;) {
|
||||||
|
const std::size_t separator = m_buffer.find("\n\n");
|
||||||
|
if (separator == std::string::npos) {
|
||||||
|
return std::optional<SseEvent>{};
|
||||||
|
}
|
||||||
|
const std::string block = m_buffer.substr(0, separator);
|
||||||
|
m_buffer.erase(0, separator + 2U);
|
||||||
|
|
||||||
|
SseEvent event;
|
||||||
|
bool has_data = false;
|
||||||
|
std::size_t begin = 0;
|
||||||
|
while (begin <= block.size()) {
|
||||||
|
const std::size_t newline = block.find('\n', begin);
|
||||||
|
const std::string_view line =
|
||||||
|
newline == std::string::npos
|
||||||
|
? std::string_view{block}.substr(begin)
|
||||||
|
: std::string_view{block}.substr(
|
||||||
|
begin, newline - begin);
|
||||||
|
begin = newline == std::string::npos ? block.size() + 1U
|
||||||
|
: newline + 1U;
|
||||||
|
if (line.empty() || line.front() == ':') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const std::size_t colon = line.find(':');
|
||||||
|
const std::string_view field =
|
||||||
|
colon == std::string_view::npos
|
||||||
|
? line
|
||||||
|
: line.substr(0, colon);
|
||||||
|
std::string_view value =
|
||||||
|
colon == std::string_view::npos
|
||||||
|
? std::string_view{}
|
||||||
|
: line.substr(colon + 1U);
|
||||||
|
if (!value.empty() && value.front() == ' ') {
|
||||||
|
value.remove_prefix(1U);
|
||||||
|
}
|
||||||
|
if (field == "event") {
|
||||||
|
event.event = value;
|
||||||
|
} else if (field == "id") {
|
||||||
|
event.id = value;
|
||||||
|
} else if (field == "data") {
|
||||||
|
if (has_data) {
|
||||||
|
event.data.push_back('\n');
|
||||||
|
}
|
||||||
|
event.data += value;
|
||||||
|
has_data = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!has_data) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (event.data.size() > m_limits.max_sse_event_bytes) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::payload_too_large,
|
||||||
|
"MCP: SSE event data exceeds limit")};
|
||||||
|
}
|
||||||
|
return std::optional<SseEvent>{std::move(event)};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::MCP
|
||||||
@@ -0,0 +1,493 @@
|
|||||||
|
#include <Void/MCP/Envelope.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <format>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
#include <variant>
|
||||||
|
|
||||||
|
namespace Void::MCP
|
||||||
|
{
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
using Object = JsonValue::Object;
|
||||||
|
using Array = JsonValue::Array;
|
||||||
|
|
||||||
|
[[nodiscard]] const Object* as_object(const JsonValue& value) noexcept
|
||||||
|
{
|
||||||
|
return std::get_if<Object>(&value.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] const std::string*
|
||||||
|
as_string(const JsonValue& value) noexcept
|
||||||
|
{
|
||||||
|
return std::get_if<std::string>(&value.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] const std::int64_t*
|
||||||
|
as_integer(const JsonValue& value) noexcept
|
||||||
|
{
|
||||||
|
return std::get_if<std::int64_t>(&value.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Error
|
||||||
|
invalid(std::string message)
|
||||||
|
{
|
||||||
|
return make_mcp_error(McpErrorCode::invalid_request,
|
||||||
|
std::move(message));
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::string>
|
||||||
|
serialize_value(const JsonValue& value, const McpLimits& limits)
|
||||||
|
{
|
||||||
|
auto text = Void::Json::Strict::serialize(value,
|
||||||
|
limits.max_json_depth);
|
||||||
|
if (!text.has_value()) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::invalid_params,
|
||||||
|
std::format("MCP: JSON serialize failed: {}",
|
||||||
|
text.error().message))};
|
||||||
|
}
|
||||||
|
if (text->size() > limits.max_message_bytes) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::payload_too_large,
|
||||||
|
std::format("MCP: encoded message {} bytes exceeds {}",
|
||||||
|
text->size(), limits.max_message_bytes))};
|
||||||
|
}
|
||||||
|
return std::move(*text);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] JsonValue encode_id(const JsonRpcId& id)
|
||||||
|
{
|
||||||
|
return std::visit(
|
||||||
|
[](const auto& value) -> JsonValue {
|
||||||
|
using T = std::decay_t<decltype(value)>;
|
||||||
|
if constexpr (std::same_as<T, std::monostate>) {
|
||||||
|
return JsonValue{nullptr};
|
||||||
|
} else if constexpr (std::same_as<T, std::int64_t>) {
|
||||||
|
return JsonValue{value};
|
||||||
|
} else {
|
||||||
|
return JsonValue{value};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
id.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<JsonRpcId>
|
||||||
|
decode_id(const JsonValue& value)
|
||||||
|
{
|
||||||
|
if (std::holds_alternative<std::nullptr_t>(value.value)) {
|
||||||
|
return JsonRpcId{};
|
||||||
|
}
|
||||||
|
if (const auto* number = as_integer(value); number != nullptr) {
|
||||||
|
return JsonRpcId{*number};
|
||||||
|
}
|
||||||
|
if (const auto* text = as_string(value); text != nullptr) {
|
||||||
|
return JsonRpcId{*text};
|
||||||
|
}
|
||||||
|
return std::unexpected{invalid(
|
||||||
|
"MCP: JSON-RPC id must be null, an integer, or a string")};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<JsonValue>
|
||||||
|
merge_metadata(std::optional<JsonValue> params,
|
||||||
|
const RequestMetadata& metadata,
|
||||||
|
const McpLimits& limits)
|
||||||
|
{
|
||||||
|
auto meta = metadata_to_json(metadata, limits);
|
||||||
|
if (!meta.has_value()) {
|
||||||
|
return std::unexpected{std::move(meta.error())};
|
||||||
|
}
|
||||||
|
Object object;
|
||||||
|
if (params.has_value()) {
|
||||||
|
if (const auto* existing = as_object(*params);
|
||||||
|
existing != nullptr) {
|
||||||
|
object = *existing;
|
||||||
|
} else if (!std::holds_alternative<std::nullptr_t>(
|
||||||
|
params->value)) {
|
||||||
|
return std::unexpected{invalid(
|
||||||
|
"MCP: params must be an object when present")};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
object[std::string{"_meta"}] = std::move(*meta);
|
||||||
|
return JsonValue{std::move(object)};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] JsonValue encode_error(const ErrorObject& error)
|
||||||
|
{
|
||||||
|
Object object;
|
||||||
|
object["code"] = JsonValue{static_cast<std::int64_t>(error.code)};
|
||||||
|
object["message"] = JsonValue{error.message};
|
||||||
|
if (error.data.has_value()) {
|
||||||
|
object["data"] = *error.data;
|
||||||
|
}
|
||||||
|
return JsonValue{std::move(object)};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<ErrorObject>
|
||||||
|
decode_error(const JsonValue& value)
|
||||||
|
{
|
||||||
|
const auto* object = as_object(value);
|
||||||
|
if (object == nullptr) {
|
||||||
|
return std::unexpected{invalid(
|
||||||
|
"MCP: JSON-RPC error must be an object")};
|
||||||
|
}
|
||||||
|
const auto code_it = object->find("code");
|
||||||
|
const auto message_it = object->find("message");
|
||||||
|
if (code_it == object->end() || message_it == object->end()) {
|
||||||
|
return std::unexpected{invalid(
|
||||||
|
"MCP: JSON-RPC error requires code and message")};
|
||||||
|
}
|
||||||
|
const auto* code = as_integer(code_it->second);
|
||||||
|
const auto* message = as_string(message_it->second);
|
||||||
|
if (code == nullptr || message == nullptr ||
|
||||||
|
*code < INT32_MIN || *code > INT32_MAX) {
|
||||||
|
return std::unexpected{invalid(
|
||||||
|
"MCP: malformed JSON-RPC error code or message")};
|
||||||
|
}
|
||||||
|
ErrorObject error;
|
||||||
|
error.code = static_cast<std::int32_t>(*code);
|
||||||
|
error.message = *message;
|
||||||
|
if (const auto data_it = object->find("data");
|
||||||
|
data_it != object->end()) {
|
||||||
|
error.data = data_it->second;
|
||||||
|
}
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<RequestMetadata>
|
||||||
|
parse_meta_object(const JsonValue& meta, const McpLimits& limits)
|
||||||
|
{
|
||||||
|
const auto* object = as_object(meta);
|
||||||
|
if (object == nullptr) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::invalid_params,
|
||||||
|
"MCP: _meta must be an object")};
|
||||||
|
}
|
||||||
|
RequestMetadata metadata;
|
||||||
|
std::size_t entries = 0;
|
||||||
|
for (const auto& [key, value] : *object) {
|
||||||
|
++entries;
|
||||||
|
if (entries > limits.max_metadata_entries) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::payload_too_large,
|
||||||
|
std::format("MCP: _meta exceeds {} entries",
|
||||||
|
limits.max_metadata_entries))};
|
||||||
|
}
|
||||||
|
if (key == kMetaProtocolVersion) {
|
||||||
|
const auto* text = as_string(value);
|
||||||
|
if (text == nullptr ||
|
||||||
|
text->size() >
|
||||||
|
limits.max_metadata_value_bytes) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::invalid_params,
|
||||||
|
"MCP: protocolVersion must be a bounded string")};
|
||||||
|
}
|
||||||
|
metadata.protocol_version = *text;
|
||||||
|
} else if (key == kMetaClientInfo) {
|
||||||
|
const auto* info = as_object(value);
|
||||||
|
if (info == nullptr) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::invalid_params,
|
||||||
|
"MCP: clientInfo must be an object")};
|
||||||
|
}
|
||||||
|
if (const auto name = info->find("name");
|
||||||
|
name != info->end()) {
|
||||||
|
if (const auto* text = as_string(name->second);
|
||||||
|
text != nullptr) {
|
||||||
|
metadata.client_info.name = *text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (const auto version = info->find("version");
|
||||||
|
version != info->end()) {
|
||||||
|
if (const auto* text = as_string(version->second);
|
||||||
|
text != nullptr) {
|
||||||
|
metadata.client_info.version = *text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (key == kMetaClientCapabilities) {
|
||||||
|
auto text = serialize_value(value, limits);
|
||||||
|
if (!text.has_value()) {
|
||||||
|
return std::unexpected{
|
||||||
|
std::move(text.error())};
|
||||||
|
}
|
||||||
|
metadata.client_capabilities_json = std::move(*text);
|
||||||
|
} else if (key == kMetaProgressToken) {
|
||||||
|
if (const auto* text = as_string(value);
|
||||||
|
text != nullptr) {
|
||||||
|
metadata.progress_token = *text;
|
||||||
|
}
|
||||||
|
} else if (key == kMetaSubscriptionId) {
|
||||||
|
if (const auto* text = as_string(value);
|
||||||
|
text != nullptr) {
|
||||||
|
metadata.subscription_id = *text;
|
||||||
|
}
|
||||||
|
} else if (const auto* text = as_string(value);
|
||||||
|
text != nullptr) {
|
||||||
|
if (key.size() > limits.max_metadata_value_bytes ||
|
||||||
|
text->size() > limits.max_metadata_value_bytes) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::payload_too_large,
|
||||||
|
"MCP: _meta entry exceeds size limit")};
|
||||||
|
}
|
||||||
|
metadata.extra.push_back({key, *text});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return metadata;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Result::Result<std::string>
|
||||||
|
encode_json(const JsonValue& value, const McpLimits& limits)
|
||||||
|
{
|
||||||
|
return serialize_value(value, limits);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<JsonValue>
|
||||||
|
decode_json(std::string_view text, const McpLimits& limits)
|
||||||
|
{
|
||||||
|
if (text.size() > limits.max_message_bytes) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::payload_too_large,
|
||||||
|
std::format("MCP: message {} bytes exceeds {}",
|
||||||
|
text.size(), limits.max_message_bytes))};
|
||||||
|
}
|
||||||
|
auto value = Void::Json::Strict::parse(
|
||||||
|
text, Void::Json::Strict::ParseOptions{
|
||||||
|
.maximumDepth = limits.max_json_depth,
|
||||||
|
.allowDecimals = true});
|
||||||
|
if (!value.has_value()) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::parse_error,
|
||||||
|
std::format("MCP: invalid JSON at {}: {}",
|
||||||
|
value.error().offset, value.error().message))};
|
||||||
|
}
|
||||||
|
return std::move(*value);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<RequestMetadata>
|
||||||
|
parse_metadata(const JsonValue& params, const McpLimits& limits)
|
||||||
|
{
|
||||||
|
const auto* object = as_object(params);
|
||||||
|
if (object == nullptr) {
|
||||||
|
return RequestMetadata{};
|
||||||
|
}
|
||||||
|
const auto meta = object->find("_meta");
|
||||||
|
if (meta == object->end()) {
|
||||||
|
return RequestMetadata{};
|
||||||
|
}
|
||||||
|
return parse_meta_object(meta->second, limits);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<JsonValue>
|
||||||
|
metadata_to_json(const RequestMetadata& metadata,
|
||||||
|
const McpLimits& limits)
|
||||||
|
{
|
||||||
|
if (metadata.protocol_version.size() >
|
||||||
|
limits.max_metadata_value_bytes) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::payload_too_large,
|
||||||
|
"MCP: protocol version exceeds metadata limit")};
|
||||||
|
}
|
||||||
|
Object meta;
|
||||||
|
meta[std::string{kMetaProtocolVersion}] =
|
||||||
|
JsonValue{metadata.protocol_version};
|
||||||
|
if (!metadata.client_info.name.empty() ||
|
||||||
|
!metadata.client_info.version.empty()) {
|
||||||
|
Object info;
|
||||||
|
info["name"] = JsonValue{metadata.client_info.name};
|
||||||
|
info["version"] = JsonValue{metadata.client_info.version};
|
||||||
|
meta[std::string{kMetaClientInfo}] =
|
||||||
|
JsonValue{std::move(info)};
|
||||||
|
}
|
||||||
|
if (!metadata.client_capabilities_json.empty()) {
|
||||||
|
auto capabilities =
|
||||||
|
decode_json(metadata.client_capabilities_json, limits);
|
||||||
|
if (!capabilities.has_value()) {
|
||||||
|
return std::unexpected{std::move(capabilities.error())};
|
||||||
|
}
|
||||||
|
if (as_object(*capabilities) == nullptr) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::invalid_params,
|
||||||
|
"MCP: clientCapabilities must be a JSON object")};
|
||||||
|
}
|
||||||
|
meta[std::string{kMetaClientCapabilities}] =
|
||||||
|
std::move(*capabilities);
|
||||||
|
}
|
||||||
|
if (metadata.progress_token.has_value()) {
|
||||||
|
meta[std::string{kMetaProgressToken}] =
|
||||||
|
JsonValue{*metadata.progress_token};
|
||||||
|
}
|
||||||
|
if (metadata.subscription_id.has_value()) {
|
||||||
|
meta[std::string{kMetaSubscriptionId}] =
|
||||||
|
JsonValue{*metadata.subscription_id};
|
||||||
|
}
|
||||||
|
if (metadata.extra.size() > limits.max_metadata_entries) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::payload_too_large,
|
||||||
|
"MCP: too many metadata entries")};
|
||||||
|
}
|
||||||
|
for (const auto& entry : metadata.extra) {
|
||||||
|
if (entry.key.size() > limits.max_metadata_value_bytes ||
|
||||||
|
entry.value.size() > limits.max_metadata_value_bytes) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::payload_too_large,
|
||||||
|
"MCP: metadata entry exceeds size limit")};
|
||||||
|
}
|
||||||
|
meta[entry.key] = JsonValue{entry.value};
|
||||||
|
}
|
||||||
|
return JsonValue{std::move(meta)};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::string>
|
||||||
|
encode_message(const Message& message, const McpLimits& limits)
|
||||||
|
{
|
||||||
|
Object object;
|
||||||
|
object["jsonrpc"] = JsonValue{std::string{kJsonRpcVersion}};
|
||||||
|
if (const auto* request = std::get_if<Request>(&message);
|
||||||
|
request != nullptr) {
|
||||||
|
object["id"] = encode_id(request->id);
|
||||||
|
object["method"] = JsonValue{request->method};
|
||||||
|
auto params = merge_metadata(request->params,
|
||||||
|
request->metadata, limits);
|
||||||
|
if (!params.has_value()) {
|
||||||
|
return std::unexpected{std::move(params.error())};
|
||||||
|
}
|
||||||
|
object["params"] = std::move(*params);
|
||||||
|
} else if (const auto* notification =
|
||||||
|
std::get_if<Notification>(&message);
|
||||||
|
notification != nullptr) {
|
||||||
|
object["method"] = JsonValue{notification->method};
|
||||||
|
auto params = merge_metadata(notification->params,
|
||||||
|
notification->metadata, limits);
|
||||||
|
if (!params.has_value()) {
|
||||||
|
return std::unexpected{std::move(params.error())};
|
||||||
|
}
|
||||||
|
object["params"] = std::move(*params);
|
||||||
|
} else {
|
||||||
|
const auto& response = std::get<Response>(message);
|
||||||
|
object["id"] = encode_id(response.id);
|
||||||
|
if (response.error.has_value() &&
|
||||||
|
response.result.has_value()) {
|
||||||
|
return std::unexpected{invalid(
|
||||||
|
"MCP: response cannot carry both result and error")};
|
||||||
|
}
|
||||||
|
if (response.error.has_value()) {
|
||||||
|
object["error"] = encode_error(*response.error);
|
||||||
|
} else if (response.result.has_value()) {
|
||||||
|
object["result"] = *response.result;
|
||||||
|
} else {
|
||||||
|
return std::unexpected{invalid(
|
||||||
|
"MCP: response requires result or error")};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return serialize_value(JsonValue{std::move(object)}, limits);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<Message>
|
||||||
|
decode_message(std::string_view text, const McpLimits& limits)
|
||||||
|
{
|
||||||
|
auto value = decode_json(text, limits);
|
||||||
|
if (!value.has_value()) {
|
||||||
|
return std::unexpected{std::move(value.error())};
|
||||||
|
}
|
||||||
|
const auto* object = as_object(*value);
|
||||||
|
if (object == nullptr) {
|
||||||
|
return std::unexpected{invalid(
|
||||||
|
"MCP: JSON-RPC message must be an object")};
|
||||||
|
}
|
||||||
|
const auto version = object->find("jsonrpc");
|
||||||
|
if (version == object->end() ||
|
||||||
|
as_string(version->second) == nullptr ||
|
||||||
|
*as_string(version->second) != kJsonRpcVersion) {
|
||||||
|
return std::unexpected{invalid(
|
||||||
|
"MCP: jsonrpc must be \"2.0\"")};
|
||||||
|
}
|
||||||
|
const auto method = object->find("method");
|
||||||
|
const auto id = object->find("id");
|
||||||
|
if (method != object->end()) {
|
||||||
|
if (object->contains("result") || object->contains("error")) {
|
||||||
|
return std::unexpected{invalid(
|
||||||
|
"MCP: message cannot mix method with result/error")};
|
||||||
|
}
|
||||||
|
const auto* method_text = as_string(method->second);
|
||||||
|
if (method_text == nullptr || method_text->empty() ||
|
||||||
|
method_text->size() > limits.max_metadata_value_bytes) {
|
||||||
|
return std::unexpected{invalid(
|
||||||
|
"MCP: method must be a bounded non-empty string")};
|
||||||
|
}
|
||||||
|
std::optional<JsonValue> params;
|
||||||
|
if (const auto params_it = object->find("params");
|
||||||
|
params_it != object->end()) {
|
||||||
|
if (as_object(params_it->second) == nullptr) {
|
||||||
|
return std::unexpected{invalid(
|
||||||
|
"MCP: params must be an object when present")};
|
||||||
|
}
|
||||||
|
params = params_it->second;
|
||||||
|
}
|
||||||
|
RequestMetadata metadata;
|
||||||
|
if (params.has_value()) {
|
||||||
|
auto parsed = parse_metadata(*params, limits);
|
||||||
|
if (!parsed.has_value()) {
|
||||||
|
return std::unexpected{std::move(parsed.error())};
|
||||||
|
}
|
||||||
|
metadata = std::move(*parsed);
|
||||||
|
}
|
||||||
|
if (id != object->end()) {
|
||||||
|
auto decoded_id = decode_id(id->second);
|
||||||
|
if (!decoded_id.has_value()) {
|
||||||
|
return std::unexpected{
|
||||||
|
std::move(decoded_id.error())};
|
||||||
|
}
|
||||||
|
return Request{std::move(*decoded_id),
|
||||||
|
std::move(*method_text),
|
||||||
|
std::move(params), std::move(metadata)};
|
||||||
|
}
|
||||||
|
return Notification{std::move(*method_text),
|
||||||
|
std::move(params), std::move(metadata)};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (id == object->end()) {
|
||||||
|
return std::unexpected{invalid(
|
||||||
|
"MCP: response requires an id")};
|
||||||
|
}
|
||||||
|
auto decoded_id = decode_id(id->second);
|
||||||
|
if (!decoded_id.has_value()) {
|
||||||
|
return std::unexpected{std::move(decoded_id.error())};
|
||||||
|
}
|
||||||
|
const auto result = object->find("result");
|
||||||
|
const auto error = object->find("error");
|
||||||
|
if (result != object->end() && error != object->end()) {
|
||||||
|
return std::unexpected{invalid(
|
||||||
|
"MCP: response cannot carry both result and error")};
|
||||||
|
}
|
||||||
|
if (result != object->end()) {
|
||||||
|
return Response{std::move(*decoded_id), result->second,
|
||||||
|
std::nullopt};
|
||||||
|
}
|
||||||
|
if (error != object->end()) {
|
||||||
|
auto decoded_error = decode_error(error->second);
|
||||||
|
if (!decoded_error.has_value()) {
|
||||||
|
return std::unexpected{
|
||||||
|
std::move(decoded_error.error())};
|
||||||
|
}
|
||||||
|
return Response{std::move(*decoded_id), std::nullopt,
|
||||||
|
std::move(*decoded_error)};
|
||||||
|
}
|
||||||
|
return std::unexpected{invalid(
|
||||||
|
"MCP: response requires result or error")};
|
||||||
|
}
|
||||||
|
|
||||||
|
Response make_error_response(const JsonRpcId& id, std::int32_t code,
|
||||||
|
std::string message,
|
||||||
|
std::optional<JsonValue> data)
|
||||||
|
{
|
||||||
|
Response response;
|
||||||
|
response.id = id;
|
||||||
|
response.error =
|
||||||
|
ErrorObject{code, std::move(message), std::move(data)};
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::MCP
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
#include <Void/MCP/Transport.hpp>
|
||||||
|
|
||||||
|
#include <Void/MCP/Envelope.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <atomic>
|
||||||
|
#include <format>
|
||||||
|
#include <map>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
#include <variant>
|
||||||
|
|
||||||
|
namespace Void::MCP
|
||||||
|
{
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
[[nodiscard]] std::string default_session_id()
|
||||||
|
{
|
||||||
|
static std::atomic<std::uint64_t> counter{1};
|
||||||
|
return std::format("mcp-session-{}",
|
||||||
|
counter.fetch_add(1,
|
||||||
|
std::memory_order_relaxed));
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] const JsonValue::Object*
|
||||||
|
as_object(const JsonValue& value) noexcept
|
||||||
|
{
|
||||||
|
return std::get_if<JsonValue::Object>(&value.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::string
|
||||||
|
param_string(const Request& request, std::string_view key)
|
||||||
|
{
|
||||||
|
if (!request.params.has_value()) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
const auto* object = as_object(*request.params);
|
||||||
|
if (object == nullptr) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
const auto field = object->find(key);
|
||||||
|
if (field == object->end()) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
if (const auto* text = std::get_if<std::string>(&field->second.value);
|
||||||
|
text != nullptr) {
|
||||||
|
return *text;
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool contains(const std::vector<std::string>& values,
|
||||||
|
std::string_view wanted) noexcept
|
||||||
|
{
|
||||||
|
return std::ranges::any_of(values, [&](const std::string& value) {
|
||||||
|
return value == wanted;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
struct LegacySessionAdapter::Impl {
|
||||||
|
LegacySessionOptions options;
|
||||||
|
std::map<std::string, LegacySession, std::less<>> sessions;
|
||||||
|
|
||||||
|
Impl() = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
LegacySessionAdapter::LegacySessionAdapter(LegacySessionOptions options)
|
||||||
|
: m_impl(std::make_unique<Impl>())
|
||||||
|
{
|
||||||
|
m_impl->options = std::move(options);
|
||||||
|
if (m_impl->options.supported_versions.empty()) {
|
||||||
|
m_impl->options.supported_versions.push_back("2025-11-25");
|
||||||
|
}
|
||||||
|
if (!m_impl->options.session_id_factory) {
|
||||||
|
m_impl->options.session_id_factory = default_session_id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
LegacySessionAdapter::~LegacySessionAdapter() = default;
|
||||||
|
|
||||||
|
Void::Result::Result<std::optional<Message>>
|
||||||
|
LegacySessionAdapter::handle(const Message& inbound,
|
||||||
|
std::string_view session_id)
|
||||||
|
{
|
||||||
|
auto& impl = *m_impl;
|
||||||
|
if (const auto* request = std::get_if<Request>(&inbound);
|
||||||
|
request != nullptr) {
|
||||||
|
if (request->method == "initialize") {
|
||||||
|
if (!session_id.empty() &&
|
||||||
|
impl.sessions.contains(session_id)) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::invalid_request,
|
||||||
|
"MCP: session is already initialized")};
|
||||||
|
}
|
||||||
|
const std::string requested =
|
||||||
|
param_string(*request, "protocolVersion");
|
||||||
|
const std::string negotiated =
|
||||||
|
contains(impl.options.supported_versions, requested)
|
||||||
|
? requested
|
||||||
|
: impl.options.supported_versions.front();
|
||||||
|
LegacySession session;
|
||||||
|
session.id = impl.options.session_id_factory();
|
||||||
|
session.protocol_version = negotiated;
|
||||||
|
impl.sessions.emplace(session.id, session);
|
||||||
|
|
||||||
|
JsonValue::Object capabilities;
|
||||||
|
JsonValue::Object server_info;
|
||||||
|
server_info["name"] =
|
||||||
|
JsonValue{impl.options.server_name};
|
||||||
|
server_info["version"] =
|
||||||
|
JsonValue{impl.options.server_version};
|
||||||
|
JsonValue::Object result;
|
||||||
|
result["protocolVersion"] = JsonValue{negotiated};
|
||||||
|
result["capabilities"] =
|
||||||
|
JsonValue{std::move(capabilities)};
|
||||||
|
result["serverInfo"] = JsonValue{std::move(server_info)};
|
||||||
|
return std::optional<Message>{Response{
|
||||||
|
request->id, JsonValue{std::move(result)},
|
||||||
|
std::nullopt}};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto session = impl.sessions.find(session_id);
|
||||||
|
if (session == impl.sessions.end() ||
|
||||||
|
!session->second.initialized) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::session_not_found,
|
||||||
|
"MCP: no initialized legacy session")};
|
||||||
|
}
|
||||||
|
return std::optional<Message>{inbound};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (const auto* notification = std::get_if<Notification>(&inbound);
|
||||||
|
notification != nullptr) {
|
||||||
|
if (notification->method == "initialized") {
|
||||||
|
const auto session = impl.sessions.find(session_id);
|
||||||
|
if (session == impl.sessions.end()) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::session_not_found,
|
||||||
|
"MCP: initialized without a legacy session")};
|
||||||
|
}
|
||||||
|
session->second.initialized = true;
|
||||||
|
}
|
||||||
|
return std::optional<Message>{};
|
||||||
|
}
|
||||||
|
return std::optional<Message>{};
|
||||||
|
}
|
||||||
|
|
||||||
|
const LegacySession*
|
||||||
|
LegacySessionAdapter::find(std::string_view session_id) const
|
||||||
|
{
|
||||||
|
const auto session =
|
||||||
|
m_impl->sessions.find(std::string{session_id});
|
||||||
|
if (session == m_impl->sessions.end()) {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
return &session->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool LegacySessionAdapter::terminate(std::string_view session_id)
|
||||||
|
{
|
||||||
|
return m_impl->sessions.erase(std::string{session_id}) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t LegacySessionAdapter::session_count() const
|
||||||
|
{
|
||||||
|
return m_impl->sessions.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::MCP
|
||||||
@@ -0,0 +1,729 @@
|
|||||||
|
#include <Void/MCP/Transport.hpp>
|
||||||
|
|
||||||
|
#include <Void/MCP/Codec.hpp>
|
||||||
|
#include <Void/MCP/Envelope.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
|
#include <cerrno>
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstring>
|
||||||
|
#include <format>
|
||||||
|
#include <limits>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
#include <variant>
|
||||||
|
|
||||||
|
#if defined(_WIN32)
|
||||||
|
#include <io.h>
|
||||||
|
#else
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <poll.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace Void::MCP
|
||||||
|
{
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
[[nodiscard]] bool ascii_iequals(std::string_view left,
|
||||||
|
std::string_view right) noexcept
|
||||||
|
{
|
||||||
|
if (left.size() != right.size()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (std::size_t index = 0; index < left.size(); ++index) {
|
||||||
|
const auto a = static_cast<unsigned char>(left[index]);
|
||||||
|
const auto b = static_cast<unsigned char>(right[index]);
|
||||||
|
if (std::tolower(a) != std::tolower(b)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::string_view trim(std::string_view text) noexcept
|
||||||
|
{
|
||||||
|
constexpr std::string_view whitespace = " \t";
|
||||||
|
const auto begin = text.find_first_not_of(whitespace);
|
||||||
|
if (begin == std::string_view::npos) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
const auto end = text.find_last_not_of(whitespace);
|
||||||
|
return text.substr(begin, end - begin + 1U);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a comma-separated header list contains `token` (media
|
||||||
|
/// type parameters are ignored).
|
||||||
|
[[nodiscard]] bool
|
||||||
|
contains_token(std::string_view list, std::string_view token)
|
||||||
|
{
|
||||||
|
std::size_t begin = 0;
|
||||||
|
while (begin <= list.size()) {
|
||||||
|
const std::size_t comma = list.find(',', begin);
|
||||||
|
std::string_view item =
|
||||||
|
comma == std::string_view::npos
|
||||||
|
? list.substr(begin)
|
||||||
|
: list.substr(begin, comma - begin);
|
||||||
|
const std::size_t semicolon = item.find(';');
|
||||||
|
if (semicolon != std::string_view::npos) {
|
||||||
|
item = item.substr(0, semicolon);
|
||||||
|
}
|
||||||
|
if (ascii_iequals(trim(item), token)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (comma == std::string_view::npos) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
begin = comma + 1U;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] const JsonValue::Object*
|
||||||
|
as_object(const JsonValue& value) noexcept
|
||||||
|
{
|
||||||
|
return std::get_if<JsonValue::Object>(&value.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] const std::string*
|
||||||
|
as_string(const JsonValue& value) noexcept
|
||||||
|
{
|
||||||
|
return std::get_if<std::string>(&value.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] HttpResponse json_response(int status,
|
||||||
|
const Message& message,
|
||||||
|
const McpLimits& limits)
|
||||||
|
{
|
||||||
|
HttpResponse response;
|
||||||
|
response.status = status;
|
||||||
|
response.headers.push_back(
|
||||||
|
{"Content-Type", std::string{kJsonContentType}});
|
||||||
|
auto encoded = encode_message(message, limits);
|
||||||
|
if (encoded.has_value()) {
|
||||||
|
response.body = std::move(*encoded);
|
||||||
|
} else {
|
||||||
|
response.status = 500;
|
||||||
|
response.body = "{\"jsonrpc\":\"2.0\",\"id\":null,"
|
||||||
|
"\"error\":{\"code\":-32603,\"message\":"
|
||||||
|
"\"failed to encode error response\"}}";
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] HttpResponse
|
||||||
|
error_response(int status, const JsonRpcId& id,
|
||||||
|
McpErrorCode code, std::string message,
|
||||||
|
const McpLimits& limits,
|
||||||
|
std::optional<JsonValue> data = {})
|
||||||
|
{
|
||||||
|
return json_response(
|
||||||
|
status,
|
||||||
|
make_error_response(id, json_rpc_error_code(code),
|
||||||
|
std::move(message), std::move(data)),
|
||||||
|
limits);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::optional<std::string>
|
||||||
|
request_name(const Request& request)
|
||||||
|
{
|
||||||
|
if (!request.params.has_value()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const auto* object = as_object(*request.params);
|
||||||
|
if (object == nullptr) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const auto field =
|
||||||
|
request.method == "resources/read"
|
||||||
|
? object->find("uri")
|
||||||
|
: object->find("name");
|
||||||
|
if (field == object->end()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
if (const auto* text = as_string(field->second);
|
||||||
|
text != nullptr) {
|
||||||
|
return *text;
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool method_requires_name(std::string_view method) noexcept
|
||||||
|
{
|
||||||
|
return method == "tools/call" || method == "resources/read" ||
|
||||||
|
method == "prompts/get";
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] RequestMetadata message_metadata(const Message& message)
|
||||||
|
{
|
||||||
|
if (const auto* request = std::get_if<Request>(&message);
|
||||||
|
request != nullptr) {
|
||||||
|
return request->metadata;
|
||||||
|
}
|
||||||
|
if (const auto* notification = std::get_if<Notification>(&message);
|
||||||
|
notification != nullptr) {
|
||||||
|
return notification->metadata;
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] JsonRpcId message_id(const Message& message)
|
||||||
|
{
|
||||||
|
if (const auto* request = std::get_if<Request>(&message);
|
||||||
|
request != nullptr) {
|
||||||
|
return request->id;
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] JsonRpcId
|
||||||
|
parse_id_from_body(std::string_view body) noexcept
|
||||||
|
{
|
||||||
|
// Best-effort id extraction for transport-level errors; the full
|
||||||
|
// message is parsed by the caller when it is valid.
|
||||||
|
const auto position = body.find("\"id\"");
|
||||||
|
if (position == std::string_view::npos) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
std::size_t index = position + 4U;
|
||||||
|
while (index < body.size() &&
|
||||||
|
(body[index] == ' ' || body[index] == '\t' ||
|
||||||
|
body[index] == ':')) {
|
||||||
|
++index;
|
||||||
|
}
|
||||||
|
if (index >= body.size()) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
if (body[index] == '"') {
|
||||||
|
const auto end = body.find('"', index + 1U);
|
||||||
|
if (end == std::string_view::npos) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
return JsonRpcId{
|
||||||
|
std::string{body.substr(index + 1U, end - index - 1U)}};
|
||||||
|
}
|
||||||
|
std::int64_t number = 0;
|
||||||
|
const char* begin = body.data() + index;
|
||||||
|
const auto parsed = std::from_chars(begin, body.data() + body.size(),
|
||||||
|
number);
|
||||||
|
if (parsed.ec != std::errc{}) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
return JsonRpcId{number};
|
||||||
|
}
|
||||||
|
|
||||||
|
#if !defined(_WIN32)
|
||||||
|
[[nodiscard]] std::chrono::milliseconds
|
||||||
|
remaining(std::chrono::steady_clock::time_point deadline) noexcept
|
||||||
|
{
|
||||||
|
const auto left = deadline - std::chrono::steady_clock::now();
|
||||||
|
if (left <= std::chrono::steady_clock::duration::zero()) {
|
||||||
|
return std::chrono::milliseconds{0};
|
||||||
|
}
|
||||||
|
return std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||||
|
left);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
wait_fd(int fd, short events,
|
||||||
|
std::chrono::milliseconds timeout, std::stop_token stop,
|
||||||
|
std::string_view operation)
|
||||||
|
{
|
||||||
|
const auto deadline =
|
||||||
|
std::chrono::steady_clock::now() + timeout;
|
||||||
|
for (;;) {
|
||||||
|
if (stop.stop_requested()) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::cancelled,
|
||||||
|
std::format("MCP: stdio {} cancelled",
|
||||||
|
operation))};
|
||||||
|
}
|
||||||
|
auto wait = remaining(deadline);
|
||||||
|
if (timeout.count() > 0 && wait.count() == 0) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::timeout,
|
||||||
|
std::format("MCP: stdio {} timed out",
|
||||||
|
operation))};
|
||||||
|
}
|
||||||
|
if (stop.stop_possible() &&
|
||||||
|
(wait.count() == 0 || wait.count() > 50)) {
|
||||||
|
wait = std::chrono::milliseconds{50};
|
||||||
|
}
|
||||||
|
pollfd descriptor{
|
||||||
|
.fd = fd, .events = events, .revents = 0};
|
||||||
|
const int rc = ::poll(&descriptor, 1,
|
||||||
|
timeout.count() > 0
|
||||||
|
? static_cast<int>(wait.count())
|
||||||
|
: -1);
|
||||||
|
if (rc < 0) {
|
||||||
|
if (errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::protocol_error,
|
||||||
|
std::format("MCP: stdio poll failed: {}",
|
||||||
|
std::strerror(errno)))};
|
||||||
|
}
|
||||||
|
if (rc > 0) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||||
|
fd_read(int fd, std::span<std::byte> destination)
|
||||||
|
{
|
||||||
|
#if defined(_WIN32)
|
||||||
|
const int rc = ::_read(fd, destination.data(),
|
||||||
|
static_cast<unsigned int>(
|
||||||
|
std::min<std::size_t>(
|
||||||
|
destination.size(), INT_MAX)));
|
||||||
|
#else
|
||||||
|
const ssize_t rc = ::read(fd, destination.data(),
|
||||||
|
destination.size());
|
||||||
|
#endif
|
||||||
|
if (rc < 0) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::protocol_error,
|
||||||
|
std::format("MCP: stdio read failed: {}",
|
||||||
|
std::strerror(errno)))};
|
||||||
|
}
|
||||||
|
return static_cast<std::size_t>(rc);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
write_all_fd(int fd, std::string_view data,
|
||||||
|
std::chrono::milliseconds timeout,
|
||||||
|
std::stop_token stop)
|
||||||
|
{
|
||||||
|
bool nonblocking = false;
|
||||||
|
#if !defined(_WIN32)
|
||||||
|
const int flags = ::fcntl(fd, F_GETFL, 0);
|
||||||
|
nonblocking = flags >= 0 && (flags & O_NONBLOCK) != 0;
|
||||||
|
#endif
|
||||||
|
while (!data.empty()) {
|
||||||
|
if (stop.stop_requested()) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::cancelled,
|
||||||
|
"MCP: stdio write cancelled")};
|
||||||
|
}
|
||||||
|
#if !defined(_WIN32)
|
||||||
|
if (nonblocking) {
|
||||||
|
auto waited =
|
||||||
|
wait_fd(fd, POLLOUT, timeout, stop, "write");
|
||||||
|
if (!waited.has_value()) {
|
||||||
|
return std::unexpected{
|
||||||
|
std::move(waited.error())};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
const std::size_t chunk =
|
||||||
|
std::min<std::size_t>(data.size(), 4096U);
|
||||||
|
#if defined(_WIN32)
|
||||||
|
const int rc = ::_write(
|
||||||
|
fd, data.data(), static_cast<unsigned int>(chunk));
|
||||||
|
#else
|
||||||
|
const ssize_t rc = ::write(fd, data.data(), chunk);
|
||||||
|
#endif
|
||||||
|
if (rc < 0) {
|
||||||
|
if (errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (errno == EAGAIN || errno == EWOULDBLOCK) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::transport_closed,
|
||||||
|
std::format("MCP: stdio write failed: {}",
|
||||||
|
std::strerror(errno)))};
|
||||||
|
}
|
||||||
|
data.remove_prefix(static_cast<std::size_t>(rc));
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::optional<std::string_view>
|
||||||
|
header_value(const HttpRequest& request, std::string_view name)
|
||||||
|
{
|
||||||
|
for (const auto& header : request.headers) {
|
||||||
|
if (ascii_iequals(header.name, name)) {
|
||||||
|
return header.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct StreamableHttpEndpoint::Impl {
|
||||||
|
RequestHandler requests;
|
||||||
|
NotificationHandler notifications;
|
||||||
|
StreamableHttpOptions options;
|
||||||
|
|
||||||
|
Impl(RequestHandler request_handler,
|
||||||
|
NotificationHandler notification_handler,
|
||||||
|
StreamableHttpOptions opts)
|
||||||
|
: requests(std::move(request_handler)),
|
||||||
|
notifications(std::move(notification_handler)),
|
||||||
|
options(std::move(opts))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
StreamableHttpEndpoint::StreamableHttpEndpoint(
|
||||||
|
RequestHandler requests, NotificationHandler notifications,
|
||||||
|
StreamableHttpOptions options)
|
||||||
|
: m_impl(std::make_unique<Impl>(std::move(requests),
|
||||||
|
std::move(notifications),
|
||||||
|
std::move(options)))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
StreamableHttpEndpoint::~StreamableHttpEndpoint() = default;
|
||||||
|
|
||||||
|
HttpResponse StreamableHttpEndpoint::handle(
|
||||||
|
const HttpRequest& request) const
|
||||||
|
{
|
||||||
|
const auto& options = m_impl->options;
|
||||||
|
const auto& limits = options.limits;
|
||||||
|
|
||||||
|
if (request.method != "POST") {
|
||||||
|
return error_response(
|
||||||
|
405, JsonRpcId{}, McpErrorCode::method_not_allowed,
|
||||||
|
"MCP: 2026-07-28 Streamable HTTP accepts POST only", limits);
|
||||||
|
}
|
||||||
|
const auto content_type = header_value(request, "Content-Type");
|
||||||
|
if (!content_type.has_value() ||
|
||||||
|
!contains_token(*content_type, kJsonContentType)) {
|
||||||
|
return error_response(
|
||||||
|
415, JsonRpcId{}, McpErrorCode::unsupported_media_type,
|
||||||
|
"MCP: Content-Type must be application/json", limits);
|
||||||
|
}
|
||||||
|
const auto accept = header_value(request, "Accept");
|
||||||
|
if (!accept.has_value() ||
|
||||||
|
!contains_token(*accept, kJsonContentType) ||
|
||||||
|
!contains_token(*accept, kSseContentType)) {
|
||||||
|
return error_response(
|
||||||
|
406, JsonRpcId{}, McpErrorCode::not_acceptable,
|
||||||
|
"MCP: Accept must list application/json and "
|
||||||
|
"text/event-stream",
|
||||||
|
limits);
|
||||||
|
}
|
||||||
|
if (options.authorize) {
|
||||||
|
auto authorized = options.authorize(request);
|
||||||
|
if (!authorized.has_value()) {
|
||||||
|
return error_response(
|
||||||
|
401, JsonRpcId{}, McpErrorCode::unauthorized,
|
||||||
|
"MCP: authorization failed", limits);
|
||||||
|
}
|
||||||
|
} else if (options.require_authorization) {
|
||||||
|
return error_response(
|
||||||
|
401, JsonRpcId{}, McpErrorCode::unauthorized,
|
||||||
|
"MCP: authorization is required", limits);
|
||||||
|
}
|
||||||
|
if (request.body.size() > limits.max_message_bytes) {
|
||||||
|
return error_response(
|
||||||
|
413, JsonRpcId{}, McpErrorCode::payload_too_large,
|
||||||
|
"MCP: request body exceeds message limit", limits);
|
||||||
|
}
|
||||||
|
auto message = decode_message(request.body, limits);
|
||||||
|
if (!message.has_value()) {
|
||||||
|
return error_response(
|
||||||
|
400, parse_id_from_body(request.body),
|
||||||
|
McpErrorCode::parse_error, message.error().message(),
|
||||||
|
limits);
|
||||||
|
}
|
||||||
|
if (std::holds_alternative<Response>(*message)) {
|
||||||
|
return error_response(
|
||||||
|
400, message_id(*message), McpErrorCode::invalid_request,
|
||||||
|
"MCP: clients must not POST JSON-RPC responses", limits);
|
||||||
|
}
|
||||||
|
|
||||||
|
const RequestMetadata metadata = message_metadata(*message);
|
||||||
|
const auto protocol_header =
|
||||||
|
header_value(request, kProtocolHeader);
|
||||||
|
if (!protocol_header.has_value() ||
|
||||||
|
*protocol_header != metadata.protocol_version) {
|
||||||
|
return error_response(
|
||||||
|
400, message_id(*message), McpErrorCode::header_mismatch,
|
||||||
|
"MCP: MCP-Protocol-Version header missing or does not "
|
||||||
|
"match _meta",
|
||||||
|
limits);
|
||||||
|
}
|
||||||
|
const bool version_supported = std::ranges::any_of(
|
||||||
|
options.supported_versions,
|
||||||
|
[&](const std::string& version) {
|
||||||
|
return version == metadata.protocol_version;
|
||||||
|
});
|
||||||
|
if (!version_supported) {
|
||||||
|
JsonValue::Object data;
|
||||||
|
JsonValue::Array supported;
|
||||||
|
for (const auto& version : options.supported_versions) {
|
||||||
|
supported.push_back(JsonValue{version});
|
||||||
|
}
|
||||||
|
data["supported"] = JsonValue{std::move(supported)};
|
||||||
|
data["requested"] = JsonValue{metadata.protocol_version};
|
||||||
|
return error_response(
|
||||||
|
400, message_id(*message),
|
||||||
|
McpErrorCode::unsupported_protocol_version,
|
||||||
|
"MCP: unsupported protocol version", limits,
|
||||||
|
JsonValue{std::move(data)});
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::string method =
|
||||||
|
std::holds_alternative<Request>(*message)
|
||||||
|
? std::get<Request>(*message).method
|
||||||
|
: std::get<Notification>(*message).method;
|
||||||
|
const auto method_header = header_value(request, kMethodHeader);
|
||||||
|
if (!method_header.has_value() || *method_header != method) {
|
||||||
|
return error_response(
|
||||||
|
400, message_id(*message), McpErrorCode::header_mismatch,
|
||||||
|
"MCP: Mcp-Method header missing or does not match the "
|
||||||
|
"body method",
|
||||||
|
limits);
|
||||||
|
}
|
||||||
|
if (method_requires_name(method)) {
|
||||||
|
const auto& request_message = std::get<Request>(*message);
|
||||||
|
const auto name = request_name(request_message);
|
||||||
|
const auto name_header = header_value(request, kNameHeader);
|
||||||
|
if (!name.has_value() || !name_header.has_value() ||
|
||||||
|
*name_header != *name) {
|
||||||
|
return error_response(
|
||||||
|
400, message_id(*message),
|
||||||
|
McpErrorCode::header_mismatch,
|
||||||
|
"MCP: Mcp-Name header missing or does not match the "
|
||||||
|
"body",
|
||||||
|
limits);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (const auto* notification = std::get_if<Notification>(&*message)) {
|
||||||
|
auto accepted =
|
||||||
|
m_impl->notifications
|
||||||
|
? m_impl->notifications(*notification)
|
||||||
|
: Void::Result::Result<void>{};
|
||||||
|
if (!accepted.has_value()) {
|
||||||
|
return error_response(
|
||||||
|
400, JsonRpcId{}, McpErrorCode::invalid_request,
|
||||||
|
accepted.error().message(), limits);
|
||||||
|
}
|
||||||
|
HttpResponse response;
|
||||||
|
response.status = 202;
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto& request_message = std::get<Request>(*message);
|
||||||
|
auto handled =
|
||||||
|
m_impl->requests
|
||||||
|
? m_impl->requests(request_message)
|
||||||
|
: Void::Result::Result<Message>{std::unexpected{
|
||||||
|
make_mcp_error(McpErrorCode::method_not_found,
|
||||||
|
"MCP: no request handler")}};
|
||||||
|
if (!handled.has_value()) {
|
||||||
|
const auto& error = handled.error();
|
||||||
|
const auto code =
|
||||||
|
error.code().domain == kMcpErrorDomain
|
||||||
|
? static_cast<McpErrorCode>(error.code().value)
|
||||||
|
: McpErrorCode::internal_error;
|
||||||
|
return json_response(
|
||||||
|
200,
|
||||||
|
make_error_response(request_message.id,
|
||||||
|
json_rpc_error_code(code),
|
||||||
|
error.message()),
|
||||||
|
limits);
|
||||||
|
}
|
||||||
|
|
||||||
|
auto encoded = encode_message(*handled, limits);
|
||||||
|
if (!encoded.has_value()) {
|
||||||
|
return error_response(
|
||||||
|
500, request_message.id, McpErrorCode::internal_error,
|
||||||
|
encoded.error().message(), limits);
|
||||||
|
}
|
||||||
|
HttpResponse response;
|
||||||
|
response.status = 200;
|
||||||
|
if (options.prefer_sse) {
|
||||||
|
response.headers.push_back(
|
||||||
|
{"Content-Type", std::string{kSseContentType}});
|
||||||
|
auto event = encode_sse_event(
|
||||||
|
SseEvent{.event = "message", .data = std::move(*encoded)},
|
||||||
|
limits);
|
||||||
|
if (!event.has_value()) {
|
||||||
|
return error_response(
|
||||||
|
500, request_message.id,
|
||||||
|
McpErrorCode::payload_too_large,
|
||||||
|
event.error().message(), limits);
|
||||||
|
}
|
||||||
|
response.body = std::move(*event);
|
||||||
|
} else {
|
||||||
|
response.headers.push_back(
|
||||||
|
{"Content-Type", std::string{kJsonContentType}});
|
||||||
|
response.body = std::move(*encoded);
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct StdioTransport::Impl {
|
||||||
|
int read_fd{-1};
|
||||||
|
int write_fd{-1};
|
||||||
|
RequestHandler requests;
|
||||||
|
NotificationHandler notifications;
|
||||||
|
McpLimits limits;
|
||||||
|
std::chrono::milliseconds io_timeout;
|
||||||
|
LineFramer framer;
|
||||||
|
|
||||||
|
Impl(int reader, int writer, RequestHandler request_handler,
|
||||||
|
NotificationHandler notification_handler, McpLimits
|
||||||
|
transport_limits,
|
||||||
|
std::chrono::milliseconds timeout)
|
||||||
|
: read_fd(reader), write_fd(writer),
|
||||||
|
requests(std::move(request_handler)),
|
||||||
|
notifications(std::move(notification_handler)),
|
||||||
|
limits(std::move(transport_limits)), io_timeout(timeout),
|
||||||
|
framer(limits)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
StdioTransport::StdioTransport(int read_fd, int write_fd,
|
||||||
|
RequestHandler requests,
|
||||||
|
NotificationHandler notifications,
|
||||||
|
McpLimits limits,
|
||||||
|
std::chrono::milliseconds io_timeout)
|
||||||
|
: m_impl(std::make_unique<Impl>(
|
||||||
|
read_fd, write_fd, std::move(requests),
|
||||||
|
std::move(notifications), std::move(limits), io_timeout))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
StdioTransport::~StdioTransport() = default;
|
||||||
|
|
||||||
|
Void::Result::Result<std::optional<Message>>
|
||||||
|
StdioTransport::read_message(std::stop_token stop)
|
||||||
|
{
|
||||||
|
auto& impl = *m_impl;
|
||||||
|
for (;;) {
|
||||||
|
if (stop.stop_requested()) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::cancelled, "MCP: stdio read cancelled")};
|
||||||
|
}
|
||||||
|
auto line = impl.framer.next();
|
||||||
|
if (!line.has_value()) {
|
||||||
|
return std::unexpected{std::move(line.error())};
|
||||||
|
}
|
||||||
|
if (line->has_value()) {
|
||||||
|
auto message =
|
||||||
|
decode_message(**line, impl.limits);
|
||||||
|
if (!message.has_value()) {
|
||||||
|
return std::unexpected{
|
||||||
|
std::move(message.error())};
|
||||||
|
}
|
||||||
|
return std::optional<Message>{std::move(*message)};
|
||||||
|
}
|
||||||
|
std::array<std::byte, 8192> buffer{};
|
||||||
|
auto count = fd_read(impl.read_fd, buffer);
|
||||||
|
if (!count.has_value()) {
|
||||||
|
#if !defined(_WIN32)
|
||||||
|
if (errno == EAGAIN || errno == EWOULDBLOCK) {
|
||||||
|
auto waited = wait_fd(impl.read_fd, POLLIN,
|
||||||
|
impl.io_timeout, stop, "read");
|
||||||
|
if (!waited.has_value()) {
|
||||||
|
return std::unexpected{
|
||||||
|
std::move(waited.error())};
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
return std::unexpected{std::move(count.error())};
|
||||||
|
}
|
||||||
|
if (*count == 0) {
|
||||||
|
if (impl.framer.buffered() > 0) {
|
||||||
|
return std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::protocol_error,
|
||||||
|
"MCP: stdio stream ended mid-frame")};
|
||||||
|
}
|
||||||
|
return std::optional<Message>{};
|
||||||
|
}
|
||||||
|
auto appended = impl.framer.append(std::string_view{
|
||||||
|
reinterpret_cast<const char*>(buffer.data()), *count});
|
||||||
|
if (!appended.has_value()) {
|
||||||
|
return std::unexpected{std::move(appended.error())};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void>
|
||||||
|
StdioTransport::write_message(const Message& message,
|
||||||
|
std::stop_token stop)
|
||||||
|
{
|
||||||
|
auto& impl = *m_impl;
|
||||||
|
auto encoded = encode_message(message, impl.limits);
|
||||||
|
if (!encoded.has_value()) {
|
||||||
|
return std::unexpected{std::move(encoded.error())};
|
||||||
|
}
|
||||||
|
auto frame = frame_line(*encoded, impl.limits);
|
||||||
|
if (!frame.has_value()) {
|
||||||
|
return std::unexpected{std::move(frame.error())};
|
||||||
|
}
|
||||||
|
return write_all_fd(impl.write_fd, *frame, impl.io_timeout, stop);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void> StdioTransport::run(std::stop_token stop)
|
||||||
|
{
|
||||||
|
for (;;) {
|
||||||
|
auto message = read_message(stop);
|
||||||
|
if (!message.has_value()) {
|
||||||
|
if (message.error().kind() ==
|
||||||
|
Void::Result::ErrorKind::cancelled) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
// Malformed frame: answer and keep reading.
|
||||||
|
auto error_response = make_error_response(
|
||||||
|
JsonRpcId{}, json_rpc_error_code(
|
||||||
|
McpErrorCode::parse_error),
|
||||||
|
message.error().message());
|
||||||
|
auto written = write_message(error_response, stop);
|
||||||
|
if (!written.has_value()) {
|
||||||
|
return std::unexpected{
|
||||||
|
std::move(written.error())};
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!message->has_value()) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
Message inbound = std::move(**message);
|
||||||
|
if (const auto* request = std::get_if<Request>(&inbound)) {
|
||||||
|
auto handled =
|
||||||
|
m_impl->requests
|
||||||
|
? m_impl->requests(*request)
|
||||||
|
: Void::Result::Result<Message>{
|
||||||
|
std::unexpected{make_mcp_error(
|
||||||
|
McpErrorCode::method_not_found,
|
||||||
|
"MCP: no request handler")}};
|
||||||
|
if (!handled.has_value()) {
|
||||||
|
handled = make_error_response(
|
||||||
|
request->id,
|
||||||
|
json_rpc_error_code(McpErrorCode::internal_error),
|
||||||
|
handled.error().message());
|
||||||
|
}
|
||||||
|
auto written = write_message(*handled, stop);
|
||||||
|
if (!written.has_value()) {
|
||||||
|
return std::unexpected{
|
||||||
|
std::move(written.error())};
|
||||||
|
}
|
||||||
|
} else if (const auto* notification =
|
||||||
|
std::get_if<Notification>(&inbound)) {
|
||||||
|
if (m_impl->notifications) {
|
||||||
|
auto accepted =
|
||||||
|
m_impl->notifications(*notification);
|
||||||
|
if (!accepted.has_value()) {
|
||||||
|
return std::unexpected{
|
||||||
|
std::move(accepted.error())};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::MCP
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
void_add_module(MCP
|
||||||
|
INTERNAL_DEPS Functional Data
|
||||||
|
)
|
||||||
+103
-1
@@ -24,6 +24,19 @@
|
|||||||
#include <sys/stat.h>
|
#include <sys/stat.h>
|
||||||
#include <sys/time.h>
|
#include <sys/time.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
|
#else
|
||||||
|
#ifndef NOMINMAX
|
||||||
|
#define NOMINMAX
|
||||||
|
#endif
|
||||||
|
#ifndef WIN32_LEAN_AND_MEAN
|
||||||
|
#define WIN32_LEAN_AND_MEAN
|
||||||
|
#endif
|
||||||
|
#include <windows.h>
|
||||||
|
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <io.h>
|
||||||
|
#include <process.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
@@ -56,6 +69,26 @@ namespace Void::Net
|
|||||||
|
|
||||||
std::atomic<std::uint64_t> g_dl_temp_seq{0};
|
std::atomic<std::uint64_t> g_dl_temp_seq{0};
|
||||||
|
|
||||||
|
#if defined(_WIN32)
|
||||||
|
// Win32 paths above MAX_PATH must use the extended-length prefix, and
|
||||||
|
// forward slashes are not accepted by the wide file APIs.
|
||||||
|
[[nodiscard]] std::filesystem::path
|
||||||
|
extended_path(const std::filesystem::path& path)
|
||||||
|
{
|
||||||
|
std::error_code ec;
|
||||||
|
const auto absolute = std::filesystem::absolute(path, ec);
|
||||||
|
std::wstring text = (ec ? path : absolute).wstring();
|
||||||
|
std::replace(text.begin(), text.end(), L'/', L'\\');
|
||||||
|
if (text.rfind(L"\\\\?\\", 0) == 0 || text.size() < MAX_PATH) {
|
||||||
|
return std::filesystem::path{text};
|
||||||
|
}
|
||||||
|
if (text.rfind(L"\\\\", 0) == 0) {
|
||||||
|
return std::filesystem::path{L"\\\\?\\UNC\\" + text.substr(2)};
|
||||||
|
}
|
||||||
|
return std::filesystem::path{L"\\\\?\\" + text};
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
[[nodiscard]] bool
|
[[nodiscard]] bool
|
||||||
equal_ascii_ci(std::string_view a, std::string_view b) noexcept
|
equal_ascii_ci(std::string_view a, std::string_view b) noexcept
|
||||||
{
|
{
|
||||||
@@ -557,13 +590,26 @@ namespace Void::Net
|
|||||||
}
|
}
|
||||||
const std::filesystem::path tmp_path =
|
const std::filesystem::path tmp_path =
|
||||||
parent / std::format(".void-dl-{}-{}",
|
parent / std::format(".void-dl-{}-{}",
|
||||||
|
#if defined(_WIN32)
|
||||||
|
static_cast<long long>(::_getpid()),
|
||||||
|
#else
|
||||||
static_cast<long long>(::getpid()),
|
static_cast<long long>(::getpid()),
|
||||||
|
#endif
|
||||||
g_dl_temp_seq.fetch_add(
|
g_dl_temp_seq.fetch_add(
|
||||||
1, std::memory_order_relaxed));
|
1, std::memory_order_relaxed));
|
||||||
|
#if defined(_WIN32)
|
||||||
|
// Create exclusively next to the destination: an existing entry
|
||||||
|
// (including a reparse point) is never followed or truncated.
|
||||||
|
const int fd = ::_wopen(
|
||||||
|
extended_path(tmp_path).c_str(),
|
||||||
|
_O_WRONLY | _O_CREAT | _O_EXCL | _O_BINARY | _O_NOINHERIT,
|
||||||
|
_S_IREAD | _S_IWRITE);
|
||||||
|
#else
|
||||||
const int fd = ::open(
|
const int fd = ::open(
|
||||||
tmp_path.c_str(),
|
tmp_path.c_str(),
|
||||||
O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW,
|
O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW,
|
||||||
0644);
|
0644);
|
||||||
|
#endif
|
||||||
if (fd < 0) {
|
if (fd < 0) {
|
||||||
return std::unexpected{make_net_error(
|
return std::unexpected{make_net_error(
|
||||||
NetErrorCode::io_error,
|
NetErrorCode::io_error,
|
||||||
@@ -593,10 +639,17 @@ namespace Void::Net
|
|||||||
{
|
{
|
||||||
std::size_t off = 0;
|
std::size_t off = 0;
|
||||||
while (off < data.size()) {
|
while (off < data.size()) {
|
||||||
|
#if defined(_WIN32)
|
||||||
|
const int w = ::_write(
|
||||||
|
m_fd,
|
||||||
|
reinterpret_cast<const char*>(data.data()) + off,
|
||||||
|
static_cast<unsigned int>(data.size() - off));
|
||||||
|
#else
|
||||||
const ssize_t w = ::write(
|
const ssize_t w = ::write(
|
||||||
m_fd,
|
m_fd,
|
||||||
reinterpret_cast<const char*>(data.data()) + off,
|
reinterpret_cast<const char*>(data.data()) + off,
|
||||||
data.size() - off);
|
data.size() - off);
|
||||||
|
#endif
|
||||||
if (w < 0 && errno == EINTR) {
|
if (w < 0 && errno == EINTR) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -616,6 +669,50 @@ namespace Void::Net
|
|||||||
|
|
||||||
[[nodiscard]] Void::Result::Result<void> commit()
|
[[nodiscard]] Void::Result::Result<void> commit()
|
||||||
{
|
{
|
||||||
|
#if defined(_WIN32)
|
||||||
|
if (::_commit(m_fd) != 0) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error,
|
||||||
|
std::format("Net: flush download file failed: {}",
|
||||||
|
std::strerror(errno)),
|
||||||
|
std::error_code{errno, std::generic_category()})};
|
||||||
|
}
|
||||||
|
const int raw = std::exchange(m_fd, -1);
|
||||||
|
if (::_close(raw) != 0) {
|
||||||
|
discard();
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error,
|
||||||
|
std::format("Net: close download file failed: {}",
|
||||||
|
std::strerror(errno)),
|
||||||
|
std::error_code{errno, std::generic_category()})};
|
||||||
|
}
|
||||||
|
// Never replace a reparse point: a hostile workspace entry
|
||||||
|
// could redirect the completed download outside the target.
|
||||||
|
const DWORD attributes =
|
||||||
|
::GetFileAttributesW(extended_path(m_dest).c_str());
|
||||||
|
if (attributes != INVALID_FILE_ATTRIBUTES &&
|
||||||
|
(attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {
|
||||||
|
discard();
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error,
|
||||||
|
"Net: refusing to replace a reparse-point "
|
||||||
|
"download destination")};
|
||||||
|
}
|
||||||
|
if (::MoveFileExW(extended_path(m_tmp).c_str(),
|
||||||
|
extended_path(m_dest).c_str(),
|
||||||
|
MOVEFILE_REPLACE_EXISTING |
|
||||||
|
MOVEFILE_WRITE_THROUGH) == 0) {
|
||||||
|
const DWORD error = ::GetLastError();
|
||||||
|
discard();
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error,
|
||||||
|
std::format("Net: replace download file failed: "
|
||||||
|
"win32={}",
|
||||||
|
error),
|
||||||
|
std::error_code{static_cast<int>(error),
|
||||||
|
std::system_category()})};
|
||||||
|
}
|
||||||
|
#else
|
||||||
if (::fsync(m_fd) != 0) {
|
if (::fsync(m_fd) != 0) {
|
||||||
return std::unexpected{make_net_error(
|
return std::unexpected{make_net_error(
|
||||||
NetErrorCode::io_error,
|
NetErrorCode::io_error,
|
||||||
@@ -639,9 +736,10 @@ namespace Void::Net
|
|||||||
return std::unexpected{make_net_error(
|
return std::unexpected{make_net_error(
|
||||||
NetErrorCode::io_error,
|
NetErrorCode::io_error,
|
||||||
std::format("Net: rename download file failed: {}",
|
std::format("Net: rename download file failed: {}",
|
||||||
ec.message()),
|
ec.message()),
|
||||||
ec)};
|
ec)};
|
||||||
}
|
}
|
||||||
|
#endif
|
||||||
m_committed = true;
|
m_committed = true;
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
@@ -649,7 +747,11 @@ namespace Void::Net
|
|||||||
void discard() noexcept
|
void discard() noexcept
|
||||||
{
|
{
|
||||||
if (m_fd >= 0) {
|
if (m_fd >= 0) {
|
||||||
|
#if defined(_WIN32)
|
||||||
|
(void)::_close(m_fd);
|
||||||
|
#else
|
||||||
(void)::close(m_fd);
|
(void)::close(m_fd);
|
||||||
|
#endif
|
||||||
m_fd = -1;
|
m_fd = -1;
|
||||||
}
|
}
|
||||||
if (!m_committed && !m_tmp.empty()) {
|
if (!m_committed && !m_tmp.empty()) {
|
||||||
|
|||||||
+770
-7
@@ -867,6 +867,588 @@ namespace Void::Net
|
|||||||
return written_total;
|
return written_total;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct ResponseWriter::State {
|
||||||
|
int fd{-1};
|
||||||
|
const std::atomic<bool>* stopping{nullptr};
|
||||||
|
|
||||||
|
std::atomic<bool> cancel_requested{false};
|
||||||
|
std::atomic<bool> head_attempted{false};
|
||||||
|
std::atomic<bool> begun{false};
|
||||||
|
std::atomic<bool> finished{false};
|
||||||
|
std::atomic<bool> invalid{false};
|
||||||
|
std::atomic<bool> chunked{false};
|
||||||
|
std::atomic<bool> bodyless{false};
|
||||||
|
std::atomic<bool> fixed_length{false};
|
||||||
|
std::atomic<bool> close_delimited{false};
|
||||||
|
std::atomic<bool> has_content_length{false};
|
||||||
|
std::atomic<bool> keep_alive{true};
|
||||||
|
std::atomic<std::uint64_t> content_length{0};
|
||||||
|
std::atomic<std::uint64_t> accepted{0};
|
||||||
|
std::atomic<std::uint64_t> sent{0};
|
||||||
|
std::atomic<std::size_t> pending_bytes{0};
|
||||||
|
std::atomic<std::chrono::milliseconds::rep> write_timeout_ms{
|
||||||
|
std::chrono::seconds{30}.count()};
|
||||||
|
|
||||||
|
std::mutex io_mutex{};
|
||||||
|
std::string pending{};
|
||||||
|
std::size_t max_pending{64ULL * 1024};
|
||||||
|
bool head_request{false};
|
||||||
|
bool http10{false};
|
||||||
|
|
||||||
|
std::stop_source stop_source{};
|
||||||
|
|
||||||
|
[[nodiscard]] bool stopped() const noexcept
|
||||||
|
{
|
||||||
|
return cancel_requested.load(std::memory_order_acquire) ||
|
||||||
|
(stopping != nullptr &&
|
||||||
|
stopping->load(std::memory_order_acquire));
|
||||||
|
}
|
||||||
|
|
||||||
|
void request_stop() noexcept
|
||||||
|
{
|
||||||
|
(void)stop_source.request_stop();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
writer_send_all(ResponseWriter::State& state,
|
||||||
|
std::span<const std::byte> data)
|
||||||
|
{
|
||||||
|
const auto timeout = std::chrono::milliseconds{
|
||||||
|
state.write_timeout_ms.load(std::memory_order_acquire)};
|
||||||
|
const auto deadline = std::chrono::steady_clock::now() + timeout;
|
||||||
|
std::size_t off = 0;
|
||||||
|
while (off < data.size()) {
|
||||||
|
if (state.stopped()) {
|
||||||
|
state.request_stop();
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::cancelled,
|
||||||
|
"Net::ResponseWriter: exchange cancelled")};
|
||||||
|
}
|
||||||
|
const auto now = std::chrono::steady_clock::now();
|
||||||
|
if (timeout > std::chrono::milliseconds::zero() &&
|
||||||
|
now >= deadline) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::timeout,
|
||||||
|
"Net::ResponseWriter: write timeout")};
|
||||||
|
}
|
||||||
|
int wait_ms = 100;
|
||||||
|
if (timeout > std::chrono::milliseconds::zero()) {
|
||||||
|
const auto rem = std::chrono::duration_cast<
|
||||||
|
std::chrono::milliseconds>(deadline - now)
|
||||||
|
.count();
|
||||||
|
wait_ms = static_cast<int>(std::clamp<long long>(rem, 1, 100));
|
||||||
|
}
|
||||||
|
|
||||||
|
struct pollfd pfd{};
|
||||||
|
pfd.fd = state.fd;
|
||||||
|
pfd.events = POLLOUT;
|
||||||
|
const int pr = ::poll(&pfd, 1, wait_ms);
|
||||||
|
if (pr < 0) {
|
||||||
|
if (errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error,
|
||||||
|
"Net::ResponseWriter: poll failed")};
|
||||||
|
}
|
||||||
|
if (pr == 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const ssize_t n = ::send(
|
||||||
|
state.fd,
|
||||||
|
reinterpret_cast<const char*>(data.data()) + off,
|
||||||
|
data.size() - off, MSG_NOSIGNAL);
|
||||||
|
if (n < 0) {
|
||||||
|
if (errno == EINTR || errno == EAGAIN ||
|
||||||
|
errno == EWOULDBLOCK) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
state.request_stop();
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error,
|
||||||
|
std::format("Net::ResponseWriter: send failed: {}",
|
||||||
|
std::strerror(errno)),
|
||||||
|
std::error_code{errno, std::generic_category()})};
|
||||||
|
}
|
||||||
|
if (n == 0) {
|
||||||
|
state.request_stop();
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error,
|
||||||
|
"Net::ResponseWriter: peer closed connection")};
|
||||||
|
}
|
||||||
|
off += static_cast<std::size_t>(n);
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
writer_flush(ResponseWriter::State& state)
|
||||||
|
{
|
||||||
|
if (state.pending.empty()) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
auto res = writer_send_all(
|
||||||
|
state, std::as_bytes(std::span{state.pending.data(),
|
||||||
|
state.pending.size()}));
|
||||||
|
if (!res.has_value()) {
|
||||||
|
return std::unexpected{std::move(res.error())};
|
||||||
|
}
|
||||||
|
state.pending.clear();
|
||||||
|
state.pending_bytes.store(0, std::memory_order_release);
|
||||||
|
state.sent.store(state.accepted.load(std::memory_order_acquire),
|
||||||
|
std::memory_order_release);
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
writer_require_active(const std::shared_ptr<ResponseWriter::State>& s)
|
||||||
|
{
|
||||||
|
if (!s || s->invalid.load(std::memory_order_acquire)) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: exchange is no longer active")};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
bool ResponseWriter::valid() const noexcept
|
||||||
|
{
|
||||||
|
return m_state != nullptr &&
|
||||||
|
!m_state->invalid.load(std::memory_order_acquire);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ResponseWriter::begun() const noexcept
|
||||||
|
{
|
||||||
|
return m_state != nullptr &&
|
||||||
|
m_state->begun.load(std::memory_order_acquire);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ResponseWriter::finished() const noexcept
|
||||||
|
{
|
||||||
|
return m_state != nullptr &&
|
||||||
|
m_state->finished.load(std::memory_order_acquire);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ResponseWriter::cancelled() const noexcept
|
||||||
|
{
|
||||||
|
return m_state == nullptr ||
|
||||||
|
m_state->cancel_requested.load(std::memory_order_acquire) ||
|
||||||
|
(m_state->stopping != nullptr &&
|
||||||
|
m_state->stopping->load(std::memory_order_acquire));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ResponseWriter::chunked() const noexcept
|
||||||
|
{
|
||||||
|
return m_state != nullptr &&
|
||||||
|
m_state->chunked.load(std::memory_order_acquire);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<std::uint64_t> ResponseWriter::content_length() const noexcept
|
||||||
|
{
|
||||||
|
if (m_state == nullptr ||
|
||||||
|
!m_state->has_content_length.load(std::memory_order_acquire)) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return m_state->content_length.load(std::memory_order_acquire);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::uint64_t ResponseWriter::bytes_accepted() const noexcept
|
||||||
|
{
|
||||||
|
return m_state != nullptr
|
||||||
|
? m_state->accepted.load(std::memory_order_acquire)
|
||||||
|
: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::uint64_t ResponseWriter::bytes_sent() const noexcept
|
||||||
|
{
|
||||||
|
return m_state != nullptr
|
||||||
|
? m_state->sent.load(std::memory_order_acquire)
|
||||||
|
: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t ResponseWriter::buffered_bytes() const noexcept
|
||||||
|
{
|
||||||
|
return m_state != nullptr
|
||||||
|
? m_state->pending_bytes.load(std::memory_order_acquire)
|
||||||
|
: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::stop_token ResponseWriter::stop_token() const noexcept
|
||||||
|
{
|
||||||
|
return m_state != nullptr ? m_state->stop_source.get_token()
|
||||||
|
: std::stop_token{};
|
||||||
|
}
|
||||||
|
|
||||||
|
void ResponseWriter::cancel() noexcept
|
||||||
|
{
|
||||||
|
if (m_state) {
|
||||||
|
m_state->cancel_requested.store(true, std::memory_order_release);
|
||||||
|
m_state->request_stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ResponseWriter::set_write_timeout(
|
||||||
|
std::chrono::milliseconds timeout) noexcept
|
||||||
|
{
|
||||||
|
if (m_state) {
|
||||||
|
m_state->write_timeout_ms.store(timeout.count(),
|
||||||
|
std::memory_order_release);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::chrono::milliseconds ResponseWriter::write_timeout() const noexcept
|
||||||
|
{
|
||||||
|
return std::chrono::milliseconds{
|
||||||
|
m_state != nullptr
|
||||||
|
? m_state->write_timeout_ms.load(std::memory_order_acquire)
|
||||||
|
: std::chrono::seconds{30}.count()};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void>
|
||||||
|
ResponseWriter::begin(std::uint16_t status, std::vector<Header> headers)
|
||||||
|
{
|
||||||
|
auto active = writer_require_active(m_state);
|
||||||
|
if (!active.has_value()) {
|
||||||
|
return active;
|
||||||
|
}
|
||||||
|
State& state = *m_state;
|
||||||
|
std::unique_lock lock{state.io_mutex, std::try_to_lock};
|
||||||
|
if (!lock.owns_lock()) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
Void::Result::ErrorKind::overloaded,
|
||||||
|
"Net::ResponseWriter: concurrent writer");
|
||||||
|
}
|
||||||
|
if (state.invalid.load(std::memory_order_acquire)) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: exchange is no longer active")};
|
||||||
|
}
|
||||||
|
if (state.begun.load(std::memory_order_acquire)) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: response already started")};
|
||||||
|
}
|
||||||
|
if (state.stopped()) {
|
||||||
|
state.request_stop();
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::cancelled,
|
||||||
|
"Net::ResponseWriter: exchange cancelled")};
|
||||||
|
}
|
||||||
|
if (status < 100 || status > 599) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: invalid status code")};
|
||||||
|
}
|
||||||
|
|
||||||
|
const bool bodyless = state.head_request ||
|
||||||
|
(status >= 100 && status < 200) || status == 204 ||
|
||||||
|
status == 304;
|
||||||
|
|
||||||
|
std::optional<std::uint64_t> content_length;
|
||||||
|
std::optional<std::string> transfer_encoding;
|
||||||
|
bool connection_close = false;
|
||||||
|
std::string extra_headers;
|
||||||
|
for (const auto& header : headers) {
|
||||||
|
if (!is_valid_token(header.name) ||
|
||||||
|
has_crlf_or_nul(header.name) ||
|
||||||
|
has_crlf_or_nul(header.value)) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: invalid response header")};
|
||||||
|
}
|
||||||
|
if (equal_ascii_ci(header.name, "Content-Length")) {
|
||||||
|
std::uint64_t parsed = 0;
|
||||||
|
if (!parse_u64_decimal(trim_ows(header.value), parsed)) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: invalid Content-Length")};
|
||||||
|
}
|
||||||
|
if (content_length.has_value() &&
|
||||||
|
*content_length != parsed) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: conflicting Content-Length")};
|
||||||
|
}
|
||||||
|
content_length = parsed;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (equal_ascii_ci(header.name, "Transfer-Encoding")) {
|
||||||
|
if (transfer_encoding.has_value()) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: duplicate Transfer-Encoding")};
|
||||||
|
}
|
||||||
|
transfer_encoding = header.value;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (equal_ascii_ci(header.name, "Connection")) {
|
||||||
|
if (contains_ascii_ci(header.value, "close")) {
|
||||||
|
connection_close = true;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
extra_headers += header.name;
|
||||||
|
extra_headers += ": ";
|
||||||
|
extra_headers += header.value;
|
||||||
|
extra_headers += "\r\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (transfer_encoding.has_value() &&
|
||||||
|
!equal_ascii_ci(trim_ows(*transfer_encoding), "chunked")) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: unsupported Transfer-Encoding")};
|
||||||
|
}
|
||||||
|
if (transfer_encoding.has_value() && content_length.has_value()) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: ambiguous response framing")};
|
||||||
|
}
|
||||||
|
if (bodyless && transfer_encoding.has_value()) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: bodyless response with "
|
||||||
|
"Transfer-Encoding")};
|
||||||
|
}
|
||||||
|
if (bodyless && content_length.has_value() && !state.head_request &&
|
||||||
|
status != 304) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: bodyless response with "
|
||||||
|
"Content-Length")};
|
||||||
|
}
|
||||||
|
|
||||||
|
bool chunked = false;
|
||||||
|
bool fixed = false;
|
||||||
|
bool close_delimited = false;
|
||||||
|
if (!bodyless) {
|
||||||
|
if (transfer_encoding.has_value()) {
|
||||||
|
chunked = true;
|
||||||
|
} else if (content_length.has_value()) {
|
||||||
|
fixed = true;
|
||||||
|
} else if (state.http10) {
|
||||||
|
close_delimited = true;
|
||||||
|
} else {
|
||||||
|
chunked = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool keep = state.keep_alive.load(std::memory_order_acquire) &&
|
||||||
|
!close_delimited;
|
||||||
|
if (connection_close) {
|
||||||
|
keep = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string head =
|
||||||
|
std::format("HTTP/1.1 {} {}\r\n", status, reason_phrase(status));
|
||||||
|
head += extra_headers;
|
||||||
|
if (bodyless) {
|
||||||
|
if (content_length.has_value()) {
|
||||||
|
head += std::format("Content-Length: {}\r\n",
|
||||||
|
*content_length);
|
||||||
|
}
|
||||||
|
} else if (fixed) {
|
||||||
|
head += std::format("Content-Length: {}\r\n", *content_length);
|
||||||
|
} else if (chunked) {
|
||||||
|
head += "Transfer-Encoding: chunked\r\n";
|
||||||
|
}
|
||||||
|
head += std::format("Connection: {}\r\n\r\n",
|
||||||
|
keep ? "keep-alive" : "close");
|
||||||
|
|
||||||
|
state.head_attempted.store(true, std::memory_order_release);
|
||||||
|
auto sent_head = writer_send_all(
|
||||||
|
state, std::as_bytes(std::span{head.data(), head.size()}));
|
||||||
|
if (!sent_head.has_value()) {
|
||||||
|
return std::unexpected{std::move(sent_head.error())};
|
||||||
|
}
|
||||||
|
|
||||||
|
state.bodyless.store(bodyless, std::memory_order_release);
|
||||||
|
state.chunked.store(chunked, std::memory_order_release);
|
||||||
|
state.fixed_length.store(fixed, std::memory_order_release);
|
||||||
|
state.close_delimited.store(close_delimited,
|
||||||
|
std::memory_order_release);
|
||||||
|
state.keep_alive.store(keep, std::memory_order_release);
|
||||||
|
if (content_length.has_value()) {
|
||||||
|
state.content_length.store(*content_length,
|
||||||
|
std::memory_order_release);
|
||||||
|
state.has_content_length.store(true,
|
||||||
|
std::memory_order_release);
|
||||||
|
}
|
||||||
|
state.begun.store(true, std::memory_order_release);
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::size_t>
|
||||||
|
ResponseWriter::write_some(std::span<const std::byte> bytes)
|
||||||
|
{
|
||||||
|
auto active = writer_require_active(m_state);
|
||||||
|
if (!active.has_value()) {
|
||||||
|
return std::unexpected{std::move(active.error())};
|
||||||
|
}
|
||||||
|
State& state = *m_state;
|
||||||
|
std::unique_lock lock{state.io_mutex, std::try_to_lock};
|
||||||
|
if (!lock.owns_lock()) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
Void::Result::ErrorKind::overloaded,
|
||||||
|
"Net::ResponseWriter: concurrent writer");
|
||||||
|
}
|
||||||
|
if (state.invalid.load(std::memory_order_acquire)) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: exchange is no longer active")};
|
||||||
|
}
|
||||||
|
if (!state.begun.load(std::memory_order_acquire)) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: response not started")};
|
||||||
|
}
|
||||||
|
if (state.finished.load(std::memory_order_acquire)) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: response already finished")};
|
||||||
|
}
|
||||||
|
if (state.stopped()) {
|
||||||
|
state.request_stop();
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::cancelled,
|
||||||
|
"Net::ResponseWriter: exchange cancelled")};
|
||||||
|
}
|
||||||
|
if (bytes.empty()) {
|
||||||
|
return std::size_t{0};
|
||||||
|
}
|
||||||
|
if (state.bodyless.load(std::memory_order_acquire)) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: bodyless response cannot carry a body")};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto flushed = writer_flush(state);
|
||||||
|
if (!flushed.has_value()) {
|
||||||
|
return std::unexpected{std::move(flushed.error())};
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::size_t max_pending = state.max_pending;
|
||||||
|
std::size_t capacity = max_pending;
|
||||||
|
if (state.chunked.load(std::memory_order_acquire)) {
|
||||||
|
// Leave room for the chunk size line and trailing CRLF.
|
||||||
|
capacity = max_pending > 32 ? max_pending - 32 : 1;
|
||||||
|
}
|
||||||
|
std::size_t accepted = std::min(bytes.size(), capacity);
|
||||||
|
if (accepted == 0) {
|
||||||
|
return std::size_t{0};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.fixed_length.load(std::memory_order_acquire)) {
|
||||||
|
const std::uint64_t total =
|
||||||
|
state.content_length.load(std::memory_order_acquire);
|
||||||
|
const std::uint64_t written =
|
||||||
|
state.accepted.load(std::memory_order_acquire);
|
||||||
|
const std::uint64_t remaining =
|
||||||
|
total > written ? total - written : 0;
|
||||||
|
if (accepted > remaining) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: fixed-length body overflow")};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.chunked.load(std::memory_order_acquire)) {
|
||||||
|
state.pending += std::format("{:x}\r\n", accepted);
|
||||||
|
state.pending.append(
|
||||||
|
reinterpret_cast<const char*>(bytes.data()), accepted);
|
||||||
|
state.pending += "\r\n";
|
||||||
|
} else {
|
||||||
|
state.pending.append(
|
||||||
|
reinterpret_cast<const char*>(bytes.data()), accepted);
|
||||||
|
}
|
||||||
|
state.pending_bytes.store(state.pending.size(),
|
||||||
|
std::memory_order_release);
|
||||||
|
state.accepted.fetch_add(accepted, std::memory_order_acq_rel);
|
||||||
|
|
||||||
|
auto after = writer_flush(state);
|
||||||
|
if (!after.has_value()) {
|
||||||
|
return std::unexpected{std::move(after.error())};
|
||||||
|
}
|
||||||
|
return accepted;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void> ResponseWriter::finish()
|
||||||
|
{
|
||||||
|
auto active = writer_require_active(m_state);
|
||||||
|
if (!active.has_value()) {
|
||||||
|
return active;
|
||||||
|
}
|
||||||
|
State& state = *m_state;
|
||||||
|
std::unique_lock lock{state.io_mutex, std::try_to_lock};
|
||||||
|
if (!lock.owns_lock()) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
Void::Result::ErrorKind::overloaded,
|
||||||
|
"Net::ResponseWriter: concurrent writer");
|
||||||
|
}
|
||||||
|
if (state.invalid.load(std::memory_order_acquire)) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: exchange is no longer active")};
|
||||||
|
}
|
||||||
|
if (!state.begun.load(std::memory_order_acquire)) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: response not started")};
|
||||||
|
}
|
||||||
|
if (state.finished.load(std::memory_order_acquire)) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::ResponseWriter: response already finished")};
|
||||||
|
}
|
||||||
|
if (state.stopped()) {
|
||||||
|
state.request_stop();
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::cancelled,
|
||||||
|
"Net::ResponseWriter: exchange cancelled")};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto flushed = writer_flush(state);
|
||||||
|
if (!flushed.has_value()) {
|
||||||
|
return std::unexpected{std::move(flushed.error())};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.chunked.load(std::memory_order_acquire)) {
|
||||||
|
const std::string_view terminal = "0\r\n\r\n";
|
||||||
|
auto res = writer_send_all(
|
||||||
|
state, std::as_bytes(std::span{terminal.data(),
|
||||||
|
terminal.size()}));
|
||||||
|
if (!res.has_value()) {
|
||||||
|
return std::unexpected{std::move(res.error())};
|
||||||
|
}
|
||||||
|
} else if (state.fixed_length.load(std::memory_order_acquire)) {
|
||||||
|
const std::uint64_t total =
|
||||||
|
state.content_length.load(std::memory_order_acquire);
|
||||||
|
const std::uint64_t written =
|
||||||
|
state.accepted.load(std::memory_order_acquire);
|
||||||
|
if (written != total) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::protocol_error,
|
||||||
|
"Net::ResponseWriter: fixed-length body incomplete")};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
state.finished.store(true, std::memory_order_release);
|
||||||
|
state.request_stop();
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ResponseWriterAccess {
|
||||||
|
static ResponseWriter
|
||||||
|
make(std::shared_ptr<ResponseWriter::State> state)
|
||||||
|
{
|
||||||
|
return ResponseWriter{std::move(state)};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
namespace
|
namespace
|
||||||
{
|
{
|
||||||
struct StreamingRoute {
|
struct StreamingRoute {
|
||||||
@@ -876,6 +1458,13 @@ namespace Void::Net
|
|||||||
StreamingRouteHandler handler;
|
StreamingRouteHandler handler;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
struct DuplexRoute {
|
||||||
|
Method method;
|
||||||
|
std::string pattern;
|
||||||
|
std::vector<std::string> segments;
|
||||||
|
DuplexRouteHandler handler;
|
||||||
|
};
|
||||||
|
|
||||||
struct WorkerEntry {
|
struct WorkerEntry {
|
||||||
std::uint64_t id{0};
|
std::uint64_t id{0};
|
||||||
std::atomic<int> client_fd{-1};
|
std::atomic<int> client_fd{-1};
|
||||||
@@ -1023,6 +1612,7 @@ namespace Void::Net
|
|||||||
|
|
||||||
mutable std::shared_mutex stream_mutex{};
|
mutable std::shared_mutex stream_mutex{};
|
||||||
std::vector<StreamingRoute> streaming_routes{};
|
std::vector<StreamingRoute> streaming_routes{};
|
||||||
|
std::vector<DuplexRoute> duplex_routes{};
|
||||||
std::vector<WebSocketRoute> ws_routes{};
|
std::vector<WebSocketRoute> ws_routes{};
|
||||||
std::atomic<std::uint64_t> next_ws_id{1};
|
std::atomic<std::uint64_t> next_ws_id{1};
|
||||||
|
|
||||||
@@ -1092,6 +1682,35 @@ namespace Void::Net
|
|||||||
best->handler, std::move(best_params)};
|
best->handler, std::move(best_params)};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::optional<
|
||||||
|
std::pair<DuplexRouteHandler, RouteParameters>>
|
||||||
|
match_duplex(Method m, std::string_view path_view) const
|
||||||
|
{
|
||||||
|
const auto segments = split_path(path_view);
|
||||||
|
std::shared_lock lock{stream_mutex};
|
||||||
|
const DuplexRoute* best = nullptr;
|
||||||
|
RouteParameters best_params;
|
||||||
|
for (const auto& r : duplex_routes) {
|
||||||
|
if (r.method != m) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
auto matched = match_segments(r.segments, segments);
|
||||||
|
if (!matched.has_value()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (best == nullptr ||
|
||||||
|
more_specific_route(r.segments, best->segments)) {
|
||||||
|
best = &r;
|
||||||
|
best_params = std::move(*matched);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (best == nullptr) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return std::pair<DuplexRouteHandler, RouteParameters>{
|
||||||
|
best->handler, std::move(best_params)};
|
||||||
|
}
|
||||||
|
|
||||||
[[nodiscard]] std::optional<WebSocketRoute>
|
[[nodiscard]] std::optional<WebSocketRoute>
|
||||||
match_websocket(std::string_view path_view) const
|
match_websocket(std::string_view path_view) const
|
||||||
{
|
{
|
||||||
@@ -1257,6 +1876,13 @@ namespace Void::Net
|
|||||||
methods.push_back(r.method);
|
methods.push_back(r.method);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for (const auto& r : duplex_routes) {
|
||||||
|
if (match_segments(r.segments, segments).has_value() &&
|
||||||
|
std::ranges::find(methods, r.method) ==
|
||||||
|
methods.end()) {
|
||||||
|
methods.push_back(r.method);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return methods;
|
return methods;
|
||||||
}
|
}
|
||||||
@@ -1594,10 +2220,13 @@ namespace Void::Net
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Check streaming route vs buffered Router.
|
// 4. Check duplex/streaming routes vs buffered Router.
|
||||||
|
auto duplex_match = match_duplex(*method_opt, raw_path);
|
||||||
auto streaming_match =
|
auto streaming_match =
|
||||||
match_streaming(*method_opt, raw_path);
|
match_streaming(*method_opt, raw_path);
|
||||||
if (!streaming_match.has_value()) {
|
const bool live_route = duplex_match.has_value() ||
|
||||||
|
streaming_match.has_value();
|
||||||
|
if (!live_route) {
|
||||||
// Enforce buffered max_body_bytes before reading body.
|
// Enforce buffered max_body_bytes before reading body.
|
||||||
if (!chunked && content_length.has_value() &&
|
if (!chunked && content_length.has_value() &&
|
||||||
*content_length > options.max_body_bytes) {
|
*content_length > options.max_body_bytes) {
|
||||||
@@ -1644,6 +2273,99 @@ namespace Void::Net
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (duplex_match.has_value()) {
|
||||||
|
ServerRequest req;
|
||||||
|
req.method = *method_opt;
|
||||||
|
req.path = std::string{raw_path};
|
||||||
|
req.headers = std::move(headers);
|
||||||
|
req.parameters = std::move(duplex_match->second);
|
||||||
|
req.query = std::string{raw_query};
|
||||||
|
|
||||||
|
auto writer_state =
|
||||||
|
std::make_shared<ResponseWriter::State>();
|
||||||
|
writer_state->fd = fd_guard.get();
|
||||||
|
writer_state->stopping = &stopping;
|
||||||
|
writer_state->write_timeout_ms.store(
|
||||||
|
options.write_timeout.count(),
|
||||||
|
std::memory_order_release);
|
||||||
|
writer_state->max_pending =
|
||||||
|
options.duplex_write_buffer_bytes;
|
||||||
|
writer_state->head_request =
|
||||||
|
(*method_opt == Method::Head);
|
||||||
|
writer_state->http10 = (version == "HTTP/1.0");
|
||||||
|
writer_state->keep_alive.store(
|
||||||
|
keep_alive, std::memory_order_release);
|
||||||
|
|
||||||
|
ResponseWriter writer =
|
||||||
|
ResponseWriterAccess::make(writer_state);
|
||||||
|
auto route_res = duplex_match->first(
|
||||||
|
req, body_reader, writer);
|
||||||
|
|
||||||
|
const bool committed = writer_state->begun.load(
|
||||||
|
std::memory_order_acquire);
|
||||||
|
const bool head_attempted =
|
||||||
|
writer_state->head_attempted.load(
|
||||||
|
std::memory_order_acquire);
|
||||||
|
if (!route_res.has_value()) {
|
||||||
|
if (!committed && !head_attempted &&
|
||||||
|
!stopping.load(std::memory_order_acquire)) {
|
||||||
|
if (route_res.error().kind() ==
|
||||||
|
Void::Result::ErrorKind::exhausted) {
|
||||||
|
send_error_close(fd_guard.get(), 413,
|
||||||
|
"Payload Too Large");
|
||||||
|
} else if (
|
||||||
|
route_res.error().kind() ==
|
||||||
|
Void::Result::ErrorKind::timeout ||
|
||||||
|
route_res.error().kind() ==
|
||||||
|
Void::Result::ErrorKind::cancelled) {
|
||||||
|
send_error_close(fd_guard.get(), 408,
|
||||||
|
"Request Timeout");
|
||||||
|
} else {
|
||||||
|
send_error_close(
|
||||||
|
fd_guard.get(), 500,
|
||||||
|
"Internal Server Error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// After headers the stream is simply terminated
|
||||||
|
// without a successful terminal chunk.
|
||||||
|
} else if (!committed) {
|
||||||
|
if (!head_attempted) {
|
||||||
|
send_error_close(fd_guard.get(), 500,
|
||||||
|
"Internal Server Error");
|
||||||
|
}
|
||||||
|
} else if (!writer_state->finished.load(
|
||||||
|
std::memory_order_acquire)) {
|
||||||
|
auto fin = writer.finish();
|
||||||
|
if (!fin.has_value()) {
|
||||||
|
// Framing could not be completed; close.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const bool completed = writer_state->finished.load(
|
||||||
|
std::memory_order_acquire);
|
||||||
|
const bool exchange_keep_alive =
|
||||||
|
keep_alive &&
|
||||||
|
writer_state->keep_alive.load(
|
||||||
|
std::memory_order_acquire) &&
|
||||||
|
reader_state.eof;
|
||||||
|
{
|
||||||
|
// Wait for any writer still inside an
|
||||||
|
// operation, then permanently invalidate the
|
||||||
|
// shared state. Retained writers stay memory-safe
|
||||||
|
// but can no longer touch this connection.
|
||||||
|
std::lock_guard lock{writer_state->io_mutex};
|
||||||
|
writer_state->invalid.store(
|
||||||
|
true, std::memory_order_release);
|
||||||
|
writer_state->fd = -1;
|
||||||
|
writer_state->stopping = nullptr;
|
||||||
|
}
|
||||||
|
writer_state->request_stop();
|
||||||
|
if (!exchange_keep_alive || !completed) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if (streaming_match.has_value()) {
|
if (streaming_match.has_value()) {
|
||||||
ServerRequest req;
|
ServerRequest req;
|
||||||
req.method = *method_opt;
|
req.method = *method_opt;
|
||||||
@@ -1794,7 +2516,11 @@ namespace Void::Net
|
|||||||
}
|
}
|
||||||
if ((pfds[1].revents & POLLIN) != 0) {
|
if ((pfds[1].revents & POLLIN) != 0) {
|
||||||
std::uint64_t val = 0;
|
std::uint64_t val = 0;
|
||||||
(void)::read(wake_fd, &val, sizeof(val));
|
// Best effort: the eventfd is only a wakeup hint and the
|
||||||
|
// stopping flag is authoritative, but consume the result so
|
||||||
|
// fortified headers do not raise -Wunused-result.
|
||||||
|
[[maybe_unused]] const ssize_t drained =
|
||||||
|
::read(wake_fd, &val, sizeof(val));
|
||||||
}
|
}
|
||||||
if (stopping.load(std::memory_order_acquire)) {
|
if (stopping.load(std::memory_order_acquire)) {
|
||||||
break;
|
break;
|
||||||
@@ -1833,8 +2559,11 @@ namespace Void::Net
|
|||||||
"Content-Length: 19\r\n"
|
"Content-Length: 19\r\n"
|
||||||
"Connection: close\r\n\r\n"
|
"Connection: close\r\n\r\n"
|
||||||
"Service Unavailable";
|
"Service Unavailable";
|
||||||
(void)::send(client_fd, busy.data(), busy.size(),
|
// The connection is closed regardless of whether the
|
||||||
MSG_NOSIGNAL);
|
// 503 could be delivered; consume the result explicitly.
|
||||||
|
[[maybe_unused]] const ssize_t sent =
|
||||||
|
::send(client_fd, busy.data(), busy.size(),
|
||||||
|
MSG_NOSIGNAL);
|
||||||
(void)::close(client_fd);
|
(void)::close(client_fd);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -1868,7 +2597,10 @@ namespace Void::Net
|
|||||||
stopping.store(true, std::memory_order_release);
|
stopping.store(true, std::memory_order_release);
|
||||||
if (wake_fd >= 0) {
|
if (wake_fd >= 0) {
|
||||||
const std::uint64_t one = 1;
|
const std::uint64_t one = 1;
|
||||||
(void)::write(wake_fd, &one, sizeof(one));
|
// Best effort wakeup: the accept loop also polls with a
|
||||||
|
// timeout, so a full eventfd cannot delay shutdown.
|
||||||
|
[[maybe_unused]] const ssize_t signalled =
|
||||||
|
::write(wake_fd, &one, sizeof(one));
|
||||||
}
|
}
|
||||||
if (accept_thread.joinable()) {
|
if (accept_thread.joinable()) {
|
||||||
accept_thread.join();
|
accept_thread.join();
|
||||||
@@ -1986,6 +2718,36 @@ namespace Void::Net
|
|||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void>
|
||||||
|
HttpServer::add_duplex_route(Method method, std::string pattern,
|
||||||
|
DuplexRouteHandler handler)
|
||||||
|
{
|
||||||
|
if (!handler) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::HttpServer: duplex route handler is empty")};
|
||||||
|
}
|
||||||
|
auto compiled = compile_route_pattern(pattern);
|
||||||
|
if (!compiled.has_value()) {
|
||||||
|
return std::unexpected{std::move(compiled.error())};
|
||||||
|
}
|
||||||
|
std::unique_lock lock{m_impl->stream_mutex};
|
||||||
|
const auto dup = std::ranges::find_if(
|
||||||
|
m_impl->duplex_routes, [&](const DuplexRoute& r) {
|
||||||
|
return r.method == method &&
|
||||||
|
same_route_shape(r.segments, *compiled);
|
||||||
|
});
|
||||||
|
if (dup != m_impl->duplex_routes.end()) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net::HttpServer: duplicate duplex route")};
|
||||||
|
}
|
||||||
|
m_impl->duplex_routes.push_back(DuplexRoute{
|
||||||
|
method, std::move(pattern), std::move(*compiled),
|
||||||
|
std::move(handler)});
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
Void::Result::Result<void>
|
Void::Result::Result<void>
|
||||||
HttpServer::add_websocket_route(std::string pattern,
|
HttpServer::add_websocket_route(std::string pattern,
|
||||||
WebSocketSessions& sessions,
|
WebSocketSessions& sessions,
|
||||||
@@ -2020,7 +2782,8 @@ namespace Void::Net
|
|||||||
}
|
}
|
||||||
if (m_impl->options.max_concurrent_connections == 0 ||
|
if (m_impl->options.max_concurrent_connections == 0 ||
|
||||||
m_impl->options.max_header_bytes == 0 ||
|
m_impl->options.max_header_bytes == 0 ||
|
||||||
m_impl->options.max_headers == 0) {
|
m_impl->options.max_headers == 0 ||
|
||||||
|
m_impl->options.duplex_write_buffer_bytes == 0) {
|
||||||
return std::unexpected{make_net_error(
|
return std::unexpected{make_net_error(
|
||||||
NetErrorCode::invalid_argument,
|
NetErrorCode::invalid_argument,
|
||||||
"Net::HttpServer::start: limits must be positive")};
|
"Net::HttpServer::start: limits must be positive")};
|
||||||
|
|||||||
@@ -0,0 +1,635 @@
|
|||||||
|
#include <Void/Net/Smtp.hpp>
|
||||||
|
#include <Void/Net/Http.hpp>
|
||||||
|
#include <Void/Net/Tls.hpp>
|
||||||
|
#include <Void/Text/Base64.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
|
#include <charconv>
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <format>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Net
|
||||||
|
{
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
[[nodiscard]] std::string upper_ascii(std::string_view text)
|
||||||
|
{
|
||||||
|
std::string out{text};
|
||||||
|
for (char& c : out) {
|
||||||
|
c = static_cast<char>(
|
||||||
|
std::toupper(static_cast<unsigned char>(c)));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::string_view trimmed(std::string_view text) noexcept
|
||||||
|
{
|
||||||
|
constexpr std::string_view whitespace = " \t\r\n";
|
||||||
|
const std::size_t begin = text.find_first_not_of(whitespace);
|
||||||
|
if (begin == std::string_view::npos) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
const std::size_t end = text.find_last_not_of(whitespace);
|
||||||
|
return text.substr(begin, end - begin + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool has_control(std::string_view text) noexcept
|
||||||
|
{
|
||||||
|
return std::ranges::any_of(text, [](char c) {
|
||||||
|
const auto value = static_cast<unsigned char>(c);
|
||||||
|
return value < 0x20U || value == 0x7FU;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
validate_address(std::string_view field, std::string_view value)
|
||||||
|
{
|
||||||
|
if (value.empty()) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
std::format("SMTP: {} must not be empty", field))};
|
||||||
|
}
|
||||||
|
if (has_control(value) || value.find('<') != std::string_view::npos ||
|
||||||
|
value.find('>') != std::string_view::npos) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
std::format("SMTP: {} contains invalid characters",
|
||||||
|
field))};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SmtpReply {
|
||||||
|
int code{0};
|
||||||
|
std::vector<std::string> lines{};
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] std::string
|
||||||
|
reply_summary(const SmtpReply& reply)
|
||||||
|
{
|
||||||
|
if (reply.lines.empty()) {
|
||||||
|
return std::to_string(reply.code);
|
||||||
|
}
|
||||||
|
return std::format("{} {}", reply.code, reply.lines.front());
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Error
|
||||||
|
rejected_error(std::string_view context,
|
||||||
|
const SmtpReply& reply)
|
||||||
|
{
|
||||||
|
return make_net_error(
|
||||||
|
NetErrorCode::smtp_rejected,
|
||||||
|
std::format("SMTP: {} rejected: {}", context,
|
||||||
|
reply_summary(reply)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::string encode_data(std::string_view data)
|
||||||
|
{
|
||||||
|
std::string out;
|
||||||
|
out.reserve(data.size() + data.size() / 16U + 8U);
|
||||||
|
bool line_start = true;
|
||||||
|
for (std::size_t i = 0; i < data.size(); ++i) {
|
||||||
|
const char c = data[i];
|
||||||
|
if (line_start && c == '.') {
|
||||||
|
out.push_back('.');
|
||||||
|
}
|
||||||
|
if (c == '\r') {
|
||||||
|
if (i + 1U < data.size() && data[i + 1U] == '\n') {
|
||||||
|
++i;
|
||||||
|
}
|
||||||
|
out += "\r\n";
|
||||||
|
line_start = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '\n') {
|
||||||
|
out += "\r\n";
|
||||||
|
line_start = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.push_back(c);
|
||||||
|
line_start = false;
|
||||||
|
}
|
||||||
|
if (!line_start) {
|
||||||
|
out += "\r\n";
|
||||||
|
}
|
||||||
|
out += ".\r\n";
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
struct SmtpClient::Impl {
|
||||||
|
TlsClientStream stream;
|
||||||
|
SmtpOptions options;
|
||||||
|
std::string pending{};
|
||||||
|
std::vector<std::string> capabilities{};
|
||||||
|
|
||||||
|
Impl(TlsClientStream s, SmtpOptions o)
|
||||||
|
: stream(std::move(s)), options(std::move(o))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::string> read_line()
|
||||||
|
{
|
||||||
|
for (;;) {
|
||||||
|
const std::size_t end = pending.find("\r\n");
|
||||||
|
if (end != std::string::npos) {
|
||||||
|
std::string line = pending.substr(0, end);
|
||||||
|
pending.erase(0, end + 2U);
|
||||||
|
if (line.size() >
|
||||||
|
options.limits.max_line_bytes) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::protocol_error,
|
||||||
|
std::format("SMTP: reply line exceeds {} "
|
||||||
|
"bytes",
|
||||||
|
options.limits
|
||||||
|
.max_line_bytes))};
|
||||||
|
}
|
||||||
|
return line;
|
||||||
|
}
|
||||||
|
if (pending.size() >
|
||||||
|
options.limits.max_line_bytes) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::protocol_error,
|
||||||
|
"SMTP: reply line too long")};
|
||||||
|
}
|
||||||
|
std::array<std::byte, 1024> chunk{};
|
||||||
|
auto count = stream.read(chunk, options.io_timeout,
|
||||||
|
options.stop);
|
||||||
|
if (!count.has_value()) {
|
||||||
|
return std::unexpected{
|
||||||
|
std::move(count.error())};
|
||||||
|
}
|
||||||
|
if (*count == 0) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::protocol_error,
|
||||||
|
"SMTP: server closed the connection")};
|
||||||
|
}
|
||||||
|
pending.append(
|
||||||
|
reinterpret_cast<const char*>(chunk.data()),
|
||||||
|
*count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<SmtpReply> read_reply()
|
||||||
|
{
|
||||||
|
SmtpReply reply;
|
||||||
|
std::uint64_t total = 0;
|
||||||
|
for (;;) {
|
||||||
|
auto line = read_line();
|
||||||
|
if (!line.has_value()) {
|
||||||
|
return std::unexpected{
|
||||||
|
std::move(line.error())};
|
||||||
|
}
|
||||||
|
total += line->size() + 2U;
|
||||||
|
if (total >
|
||||||
|
options.limits.max_response_bytes) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::protocol_error,
|
||||||
|
std::format("SMTP: reply exceeds {} bytes",
|
||||||
|
options.limits
|
||||||
|
.max_response_bytes))};
|
||||||
|
}
|
||||||
|
if (line->size() < 3U) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::protocol_error,
|
||||||
|
"SMTP: malformed reply")};
|
||||||
|
}
|
||||||
|
int code = 0;
|
||||||
|
const char* begin = line->data();
|
||||||
|
const char* finish = begin + 3;
|
||||||
|
const auto parsed =
|
||||||
|
std::from_chars(begin, finish, code);
|
||||||
|
if (parsed.ec != std::errc{} ||
|
||||||
|
parsed.ptr != finish || code < 100 ||
|
||||||
|
code > 599) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::protocol_error,
|
||||||
|
"SMTP: malformed reply code")};
|
||||||
|
}
|
||||||
|
const char separator =
|
||||||
|
line->size() > 3U ? (*line)[3] : ' ';
|
||||||
|
if (separator != '-' && separator != ' ') {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::protocol_error,
|
||||||
|
"SMTP: malformed reply separator")};
|
||||||
|
}
|
||||||
|
if (!reply.lines.empty() &&
|
||||||
|
reply.code != code) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::protocol_error,
|
||||||
|
"SMTP: inconsistent multi-line reply")};
|
||||||
|
}
|
||||||
|
reply.code = code;
|
||||||
|
reply.lines.push_back(
|
||||||
|
line->size() > 4U ? line->substr(4)
|
||||||
|
: std::string{});
|
||||||
|
if (separator == ' ') {
|
||||||
|
return reply;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
command(std::string_view line)
|
||||||
|
{
|
||||||
|
std::string wire{line};
|
||||||
|
wire += "\r\n";
|
||||||
|
return stream.write_all(wire, options.io_timeout,
|
||||||
|
options.stop);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<SmtpReply>
|
||||||
|
command_reply(std::string_view line)
|
||||||
|
{
|
||||||
|
auto sent = command(line);
|
||||||
|
if (!sent.has_value()) {
|
||||||
|
return std::unexpected{std::move(sent.error())};
|
||||||
|
}
|
||||||
|
return read_reply();
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool
|
||||||
|
has_capability(std::string_view name) const
|
||||||
|
{
|
||||||
|
const std::string wanted = upper_ascii(name);
|
||||||
|
return std::ranges::any_of(
|
||||||
|
capabilities, [&](const std::string& capability) {
|
||||||
|
return capability == wanted ||
|
||||||
|
capability.starts_with(wanted + " ") ||
|
||||||
|
capability.starts_with(wanted + "=");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool auth_plain_supported() const
|
||||||
|
{
|
||||||
|
for (const auto& capability : capabilities) {
|
||||||
|
if (!capability.starts_with("AUTH ") &&
|
||||||
|
!capability.starts_with("AUTH=")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
std::string mechanisms = capability.substr(5);
|
||||||
|
std::ranges::replace(mechanisms, '=', ' ');
|
||||||
|
std::size_t begin = 0;
|
||||||
|
while (begin < mechanisms.size()) {
|
||||||
|
const std::size_t end =
|
||||||
|
mechanisms.find(' ', begin);
|
||||||
|
const std::string_view mechanism{
|
||||||
|
mechanisms.data() + begin,
|
||||||
|
(end == std::string::npos ? mechanisms.size()
|
||||||
|
: end) -
|
||||||
|
begin};
|
||||||
|
if (mechanism == "PLAIN") {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (end == std::string::npos) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
begin = end + 1U;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::optional<std::uint64_t>
|
||||||
|
server_size_limit() const
|
||||||
|
{
|
||||||
|
for (const auto& capability : capabilities) {
|
||||||
|
if (!capability.starts_with("SIZE")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (capability.size() == 4U) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
if (capability[4] != ' ') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
std::uint64_t limit = 0;
|
||||||
|
const char* begin = capability.data() + 5;
|
||||||
|
const char* end =
|
||||||
|
capability.data() + capability.size();
|
||||||
|
const auto parsed =
|
||||||
|
std::from_chars(begin, end, limit);
|
||||||
|
if (parsed.ec == std::errc{} &&
|
||||||
|
parsed.ptr == end) {
|
||||||
|
return limit;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void> ehlo()
|
||||||
|
{
|
||||||
|
auto reply =
|
||||||
|
command_reply("EHLO " + options.client_domain);
|
||||||
|
if (!reply.has_value()) {
|
||||||
|
return std::unexpected{std::move(reply.error())};
|
||||||
|
}
|
||||||
|
if (reply->code != 250) {
|
||||||
|
return std::unexpected{
|
||||||
|
rejected_error("EHLO", *reply)};
|
||||||
|
}
|
||||||
|
capabilities.clear();
|
||||||
|
for (std::size_t i = 1; i < reply->lines.size(); ++i) {
|
||||||
|
const std::string_view capability =
|
||||||
|
trimmed(reply->lines[i]);
|
||||||
|
if (!capability.empty()) {
|
||||||
|
capabilities.push_back(
|
||||||
|
upper_ascii(capability));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void> authenticate()
|
||||||
|
{
|
||||||
|
if (!options.credentials.has_value()) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
if (!stream.secure()) {
|
||||||
|
// Credentials are never sent on a plaintext channel.
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::tls_required,
|
||||||
|
"SMTP: refusing to send credentials without TLS")};
|
||||||
|
}
|
||||||
|
if (!auth_plain_supported()) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::auth_failed,
|
||||||
|
"SMTP: server does not advertise AUTH PLAIN")};
|
||||||
|
}
|
||||||
|
std::string payload;
|
||||||
|
payload.reserve(1U + options.credentials->username.size() +
|
||||||
|
1U +
|
||||||
|
options.credentials->password.size());
|
||||||
|
payload.push_back('\0');
|
||||||
|
payload += options.credentials->username;
|
||||||
|
payload.push_back('\0');
|
||||||
|
payload += options.credentials->password;
|
||||||
|
const std::string token =
|
||||||
|
Void::Encoding::Base64::encode(payload);
|
||||||
|
auto reply = command_reply("AUTH PLAIN " + token);
|
||||||
|
if (!reply.has_value()) {
|
||||||
|
return std::unexpected{std::move(reply.error())};
|
||||||
|
}
|
||||||
|
if (reply->code != 235) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::auth_failed,
|
||||||
|
std::format("SMTP: authentication failed: {}",
|
||||||
|
reply_summary(*reply)))};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
expect(const SmtpReply& reply, int code,
|
||||||
|
std::string_view context)
|
||||||
|
{
|
||||||
|
if (reply.code != code) {
|
||||||
|
return std::unexpected{
|
||||||
|
rejected_error(context, reply)};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
SmtpClient::SmtpClient() noexcept = default;
|
||||||
|
SmtpClient::SmtpClient(std::unique_ptr<Impl> impl) noexcept
|
||||||
|
: m_impl(std::move(impl))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
SmtpClient::~SmtpClient() noexcept = default;
|
||||||
|
SmtpClient::SmtpClient(SmtpClient&&) noexcept = default;
|
||||||
|
SmtpClient& SmtpClient::operator=(SmtpClient&&) noexcept = default;
|
||||||
|
|
||||||
|
bool SmtpClient::valid() const noexcept
|
||||||
|
{
|
||||||
|
return m_impl != nullptr && m_impl->stream.valid();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SmtpClient::secure() const noexcept
|
||||||
|
{
|
||||||
|
return m_impl != nullptr && m_impl->stream.secure();
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<SmtpClient>
|
||||||
|
SmtpClient::connect(SmtpOptions options)
|
||||||
|
{
|
||||||
|
if (options.host.empty() || options.port == 0) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"SMTP: connect requires a host and port")};
|
||||||
|
}
|
||||||
|
TlsClientOptions tls;
|
||||||
|
tls.host = options.host;
|
||||||
|
tls.port = options.port;
|
||||||
|
tls.server_name = options.server_name;
|
||||||
|
tls.ca_file = options.ca_file;
|
||||||
|
tls.connect_timeout = options.connect_timeout;
|
||||||
|
tls.io_timeout = options.io_timeout;
|
||||||
|
tls.stop = options.stop;
|
||||||
|
|
||||||
|
auto stream =
|
||||||
|
options.security == SmtpSecurity::implicit_tls
|
||||||
|
? TlsClientStream::connect(std::move(tls))
|
||||||
|
: TlsClientStream::connect_plain(std::move(tls));
|
||||||
|
if (!stream.has_value()) {
|
||||||
|
return std::unexpected{std::move(stream.error())};
|
||||||
|
}
|
||||||
|
auto impl =
|
||||||
|
std::make_unique<Impl>(std::move(*stream), std::move(options));
|
||||||
|
|
||||||
|
auto greeting = impl->read_reply();
|
||||||
|
if (!greeting.has_value()) {
|
||||||
|
return std::unexpected{std::move(greeting.error())};
|
||||||
|
}
|
||||||
|
if (greeting->code != 220) {
|
||||||
|
return std::unexpected{
|
||||||
|
rejected_error("greeting", *greeting)};
|
||||||
|
}
|
||||||
|
auto hello = impl->ehlo();
|
||||||
|
if (!hello.has_value()) {
|
||||||
|
return std::unexpected{std::move(hello.error())};
|
||||||
|
}
|
||||||
|
if (impl->options.security ==
|
||||||
|
SmtpSecurity::starttls_required) {
|
||||||
|
if (!impl->has_capability("STARTTLS")) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::tls_required,
|
||||||
|
"SMTP: server does not advertise STARTTLS")};
|
||||||
|
}
|
||||||
|
auto reply = impl->command_reply("STARTTLS");
|
||||||
|
if (!reply.has_value()) {
|
||||||
|
return std::unexpected{std::move(reply.error())};
|
||||||
|
}
|
||||||
|
if (reply->code != 220) {
|
||||||
|
return std::unexpected{
|
||||||
|
rejected_error("STARTTLS", *reply)};
|
||||||
|
}
|
||||||
|
auto upgraded = impl->stream.start_tls();
|
||||||
|
if (!upgraded.has_value()) {
|
||||||
|
return std::unexpected{std::move(upgraded.error())};
|
||||||
|
}
|
||||||
|
auto hello_again = impl->ehlo();
|
||||||
|
if (!hello_again.has_value()) {
|
||||||
|
return std::unexpected{
|
||||||
|
std::move(hello_again.error())};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
auto authenticated = impl->authenticate();
|
||||||
|
if (!authenticated.has_value()) {
|
||||||
|
return std::unexpected{std::move(authenticated.error())};
|
||||||
|
}
|
||||||
|
return SmtpClient{std::move(impl)};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void>
|
||||||
|
SmtpClient::send(const SmtpMessage& message)
|
||||||
|
{
|
||||||
|
if (!valid()) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error, "SMTP: client is not connected")};
|
||||||
|
}
|
||||||
|
auto& impl = *m_impl;
|
||||||
|
const auto fail =
|
||||||
|
[&](Void::Result::Error error)
|
||||||
|
-> Void::Result::Result<void> {
|
||||||
|
impl.stream.close();
|
||||||
|
return std::unexpected{std::move(error)};
|
||||||
|
};
|
||||||
|
|
||||||
|
auto valid_from = validate_address("from", message.from);
|
||||||
|
if (!valid_from.has_value()) {
|
||||||
|
return std::unexpected{std::move(valid_from.error())};
|
||||||
|
}
|
||||||
|
if (message.recipients.empty()) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"SMTP: at least one recipient is required")};
|
||||||
|
}
|
||||||
|
if (message.recipients.size() >
|
||||||
|
impl.options.limits.max_recipients) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
std::format("SMTP: {} recipients exceeds limit {}",
|
||||||
|
message.recipients.size(),
|
||||||
|
impl.options.limits.max_recipients))};
|
||||||
|
}
|
||||||
|
for (const auto& recipient : message.recipients) {
|
||||||
|
auto valid_recipient =
|
||||||
|
validate_address("recipient", recipient);
|
||||||
|
if (!valid_recipient.has_value()) {
|
||||||
|
return std::unexpected{
|
||||||
|
std::move(valid_recipient.error())};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (message.data.size() >
|
||||||
|
impl.options.limits.max_message_bytes) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::payload_too_large,
|
||||||
|
std::format("SMTP: message {} bytes exceeds limit {}",
|
||||||
|
message.data.size(),
|
||||||
|
impl.options.limits.max_message_bytes))};
|
||||||
|
}
|
||||||
|
if (const auto server_limit = impl.server_size_limit();
|
||||||
|
server_limit.has_value() && *server_limit > 0 &&
|
||||||
|
message.data.size() > *server_limit) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::payload_too_large,
|
||||||
|
std::format("SMTP: message {} bytes exceeds server SIZE {}",
|
||||||
|
message.data.size(), *server_limit))};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto mail = impl.command_reply("MAIL FROM:<" +
|
||||||
|
message.from + ">");
|
||||||
|
if (!mail.has_value()) {
|
||||||
|
return fail(std::move(mail.error()));
|
||||||
|
}
|
||||||
|
if (mail->code != 250) {
|
||||||
|
return fail(rejected_error("MAIL FROM", *mail));
|
||||||
|
}
|
||||||
|
for (const auto& recipient : message.recipients) {
|
||||||
|
auto rcpt =
|
||||||
|
impl.command_reply("RCPT TO:<" + recipient + ">");
|
||||||
|
if (!rcpt.has_value()) {
|
||||||
|
return fail(std::move(rcpt.error()));
|
||||||
|
}
|
||||||
|
if (rcpt->code != 250 && rcpt->code != 251) {
|
||||||
|
return fail(rejected_error("RCPT TO", *rcpt));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
auto data = impl.command_reply("DATA");
|
||||||
|
if (!data.has_value()) {
|
||||||
|
return fail(std::move(data.error()));
|
||||||
|
}
|
||||||
|
if (data->code != 354) {
|
||||||
|
return fail(rejected_error("DATA", *data));
|
||||||
|
}
|
||||||
|
const std::string encoded = encode_data(message.data);
|
||||||
|
auto written = impl.stream.write_all(encoded,
|
||||||
|
impl.options.io_timeout,
|
||||||
|
impl.options.stop);
|
||||||
|
if (!written.has_value()) {
|
||||||
|
return fail(std::move(written.error()));
|
||||||
|
}
|
||||||
|
auto accepted = impl.read_reply();
|
||||||
|
if (!accepted.has_value()) {
|
||||||
|
return fail(std::move(accepted.error()));
|
||||||
|
}
|
||||||
|
if (accepted->code != 250) {
|
||||||
|
return fail(rejected_error("message body", *accepted));
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void> SmtpClient::quit()
|
||||||
|
{
|
||||||
|
if (m_impl == nullptr) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
auto& impl = *m_impl;
|
||||||
|
Void::Result::Result<void> result{};
|
||||||
|
if (impl.stream.valid()) {
|
||||||
|
auto reply = impl.command_reply("QUIT");
|
||||||
|
if (!reply.has_value()) {
|
||||||
|
result = std::unexpected{std::move(reply.error())};
|
||||||
|
} else if (reply->code != 221) {
|
||||||
|
result = std::unexpected{
|
||||||
|
rejected_error("QUIT", *reply)};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
auto closed = impl.stream.shutdown();
|
||||||
|
if (result.has_value() && !closed.has_value()) {
|
||||||
|
result = std::unexpected{std::move(closed.error())};
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SmtpClient::close() noexcept
|
||||||
|
{
|
||||||
|
if (m_impl != nullptr) {
|
||||||
|
m_impl->stream.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void>
|
||||||
|
SmtpClient::submit(SmtpOptions options,
|
||||||
|
const SmtpMessage& message)
|
||||||
|
{
|
||||||
|
auto client = connect(std::move(options));
|
||||||
|
if (!client.has_value()) {
|
||||||
|
return std::unexpected{std::move(client.error())};
|
||||||
|
}
|
||||||
|
auto sent = client->send(message);
|
||||||
|
if (!sent.has_value()) {
|
||||||
|
client->close();
|
||||||
|
return std::unexpected{std::move(sent.error())};
|
||||||
|
}
|
||||||
|
return client->quit();
|
||||||
|
}
|
||||||
|
} // namespace Void::Net
|
||||||
+872
@@ -0,0 +1,872 @@
|
|||||||
|
#include <Void/Net/Tls.hpp>
|
||||||
|
#include <Void/Net/Http.hpp>
|
||||||
|
|
||||||
|
#include <openssl/err.h>
|
||||||
|
#include <openssl/ssl.h>
|
||||||
|
#include <openssl/x509v3.h>
|
||||||
|
|
||||||
|
#if !defined(_WIN32)
|
||||||
|
#include <arpa/inet.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <netdb.h>
|
||||||
|
#include <poll.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cerrno>
|
||||||
|
#include <chrono>
|
||||||
|
#include <climits>
|
||||||
|
#include <cstring>
|
||||||
|
#include <format>
|
||||||
|
#include <limits>
|
||||||
|
#include <memory>
|
||||||
|
#include <optional>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::Net
|
||||||
|
{
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
#if !defined(_WIN32)
|
||||||
|
using Clock = std::chrono::steady_clock;
|
||||||
|
|
||||||
|
[[nodiscard]] std::chrono::milliseconds
|
||||||
|
effective_timeout(std::chrono::milliseconds requested,
|
||||||
|
std::chrono::milliseconds fallback) noexcept
|
||||||
|
{
|
||||||
|
return requested.count() > 0 ? requested : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Clock::time_point
|
||||||
|
deadline_for(std::chrono::milliseconds timeout) noexcept
|
||||||
|
{
|
||||||
|
if (timeout.count() <= 0) {
|
||||||
|
return Clock::time_point::max();
|
||||||
|
}
|
||||||
|
return Clock::now() + timeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] int poll_timeout_ms(Clock::time_point deadline) noexcept
|
||||||
|
{
|
||||||
|
if (deadline == Clock::time_point::max()) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
const auto left = deadline - Clock::now();
|
||||||
|
if (left <= Clock::duration::zero()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(left);
|
||||||
|
if (std::chrono::duration_cast<Clock::duration>(ms) < left) {
|
||||||
|
ms += std::chrono::milliseconds{1};
|
||||||
|
}
|
||||||
|
return static_cast<int>(std::clamp<long long>(
|
||||||
|
ms.count(), 0, std::numeric_limits<int>::max()));
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::string openssl_error_text()
|
||||||
|
{
|
||||||
|
const unsigned long code = ERR_get_error();
|
||||||
|
if (code == 0) {
|
||||||
|
return "no OpenSSL error detail";
|
||||||
|
}
|
||||||
|
char buffer[256];
|
||||||
|
ERR_error_string_n(code, buffer, sizeof(buffer));
|
||||||
|
return std::string{buffer};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Error
|
||||||
|
cancelled_error(std::string_view operation)
|
||||||
|
{
|
||||||
|
return make_net_error(
|
||||||
|
NetErrorCode::cancelled,
|
||||||
|
std::format("Net: TLS {} cancelled", operation));
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Error
|
||||||
|
timeout_error(std::string_view operation)
|
||||||
|
{
|
||||||
|
return make_net_error(
|
||||||
|
NetErrorCode::timeout,
|
||||||
|
std::format("Net: TLS {} timed out", operation));
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
wait_fd(int fd, short events, Clock::time_point deadline,
|
||||||
|
std::stop_token stop, std::string_view operation)
|
||||||
|
{
|
||||||
|
for (;;) {
|
||||||
|
if (stop.stop_requested()) {
|
||||||
|
return std::unexpected{cancelled_error(operation)};
|
||||||
|
}
|
||||||
|
pollfd descriptor{.fd = fd, .events = events, .revents = 0};
|
||||||
|
int wait_ms = poll_timeout_ms(deadline);
|
||||||
|
if (stop.stop_possible() &&
|
||||||
|
(wait_ms < 0 || wait_ms > 50)) {
|
||||||
|
// Keep cancellation latency bounded without closing the
|
||||||
|
// stream; poll again after the slice.
|
||||||
|
wait_ms = 50;
|
||||||
|
}
|
||||||
|
const int rc = ::poll(&descriptor, 1, wait_ms);
|
||||||
|
if (rc < 0) {
|
||||||
|
if (errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error,
|
||||||
|
std::format("Net: TLS poll failed: {}",
|
||||||
|
std::strerror(errno)))};
|
||||||
|
}
|
||||||
|
if (rc == 0) {
|
||||||
|
if (Clock::now() >= deadline) {
|
||||||
|
return std::unexpected{timeout_error(operation)};
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ((descriptor.revents & events) != 0 ||
|
||||||
|
(descriptor.revents & (POLLHUP | POLLERR | POLLNVAL)) !=
|
||||||
|
0) {
|
||||||
|
// Let the caller perform the I/O and report the real
|
||||||
|
// error; POLLHUP still delivers buffered data and EOF.
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<int>
|
||||||
|
tcp_connect(const TlsClientOptions& options,
|
||||||
|
Clock::time_point deadline)
|
||||||
|
{
|
||||||
|
if (options.host.empty() || options.port == 0) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net: TLS connect requires a host and port")};
|
||||||
|
}
|
||||||
|
addrinfo hints{};
|
||||||
|
hints.ai_family = AF_UNSPEC;
|
||||||
|
hints.ai_socktype = SOCK_STREAM;
|
||||||
|
addrinfo* addresses = nullptr;
|
||||||
|
const std::string service = std::to_string(options.port);
|
||||||
|
const int resolved =
|
||||||
|
::getaddrinfo(options.host.c_str(), service.c_str(), &hints,
|
||||||
|
&addresses);
|
||||||
|
if (resolved != 0) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::connect_failed,
|
||||||
|
std::format("Net: TLS resolve '{}': {}", options.host,
|
||||||
|
gai_strerror(resolved)))};
|
||||||
|
}
|
||||||
|
std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> guard{
|
||||||
|
addresses, &freeaddrinfo};
|
||||||
|
|
||||||
|
Void::Result::Error last = make_net_error(
|
||||||
|
NetErrorCode::connect_failed,
|
||||||
|
std::format("Net: TLS connect to '{}:{}' failed", options.host,
|
||||||
|
options.port));
|
||||||
|
for (addrinfo* address = addresses; address != nullptr;
|
||||||
|
address = address->ai_next) {
|
||||||
|
#ifdef SOCK_CLOEXEC
|
||||||
|
const int fd =
|
||||||
|
::socket(address->ai_family,
|
||||||
|
address->ai_socktype | SOCK_CLOEXEC,
|
||||||
|
address->ai_protocol);
|
||||||
|
#else
|
||||||
|
const int fd =
|
||||||
|
::socket(address->ai_family, address->ai_socktype,
|
||||||
|
address->ai_protocol);
|
||||||
|
#endif
|
||||||
|
if (fd < 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const int flags = ::fcntl(fd, F_GETFL, 0);
|
||||||
|
if (flags < 0 ||
|
||||||
|
::fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) {
|
||||||
|
::close(fd);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (::connect(fd, address->ai_addr, address->ai_addrlen) ==
|
||||||
|
0) {
|
||||||
|
return fd;
|
||||||
|
}
|
||||||
|
if (errno != EINPROGRESS && errno != EINTR) {
|
||||||
|
last = make_net_error(
|
||||||
|
NetErrorCode::connect_failed,
|
||||||
|
std::format("Net: TLS connect failed: {}",
|
||||||
|
std::strerror(errno)));
|
||||||
|
::close(fd);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const auto waited =
|
||||||
|
wait_fd(fd, POLLOUT, deadline, options.stop, "connect");
|
||||||
|
if (!waited.has_value()) {
|
||||||
|
::close(fd);
|
||||||
|
return std::unexpected{std::move(waited.error())};
|
||||||
|
}
|
||||||
|
int socket_error = 0;
|
||||||
|
socklen_t length = sizeof(socket_error);
|
||||||
|
if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error,
|
||||||
|
&length) != 0 ||
|
||||||
|
socket_error != 0) {
|
||||||
|
const int code =
|
||||||
|
socket_error != 0 ? socket_error : errno;
|
||||||
|
last = make_net_error(
|
||||||
|
NetErrorCode::connect_failed,
|
||||||
|
std::format("Net: TLS connect failed: {}",
|
||||||
|
std::strerror(code)));
|
||||||
|
::close(fd);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return fd;
|
||||||
|
}
|
||||||
|
return std::unexpected{std::move(last)};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool is_ip_literal(std::string_view host) noexcept
|
||||||
|
{
|
||||||
|
std::string text{host};
|
||||||
|
if (text.size() >= 2 && text.front() == '[' &&
|
||||||
|
text.back() == ']') {
|
||||||
|
text = text.substr(1, text.size() - 2);
|
||||||
|
}
|
||||||
|
unsigned char storage[sizeof(in6_addr)]{};
|
||||||
|
return ::inet_pton(AF_INET, text.c_str(), storage) == 1 ||
|
||||||
|
::inet_pton(AF_INET6, text.c_str(), storage) == 1;
|
||||||
|
}
|
||||||
|
[[nodiscard]] std::string
|
||||||
|
verification_name(const TlsClientOptions& options)
|
||||||
|
{
|
||||||
|
std::string name = options.server_name.empty() ? options.host
|
||||||
|
: options.server_name;
|
||||||
|
if (name.size() >= 2 && name.front() == '[' &&
|
||||||
|
name.back() == ']') {
|
||||||
|
name = name.substr(1, name.size() - 2);
|
||||||
|
}
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
struct TlsClientStream::Impl {
|
||||||
|
int fd{-1};
|
||||||
|
SSL_CTX* ctx{nullptr};
|
||||||
|
SSL* ssl{nullptr};
|
||||||
|
bool secure{false};
|
||||||
|
std::chrono::milliseconds io_timeout{
|
||||||
|
std::chrono::seconds{30}};
|
||||||
|
std::chrono::milliseconds handshake_timeout{
|
||||||
|
std::chrono::seconds{10}};
|
||||||
|
std::stop_token stop{};
|
||||||
|
std::string server_name{};
|
||||||
|
std::string ca_file{};
|
||||||
|
|
||||||
|
~Impl() noexcept { close_all(); }
|
||||||
|
|
||||||
|
[[nodiscard]] bool valid() const noexcept { return fd >= 0; }
|
||||||
|
|
||||||
|
void close_all() noexcept
|
||||||
|
{
|
||||||
|
if (ssl != nullptr) {
|
||||||
|
SSL_free(ssl);
|
||||||
|
ssl = nullptr;
|
||||||
|
}
|
||||||
|
if (ctx != nullptr) {
|
||||||
|
SSL_CTX_free(ctx);
|
||||||
|
ctx = nullptr;
|
||||||
|
}
|
||||||
|
#if !defined(_WIN32)
|
||||||
|
if (fd >= 0) {
|
||||||
|
(void)::shutdown(fd, SHUT_RDWR);
|
||||||
|
(void)::close(fd);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
fd = -1;
|
||||||
|
secure = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
TlsClientStream::TlsClientStream() noexcept = default;
|
||||||
|
TlsClientStream::TlsClientStream(std::unique_ptr<Impl> impl) noexcept
|
||||||
|
: m_impl(std::move(impl))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
TlsClientStream::~TlsClientStream() noexcept = default;
|
||||||
|
TlsClientStream::TlsClientStream(TlsClientStream&&) noexcept = default;
|
||||||
|
TlsClientStream&
|
||||||
|
TlsClientStream::operator=(TlsClientStream&&) noexcept = default;
|
||||||
|
|
||||||
|
bool TlsClientStream::valid() const noexcept
|
||||||
|
{
|
||||||
|
return m_impl != nullptr && m_impl->valid();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool TlsClientStream::secure() const noexcept
|
||||||
|
{
|
||||||
|
return m_impl != nullptr && m_impl->secure;
|
||||||
|
}
|
||||||
|
|
||||||
|
int TlsClientStream::native_handle() const noexcept
|
||||||
|
{
|
||||||
|
return m_impl != nullptr ? m_impl->fd : -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if defined(_WIN32)
|
||||||
|
Void::Result::Result<TlsClientStream>
|
||||||
|
TlsClientStream::connect(TlsClientOptions)
|
||||||
|
{
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::tls_error,
|
||||||
|
"Net: TlsClientStream is not implemented on Windows")};
|
||||||
|
}
|
||||||
|
Void::Result::Result<TlsClientStream>
|
||||||
|
TlsClientStream::connect_plain(TlsClientOptions)
|
||||||
|
{
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::tls_error,
|
||||||
|
"Net: TlsClientStream is not implemented on Windows")};
|
||||||
|
}
|
||||||
|
Void::Result::Result<TlsClientStream>
|
||||||
|
TlsClientStream::adopt(int, TlsClientOptions)
|
||||||
|
{
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::tls_error,
|
||||||
|
"Net: TlsClientStream is not implemented on Windows")};
|
||||||
|
}
|
||||||
|
Void::Result::Result<void> TlsClientStream::start_tls()
|
||||||
|
{
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::tls_error,
|
||||||
|
"Net: TlsClientStream is not implemented on Windows")};
|
||||||
|
}
|
||||||
|
Void::Result::Result<std::size_t>
|
||||||
|
TlsClientStream::read(std::span<std::byte>, std::chrono::milliseconds,
|
||||||
|
std::stop_token)
|
||||||
|
{
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||||
|
}
|
||||||
|
Void::Result::Result<std::size_t>
|
||||||
|
TlsClientStream::write(std::span<const std::byte>,
|
||||||
|
std::chrono::milliseconds, std::stop_token)
|
||||||
|
{
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||||
|
}
|
||||||
|
Void::Result::Result<void>
|
||||||
|
TlsClientStream::write_all(std::span<const std::byte>,
|
||||||
|
std::chrono::milliseconds, std::stop_token)
|
||||||
|
{
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||||
|
}
|
||||||
|
Void::Result::Result<void>
|
||||||
|
TlsClientStream::write_all(std::string_view, std::chrono::milliseconds,
|
||||||
|
std::stop_token)
|
||||||
|
{
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||||
|
}
|
||||||
|
Void::Result::Result<void> TlsClientStream::shutdown()
|
||||||
|
{
|
||||||
|
if (m_impl != nullptr) {
|
||||||
|
m_impl->close_all();
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
void TlsClientStream::close() noexcept
|
||||||
|
{
|
||||||
|
if (m_impl != nullptr) {
|
||||||
|
m_impl->close_all();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
Void::Result::Result<TlsClientStream>
|
||||||
|
TlsClientStream::connect(TlsClientOptions options)
|
||||||
|
{
|
||||||
|
const auto timeout =
|
||||||
|
effective_timeout(options.connect_timeout,
|
||||||
|
std::chrono::seconds{10});
|
||||||
|
auto fd = tcp_connect(options, deadline_for(timeout));
|
||||||
|
if (!fd.has_value()) {
|
||||||
|
return std::unexpected{std::move(fd.error())};
|
||||||
|
}
|
||||||
|
auto impl = std::make_unique<Impl>();
|
||||||
|
impl->fd = *fd;
|
||||||
|
impl->io_timeout = options.io_timeout;
|
||||||
|
impl->handshake_timeout = options.handshake_timeout;
|
||||||
|
impl->stop = options.stop;
|
||||||
|
impl->server_name = verification_name(options);
|
||||||
|
impl->ca_file = std::move(options.ca_file);
|
||||||
|
TlsClientStream stream{std::move(impl)};
|
||||||
|
auto started = stream.start_tls();
|
||||||
|
if (!started.has_value()) {
|
||||||
|
return std::unexpected{std::move(started.error())};
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<TlsClientStream>
|
||||||
|
TlsClientStream::connect_plain(TlsClientOptions options)
|
||||||
|
{
|
||||||
|
const auto timeout =
|
||||||
|
effective_timeout(options.connect_timeout,
|
||||||
|
std::chrono::seconds{10});
|
||||||
|
auto fd = tcp_connect(options, deadline_for(timeout));
|
||||||
|
if (!fd.has_value()) {
|
||||||
|
return std::unexpected{std::move(fd.error())};
|
||||||
|
}
|
||||||
|
auto impl = std::make_unique<Impl>();
|
||||||
|
impl->fd = *fd;
|
||||||
|
impl->io_timeout = options.io_timeout;
|
||||||
|
impl->handshake_timeout = options.handshake_timeout;
|
||||||
|
impl->stop = options.stop;
|
||||||
|
impl->server_name = verification_name(options);
|
||||||
|
impl->ca_file = std::move(options.ca_file);
|
||||||
|
return TlsClientStream{std::move(impl)};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<TlsClientStream>
|
||||||
|
TlsClientStream::adopt(int native_socket, TlsClientOptions options)
|
||||||
|
{
|
||||||
|
if (native_socket < 0) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net: TLS adopt requires an open socket")};
|
||||||
|
}
|
||||||
|
const int flags = ::fcntl(native_socket, F_GETFL, 0);
|
||||||
|
if (flags < 0 ||
|
||||||
|
::fcntl(native_socket, F_SETFL, flags | O_NONBLOCK) < 0) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error,
|
||||||
|
std::format("Net: TLS adopt failed to configure socket: {}",
|
||||||
|
std::strerror(errno)))};
|
||||||
|
}
|
||||||
|
auto impl = std::make_unique<Impl>();
|
||||||
|
impl->fd = native_socket;
|
||||||
|
impl->io_timeout = options.io_timeout;
|
||||||
|
impl->handshake_timeout = options.handshake_timeout;
|
||||||
|
impl->stop = options.stop;
|
||||||
|
impl->server_name = verification_name(options);
|
||||||
|
impl->ca_file = std::move(options.ca_file);
|
||||||
|
TlsClientStream stream{std::move(impl)};
|
||||||
|
auto started = stream.start_tls();
|
||||||
|
if (!started.has_value()) {
|
||||||
|
return std::unexpected{std::move(started.error())};
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void> TlsClientStream::start_tls()
|
||||||
|
{
|
||||||
|
if (m_impl == nullptr || !m_impl->valid()) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||||
|
}
|
||||||
|
auto& impl = *m_impl;
|
||||||
|
if (impl.secure) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
if (impl.ctx != nullptr || impl.ssl != nullptr) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
"Net: TLS handshake already attempted")};
|
||||||
|
}
|
||||||
|
|
||||||
|
impl.ctx = SSL_CTX_new(TLS_client_method());
|
||||||
|
if (impl.ctx == nullptr) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::tls_error,
|
||||||
|
"Net: TLS failed to create context: " +
|
||||||
|
openssl_error_text())};
|
||||||
|
}
|
||||||
|
if (SSL_CTX_set_min_proto_version(impl.ctx, TLS1_2_VERSION) != 1) {
|
||||||
|
const auto error = make_net_error(
|
||||||
|
NetErrorCode::tls_error,
|
||||||
|
"Net: TLS failed to require TLS 1.2: " + openssl_error_text());
|
||||||
|
impl.close_all();
|
||||||
|
return std::unexpected{error};
|
||||||
|
}
|
||||||
|
SSL_CTX_set_verify(impl.ctx, SSL_VERIFY_PEER, nullptr);
|
||||||
|
// The trust store is always applied; a failure is fatal and never
|
||||||
|
// downgrades verification.
|
||||||
|
const int loaded =
|
||||||
|
impl.ca_file.empty()
|
||||||
|
? SSL_CTX_set_default_verify_paths(impl.ctx)
|
||||||
|
: SSL_CTX_load_verify_locations(impl.ctx,
|
||||||
|
impl.ca_file.c_str(), nullptr);
|
||||||
|
if (loaded != 1) {
|
||||||
|
const auto error = make_net_error(
|
||||||
|
NetErrorCode::tls_error,
|
||||||
|
std::format("Net: TLS failed to load trust store{}: {}",
|
||||||
|
impl.ca_file.empty()
|
||||||
|
? std::string{}
|
||||||
|
: " '" + impl.ca_file + "'",
|
||||||
|
openssl_error_text()));
|
||||||
|
impl.close_all();
|
||||||
|
return std::unexpected{error};
|
||||||
|
}
|
||||||
|
|
||||||
|
impl.ssl = SSL_new(impl.ctx);
|
||||||
|
if (impl.ssl == nullptr) {
|
||||||
|
const auto error = make_net_error(
|
||||||
|
NetErrorCode::tls_error,
|
||||||
|
"Net: TLS failed to create session: " +
|
||||||
|
openssl_error_text());
|
||||||
|
impl.close_all();
|
||||||
|
return std::unexpected{error};
|
||||||
|
}
|
||||||
|
if (SSL_set_fd(impl.ssl, impl.fd) != 1) {
|
||||||
|
const auto error = make_net_error(
|
||||||
|
NetErrorCode::tls_error,
|
||||||
|
"Net: TLS failed to attach socket: " +
|
||||||
|
openssl_error_text());
|
||||||
|
impl.close_all();
|
||||||
|
return std::unexpected{error};
|
||||||
|
}
|
||||||
|
(void)SSL_set_mode(impl.ssl,
|
||||||
|
SSL_MODE_ENABLE_PARTIAL_WRITE |
|
||||||
|
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
|
||||||
|
if (!is_ip_literal(impl.server_name) &&
|
||||||
|
SSL_set_tlsext_host_name(impl.ssl,
|
||||||
|
impl.server_name.c_str()) != 1) {
|
||||||
|
const auto error = make_net_error(
|
||||||
|
NetErrorCode::tls_error,
|
||||||
|
"Net: TLS failed to set SNI hostname: " +
|
||||||
|
openssl_error_text());
|
||||||
|
impl.close_all();
|
||||||
|
return std::unexpected{error};
|
||||||
|
}
|
||||||
|
X509_VERIFY_PARAM* param = SSL_get0_param(impl.ssl);
|
||||||
|
if (param == nullptr) {
|
||||||
|
const auto error = make_net_error(
|
||||||
|
NetErrorCode::tls_error,
|
||||||
|
"Net: TLS X509 verification parameters unavailable");
|
||||||
|
impl.close_all();
|
||||||
|
return std::unexpected{error};
|
||||||
|
}
|
||||||
|
X509_VERIFY_PARAM_set_hostflags(param,
|
||||||
|
X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
|
||||||
|
const int set_name =
|
||||||
|
is_ip_literal(impl.server_name)
|
||||||
|
? X509_VERIFY_PARAM_set1_ip_asc(param,
|
||||||
|
impl.server_name.c_str())
|
||||||
|
: X509_VERIFY_PARAM_set1_host(param,
|
||||||
|
impl.server_name.c_str(),
|
||||||
|
impl.server_name.size());
|
||||||
|
if (set_name != 1) {
|
||||||
|
const auto error = make_net_error(
|
||||||
|
NetErrorCode::tls_error,
|
||||||
|
"Net: TLS failed to set peer verification target");
|
||||||
|
impl.close_all();
|
||||||
|
return std::unexpected{error};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto deadline =
|
||||||
|
deadline_for(effective_timeout({}, impl.handshake_timeout));
|
||||||
|
for (;;) {
|
||||||
|
if (impl.stop.stop_requested()) {
|
||||||
|
const auto error = cancelled_error("handshake");
|
||||||
|
impl.close_all();
|
||||||
|
return std::unexpected{error};
|
||||||
|
}
|
||||||
|
ERR_clear_error();
|
||||||
|
const int rc = SSL_connect(impl.ssl);
|
||||||
|
if (rc == 1) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const int error_code = SSL_get_error(impl.ssl, rc);
|
||||||
|
if (error_code == SSL_ERROR_WANT_READ ||
|
||||||
|
error_code == SSL_ERROR_WANT_WRITE) {
|
||||||
|
const auto waited = wait_fd(
|
||||||
|
impl.fd,
|
||||||
|
error_code == SSL_ERROR_WANT_READ ? POLLIN : POLLOUT,
|
||||||
|
deadline, impl.stop, "handshake");
|
||||||
|
if (!waited.has_value()) {
|
||||||
|
const auto error = waited.error();
|
||||||
|
impl.close_all();
|
||||||
|
return std::unexpected{error};
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (error_code == SSL_ERROR_SYSCALL && errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const long verify = SSL_get_verify_result(impl.ssl);
|
||||||
|
std::string detail = openssl_error_text();
|
||||||
|
if (verify != X509_V_OK) {
|
||||||
|
detail += std::format(" (certificate verify: {})",
|
||||||
|
X509_verify_cert_error_string(verify));
|
||||||
|
}
|
||||||
|
const auto error = make_net_error(
|
||||||
|
NetErrorCode::tls_error,
|
||||||
|
"Net: TLS handshake failed: " + detail);
|
||||||
|
impl.close_all();
|
||||||
|
return std::unexpected{error};
|
||||||
|
}
|
||||||
|
const long verify = SSL_get_verify_result(impl.ssl);
|
||||||
|
if (verify != X509_V_OK) {
|
||||||
|
const auto error = make_net_error(
|
||||||
|
NetErrorCode::tls_error,
|
||||||
|
std::format("Net: TLS peer verification failed: {}",
|
||||||
|
X509_verify_cert_error_string(verify)));
|
||||||
|
impl.close_all();
|
||||||
|
return std::unexpected{error};
|
||||||
|
}
|
||||||
|
impl.secure = true;
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::size_t>
|
||||||
|
TlsClientStream::read(std::span<std::byte> destination,
|
||||||
|
std::chrono::milliseconds timeout,
|
||||||
|
std::stop_token stop)
|
||||||
|
{
|
||||||
|
if (m_impl == nullptr || !m_impl->valid()) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||||
|
}
|
||||||
|
if (destination.empty()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
auto& impl = *m_impl;
|
||||||
|
const auto deadline =
|
||||||
|
deadline_for(effective_timeout(timeout, impl.io_timeout));
|
||||||
|
const std::stop_token token =
|
||||||
|
stop.stop_possible() ? stop : impl.stop;
|
||||||
|
for (;;) {
|
||||||
|
if (token.stop_requested()) {
|
||||||
|
return std::unexpected{cancelled_error("read")};
|
||||||
|
}
|
||||||
|
if (impl.secure) {
|
||||||
|
ERR_clear_error();
|
||||||
|
const int rc = SSL_read(
|
||||||
|
impl.ssl, destination.data(),
|
||||||
|
static_cast<int>(std::min<std::size_t>(
|
||||||
|
destination.size(),
|
||||||
|
static_cast<std::size_t>(INT_MAX))));
|
||||||
|
if (rc > 0) {
|
||||||
|
return static_cast<std::size_t>(rc);
|
||||||
|
}
|
||||||
|
const int error_code = SSL_get_error(impl.ssl, rc);
|
||||||
|
if (error_code == SSL_ERROR_WANT_READ ||
|
||||||
|
error_code == SSL_ERROR_WANT_WRITE) {
|
||||||
|
auto waited = wait_fd(
|
||||||
|
impl.fd,
|
||||||
|
error_code == SSL_ERROR_WANT_READ ? POLLIN
|
||||||
|
: POLLOUT,
|
||||||
|
deadline, token, "read");
|
||||||
|
if (!waited.has_value()) {
|
||||||
|
return std::unexpected{std::move(waited.error())};
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (error_code == SSL_ERROR_ZERO_RETURN) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (error_code == SSL_ERROR_SYSCALL) {
|
||||||
|
if (errno == EINTR || errno == EAGAIN ||
|
||||||
|
errno == EWOULDBLOCK) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (rc == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error,
|
||||||
|
std::format("Net: TLS read failed: {}",
|
||||||
|
std::strerror(errno)))};
|
||||||
|
}
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::tls_error,
|
||||||
|
"Net: TLS read failed: " + openssl_error_text())};
|
||||||
|
}
|
||||||
|
const ssize_t rc = ::recv(impl.fd, destination.data(),
|
||||||
|
destination.size(), 0);
|
||||||
|
if (rc > 0) {
|
||||||
|
return static_cast<std::size_t>(rc);
|
||||||
|
}
|
||||||
|
if (rc == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (errno == EAGAIN || errno == EWOULDBLOCK) {
|
||||||
|
auto waited = wait_fd(impl.fd, POLLIN, deadline, token,
|
||||||
|
"read");
|
||||||
|
if (!waited.has_value()) {
|
||||||
|
return std::unexpected{std::move(waited.error())};
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error,
|
||||||
|
std::format("Net: TCP read failed: {}",
|
||||||
|
std::strerror(errno)))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::size_t>
|
||||||
|
TlsClientStream::write(std::span<const std::byte> source,
|
||||||
|
std::chrono::milliseconds timeout,
|
||||||
|
std::stop_token stop)
|
||||||
|
{
|
||||||
|
if (m_impl == nullptr || !m_impl->valid()) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||||
|
}
|
||||||
|
if (source.empty()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
auto& impl = *m_impl;
|
||||||
|
const auto deadline =
|
||||||
|
deadline_for(effective_timeout(timeout, impl.io_timeout));
|
||||||
|
const std::stop_token token =
|
||||||
|
stop.stop_possible() ? stop : impl.stop;
|
||||||
|
for (;;) {
|
||||||
|
if (token.stop_requested()) {
|
||||||
|
return std::unexpected{cancelled_error("write")};
|
||||||
|
}
|
||||||
|
if (impl.secure) {
|
||||||
|
ERR_clear_error();
|
||||||
|
const int rc = SSL_write(
|
||||||
|
impl.ssl, source.data(),
|
||||||
|
static_cast<int>(std::min<std::size_t>(
|
||||||
|
source.size(),
|
||||||
|
static_cast<std::size_t>(INT_MAX))));
|
||||||
|
if (rc > 0) {
|
||||||
|
return static_cast<std::size_t>(rc);
|
||||||
|
}
|
||||||
|
const int error_code = SSL_get_error(impl.ssl, rc);
|
||||||
|
if (error_code == SSL_ERROR_WANT_READ ||
|
||||||
|
error_code == SSL_ERROR_WANT_WRITE) {
|
||||||
|
auto waited = wait_fd(
|
||||||
|
impl.fd,
|
||||||
|
error_code == SSL_ERROR_WANT_READ ? POLLIN
|
||||||
|
: POLLOUT,
|
||||||
|
deadline, token, "write");
|
||||||
|
if (!waited.has_value()) {
|
||||||
|
return std::unexpected{std::move(waited.error())};
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (error_code == SSL_ERROR_SYSCALL) {
|
||||||
|
if (errno == EINTR || errno == EAGAIN ||
|
||||||
|
errno == EWOULDBLOCK) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error,
|
||||||
|
std::format("Net: TLS write failed: {}",
|
||||||
|
std::strerror(errno)))};
|
||||||
|
}
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::tls_error,
|
||||||
|
"Net: TLS write failed: " + openssl_error_text())};
|
||||||
|
}
|
||||||
|
#ifdef MSG_NOSIGNAL
|
||||||
|
constexpr int flags = MSG_NOSIGNAL;
|
||||||
|
#else
|
||||||
|
constexpr int flags = 0;
|
||||||
|
#endif
|
||||||
|
const ssize_t rc =
|
||||||
|
::send(impl.fd, source.data(), source.size(), flags);
|
||||||
|
if (rc > 0) {
|
||||||
|
return static_cast<std::size_t>(rc);
|
||||||
|
}
|
||||||
|
if (rc < 0 && errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (rc < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
|
||||||
|
auto waited = wait_fd(impl.fd, POLLOUT, deadline, token,
|
||||||
|
"write");
|
||||||
|
if (!waited.has_value()) {
|
||||||
|
return std::unexpected{std::move(waited.error())};
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error,
|
||||||
|
std::format("Net: TCP write failed: {}",
|
||||||
|
std::strerror(errno)))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void>
|
||||||
|
TlsClientStream::write_all(std::span<const std::byte> source,
|
||||||
|
std::chrono::milliseconds timeout,
|
||||||
|
std::stop_token stop)
|
||||||
|
{
|
||||||
|
while (!source.empty()) {
|
||||||
|
auto written = write(source, timeout, stop);
|
||||||
|
if (!written.has_value()) {
|
||||||
|
return std::unexpected{std::move(written.error())};
|
||||||
|
}
|
||||||
|
if (*written == 0) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::io_error,
|
||||||
|
"Net: TLS write made no progress")};
|
||||||
|
}
|
||||||
|
source = source.subspan(*written);
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void>
|
||||||
|
TlsClientStream::write_all(std::string_view text,
|
||||||
|
std::chrono::milliseconds timeout,
|
||||||
|
std::stop_token stop)
|
||||||
|
{
|
||||||
|
return write_all(
|
||||||
|
std::span<const std::byte>{
|
||||||
|
reinterpret_cast<const std::byte*>(text.data()),
|
||||||
|
text.size()},
|
||||||
|
timeout, stop);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void> TlsClientStream::shutdown()
|
||||||
|
{
|
||||||
|
if (m_impl == nullptr) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
auto& impl = *m_impl;
|
||||||
|
Void::Result::Result<void> result{};
|
||||||
|
if (impl.secure && impl.ssl != nullptr) {
|
||||||
|
const auto deadline =
|
||||||
|
deadline_for(effective_timeout({}, impl.io_timeout));
|
||||||
|
for (;;) {
|
||||||
|
ERR_clear_error();
|
||||||
|
const int rc = SSL_shutdown(impl.ssl);
|
||||||
|
if (rc >= 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const int error_code = SSL_get_error(impl.ssl, rc);
|
||||||
|
if (error_code == SSL_ERROR_WANT_READ ||
|
||||||
|
error_code == SSL_ERROR_WANT_WRITE) {
|
||||||
|
auto waited = wait_fd(
|
||||||
|
impl.fd,
|
||||||
|
error_code == SSL_ERROR_WANT_READ ? POLLIN
|
||||||
|
: POLLOUT,
|
||||||
|
deadline, impl.stop, "shutdown");
|
||||||
|
if (!waited.has_value()) {
|
||||||
|
result = std::unexpected{
|
||||||
|
std::move(waited.error())};
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl.close_all();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
void TlsClientStream::close() noexcept
|
||||||
|
{
|
||||||
|
if (m_impl != nullptr) {
|
||||||
|
m_impl->close_all();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
} // namespace Void::Net
|
||||||
@@ -1,5 +1,10 @@
|
|||||||
void_add_module(Net
|
void_add_module(Net
|
||||||
INTERNAL_DEPS Functional Text Time
|
INTERNAL_DEPS Functional Text Time
|
||||||
|
# The HTTP server is POSIX-only. Windows builds get the client-side
|
||||||
|
# surface; a Windows server port is explicitly out of scope, and any
|
||||||
|
# server symbol left undefined fails closed at link time.
|
||||||
|
EXCLUDE_SOURCES_WIN32
|
||||||
|
HttpServer.cpp
|
||||||
EXTERNAL_DEPS
|
EXTERNAL_DEPS
|
||||||
Boost::headers
|
Boost::headers
|
||||||
Boost::beast
|
Boost::beast
|
||||||
|
|||||||
@@ -0,0 +1,337 @@
|
|||||||
|
#include <Void/Script/Lua.hpp>
|
||||||
|
|
||||||
|
#if defined(VOID_SCRIPT_HAS_LUA)
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <exception>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
extern "C" {
|
||||||
|
#include <lauxlib.h>
|
||||||
|
#include <lua.h>
|
||||||
|
#include <lualib.h>
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace Void::Script
|
||||||
|
{
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
struct Context {
|
||||||
|
const Limits* limits{nullptr};
|
||||||
|
const std::vector<Host>* hosts{nullptr};
|
||||||
|
const CancelFunction* cancelled{nullptr};
|
||||||
|
std::size_t used_bytes{0};
|
||||||
|
std::size_t executed{0};
|
||||||
|
std::size_t hook_step{1};
|
||||||
|
std::size_t host_calls{0};
|
||||||
|
bool allocator_limit_hit{false};
|
||||||
|
bool instruction_limit_hit{false};
|
||||||
|
bool host_call_limit_hit{false};
|
||||||
|
bool cancel_requested{false};
|
||||||
|
std::string host_error;
|
||||||
|
std::vector<Integer> scratch_arguments;
|
||||||
|
std::vector<HostInvocation> invocations;
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] Context* context_of(lua_State* state)
|
||||||
|
{
|
||||||
|
return *static_cast<Context**>(lua_getextraspace(state));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Polls the cancellation callback. Exceptions thrown by the callback count as
|
||||||
|
/// a cancellation request so a misbehaving policy can never escape into Lua's
|
||||||
|
/// C error machinery.
|
||||||
|
[[nodiscard]] bool cancellation_pending(Context& context)
|
||||||
|
{
|
||||||
|
if (context.cancel_requested) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (context.cancelled == nullptr || !*context.cancelled) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if ((*context.cancelled)()) {
|
||||||
|
context.cancel_requested = true;
|
||||||
|
}
|
||||||
|
} catch (...) {
|
||||||
|
context.cancel_requested = true;
|
||||||
|
}
|
||||||
|
return context.cancel_requested;
|
||||||
|
}
|
||||||
|
|
||||||
|
void* limited_alloc(void* user, void* pointer, std::size_t old_size,
|
||||||
|
std::size_t new_size)
|
||||||
|
{
|
||||||
|
auto* context = static_cast<Context*>(user);
|
||||||
|
if (new_size == 0) {
|
||||||
|
if (pointer != nullptr) {
|
||||||
|
context->used_bytes = old_size >= context->used_bytes
|
||||||
|
? 0
|
||||||
|
: context->used_bytes - old_size;
|
||||||
|
std::free(pointer);
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
const std::size_t current = pointer != nullptr ? old_size : 0;
|
||||||
|
const std::size_t limit = context->limits->max_allocator_bytes;
|
||||||
|
const std::size_t used = context->used_bytes;
|
||||||
|
if (new_size > current &&
|
||||||
|
(used > limit || new_size - current > limit - used)) {
|
||||||
|
context->allocator_limit_hit = true;
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
void* result = std::realloc(pointer, new_size);
|
||||||
|
if (result != nullptr) {
|
||||||
|
context->used_bytes = used - current + new_size;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
void instruction_hook(lua_State* state, lua_Debug*)
|
||||||
|
{
|
||||||
|
Context* context = context_of(state);
|
||||||
|
if (cancellation_pending(*context)) {
|
||||||
|
luaL_error(state, "evaluation cancelled");
|
||||||
|
}
|
||||||
|
context->executed += context->hook_step;
|
||||||
|
if (context->executed >= context->limits->max_instructions) {
|
||||||
|
context->instruction_limit_hit = true;
|
||||||
|
luaL_error(state, "instruction limit exceeded");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes the base-library entry points that reach outside the sandbox.
|
||||||
|
void harden_base(lua_State* state)
|
||||||
|
{
|
||||||
|
const char* const removed[] = {"load", "loadfile", "dofile",
|
||||||
|
"print", "collectgarbage"};
|
||||||
|
for (const char* name : removed) {
|
||||||
|
lua_pushnil(state);
|
||||||
|
lua_setglobal(state, name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void open_bindings(lua_State* state, const Bindings& bindings)
|
||||||
|
{
|
||||||
|
struct Library {
|
||||||
|
bool enabled;
|
||||||
|
const char* name;
|
||||||
|
lua_CFunction open;
|
||||||
|
};
|
||||||
|
const Library libraries[] = {
|
||||||
|
{bindings.base, LUA_GNAME, luaopen_base},
|
||||||
|
{bindings.table, LUA_TABLIBNAME, luaopen_table},
|
||||||
|
{bindings.string, LUA_STRLIBNAME, luaopen_string},
|
||||||
|
{bindings.math, LUA_MATHLIBNAME, luaopen_math},
|
||||||
|
{bindings.coroutine, LUA_COLIBNAME, luaopen_coroutine},
|
||||||
|
};
|
||||||
|
for (const auto& library : libraries) {
|
||||||
|
if (!library.enabled) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
luaL_requiref(state, library.name, library.open, 1);
|
||||||
|
lua_pop(state, 1);
|
||||||
|
}
|
||||||
|
if (bindings.base) {
|
||||||
|
harden_base(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int host_trampoline(lua_State* state)
|
||||||
|
{
|
||||||
|
Context* context = context_of(state);
|
||||||
|
if (cancellation_pending(*context)) {
|
||||||
|
lua_pushliteral(state, "evaluation cancelled");
|
||||||
|
return lua_error(state);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<Integer>& arguments = context->scratch_arguments;
|
||||||
|
arguments.clear();
|
||||||
|
const int argument_count = lua_gettop(state);
|
||||||
|
arguments.reserve(static_cast<std::size_t>(argument_count));
|
||||||
|
for (int index = 1; index <= argument_count; ++index) {
|
||||||
|
int is_integer = 0;
|
||||||
|
const lua_Integer value = lua_tointegerx(state, index, &is_integer);
|
||||||
|
if (is_integer == 0) {
|
||||||
|
lua_pushliteral(state, "host arguments must be integers");
|
||||||
|
return lua_error(state);
|
||||||
|
}
|
||||||
|
arguments.push_back(static_cast<Integer>(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto host_index = static_cast<std::size_t>(
|
||||||
|
lua_tointeger(state, lua_upvalueindex(1)));
|
||||||
|
const Host& host = (*context->hosts)[host_index];
|
||||||
|
if (context->host_calls >= context->limits->max_host_calls) {
|
||||||
|
context->host_call_limit_hit = true;
|
||||||
|
lua_pushliteral(state, "host call limit exceeded");
|
||||||
|
return lua_error(state);
|
||||||
|
}
|
||||||
|
++context->host_calls;
|
||||||
|
|
||||||
|
bool succeeded = false;
|
||||||
|
Integer value = 0;
|
||||||
|
try {
|
||||||
|
auto result = host.function(arguments);
|
||||||
|
if (result.has_value()) {
|
||||||
|
succeeded = true;
|
||||||
|
value = *result;
|
||||||
|
} else {
|
||||||
|
context->host_error = result.error();
|
||||||
|
}
|
||||||
|
} catch (const std::exception& exception) {
|
||||||
|
context->host_error = exception.what();
|
||||||
|
} catch (...) {
|
||||||
|
context->host_error = "host threw an unknown exception";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!succeeded) {
|
||||||
|
lua_pushfstring(state, "host '%s' failed: %s", host.name.c_str(),
|
||||||
|
context->host_error.c_str());
|
||||||
|
return lua_error(state);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
context->invocations.push_back(
|
||||||
|
HostInvocation{.host = host.name,
|
||||||
|
.arguments = std::move(arguments),
|
||||||
|
.result = value});
|
||||||
|
} catch (...) {
|
||||||
|
lua_pushliteral(state, "host result allocation failed");
|
||||||
|
return lua_error(state);
|
||||||
|
}
|
||||||
|
lua_pushinteger(state, static_cast<lua_Integer>(value));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::string last_message(lua_State* state,
|
||||||
|
std::string_view fallback)
|
||||||
|
{
|
||||||
|
const char* message = lua_tostring(state, -1);
|
||||||
|
return message != nullptr ? std::string{message} : std::string{fallback};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::expected<Result, Error>
|
||||||
|
LuaEvaluator::evaluate(std::string_view source,
|
||||||
|
std::span<const Input> inputs) const
|
||||||
|
{
|
||||||
|
const Limits& limits = configuration_.limits;
|
||||||
|
if (inputs.size() > limits.max_inputs) {
|
||||||
|
return std::unexpected{Error{.kind = ErrorKind::invalid_input,
|
||||||
|
.message = "too many inputs"}};
|
||||||
|
}
|
||||||
|
|
||||||
|
Context context;
|
||||||
|
context.limits = &limits;
|
||||||
|
context.hosts = &configuration_.hosts;
|
||||||
|
context.cancelled = &configuration_.cancelled;
|
||||||
|
|
||||||
|
lua_State* state = lua_newstate(limited_alloc, &context);
|
||||||
|
if (state == nullptr) {
|
||||||
|
return std::unexpected{
|
||||||
|
Error{.kind = ErrorKind::allocator_limit,
|
||||||
|
.message = "cannot create Lua state"}};
|
||||||
|
}
|
||||||
|
*static_cast<Context**>(lua_getextraspace(state)) = &context;
|
||||||
|
|
||||||
|
open_bindings(state, configuration_.bindings);
|
||||||
|
|
||||||
|
lua_createtable(state, 0, static_cast<int>(inputs.size()));
|
||||||
|
for (const auto& input : inputs) {
|
||||||
|
lua_pushinteger(state, static_cast<lua_Integer>(input.value));
|
||||||
|
lua_seti(state, -2, static_cast<lua_Integer>(input.key));
|
||||||
|
}
|
||||||
|
lua_setglobal(state, "input");
|
||||||
|
|
||||||
|
for (std::size_t index = 0; index < configuration_.hosts.size(); ++index) {
|
||||||
|
lua_pushinteger(state, static_cast<lua_Integer>(index));
|
||||||
|
lua_pushcclosure(state, host_trampoline, 1);
|
||||||
|
lua_setglobal(state, configuration_.hosts[index].name.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
context.hook_step = std::clamp<std::size_t>(limits.max_instructions, 1, 1000);
|
||||||
|
lua_sethook(state, instruction_hook, LUA_MASKCOUNT,
|
||||||
|
static_cast<int>(context.hook_step));
|
||||||
|
|
||||||
|
if (luaL_loadbufferx(state, source.data(), source.size(), "chunk", "t") !=
|
||||||
|
LUA_OK) {
|
||||||
|
std::string message = last_message(state, "compile error");
|
||||||
|
lua_close(state);
|
||||||
|
return std::unexpected{
|
||||||
|
Error{.kind = ErrorKind::compile, .message = std::move(message)}};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cancellation_pending(context)) {
|
||||||
|
lua_close(state);
|
||||||
|
return std::unexpected{
|
||||||
|
Error{.kind = ErrorKind::cancelled, .message = "evaluation cancelled"}};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lua_pcall(state, 0, LUA_MULTRET, 0) != LUA_OK) {
|
||||||
|
std::string message = last_message(state, "runtime error");
|
||||||
|
ErrorKind kind = ErrorKind::runtime;
|
||||||
|
if (context.allocator_limit_hit) {
|
||||||
|
kind = ErrorKind::allocator_limit;
|
||||||
|
} else if (context.cancel_requested) {
|
||||||
|
kind = ErrorKind::cancelled;
|
||||||
|
} else if (context.instruction_limit_hit) {
|
||||||
|
kind = ErrorKind::instruction_limit;
|
||||||
|
} else if (context.host_call_limit_hit) {
|
||||||
|
kind = ErrorKind::host_call_limit;
|
||||||
|
} else if (!context.host_error.empty()) {
|
||||||
|
kind = ErrorKind::host_error;
|
||||||
|
}
|
||||||
|
lua_close(state);
|
||||||
|
return std::unexpected{
|
||||||
|
Error{.kind = kind, .message = std::move(message)}};
|
||||||
|
}
|
||||||
|
|
||||||
|
Result result;
|
||||||
|
const int result_count = lua_gettop(state);
|
||||||
|
for (int index = 1; index <= result_count; ++index) {
|
||||||
|
int is_integer = 0;
|
||||||
|
const lua_Integer value = lua_tointegerx(state, index, &is_integer);
|
||||||
|
if (is_integer == 0) {
|
||||||
|
lua_close(state);
|
||||||
|
return std::unexpected{
|
||||||
|
Error{.kind = ErrorKind::runtime,
|
||||||
|
.message = "script results must be integers"}};
|
||||||
|
}
|
||||||
|
if (result.integers.size() >= limits.max_result_integers) {
|
||||||
|
lua_close(state);
|
||||||
|
return std::unexpected{
|
||||||
|
Error{.kind = ErrorKind::result_limit,
|
||||||
|
.message = "result limit exceeded"}};
|
||||||
|
}
|
||||||
|
result.integers.push_back(static_cast<Integer>(value));
|
||||||
|
}
|
||||||
|
result.host_calls = std::move(context.invocations);
|
||||||
|
lua_close(state);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Script
|
||||||
|
|
||||||
|
#else
|
||||||
|
|
||||||
|
namespace Void::Script
|
||||||
|
{
|
||||||
|
|
||||||
|
std::expected<Result, Error>
|
||||||
|
LuaEvaluator::evaluate(std::string_view, std::span<const Input>) const
|
||||||
|
{
|
||||||
|
return std::unexpected{
|
||||||
|
Error{.kind = ErrorKind::runtime,
|
||||||
|
.message = "Lua adapter not compiled in"}};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Script
|
||||||
|
|
||||||
|
#endif // VOID_SCRIPT_HAS_LUA
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
set(_void_script_lua OFF)
|
||||||
|
if(VOID_SCRIPT_ENABLE_LUA)
|
||||||
|
find_package(Lua 5.4 QUIET)
|
||||||
|
if(LUA_FOUND OR VOID_FETCH_LUA)
|
||||||
|
set(_void_script_lua ON)
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(_void_script_lua)
|
||||||
|
void_add_module(Script
|
||||||
|
EXTERNAL_DEPS Lua::Lua
|
||||||
|
)
|
||||||
|
target_compile_definitions(Void_Script PUBLIC VOID_SCRIPT_HAS_LUA=1)
|
||||||
|
else()
|
||||||
|
message(STATUS "[Void] Lua 5.4 not available - building Script without the Lua adapter")
|
||||||
|
void_add_module(Script)
|
||||||
|
endif()
|
||||||
@@ -186,6 +186,24 @@ namespace Void::Security
|
|||||||
return encoded;
|
return encoded;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void> random_bytes(std::span<unsigned char> buffer)
|
||||||
|
{
|
||||||
|
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||||
|
return std::unexpected{initialized.error()};
|
||||||
|
}
|
||||||
|
if (buffer.empty()) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
if (auto fault = Detail::maybe_inject_fault(
|
||||||
|
FaultOperation::random_bytes, "Security::random_bytes");
|
||||||
|
fault.has_value()) {
|
||||||
|
wipe_bytes(buffer);
|
||||||
|
return std::unexpected{std::move(*fault)};
|
||||||
|
}
|
||||||
|
randombytes_buf(buffer.data(), buffer.size());
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
Void::Result::Result<std::string> hash_token(std::string_view token)
|
Void::Result::Result<std::string> hash_token(std::string_view token)
|
||||||
{
|
{
|
||||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||||
|
|||||||
+290
-27
@@ -33,6 +33,8 @@ namespace Void::Sqlite
|
|||||||
out.fail_next_commit_rc = std::exchange(g_fault_config.fail_next_commit_rc, 0);
|
out.fail_next_commit_rc = std::exchange(g_fault_config.fail_next_commit_rc, 0);
|
||||||
out.auto_rollback_on_faulted_commit =
|
out.auto_rollback_on_faulted_commit =
|
||||||
std::exchange(g_fault_config.auto_rollback_on_faulted_commit, false);
|
std::exchange(g_fault_config.auto_rollback_on_faulted_commit, false);
|
||||||
|
out.commit_applied_before_error =
|
||||||
|
std::exchange(g_fault_config.commit_applied_before_error, false);
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
@@ -82,6 +84,16 @@ namespace Void::Sqlite
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A WAL I/O error during COMMIT can be reported after the commit record
|
||||||
|
/// was written, so the wrapper cannot prove whether the transaction
|
||||||
|
/// committed. SQLite documents automatic rollback for other COMMIT
|
||||||
|
/// failures, and a rollback journal has crash recovery to resolve them.
|
||||||
|
[[nodiscard]] bool commit_outcome_unknown(
|
||||||
|
int rc, std::string_view journal_mode) noexcept
|
||||||
|
{
|
||||||
|
return (rc & 0xFF) == SQLITE_IOERR && journal_mode == "wal";
|
||||||
|
}
|
||||||
|
|
||||||
[[nodiscard]] Error sqlite_error_from_db(
|
[[nodiscard]] Error sqlite_error_from_db(
|
||||||
sqlite3* db,
|
sqlite3* db,
|
||||||
int primary_rc,
|
int primary_rc,
|
||||||
@@ -383,15 +395,29 @@ namespace Void::Sqlite
|
|||||||
namespace detail
|
namespace detail
|
||||||
{
|
{
|
||||||
struct ConnectionState {
|
struct ConnectionState {
|
||||||
|
struct WalUsage {
|
||||||
|
std::uint64_t size_bytes{0};
|
||||||
|
std::uint64_t uncheckpointed_bytes{0};
|
||||||
|
int log_frames{-1};
|
||||||
|
int checkpointed_frames{-1};
|
||||||
|
bool frames_known{false};
|
||||||
|
};
|
||||||
|
|
||||||
sqlite3* db{nullptr};
|
sqlite3* db{nullptr};
|
||||||
std::filesystem::path path{};
|
std::filesystem::path path{};
|
||||||
OpenOptions options{};
|
OpenOptions options{};
|
||||||
EffectiveCapabilities caps{};
|
EffectiveCapabilities caps{};
|
||||||
|
int page_size{0};
|
||||||
bool closing{false};
|
bool closing{false};
|
||||||
bool closed{false};
|
bool closed{false};
|
||||||
std::size_t live_statements{0};
|
std::size_t live_statements{0};
|
||||||
bool active_transaction{false};
|
bool active_transaction{false};
|
||||||
|
std::uint64_t active_transaction_id{0};
|
||||||
|
std::uint64_t next_transaction_id{0};
|
||||||
std::size_t open_savepoints{0};
|
std::size_t open_savepoints{0};
|
||||||
|
/// Current busy timeout, tracked so scoped overrides restore the
|
||||||
|
/// exact prior value instead of the configured default.
|
||||||
|
std::chrono::milliseconds busy_timeout{0};
|
||||||
|
|
||||||
std::vector<std::unique_ptr<ScalarFunctionBox>> scalar_functions{};
|
std::vector<std::unique_ptr<ScalarFunctionBox>> scalar_functions{};
|
||||||
std::unique_ptr<AuthorizerBox> authorizer{};
|
std::unique_ptr<AuthorizerBox> authorizer{};
|
||||||
@@ -422,6 +448,62 @@ namespace Void::Sqlite
|
|||||||
return ec ? 0ULL : static_cast<std::uint64_t>(sz);
|
return ec ? 0ULL : static_cast<std::uint64_t>(sz);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Measures WAL usage with an un-checkpointed-frame count. A passive
|
||||||
|
/// checkpoint is only attempted once the on-disk WAL reaches
|
||||||
|
/// `probe_threshold`; below that the file size is already a safe upper
|
||||||
|
/// bound and no native checkpoint work is done. Passive checkpoints never
|
||||||
|
/// block writers and never truncate, so this only advances nBackfill when
|
||||||
|
/// no reader pins the frames. If frame information is unavailable the
|
||||||
|
/// on-disk size is returned as a conservative fallback.
|
||||||
|
[[nodiscard]] WalUsage wal_usage(std::uint64_t probe_threshold) noexcept
|
||||||
|
{
|
||||||
|
WalUsage usage;
|
||||||
|
usage.size_bytes = current_wal_size_bytes();
|
||||||
|
if (usage.size_bytes == 0) {
|
||||||
|
return usage;
|
||||||
|
}
|
||||||
|
if (db == nullptr || usage.size_bytes < probe_threshold) {
|
||||||
|
usage.uncheckpointed_bytes = usage.size_bytes;
|
||||||
|
return usage;
|
||||||
|
}
|
||||||
|
|
||||||
|
int log_frames = -1;
|
||||||
|
int checkpointed_frames = -1;
|
||||||
|
const int rc = sqlite3_wal_checkpoint_v2(
|
||||||
|
db, "main", SQLITE_CHECKPOINT_PASSIVE, &log_frames, &checkpointed_frames);
|
||||||
|
if ((rc == SQLITE_OK || rc == SQLITE_BUSY) && log_frames >= 0 &&
|
||||||
|
checkpointed_frames >= 0) {
|
||||||
|
usage.log_frames = log_frames;
|
||||||
|
usage.checkpointed_frames = checkpointed_frames;
|
||||||
|
usage.frames_known = true;
|
||||||
|
const auto remaining = static_cast<std::uint64_t>(
|
||||||
|
std::max(0, log_frames - checkpointed_frames));
|
||||||
|
if (page_size > 0) {
|
||||||
|
usage.uncheckpointed_bytes =
|
||||||
|
std::min(usage.size_bytes,
|
||||||
|
remaining * static_cast<std::uint64_t>(page_size));
|
||||||
|
} else {
|
||||||
|
usage.uncheckpointed_bytes = usage.size_bytes;
|
||||||
|
}
|
||||||
|
return usage;
|
||||||
|
}
|
||||||
|
|
||||||
|
usage.uncheckpointed_bytes = usage.size_bytes;
|
||||||
|
return usage;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Clears wrapper transaction bookkeeping when SQLite ended the
|
||||||
|
/// transaction on its own (autocommit is back on). The original SQLite
|
||||||
|
/// error is never replaced by this observation.
|
||||||
|
void observe_autocommit_transition() noexcept
|
||||||
|
{
|
||||||
|
if (db != nullptr && active_transaction &&
|
||||||
|
sqlite3_get_autocommit(db) != 0) {
|
||||||
|
active_transaction = false;
|
||||||
|
active_transaction_id = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
~ConnectionState()
|
~ConnectionState()
|
||||||
{
|
{
|
||||||
if (db != nullptr) {
|
if (db != nullptr) {
|
||||||
@@ -890,16 +972,20 @@ namespace Void::Sqlite
|
|||||||
++m_row_generation;
|
++m_row_generation;
|
||||||
m_has_row = false;
|
m_has_row = false;
|
||||||
|
|
||||||
if (!m_conn->active_transaction &&
|
if (!m_conn->active_transaction && sqlite3_stmt_readonly(m_stmt) == 0) {
|
||||||
sqlite3_stmt_readonly(m_stmt) == 0 &&
|
const auto wal = m_conn->wal_usage(
|
||||||
m_conn->current_wal_size_bytes() >=
|
m_conn->options.limits.wal_stop_writes_threshold_bytes);
|
||||||
|
if (wal.uncheckpointed_bytes >=
|
||||||
m_conn->options.limits.wal_stop_writes_threshold_bytes) {
|
m_conn->options.limits.wal_stop_writes_threshold_bytes) {
|
||||||
return Void::Result::fail(make_sqlite_error(
|
return Void::Result::fail(make_sqlite_error(
|
||||||
SqliteErrorCode::overloaded,
|
SqliteErrorCode::overloaded,
|
||||||
"Sqlite: WAL size reached write-admission stop threshold; checkpoint required"));
|
"Sqlite: un-checkpointed WAL frames reached write-admission stop "
|
||||||
|
"threshold; checkpoint required"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const int rc = sqlite3_step(m_stmt);
|
const int rc = sqlite3_step(m_stmt);
|
||||||
|
m_conn->observe_autocommit_transition();
|
||||||
if (rc == SQLITE_ROW) {
|
if (rc == SQLITE_ROW) {
|
||||||
m_has_row = true;
|
m_has_row = true;
|
||||||
return true;
|
return true;
|
||||||
@@ -1251,13 +1337,44 @@ namespace Void::Sqlite
|
|||||||
|
|
||||||
// ── Transaction ──────────────────────────────────────────────────────────
|
// ── Transaction ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
Transaction::Transaction(std::shared_ptr<detail::ConnectionState> conn) noexcept
|
Transaction::Transaction(
|
||||||
: m_conn(std::move(conn)), m_state(TransactionState::Active)
|
std::shared_ptr<detail::ConnectionState> conn,
|
||||||
|
std::uint64_t id) noexcept
|
||||||
|
: m_conn(std::move(conn)), m_id(id), m_state(TransactionState::Active)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void Transaction::refresh_state() const noexcept
|
||||||
|
{
|
||||||
|
if (m_state != TransactionState::Active || !m_conn || m_conn->db == nullptr) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const bool owns_connection_transaction =
|
||||||
|
m_conn->active_transaction && m_conn->active_transaction_id == m_id;
|
||||||
|
if (!owns_connection_transaction ||
|
||||||
|
sqlite3_get_autocommit(m_conn->db) != 0) {
|
||||||
|
m_state = TransactionState::RolledBack;
|
||||||
|
if (m_conn->active_transaction_id == m_id) {
|
||||||
|
m_conn->active_transaction = false;
|
||||||
|
m_conn->active_transaction_id = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TransactionState Transaction::state() const noexcept
|
||||||
|
{
|
||||||
|
refresh_state();
|
||||||
|
return m_state;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Transaction::is_active() const noexcept
|
||||||
|
{
|
||||||
|
return state() == TransactionState::Active;
|
||||||
|
}
|
||||||
|
|
||||||
Transaction::~Transaction()
|
Transaction::~Transaction()
|
||||||
{
|
{
|
||||||
|
refresh_state();
|
||||||
if (m_state == TransactionState::Active) {
|
if (m_state == TransactionState::Active) {
|
||||||
auto r = rollback_checked();
|
auto r = rollback_checked();
|
||||||
if (!r && m_conn) {
|
if (!r && m_conn) {
|
||||||
@@ -1268,6 +1385,7 @@ namespace Void::Sqlite
|
|||||||
|
|
||||||
Transaction::Transaction(Transaction&& o) noexcept
|
Transaction::Transaction(Transaction&& o) noexcept
|
||||||
: m_conn(std::move(o.m_conn)),
|
: m_conn(std::move(o.m_conn)),
|
||||||
|
m_id(std::exchange(o.m_id, 0)),
|
||||||
m_state(std::exchange(o.m_state, TransactionState::RolledBack))
|
m_state(std::exchange(o.m_state, TransactionState::RolledBack))
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
@@ -1275,6 +1393,7 @@ namespace Void::Sqlite
|
|||||||
Transaction& Transaction::operator=(Transaction&& o) noexcept
|
Transaction& Transaction::operator=(Transaction&& o) noexcept
|
||||||
{
|
{
|
||||||
if (this != &o) {
|
if (this != &o) {
|
||||||
|
refresh_state();
|
||||||
if (m_state == TransactionState::Active) {
|
if (m_state == TransactionState::Active) {
|
||||||
auto r = rollback_checked();
|
auto r = rollback_checked();
|
||||||
if (!r && m_conn) {
|
if (!r && m_conn) {
|
||||||
@@ -1282,6 +1401,7 @@ namespace Void::Sqlite
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
m_conn = std::move(o.m_conn);
|
m_conn = std::move(o.m_conn);
|
||||||
|
m_id = std::exchange(o.m_id, 0);
|
||||||
m_state = std::exchange(o.m_state, TransactionState::RolledBack);
|
m_state = std::exchange(o.m_state, TransactionState::RolledBack);
|
||||||
}
|
}
|
||||||
return *this;
|
return *this;
|
||||||
@@ -1289,10 +1409,15 @@ namespace Void::Sqlite
|
|||||||
|
|
||||||
Result<void> Transaction::commit()
|
Result<void> Transaction::commit()
|
||||||
{
|
{
|
||||||
|
refresh_state();
|
||||||
if (m_state != TransactionState::Active) {
|
if (m_state != TransactionState::Active) {
|
||||||
return Void::Result::fail(make_sqlite_error(
|
return Void::Result::fail(make_sqlite_error(
|
||||||
SqliteErrorCode::misuse,
|
SqliteErrorCode::misuse,
|
||||||
"Sqlite: commit() called on non-active transaction"));
|
m_state == TransactionState::RolledBack
|
||||||
|
? "Sqlite: commit() called on a transaction that was already rolled back"
|
||||||
|
: m_state == TransactionState::Unknown
|
||||||
|
? "Sqlite: commit() called after an unknown commit outcome; inspect the database"
|
||||||
|
: "Sqlite: commit() called on non-active transaction"));
|
||||||
}
|
}
|
||||||
if (!m_conn || m_conn->db == nullptr) {
|
if (!m_conn || m_conn->db == nullptr) {
|
||||||
m_state = TransactionState::RecoveryRequired;
|
m_state = TransactionState::RecoveryRequired;
|
||||||
@@ -1303,15 +1428,32 @@ namespace Void::Sqlite
|
|||||||
|
|
||||||
const auto fault = consume_fault_commit();
|
const auto fault = consume_fault_commit();
|
||||||
if (fault.fail_next_commit_rc != 0) {
|
if (fault.fail_next_commit_rc != 0) {
|
||||||
if (fault.auto_rollback_on_faulted_commit) {
|
bool applied = false;
|
||||||
|
if (fault.commit_applied_before_error) {
|
||||||
|
char* apply_err = nullptr;
|
||||||
|
applied = sqlite3_exec(
|
||||||
|
m_conn->db, "COMMIT", nullptr, nullptr, &apply_err) == SQLITE_OK;
|
||||||
|
if (apply_err) sqlite3_free(apply_err);
|
||||||
|
} else if (fault.auto_rollback_on_faulted_commit) {
|
||||||
(void)sqlite3_exec(m_conn->db, "ROLLBACK", nullptr, nullptr, nullptr);
|
(void)sqlite3_exec(m_conn->db, "ROLLBACK", nullptr, nullptr, nullptr);
|
||||||
}
|
}
|
||||||
if (sqlite3_get_autocommit(m_conn->db) == 0) {
|
|
||||||
|
if (applied) {
|
||||||
|
// The commit took effect even though the caller sees an error.
|
||||||
|
m_state = TransactionState::Unknown;
|
||||||
|
m_conn->active_transaction = false;
|
||||||
|
m_conn->active_transaction_id = 0;
|
||||||
|
} else if (sqlite3_get_autocommit(m_conn->db) == 0) {
|
||||||
m_state = TransactionState::Active;
|
m_state = TransactionState::Active;
|
||||||
m_conn->active_transaction = true;
|
m_conn->active_transaction = true;
|
||||||
|
m_conn->active_transaction_id = m_id;
|
||||||
} else {
|
} else {
|
||||||
m_state = TransactionState::RolledBack;
|
m_state = commit_outcome_unknown(
|
||||||
|
fault.fail_next_commit_rc, m_conn->caps.journal_mode)
|
||||||
|
? TransactionState::Unknown
|
||||||
|
: TransactionState::RolledBack;
|
||||||
m_conn->active_transaction = false;
|
m_conn->active_transaction = false;
|
||||||
|
m_conn->active_transaction_id = 0;
|
||||||
}
|
}
|
||||||
return Void::Result::fail(make_sqlite_error(
|
return Void::Result::fail(make_sqlite_error(
|
||||||
map_sqlite_rc(fault.fail_next_commit_rc),
|
map_sqlite_rc(fault.fail_next_commit_rc),
|
||||||
@@ -1325,6 +1467,7 @@ namespace Void::Sqlite
|
|||||||
if (rc == SQLITE_OK) {
|
if (rc == SQLITE_OK) {
|
||||||
m_state = TransactionState::Committed;
|
m_state = TransactionState::Committed;
|
||||||
m_conn->active_transaction = false;
|
m_conn->active_transaction = false;
|
||||||
|
m_conn->active_transaction_id = 0;
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1338,23 +1481,39 @@ namespace Void::Sqlite
|
|||||||
if (sqlite3_get_autocommit(m_conn->db) == 0) {
|
if (sqlite3_get_autocommit(m_conn->db) == 0) {
|
||||||
m_state = TransactionState::Active;
|
m_state = TransactionState::Active;
|
||||||
m_conn->active_transaction = true;
|
m_conn->active_transaction = true;
|
||||||
} else {
|
m_conn->active_transaction_id = m_id;
|
||||||
m_state = TransactionState::RolledBack;
|
return Void::Result::fail(make_sqlite_error(
|
||||||
m_conn->active_transaction = false;
|
map_sqlite_rc(rc),
|
||||||
|
std::format("Sqlite: commit: {}", msg),
|
||||||
|
rc,
|
||||||
|
ext));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
m_conn->active_transaction = false;
|
||||||
|
m_conn->active_transaction_id = 0;
|
||||||
|
const bool unknown = commit_outcome_unknown(rc, m_conn->caps.journal_mode);
|
||||||
|
m_state = unknown ? TransactionState::Unknown : TransactionState::RolledBack;
|
||||||
return Void::Result::fail(make_sqlite_error(
|
return Void::Result::fail(make_sqlite_error(
|
||||||
map_sqlite_rc(rc),
|
map_sqlite_rc(rc),
|
||||||
std::format("Sqlite: commit: {}", msg),
|
unknown
|
||||||
|
? std::format("Sqlite: commit outcome unknown after WAL I/O error; "
|
||||||
|
"inspect the database: {}", msg)
|
||||||
|
: std::format("Sqlite: commit: {}", msg),
|
||||||
rc,
|
rc,
|
||||||
ext));
|
ext));
|
||||||
}
|
}
|
||||||
|
|
||||||
Result<void> Transaction::rollback_checked()
|
Result<void> Transaction::rollback_checked()
|
||||||
{
|
{
|
||||||
|
refresh_state();
|
||||||
if (m_state == TransactionState::RolledBack) {
|
if (m_state == TransactionState::RolledBack) {
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
if (m_state == TransactionState::Unknown) {
|
||||||
|
return Void::Result::fail(make_sqlite_error(
|
||||||
|
SqliteErrorCode::recovery_required,
|
||||||
|
"Sqlite: rollback after an unknown commit outcome; inspect the database"));
|
||||||
|
}
|
||||||
if (m_state != TransactionState::Active) {
|
if (m_state != TransactionState::Active) {
|
||||||
return Void::Result::fail(make_sqlite_error(
|
return Void::Result::fail(make_sqlite_error(
|
||||||
SqliteErrorCode::misuse,
|
SqliteErrorCode::misuse,
|
||||||
@@ -1375,6 +1534,7 @@ namespace Void::Sqlite
|
|||||||
if (rc == SQLITE_OK || sqlite3_get_autocommit(m_conn->db) != 0) {
|
if (rc == SQLITE_OK || sqlite3_get_autocommit(m_conn->db) != 0) {
|
||||||
m_state = TransactionState::RolledBack;
|
m_state = TransactionState::RolledBack;
|
||||||
m_conn->active_transaction = false;
|
m_conn->active_transaction = false;
|
||||||
|
m_conn->active_transaction_id = 0;
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1547,6 +1707,10 @@ namespace Void::Sqlite
|
|||||||
state->caps.in_memory = is_memory_path(path);
|
state->caps.in_memory = is_memory_path(path);
|
||||||
state->caps.read_only = (state->options.mode == OpenMode::ReadOnly) ||
|
state->caps.read_only = (state->options.mode == OpenMode::ReadOnly) ||
|
||||||
(sqlite3_db_readonly(raw_db, "main") > 0);
|
(sqlite3_db_readonly(raw_db, "main") > 0);
|
||||||
|
if (auto page_size = query_single_int_pragma(raw_db, "PRAGMA page_size");
|
||||||
|
page_size && *page_size > 0) {
|
||||||
|
state->page_size = *page_size;
|
||||||
|
}
|
||||||
|
|
||||||
// Disable extension loading by default.
|
// Disable extension loading by default.
|
||||||
int ext_enabled = 0;
|
int ext_enabled = 0;
|
||||||
@@ -1575,6 +1739,7 @@ namespace Void::Sqlite
|
|||||||
const auto busy_ms = state->options.limits.busy_timeout.count();
|
const auto busy_ms = state->options.limits.busy_timeout.count();
|
||||||
const int clamped_busy = busy_ms > INT_MAX ? INT_MAX : static_cast<int>(busy_ms);
|
const int clamped_busy = busy_ms > INT_MAX ? INT_MAX : static_cast<int>(busy_ms);
|
||||||
const int busy_rc = sqlite3_busy_timeout(raw_db, clamped_busy);
|
const int busy_rc = sqlite3_busy_timeout(raw_db, clamped_busy);
|
||||||
|
state->busy_timeout = std::chrono::milliseconds{clamped_busy};
|
||||||
if (busy_rc != SQLITE_OK) {
|
if (busy_rc != SQLITE_OK) {
|
||||||
return Void::Result::fail(sqlite_error_from_db(raw_db, busy_rc, "busy_timeout"));
|
return Void::Result::fail(sqlite_error_from_db(raw_db, busy_rc, "busy_timeout"));
|
||||||
}
|
}
|
||||||
@@ -1675,7 +1840,9 @@ namespace Void::Sqlite
|
|||||||
SqliteErrorCode::invalid_argument, "Sqlite: SQL contains embedded NUL byte"));
|
SqliteErrorCode::invalid_argument, "Sqlite: SQL contains embedded NUL byte"));
|
||||||
}
|
}
|
||||||
const std::string s{sql};
|
const std::string s{sql};
|
||||||
return exec_raw_sql(m_conn->db, s, "exec");
|
auto result = exec_raw_sql(m_conn->db, s, "exec");
|
||||||
|
m_conn->observe_autocommit_transition();
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
Result<Statement> Database::prepare(std::string_view sql)
|
Result<Statement> Database::prepare(std::string_view sql)
|
||||||
@@ -1753,12 +1920,16 @@ namespace Void::Sqlite
|
|||||||
SqliteErrorCode::misuse,
|
SqliteErrorCode::misuse,
|
||||||
"Sqlite: nested begin() rejected; use savepoint() for nested scopes"));
|
"Sqlite: nested begin() rejected; use savepoint() for nested scopes"));
|
||||||
}
|
}
|
||||||
if (mode != BeginMode::Deferred &&
|
if (mode != BeginMode::Deferred) {
|
||||||
m_conn->current_wal_size_bytes() >=
|
const auto wal = m_conn->wal_usage(
|
||||||
|
m_conn->options.limits.wal_stop_writes_threshold_bytes);
|
||||||
|
if (wal.uncheckpointed_bytes >=
|
||||||
m_conn->options.limits.wal_stop_writes_threshold_bytes) {
|
m_conn->options.limits.wal_stop_writes_threshold_bytes) {
|
||||||
return Void::Result::fail(make_sqlite_error(
|
return Void::Result::fail(make_sqlite_error(
|
||||||
SqliteErrorCode::overloaded,
|
SqliteErrorCode::overloaded,
|
||||||
"Sqlite: WAL size reached write-admission stop threshold; checkpoint required"));
|
"Sqlite: un-checkpointed WAL frames reached write-admission stop "
|
||||||
|
"threshold; checkpoint required"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const char* sql = "BEGIN";
|
const char* sql = "BEGIN";
|
||||||
@@ -1771,7 +1942,11 @@ namespace Void::Sqlite
|
|||||||
return Void::Result::fail(std::move(r).error());
|
return Void::Result::fail(std::move(r).error());
|
||||||
}
|
}
|
||||||
m_conn->active_transaction = true;
|
m_conn->active_transaction = true;
|
||||||
return Transaction{m_conn};
|
m_conn->active_transaction_id = ++m_conn->next_transaction_id;
|
||||||
|
if (m_conn->active_transaction_id == 0) {
|
||||||
|
m_conn->active_transaction_id = ++m_conn->next_transaction_id;
|
||||||
|
}
|
||||||
|
return Transaction{m_conn, m_conn->active_transaction_id};
|
||||||
}
|
}
|
||||||
|
|
||||||
Result<Savepoint> Database::savepoint(std::string_view name)
|
Result<Savepoint> Database::savepoint(std::string_view name)
|
||||||
@@ -1845,6 +2020,79 @@ namespace Void::Sqlite
|
|||||||
return rows;
|
return rows;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
BusyTimeoutOverride::BusyTimeoutOverride(
|
||||||
|
std::shared_ptr<detail::ConnectionState> conn,
|
||||||
|
std::chrono::milliseconds previous) noexcept
|
||||||
|
: m_conn{std::move(conn)}
|
||||||
|
, m_previous{previous}
|
||||||
|
, m_active{true}
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
BusyTimeoutOverride::~BusyTimeoutOverride()
|
||||||
|
{
|
||||||
|
restore();
|
||||||
|
}
|
||||||
|
|
||||||
|
BusyTimeoutOverride::BusyTimeoutOverride(BusyTimeoutOverride&& other) noexcept
|
||||||
|
: m_conn{std::move(other.m_conn)}
|
||||||
|
, m_previous{other.m_previous}
|
||||||
|
, m_active{other.m_active}
|
||||||
|
{
|
||||||
|
other.m_active = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
BusyTimeoutOverride&
|
||||||
|
BusyTimeoutOverride::operator=(BusyTimeoutOverride&& other) noexcept
|
||||||
|
{
|
||||||
|
if (this != &other) {
|
||||||
|
restore();
|
||||||
|
m_conn = std::move(other.m_conn);
|
||||||
|
m_previous = other.m_previous;
|
||||||
|
m_active = other.m_active;
|
||||||
|
other.m_active = false;
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
void BusyTimeoutOverride::restore() noexcept
|
||||||
|
{
|
||||||
|
if (!m_active) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
m_active = false;
|
||||||
|
if (!m_conn || m_conn->db == nullptr || m_conn->closed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const int clamped = static_cast<int>(std::clamp<std::int64_t>(
|
||||||
|
m_previous.count(), 0, std::numeric_limits<int>::max()));
|
||||||
|
(void)sqlite3_busy_timeout(m_conn->db, clamped);
|
||||||
|
m_conn->busy_timeout = std::chrono::milliseconds{clamped};
|
||||||
|
}
|
||||||
|
|
||||||
|
Result<BusyTimeoutOverride>
|
||||||
|
Database::override_busy_timeout(std::chrono::milliseconds timeout)
|
||||||
|
{
|
||||||
|
if (timeout.count() < 0) {
|
||||||
|
return Void::Result::fail(make_sqlite_error(
|
||||||
|
SqliteErrorCode::invalid_argument,
|
||||||
|
"Sqlite: busy timeout must be non-negative"));
|
||||||
|
}
|
||||||
|
if (!m_conn || m_conn->db == nullptr || m_conn->closed) {
|
||||||
|
return Void::Result::fail(make_sqlite_error(
|
||||||
|
SqliteErrorCode::closed, "Sqlite: database is closed"));
|
||||||
|
}
|
||||||
|
const int clamped = static_cast<int>(std::clamp<std::int64_t>(
|
||||||
|
timeout.count(), 0, std::numeric_limits<int>::max()));
|
||||||
|
if (sqlite3_busy_timeout(m_conn->db, clamped) != SQLITE_OK) {
|
||||||
|
return Void::Result::fail(
|
||||||
|
sqlite_error_from_db(m_conn->db, SQLITE_ERROR, "busy_timeout"));
|
||||||
|
}
|
||||||
|
const auto previous = m_conn->busy_timeout;
|
||||||
|
m_conn->busy_timeout = std::chrono::milliseconds{clamped};
|
||||||
|
return BusyTimeoutOverride{m_conn, previous};
|
||||||
|
}
|
||||||
|
|
||||||
Result<void> Database::close()
|
Result<void> Database::close()
|
||||||
{
|
{
|
||||||
if (!m_conn || m_conn->db == nullptr || m_conn->closed) {
|
if (!m_conn || m_conn->db == nullptr || m_conn->closed) {
|
||||||
@@ -1912,16 +2160,29 @@ namespace Void::Sqlite
|
|||||||
{
|
{
|
||||||
ConnectionHealth out;
|
ConnectionHealth out;
|
||||||
if (!m_conn) return out;
|
if (!m_conn) return out;
|
||||||
|
m_conn->observe_autocommit_transition();
|
||||||
out.live_statements = m_conn->live_statements;
|
out.live_statements = m_conn->live_statements;
|
||||||
out.active_transaction = m_conn->active_transaction;
|
out.active_transaction = m_conn->active_transaction;
|
||||||
out.open_savepoints = m_conn->open_savepoints;
|
out.open_savepoints = m_conn->open_savepoints;
|
||||||
out.wal_size_bytes = m_conn->current_wal_size_bytes();
|
const auto wal = m_conn->wal_usage(
|
||||||
|
m_conn->options.limits.wal_checkpoint_threshold_bytes);
|
||||||
|
out.wal_size_bytes = wal.size_bytes;
|
||||||
|
out.wal_frames_known = wal.frames_known;
|
||||||
|
out.wal_log_frames = std::max(0, wal.log_frames);
|
||||||
|
out.wal_checkpointed_frames = std::max(0, wal.checkpointed_frames);
|
||||||
|
out.wal_uncheckpointed_frames =
|
||||||
|
wal.frames_known
|
||||||
|
? std::max(0, wal.log_frames - wal.checkpointed_frames)
|
||||||
|
: 0;
|
||||||
|
out.wal_uncheckpointed_bytes = wal.uncheckpointed_bytes;
|
||||||
out.wal_checkpoint_recommended =
|
out.wal_checkpoint_recommended =
|
||||||
out.wal_size_bytes >= m_conn->options.limits.wal_checkpoint_threshold_bytes;
|
wal.uncheckpointed_bytes >=
|
||||||
|
m_conn->options.limits.wal_checkpoint_threshold_bytes;
|
||||||
out.wal_warn_exceeded =
|
out.wal_warn_exceeded =
|
||||||
out.wal_size_bytes >= m_conn->options.limits.wal_warn_threshold_bytes;
|
wal.uncheckpointed_bytes >= m_conn->options.limits.wal_warn_threshold_bytes;
|
||||||
out.wal_write_admission_blocked =
|
out.wal_write_admission_blocked =
|
||||||
out.wal_size_bytes >= m_conn->options.limits.wal_stop_writes_threshold_bytes;
|
wal.uncheckpointed_bytes >=
|
||||||
|
m_conn->options.limits.wal_stop_writes_threshold_bytes;
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2212,6 +2473,8 @@ namespace Void::Sqlite
|
|||||||
CheckpointReport rep;
|
CheckpointReport rep;
|
||||||
rep.log_frames = std::max(0, log_frames);
|
rep.log_frames = std::max(0, log_frames);
|
||||||
rep.checkpointed_frames = std::max(0, ckpt_frames);
|
rep.checkpointed_frames = std::max(0, ckpt_frames);
|
||||||
|
rep.uncheckpointed_frames =
|
||||||
|
std::max(0, rep.log_frames - rep.checkpointed_frames);
|
||||||
rep.busy = (rc == SQLITE_BUSY) || (rep.log_frames > rep.checkpointed_frames);
|
rep.busy = (rc == SQLITE_BUSY) || (rep.log_frames > rep.checkpointed_frames);
|
||||||
rep.wal_size_bytes = m_conn->current_wal_size_bytes();
|
rep.wal_size_bytes = m_conn->current_wal_size_bytes();
|
||||||
return rep;
|
return rep;
|
||||||
|
|||||||
+576
-134
@@ -20,139 +20,7 @@
|
|||||||
#include <utility>
|
#include <utility>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
#ifdef _WIN32
|
#ifndef _WIN32
|
||||||
|
|
||||||
namespace Void::Process
|
|
||||||
{
|
|
||||||
|
|
||||||
Child::Child(long long,
|
|
||||||
long long,
|
|
||||||
bool,
|
|
||||||
Void::System::OwnedFd,
|
|
||||||
Void::System::OwnedFd,
|
|
||||||
Void::System::OwnedFd,
|
|
||||||
std::chrono::milliseconds) noexcept
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
Child::~Child() noexcept = default;
|
|
||||||
Child::Child(Child&&) noexcept = default;
|
|
||||||
Child& Child::operator=(Child&&) noexcept = default;
|
|
||||||
bool Child::valid() const noexcept { return false; }
|
|
||||||
bool Child::running() const noexcept { return false; }
|
|
||||||
bool Child::process_group_alive() const noexcept { return false; }
|
|
||||||
long long Child::pid() const noexcept { return -1; }
|
|
||||||
long long Child::pgid() const noexcept { return -1; }
|
|
||||||
bool Child::owns_process_group() const noexcept { return false; }
|
|
||||||
int Child::stdin_fd() const noexcept { return -1; }
|
|
||||||
int Child::stdout_fd() const noexcept { return -1; }
|
|
||||||
int Child::stderr_fd() const noexcept { return -1; }
|
|
||||||
Void::System::OwnedFd Child::take_stdin_fd() noexcept { return {}; }
|
|
||||||
Void::System::OwnedFd Child::take_stdout_fd() noexcept { return {}; }
|
|
||||||
Void::System::OwnedFd Child::take_stderr_fd() noexcept { return {}; }
|
|
||||||
void Child::close_stdin() noexcept {}
|
|
||||||
|
|
||||||
Void::Result::Result<void, Void::Result::Error> Child::send_signal(int) noexcept
|
|
||||||
{
|
|
||||||
return std::unexpected{Void::System::make_system_error(
|
|
||||||
Void::System::SystemErrorCode::unsupported,
|
|
||||||
"Process::Child::send_signal: not implemented on Windows")};
|
|
||||||
}
|
|
||||||
|
|
||||||
Void::Result::Result<ExitStatus, Void::Result::Error>
|
|
||||||
Child::terminate(std::chrono::milliseconds)
|
|
||||||
{
|
|
||||||
return std::unexpected{Void::System::make_system_error(
|
|
||||||
Void::System::SystemErrorCode::unsupported,
|
|
||||||
"Process::Child::terminate: not implemented on Windows")};
|
|
||||||
}
|
|
||||||
|
|
||||||
Void::Result::Result<std::optional<ExitStatus>, Void::Result::Error>
|
|
||||||
Child::try_wait()
|
|
||||||
{
|
|
||||||
return std::unexpected{Void::System::make_system_error(
|
|
||||||
Void::System::SystemErrorCode::unsupported,
|
|
||||||
"Process::Child::try_wait: not implemented on Windows")};
|
|
||||||
}
|
|
||||||
|
|
||||||
Void::Result::Result<ExitStatus, Void::Result::Error>
|
|
||||||
Child::wait_blocking(std::chrono::milliseconds,
|
|
||||||
std::stop_token,
|
|
||||||
std::chrono::milliseconds)
|
|
||||||
{
|
|
||||||
return std::unexpected{Void::System::make_system_error(
|
|
||||||
Void::System::SystemErrorCode::unsupported,
|
|
||||||
"Process::Child::wait_blocking: not implemented on Windows")};
|
|
||||||
}
|
|
||||||
|
|
||||||
Void::Result::Result<Child, Void::Result::Error> spawn(const SpawnOptions&)
|
|
||||||
{
|
|
||||||
return std::unexpected{Void::System::make_system_error(
|
|
||||||
Void::System::SystemErrorCode::unsupported,
|
|
||||||
"Process::spawn: not implemented on Windows")};
|
|
||||||
}
|
|
||||||
|
|
||||||
Void::Result::Result<CommunicateResult, Void::Result::Error>
|
|
||||||
communicate_blocking(Child&,
|
|
||||||
std::string_view,
|
|
||||||
CaptureLimits,
|
|
||||||
std::chrono::milliseconds,
|
|
||||||
std::stop_token,
|
|
||||||
const StreamCallbacks*)
|
|
||||||
{
|
|
||||||
return std::unexpected{Void::System::make_system_error(
|
|
||||||
Void::System::SystemErrorCode::unsupported,
|
|
||||||
"Process::communicate_blocking: not implemented on Windows")};
|
|
||||||
}
|
|
||||||
|
|
||||||
Void::Result::Result<Output, Void::Result::Error> run(
|
|
||||||
const std::filesystem::path&,
|
|
||||||
std::vector<std::string>,
|
|
||||||
std::string_view,
|
|
||||||
std::chrono::milliseconds)
|
|
||||||
{
|
|
||||||
return Void::Result::fail("Process::run: not implemented on Windows");
|
|
||||||
}
|
|
||||||
|
|
||||||
Void::Result::Result<Output, Void::Result::Error> run_streaming(
|
|
||||||
const std::filesystem::path&,
|
|
||||||
std::vector<std::string>,
|
|
||||||
const StreamCallbacks&,
|
|
||||||
std::string_view,
|
|
||||||
std::chrono::milliseconds)
|
|
||||||
{
|
|
||||||
return Void::Result::fail(
|
|
||||||
"Process::run_streaming: not implemented on Windows");
|
|
||||||
}
|
|
||||||
|
|
||||||
Void::Result::Result<Output, Void::Result::Error>
|
|
||||||
shell(std::string_view, std::chrono::milliseconds)
|
|
||||||
{
|
|
||||||
return Void::Result::fail("Process::shell: not implemented on Windows");
|
|
||||||
}
|
|
||||||
|
|
||||||
Void::Result::Result<void, Void::Result::Error>
|
|
||||||
reexec(const std::filesystem::path&, const std::vector<std::string>&)
|
|
||||||
{
|
|
||||||
return Void::Result::fail("Process::reexec: not implemented on Windows");
|
|
||||||
}
|
|
||||||
|
|
||||||
Void::Result::Result<void, Void::Result::Error> reexec(
|
|
||||||
const std::filesystem::path&, const std::vector<std::string>&, bool)
|
|
||||||
{
|
|
||||||
return Void::Result::fail("Process::reexec: not implemented on Windows");
|
|
||||||
}
|
|
||||||
|
|
||||||
Void::Result::Result<void, Void::Result::Error> enable_subreaper() noexcept
|
|
||||||
{
|
|
||||||
return std::unexpected{Void::System::make_system_error(
|
|
||||||
Void::System::SystemErrorCode::unsupported,
|
|
||||||
"Process::enable_subreaper: not supported on Windows")};
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Void::Process
|
|
||||||
|
|
||||||
#else // POSIX
|
|
||||||
|
|
||||||
#include <dirent.h>
|
#include <dirent.h>
|
||||||
#include <fcntl.h>
|
#include <fcntl.h>
|
||||||
@@ -740,6 +608,8 @@ void emit_lines_from_offset(const std::string& buf,
|
|||||||
|
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
|
Child::Child() noexcept = default;
|
||||||
|
|
||||||
Child::Child(long long pid,
|
Child::Child(long long pid,
|
||||||
long long pgid,
|
long long pgid,
|
||||||
bool owns_process_group,
|
bool owns_process_group,
|
||||||
@@ -1327,6 +1197,578 @@ Void::Result::Result<Child, Void::Result::Error>
|
|||||||
options.kill_grace};
|
options.kill_grace};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
BinarySession::BinarySession(Child child, BinarySessionOptions options)
|
||||||
|
: child_(std::move(child)),
|
||||||
|
stdin_(child_.take_stdin_fd()),
|
||||||
|
stdout_(child_.take_stdout_fd()),
|
||||||
|
stderr_(child_.take_stderr_fd()),
|
||||||
|
stdout_eof_(!stdout_.valid()),
|
||||||
|
stderr_eof_(!stderr_.valid()),
|
||||||
|
stdin_closed_(!stdin_.valid()),
|
||||||
|
options_(options)
|
||||||
|
{
|
||||||
|
options_.max_stdout_buffer = std::max<std::size_t>(1, options_.max_stdout_buffer);
|
||||||
|
options_.max_stderr_buffer = std::max<std::size_t>(1, options_.max_stderr_buffer);
|
||||||
|
if (stdin_.valid()) {
|
||||||
|
(void)set_nonblock(stdin_.get());
|
||||||
|
}
|
||||||
|
if (stdout_.valid()) {
|
||||||
|
(void)set_nonblock(stdout_.get());
|
||||||
|
}
|
||||||
|
if (stderr_.valid()) {
|
||||||
|
(void)set_nonblock(stderr_.get());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
BinarySession::~BinarySession() noexcept = default;
|
||||||
|
|
||||||
|
BinarySession::BinarySession(BinarySession&& other) noexcept
|
||||||
|
: child_(std::move(other.child_)),
|
||||||
|
stdin_(std::move(other.stdin_)),
|
||||||
|
stdout_(std::move(other.stdout_)),
|
||||||
|
stderr_(std::move(other.stderr_)),
|
||||||
|
stdout_buffer_(std::move(other.stdout_buffer_)),
|
||||||
|
stdout_offset_(std::exchange(other.stdout_offset_, 0)),
|
||||||
|
stderr_buffer_(std::move(other.stderr_buffer_)),
|
||||||
|
stderr_offset_(std::exchange(other.stderr_offset_, 0)),
|
||||||
|
stdout_eof_(other.stdout_eof_),
|
||||||
|
stderr_eof_(other.stderr_eof_),
|
||||||
|
stdin_closed_(other.stdin_closed_),
|
||||||
|
stdout_truncated_(other.stdout_truncated_),
|
||||||
|
stderr_truncated_(other.stderr_truncated_),
|
||||||
|
options_(other.options_),
|
||||||
|
cancelled_(other.cancelled_.exchange(false)),
|
||||||
|
status_(other.status_),
|
||||||
|
reaped_(other.reaped_)
|
||||||
|
{
|
||||||
|
other.stdout_eof_ = true;
|
||||||
|
other.stderr_eof_ = true;
|
||||||
|
other.stdin_closed_ = true;
|
||||||
|
other.reaped_ = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
BinarySession& BinarySession::operator=(BinarySession&& other) noexcept
|
||||||
|
{
|
||||||
|
if (this != &other) {
|
||||||
|
child_ = std::move(other.child_);
|
||||||
|
stdin_ = std::move(other.stdin_);
|
||||||
|
stdout_ = std::move(other.stdout_);
|
||||||
|
stderr_ = std::move(other.stderr_);
|
||||||
|
stdout_buffer_ = std::move(other.stdout_buffer_);
|
||||||
|
stdout_offset_ = std::exchange(other.stdout_offset_, 0);
|
||||||
|
stderr_buffer_ = std::move(other.stderr_buffer_);
|
||||||
|
stderr_offset_ = std::exchange(other.stderr_offset_, 0);
|
||||||
|
stdout_eof_ = other.stdout_eof_;
|
||||||
|
stderr_eof_ = other.stderr_eof_;
|
||||||
|
stdin_closed_ = other.stdin_closed_;
|
||||||
|
stdout_truncated_ = other.stdout_truncated_;
|
||||||
|
stderr_truncated_ = other.stderr_truncated_;
|
||||||
|
options_ = other.options_;
|
||||||
|
cancelled_.store(other.cancelled_.exchange(false));
|
||||||
|
status_ = other.status_;
|
||||||
|
reaped_ = other.reaped_;
|
||||||
|
other.stdout_eof_ = true;
|
||||||
|
other.stderr_eof_ = true;
|
||||||
|
other.stdin_closed_ = true;
|
||||||
|
other.reaped_ = true;
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<BinarySession, Void::Result::Error>
|
||||||
|
BinarySession::spawn(const SpawnOptions& options, BinarySessionOptions session_options)
|
||||||
|
{
|
||||||
|
auto spawned = Process::spawn(options);
|
||||||
|
if (!spawned.has_value()) {
|
||||||
|
return std::unexpected{std::move(spawned.error())};
|
||||||
|
}
|
||||||
|
return BinarySession{std::move(*spawned), session_options};
|
||||||
|
}
|
||||||
|
|
||||||
|
bool BinarySession::valid() const noexcept { return child_.valid(); }
|
||||||
|
|
||||||
|
BinarySession::PollFill BinarySession::poll_fill(
|
||||||
|
int timeout_ms,
|
||||||
|
std::span<const std::byte> stdin_data,
|
||||||
|
std::size_t& stdin_written,
|
||||||
|
bool discard_on_full)
|
||||||
|
{
|
||||||
|
PollFill result;
|
||||||
|
|
||||||
|
std::array<struct pollfd, 3> pfds{};
|
||||||
|
nfds_t nfds = 0;
|
||||||
|
int stdin_index = -1;
|
||||||
|
int stdout_index = -1;
|
||||||
|
int stderr_index = -1;
|
||||||
|
|
||||||
|
if (!stdin_data.empty() && stdin_written < stdin_data.size() &&
|
||||||
|
!stdin_closed_ && stdin_.valid()) {
|
||||||
|
stdin_index = static_cast<int>(nfds);
|
||||||
|
pfds[nfds++] = {stdin_.get(), POLLOUT, 0};
|
||||||
|
}
|
||||||
|
const std::size_t stdout_used = stdout_buffer_.size() - stdout_offset_;
|
||||||
|
if (!stdout_eof_ && stdout_.valid() &&
|
||||||
|
(discard_on_full || stdout_used < options_.max_stdout_buffer)) {
|
||||||
|
stdout_index = static_cast<int>(nfds);
|
||||||
|
pfds[nfds++] = {stdout_.get(), POLLIN, 0};
|
||||||
|
}
|
||||||
|
const std::size_t stderr_used = stderr_buffer_.size() - stderr_offset_;
|
||||||
|
if (!stderr_eof_ && stderr_.valid() &&
|
||||||
|
(discard_on_full || stderr_used < options_.max_stderr_buffer)) {
|
||||||
|
stderr_index = static_cast<int>(nfds);
|
||||||
|
pfds[nfds++] = {stderr_.get(), POLLIN, 0};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nfds == 0) {
|
||||||
|
result.idle = true;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
const int rc = ::poll(pfds.data(), nfds, timeout_ms);
|
||||||
|
if (rc < 0) {
|
||||||
|
if (errno == EINTR) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
const int err = errno;
|
||||||
|
result.failure = BinaryFailureCode::io_error;
|
||||||
|
result.error = Void::System::make_system_error(
|
||||||
|
Void::System::map_errno_to_system_code(err),
|
||||||
|
"Process::BinarySession: poll failed",
|
||||||
|
err);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
if (rc == 0) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stdin_index >= 0) {
|
||||||
|
const short revents = pfds[static_cast<std::size_t>(stdin_index)].revents;
|
||||||
|
if ((revents & POLLOUT) != 0) {
|
||||||
|
while (stdin_written < stdin_data.size()) {
|
||||||
|
int write_err = 0;
|
||||||
|
const ssize_t n = write_pipe_nosigpipe(stdin_.get(),
|
||||||
|
stdin_data.data() + stdin_written,
|
||||||
|
stdin_data.size() - stdin_written,
|
||||||
|
write_err);
|
||||||
|
if (n > 0) {
|
||||||
|
stdin_written += static_cast<std::size_t>(n);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (n == 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (n < 0 && (write_err == EAGAIN || write_err == EWOULDBLOCK)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
stdin_closed_ = true;
|
||||||
|
stdin_.reset();
|
||||||
|
result.stdin_broken = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!result.stdin_broken &&
|
||||||
|
(revents & (POLLERR | POLLHUP | POLLNVAL)) != 0 &&
|
||||||
|
(revents & POLLOUT) == 0) {
|
||||||
|
stdin_closed_ = true;
|
||||||
|
stdin_.reset();
|
||||||
|
result.stdin_broken = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::array<std::byte, 8192> chunk{};
|
||||||
|
auto service_read = [&](int index,
|
||||||
|
int fd,
|
||||||
|
std::vector<std::byte>& buffer,
|
||||||
|
std::size_t& offset,
|
||||||
|
bool& eof,
|
||||||
|
bool& truncated,
|
||||||
|
std::size_t cap) {
|
||||||
|
if (index < 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const short revents = pfds[static_cast<std::size_t>(index)].revents;
|
||||||
|
if ((revents & (POLLIN | POLLHUP | POLLERR | POLLNVAL)) == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (;;) {
|
||||||
|
const std::size_t used = buffer.size() - offset;
|
||||||
|
const std::size_t space = (cap > used) ? (cap - used) : 0;
|
||||||
|
if (space == 0 && !discard_on_full) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const std::size_t want =
|
||||||
|
discard_on_full ? chunk.size() : std::min(chunk.size(), space);
|
||||||
|
if (want == 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const ssize_t n = ::read(fd, chunk.data(), want);
|
||||||
|
if (n > 0) {
|
||||||
|
if (offset > 0 && offset == buffer.size()) {
|
||||||
|
buffer.clear();
|
||||||
|
offset = 0;
|
||||||
|
}
|
||||||
|
std::size_t take = static_cast<std::size_t>(n);
|
||||||
|
if (take > space) {
|
||||||
|
take = space;
|
||||||
|
truncated = true;
|
||||||
|
}
|
||||||
|
buffer.insert(buffer.end(), chunk.begin(), chunk.begin() + take);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (n == 0) {
|
||||||
|
eof = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (errno == EAGAIN || errno == EWOULDBLOCK) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const int err = errno;
|
||||||
|
eof = true;
|
||||||
|
result.failure = BinaryFailureCode::io_error;
|
||||||
|
result.error = Void::System::make_system_error(
|
||||||
|
Void::System::map_errno_to_system_code(err),
|
||||||
|
"Process::BinarySession: read failed",
|
||||||
|
err);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if ((revents & (POLLHUP | POLLERR | POLLNVAL)) != 0 && !eof) {
|
||||||
|
eof = true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
service_read(stdout_index,
|
||||||
|
stdout_.get(),
|
||||||
|
stdout_buffer_,
|
||||||
|
stdout_offset_,
|
||||||
|
stdout_eof_,
|
||||||
|
stdout_truncated_,
|
||||||
|
options_.max_stdout_buffer);
|
||||||
|
service_read(stderr_index,
|
||||||
|
stderr_.get(),
|
||||||
|
stderr_buffer_,
|
||||||
|
stderr_offset_,
|
||||||
|
stderr_eof_,
|
||||||
|
stderr_truncated_,
|
||||||
|
options_.max_stderr_buffer);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::write_stdin(
|
||||||
|
std::span<const std::byte> data,
|
||||||
|
std::chrono::milliseconds timeout,
|
||||||
|
std::stop_token stop)
|
||||||
|
{
|
||||||
|
if (!valid()) {
|
||||||
|
return std::unexpected{BinaryError{
|
||||||
|
0,
|
||||||
|
false,
|
||||||
|
BinaryFailureCode::closed,
|
||||||
|
Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"Process::BinarySession::write_stdin: invalid session")}};
|
||||||
|
}
|
||||||
|
BinaryTransfer transfer;
|
||||||
|
if (data.empty()) {
|
||||||
|
return transfer;
|
||||||
|
}
|
||||||
|
if (stdin_closed_ || !stdin_.valid()) {
|
||||||
|
return std::unexpected{BinaryError{
|
||||||
|
0,
|
||||||
|
false,
|
||||||
|
BinaryFailureCode::closed,
|
||||||
|
Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::busy,
|
||||||
|
"Process::BinarySession::write_stdin: stdin is closed")}};
|
||||||
|
}
|
||||||
|
|
||||||
|
const bool has_deadline = timeout.count() > 0;
|
||||||
|
const auto deadline = std::chrono::steady_clock::now() + timeout;
|
||||||
|
std::size_t written = 0;
|
||||||
|
|
||||||
|
while (written < data.size()) {
|
||||||
|
if (cancelled_.load(std::memory_order_acquire) || stop.stop_requested()) {
|
||||||
|
return std::unexpected{BinaryError{
|
||||||
|
written,
|
||||||
|
false,
|
||||||
|
BinaryFailureCode::cancelled,
|
||||||
|
Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::cancelled,
|
||||||
|
"Process::BinarySession::write_stdin: cancelled")}};
|
||||||
|
}
|
||||||
|
if (has_deadline && std::chrono::steady_clock::now() >= deadline) {
|
||||||
|
return std::unexpected{BinaryError{
|
||||||
|
written,
|
||||||
|
false,
|
||||||
|
BinaryFailureCode::timeout,
|
||||||
|
Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::timed_out,
|
||||||
|
"Process::BinarySession::write_stdin: timed out")}};
|
||||||
|
}
|
||||||
|
|
||||||
|
int poll_timeout_ms = -1;
|
||||||
|
if (has_deadline) {
|
||||||
|
const auto remaining =
|
||||||
|
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||||
|
deadline - std::chrono::steady_clock::now())
|
||||||
|
.count();
|
||||||
|
if (remaining <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
poll_timeout_ms =
|
||||||
|
static_cast<int>(std::min<long long>(remaining,
|
||||||
|
std::numeric_limits<int>::max()));
|
||||||
|
}
|
||||||
|
// Bound every wait so cancel() (which may come from another thread)
|
||||||
|
// and a stop request are observed promptly.
|
||||||
|
poll_timeout_ms =
|
||||||
|
(poll_timeout_ms < 0) ? 25 : std::min(poll_timeout_ms, 25);
|
||||||
|
|
||||||
|
auto filled = poll_fill(poll_timeout_ms, data, written, false);
|
||||||
|
if (filled.failure != BinaryFailureCode::none) {
|
||||||
|
return std::unexpected{BinaryError{
|
||||||
|
written, false, filled.failure, std::move(filled.error)}};
|
||||||
|
}
|
||||||
|
if (filled.stdin_broken) {
|
||||||
|
return std::unexpected{BinaryError{
|
||||||
|
written,
|
||||||
|
false,
|
||||||
|
BinaryFailureCode::closed,
|
||||||
|
Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::busy,
|
||||||
|
"Process::BinarySession::write_stdin: child closed stdin")}};
|
||||||
|
}
|
||||||
|
if (filled.idle) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
transfer.bytes = written;
|
||||||
|
return transfer;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::read_stdout(
|
||||||
|
std::span<std::byte> out,
|
||||||
|
std::chrono::milliseconds timeout,
|
||||||
|
std::stop_token stop)
|
||||||
|
{
|
||||||
|
return read_stream(true, out, timeout, stop);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::read_stderr(
|
||||||
|
std::span<std::byte> out,
|
||||||
|
std::chrono::milliseconds timeout,
|
||||||
|
std::stop_token stop)
|
||||||
|
{
|
||||||
|
return read_stream(false, out, timeout, stop);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::read_stream(
|
||||||
|
bool is_stdout,
|
||||||
|
std::span<std::byte> out,
|
||||||
|
std::chrono::milliseconds timeout,
|
||||||
|
std::stop_token stop)
|
||||||
|
{
|
||||||
|
if (!valid()) {
|
||||||
|
return std::unexpected{BinaryError{
|
||||||
|
0,
|
||||||
|
false,
|
||||||
|
BinaryFailureCode::closed,
|
||||||
|
Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"Process::BinarySession: invalid session")}};
|
||||||
|
}
|
||||||
|
BinaryTransfer transfer;
|
||||||
|
if (out.empty()) {
|
||||||
|
return transfer;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto& buffer = is_stdout ? stdout_buffer_ : stderr_buffer_;
|
||||||
|
auto& offset = is_stdout ? stdout_offset_ : stderr_offset_;
|
||||||
|
bool& eof = is_stdout ? stdout_eof_ : stderr_eof_;
|
||||||
|
bool& truncated = is_stdout ? stdout_truncated_ : stderr_truncated_;
|
||||||
|
|
||||||
|
const bool has_deadline = timeout.count() > 0;
|
||||||
|
const auto deadline = std::chrono::steady_clock::now() + timeout;
|
||||||
|
|
||||||
|
while ((buffer.size() - offset) == 0 && !eof) {
|
||||||
|
if (cancelled_.load(std::memory_order_acquire) || stop.stop_requested()) {
|
||||||
|
return std::unexpected{BinaryError{
|
||||||
|
0,
|
||||||
|
eof,
|
||||||
|
BinaryFailureCode::cancelled,
|
||||||
|
Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::cancelled,
|
||||||
|
"Process::BinarySession: read cancelled")}};
|
||||||
|
}
|
||||||
|
if (has_deadline && std::chrono::steady_clock::now() >= deadline) {
|
||||||
|
return std::unexpected{BinaryError{
|
||||||
|
0,
|
||||||
|
eof,
|
||||||
|
BinaryFailureCode::timeout,
|
||||||
|
Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::timed_out,
|
||||||
|
"Process::BinarySession: read timed out")}};
|
||||||
|
}
|
||||||
|
|
||||||
|
int poll_timeout_ms = -1;
|
||||||
|
if (has_deadline) {
|
||||||
|
const auto remaining =
|
||||||
|
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||||
|
deadline - std::chrono::steady_clock::now())
|
||||||
|
.count();
|
||||||
|
if (remaining <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
poll_timeout_ms =
|
||||||
|
static_cast<int>(std::min<long long>(remaining,
|
||||||
|
std::numeric_limits<int>::max()));
|
||||||
|
}
|
||||||
|
// Bound every wait so cancel() (which may come from another thread)
|
||||||
|
// and a stop request are observed promptly.
|
||||||
|
poll_timeout_ms =
|
||||||
|
(poll_timeout_ms < 0) ? 25 : std::min(poll_timeout_ms, 25);
|
||||||
|
|
||||||
|
std::span<const std::byte> no_stdin{};
|
||||||
|
std::size_t no_written = 0;
|
||||||
|
auto filled = poll_fill(poll_timeout_ms,
|
||||||
|
no_stdin,
|
||||||
|
no_written,
|
||||||
|
options_.truncate_output_on_overflow);
|
||||||
|
if (filled.failure != BinaryFailureCode::none) {
|
||||||
|
return std::unexpected{BinaryError{
|
||||||
|
0, eof, filled.failure, std::move(filled.error)}};
|
||||||
|
}
|
||||||
|
if (filled.idle) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::size_t used = buffer.size() - offset;
|
||||||
|
if (used > 0) {
|
||||||
|
const std::size_t take = std::min(used, out.size());
|
||||||
|
std::copy_n(buffer.begin() + static_cast<std::ptrdiff_t>(offset),
|
||||||
|
take,
|
||||||
|
out.begin());
|
||||||
|
offset += take;
|
||||||
|
transfer.bytes = take;
|
||||||
|
if (offset == buffer.size()) {
|
||||||
|
buffer.clear();
|
||||||
|
offset = 0;
|
||||||
|
} else if (offset >= 65536 && offset * 2 >= buffer.size()) {
|
||||||
|
buffer.erase(buffer.begin(),
|
||||||
|
buffer.begin() + static_cast<std::ptrdiff_t>(offset));
|
||||||
|
offset = 0;
|
||||||
|
}
|
||||||
|
} else if (eof) {
|
||||||
|
transfer.eof = true;
|
||||||
|
note_exit();
|
||||||
|
transfer.exited = reaped_;
|
||||||
|
transfer.status = status_;
|
||||||
|
}
|
||||||
|
transfer.truncated = truncated;
|
||||||
|
return transfer;
|
||||||
|
}
|
||||||
|
|
||||||
|
void BinarySession::note_exit() noexcept
|
||||||
|
{
|
||||||
|
if (reaped_ || !child_.valid()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
auto waited = child_.try_wait();
|
||||||
|
if (waited.has_value() && waited->has_value()) {
|
||||||
|
status_ = **waited;
|
||||||
|
reaped_ = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error> BinarySession::close_stdin()
|
||||||
|
{
|
||||||
|
if (stdin_closed_) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
stdin_closed_ = true;
|
||||||
|
return stdin_.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<ExitStatus, Void::Result::Error> BinarySession::wait(
|
||||||
|
std::chrono::milliseconds timeout,
|
||||||
|
std::stop_token stop)
|
||||||
|
{
|
||||||
|
if (!child_.valid()) {
|
||||||
|
return std::unexpected{Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"Process::BinarySession::wait: invalid session")};
|
||||||
|
}
|
||||||
|
if (reaped_) {
|
||||||
|
return status_;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bool has_deadline = timeout.count() > 0;
|
||||||
|
const auto deadline = std::chrono::steady_clock::now() + timeout;
|
||||||
|
|
||||||
|
for (;;) {
|
||||||
|
auto waited = child_.try_wait();
|
||||||
|
if (!waited.has_value()) {
|
||||||
|
return std::unexpected{std::move(waited.error())};
|
||||||
|
}
|
||||||
|
if (waited->has_value()) {
|
||||||
|
status_ = **waited;
|
||||||
|
reaped_ = true;
|
||||||
|
return status_;
|
||||||
|
}
|
||||||
|
if (cancelled_.load(std::memory_order_acquire) || stop.stop_requested()) {
|
||||||
|
return std::unexpected{Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::cancelled,
|
||||||
|
"Process::BinarySession::wait: cancelled")};
|
||||||
|
}
|
||||||
|
if (has_deadline && std::chrono::steady_clock::now() >= deadline) {
|
||||||
|
return std::unexpected{Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::timed_out,
|
||||||
|
"Process::BinarySession::wait: timed out")};
|
||||||
|
}
|
||||||
|
|
||||||
|
int poll_timeout_ms = 5;
|
||||||
|
if (has_deadline) {
|
||||||
|
const auto remaining =
|
||||||
|
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||||
|
deadline - std::chrono::steady_clock::now())
|
||||||
|
.count();
|
||||||
|
poll_timeout_ms = static_cast<int>(std::clamp<long long>(
|
||||||
|
remaining, 1, static_cast<long long>(poll_timeout_ms)));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::span<const std::byte> no_stdin{};
|
||||||
|
std::size_t no_written = 0;
|
||||||
|
auto filled = poll_fill(
|
||||||
|
poll_timeout_ms, no_stdin, no_written, options_.truncate_output_on_overflow);
|
||||||
|
if (filled.failure != BinaryFailureCode::none) {
|
||||||
|
return std::unexpected{std::move(filled.error)};
|
||||||
|
}
|
||||||
|
if (filled.idle) {
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds{1});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<ExitStatus, Void::Result::Error> BinarySession::terminate(
|
||||||
|
std::chrono::milliseconds grace)
|
||||||
|
{
|
||||||
|
if (!child_.valid()) {
|
||||||
|
return std::unexpected{Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"Process::BinarySession::terminate: invalid session")};
|
||||||
|
}
|
||||||
|
auto terminated = child_.terminate(grace);
|
||||||
|
if (terminated.has_value()) {
|
||||||
|
status_ = *terminated;
|
||||||
|
reaped_ = true;
|
||||||
|
}
|
||||||
|
return terminated;
|
||||||
|
}
|
||||||
|
|
||||||
Void::Result::Result<CommunicateResult, Void::Result::Error>
|
Void::Result::Result<CommunicateResult, Void::Result::Error>
|
||||||
communicate_blocking(Child& child,
|
communicate_blocking(Child& child,
|
||||||
std::string_view stdin_data,
|
std::string_view stdin_data,
|
||||||
@@ -1783,4 +2225,4 @@ Void::Result::Result<void, Void::Result::Error> enable_subreaper() noexcept
|
|||||||
|
|
||||||
} // namespace Void::Process
|
} // namespace Void::Process
|
||||||
|
|
||||||
#endif // _WIN32
|
#endif // !_WIN32
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -34,6 +34,7 @@ void handle_assertion(AssertionResult result)
|
|||||||
|
|
||||||
if (!passed) {
|
if (!passed) {
|
||||||
tr->state = TestState::Failed;
|
tr->state = TestState::Failed;
|
||||||
|
++tr->failed_assertions;
|
||||||
}
|
}
|
||||||
|
|
||||||
const std::size_t entry_bytes =
|
const std::size_t entry_bytes =
|
||||||
|
|||||||
@@ -8,14 +8,14 @@ namespace Void::Testing {
|
|||||||
using namespace Void::Testing::Detail::Color;
|
using namespace Void::Testing::Detail::Color;
|
||||||
|
|
||||||
void ConsoleReporter::on_run_start(const RunConfig&, int total_tests) {
|
void ConsoleReporter::on_run_start(const RunConfig&, int total_tests) {
|
||||||
os_ << "\n" << apply(bold_blue, "╭──────────────────────────────────────────────╮") << "\n"
|
os_ << "\n" << Void::Testing::Detail::Color::apply(bold_blue, "╭──────────────────────────────────────────────╮") << "\n"
|
||||||
<< apply(bold_blue, "│") << apply(bold_white, " Void Testing") << apply(dim, " v1.0") << std::string(31, ' ') << apply(bold_blue, "│") << "\n"
|
<< Void::Testing::Detail::Color::apply(bold_blue, "│") << Void::Testing::Detail::Color::apply(bold_white, " Void Testing") << Void::Testing::Detail::Color::apply(dim, " v1.0") << std::string(31, ' ') << Void::Testing::Detail::Color::apply(bold_blue, "│") << "\n"
|
||||||
<< std::format("{}│{} Discovered {} test{}{}│\n", apply(bold_blue, "╰"), apply(dim, ""), apply(bold_white, std::to_string(total_tests)), total_tests != 1 ? "s" : "", std::string(total_tests < 10 ? 33 : 28, ' '))
|
<< std::format("{}│{} Discovered {} test{}{}│\n", Void::Testing::Detail::Color::apply(bold_blue, "╰"), Void::Testing::Detail::Color::apply(dim, ""), Void::Testing::Detail::Color::apply(bold_white, std::to_string(total_tests)), total_tests != 1 ? "s" : "", std::string(total_tests < 10 ? 33 : 28, ' '))
|
||||||
<< apply(bold_blue, "╰──────────────────────────────────────────────╯") << "\n\n";
|
<< Void::Testing::Detail::Color::apply(bold_blue, "╰──────────────────────────────────────────────╯") << "\n\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
void ConsoleReporter::on_suite_start(const std::string& suite_name, int test_count) {
|
void ConsoleReporter::on_suite_start(const std::string& suite_name, int test_count) {
|
||||||
os_ << std::format(" {} {} [{} test{}]\n", apply(bold_blue, "◆"), apply(bold_white, suite_name), apply(dim, std::to_string(test_count)), test_count != 1 ? "s" : "");
|
os_ << std::format(" {} {} [{} test{}]\n", Void::Testing::Detail::Color::apply(bold_blue, "◆"), Void::Testing::Detail::Color::apply(bold_white, suite_name), Void::Testing::Detail::Color::apply(dim, std::to_string(test_count)), test_count != 1 ? "s" : "");
|
||||||
}
|
}
|
||||||
|
|
||||||
void ConsoleReporter::on_test_start(const TestCase&) {}
|
void ConsoleReporter::on_test_start(const TestCase&) {}
|
||||||
@@ -25,46 +25,46 @@ void ConsoleReporter::on_test_end(const TestResult& result) {
|
|||||||
double ms = std::chrono::duration<double, std::milli>(result.duration).count();
|
double ms = std::chrono::duration<double, std::milli>(result.duration).count();
|
||||||
std::string time_str = ms < 1.0 ? std::format("{:.3f}ms", ms) : std::format("{:.1f}ms", ms);
|
std::string time_str = ms < 1.0 ? std::format("{:.3f}ms", ms) : std::format("{:.1f}ms", ms);
|
||||||
std::string tags_str;
|
std::string tags_str;
|
||||||
if (!result.tags.empty()) { for(const auto& t : result.tags) tags_str += "[" + t + "]"; tags_str = " " + apply(dim, tags_str); }
|
if (!result.tags.empty()) { for(const auto& t : result.tags) tags_str += "[" + t + "]"; tags_str = " " + Void::Testing::Detail::Color::apply(dim, tags_str); }
|
||||||
|
|
||||||
switch (result.state) {
|
switch (result.state) {
|
||||||
case TestState::Passed: os_ << std::format(" {} {:<40s}{}{}\n", apply(bold_green, "✔"), apply(green, result.name), tags_str, apply(dim, time_str)); break;
|
case TestState::Passed: os_ << std::format(" {} {:<40s}{}{}\n", Void::Testing::Detail::Color::apply(bold_green, "✔"), Void::Testing::Detail::Color::apply(green, result.name), tags_str, Void::Testing::Detail::Color::apply(dim, time_str)); break;
|
||||||
case TestState::Failed:
|
case TestState::Failed:
|
||||||
os_ << std::format(" {} {:<40s}{}{}\n", apply(bold_red, "✘"), apply(red, result.name), tags_str, apply(dim, time_str));
|
os_ << std::format(" {} {:<40s}{}{}\n", Void::Testing::Detail::Color::apply(bold_red, "✘"), Void::Testing::Detail::Color::apply(red, result.name), tags_str, Void::Testing::Detail::Color::apply(dim, time_str));
|
||||||
for (const auto& ar : result.assertions) if (!ar.passed) print_assertion_failure(ar);
|
for (const auto& ar : result.assertions) if (!ar.passed) print_assertion_failure(ar);
|
||||||
if (!result.crash_info.empty()) print_crash_info(result);
|
if (!result.crash_info.empty()) print_crash_info(result);
|
||||||
break;
|
break;
|
||||||
case TestState::Skipped: os_ << std::format(" {} {:<40s}{}\n", apply(bold_yellow, "⊘"), apply(yellow, result.name), apply(dim, std::format("[SKIPPED: {}]", result.skip_reason.empty() ? "no reason" : result.skip_reason))); break;
|
case TestState::Skipped: os_ << std::format(" {} {:<40s}{}\n", Void::Testing::Detail::Color::apply(bold_yellow, "⊘"), Void::Testing::Detail::Color::apply(yellow, result.name), Void::Testing::Detail::Color::apply(dim, std::format("[SKIPPED: {}]", result.skip_reason.empty() ? "no reason" : result.skip_reason))); break;
|
||||||
case TestState::Crashed: os_ << std::format(" {} {:<40s}{}\n", apply(bold_red, "⚡"), apply(red, result.name), apply(dim, time_str)); print_crash_info(result); break;
|
case TestState::Crashed: os_ << std::format(" {} {:<40s}{}\n", Void::Testing::Detail::Color::apply(bold_red, "⚡"), Void::Testing::Detail::Color::apply(red, result.name), Void::Testing::Detail::Color::apply(dim, time_str)); print_crash_info(result); break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void ConsoleReporter::print_assertion_failure(const AssertionResult& ar) {
|
void ConsoleReporter::print_assertion_failure(const AssertionResult& ar) {
|
||||||
os_ << apply(red, " ╭─── Assertion Failed") << apply(dim, " ──────────────────────╮") << "\n";
|
os_ << Void::Testing::Detail::Color::apply(red, " ╭─── Assertion Failed") << Void::Testing::Detail::Color::apply(dim, " ──────────────────────╮") << "\n";
|
||||||
std::filesystem::path p{ar.location.file_name()};
|
std::filesystem::path p{ar.location.file_name()};
|
||||||
os_ << std::format(" │ {}:{}\n", apply(bold_white, p.filename().string()), ar.location.line());
|
os_ << std::format(" │ {}:{}\n", Void::Testing::Detail::Color::apply(bold_white, p.filename().string()), ar.location.line());
|
||||||
if (!ar.expression.empty()) os_ << std::format(" │ {}\n", apply(cyan, ar.expression));
|
if (!ar.expression.empty()) os_ << std::format(" │ {}\n", Void::Testing::Detail::Color::apply(cyan, ar.expression));
|
||||||
if (!ar.expected_repr.empty()) os_ << std::format(" │ {} {}\n", apply(bold_white, "expected:"), apply(green, ar.expected_repr));
|
if (!ar.expected_repr.empty()) os_ << std::format(" │ {} {}\n", Void::Testing::Detail::Color::apply(bold_white, "expected:"), Void::Testing::Detail::Color::apply(green, ar.expected_repr));
|
||||||
if (!ar.actual_repr.empty()) os_ << std::format(" │ {} {}\n", apply(bold_white, "actual: "), apply(red, ar.actual_repr));
|
if (!ar.actual_repr.empty()) os_ << std::format(" │ {} {}\n", Void::Testing::Detail::Color::apply(bold_white, "actual: "), Void::Testing::Detail::Color::apply(red, ar.actual_repr));
|
||||||
if (!ar.message.empty()) os_ << std::format(" │ {}\n", ar.message);
|
if (!ar.message.empty()) os_ << std::format(" │ {}\n", ar.message);
|
||||||
os_ << apply(red, " ╰────────────────────────────────────────────╯") << "\n";
|
os_ << Void::Testing::Detail::Color::apply(red, " ╰────────────────────────────────────────────╯") << "\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
void ConsoleReporter::print_crash_info(const TestResult& result) {
|
void ConsoleReporter::print_crash_info(const TestResult& result) {
|
||||||
os_ << apply(bold_red, " ╭─── Crash") << apply(dim, " ───────────────────────────╮") << "\n";
|
os_ << Void::Testing::Detail::Color::apply(bold_red, " ╭─── Crash") << Void::Testing::Detail::Color::apply(dim, " ───────────────────────────╮") << "\n";
|
||||||
if (!result.crash_info.empty()) os_ << std::format(" │ {}\n", apply(red, result.crash_info));
|
if (!result.crash_info.empty()) os_ << std::format(" │ {}\n", Void::Testing::Detail::Color::apply(red, result.crash_info));
|
||||||
os_ << apply(bold_red, " ╰────────────────────────────────────────────╯") << "\n";
|
os_ << Void::Testing::Detail::Color::apply(bold_red, " ╰────────────────────────────────────────────╯") << "\n";
|
||||||
if (!result.stacktrace.empty()) os_ << apply(dim, " Stacktrace:\n") << result.stacktrace << "\n";
|
if (!result.stacktrace.empty()) os_ << Void::Testing::Detail::Color::apply(dim, " Stacktrace:\n") << result.stacktrace << "\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
void ConsoleReporter::on_run_end(const RunResult& result) {
|
void ConsoleReporter::on_run_end(const RunResult& result) {
|
||||||
os_ << "\n" << apply(dim, "╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍") << "\n"
|
os_ << "\n" << Void::Testing::Detail::Color::apply(dim, "╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍") << "\n"
|
||||||
<< std::format(" {} tests: ", apply(bold_white, std::to_string(result.total)));
|
<< std::format(" {} tests: ", Void::Testing::Detail::Color::apply(bold_white, std::to_string(result.total)));
|
||||||
if (result.passed > 0) os_ << std::format("{} {} ", apply(bold_green, std::to_string(result.passed)), apply(green, "✔"));
|
if (result.passed > 0) os_ << std::format("{} {} ", Void::Testing::Detail::Color::apply(bold_green, std::to_string(result.passed)), Void::Testing::Detail::Color::apply(green, "✔"));
|
||||||
if (result.failed + result.crashed > 0) os_ << std::format("{} {} ", apply(bold_red, std::to_string(result.failed + result.crashed)), apply(red, "✘"));
|
if (result.failed + result.crashed > 0) os_ << std::format("{} {} ", Void::Testing::Detail::Color::apply(bold_red, std::to_string(result.failed + result.crashed)), Void::Testing::Detail::Color::apply(red, "✘"));
|
||||||
if (result.skipped > 0) os_ << std::format("{} {} ", apply(bold_yellow, std::to_string(result.skipped)), apply(yellow, "⊘"));
|
if (result.skipped > 0) os_ << std::format("{} {} ", Void::Testing::Detail::Color::apply(bold_yellow, std::to_string(result.skipped)), Void::Testing::Detail::Color::apply(yellow, "⊘"));
|
||||||
double total_ms = std::chrono::duration<double, std::milli>(result.total_duration).count();
|
double total_ms = std::chrono::duration<double, std::milli>(result.total_duration).count();
|
||||||
os_ << std::format(" {} {}\n", apply(dim, "in"), apply(bold_cyan, total_ms < 1000 ? std::format("{:.1f}ms", total_ms) : std::format("{:.2f}s", total_ms / 1000.0)))
|
os_ << std::format(" {} {}\n", Void::Testing::Detail::Color::apply(dim, "in"), Void::Testing::Detail::Color::apply(bold_cyan, total_ms < 1000 ? std::format("{:.1f}ms", total_ms) : std::format("{:.2f}s", total_ms / 1000.0)))
|
||||||
<< apply(dim, "╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍") << "\n\n";
|
<< Void::Testing::Detail::Color::apply(dim, "╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍") << "\n\n";
|
||||||
}
|
}
|
||||||
} // namespace Void::Testing
|
} // namespace Void::Testing
|
||||||
+44
-42
@@ -115,6 +115,12 @@ namespace Void::Testing
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Failures are counted when recorded (TestResult::failed_assertions),
|
||||||
|
// independently of the bounded assertion vector kept for reporting.
|
||||||
|
[[nodiscard]] bool has_recorded_failure(const TestResult& result) noexcept
|
||||||
|
{
|
||||||
|
return result.failed_assertions > 0;
|
||||||
|
}
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
RunConfig Runner::parse_args(int argc, char** argv)
|
RunConfig Runner::parse_args(int argc, char** argv)
|
||||||
@@ -325,9 +331,7 @@ namespace Void::Testing
|
|||||||
|
|
||||||
if (result.state != TestState::Skipped &&
|
if (result.state != TestState::Skipped &&
|
||||||
result.state != TestState::Crashed) {
|
result.state != TestState::Crashed) {
|
||||||
bool any = std::any_of(
|
const bool any = has_recorded_failure(result);
|
||||||
result.assertions.begin(), result.assertions.end(),
|
|
||||||
[](const auto& a) { return !a.passed; });
|
|
||||||
// An exception that escaped the body fails it too, with no failed
|
// An exception that escaped the body fails it too, with no failed
|
||||||
// assertion recorded.
|
// assertion recorded.
|
||||||
const bool unhandled = !result.crash_info.empty() || !result.cleanup_error.empty();
|
const bool unhandled = !result.crash_info.empty() || !result.cleanup_error.empty();
|
||||||
@@ -376,9 +380,7 @@ namespace Void::Testing
|
|||||||
|
|
||||||
if (result.state != TestState::Skipped &&
|
if (result.state != TestState::Skipped &&
|
||||||
result.state != TestState::Crashed) {
|
result.state != TestState::Crashed) {
|
||||||
bool any = std::any_of(
|
const bool any = has_recorded_failure(result);
|
||||||
result.assertions.begin(), result.assertions.end(),
|
|
||||||
[](const auto& a) { return !a.passed; });
|
|
||||||
// An exception that escaped the body fails it too, with no failed
|
// An exception that escaped the body fails it too, with no failed
|
||||||
// assertion recorded.
|
// assertion recorded.
|
||||||
const bool unhandled = !result.crash_info.empty() || !result.cleanup_error.empty();
|
const bool unhandled = !result.crash_info.empty() || !result.cleanup_error.empty();
|
||||||
@@ -447,7 +449,7 @@ namespace Void::Testing
|
|||||||
|
|
||||||
std::cout
|
std::cout
|
||||||
<< "\n"
|
<< "\n"
|
||||||
<< apply(bold_blue,
|
<< Void::Testing::Detail::Color::apply(bold_blue,
|
||||||
"\xe2\x95\xad\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
"\xe2\x95\xad\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||||
@@ -461,12 +463,12 @@ namespace Void::Testing
|
|||||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x95\xae")
|
"\xe2\x94\x80\xe2\x94\x80\xe2\x95\xae")
|
||||||
<< "\n"
|
<< "\n"
|
||||||
<< apply(bold_blue, "\xe2\x94\x82")
|
<< Void::Testing::Detail::Color::apply(bold_blue, "\xe2\x94\x82")
|
||||||
<< apply(bold_white, " Void Testing")
|
<< Void::Testing::Detail::Color::apply(bold_white, " Void Testing")
|
||||||
<< apply(dim, " \xe2\x80\x94 Command Line Interface")
|
<< Void::Testing::Detail::Color::apply(dim, " \xe2\x80\x94 Command Line Interface")
|
||||||
<< std::string(28, ' ') << apply(bold_blue, "\xe2\x94\x82")
|
<< std::string(28, ' ') << Void::Testing::Detail::Color::apply(bold_blue, "\xe2\x94\x82")
|
||||||
<< "\n"
|
<< "\n"
|
||||||
<< apply(bold_blue,
|
<< Void::Testing::Detail::Color::apply(bold_blue,
|
||||||
"\xe2\x95\xb0\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
"\xe2\x95\xb0\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
"\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80"
|
||||||
@@ -481,76 +483,76 @@ namespace Void::Testing
|
|||||||
"\xe2\x94\x80\xe2\x94\x80\xe2\x95\xaf")
|
"\xe2\x94\x80\xe2\x94\x80\xe2\x95\xaf")
|
||||||
<< "\n"
|
<< "\n"
|
||||||
<< "\n"
|
<< "\n"
|
||||||
<< " " << apply(bold_white, "USAGE:") << "\n"
|
<< " " << Void::Testing::Detail::Color::apply(bold_white, "USAGE:") << "\n"
|
||||||
<< " " << apply(cyan, "<executable>") << " "
|
<< " " << Void::Testing::Detail::Color::apply(cyan, "<executable>") << " "
|
||||||
<< apply(dim, "[options]") << "\n"
|
<< Void::Testing::Detail::Color::apply(dim, "[options]") << "\n"
|
||||||
<< "\n"
|
<< "\n"
|
||||||
<< " " << apply(bold_white, "OPTIONS:") << "\n";
|
<< " " << Void::Testing::Detail::Color::apply(bold_white, "OPTIONS:") << "\n";
|
||||||
|
|
||||||
constexpr std::size_t OPT_WIDTH = 23;
|
constexpr std::size_t OPT_WIDTH = 23;
|
||||||
auto opt = [&](std::string_view name) {
|
auto opt = [&](std::string_view name) {
|
||||||
#ifdef VOID_HAS_TEXT
|
#ifdef VOID_HAS_TEXT
|
||||||
return apply(green, Void::Str::pad_right(name, OPT_WIDTH));
|
return Void::Testing::Detail::Color::apply(green, Void::Str::pad_right(name, OPT_WIDTH));
|
||||||
#else
|
#else
|
||||||
std::string s{name};
|
std::string s{name};
|
||||||
if (s.size() < OPT_WIDTH) {
|
if (s.size() < OPT_WIDTH) {
|
||||||
s.append(OPT_WIDTH - s.size(), ' ');
|
s.append(OPT_WIDTH - s.size(), ' ');
|
||||||
}
|
}
|
||||||
return apply(green, s);
|
return Void::Testing::Detail::Color::apply(green, s);
|
||||||
#endif
|
#endif
|
||||||
};
|
};
|
||||||
|
|
||||||
std::cout
|
std::cout
|
||||||
<< " " << opt("--filter <pattern>")
|
<< " " << opt("--filter <pattern>")
|
||||||
<< apply(dim, "Run tests matching the regex pattern") << "\n"
|
<< Void::Testing::Detail::Color::apply(dim, "Run tests matching the regex pattern") << "\n"
|
||||||
<< " " << opt("--suite <name>")
|
<< " " << opt("--suite <name>")
|
||||||
<< apply(dim, "Run only tests in the specified suite") << "\n"
|
<< Void::Testing::Detail::Color::apply(dim, "Run only tests in the specified suite") << "\n"
|
||||||
<< " " << opt("--tag <name>")
|
<< " " << opt("--tag <name>")
|
||||||
<< apply(dim, "Run only tests with the specified tag") << "\n"
|
<< Void::Testing::Detail::Color::apply(dim, "Run only tests with the specified tag") << "\n"
|
||||||
<< " " << opt("--list")
|
<< " " << opt("--list")
|
||||||
<< apply(dim, "List discovered tests without running them")
|
<< Void::Testing::Detail::Color::apply(dim, "List discovered tests without running them")
|
||||||
<< "\n"
|
<< "\n"
|
||||||
<< " " << opt("--shuffle")
|
<< " " << opt("--shuffle")
|
||||||
<< apply(dim, "Randomize the order of test execution") << "\n"
|
<< Void::Testing::Detail::Color::apply(dim, "Randomize the order of test execution") << "\n"
|
||||||
<< " " << opt("--seed <n>")
|
<< " " << opt("--seed <n>")
|
||||||
<< apply(dim, "Set the random seed (implies --shuffle)") << "\n"
|
<< Void::Testing::Detail::Color::apply(dim, "Set the random seed (implies --shuffle)") << "\n"
|
||||||
<< " " << opt("--repeat <n>")
|
<< " " << opt("--repeat <n>")
|
||||||
<< apply(dim, "Repeat the test run n times") << "\n"
|
<< Void::Testing::Detail::Color::apply(dim, "Repeat the test run n times") << "\n"
|
||||||
<< " " << opt("--reporter <type>")
|
<< " " << opt("--reporter <type>")
|
||||||
<< apply(dim, "Choose the output reporter: console, junit")
|
<< Void::Testing::Detail::Color::apply(dim, "Choose the output reporter: console, junit")
|
||||||
<< "\n"
|
<< "\n"
|
||||||
<< " " << opt("--output <file>")
|
<< " " << opt("--output <file>")
|
||||||
<< apply(dim, "Write reporter output to a file") << "\n"
|
<< Void::Testing::Detail::Color::apply(dim, "Write reporter output to a file") << "\n"
|
||||||
#ifdef VOID_HAS_LOG
|
#ifdef VOID_HAS_LOG
|
||||||
<< " " << opt("--log-file <file>")
|
<< " " << opt("--log-file <file>")
|
||||||
<< apply(dim,
|
<< Void::Testing::Detail::Color::apply(dim,
|
||||||
"Mirror test events to <file> via Void::Logging")
|
"Mirror test events to <file> via Void::Logging")
|
||||||
<< "\n"
|
<< "\n"
|
||||||
#endif
|
#endif
|
||||||
#ifdef VOID_HAS_ASYNC
|
#ifdef VOID_HAS_ASYNC
|
||||||
<< " " << opt("--parallel <n>")
|
<< " " << opt("--parallel <n>")
|
||||||
<< apply(dim,
|
<< Void::Testing::Detail::Color::apply(dim,
|
||||||
"Run tests across n threads (no crash detection)")
|
"Run tests across n threads (no crash detection)")
|
||||||
<< "\n"
|
<< "\n"
|
||||||
#endif
|
#endif
|
||||||
<< " " << opt("--verbose")
|
<< " " << opt("--verbose")
|
||||||
<< apply(dim, "Enable verbose output") << "\n"
|
<< Void::Testing::Detail::Color::apply(dim, "Enable verbose output") << "\n"
|
||||||
<< " " << opt("--no-color")
|
<< " " << opt("--no-color")
|
||||||
<< apply(dim, "Disable colored console output") << "\n"
|
<< Void::Testing::Detail::Color::apply(dim, "Disable colored console output") << "\n"
|
||||||
<< " " << opt("--allow-empty")
|
<< " " << opt("--allow-empty")
|
||||||
<< apply(dim, "Do not fail when selection matches zero tests") << "\n"
|
<< Void::Testing::Detail::Color::apply(dim, "Do not fail when selection matches zero tests") << "\n"
|
||||||
<< " " << opt("--help")
|
<< " " << opt("--help")
|
||||||
<< apply(dim, "Show this help message") << "\n"
|
<< Void::Testing::Detail::Color::apply(dim, "Show this help message") << "\n"
|
||||||
<< "\n"
|
<< "\n"
|
||||||
<< " " << apply(bold_white, "EXAMPLES:") << "\n"
|
<< " " << Void::Testing::Detail::Color::apply(bold_white, "EXAMPLES:") << "\n"
|
||||||
<< " " << apply(cyan, "./run_tests") << " "
|
<< " " << Void::Testing::Detail::Color::apply(cyan, "./run_tests") << " "
|
||||||
<< apply(yellow, "--filter") << " \"math_tests.*\"" << "\n"
|
<< Void::Testing::Detail::Color::apply(yellow, "--filter") << " \"math_tests.*\"" << "\n"
|
||||||
<< " " << apply(cyan, "./run_tests") << " "
|
<< " " << Void::Testing::Detail::Color::apply(cyan, "./run_tests") << " "
|
||||||
<< apply(yellow, "--tag") << " integration "
|
<< Void::Testing::Detail::Color::apply(yellow, "--tag") << " integration "
|
||||||
<< apply(yellow, "--shuffle") << "\n"
|
<< Void::Testing::Detail::Color::apply(yellow, "--shuffle") << "\n"
|
||||||
<< " " << apply(cyan, "./run_tests") << " "
|
<< " " << Void::Testing::Detail::Color::apply(cyan, "./run_tests") << " "
|
||||||
<< apply(yellow, "--reporter") << " junit "
|
<< Void::Testing::Detail::Color::apply(yellow, "--reporter") << " junit "
|
||||||
<< apply(yellow, "--output") << " results.xml" << "\n"
|
<< Void::Testing::Detail::Color::apply(yellow, "--output") << " results.xml" << "\n"
|
||||||
<< "\n";
|
<< "\n";
|
||||||
|
|
||||||
return {};
|
return {};
|
||||||
|
|||||||
+48
-2
@@ -11,6 +11,21 @@ get_property(ACTIVE_HEADERS GLOBAL PROPERTY VOID_ACTIVE_PUBLIC_HEADERS)
|
|||||||
|
|
||||||
function(_void_test_requires_satisfied src_file active_modules active_headers out_var)
|
function(_void_test_requires_satisfied src_file active_modules active_headers out_var)
|
||||||
file(READ "${src_file}" _src_content)
|
file(READ "${src_file}" _src_content)
|
||||||
|
# Whole-file capability gates. The test scanner is line-based and does not
|
||||||
|
# evaluate preprocessor conditionals, so a file whose tests live inside
|
||||||
|
# `#ifdef VOID_HAS_*_REFLECTION` would still get registrations generated
|
||||||
|
# for functions that are not defined. Such files declare
|
||||||
|
# `// @requires-reflection` and are skipped when the compiler cannot do
|
||||||
|
# C++26 reflection.
|
||||||
|
if(NOT VOID_HAS_CXX26_REFLECTION)
|
||||||
|
string(FIND "${_src_content}" "// @requires-reflection" _needs_reflection)
|
||||||
|
if(NOT _needs_reflection EQUAL -1)
|
||||||
|
message(STATUS
|
||||||
|
"[VoidTests] Skipping ${src_file} (requires C++26 reflection)")
|
||||||
|
set(${out_var} FALSE PARENT_SCOPE)
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
string(REGEX MATCHALL "#[ \t]*include[ \t]*[<\"](Void/[^/\">]+/[^>\"]+)[>\"]"
|
string(REGEX MATCHALL "#[ \t]*include[ \t]*[<\"](Void/[^/\">]+/[^>\"]+)[>\"]"
|
||||||
_matches "${_src_content}")
|
_matches "${_src_content}")
|
||||||
set(_ok TRUE)
|
set(_ok TRUE)
|
||||||
@@ -114,10 +129,24 @@ endforeach()
|
|||||||
if(_all_generated)
|
if(_all_generated)
|
||||||
add_executable(VoidTests ${_all_generated})
|
add_executable(VoidTests ${_all_generated})
|
||||||
|
|
||||||
|
# The generated test translation units belong to VoidTests, not to a module
|
||||||
|
# target, so the warnings-as-errors policy from void_add_module does not
|
||||||
|
# reach them unless it is applied here explicitly (X-QA-01).
|
||||||
|
if(VOID_WARNINGS_AS_ERRORS)
|
||||||
|
target_compile_options(VoidTests PRIVATE
|
||||||
|
"$<$<COMPILE_LANGUAGE:CXX>:$<$<CXX_COMPILER_ID:GNU,Clang,AppleClang>:-Wall;-Wextra;-Wpedantic;-Werror;-Wno-missing-field-initializers>>"
|
||||||
|
# Test helpers live in anonymous namespaces and are captured by
|
||||||
|
# coroutine frames; GCC's subobject-linkage diagnostic is noise for
|
||||||
|
# that pattern, not a defect in the test code.
|
||||||
|
"$<$<COMPILE_LANGUAGE:CXX>:$<$<CXX_COMPILER_ID:GNU>:-Wno-subobject-linkage>>")
|
||||||
|
endif()
|
||||||
|
|
||||||
# Disable auto-sweep: we already applied the scanner manually above.
|
# Disable auto-sweep: we already applied the scanner manually above.
|
||||||
set_target_properties(VoidTests PROPERTIES VOID_TESTING_NO_AUTO_SCAN TRUE)
|
set_target_properties(VoidTests PROPERTIES VOID_TESTING_NO_AUTO_SCAN TRUE)
|
||||||
|
|
||||||
target_link_libraries(VoidTests PRIVATE Void::Testing)
|
target_link_libraries(VoidTests PRIVATE Void::Testing)
|
||||||
|
target_compile_definitions(VoidTests PRIVATE
|
||||||
|
"VOID_HAS_CXX26_REFLECTION=$<BOOL:${VOID_HAS_CXX26_REFLECTION}>")
|
||||||
foreach(mod ${ACTIVE_MODULES})
|
foreach(mod ${ACTIVE_MODULES})
|
||||||
if(NOT mod STREQUAL "Testing" AND TARGET Void::${mod})
|
if(NOT mod STREQUAL "Testing" AND TARGET Void::${mod})
|
||||||
target_link_libraries(VoidTests PRIVATE Void::${mod})
|
target_link_libraries(VoidTests PRIVATE Void::${mod})
|
||||||
@@ -158,6 +187,23 @@ if(_all_generated)
|
|||||||
)
|
)
|
||||||
set_tests_properties(VoidInstalledComponentConsumers PROPERTIES
|
set_tests_properties(VoidInstalledComponentConsumers PROPERTIES
|
||||||
DEPENDS VoidTests)
|
DEPENDS VoidTests)
|
||||||
|
|
||||||
|
add_test(NAME VoidTargetQualification
|
||||||
|
COMMAND ${CMAKE_COMMAND}
|
||||||
|
-DVOID_BUILD_DIR=${CMAKE_BINARY_DIR}
|
||||||
|
-DVOID_SOURCE_DIR=${CMAKE_SOURCE_DIR}
|
||||||
|
-DVOID_TEST_SOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR}/package
|
||||||
|
-DVOID_TEST_ROOT=${CMAKE_CURRENT_BINARY_DIR}/target-qualification
|
||||||
|
-DVOID_CXX_COMPILER=${CMAKE_CXX_COMPILER}
|
||||||
|
-DVOID_CTEST_COMMAND=${CMAKE_CTEST_COMMAND}
|
||||||
|
-DVOID_GENERATOR=${CMAKE_GENERATOR}
|
||||||
|
-DVOID_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM}
|
||||||
|
-DVOID_TARGET=${VOID_TARGET_DETECTED}
|
||||||
|
-DVOID_CROSSCOMPILING=${CMAKE_CROSSCOMPILING}
|
||||||
|
-DVOID_BUILD_CONFIG=$<CONFIG>
|
||||||
|
-P ${CMAKE_CURRENT_SOURCE_DIR}/package/TargetQualification.cmake)
|
||||||
|
set_tests_properties(VoidTargetQualification PROPERTIES
|
||||||
|
DEPENDS VoidTests)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
# ── Test-support executables & libraries ──────────────────────────────────────
|
# ── Test-support executables & libraries ──────────────────────────────────────
|
||||||
@@ -167,7 +213,7 @@ if(TARGET VoidTests AND (TARGET Void::System OR TARGET Void::IPC))
|
|||||||
add_executable(VoidProcessHelper
|
add_executable(VoidProcessHelper
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/helpers/ProcessHelper.cpp")
|
"${CMAKE_CURRENT_SOURCE_DIR}/helpers/ProcessHelper.cpp")
|
||||||
set_target_properties(VoidProcessHelper PROPERTIES
|
set_target_properties(VoidProcessHelper PROPERTIES
|
||||||
CXX_STANDARD 26
|
CXX_STANDARD ${CMAKE_CXX_STANDARD}
|
||||||
CXX_STANDARD_REQUIRED ON
|
CXX_STANDARD_REQUIRED ON
|
||||||
CXX_EXTENSIONS OFF
|
CXX_EXTENSIONS OFF
|
||||||
VOID_TESTING_NO_AUTO_SCAN TRUE)
|
VOID_TESTING_NO_AUTO_SCAN TRUE)
|
||||||
@@ -181,7 +227,7 @@ if(TARGET VoidTests AND TARGET Void::Archive)
|
|||||||
"${CMAKE_CURRENT_SOURCE_DIR}/helpers/ArchiveWorker.cpp")
|
"${CMAKE_CURRENT_SOURCE_DIR}/helpers/ArchiveWorker.cpp")
|
||||||
target_link_libraries(VoidArchiveWorker PRIVATE Void::Archive)
|
target_link_libraries(VoidArchiveWorker PRIVATE Void::Archive)
|
||||||
set_target_properties(VoidArchiveWorker PROPERTIES
|
set_target_properties(VoidArchiveWorker PROPERTIES
|
||||||
CXX_STANDARD 26
|
CXX_STANDARD ${CMAKE_CXX_STANDARD}
|
||||||
CXX_STANDARD_REQUIRED ON
|
CXX_STANDARD_REQUIRED ON
|
||||||
CXX_EXTENSIONS OFF
|
CXX_EXTENSIONS OFF
|
||||||
VOID_TESTING_NO_AUTO_SCAN TRUE)
|
VOID_TESTING_NO_AUTO_SCAN TRUE)
|
||||||
|
|||||||
@@ -0,0 +1,189 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
// Shared test-only support for loopback TLS/SMTP fixtures.
|
||||||
|
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
|
||||||
|
#include <openssl/evp.h>
|
||||||
|
#include <openssl/pem.h>
|
||||||
|
#include <openssl/x509.h>
|
||||||
|
#include <openssl/x509v3.h>
|
||||||
|
|
||||||
|
#include <arpa/inet.h>
|
||||||
|
#include <netinet/in.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#include <cerrno>
|
||||||
|
#include <cstdio>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <memory>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <system_error>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::Testing::NetSupport
|
||||||
|
{
|
||||||
|
inline std::filesystem::path make_scratch_dir(std::string_view prefix)
|
||||||
|
{
|
||||||
|
static unsigned counter = 0;
|
||||||
|
auto path = std::filesystem::temp_directory_path() /
|
||||||
|
(std::string{prefix} + std::to_string(::getpid()) + "_" +
|
||||||
|
std::to_string(counter++));
|
||||||
|
std::filesystem::create_directories(path);
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ScratchDir {
|
||||||
|
std::filesystem::path path;
|
||||||
|
|
||||||
|
explicit ScratchDir(std::string_view prefix)
|
||||||
|
: path(make_scratch_dir(prefix))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
ScratchDir(const ScratchDir&) = delete;
|
||||||
|
ScratchDir& operator=(const ScratchDir&) = delete;
|
||||||
|
|
||||||
|
~ScratchDir()
|
||||||
|
{
|
||||||
|
std::error_code ec;
|
||||||
|
std::filesystem::remove_all(path, ec);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
struct GeneratedCert {
|
||||||
|
std::filesystem::path cert_file;
|
||||||
|
std::filesystem::path key_file;
|
||||||
|
};
|
||||||
|
|
||||||
|
inline GeneratedCert
|
||||||
|
generate_self_signed_cert(const std::filesystem::path& dir,
|
||||||
|
const char* san_value, const char* tag)
|
||||||
|
{
|
||||||
|
using PkeyPtr = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
|
||||||
|
using X509Ptr = std::unique_ptr<X509, decltype(&X509_free)>;
|
||||||
|
using ExtPtr =
|
||||||
|
std::unique_ptr<X509_EXTENSION, decltype(&X509_EXTENSION_free)>;
|
||||||
|
|
||||||
|
PkeyPtr pkey{EVP_RSA_gen(2048), &EVP_PKEY_free};
|
||||||
|
Void::Testing::require(static_cast<bool>(pkey));
|
||||||
|
|
||||||
|
X509Ptr cert{X509_new(), &X509_free};
|
||||||
|
Void::Testing::require(static_cast<bool>(cert));
|
||||||
|
X509_set_version(cert.get(), 2);
|
||||||
|
ASN1_INTEGER_set(X509_get_serialNumber(cert.get()), 1);
|
||||||
|
X509_gmtime_adj(X509_get_notBefore(cert.get()), -60);
|
||||||
|
X509_gmtime_adj(X509_get_notAfter(cert.get()), 3600);
|
||||||
|
X509_set_pubkey(cert.get(), pkey.get());
|
||||||
|
|
||||||
|
X509_NAME* name = X509_get_subject_name(cert.get());
|
||||||
|
X509_NAME_add_entry_by_txt(
|
||||||
|
name, "CN", MBSTRING_ASC,
|
||||||
|
reinterpret_cast<const unsigned char*>("127.0.0.1"), -1, -1, 0);
|
||||||
|
X509_set_issuer_name(cert.get(), name);
|
||||||
|
|
||||||
|
X509V3_CTX ctx{};
|
||||||
|
X509V3_set_ctx_nodb(&ctx);
|
||||||
|
X509V3_set_ctx(&ctx, cert.get(), cert.get(), nullptr, nullptr, 0);
|
||||||
|
ExtPtr ext{X509V3_EXT_conf_nid(nullptr, &ctx, NID_subject_alt_name,
|
||||||
|
const_cast<char*>(san_value)),
|
||||||
|
&X509_EXTENSION_free};
|
||||||
|
Void::Testing::require(static_cast<bool>(ext));
|
||||||
|
Void::Testing::require(X509_add_ext(cert.get(), ext.get(), -1) == 1);
|
||||||
|
|
||||||
|
Void::Testing::require(
|
||||||
|
X509_sign(cert.get(), pkey.get(), EVP_sha256()) > 0);
|
||||||
|
|
||||||
|
const auto cert_path = dir / (std::string{"cert_"} + tag + ".pem");
|
||||||
|
const auto key_path = dir / (std::string{"key_"} + tag + ".pem");
|
||||||
|
FILE* cf = std::fopen(cert_path.c_str(), "wb");
|
||||||
|
Void::Testing::require(cf != nullptr);
|
||||||
|
Void::Testing::require(PEM_write_X509(cf, cert.get()) == 1);
|
||||||
|
std::fclose(cf);
|
||||||
|
|
||||||
|
FILE* kf = std::fopen(key_path.c_str(), "wb");
|
||||||
|
Void::Testing::require(kf != nullptr);
|
||||||
|
Void::Testing::require(PEM_write_PrivateKey(
|
||||||
|
kf, pkey.get(), nullptr, nullptr, 0,
|
||||||
|
nullptr, nullptr) == 1);
|
||||||
|
std::fclose(kf);
|
||||||
|
return GeneratedCert{cert_path, key_path};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bound TCP listener on 127.0.0.1 with an ephemeral port.
|
||||||
|
struct LoopbackListener {
|
||||||
|
int fd{-1};
|
||||||
|
std::uint16_t port{0};
|
||||||
|
|
||||||
|
LoopbackListener()
|
||||||
|
{
|
||||||
|
fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||||
|
Void::Testing::require(fd >= 0);
|
||||||
|
int yes = 1;
|
||||||
|
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes,
|
||||||
|
sizeof(yes));
|
||||||
|
sockaddr_in address{};
|
||||||
|
address.sin_family = AF_INET;
|
||||||
|
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||||
|
address.sin_port = 0;
|
||||||
|
Void::Testing::require(
|
||||||
|
::bind(fd, reinterpret_cast<sockaddr*>(&address),
|
||||||
|
sizeof(address)) == 0);
|
||||||
|
socklen_t length = sizeof(address);
|
||||||
|
Void::Testing::require(
|
||||||
|
::getsockname(fd, reinterpret_cast<sockaddr*>(&address),
|
||||||
|
&length) == 0);
|
||||||
|
port = ntohs(address.sin_port);
|
||||||
|
Void::Testing::require(::listen(fd, 4) == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
LoopbackListener(const LoopbackListener&) = delete;
|
||||||
|
LoopbackListener& operator=(const LoopbackListener&) = delete;
|
||||||
|
|
||||||
|
~LoopbackListener()
|
||||||
|
{
|
||||||
|
if (fd >= 0) {
|
||||||
|
::close(fd);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] int accept_one() const
|
||||||
|
{
|
||||||
|
return ::accept(fd, nullptr, nullptr);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
inline bool 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 (written < 0 && errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
data.remove_prefix(static_cast<std::size_t>(written));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read until `delimiter` is found or `max_bytes` is exceeded.
|
||||||
|
inline std::string read_until(int fd, std::string_view delimiter,
|
||||||
|
std::size_t max_bytes)
|
||||||
|
{
|
||||||
|
std::string buffer;
|
||||||
|
while (buffer.find(delimiter) == std::string::npos &&
|
||||||
|
buffer.size() <= max_bytes) {
|
||||||
|
char chunk[1024];
|
||||||
|
const ssize_t count = ::recv(fd, chunk, sizeof(chunk), 0);
|
||||||
|
if (count <= 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
buffer.append(chunk, static_cast<std::size_t>(count));
|
||||||
|
}
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
} // namespace Void::Testing::NetSupport
|
||||||
@@ -245,6 +245,31 @@ int mode_grandchild_ignore_sigterm(int argc, char** argv)
|
|||||||
::_exit(0);
|
::_exit(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int mode_descendant_holds_stdout(int argc, char** argv)
|
||||||
|
{
|
||||||
|
std::int64_t hold_ms = 5000;
|
||||||
|
if (argc >= 3 && !parse_i64(argv[2], hold_ms)) {
|
||||||
|
return usage_error("descendant-holds-stdout duration must be an integer");
|
||||||
|
}
|
||||||
|
if (hold_ms < 0) {
|
||||||
|
hold_ms = 0;
|
||||||
|
}
|
||||||
|
const pid_t descendant = ::fork();
|
||||||
|
if (descendant < 0) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (descendant == 0) {
|
||||||
|
// Keep the inherited stdout write end open while ignoring graceful
|
||||||
|
// termination, so the parent's reader sees no EOF.
|
||||||
|
std::signal(SIGTERM, SIG_IGN);
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds{hold_ms});
|
||||||
|
::_exit(0);
|
||||||
|
}
|
||||||
|
static constexpr char kReady[] = "ready\n";
|
||||||
|
(void)write_all_fd(STDOUT_FILENO, kReady, sizeof(kReady) - 1);
|
||||||
|
::_exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
int mode_simultaneous_io(int argc, char** argv)
|
int mode_simultaneous_io(int argc, char** argv)
|
||||||
{
|
{
|
||||||
if (argc != 3) {
|
if (argc != 3) {
|
||||||
@@ -539,6 +564,9 @@ int main(int argc, char** argv)
|
|||||||
if (mode == "grandchild-ignore-sigterm") {
|
if (mode == "grandchild-ignore-sigterm") {
|
||||||
return mode_grandchild_ignore_sigterm(argc, argv);
|
return mode_grandchild_ignore_sigterm(argc, argv);
|
||||||
}
|
}
|
||||||
|
if (mode == "descendant-holds-stdout") {
|
||||||
|
return mode_descendant_holds_stdout(argc, argv);
|
||||||
|
}
|
||||||
if (mode == "simultaneous-io") {
|
if (mode == "simultaneous-io") {
|
||||||
return mode_simultaneous_io(argc, argv);
|
return mode_simultaneous_io(argc, argv);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
cmake_minimum_required(VERSION 4.0)
|
||||||
|
project(VoidTargetProfileConsumer LANGUAGES CXX)
|
||||||
|
|
||||||
|
# Records and asserts the target tuple of an installed Void package. The
|
||||||
|
# qualification driver (tests/package/TargetQualification.cmake) passes the
|
||||||
|
# expected target and then checks the emitted profile file. Core is the
|
||||||
|
# always-present leaf module; per-module consumption is covered by the other
|
||||||
|
# tests/package fixtures.
|
||||||
|
if(NOT DEFINED VOID_EXPECTED_TARGET OR VOID_EXPECTED_TARGET STREQUAL "")
|
||||||
|
message(FATAL_ERROR "VOID_EXPECTED_TARGET is required")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
find_package(Void CONFIG REQUIRED COMPONENTS Core)
|
||||||
|
|
||||||
|
include("${Void_DIR}/void-target-manifest.cmake")
|
||||||
|
|
||||||
|
if(NOT VOID_TARGET_MANIFEST_TARGET STREQUAL VOID_EXPECTED_TARGET)
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"[TargetProfile] installed manifest target "
|
||||||
|
"'${VOID_TARGET_MANIFEST_TARGET}' does not match expected "
|
||||||
|
"'${VOID_EXPECTED_TARGET}'")
|
||||||
|
endif()
|
||||||
|
if(NOT Core IN_LIST VOID_TARGET_MANIFEST_MODULES)
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"[TargetProfile] installed manifest does not record module 'Core' "
|
||||||
|
"(modules: ${VOID_TARGET_MANIFEST_MODULES})")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/target-profile.txt"
|
||||||
|
"target=${VOID_TARGET_MANIFEST_TARGET}\n"
|
||||||
|
"triple=${VOID_TARGET_MANIFEST_TRIPLE}\n"
|
||||||
|
"compiler=${VOID_TARGET_MANIFEST_COMPILER_ID}-${VOID_TARGET_MANIFEST_COMPILER_VERSION}\n"
|
||||||
|
"cxx_standard=${VOID_TARGET_MANIFEST_CXX_STANDARD}\n"
|
||||||
|
"linkage=${VOID_TARGET_MANIFEST_LINKAGE}\n"
|
||||||
|
"reflection=${VOID_TARGET_MANIFEST_REFLECTION}\n"
|
||||||
|
"sanitizers=${VOID_TARGET_MANIFEST_SANITIZERS}\n"
|
||||||
|
"modules=${VOID_TARGET_MANIFEST_MODULES}\n"
|
||||||
|
)
|
||||||
|
message(STATUS
|
||||||
|
"[TargetProfile] target=${VOID_TARGET_MANIFEST_TARGET} "
|
||||||
|
"triple=${VOID_TARGET_MANIFEST_TRIPLE} "
|
||||||
|
"compiler=${VOID_TARGET_MANIFEST_COMPILER_ID}-${VOID_TARGET_MANIFEST_COMPILER_VERSION} "
|
||||||
|
"linkage=${VOID_TARGET_MANIFEST_LINKAGE} "
|
||||||
|
"reflection=${VOID_TARGET_MANIFEST_REFLECTION}")
|
||||||
|
|
||||||
|
add_executable(void_target_profile_consumer main.cpp)
|
||||||
|
target_link_libraries(void_target_profile_consumer PRIVATE Void::Core)
|
||||||
|
|
||||||
|
enable_testing()
|
||||||
|
add_test(NAME VoidTargetProfileConsumer COMMAND void_target_profile_consumer)
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
// Isolated consumer fixture for target qualification. Exercises a small
|
||||||
|
// runtime behaviour from the always-present Core module so an install/consume
|
||||||
|
// check covers headers, linkage and the module dependency closure.
|
||||||
|
#include <Void/Core/CheckedBits.hpp>
|
||||||
|
#include <Void/Core/Hash.hpp>
|
||||||
|
#include <Void/Core/Uuid.hpp>
|
||||||
|
|
||||||
|
#include <random>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
std::mt19937_64 rng{11};
|
||||||
|
const auto uuid = Void::Uuid::v4(rng);
|
||||||
|
const auto chars = Void::Uuid::format_chars(uuid);
|
||||||
|
const auto reparsed =
|
||||||
|
Void::Uuid::parse(std::string_view{chars.data(), chars.size()});
|
||||||
|
if (!reparsed || *reparsed != uuid) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto aligned = Void::Bits::checked_align_up(13u, 8u);
|
||||||
|
if (!aligned || *aligned != 16u) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Void::Hash::fnv1a64("target-profile") != 0 ? 0 : 1;
|
||||||
|
}
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
# Target qualification driver.
|
||||||
|
#
|
||||||
|
# 1. Installs the build tree and consumes it through an isolated fixture that
|
||||||
|
# records the target tuple (target, triple, compiler, linkage, reflection,
|
||||||
|
# modules) and runs one behaviour per module.
|
||||||
|
# 2. Re-configures the source tree for negative cases: unknown target,
|
||||||
|
# unsupported module on a target, and a missing external dependency. Each
|
||||||
|
# must fail at configure time with a useful message.
|
||||||
|
# 3. Re-configures the wasm subset positively to prove the allowlist accepts
|
||||||
|
# a pure computation selection without native networking/SQLite/reflection.
|
||||||
|
|
||||||
|
foreach(required IN ITEMS VOID_BUILD_DIR VOID_SOURCE_DIR VOID_TEST_SOURCE_DIR
|
||||||
|
VOID_TEST_ROOT VOID_CXX_COMPILER VOID_CTEST_COMMAND)
|
||||||
|
if(NOT DEFINED ${required} OR "${${required}}" STREQUAL "")
|
||||||
|
message(FATAL_ERROR "${required} is required")
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
|
||||||
|
file(REMOVE_RECURSE "${VOID_TEST_ROOT}")
|
||||||
|
file(MAKE_DIRECTORY "${VOID_TEST_ROOT}")
|
||||||
|
|
||||||
|
set(_gen_args "")
|
||||||
|
if(DEFINED VOID_GENERATOR AND NOT VOID_GENERATOR STREQUAL "")
|
||||||
|
list(APPEND _gen_args -G "${VOID_GENERATOR}")
|
||||||
|
endif()
|
||||||
|
if(DEFINED VOID_MAKE_PROGRAM AND NOT VOID_MAKE_PROGRAM STREQUAL "")
|
||||||
|
list(APPEND _gen_args "-DCMAKE_MAKE_PROGRAM=${VOID_MAKE_PROGRAM}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# ── 1. Install and consume the current target ─────────────────────────────────
|
||||||
|
set(_install_prefix "${VOID_TEST_ROOT}/install")
|
||||||
|
set(_install_command "${CMAKE_COMMAND}" --install "${VOID_BUILD_DIR}"
|
||||||
|
--prefix "${_install_prefix}")
|
||||||
|
if(DEFINED VOID_BUILD_CONFIG AND NOT VOID_BUILD_CONFIG STREQUAL "")
|
||||||
|
list(APPEND _install_command --config "${VOID_BUILD_CONFIG}")
|
||||||
|
endif()
|
||||||
|
execute_process(COMMAND ${_install_command} COMMAND_ERROR_IS_FATAL ANY)
|
||||||
|
|
||||||
|
set(_consumer_build "${VOID_TEST_ROOT}/TargetProfile")
|
||||||
|
set(_consumer_source "${VOID_TEST_SOURCE_DIR}/TargetProfile")
|
||||||
|
set(_no_external_deps
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_Threads=TRUE)
|
||||||
|
execute_process(
|
||||||
|
COMMAND "${CMAKE_COMMAND}" -S "${_consumer_source}" -B "${_consumer_build}"
|
||||||
|
${_gen_args}
|
||||||
|
"-DCMAKE_PREFIX_PATH=${_install_prefix}"
|
||||||
|
"-DCMAKE_CXX_COMPILER=${VOID_CXX_COMPILER}"
|
||||||
|
"-DVOID_EXPECTED_TARGET=${VOID_TARGET}"
|
||||||
|
${_no_external_deps}
|
||||||
|
COMMAND_ERROR_IS_FATAL ANY)
|
||||||
|
|
||||||
|
set(_consumer_build_command "${CMAKE_COMMAND}" --build "${_consumer_build}")
|
||||||
|
if(DEFINED VOID_BUILD_CONFIG AND NOT VOID_BUILD_CONFIG STREQUAL "")
|
||||||
|
list(APPEND _consumer_build_command --config "${VOID_BUILD_CONFIG}")
|
||||||
|
endif()
|
||||||
|
execute_process(COMMAND ${_consumer_build_command} COMMAND_ERROR_IS_FATAL ANY)
|
||||||
|
|
||||||
|
set(_profile_file "${_consumer_build}/target-profile.txt")
|
||||||
|
if(NOT EXISTS "${_profile_file}")
|
||||||
|
message(FATAL_ERROR "[TargetQualification] consumer did not record a profile")
|
||||||
|
endif()
|
||||||
|
file(READ "${_profile_file}" _profile)
|
||||||
|
foreach(_field IN ITEMS target triple compiler linkage reflection modules)
|
||||||
|
if(NOT _profile MATCHES "(^|\n)${_field}=")
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"[TargetQualification] profile misses '${_field}':\n${_profile}")
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
if(NOT _profile MATCHES "(^|\n)target=${VOID_TARGET}(\n|$)")
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"[TargetQualification] profile target mismatch (expected ${VOID_TARGET}):\n${_profile}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(NOT DEFINED VOID_CROSSCOMPILING OR NOT VOID_CROSSCOMPILING)
|
||||||
|
execute_process(
|
||||||
|
COMMAND "${VOID_CTEST_COMMAND}" --test-dir "${_consumer_build}"
|
||||||
|
--output-on-failure
|
||||||
|
COMMAND_ERROR_IS_FATAL ANY)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# ── 2. Negative and positive configure cases ─────────────────────────────────
|
||||||
|
set(_configure_result 0)
|
||||||
|
set(_configure_output "")
|
||||||
|
|
||||||
|
function(run_void_configure name)
|
||||||
|
set(_build_dir "${VOID_TEST_ROOT}/configure-${name}")
|
||||||
|
file(REMOVE_RECURSE "${_build_dir}")
|
||||||
|
execute_process(
|
||||||
|
COMMAND "${CMAKE_COMMAND}" -S "${VOID_SOURCE_DIR}" -B "${_build_dir}"
|
||||||
|
${_gen_args}
|
||||||
|
"-DCMAKE_CXX_COMPILER=${VOID_CXX_COMPILER}"
|
||||||
|
-DCMAKE_BUILD_TYPE=Debug
|
||||||
|
${ARGN}
|
||||||
|
RESULT_VARIABLE _result
|
||||||
|
OUTPUT_VARIABLE _stdout
|
||||||
|
ERROR_VARIABLE _stderr)
|
||||||
|
set(_configure_result "${_result}" PARENT_SCOPE)
|
||||||
|
set(_configure_output "${_stdout}${_stderr}" PARENT_SCOPE)
|
||||||
|
set(_configure_build_dir "${_build_dir}" PARENT_SCOPE)
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
function(expect_configure_failure name pattern)
|
||||||
|
run_void_configure("${name}" ${ARGN})
|
||||||
|
if(_configure_result EQUAL 0)
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"[TargetQualification] '${name}' configured successfully but "
|
||||||
|
"was expected to fail")
|
||||||
|
endif()
|
||||||
|
if(NOT _configure_output MATCHES "${pattern}")
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"[TargetQualification] '${name}' failed without matching "
|
||||||
|
"'${pattern}'. Output:\n${_configure_output}")
|
||||||
|
endif()
|
||||||
|
message(STATUS "[TargetQualification] ${name}: rejected as expected")
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
# Unknown target profile.
|
||||||
|
expect_configure_failure(unknown-target "Unknown VOID_TARGET"
|
||||||
|
-DVOID_TARGET=plan9
|
||||||
|
-DVOID_ENABLED_MODULES=Core
|
||||||
|
-DVOID_ENABLE_TESTING=OFF)
|
||||||
|
|
||||||
|
# Native module on the browser/Wasm target. IPC pulls IO/Async/Resilience,
|
||||||
|
# which are also outside the wasm allowlist.
|
||||||
|
expect_configure_failure(wasm-rejects-native
|
||||||
|
"Modules not supported on target 'wasm'"
|
||||||
|
-DVOID_TARGET=wasm
|
||||||
|
-DVOID_ENABLED_MODULES=IPC
|
||||||
|
-DVOID_ENABLE_TESTING=OFF)
|
||||||
|
|
||||||
|
# Native networking is rejected before Boost/OpenSSL are even resolved.
|
||||||
|
expect_configure_failure(wasm-rejects-net
|
||||||
|
"Modules not supported on target 'wasm'"
|
||||||
|
-DVOID_TARGET=wasm
|
||||||
|
-DVOID_ENABLED_MODULES=Net
|
||||||
|
-DVOID_ENABLE_TESTING=OFF)
|
||||||
|
|
||||||
|
# Missing external dependency fails with the dependency name.
|
||||||
|
expect_configure_failure(missing-sqlite "SQLite3"
|
||||||
|
-DVOID_ENABLED_MODULES=Sqlite
|
||||||
|
-DVOID_ENABLE_TESTING=OFF
|
||||||
|
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
|
||||||
|
|
||||||
|
# The pure subset must configure for wasm and record the target.
|
||||||
|
run_void_configure(wasm-subset
|
||||||
|
-DVOID_TARGET=wasm
|
||||||
|
-DVOID_ENABLED_MODULES=Data
|
||||||
|
-DVOID_ENABLE_TESTING=OFF)
|
||||||
|
if(NOT _configure_result EQUAL 0)
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"[TargetQualification] wasm subset failed to configure:\n${_configure_output}")
|
||||||
|
endif()
|
||||||
|
set(_manifest "${_configure_build_dir}/void-target-manifest.cmake")
|
||||||
|
if(NOT EXISTS "${_manifest}")
|
||||||
|
message(FATAL_ERROR "[TargetQualification] wasm subset wrote no manifest")
|
||||||
|
endif()
|
||||||
|
file(READ "${_manifest}" _manifest_text)
|
||||||
|
if(NOT _manifest_text MATCHES "VOID_TARGET_MANIFEST_TARGET \"wasm\"")
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"[TargetQualification] wasm manifest does not record target wasm:\n${_manifest_text}")
|
||||||
|
endif()
|
||||||
|
message(STATUS "[TargetQualification] wasm subset: configured and recorded")
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
#include <Void/Algorithms/GridRay.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cmath>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <limits>
|
||||||
|
#include <set>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
using Void::Algorithms::GridAxis;
|
||||||
|
using Void::Algorithms::GridCell;
|
||||||
|
using Void::Algorithms::GridFace;
|
||||||
|
using Void::Algorithms::GridRayIterator;
|
||||||
|
using Void::Algorithms::GridRayOptions;
|
||||||
|
using Void::Algorithms::GridRayStatus;
|
||||||
|
using Void::Algorithms::GridRayVisit;
|
||||||
|
using Void::Math::Vec3d;
|
||||||
|
|
||||||
|
[[nodiscard]] std::vector<GridRayVisit> take(GridRayIterator& iterator,
|
||||||
|
std::size_t count)
|
||||||
|
{
|
||||||
|
std::vector<GridRayVisit> visits;
|
||||||
|
for (std::size_t index = 0; index < count; ++index) {
|
||||||
|
auto visit = iterator.next();
|
||||||
|
if (!visit.has_value()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
visits.push_back(*visit);
|
||||||
|
}
|
||||||
|
return visits;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] GridCell cell(std::int64_t x, std::int64_t y, std::int64_t z)
|
||||||
|
{
|
||||||
|
return GridCell{.x = x, .y = y, .z = z};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_forward_corner_tie_order()
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{Vec3d{31.5, 31.5, 31.5}, Vec3d{1, 1, 1},
|
||||||
|
GridRayOptions{.max_steps = 10}};
|
||||||
|
const auto visits = take(iterator, 5);
|
||||||
|
Void::Testing::require(visits.size() == 5);
|
||||||
|
|
||||||
|
Void::Testing::expect(visits[0].cell == cell(31, 31, 31));
|
||||||
|
Void::Testing::expect(visits[0].face == GridFace{});
|
||||||
|
Void::Testing::expect_eq(visits[0].t, 0.0);
|
||||||
|
|
||||||
|
// Exact corner tie: x first, then y, then z.
|
||||||
|
Void::Testing::expect(visits[1].cell == cell(32, 31, 31));
|
||||||
|
Void::Testing::expect(visits[1].face.axis == GridAxis::x);
|
||||||
|
Void::Testing::expect_eq(visits[1].face.sign, 1);
|
||||||
|
Void::Testing::expect_eq(visits[1].t, 0.5);
|
||||||
|
|
||||||
|
Void::Testing::expect(visits[2].cell == cell(32, 32, 31));
|
||||||
|
Void::Testing::expect(visits[2].face.axis == GridAxis::y);
|
||||||
|
|
||||||
|
Void::Testing::expect(visits[3].cell == cell(32, 32, 32));
|
||||||
|
Void::Testing::expect(visits[3].face.axis == GridAxis::z);
|
||||||
|
|
||||||
|
Void::Testing::expect(visits[4].cell == cell(33, 32, 32));
|
||||||
|
Void::Testing::expect(visits[4].face.axis == GridAxis::x);
|
||||||
|
Void::Testing::expect_eq(visits[4].t, 1.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_reverse_corner()
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{Vec3d{32.5, 32.5, 32.5}, Vec3d{-1, -1, -1},
|
||||||
|
GridRayOptions{.max_steps = 10}};
|
||||||
|
const auto visits = take(iterator, 4);
|
||||||
|
Void::Testing::require(visits.size() == 4);
|
||||||
|
|
||||||
|
Void::Testing::expect(visits[0].cell == cell(32, 32, 32));
|
||||||
|
Void::Testing::expect(visits[1].cell == cell(31, 32, 32));
|
||||||
|
Void::Testing::expect(visits[1].face.axis == GridAxis::x);
|
||||||
|
Void::Testing::expect_eq(visits[1].face.sign, -1);
|
||||||
|
Void::Testing::expect(visits[2].cell == cell(31, 31, 32));
|
||||||
|
Void::Testing::expect(visits[3].cell == cell(31, 31, 31));
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_negative_origin()
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{Vec3d{-0.5, -0.5, -0.5}, Vec3d{-1, -1, -1},
|
||||||
|
GridRayOptions{.max_steps = 10}};
|
||||||
|
const auto visits = take(iterator, 4);
|
||||||
|
Void::Testing::require(visits.size() == 4);
|
||||||
|
Void::Testing::expect(visits[0].cell == cell(-1, -1, -1));
|
||||||
|
Void::Testing::expect(visits[3].cell == cell(-2, -2, -2));
|
||||||
|
Void::Testing::expect_eq(visits[3].t, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_axis_parallel()
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{Vec3d{0.5, 0.5, 0.5}, Vec3d{1, 0, 0},
|
||||||
|
GridRayOptions{.max_steps = 4}};
|
||||||
|
const auto visits = take(iterator, 3);
|
||||||
|
Void::Testing::require(visits.size() == 3);
|
||||||
|
for (std::size_t index = 0; index < visits.size(); ++index) {
|
||||||
|
Void::Testing::expect(visits[index].cell ==
|
||||||
|
cell(static_cast<std::int64_t>(index), 0, 0));
|
||||||
|
Void::Testing::expect(visits[index].cell.y == 0);
|
||||||
|
Void::Testing::expect(visits[index].cell.z == 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_start_on_boundary()
|
||||||
|
{
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{Vec3d{32.0, 0.5, 0.5}, Vec3d{1, 0, 0},
|
||||||
|
GridRayOptions{.max_steps = 2}};
|
||||||
|
const auto visits = take(iterator, 2);
|
||||||
|
Void::Testing::require(visits.size() == 2);
|
||||||
|
Void::Testing::expect(visits[0].cell == cell(32, 0, 0));
|
||||||
|
Void::Testing::expect(visits[1].cell == cell(33, 0, 0));
|
||||||
|
Void::Testing::expect_eq(visits[1].t, 1.0);
|
||||||
|
}
|
||||||
|
{
|
||||||
|
// Exactly on the boundary moving negative: the point is assigned to
|
||||||
|
// the positive cell, then leaves it immediately at t == 0.
|
||||||
|
GridRayIterator iterator{Vec3d{32.0, 0.5, 0.5}, Vec3d{-1, 0, 0},
|
||||||
|
GridRayOptions{.max_steps = 2}};
|
||||||
|
const auto visits = take(iterator, 2);
|
||||||
|
Void::Testing::require(visits.size() == 2);
|
||||||
|
Void::Testing::expect(visits[0].cell == cell(32, 0, 0));
|
||||||
|
Void::Testing::expect(visits[1].cell == cell(31, 0, 0));
|
||||||
|
Void::Testing::expect_eq(visits[1].t, 0.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_ending_exactly_on_boundary()
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{
|
||||||
|
Vec3d{0.5, 0.5, 0.5}, Vec3d{1, 0, 0},
|
||||||
|
GridRayOptions{.max_steps = 10, .max_distance = 0.5}};
|
||||||
|
const auto visits = take(iterator, 2);
|
||||||
|
Void::Testing::require(visits.size() == 2);
|
||||||
|
Void::Testing::expect(visits[1].cell == cell(1, 0, 0));
|
||||||
|
Void::Testing::expect_eq(visits[1].t, 0.5);
|
||||||
|
Void::Testing::expect(!iterator.next().has_value());
|
||||||
|
Void::Testing::expect(iterator.status() ==
|
||||||
|
GridRayStatus::exhausted_distance);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_zero_direction_yields_start_once()
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{Vec3d{2.5, 3.5, 4.5}, Vec3d{0, 0, 0},
|
||||||
|
GridRayOptions{.max_steps = 4}};
|
||||||
|
const auto visits = take(iterator, 4);
|
||||||
|
Void::Testing::require(visits.size() == 1);
|
||||||
|
Void::Testing::expect(visits[0].cell == cell(2, 3, 4));
|
||||||
|
Void::Testing::expect(iterator.status() == GridRayStatus::zero_direction);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_rejects_nonfinite_and_out_of_range()
|
||||||
|
{
|
||||||
|
GridRayIterator nan_origin{
|
||||||
|
Vec3d{std::numeric_limits<double>::quiet_NaN(), 0, 0},
|
||||||
|
Vec3d{1, 0, 0}};
|
||||||
|
Void::Testing::expect(!nan_origin.next().has_value());
|
||||||
|
Void::Testing::expect(nan_origin.status() ==
|
||||||
|
GridRayStatus::nonfinite_input);
|
||||||
|
|
||||||
|
GridRayIterator huge_origin{Vec3d{1e300, 0, 0}, Vec3d{1, 0, 0}};
|
||||||
|
Void::Testing::expect(!huge_origin.next().has_value());
|
||||||
|
Void::Testing::expect(huge_origin.status() ==
|
||||||
|
GridRayStatus::out_of_range);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_ray_step_exhaustion()
|
||||||
|
{
|
||||||
|
GridRayIterator iterator{Vec3d{0.5, 0.5, 0.5}, Vec3d{1, 0, 0},
|
||||||
|
GridRayOptions{.max_steps = 3}};
|
||||||
|
const auto visits = take(iterator, 10);
|
||||||
|
Void::Testing::expect_eq(visits.size(), std::size_t{3});
|
||||||
|
Void::Testing::expect(iterator.status() ==
|
||||||
|
GridRayStatus::exhausted_steps);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_raycast_first_occupied_and_chunk_order()
|
||||||
|
{
|
||||||
|
const std::set<GridCell> occupied{cell(2, 0, 0), cell(0, 0, 0)};
|
||||||
|
|
||||||
|
const auto query = [&occupied](const GridCell& value) {
|
||||||
|
return occupied.contains(value);
|
||||||
|
};
|
||||||
|
|
||||||
|
auto first = Void::Algorithms::raycast_grid(
|
||||||
|
Vec3d{0.5, 0.5, 0.5}, Vec3d{1, 0, 0}, query);
|
||||||
|
Void::Testing::require(first.hit.has_value());
|
||||||
|
// The start cell is occupied and reports no entry face.
|
||||||
|
Void::Testing::expect(first.hit->cell == cell(0, 0, 0));
|
||||||
|
Void::Testing::expect(first.hit->face == GridFace{});
|
||||||
|
|
||||||
|
const auto query_without_start = [](const GridCell& value) {
|
||||||
|
return value == cell(2, 0, 0);
|
||||||
|
};
|
||||||
|
auto later = Void::Algorithms::raycast_grid(
|
||||||
|
Vec3d{0.5, 0.5, 0.5}, Vec3d{1, 0, 0}, query_without_start);
|
||||||
|
Void::Testing::require(later.hit.has_value());
|
||||||
|
Void::Testing::expect(later.hit->cell == cell(2, 0, 0));
|
||||||
|
Void::Testing::expect(later.hit->face.axis == GridAxis::x);
|
||||||
|
Void::Testing::expect_eq(later.hit->face.sign, 1);
|
||||||
|
Void::Testing::expect_eq(later.visited, std::size_t{3});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test grid_raycast_miss_reports_status()
|
||||||
|
{
|
||||||
|
auto result = Void::Algorithms::raycast_grid(
|
||||||
|
Vec3d{0.5, 0.5, 0.5}, Vec3d{1, 0, 0},
|
||||||
|
[](const GridCell&) { return false; },
|
||||||
|
GridRayOptions{.max_steps = 4});
|
||||||
|
Void::Testing::expect(!result.hit.has_value());
|
||||||
|
Void::Testing::expect(result.visited == std::size_t{4});
|
||||||
|
Void::Testing::expect(result.status == GridRayStatus::exhausted_steps);
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
#include <Void/Algorithms/RevisionReadSet.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
using Void::Algorithms::ReadSetStatus;
|
||||||
|
using Void::Algorithms::ReadSetValidation;
|
||||||
|
using Void::Algorithms::RevisionReadSet;
|
||||||
|
|
||||||
|
using View = std::map<std::string, std::uint64_t>;
|
||||||
|
|
||||||
|
[[nodiscard]] auto lookup(const View& view)
|
||||||
|
{
|
||||||
|
return [&view](const std::string& key) -> std::optional<std::uint64_t> {
|
||||||
|
const auto found = view.find(key);
|
||||||
|
if (found == view.end()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return found->second;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test read_set_deduplicates_unchanged_reads()
|
||||||
|
{
|
||||||
|
RevisionReadSet set{1};
|
||||||
|
Void::Testing::expect(set.observe("chunk", 3) == ReadSetStatus::recorded);
|
||||||
|
Void::Testing::expect(set.observe("chunk", 3) == ReadSetStatus::unchanged);
|
||||||
|
Void::Testing::expect_eq(set.size(), std::size_t{1});
|
||||||
|
Void::Testing::expect_eq(set.revision_of("chunk"), std::uint64_t{3});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test read_set_detects_conflicting_observations()
|
||||||
|
{
|
||||||
|
RevisionReadSet set{1};
|
||||||
|
Void::Testing::expect(set.observe("chunk", 3) == ReadSetStatus::recorded);
|
||||||
|
Void::Testing::expect(set.observe("chunk", 4) ==
|
||||||
|
ReadSetStatus::conflicting);
|
||||||
|
Void::Testing::expect(set.conflicted());
|
||||||
|
|
||||||
|
// The first observation is retained, but the set cannot be published.
|
||||||
|
Void::Testing::expect_eq(set.revision_of("chunk"), std::uint64_t{3});
|
||||||
|
const View view{{"chunk", 3}};
|
||||||
|
Void::Testing::expect(set.validate(1, lookup(view)) ==
|
||||||
|
ReadSetValidation::conflicted);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test read_set_reports_capacity_exhaustion()
|
||||||
|
{
|
||||||
|
RevisionReadSet set{1, RevisionReadSet::Limits{.max_entries = 2}};
|
||||||
|
Void::Testing::expect(set.observe("a", 1) == ReadSetStatus::recorded);
|
||||||
|
Void::Testing::expect(set.observe("b", 1) == ReadSetStatus::recorded);
|
||||||
|
Void::Testing::expect(set.observe("c", 1) ==
|
||||||
|
ReadSetStatus::capacity_exceeded);
|
||||||
|
Void::Testing::expect(set.incomplete());
|
||||||
|
Void::Testing::expect_eq(set.size(), std::size_t{2});
|
||||||
|
|
||||||
|
const View view{{"a", 1}, {"b", 1}, {"c", 1}};
|
||||||
|
Void::Testing::expect(set.validate(1, lookup(view)) ==
|
||||||
|
ReadSetValidation::incomplete);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test read_set_validates_against_stable_view()
|
||||||
|
{
|
||||||
|
RevisionReadSet set{1};
|
||||||
|
Void::Testing::expect(set.observe("route", 10) == ReadSetStatus::recorded);
|
||||||
|
Void::Testing::expect(set.observe("support", 20) ==
|
||||||
|
ReadSetStatus::recorded);
|
||||||
|
|
||||||
|
View view{{"route", 10}, {"support", 20}};
|
||||||
|
Void::Testing::expect(set.validate(1, lookup(view)) ==
|
||||||
|
ReadSetValidation::valid);
|
||||||
|
|
||||||
|
// An unrelated edit does not invalidate the cached result.
|
||||||
|
view["unrelated"] = 99;
|
||||||
|
Void::Testing::expect(set.validate(1, lookup(view)) ==
|
||||||
|
ReadSetValidation::valid);
|
||||||
|
|
||||||
|
// A change to a consulted revision does.
|
||||||
|
view["support"] = 21;
|
||||||
|
Void::Testing::expect(set.validate(1, lookup(view)) ==
|
||||||
|
ReadSetValidation::invalidated);
|
||||||
|
|
||||||
|
// A missing consulted key does too.
|
||||||
|
view["support"] = 20;
|
||||||
|
view.erase("route");
|
||||||
|
Void::Testing::expect(set.validate(1, lookup(view)) ==
|
||||||
|
ReadSetValidation::invalidated);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test read_set_rejects_epoch_change_even_with_matching_revisions()
|
||||||
|
{
|
||||||
|
RevisionReadSet set{1};
|
||||||
|
Void::Testing::expect(set.observe("route", 10) == ReadSetStatus::recorded);
|
||||||
|
const View view{{"route", 10}};
|
||||||
|
Void::Testing::expect(set.validate(2, lookup(view)) ==
|
||||||
|
ReadSetValidation::epoch_changed);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test read_set_failed_search_frontier_opening()
|
||||||
|
{
|
||||||
|
// A failed search consulted a closed frontier at revision 0.
|
||||||
|
RevisionReadSet set{7};
|
||||||
|
Void::Testing::expect(set.observe("frontier", 0) ==
|
||||||
|
ReadSetStatus::recorded);
|
||||||
|
View view{{"frontier", 0}};
|
||||||
|
Void::Testing::expect(set.validate(7, lookup(view)) ==
|
||||||
|
ReadSetValidation::valid);
|
||||||
|
|
||||||
|
// The frontier opens: the cached failure must not be reused.
|
||||||
|
view["frontier"] = 1;
|
||||||
|
Void::Testing::expect(set.validate(7, lookup(view)) ==
|
||||||
|
ReadSetValidation::invalidated);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test read_set_rejects_empty_key_and_sorts_entries()
|
||||||
|
{
|
||||||
|
RevisionReadSet set{1};
|
||||||
|
Void::Testing::expect(set.observe("", 1) == ReadSetStatus::invalid_key);
|
||||||
|
Void::Testing::expect_eq(set.size(), std::size_t{0});
|
||||||
|
|
||||||
|
Void::Testing::expect(set.observe("b", 2) == ReadSetStatus::recorded);
|
||||||
|
Void::Testing::expect(set.observe("a", 1) == ReadSetStatus::recorded);
|
||||||
|
const auto& entries = set.entries();
|
||||||
|
Void::Testing::require(entries.size() == 2);
|
||||||
|
Void::Testing::expect_eq(entries.begin()->first, std::string{"a"});
|
||||||
|
}
|
||||||
@@ -44,7 +44,9 @@ namespace
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void write_raw_tar(const std::filesystem::path& path,
|
// Used only when the upstream LibArchive backend is absent; keep it
|
||||||
|
// compiled so the pure-C++ fallback path is covered in that build.
|
||||||
|
[[maybe_unused]] void write_raw_tar(const std::filesystem::path& path,
|
||||||
std::span<const ArchiveEntry> entries)
|
std::span<const ArchiveEntry> entries)
|
||||||
{
|
{
|
||||||
std::ofstream out{path, std::ios::binary | std::ios::trunc};
|
std::ofstream out{path, std::ios::binary | std::ios::trunc};
|
||||||
|
|||||||
@@ -1181,3 +1181,103 @@ Void::Testing::Test async_retry_matches_blocking_schedule_same_seed()
|
|||||||
expect_eq(async_log.calls(), std::size_t{6});
|
expect_eq(async_log.calls(), std::size_t{6});
|
||||||
expect(async_log.times == blocking_log.times);
|
expect(async_log.times == blocking_log.times);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test async_retry_backoff_stop_reason_mapping()
|
||||||
|
{
|
||||||
|
using R::RetryStopReason;
|
||||||
|
|
||||||
|
// A timeout from the backoff sleep is a deadline, not a user stop.
|
||||||
|
expect(R::RetryStopReason::deadline_exceeded ==
|
||||||
|
detail::retry_backoff_stop_reason(make_async_error(AsyncErrorCode::timeout)));
|
||||||
|
|
||||||
|
// Everything else is terminal and must never retry without a wait.
|
||||||
|
for (const AsyncErrorCode code : {AsyncErrorCode::cancelled,
|
||||||
|
AsyncErrorCode::stopped,
|
||||||
|
AsyncErrorCode::closed,
|
||||||
|
AsyncErrorCode::overloaded,
|
||||||
|
AsyncErrorCode::backend_error,
|
||||||
|
AsyncErrorCode::limit_exceeded}) {
|
||||||
|
expect(R::RetryStopReason::stop_requested ==
|
||||||
|
detail::retry_backoff_stop_reason(make_async_error(code)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// A non-Async domain error is treated conservatively as a stop.
|
||||||
|
expect(R::RetryStopReason::stop_requested ==
|
||||||
|
detail::retry_backoff_stop_reason(Void::Result::Error{
|
||||||
|
Void::Result::ErrorKind::internal,
|
||||||
|
"foreign domain",
|
||||||
|
Void::Result::ErrorCode{.domain = 999, .value = 1}}));
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test async_retry_stop_poll_handshake_alternation()
|
||||||
|
{
|
||||||
|
// Both deterministic interleavings of "stop requested" and "timer polled"
|
||||||
|
// must produce exactly one resume, one attempt and one terminal result.
|
||||||
|
for (const bool stop_first : {true, false}) {
|
||||||
|
ManualExecutor exec;
|
||||||
|
ManualClock clock;
|
||||||
|
auto q = make_queue(exec, clock);
|
||||||
|
|
||||||
|
std::stop_source source;
|
||||||
|
int calls = 0;
|
||||||
|
RetryProbe<IntOut> probe;
|
||||||
|
auto task = collect(
|
||||||
|
retry_async(constant_spec(10ms, 5),
|
||||||
|
[&calls]() -> std::expected<int, std::string> {
|
||||||
|
++calls;
|
||||||
|
return std::unexpected{std::string{"e"}};
|
||||||
|
},
|
||||||
|
*q,
|
||||||
|
OperationOptions{.stop = source.get_token()}),
|
||||||
|
&probe);
|
||||||
|
start(task);
|
||||||
|
expect_eq(calls, 1);
|
||||||
|
advance_clock(clock, 10ms);
|
||||||
|
|
||||||
|
if (stop_first) {
|
||||||
|
expect(source.request_stop());
|
||||||
|
(void)q->poll_expired();
|
||||||
|
} else {
|
||||||
|
expect_eq(q->poll_expired(), std::size_t{1});
|
||||||
|
expect(source.request_stop());
|
||||||
|
}
|
||||||
|
|
||||||
|
expect_eq(exec.drain(), std::size_t{1});
|
||||||
|
expect(task.done());
|
||||||
|
expect_stop(probe, R::RetryStopReason::stop_requested, 1);
|
||||||
|
expect_eq(calls, 1);
|
||||||
|
expect_eq(q->active_timers(), std::size_t{0});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test async_retry_throwing_classifier_propagates()
|
||||||
|
{
|
||||||
|
ManualExecutor exec;
|
||||||
|
ManualClock clock;
|
||||||
|
auto q = make_queue(exec, clock);
|
||||||
|
|
||||||
|
int calls = 0;
|
||||||
|
RetryProbe<IntOut> probe;
|
||||||
|
auto classifier = [](const std::string&) -> R::AttemptOutcome {
|
||||||
|
throw std::runtime_error{"classifier threw"};
|
||||||
|
};
|
||||||
|
auto task = collect(
|
||||||
|
retry_async(constant_spec(10ms, 5),
|
||||||
|
[&calls]() -> std::expected<int, std::string> {
|
||||||
|
++calls;
|
||||||
|
return std::unexpected{std::string{"e"}};
|
||||||
|
},
|
||||||
|
*q,
|
||||||
|
{},
|
||||||
|
classifier),
|
||||||
|
&probe);
|
||||||
|
start(task);
|
||||||
|
|
||||||
|
// The classifier exception escapes the retry task; nothing is retried and
|
||||||
|
// no timer is left armed.
|
||||||
|
expect(task.done());
|
||||||
|
expect(probe.threw);
|
||||||
|
expect_eq(probe.what, std::string{"classifier threw"});
|
||||||
|
expect_eq(calls, 1);
|
||||||
|
expect_eq(q->active_timers(), std::size_t{0});
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
#include <Void/Async/PublicationGatedQueue.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <future>
|
||||||
|
#include <memory>
|
||||||
|
#include <thread>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
struct Token {
|
||||||
|
std::uint64_t epoch{0};
|
||||||
|
std::uint64_t revision{0};
|
||||||
|
|
||||||
|
[[nodiscard]] bool operator==(const Token&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] Token token(std::uint64_t epoch, std::uint64_t revision)
|
||||||
|
{
|
||||||
|
return Token{.epoch = epoch, .revision = revision};
|
||||||
|
}
|
||||||
|
|
||||||
|
using Queue =
|
||||||
|
Void::Async::PublicationGatedQueue<std::unique_ptr<int>, Token>;
|
||||||
|
using Status = Queue::Status;
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test gated_queue_rejects_stale_publication_without_moving()
|
||||||
|
{
|
||||||
|
Queue queue{token(1, 1), Queue::Limits{.capacity = 4}};
|
||||||
|
Void::Testing::require(queue.publish(token(1, 2)));
|
||||||
|
|
||||||
|
auto payload = std::make_unique<int>(7);
|
||||||
|
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(payload)) ==
|
||||||
|
Status::publication_changed);
|
||||||
|
// The payload was not moved and the queue is unchanged.
|
||||||
|
Void::Testing::require(payload != nullptr);
|
||||||
|
Void::Testing::expect_eq(*payload, 7);
|
||||||
|
Void::Testing::expect_eq(queue.size(), std::size_t{0});
|
||||||
|
|
||||||
|
Void::Testing::expect(queue.try_submit(token(1, 2), std::move(payload)) ==
|
||||||
|
Status::admitted);
|
||||||
|
Void::Testing::expect(payload == nullptr);
|
||||||
|
Void::Testing::expect_eq(queue.size(), std::size_t{1});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test gated_queue_saturation_and_capacity_reuse()
|
||||||
|
{
|
||||||
|
Queue queue{token(1, 1), Queue::Limits{.capacity = 1}};
|
||||||
|
auto first = std::make_unique<int>(1);
|
||||||
|
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(first)) ==
|
||||||
|
Status::admitted);
|
||||||
|
|
||||||
|
auto second = std::make_unique<int>(2);
|
||||||
|
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(second)) ==
|
||||||
|
Status::saturated);
|
||||||
|
Void::Testing::require(second != nullptr);
|
||||||
|
|
||||||
|
auto popped = queue.try_pop();
|
||||||
|
Void::Testing::require(popped.has_value());
|
||||||
|
Void::Testing::expect_eq(**popped, 1);
|
||||||
|
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(second)) ==
|
||||||
|
Status::admitted);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test gated_queue_closed()
|
||||||
|
{
|
||||||
|
Queue queue{token(1, 1)};
|
||||||
|
auto pending = std::make_unique<int>(3);
|
||||||
|
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(pending)) ==
|
||||||
|
Status::admitted);
|
||||||
|
queue.close();
|
||||||
|
Void::Testing::expect(!queue.publish(token(1, 2)));
|
||||||
|
Void::Testing::expect(queue.closed());
|
||||||
|
|
||||||
|
auto rejected = std::make_unique<int>(4);
|
||||||
|
Void::Testing::expect(queue.try_submit(token(1, 1), std::move(rejected)) ==
|
||||||
|
Status::closed);
|
||||||
|
Void::Testing::require(rejected != nullptr);
|
||||||
|
|
||||||
|
// Already admitted work can still be drained.
|
||||||
|
auto popped = queue.try_pop();
|
||||||
|
Void::Testing::require(popped.has_value());
|
||||||
|
Void::Testing::expect_eq(**popped, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test gated_queue_admitted_work_finishes_once()
|
||||||
|
{
|
||||||
|
Queue queue{token(1, 1)};
|
||||||
|
auto payload = std::make_unique<int>(9);
|
||||||
|
Void::Testing::require(queue.try_submit(token(1, 1), std::move(payload)) ==
|
||||||
|
Status::admitted);
|
||||||
|
|
||||||
|
auto first = queue.try_pop();
|
||||||
|
Void::Testing::require(first.has_value());
|
||||||
|
Void::Testing::expect_eq(**first, 9);
|
||||||
|
Void::Testing::expect(!queue.try_pop().has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test gated_queue_stale_submission_after_concurrent_publish()
|
||||||
|
{
|
||||||
|
Queue queue{token(1, 1)};
|
||||||
|
std::promise<void> validated;
|
||||||
|
std::promise<void> published;
|
||||||
|
std::atomic<Status> status{Status::admitted};
|
||||||
|
std::unique_ptr<int> retained;
|
||||||
|
|
||||||
|
std::thread producer{[&] {
|
||||||
|
auto payload = std::make_unique<int>(5);
|
||||||
|
validated.set_value();
|
||||||
|
published.get_future().wait();
|
||||||
|
status = queue.try_submit(token(1, 1), std::move(payload));
|
||||||
|
retained = std::move(payload);
|
||||||
|
}};
|
||||||
|
|
||||||
|
validated.get_future().wait();
|
||||||
|
// Same epoch, newer revision: the producer's retained publication is
|
||||||
|
// obsolete before its submission.
|
||||||
|
Void::Testing::require(queue.publish(token(1, 2)));
|
||||||
|
published.set_value();
|
||||||
|
producer.join();
|
||||||
|
|
||||||
|
Void::Testing::expect(status.load() == Status::publication_changed);
|
||||||
|
Void::Testing::require(retained != nullptr);
|
||||||
|
Void::Testing::expect_eq(*retained, 5);
|
||||||
|
Void::Testing::expect_eq(queue.size(), std::size_t{0});
|
||||||
|
|
||||||
|
// A fresh producer can submit against the new publication.
|
||||||
|
auto fresh = std::make_unique<int>(6);
|
||||||
|
Void::Testing::expect(queue.try_submit(token(1, 2), std::move(fresh)) ==
|
||||||
|
Status::admitted);
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// @requires-reflection
|
||||||
#include <Void/Configuration/Argparse.hpp>
|
#include <Void/Configuration/Argparse.hpp>
|
||||||
#include <Void/Testing/Assert.hpp>
|
#include <Void/Testing/Assert.hpp>
|
||||||
#include <Void/Testing/Test.hpp>
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// @requires-reflection
|
||||||
#include <Void/Configuration/Bind.hpp>
|
#include <Void/Configuration/Bind.hpp>
|
||||||
#include <Void/Configuration/Config.hpp>
|
#include <Void/Configuration/Config.hpp>
|
||||||
#include <Void/Testing/Assert.hpp>
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// @requires-reflection
|
||||||
#include <Void/Configuration/Bind.hpp>
|
#include <Void/Configuration/Bind.hpp>
|
||||||
#include <Void/Configuration/Config.hpp>
|
#include <Void/Configuration/Config.hpp>
|
||||||
#include <Void/Testing/Assert.hpp>
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// @requires-reflection
|
||||||
#include <Void/Configuration/Bind.hpp>
|
#include <Void/Configuration/Bind.hpp>
|
||||||
#include <Void/Configuration/Config.hpp>
|
#include <Void/Configuration/Config.hpp>
|
||||||
#include <Void/Configuration/Schema.hpp>
|
#include <Void/Configuration/Schema.hpp>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// @requires-reflection
|
||||||
#include <Void/Async/Executor.hpp>
|
#include <Void/Async/Executor.hpp>
|
||||||
#include <Void/Async/Task.hpp>
|
#include <Void/Async/Task.hpp>
|
||||||
#include <Void/Configuration/ReloadController.hpp>
|
#include <Void/Configuration/ReloadController.hpp>
|
||||||
|
|||||||
@@ -0,0 +1,227 @@
|
|||||||
|
#include <Void/Containers/AccountLedger.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <limits>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
|
||||||
|
using Void::Containers::AccountLedger;
|
||||||
|
using Void::Containers::LedgerDebit;
|
||||||
|
using Void::Containers::LedgerQuantity;
|
||||||
|
using Void::Containers::LedgerStatus;
|
||||||
|
using Void::Containers::ReservationPhase;
|
||||||
|
|
||||||
|
[[nodiscard]] LedgerDebit debit(std::string account, LedgerQuantity quantity)
|
||||||
|
{
|
||||||
|
return LedgerDebit{.account = std::move(account), .quantity = quantity};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] LedgerQuantity balance(const AccountLedger& ledger,
|
||||||
|
const std::string& account)
|
||||||
|
{
|
||||||
|
return ledger.account(account)->balance;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_reserve_transfer_conserves_total()
|
||||||
|
{
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 10, 10));
|
||||||
|
Void::Testing::require(ledger.create_account("b", "bob", 0, 10));
|
||||||
|
|
||||||
|
auto reserved = ledger.reserve("op1", {debit("a", 4)});
|
||||||
|
Void::Testing::expect(reserved.status == LedgerStatus::committed);
|
||||||
|
Void::Testing::expect(reserved.phase == ReservationPhase::held);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{6});
|
||||||
|
Void::Testing::expect_eq(ledger.total(), LedgerQuantity{10});
|
||||||
|
|
||||||
|
auto delivered = ledger.transfer("op1", "b");
|
||||||
|
Void::Testing::expect(delivered.status == LedgerStatus::committed);
|
||||||
|
Void::Testing::expect(delivered.phase == ReservationPhase::delivered);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{4});
|
||||||
|
Void::Testing::expect_eq(ledger.account("b")->owner, std::string{"bob"});
|
||||||
|
Void::Testing::expect_eq(ledger.total(), LedgerQuantity{10});
|
||||||
|
|
||||||
|
// Repeating the same delivery applies nothing twice.
|
||||||
|
auto replay = ledger.transfer("op1", "b");
|
||||||
|
Void::Testing::expect(replay.status == LedgerStatus::replayed);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{4});
|
||||||
|
Void::Testing::expect_eq(ledger.total(), LedgerQuantity{10});
|
||||||
|
|
||||||
|
// A different destination for the same operation is a conflict.
|
||||||
|
auto conflict = ledger.transfer("op1", "a");
|
||||||
|
Void::Testing::expect(conflict.status == LedgerStatus::invalid_state);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{4});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_two_claimants_last_unit()
|
||||||
|
{
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 1));
|
||||||
|
|
||||||
|
Void::Testing::expect(ledger.reserve("first", {debit("a", 1)}).status ==
|
||||||
|
LedgerStatus::committed);
|
||||||
|
auto second = ledger.reserve("second", {debit("a", 1)});
|
||||||
|
Void::Testing::expect(second.status == LedgerStatus::insufficient_balance);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{0});
|
||||||
|
|
||||||
|
Void::Testing::expect(ledger.release("first").status ==
|
||||||
|
LedgerStatus::committed);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{1});
|
||||||
|
Void::Testing::expect(ledger.reserve("second", {debit("a", 1)}).status ==
|
||||||
|
LedgerStatus::committed);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_multi_account_reservation_is_atomic()
|
||||||
|
{
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 5));
|
||||||
|
Void::Testing::require(ledger.create_account("b", "bob", 1));
|
||||||
|
|
||||||
|
auto failed = ledger.reserve("op", {debit("a", 3), debit("b", 2)});
|
||||||
|
Void::Testing::expect(failed.status == LedgerStatus::insufficient_balance);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{5});
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{1});
|
||||||
|
Void::Testing::expect_eq(ledger.operation_count(), std::size_t{0});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_cancel_before_pickup()
|
||||||
|
{
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 7));
|
||||||
|
Void::Testing::require(ledger.reserve("op", {debit("a", 3)}).committed());
|
||||||
|
|
||||||
|
auto released = ledger.release("op");
|
||||||
|
Void::Testing::expect(released.status == LedgerStatus::committed);
|
||||||
|
Void::Testing::expect(released.phase == ReservationPhase::released);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{7});
|
||||||
|
|
||||||
|
Void::Testing::expect(ledger.release("op").status == LedgerStatus::replayed);
|
||||||
|
Void::Testing::expect(ledger.transfer("op", "a").status ==
|
||||||
|
LedgerStatus::released);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{7});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_cancel_during_delivery()
|
||||||
|
{
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 7));
|
||||||
|
Void::Testing::require(ledger.create_account("b", "bob", 0, 2));
|
||||||
|
Void::Testing::require(ledger.reserve("op", {debit("a", 3)}).committed());
|
||||||
|
|
||||||
|
auto blocked = ledger.transfer("op", "b");
|
||||||
|
Void::Testing::expect(blocked.status == LedgerStatus::capacity_exhausted);
|
||||||
|
Void::Testing::expect(blocked.phase == ReservationPhase::held);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{0});
|
||||||
|
|
||||||
|
// The reservation is still held and can be cancelled.
|
||||||
|
Void::Testing::expect(ledger.release("op").status ==
|
||||||
|
LedgerStatus::committed);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{7});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_replay_after_restore()
|
||||||
|
{
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 10));
|
||||||
|
Void::Testing::require(ledger.create_account("b", "bob", 0));
|
||||||
|
Void::Testing::require(ledger.reserve("op", {debit("a", 4)}).committed());
|
||||||
|
|
||||||
|
const auto partially_completed = ledger.save();
|
||||||
|
|
||||||
|
auto restored = AccountLedger::restore(partially_completed);
|
||||||
|
Void::Testing::require(restored.has_value());
|
||||||
|
Void::Testing::expect(restored->transfer("op", "b").status ==
|
||||||
|
LedgerStatus::committed);
|
||||||
|
Void::Testing::expect_eq(balance(*restored, "b"), LedgerQuantity{4});
|
||||||
|
|
||||||
|
const auto delivered = restored->save();
|
||||||
|
auto after_delivery = AccountLedger::restore(delivered);
|
||||||
|
Void::Testing::require(after_delivery.has_value());
|
||||||
|
Void::Testing::expect(after_delivery->transfer("op", "b").status ==
|
||||||
|
LedgerStatus::replayed);
|
||||||
|
Void::Testing::expect_eq(balance(*after_delivery, "b"), LedgerQuantity{4});
|
||||||
|
|
||||||
|
// Restoring the earlier snapshot replays the delivery exactly once.
|
||||||
|
auto replay_world = AccountLedger::restore(partially_completed);
|
||||||
|
Void::Testing::require(replay_world.has_value());
|
||||||
|
Void::Testing::expect(replay_world->transfer("op", "b").status ==
|
||||||
|
LedgerStatus::committed);
|
||||||
|
Void::Testing::expect_eq(balance(*replay_world, "b"), LedgerQuantity{4});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_overflow_is_rejected()
|
||||||
|
{
|
||||||
|
constexpr auto kMax = std::numeric_limits<LedgerQuantity>::max();
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::require(ledger.create_account("a1", "alice", kMax));
|
||||||
|
Void::Testing::require(ledger.create_account("a2", "alice", kMax));
|
||||||
|
Void::Testing::require(ledger.create_account("b", "bob", 0));
|
||||||
|
Void::Testing::require(
|
||||||
|
ledger.reserve("op", {debit("a1", kMax), debit("a2", kMax)})
|
||||||
|
.committed());
|
||||||
|
|
||||||
|
// The reserved total cannot be represented in one quantity.
|
||||||
|
auto overflowed = ledger.transfer("op", "b");
|
||||||
|
Void::Testing::expect(overflowed.status == LedgerStatus::overflow);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{0});
|
||||||
|
Void::Testing::expect(ledger.release("op").status ==
|
||||||
|
LedgerStatus::committed);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_operation_id_conflict()
|
||||||
|
{
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 10));
|
||||||
|
Void::Testing::require(ledger.reserve("op", {debit("a", 1)}).committed());
|
||||||
|
|
||||||
|
auto conflict = ledger.reserve("op", {debit("a", 2)});
|
||||||
|
Void::Testing::expect(conflict.status == LedgerStatus::invalid_state);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{9});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_account_limits()
|
||||||
|
{
|
||||||
|
AccountLedger ledger;
|
||||||
|
Void::Testing::expect(!ledger.create_account("a", "alice", 5, 4));
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 5, 10));
|
||||||
|
Void::Testing::expect(!ledger.create_account("a", "other", 0, 10));
|
||||||
|
Void::Testing::expect(!ledger.set_capacity("a", 4));
|
||||||
|
Void::Testing::require(ledger.set_capacity("a", 8));
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_operation_limit()
|
||||||
|
{
|
||||||
|
AccountLedger ledger{AccountLedger::Limits{.max_accounts = 4,
|
||||||
|
.max_operations = 1}};
|
||||||
|
Void::Testing::require(ledger.create_account("a", "alice", 10));
|
||||||
|
Void::Testing::require(ledger.reserve("one", {debit("a", 1)}).committed());
|
||||||
|
auto limited = ledger.reserve("two", {debit("a", 1)});
|
||||||
|
Void::Testing::expect(limited.status == LedgerStatus::limit_exceeded);
|
||||||
|
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{9});
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test account_ledger_restore_rejects_invalid_state()
|
||||||
|
{
|
||||||
|
AccountLedger::State bad_balance;
|
||||||
|
bad_balance.accounts.emplace(
|
||||||
|
"a", AccountLedger::AccountState{.owner = "alice",
|
||||||
|
.balance = 5,
|
||||||
|
.capacity = 4});
|
||||||
|
Void::Testing::expect(!AccountLedger::restore(bad_balance).has_value());
|
||||||
|
|
||||||
|
AccountLedger::State dangling_operation;
|
||||||
|
dangling_operation.accounts.emplace(
|
||||||
|
"a", AccountLedger::AccountState{.owner = "alice", .balance = 1});
|
||||||
|
dangling_operation.operations.emplace(
|
||||||
|
"op", AccountLedger::OperationState{
|
||||||
|
.sources = {debit("missing", 1)},
|
||||||
|
.phase = ReservationPhase::held,
|
||||||
|
.destination = {}});
|
||||||
|
Void::Testing::expect(!AccountLedger::restore(dangling_operation).has_value());
|
||||||
|
}
|
||||||
@@ -16,9 +16,13 @@ namespace
|
|||||||
// @tag reflection
|
// @tag reflection
|
||||||
Void::Testing::Test debug_dump_reflects_struct_elements()
|
Void::Testing::Test debug_dump_reflects_struct_elements()
|
||||||
{
|
{
|
||||||
|
#if !VOID_HAS_CXX26_REFLECTION
|
||||||
|
Void::Testing::skip("C++26 reflection is not available");
|
||||||
|
#else
|
||||||
std::vector<P> v{{1, 2}, {3, 4}};
|
std::vector<P> v{{1, 2}, {3, 4}};
|
||||||
Void::Testing::expect_eq(Void::Containers::debug_dump(v),
|
Void::Testing::expect_eq(Void::Containers::debug_dump(v),
|
||||||
std::string{"[P{x: 1, y: 2}, P{x: 3, y: 4}]"});
|
std::string{"[P{x: 1, y: 2}, P{x: 3, y: 4}]"});
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
// @tag reflection
|
// @tag reflection
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ Void::Testing::Test lru_get_promotes_entry()
|
|||||||
c.put(1, "a");
|
c.put(1, "a");
|
||||||
c.put(2, "b");
|
c.put(2, "b");
|
||||||
c.put(3, "c");
|
c.put(3, "c");
|
||||||
c.get(1); // promote 1 to MRU
|
(void)c.get(1); // promote 1 to MRU
|
||||||
c.put(4, "d"); // evicts 2 (now LRU)
|
c.put(4, "d"); // evicts 2 (now LRU)
|
||||||
Void::Testing::expect(c.contains(1));
|
Void::Testing::expect(c.contains(1));
|
||||||
Void::Testing::expect(!c.contains(2));
|
Void::Testing::expect(!c.contains(2));
|
||||||
@@ -106,7 +106,7 @@ Void::Testing::Test lru_peek_does_not_promote()
|
|||||||
c.put(1, "a");
|
c.put(1, "a");
|
||||||
c.put(2, "b");
|
c.put(2, "b");
|
||||||
c.put(3, "c");
|
c.put(3, "c");
|
||||||
c.peek(1); // peek 1 but do NOT promote
|
(void)c.peek(1); // peek 1 but do NOT promote
|
||||||
c.put(4, "d"); // evicts 1 (still LRU despite peek)
|
c.put(4, "d"); // evicts 1 (still LRU despite peek)
|
||||||
Void::Testing::expect(!c.contains(1));
|
Void::Testing::expect(!c.contains(1));
|
||||||
}
|
}
|
||||||
|
|||||||
Loaded 100 of 146 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user