Initial commit
This commit is contained in:
commit
71712b07db
263 files changed
+83991
No files matched your search
@@ -0,0 +1,5 @@
|
||||
[build]
|
||||
target = "x86_64-unknown-linux-musl"
|
||||
|
||||
[target.x86_64-unknown-linux-musl]
|
||||
rustflags = ["-C", "link-self-contained=no"]
|
||||
@@ -0,0 +1,14 @@
|
||||
<!-- SPDX-FileCopyrightText: 2026 amurcanov -->
|
||||
<!-- SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 -->
|
||||
|
||||
# csqtt dataplane
|
||||
|
||||
Toolchain target: Rust 1.97.1, edition 2024, x86_64-unknown-linux-musl.
|
||||
|
||||
The packet data plane runs on one dedicated thread hosting a `current_thread` Tokio runtime created once per attempt; UDP and TUN I/O go through epoll readiness (`AsyncFd`, `try_io`) with the client's syscall semantics: `recvmmsg` (`MSG_DONTWAIT|MSG_WAITFORONE`) on receive and `sendmmsg` (`MSG_DONTWAIT`) on transmit. All buffers live in fixed pools allocated at startup — `recvmmsg` batch slots, `UDP_TX_SLOTS`, `TUN_TX_SLOTS` — so steady-state RSS never grows beyond that ceiling. The hot path is allocation-free and sans-io: `tokio_io.rs` performs I/O only, all protocol decisions stay in `protocol.rs` behind the `PacketSink`/`DataplaneLogic` traits.
|
||||
|
||||
The event loop is a single biased `tokio::select!`; commands arrive through a bounded `tokio::sync::mpsc`, wake-ups come from readiness events rather than polling. Per-stream Tokio mpsc packet fanout and O(N) worker probing are deliberately not used by the TUN route path. Fatal dataplane termination is surfaced to `main.rs`, which performs orderly server shutdown so an external process supervisor can restart the process.
|
||||
|
||||
Run `build_linux.bat --tests` or `./build_linux.sh --tests` before making a release asset.
|
||||
|
||||
Both scripts verify formatting, compile all Linux musl targets, and run Clippy with warnings denied. `build_linux.bat` runs the same checks in CI by default and **compiles** Linux musl test binaries; Windows cannot execute those ELF binaries. On a Linux host, `build_linux.sh --tests` also **executes** the Linux musl test suite. The final release binaries are linked for `x86_64-unknown-linux-musl`, `aarch64-unknown-linux-musl`, and `armv7-unknown-linux-musleabihf`, then copied to `app/src/main/assets/csqtt-linux-amd64`, `csqtt-linux-arm64`, and `csqtt-linux-armv7`; they are selected from the VPS architecture before upload.
|
||||
Generated
+1999
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,66 @@
|
||||
# SPDX-FileCopyrightText: 2026 amurcanov
|
||||
# SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
[package]
|
||||
name = "csqtt"
|
||||
version = "2.1.9"
|
||||
edition = "2024"
|
||||
rust-version = "1.97.1"
|
||||
license = "PolyForm-Noncommercial-1.0.0"
|
||||
|
||||
[[bin]]
|
||||
name = "csqtt"
|
||||
path = "main.rs"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
diagnostics = []
|
||||
|
||||
[dependencies]
|
||||
aes = "0.9.2"
|
||||
anyhow = "1.0"
|
||||
|
||||
axum = { version = "0.8", default-features = false, features = ["http1", "json", "tokio"] }
|
||||
axum-server = { version = "0.8.0", default-features = false, features = ["tls-rustls-no-provider"] }
|
||||
base64 = "0.22"
|
||||
bytes = "1.12.1"
|
||||
chrono = "0.4"
|
||||
clap = { version = "4.5", features = ["derive", "env"] }
|
||||
crossbeam-queue = "0.3.13"
|
||||
ctr = "0.10.1"
|
||||
dashmap = "6.1"
|
||||
hex = "0.4"
|
||||
hkdf = "0.13.0"
|
||||
libc = "0.2"
|
||||
rand = "0.8"
|
||||
rcgen = { version = "0.13", default-features = false, features = ["aws_lc_rs", "pem"] }
|
||||
rusqlite = { version = "0.37", features = ["bundled"] }
|
||||
aws-lc-rs = "1.18.0"
|
||||
rustls = { version = "0.23", default-features = false, features = ["aws_lc_rs", "std", "tls12"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
sha2 = "0.11.0"
|
||||
slab = "0.4"
|
||||
socket2 = "0.6"
|
||||
subtle = "2.6"
|
||||
tokio = { version = "1.53.1", features = ["macros", "rt-multi-thread", "net", "signal", "sync", "time", "fs", "process", "io-util"] }
|
||||
tokio-rustls = { version = "0.26", default-features = false, features = ["aws_lc_rs", "tls12"] }
|
||||
tokio-util = { version = "0.7", features = ["io"] }
|
||||
tun = "=0.8.14"
|
||||
x25519-dalek = { version = "2.0", features = ["static_secrets"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
snmalloc-rs = { version = "0.7.5", default-features = false, features = ["build_cc", "usewait-on-address"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1.53.1", features = ["test-util"] }
|
||||
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
panic = "unwind"
|
||||
strip = true
|
||||
debug = false
|
||||
incremental = false
|
||||
overflow-checks = false
|
||||
@@ -0,0 +1,213 @@
|
||||
@REM SPDX-FileCopyrightText: 2026 amurcanov
|
||||
@REM SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
@echo off
|
||||
setlocal EnableDelayedExpansion
|
||||
|
||||
set "BUILD_SCRIPT=%~f0"
|
||||
set "SERVER_DIR=%~dp0"
|
||||
set "PROJECT_ROOT=%~dp0..\"
|
||||
set "LINUX_TARGET_DIR=%PROJECT_ROOT%build\csqtt-uring-linux"
|
||||
set "CLIPPY_TARGET_DIR=%PROJECT_ROOT%build\csqtt-uring-linux-clippy"
|
||||
set "CARGO_TARGET_DIR=%LINUX_TARGET_DIR%"
|
||||
set "ASSETS_DIR=%PROJECT_ROOT%app\src\main\assets"
|
||||
set "PROVENANCE_SCRIPT=%PROJECT_ROOT%scripts\server_asset_provenance.ps1"
|
||||
set "VARIANT_RUNNER=%SERVER_DIR%build_linux_variants.ps1"
|
||||
set "RUN_TESTS="
|
||||
set "DIAGNOSTICS="
|
||||
|
||||
if /I "%~1"=="--build-variant" goto build_variant_worker
|
||||
if /I "%~1"=="--test-zig-cc" goto test_zig_cc
|
||||
if /I "%~1"=="--test-zig-cxx" goto test_zig_cxx
|
||||
|
||||
:parse_args
|
||||
if "%~1"=="" goto args_ready
|
||||
if /I "%~1"=="--tests" (
|
||||
set "RUN_TESTS=1"
|
||||
shift
|
||||
goto parse_args
|
||||
)
|
||||
if /I "%~1"=="--no-tests" (
|
||||
set "RUN_TESTS=0"
|
||||
shift
|
||||
goto parse_args
|
||||
)
|
||||
if /I "%~1"=="--diagnostics" (
|
||||
set "DIAGNOSTICS=1"
|
||||
shift
|
||||
goto parse_args
|
||||
)
|
||||
echo Usage: build_linux.bat [--tests^|--no-tests] [--diagnostics]
|
||||
goto fail
|
||||
|
||||
:args_ready
|
||||
if defined CI if not defined RUN_TESTS set "RUN_TESTS=1"
|
||||
|
||||
if not defined RUN_TESTS (
|
||||
choice /C YN /N /M "Run fmt, clippy and Linux test compilation before build? [Y/N]: "
|
||||
if errorlevel 2 (
|
||||
set "RUN_TESTS=0"
|
||||
) else (
|
||||
set "RUN_TESTS=1"
|
||||
)
|
||||
)
|
||||
|
||||
set "CARGO_FEATURES="
|
||||
if defined DIAGNOSTICS set "CARGO_FEATURES=--features diagnostics"
|
||||
|
||||
cd /d "%SERVER_DIR%"
|
||||
|
||||
where cargo >nul 2>nul
|
||||
if errorlevel 1 (
|
||||
echo Error: cargo not found.
|
||||
goto fail
|
||||
)
|
||||
|
||||
where zig >nul 2>nul
|
||||
if errorlevel 1 (
|
||||
set "ZIG_EXE="
|
||||
if defined LOCALAPPDATA (
|
||||
for /f "delims=" %%F in ('where /R "%LOCALAPPDATA%\Microsoft\WinGet\Packages" zig.exe 2^>nul') do (
|
||||
if not defined ZIG_EXE set "ZIG_EXE=%%F"
|
||||
)
|
||||
)
|
||||
if defined ZIG_EXE (
|
||||
for %%D in ("!ZIG_EXE!") do set "PATH=%%~dpD;!PATH!"
|
||||
)
|
||||
)
|
||||
|
||||
where zig >nul 2>nul
|
||||
if errorlevel 1 (
|
||||
echo Error: Zig not found. Install it with: winget install --id zig.zig -e
|
||||
goto fail
|
||||
)
|
||||
|
||||
cargo zigbuild --help >nul 2>nul
|
||||
if errorlevel 1 (
|
||||
echo Error: cargo-zigbuild not found. Install it with: cargo install cargo-zigbuild --locked
|
||||
goto fail
|
||||
)
|
||||
|
||||
for /f "delims=" %%V in ('zig version') do echo Using Zig: %%V
|
||||
echo Cargo target directory: %LINUX_TARGET_DIR%
|
||||
|
||||
echo Adding musl target...
|
||||
rustup target add x86_64-unknown-linux-musl
|
||||
if errorlevel 1 goto fail
|
||||
rustup target add aarch64-unknown-linux-musl
|
||||
if errorlevel 1 goto fail
|
||||
rustup target add armv7-unknown-linux-musleabihf
|
||||
if errorlevel 1 goto fail
|
||||
|
||||
if "%RUN_TESTS%"=="1" (
|
||||
echo Running Linux pre-build checks...
|
||||
call :setup_test_zig_wrappers
|
||||
if !errorlevel! neq 0 goto fail
|
||||
cargo fmt --all -- --check
|
||||
if !errorlevel! neq 0 goto fail
|
||||
|
||||
set "CARGO_TARGET_DIR=%CLIPPY_TARGET_DIR%"
|
||||
cargo clippy --release --target x86_64-unknown-linux-musl !CARGO_FEATURES! --all-targets -- -D warnings
|
||||
if !errorlevel! neq 0 goto fail
|
||||
set "CARGO_TARGET_DIR=%LINUX_TARGET_DIR%"
|
||||
|
||||
echo Compiling Linux musl test binaries - they cannot run on Windows...
|
||||
cargo zigbuild --target x86_64-unknown-linux-musl !CARGO_FEATURES! --tests
|
||||
if !errorlevel! neq 0 goto fail
|
||||
call :cleanup_test_zig_wrappers
|
||||
echo Linux musl tests compiled successfully. Run build_linux.sh --tests on Linux to execute them.
|
||||
) else (
|
||||
echo Pre-build checks skipped
|
||||
)
|
||||
|
||||
echo Building Linux server variants using cargo-zigbuild...
|
||||
if not exist "%ASSETS_DIR%" mkdir "%ASSETS_DIR%"
|
||||
if not exist "%VARIANT_RUNNER%" (
|
||||
echo Error: parallel variant runner not found: %VARIANT_RUNNER%
|
||||
goto fail
|
||||
)
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%VARIANT_RUNNER%" -BuildScript "%BUILD_SCRIPT%"
|
||||
if errorlevel 1 goto fail
|
||||
|
||||
echo Verifying Linux server assets...
|
||||
if not exist "%ASSETS_DIR%" mkdir "%ASSETS_DIR%"
|
||||
del /q "%ASSETS_DIR%\csqtt" >nul 2>nul
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%PROVENANCE_SCRIPT%" -Mode Write
|
||||
if errorlevel 1 goto fail
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%PROVENANCE_SCRIPT%" -Mode Verify
|
||||
if errorlevel 1 goto fail
|
||||
for %%F in ("%ASSETS_DIR%\csqtt-linux-amd64") do echo csqtt-linux-amd64: %%~zF bytes
|
||||
for %%F in ("%ASSETS_DIR%\csqtt-linux-arm64") do echo csqtt-linux-arm64: %%~zF bytes
|
||||
for %%F in ("%ASSETS_DIR%\csqtt-linux-armv7") do echo csqtt-linux-armv7: %%~zF bytes
|
||||
echo Success: Linux server variants copied to %ASSETS_DIR%
|
||||
exit /b 0
|
||||
|
||||
:fail
|
||||
call :cleanup_test_zig_wrappers
|
||||
echo Build failed.
|
||||
if not defined CI pause
|
||||
exit /b 1
|
||||
|
||||
:build_variant_worker
|
||||
shift
|
||||
cd /d "%SERVER_DIR%"
|
||||
call :build_server_variant "%~1" "%~2"
|
||||
exit /b !errorlevel!
|
||||
|
||||
:build_server_variant
|
||||
set "CARGO_TARGET_DIR=%PROJECT_ROOT%build\csqtt-uring-linux-%~2"
|
||||
cargo zigbuild --release --target %~1 !CARGO_FEATURES!
|
||||
if errorlevel 1 exit /b 1
|
||||
copy /Y "%CARGO_TARGET_DIR%\%~1\release\csqtt" "%ASSETS_DIR%\%~2" >nul
|
||||
if errorlevel 1 exit /b 1
|
||||
exit /b 0
|
||||
|
||||
:setup_test_zig_wrappers
|
||||
set "TEST_ZIG_WRAPPER_DIR=%TEMP%\csqtt-zig-test-%RANDOM%%RANDOM%"
|
||||
mkdir "%TEST_ZIG_WRAPPER_DIR%" >nul 2>nul
|
||||
if errorlevel 1 exit /b 1
|
||||
>"%TEST_ZIG_WRAPPER_DIR%\zigcc.cmd" echo @call "%BUILD_SCRIPT%" --test-zig-cc %%*
|
||||
>"%TEST_ZIG_WRAPPER_DIR%\zigcxx.cmd" echo @call "%BUILD_SCRIPT%" --test-zig-cxx %%*
|
||||
>"%TEST_ZIG_WRAPPER_DIR%\zigar.cmd" echo @zig ar %%*
|
||||
set "CC_x86_64_unknown_linux_musl=%TEST_ZIG_WRAPPER_DIR%\zigcc.cmd"
|
||||
set "CXX_x86_64_unknown_linux_musl=%TEST_ZIG_WRAPPER_DIR%\zigcxx.cmd"
|
||||
set "AR_x86_64_unknown_linux_musl=%TEST_ZIG_WRAPPER_DIR%\zigar.cmd"
|
||||
exit /b 0
|
||||
|
||||
:cleanup_test_zig_wrappers
|
||||
set "CC_x86_64_unknown_linux_musl="
|
||||
set "CXX_x86_64_unknown_linux_musl="
|
||||
set "AR_x86_64_unknown_linux_musl="
|
||||
if not defined TEST_ZIG_WRAPPER_DIR exit /b 0
|
||||
del /q "%TEST_ZIG_WRAPPER_DIR%\zigcc.cmd" "%TEST_ZIG_WRAPPER_DIR%\zigcxx.cmd" "%TEST_ZIG_WRAPPER_DIR%\zigar.cmd" >nul 2>nul
|
||||
rmdir "%TEST_ZIG_WRAPPER_DIR%" >nul 2>nul
|
||||
set "TEST_ZIG_WRAPPER_DIR="
|
||||
exit /b 0
|
||||
|
||||
:test_zig_cc
|
||||
@echo off
|
||||
setlocal EnableDelayedExpansion
|
||||
shift
|
||||
set "ARGS="
|
||||
:test_zig_cc_collect
|
||||
if "%~1"=="" goto test_zig_cc_run
|
||||
if /I not "%~1"=="--target=x86_64-unknown-linux-musl" set "ARGS=!ARGS! "%~1""
|
||||
shift
|
||||
goto test_zig_cc_collect
|
||||
:test_zig_cc_run
|
||||
zig cc -target x86_64-linux-musl !ARGS!
|
||||
exit /b %errorlevel%
|
||||
|
||||
:test_zig_cxx
|
||||
@echo off
|
||||
setlocal EnableDelayedExpansion
|
||||
shift
|
||||
set "ARGS="
|
||||
:test_zig_cxx_collect
|
||||
if "%~1"=="" goto test_zig_cxx_run
|
||||
if /I not "%~1"=="--target=x86_64-unknown-linux-musl" set "ARGS=!ARGS! "%~1""
|
||||
shift
|
||||
goto test_zig_cxx_collect
|
||||
:test_zig_cxx_run
|
||||
zig c++ -target x86_64-linux-musl !ARGS!
|
||||
exit /b %errorlevel%
|
||||
@@ -0,0 +1,147 @@
|
||||
#!/usr/bin/env bash
|
||||
# SPDX-FileCopyrightText: 2026 amurcanov
|
||||
# SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
set -euo pipefail
|
||||
ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||
cd "$ROOT"
|
||||
RUN_CHECKS=""
|
||||
DIAGNOSTICS=0
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
--tests) RUN_CHECKS=1 ;;
|
||||
--no-tests) RUN_CHECKS=0 ;;
|
||||
--diagnostics) DIAGNOSTICS=1 ;;
|
||||
*) echo "Usage: $0 [--tests|--no-tests] [--diagnostics]" >&2; exit 2 ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
if [[ -z "$RUN_CHECKS" ]]; then
|
||||
if [[ -t 0 ]]; then
|
||||
read -rp "Запустить проверки и тесты (или их кросс-компиляцию) перед сборкой? [Y/n]: " REPLY
|
||||
case "$REPLY" in
|
||||
[nN]|[nN][oO]|[нН]|[нН][eE][тТ]) RUN_CHECKS=0 ;;
|
||||
*) RUN_CHECKS=1 ;;
|
||||
esac
|
||||
else
|
||||
RUN_CHECKS=1
|
||||
fi
|
||||
fi
|
||||
FEATURE_ARGS=()
|
||||
if [[ "$DIAGNOSTICS" == 1 ]]; then
|
||||
FEATURE_ARGS=(--features diagnostics)
|
||||
fi
|
||||
command -v cargo >/dev/null
|
||||
command -v rustup >/dev/null
|
||||
command -v zig >/dev/null
|
||||
cargo zigbuild --help >/dev/null
|
||||
rustup toolchain install 1.97.1 --profile minimal --component rustfmt --component clippy
|
||||
rustup target add x86_64-unknown-linux-musl aarch64-unknown-linux-musl armv7-unknown-linux-musleabihf --toolchain 1.97.1
|
||||
rustc +1.97.1 --version
|
||||
zig version
|
||||
WRAP="$ROOT/build/zig-wrappers"
|
||||
mkdir -p "$WRAP"
|
||||
HOST="$(rustc +1.97.1 -vV | sed -n 's/^host: //p')"
|
||||
if [[ "$HOST" == *windows* ]]; then
|
||||
cat > "$WRAP/zigcc.ps1" <<'PS1'
|
||||
$filtered = @($args | Where-Object { $_ -notlike "--target=*" })
|
||||
& zig cc -target $env:CSQTT_ZIG_TARGET @filtered
|
||||
exit $LASTEXITCODE
|
||||
PS1
|
||||
cat > "$WRAP/zigcxx.ps1" <<'PS1'
|
||||
$filtered = @($args | Where-Object { $_ -notlike "--target=*" })
|
||||
& zig c++ -target $env:CSQTT_ZIG_TARGET @filtered
|
||||
exit $LASTEXITCODE
|
||||
PS1
|
||||
cat > "$WRAP/zigcc.cmd" <<'CMD'
|
||||
@echo off
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0zigcc.ps1" %*
|
||||
CMD
|
||||
cat > "$WRAP/zigcxx.cmd" <<'CMD'
|
||||
@echo off
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0zigcxx.ps1" %*
|
||||
CMD
|
||||
cat > "$WRAP/zigar.cmd" <<'CMD'
|
||||
@echo off
|
||||
zig ar %*
|
||||
CMD
|
||||
CC_WRAPPER="$WRAP/zigcc.cmd"
|
||||
CXX_WRAPPER="$WRAP/zigcxx.cmd"
|
||||
AR_WRAPPER="$WRAP/zigar.cmd"
|
||||
else
|
||||
cat > "$WRAP/zigcc" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
args=()
|
||||
for arg in "$@"; do
|
||||
[[ "$arg" == --target=* ]] || args+=("$arg")
|
||||
done
|
||||
exec zig cc -target "$CSQTT_ZIG_TARGET" "${args[@]}"
|
||||
SH
|
||||
cat > "$WRAP/zigcxx" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
args=()
|
||||
for arg in "$@"; do
|
||||
[[ "$arg" == --target=* ]] || args+=("$arg")
|
||||
done
|
||||
exec zig c++ -target "$CSQTT_ZIG_TARGET" "${args[@]}"
|
||||
SH
|
||||
cat > "$WRAP/zigar" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
exec zig ar "$@"
|
||||
SH
|
||||
chmod +x "$WRAP/zigcc" "$WRAP/zigcxx" "$WRAP/zigar"
|
||||
CC_WRAPPER="$WRAP/zigcc"
|
||||
CXX_WRAPPER="$WRAP/zigcxx"
|
||||
AR_WRAPPER="$WRAP/zigar"
|
||||
fi
|
||||
export CC_x86_64_unknown_linux_musl="$CC_WRAPPER"
|
||||
export CXX_x86_64_unknown_linux_musl="$CXX_WRAPPER"
|
||||
export AR_x86_64_unknown_linux_musl="$AR_WRAPPER"
|
||||
export CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_LINKER="$CC_WRAPPER"
|
||||
export CC_aarch64_unknown_linux_musl="$CC_WRAPPER"
|
||||
export CXX_aarch64_unknown_linux_musl="$CXX_WRAPPER"
|
||||
export AR_aarch64_unknown_linux_musl="$AR_WRAPPER"
|
||||
export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER="$CC_WRAPPER"
|
||||
export CC_armv7_unknown_linux_musleabihf="$CC_WRAPPER"
|
||||
export CXX_armv7_unknown_linux_musleabihf="$CXX_WRAPPER"
|
||||
export AR_armv7_unknown_linux_musleabihf="$AR_WRAPPER"
|
||||
export CARGO_TARGET_ARMV7_UNKNOWN_LINUX_MUSLEABIHF_LINKER="$CC_WRAPPER"
|
||||
export CSQTT_ZIG_TARGET=x86_64-linux-musl
|
||||
if [[ "$RUN_CHECKS" == 1 ]]; then
|
||||
cargo +1.97.1 fmt --all -- --check
|
||||
cargo +1.97.1 zigbuild --all-targets --target x86_64-unknown-linux-musl "${FEATURE_ARGS[@]}"
|
||||
CARGO_TARGET_DIR="$ROOT/build/linux-musl-check" cargo +1.97.1 clippy --release --target x86_64-unknown-linux-musl "${FEATURE_ARGS[@]}" --all-targets -- -D warnings
|
||||
if [[ "$HOST" == *linux* ]]; then
|
||||
echo "Running Linux musl tests..."
|
||||
CARGO_TARGET_DIR="$ROOT/build/linux-musl-tests" cargo +1.97.1 test --target x86_64-unknown-linux-musl "${FEATURE_ARGS[@]}" --all-targets
|
||||
else
|
||||
echo "Compiling Linux musl test binaries (they cannot run on this non-Linux host)..."
|
||||
CARGO_TARGET_DIR="$ROOT/build/linux-musl-tests" cargo +1.97.1 zigbuild --target x86_64-unknown-linux-musl "${FEATURE_ARGS[@]}" --tests
|
||||
fi
|
||||
fi
|
||||
build_variant() {
|
||||
local target="$1" zig_target="$2" asset="$3"
|
||||
CSQTT_ZIG_TARGET="$zig_target" \
|
||||
ZIG_GLOBAL_CACHE_DIR="$ROOT/build/zig-cache/$asset/global" \
|
||||
ZIG_LOCAL_CACHE_DIR="$ROOT/build/zig-cache/$asset/local" \
|
||||
CARGO_TARGET_DIR="$ROOT/build/linux-musl" \
|
||||
cargo +1.97.1 zigbuild --release --target "$target" "${FEATURE_ARGS[@]}"
|
||||
mkdir -p "$ROOT/dist" "$ROOT/../app/src/main/assets"
|
||||
cp "$ROOT/build/linux-musl/$target/release/csqtt" "$ROOT/dist/$asset"
|
||||
cp "$ROOT/build/linux-musl/$target/release/csqtt" "$ROOT/../app/src/main/assets/$asset"
|
||||
ls -lh "$ROOT/dist/$asset"
|
||||
}
|
||||
build_variant x86_64-unknown-linux-musl x86_64-linux-musl csqtt-linux-amd64
|
||||
build_variant aarch64-unknown-linux-musl aarch64-linux-musl csqtt-linux-arm64
|
||||
build_variant armv7-unknown-linux-musleabihf armv7-linux-musleabihf csqtt-linux-armv7
|
||||
rm -f "$ROOT/../app/src/main/assets/csqtt"
|
||||
if command -v pwsh >/dev/null; then
|
||||
pwsh -NoProfile -File "$ROOT/../scripts/server_asset_provenance.ps1" -Mode Write
|
||||
pwsh -NoProfile -File "$ROOT/../scripts/server_asset_provenance.ps1" -Mode Verify
|
||||
elif command -v powershell.exe >/dev/null; then
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$(wslpath -w "$ROOT/../scripts/server_asset_provenance.ps1")" -Mode Write
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$(wslpath -w "$ROOT/../scripts/server_asset_provenance.ps1")" -Mode Verify
|
||||
else
|
||||
echo "Server assets built. Run scripts/server_asset_provenance.ps1 -Mode Write and -Mode Verify before packaging an APK." >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,59 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$BuildScript
|
||||
)
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$BuildScript = (Resolve-Path -LiteralPath $BuildScript).Path
|
||||
$WorkingDirectory = (Get-Item -LiteralPath $BuildScript).DirectoryName
|
||||
|
||||
$variants = @(
|
||||
[pscustomobject]@{ Name = 'amd64'; Target = 'x86_64-unknown-linux-musl'; Asset = 'csqtt-linux-amd64' },
|
||||
[pscustomobject]@{ Name = 'arm64'; Target = 'aarch64-unknown-linux-musl'; Asset = 'csqtt-linux-arm64' },
|
||||
[pscustomobject]@{ Name = 'armv7'; Target = 'armv7-unknown-linux-musleabihf'; Asset = 'csqtt-linux-armv7' }
|
||||
)
|
||||
$runDirectory = Join-Path ([System.IO.Path]::GetTempPath()) ("csqtt-linux-build-" + [guid]::NewGuid().ToString('N'))
|
||||
New-Item -ItemType Directory -Path $runDirectory -Force | Out-Null
|
||||
|
||||
try {
|
||||
$processes = foreach ($variant in $variants) {
|
||||
$stdout = Join-Path $runDirectory "$($variant.Name).stdout.log"
|
||||
$stderr = Join-Path $runDirectory "$($variant.Name).stderr.log"
|
||||
$command = "call `"$BuildScript`" --build-variant $($variant.Target) $($variant.Asset)"
|
||||
$process = Start-Process -FilePath $env:ComSpec -ArgumentList @('/d', '/c', $command) -WorkingDirectory $WorkingDirectory -RedirectStandardOutput $stdout -RedirectStandardError $stderr -PassThru
|
||||
[pscustomobject]@{
|
||||
Variant = $variant
|
||||
Stdout = $stdout
|
||||
Stderr = $stderr
|
||||
Process = $process
|
||||
}
|
||||
}
|
||||
|
||||
$failed = @()
|
||||
foreach ($entry in $processes) {
|
||||
$entry.Process.WaitForExit()
|
||||
$entry.Process.Refresh()
|
||||
$exitCode = [int]$entry.Process.ExitCode
|
||||
if ($exitCode -ne 0) {
|
||||
$failed += [pscustomobject]@{ Entry = $entry; ExitCode = $exitCode }
|
||||
}
|
||||
}
|
||||
|
||||
if ($failed.Count -gt 0) {
|
||||
foreach ($failure in $failed) {
|
||||
$entry = $failure.Entry
|
||||
[Console]::Error.WriteLine("Build $($entry.Variant.Name) exited with code $($failure.ExitCode)")
|
||||
if (Test-Path -LiteralPath $entry.Stdout) {
|
||||
Get-Content -LiteralPath $entry.Stdout -Tail 80
|
||||
}
|
||||
if (Test-Path -LiteralPath $entry.Stderr) {
|
||||
Get-Content -LiteralPath $entry.Stderr -Tail 80
|
||||
}
|
||||
}
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
finally {
|
||||
Remove-Item -LiteralPath $runDirectory -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,402 @@
|
||||
use crate::{flow_frame::FrameHeader, packet::PacketBuffer, striped_scheduler::PacketClass};
|
||||
use std::collections::VecDeque;
|
||||
|
||||
const LATENCY_SLOTS: usize = 16;
|
||||
const PRIORITY_MIN_SLOTS: usize = 32;
|
||||
const PRIORITY_MAX_SLOTS: usize = 252;
|
||||
const PRIORITY_SLOTS_PER_PATH: usize = 2;
|
||||
const BULK_MIN_SLOTS: usize = 72;
|
||||
const BULK_MAX_SLOTS: usize = 1_008;
|
||||
const BULK_SLOTS_PER_PATH: usize = 8;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct ClientQueueProfile {
|
||||
pub latency_slots: usize,
|
||||
pub priority_slots: usize,
|
||||
pub bulk_slots: usize,
|
||||
}
|
||||
|
||||
pub fn profile_for_active_paths(active_paths: usize) -> ClientQueueProfile {
|
||||
let active_paths = active_paths.min(PRIORITY_MAX_SLOTS / PRIORITY_SLOTS_PER_PATH);
|
||||
if active_paths == 0 {
|
||||
return ClientQueueProfile {
|
||||
latency_slots: 0,
|
||||
priority_slots: 0,
|
||||
bulk_slots: 0,
|
||||
};
|
||||
}
|
||||
ClientQueueProfile {
|
||||
latency_slots: LATENCY_SLOTS,
|
||||
priority_slots: active_paths
|
||||
.saturating_mul(PRIORITY_SLOTS_PER_PATH)
|
||||
.clamp(PRIORITY_MIN_SLOTS, PRIORITY_MAX_SLOTS),
|
||||
bulk_slots: active_paths
|
||||
.saturating_mul(BULK_SLOTS_PER_PATH)
|
||||
.clamp(BULK_MIN_SLOTS, BULK_MAX_SLOTS),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct PacketSlots {
|
||||
free: Vec<PacketBuffer>,
|
||||
pending: VecDeque<PacketBuffer>,
|
||||
}
|
||||
|
||||
impl PacketSlots {
|
||||
fn resize(&mut self, capacity: usize) {
|
||||
while self.free.len().saturating_add(self.pending.len()) < capacity {
|
||||
self.free.push(PacketBuffer::new());
|
||||
}
|
||||
while self.free.len().saturating_add(self.pending.len()) > capacity {
|
||||
if self.free.pop().is_none() {
|
||||
self.pending.pop_back();
|
||||
}
|
||||
}
|
||||
if capacity == 0 {
|
||||
self.free.clear();
|
||||
self.pending.clear();
|
||||
self.free.shrink_to_fit();
|
||||
self.pending.shrink_to_fit();
|
||||
}
|
||||
}
|
||||
|
||||
fn enqueue(&mut self, packet: &[u8]) -> bool {
|
||||
let Some(mut slot) = self.free.pop() else {
|
||||
return false;
|
||||
};
|
||||
if !slot.copy_from(packet) {
|
||||
self.free.push(slot);
|
||||
return false;
|
||||
}
|
||||
self.pending.push_back(slot);
|
||||
true
|
||||
}
|
||||
|
||||
fn enqueue_framed(&mut self, header: FrameHeader, packet: &[u8]) -> bool {
|
||||
let Some(mut slot) = self.free.pop() else {
|
||||
return false;
|
||||
};
|
||||
let total = packet.len().saturating_add(crate::flow_frame::FRAME_LEN);
|
||||
if total > slot.capacity() || !slot.set_len(total) {
|
||||
self.free.push(slot);
|
||||
return false;
|
||||
}
|
||||
let output = slot.as_mut_slice();
|
||||
if !header.encode(&mut output[..crate::flow_frame::FRAME_LEN]) {
|
||||
self.free.push(slot);
|
||||
return false;
|
||||
}
|
||||
output[crate::flow_frame::FRAME_LEN..].copy_from_slice(packet);
|
||||
self.pending.push_back(slot);
|
||||
true
|
||||
}
|
||||
|
||||
fn dequeue(&mut self) -> Option<PacketBuffer> {
|
||||
self.pending.pop_front()
|
||||
}
|
||||
|
||||
fn requeue_front(&mut self, packet: PacketBuffer) {
|
||||
self.pending.push_front(packet);
|
||||
}
|
||||
|
||||
fn recycle(&mut self, packet: PacketBuffer) {
|
||||
self.free.push(packet);
|
||||
}
|
||||
|
||||
fn clear_pending(&mut self) {
|
||||
while let Some(packet) = self.pending.pop_front() {
|
||||
self.free.push(packet);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn pending_len(&self) -> usize {
|
||||
self.pending.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ClientEgressLane {
|
||||
active_paths: usize,
|
||||
latency: PacketSlots,
|
||||
priority: PacketSlots,
|
||||
bulk: PacketSlots,
|
||||
}
|
||||
|
||||
impl ClientEgressLane {
|
||||
fn configure(&mut self, active_paths: usize) {
|
||||
self.active_paths = active_paths.min(PRIORITY_MAX_SLOTS / PRIORITY_SLOTS_PER_PATH);
|
||||
let profile = profile_for_active_paths(self.active_paths);
|
||||
self.latency.resize(profile.latency_slots);
|
||||
self.priority.resize(profile.priority_slots);
|
||||
self.bulk.resize(profile.bulk_slots);
|
||||
}
|
||||
|
||||
fn queue_mut(&mut self, class: PacketClass) -> &mut PacketSlots {
|
||||
match class {
|
||||
PacketClass::Small => &mut self.latency,
|
||||
PacketClass::Medium => &mut self.priority,
|
||||
PacketClass::Bulk => &mut self.bulk,
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_pending(&mut self) {
|
||||
self.latency.clear_pending();
|
||||
self.priority.clear_pending();
|
||||
self.bulk.clear_pending();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn queue(&self, class: PacketClass) -> &PacketSlots {
|
||||
match class {
|
||||
PacketClass::Small => &self.latency,
|
||||
PacketClass::Medium => &self.priority,
|
||||
PacketClass::Bulk => &self.bulk,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DownlinkQueue {
|
||||
lanes: Box<[ClientEgressLane; 256]>,
|
||||
latency_ring: Vec<usize>,
|
||||
priority_ring: Vec<usize>,
|
||||
bulk_ring: Vec<usize>,
|
||||
latency_cursor: usize,
|
||||
priority_cursor: usize,
|
||||
bulk_cursor: usize,
|
||||
}
|
||||
|
||||
impl Default for DownlinkQueue {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
lanes: Box::new(std::array::from_fn(|_| ClientEgressLane::default())),
|
||||
latency_ring: Vec::new(),
|
||||
priority_ring: Vec::new(),
|
||||
bulk_ring: Vec::new(),
|
||||
latency_cursor: 0,
|
||||
priority_cursor: 0,
|
||||
bulk_cursor: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DownlinkQueue {
|
||||
pub fn configure(&mut self, key: usize, active_paths: usize) {
|
||||
let Some(lane) = self.lanes.get_mut(key) else {
|
||||
return;
|
||||
};
|
||||
if lane.active_paths == active_paths.min(PRIORITY_MAX_SLOTS / PRIORITY_SLOTS_PER_PATH) {
|
||||
return;
|
||||
}
|
||||
lane.configure(active_paths);
|
||||
self.rebuild_rings();
|
||||
}
|
||||
|
||||
pub fn enqueue(&mut self, key: usize, class: PacketClass, packet: &[u8]) -> bool {
|
||||
self.lanes
|
||||
.get_mut(key)
|
||||
.is_some_and(|lane| lane.active_paths != 0 && lane.queue_mut(class).enqueue(packet))
|
||||
}
|
||||
|
||||
pub fn enqueue_framed(
|
||||
&mut self,
|
||||
key: usize,
|
||||
class: PacketClass,
|
||||
header: FrameHeader,
|
||||
packet: &[u8],
|
||||
) -> bool {
|
||||
self.lanes.get_mut(key).is_some_and(|lane| {
|
||||
lane.active_paths != 0 && lane.queue_mut(class).enqueue_framed(header, packet)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn dequeue(&mut self, class: PacketClass) -> Option<(usize, PacketBuffer)> {
|
||||
let attempts = self.ring_len(class);
|
||||
for _ in 0..attempts {
|
||||
let key = self.next_key(class)?;
|
||||
let lane = &mut self.lanes[key];
|
||||
if let Some(packet) = lane.queue_mut(class).dequeue() {
|
||||
return Some((key, packet));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn requeue_front(&mut self, key: usize, class: PacketClass, packet: PacketBuffer) {
|
||||
if let Some(lane) = self.lanes.get_mut(key) {
|
||||
lane.queue_mut(class).requeue_front(packet);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn recycle(&mut self, key: usize, class: PacketClass, packet: PacketBuffer) {
|
||||
if let Some(lane) = self.lanes.get_mut(key) {
|
||||
lane.queue_mut(class).recycle(packet);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear(&mut self, key: usize) {
|
||||
if let Some(lane) = self.lanes.get_mut(key) {
|
||||
lane.clear_pending();
|
||||
}
|
||||
}
|
||||
|
||||
fn rebuild_rings(&mut self) {
|
||||
self.latency_ring.clear();
|
||||
self.priority_ring.clear();
|
||||
self.bulk_ring.clear();
|
||||
for (key, lane) in self.lanes.iter().enumerate() {
|
||||
if lane.active_paths == 0 {
|
||||
continue;
|
||||
}
|
||||
self.latency_ring.push(key);
|
||||
self.priority_ring.push(key);
|
||||
self.bulk_ring
|
||||
.extend(std::iter::repeat_n(key, lane.active_paths));
|
||||
}
|
||||
self.latency_cursor %= self.latency_ring.len().max(1);
|
||||
self.priority_cursor %= self.priority_ring.len().max(1);
|
||||
self.bulk_cursor %= self.bulk_ring.len().max(1);
|
||||
}
|
||||
|
||||
fn ring_len(&self, class: PacketClass) -> usize {
|
||||
match class {
|
||||
PacketClass::Small => self.latency_ring.len(),
|
||||
PacketClass::Medium => self.priority_ring.len(),
|
||||
PacketClass::Bulk => self.bulk_ring.len(),
|
||||
}
|
||||
}
|
||||
|
||||
fn next_key(&mut self, class: PacketClass) -> Option<usize> {
|
||||
let (ring, cursor) = match class {
|
||||
PacketClass::Small => (&self.latency_ring, &mut self.latency_cursor),
|
||||
PacketClass::Medium => (&self.priority_ring, &mut self.priority_cursor),
|
||||
PacketClass::Bulk => (&self.bulk_ring, &mut self.bulk_cursor),
|
||||
};
|
||||
let key = *ring.get(*cursor)?;
|
||||
*cursor += 1;
|
||||
if *cursor == ring.len() {
|
||||
*cursor = 0;
|
||||
}
|
||||
Some(key)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn pending_len(&self, key: usize, class: PacketClass) -> usize {
|
||||
self.lanes
|
||||
.get(key)
|
||||
.map_or(0, |lane| lane.queue(class).pending_len())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn packet(value: u8) -> [u8; 24] {
|
||||
[value; 24]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profiles_cover_each_supported_worker_total() {
|
||||
for active_paths in [9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99, 108, 117, 126] {
|
||||
let profile = profile_for_active_paths(active_paths);
|
||||
assert_eq!(profile.latency_slots, 16);
|
||||
assert_eq!(profile.priority_slots, (active_paths * 2).max(32));
|
||||
assert_eq!(profile.bulk_slots, active_paths * 8);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bulk_ring_is_weighted_by_active_paths() {
|
||||
let mut queue = DownlinkQueue::default();
|
||||
queue.configure(2, 9);
|
||||
queue.configure(3, 18);
|
||||
for value in 0..27u8 {
|
||||
assert!(queue.enqueue(2, PacketClass::Bulk, &packet(value)));
|
||||
assert!(queue.enqueue(3, PacketClass::Bulk, &packet(value)));
|
||||
}
|
||||
let mut first = 0usize;
|
||||
let mut second = 0usize;
|
||||
for _ in 0..27 {
|
||||
let (key, packet) = queue.dequeue(PacketClass::Bulk).unwrap();
|
||||
queue.recycle(key, PacketClass::Bulk, packet);
|
||||
match key {
|
||||
2 => first += 1,
|
||||
3 => second += 1,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
assert_eq!(first, 9);
|
||||
assert_eq!(second, 18);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lanes_have_independent_bulk_capacity() {
|
||||
let mut queue = DownlinkQueue::default();
|
||||
queue.configure(2, 9);
|
||||
queue.configure(3, 9);
|
||||
for value in 0..72u8 {
|
||||
assert!(queue.enqueue(2, PacketClass::Bulk, &packet(value)));
|
||||
}
|
||||
assert!(!queue.enqueue(2, PacketClass::Bulk, &packet(99)));
|
||||
assert!(queue.enqueue(3, PacketClass::Bulk, &packet(100)));
|
||||
assert_eq!(queue.pending_len(2, PacketClass::Bulk), 72);
|
||||
assert_eq!(queue.pending_len(3, PacketClass::Bulk), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrinking_active_paths_discards_only_excess_packets_from_the_lane() {
|
||||
let mut queue = DownlinkQueue::default();
|
||||
queue.configure(5, 18);
|
||||
for value in 0..144u8 {
|
||||
assert!(queue.enqueue(5, PacketClass::Bulk, &packet(value)));
|
||||
}
|
||||
queue.configure(5, 9);
|
||||
assert_eq!(queue.pending_len(5, PacketClass::Bulk), 72);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_a_lane_keeps_its_reserved_slots_isolated() {
|
||||
let mut queue = DownlinkQueue::default();
|
||||
queue.configure(5, 18);
|
||||
queue.configure(6, 18);
|
||||
assert!(queue.enqueue(5, PacketClass::Bulk, &packet(1)));
|
||||
assert!(queue.enqueue(6, PacketClass::Bulk, &packet(2)));
|
||||
queue.clear(5);
|
||||
assert_eq!(queue.pending_len(5, PacketClass::Bulk), 0);
|
||||
assert_eq!(queue.pending_len(6, PacketClass::Bulk), 1);
|
||||
for value in 0..144u8 {
|
||||
assert!(queue.enqueue(5, PacketClass::Bulk, &packet(value)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inactive_lane_rejects_packets_until_it_is_reactivated() {
|
||||
let mut queue = DownlinkQueue::default();
|
||||
assert!(!queue.enqueue(5, PacketClass::Bulk, &packet(1)));
|
||||
queue.configure(5, 18);
|
||||
assert!(queue.enqueue(5, PacketClass::Bulk, &packet(2)));
|
||||
queue.configure(5, 0);
|
||||
assert!(!queue.enqueue(5, PacketClass::Bulk, &packet(3)));
|
||||
queue.configure(5, 18);
|
||||
assert!(queue.enqueue(5, PacketClass::Bulk, &packet(4)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn framed_packet_preserves_the_header_and_inner_payload() {
|
||||
let mut queue = DownlinkQueue::default();
|
||||
queue.configure(7, 9);
|
||||
let header = FrameHeader {
|
||||
sender_id: 1,
|
||||
flow_id: 2,
|
||||
sequence: 3,
|
||||
};
|
||||
assert!(queue.enqueue_framed(7, PacketClass::Bulk, header, &packet(8)));
|
||||
let (key, queued) = queue.dequeue(PacketClass::Bulk).unwrap();
|
||||
let (decoded, payload) = FrameHeader::decode(queued.as_slice()).unwrap();
|
||||
assert_eq!(key, 7);
|
||||
assert_eq!(decoded, header);
|
||||
assert_eq!(payload, packet(8));
|
||||
queue.recycle(key, PacketClass::Bulk, queued);
|
||||
}
|
||||
}
|
||||
+2623
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,5 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
pub const TUN_IFACE: &str = "csqtt1";
|
||||
pub const TUN_ADDR: &str = "10.66.67.1";
|
||||
@@ -0,0 +1,316 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
use bytes::BytesMut;
|
||||
use crossbeam_queue::ArrayQueue;
|
||||
use std::{
|
||||
mem,
|
||||
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
pub const PACKET_CAPACITY: usize = 1600;
|
||||
pub const UDP_TX_SLOTS: usize = 4096;
|
||||
pub const TUN_TX_SLOTS: usize = 1024;
|
||||
pub const TUN_MTU: u16 = 1300;
|
||||
pub const PACKET_POOL_RETAINED_MAX: usize = 256;
|
||||
|
||||
pub const fn packet_pool_size() -> usize {
|
||||
UDP_TX_SLOTS + TUN_TX_SLOTS
|
||||
}
|
||||
|
||||
pub struct PacketPool {
|
||||
queue: ArrayQueue<BytesMut>,
|
||||
allocated: AtomicUsize,
|
||||
retained: AtomicUsize,
|
||||
retained_limit: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct PacketPoolSnapshot {
|
||||
pub capacity: usize,
|
||||
pub allocated: usize,
|
||||
pub retained: usize,
|
||||
}
|
||||
|
||||
impl PacketPool {
|
||||
pub fn new(buffers: usize) -> Arc<Self> {
|
||||
let capacity = buffers.max(1);
|
||||
Arc::new(Self {
|
||||
queue: ArrayQueue::new(capacity),
|
||||
allocated: AtomicUsize::new(0),
|
||||
retained: AtomicUsize::new(0),
|
||||
retained_limit: capacity.min(PACKET_POOL_RETAINED_MAX),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn try_acquire(self: &Arc<Self>) -> Option<PacketBuf> {
|
||||
let storage = if let Some(storage) = self.queue.pop() {
|
||||
self.retained.fetch_sub(1, Ordering::AcqRel);
|
||||
storage
|
||||
} else {
|
||||
self.allocated
|
||||
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |allocated| {
|
||||
(allocated < self.queue.capacity()).then_some(allocated + 1)
|
||||
})
|
||||
.ok()?;
|
||||
BytesMut::zeroed(PACKET_CAPACITY)
|
||||
};
|
||||
Some(PacketBuf {
|
||||
storage,
|
||||
len: 0,
|
||||
pool: self.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> PacketPoolSnapshot {
|
||||
PacketPoolSnapshot {
|
||||
capacity: self.queue.capacity(),
|
||||
allocated: self.allocated.load(Ordering::Acquire),
|
||||
retained: self.retained.load(Ordering::Acquire),
|
||||
}
|
||||
}
|
||||
|
||||
fn release(&self, storage: BytesMut) {
|
||||
if storage.len() != PACKET_CAPACITY {
|
||||
self.allocated.fetch_sub(1, Ordering::AcqRel);
|
||||
return;
|
||||
}
|
||||
if self
|
||||
.retained
|
||||
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |retained| {
|
||||
(retained < self.retained_limit).then_some(retained + 1)
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
self.allocated.fetch_sub(1, Ordering::AcqRel);
|
||||
return;
|
||||
}
|
||||
if self.queue.push(storage).is_err() {
|
||||
self.retained.fetch_sub(1, Ordering::AcqRel);
|
||||
self.allocated.fetch_sub(1, Ordering::AcqRel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PacketBuf {
|
||||
storage: BytesMut,
|
||||
len: usize,
|
||||
pool: Arc<PacketPool>,
|
||||
}
|
||||
|
||||
impl PacketBuf {
|
||||
#[inline(always)]
|
||||
pub fn len(&self) -> usize {
|
||||
self.len
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn as_slice(&self) -> &[u8] {
|
||||
&self.storage[..self.len]
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn storage_mut(&mut self) -> &mut [u8] {
|
||||
&mut self.storage[..]
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn set_len(&mut self, len: usize) -> bool {
|
||||
if len > PACKET_CAPACITY {
|
||||
return false;
|
||||
}
|
||||
self.len = len;
|
||||
true
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn copy_from(&mut self, data: &[u8]) -> bool {
|
||||
if data.len() > PACKET_CAPACITY {
|
||||
return false;
|
||||
}
|
||||
self.storage[..data.len()].copy_from_slice(data);
|
||||
self.len = data.len();
|
||||
true
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn as_mut_ptr(&mut self) -> *mut u8 {
|
||||
self.storage.as_mut_ptr()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PacketBuf {
|
||||
fn drop(&mut self) {
|
||||
self.pool.release(mem::take(&mut self.storage));
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PacketBuffer {
|
||||
bytes: [u8; PACKET_CAPACITY],
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl PacketBuffer {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
bytes: [0; PACKET_CAPACITY],
|
||||
len: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn capacity(&self) -> usize {
|
||||
PACKET_CAPACITY
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn as_slice(&self) -> &[u8] {
|
||||
&self.bytes[..self.len]
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn as_mut_slice(&mut self) -> &mut [u8] {
|
||||
&mut self.bytes[..self.len]
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn set_len(&mut self, len: usize) -> bool {
|
||||
if len > PACKET_CAPACITY {
|
||||
return false;
|
||||
}
|
||||
self.len = len;
|
||||
true
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn copy_from(&mut self, data: &[u8]) -> bool {
|
||||
if data.len() > PACKET_CAPACITY {
|
||||
return false;
|
||||
}
|
||||
self.bytes[..data.len()].copy_from_slice(data);
|
||||
self.len = data.len();
|
||||
true
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn as_mut_ptr(&mut self) -> *mut u8 {
|
||||
self.bytes.as_mut_ptr()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PacketBuffer {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn extract_dst_ipv4(packet: &[u8]) -> Option<[u8; 4]> {
|
||||
if packet.len() < 20 || packet[0] >> 4 != 4 {
|
||||
return None;
|
||||
}
|
||||
Some([packet[16], packet[17], packet[18], packet[19]])
|
||||
}
|
||||
|
||||
pub fn socket_addr_to_storage(
|
||||
address: SocketAddr,
|
||||
storage: &mut libc::sockaddr_storage,
|
||||
) -> libc::socklen_t {
|
||||
unsafe {
|
||||
std::ptr::write_bytes(
|
||||
storage as *mut libc::sockaddr_storage as *mut u8,
|
||||
0,
|
||||
std::mem::size_of::<libc::sockaddr_storage>(),
|
||||
);
|
||||
}
|
||||
match address {
|
||||
SocketAddr::V4(address) => {
|
||||
let raw = storage as *mut libc::sockaddr_storage as *mut libc::sockaddr_in;
|
||||
unsafe {
|
||||
(*raw).sin_family = libc::AF_INET as libc::sa_family_t;
|
||||
(*raw).sin_port = address.port().to_be();
|
||||
(*raw).sin_addr = libc::in_addr {
|
||||
s_addr: u32::from_ne_bytes(address.ip().octets()),
|
||||
};
|
||||
}
|
||||
std::mem::size_of::<libc::sockaddr_in>() as libc::socklen_t
|
||||
}
|
||||
SocketAddr::V6(address) => {
|
||||
let raw = storage as *mut libc::sockaddr_storage as *mut libc::sockaddr_in6;
|
||||
unsafe {
|
||||
(*raw).sin6_family = libc::AF_INET6 as libc::sa_family_t;
|
||||
(*raw).sin6_port = address.port().to_be();
|
||||
(*raw).sin6_flowinfo = address.flowinfo();
|
||||
(*raw).sin6_addr = libc::in6_addr {
|
||||
s6_addr: address.ip().octets(),
|
||||
};
|
||||
(*raw).sin6_scope_id = address.scope_id();
|
||||
}
|
||||
std::mem::size_of::<libc::sockaddr_in6>() as libc::socklen_t
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn storage_to_socket_addr(
|
||||
storage: &libc::sockaddr_storage,
|
||||
len: libc::socklen_t,
|
||||
) -> Option<SocketAddr> {
|
||||
match storage.ss_family as i32 {
|
||||
libc::AF_INET if len as usize >= std::mem::size_of::<libc::sockaddr_in>() => {
|
||||
let raw =
|
||||
unsafe { &*(storage as *const libc::sockaddr_storage as *const libc::sockaddr_in) };
|
||||
let ip = Ipv4Addr::from(raw.sin_addr.s_addr.to_ne_bytes());
|
||||
Some(SocketAddr::new(IpAddr::V4(ip), u16::from_be(raw.sin_port)))
|
||||
}
|
||||
libc::AF_INET6 if len as usize >= std::mem::size_of::<libc::sockaddr_in6>() => {
|
||||
let raw = unsafe {
|
||||
&*(storage as *const libc::sockaddr_storage as *const libc::sockaddr_in6)
|
||||
};
|
||||
let ip = Ipv6Addr::from(raw.sin6_addr.s6_addr);
|
||||
Some(SocketAddr::V6(std::net::SocketAddrV6::new(
|
||||
ip,
|
||||
u16::from_be(raw.sin6_port),
|
||||
raw.sin6_flowinfo,
|
||||
raw.sin6_scope_id,
|
||||
)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn packet_pool_is_bounded_and_recovers_buffers() {
|
||||
let pool = PacketPool::new(2);
|
||||
let first = pool.try_acquire().expect("first packet");
|
||||
let second = pool.try_acquire().expect("second packet");
|
||||
assert!(pool.try_acquire().is_none());
|
||||
assert_eq!(pool.snapshot().allocated, 2);
|
||||
drop(first);
|
||||
drop(second);
|
||||
let snapshot = pool.snapshot();
|
||||
assert_eq!(snapshot.capacity, 2);
|
||||
assert_eq!(snapshot.allocated, 2);
|
||||
assert_eq!(snapshot.retained, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_pool_discards_excess_idle_storage() {
|
||||
let capacity = PACKET_POOL_RETAINED_MAX + 8;
|
||||
let pool = PacketPool::new(capacity);
|
||||
let packets = (0..capacity)
|
||||
.map(|_| pool.try_acquire().expect("packet pool capacity"))
|
||||
.collect::<Vec<_>>();
|
||||
drop(packets);
|
||||
let snapshot = pool.snapshot();
|
||||
assert_eq!(snapshot.retained, PACKET_POOL_RETAINED_MAX);
|
||||
assert_eq!(snapshot.allocated, PACKET_POOL_RETAINED_MAX);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,649 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::{
|
||||
LazyLock, RwLock,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
pub const SAMPLE_INTERVAL: u64 = 64;
|
||||
|
||||
pub static ALL_CLIENTS: AtomicU64 = AtomicU64::new(0);
|
||||
pub static GLOBAL_DATAPLANE: LazyLock<RwLock<Snapshot>> =
|
||||
LazyLock::new(|| RwLock::new(Snapshot::default()));
|
||||
pub static GLOBAL_PROTOCOL: LazyLock<RwLock<Snapshot>> =
|
||||
LazyLock::new(|| RwLock::new(Snapshot::default()));
|
||||
pub static DATAPLANE_CPU_NS: AtomicU64 = AtomicU64::new(0);
|
||||
pub static DATAPLANE_TID: AtomicU64 = AtomicU64::new(0);
|
||||
pub static DATAPLANE_CPU_SEQUENCE: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct Counters {
|
||||
pub operations: u64,
|
||||
pub bytes: u64,
|
||||
pub samples: u64,
|
||||
pub sampled_ns: u64,
|
||||
#[serde(default)]
|
||||
pub sampled_wall_ns: u64,
|
||||
}
|
||||
|
||||
impl Counters {
|
||||
pub fn delta(self, previous: Self) -> Self {
|
||||
Self {
|
||||
operations: self.operations.saturating_sub(previous.operations),
|
||||
bytes: self.bytes.saturating_sub(previous.bytes),
|
||||
samples: self.samples.saturating_sub(previous.samples),
|
||||
sampled_ns: self.sampled_ns.saturating_sub(previous.sampled_ns),
|
||||
sampled_wall_ns: self
|
||||
.sampled_wall_ns
|
||||
.saturating_sub(previous.sampled_wall_ns),
|
||||
}
|
||||
}
|
||||
|
||||
fn add(self, other: Self) -> Self {
|
||||
Self {
|
||||
operations: self.operations.saturating_add(other.operations),
|
||||
bytes: self.bytes.saturating_add(other.bytes),
|
||||
samples: self.samples.saturating_add(other.samples),
|
||||
sampled_ns: self.sampled_ns.saturating_add(other.sampled_ns),
|
||||
sampled_wall_ns: self.sampled_wall_ns.saturating_add(other.sampled_wall_ns),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct Snapshot {
|
||||
pub dispatch: Counters,
|
||||
pub udp_rx: Counters,
|
||||
pub tun_rx: Counters,
|
||||
pub route_replay: Counters,
|
||||
pub tun_write: Counters,
|
||||
pub udp_queue: Counters,
|
||||
pub flush: Counters,
|
||||
pub bookkeeping: Counters,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
pub fn delta(self, previous: Self) -> Self {
|
||||
Self {
|
||||
dispatch: self.dispatch.delta(previous.dispatch),
|
||||
udp_rx: self.udp_rx.delta(previous.udp_rx),
|
||||
tun_rx: self.tun_rx.delta(previous.tun_rx),
|
||||
route_replay: self.route_replay.delta(previous.route_replay),
|
||||
tun_write: self.tun_write.delta(previous.tun_write),
|
||||
udp_queue: self.udp_queue.delta(previous.udp_queue),
|
||||
flush: self.flush.delta(previous.flush),
|
||||
bookkeeping: self.bookkeeping.delta(previous.bookkeeping),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn merge(self, other: Self) -> Self {
|
||||
Self {
|
||||
dispatch: self.dispatch.add(other.dispatch),
|
||||
udp_rx: self.udp_rx.add(other.udp_rx),
|
||||
tun_rx: self.tun_rx.add(other.tun_rx),
|
||||
route_replay: self.route_replay.add(other.route_replay),
|
||||
tun_write: self.tun_write.add(other.tun_write),
|
||||
udp_queue: self.udp_queue.add(other.udp_queue),
|
||||
flush: self.flush.add(other.flush),
|
||||
bookkeeping: self.bookkeeping.add(other.bookkeeping),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum Stage {
|
||||
Dispatch,
|
||||
UdpRx,
|
||||
TunRx,
|
||||
RouteReplay,
|
||||
TunWrite,
|
||||
UdpQueue,
|
||||
Flush,
|
||||
Bookkeeping,
|
||||
}
|
||||
|
||||
impl Stage {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
fn index(self) -> usize {
|
||||
match self {
|
||||
Self::Dispatch => 0,
|
||||
Self::UdpRx => 1,
|
||||
Self::TunRx => 2,
|
||||
Self::RouteReplay => 3,
|
||||
Self::TunWrite => 4,
|
||||
Self::UdpQueue => 5,
|
||||
Self::Flush => 6,
|
||||
Self::Bookkeeping => 7,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Profiler {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
enabled: bool,
|
||||
#[cfg(feature = "diagnostics")]
|
||||
cursors: [u64; 8],
|
||||
#[cfg(feature = "diagnostics")]
|
||||
counters: [Counters; 8],
|
||||
}
|
||||
|
||||
impl Profiler {
|
||||
pub fn refresh_enabled(&mut self) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
self.enabled = ALL_CLIENTS.load(Ordering::Acquire) != 0;
|
||||
}
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
{
|
||||
let _ = self;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn enabled(&self) -> bool {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
self.enabled
|
||||
}
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
{
|
||||
let _ = self;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn begin(&mut self, stage: Stage, bytes: usize) -> Option<u64> {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
if !self.enabled {
|
||||
return None;
|
||||
}
|
||||
let index = stage.index();
|
||||
let counter = &mut self.counters[index];
|
||||
counter.operations = counter.operations.saturating_add(1);
|
||||
counter.bytes = counter.bytes.saturating_add(bytes as u64);
|
||||
let cursor = self.cursors[index];
|
||||
self.cursors[index] = cursor.wrapping_add(1);
|
||||
if cursor.is_multiple_of(SAMPLE_INTERVAL) {
|
||||
counter.samples = counter.samples.saturating_add(1);
|
||||
Some(thread_cpu_time_ns())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
{
|
||||
let _ = (stage, bytes);
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn finish(&mut self, stage: Stage, started: Option<u64>) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
let Some(started) = started else {
|
||||
return;
|
||||
};
|
||||
self.finish_elapsed(stage, thread_cpu_time_ns().saturating_sub(started));
|
||||
}
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
{
|
||||
let _ = (stage, started);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "diagnostics")]
|
||||
#[inline(always)]
|
||||
pub fn finish_elapsed(&mut self, stage: Stage, elapsed_ns: u64) {
|
||||
let counter = &mut self.counters[stage.index()];
|
||||
counter.sampled_ns = counter.sampled_ns.saturating_add(elapsed_ns);
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn expand_batch(&mut self, stage: Stage, operations: u64, bytes: u64, sampled: bool) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
if !self.enabled {
|
||||
return;
|
||||
}
|
||||
let counter = &mut self.counters[stage.index()];
|
||||
let additional = operations.saturating_sub(1);
|
||||
counter.operations = counter.operations.saturating_add(additional);
|
||||
counter.bytes = counter.bytes.saturating_add(bytes);
|
||||
if sampled {
|
||||
counter.samples = counter.samples.saturating_add(additional);
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
{
|
||||
let _ = (stage, operations, bytes, sampled);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "diagnostics")]
|
||||
pub fn snapshot(&self) -> Snapshot {
|
||||
Snapshot {
|
||||
dispatch: self.counters[Stage::Dispatch.index()],
|
||||
udp_rx: self.counters[Stage::UdpRx.index()],
|
||||
tun_rx: self.counters[Stage::TunRx.index()],
|
||||
route_replay: self.counters[Stage::RouteReplay.index()],
|
||||
tun_write: self.counters[Stage::TunWrite.index()],
|
||||
udp_queue: self.counters[Stage::UdpQueue.index()],
|
||||
flush: self.counters[Stage::Flush.index()],
|
||||
bookkeeping: self.counters[Stage::Bookkeeping.index()],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn publish_dataplane(&self) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
if self.enabled
|
||||
&& let Ok(mut global) = GLOBAL_DATAPLANE.write()
|
||||
{
|
||||
*global = self.snapshot();
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
{
|
||||
let _ = self;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "diagnostics")]
|
||||
pub fn publish_protocol(&self) {
|
||||
if self.enabled
|
||||
&& let Ok(mut global) = GLOBAL_PROTOCOL.write()
|
||||
{
|
||||
*global = self.snapshot();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn publish_dataplane_cpu(cpu_ns: u64) {
|
||||
DATAPLANE_CPU_NS.store(cpu_ns, Ordering::Release);
|
||||
DATAPLANE_CPU_SEQUENCE.fetch_add(1, Ordering::Release);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn publish_dataplane_tid() {
|
||||
let tid = unsafe { libc::syscall(libc::SYS_gettid) };
|
||||
if tid > 0 {
|
||||
DATAPLANE_TID.store(tid as u64, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn thread_cpu_time_ns() -> u64 {
|
||||
clock_time_ns(libc::CLOCK_THREAD_CPUTIME_ID)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn process_cpu_time_ns() -> u64 {
|
||||
clock_time_ns(libc::CLOCK_PROCESS_CPUTIME_ID)
|
||||
}
|
||||
|
||||
pub fn process_cpu_split_ns() -> (u64, u64) {
|
||||
let Ok(stat) = std::fs::read_to_string("/proc/self/stat") else {
|
||||
return (0, 0);
|
||||
};
|
||||
let Some((_, user_ticks, system_ticks)) = parse_proc_stat(&stat) else {
|
||||
return (0, 0);
|
||||
};
|
||||
ticks_to_ns(user_ticks, system_ticks).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ThreadCpuSnapshot {
|
||||
pub tid: u32,
|
||||
pub name: String,
|
||||
pub user_ns: u64,
|
||||
pub system_ns: u64,
|
||||
}
|
||||
|
||||
pub fn process_thread_cpu_snapshot() -> Vec<ThreadCpuSnapshot> {
|
||||
let Ok(entries) = std::fs::read_dir("/proc/self/task") else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut threads = Vec::new();
|
||||
for entry in entries.flatten() {
|
||||
let Some(tid) = entry
|
||||
.file_name()
|
||||
.to_str()
|
||||
.and_then(|value| value.parse().ok())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else {
|
||||
continue;
|
||||
};
|
||||
let Some((name, user_ticks, system_ticks)) = parse_proc_stat(&stat) else {
|
||||
continue;
|
||||
};
|
||||
let Some((user_ns, system_ns)) = ticks_to_ns(user_ticks, system_ticks) else {
|
||||
continue;
|
||||
};
|
||||
threads.push(ThreadCpuSnapshot {
|
||||
tid,
|
||||
name: name.to_owned(),
|
||||
user_ns,
|
||||
system_ns,
|
||||
});
|
||||
}
|
||||
threads
|
||||
}
|
||||
|
||||
fn parse_proc_stat(stat: &str) -> Option<(&str, u64, u64)> {
|
||||
let comm_start = stat.find('(')?;
|
||||
let comm_end = stat.rfind(')')?;
|
||||
if comm_end <= comm_start {
|
||||
return None;
|
||||
}
|
||||
let mut fields = stat[comm_end + 1..].split_whitespace();
|
||||
let user_ticks = fields.nth(11)?.parse().ok()?;
|
||||
let system_ticks = fields.next()?.parse().ok()?;
|
||||
Some((&stat[comm_start + 1..comm_end], user_ticks, system_ticks))
|
||||
}
|
||||
|
||||
fn ticks_to_ns(user_ticks: u64, system_ticks: u64) -> Option<(u64, u64)> {
|
||||
#[allow(clippy::useless_conversion)]
|
||||
static TICKS_PER_SECOND: LazyLock<i64> =
|
||||
LazyLock::new(|| unsafe { libc::sysconf(libc::_SC_CLK_TCK).into() });
|
||||
let ticks_per_second = *TICKS_PER_SECOND;
|
||||
if ticks_per_second <= 0 {
|
||||
return None;
|
||||
}
|
||||
let scale = |ticks: u64| {
|
||||
(u128::from(ticks) * 1_000_000_000u128 / ticks_per_second as u128).min(u128::from(u64::MAX))
|
||||
as u64
|
||||
};
|
||||
Some((scale(user_ticks), scale(system_ticks)))
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn clock_time_ns(clock: libc::clockid_t) -> u64 {
|
||||
let mut value = libc::timespec {
|
||||
tv_sec: 0,
|
||||
tv_nsec: 0,
|
||||
};
|
||||
let result = unsafe { libc::clock_gettime(clock, &mut value) };
|
||||
if result != 0 {
|
||||
return 0;
|
||||
}
|
||||
(value.tv_sec as u64)
|
||||
.saturating_mul(1_000_000_000)
|
||||
.saturating_add(value.tv_nsec as u64)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
macro_rules! counter_delta_case {
|
||||
($name:ident, $field:ident, $current:expr, $previous:expr, $expected:expr) => {
|
||||
#[test]
|
||||
fn $name() {
|
||||
let current = Counters {
|
||||
$field: $current,
|
||||
..Counters::default()
|
||||
};
|
||||
let previous = Counters {
|
||||
$field: $previous,
|
||||
..Counters::default()
|
||||
};
|
||||
assert_eq!(current.delta(previous).$field, $expected);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
counter_delta_case!(counter_delta_operations_increase, operations, 9, 4, 5);
|
||||
counter_delta_case!(
|
||||
counter_delta_operations_rolls_back_to_zero,
|
||||
operations,
|
||||
4,
|
||||
9,
|
||||
0
|
||||
);
|
||||
counter_delta_case!(counter_delta_bytes_increase, bytes, 4096, 1024, 3072);
|
||||
counter_delta_case!(counter_delta_bytes_rolls_back_to_zero, bytes, 7, 8, 0);
|
||||
counter_delta_case!(counter_delta_samples_increase, samples, 72, 64, 8);
|
||||
counter_delta_case!(counter_delta_samples_rolls_back_to_zero, samples, 63, 64, 0);
|
||||
counter_delta_case!(counter_delta_cpu_increase, sampled_ns, 901, 900, 1);
|
||||
counter_delta_case!(counter_delta_cpu_rolls_back_to_zero, sampled_ns, 0, 1, 0);
|
||||
counter_delta_case!(counter_delta_wall_increase, sampled_wall_ns, 128, 32, 96);
|
||||
counter_delta_case!(
|
||||
counter_delta_wall_rolls_back_to_zero,
|
||||
sampled_wall_ns,
|
||||
1,
|
||||
2,
|
||||
0
|
||||
);
|
||||
|
||||
macro_rules! counter_merge_case {
|
||||
($name:ident, $field:ident, $left:expr, $right:expr, $expected:expr) => {
|
||||
#[test]
|
||||
fn $name() {
|
||||
let left = Counters {
|
||||
$field: $left,
|
||||
..Counters::default()
|
||||
};
|
||||
let right = Counters {
|
||||
$field: $right,
|
||||
..Counters::default()
|
||||
};
|
||||
assert_eq!(left.add(right).$field, $expected);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
counter_merge_case!(counter_merge_operations_adds, operations, 19, 23, 42);
|
||||
counter_merge_case!(
|
||||
counter_merge_operations_saturates,
|
||||
operations,
|
||||
u64::MAX,
|
||||
1,
|
||||
u64::MAX
|
||||
);
|
||||
counter_merge_case!(counter_merge_bytes_adds, bytes, 12_000, 34_000, 46_000);
|
||||
counter_merge_case!(
|
||||
counter_merge_bytes_saturates,
|
||||
bytes,
|
||||
u64::MAX - 1,
|
||||
2,
|
||||
u64::MAX
|
||||
);
|
||||
counter_merge_case!(counter_merge_samples_adds, samples, 63, 1, 64);
|
||||
counter_merge_case!(
|
||||
counter_merge_samples_saturates,
|
||||
samples,
|
||||
u64::MAX,
|
||||
64,
|
||||
u64::MAX
|
||||
);
|
||||
counter_merge_case!(counter_merge_cpu_adds, sampled_ns, 55, 89, 144);
|
||||
counter_merge_case!(
|
||||
counter_merge_cpu_saturates,
|
||||
sampled_ns,
|
||||
u64::MAX - 7,
|
||||
8,
|
||||
u64::MAX
|
||||
);
|
||||
counter_merge_case!(counter_merge_wall_adds, sampled_wall_ns, 250, 750, 1000);
|
||||
counter_merge_case!(
|
||||
counter_merge_wall_saturates,
|
||||
sampled_wall_ns,
|
||||
u64::MAX,
|
||||
1,
|
||||
u64::MAX
|
||||
);
|
||||
|
||||
macro_rules! snapshot_delta_case {
|
||||
($name:ident, $field:ident) => {
|
||||
#[test]
|
||||
fn $name() {
|
||||
let current = Snapshot {
|
||||
$field: Counters {
|
||||
operations: 21,
|
||||
bytes: 2100,
|
||||
samples: 21,
|
||||
sampled_ns: 210,
|
||||
sampled_wall_ns: 420,
|
||||
},
|
||||
..Snapshot::default()
|
||||
};
|
||||
let previous = Snapshot {
|
||||
$field: Counters {
|
||||
operations: 13,
|
||||
bytes: 1300,
|
||||
samples: 13,
|
||||
sampled_ns: 130,
|
||||
sampled_wall_ns: 260,
|
||||
},
|
||||
..Snapshot::default()
|
||||
};
|
||||
let delta = current.delta(previous).$field;
|
||||
assert_eq!(delta.operations, 8);
|
||||
assert_eq!(delta.bytes, 800);
|
||||
assert_eq!(delta.samples, 8);
|
||||
assert_eq!(delta.sampled_ns, 80);
|
||||
assert_eq!(delta.sampled_wall_ns, 160);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
snapshot_delta_case!(snapshot_delta_dispatch, dispatch);
|
||||
snapshot_delta_case!(snapshot_delta_udp_rx, udp_rx);
|
||||
snapshot_delta_case!(snapshot_delta_tun_rx, tun_rx);
|
||||
snapshot_delta_case!(snapshot_delta_route_replay, route_replay);
|
||||
snapshot_delta_case!(snapshot_delta_tun_write, tun_write);
|
||||
snapshot_delta_case!(snapshot_delta_udp_queue, udp_queue);
|
||||
snapshot_delta_case!(snapshot_delta_flush, flush);
|
||||
snapshot_delta_case!(snapshot_delta_bookkeeping, bookkeeping);
|
||||
|
||||
macro_rules! snapshot_merge_case {
|
||||
($name:ident, $field:ident) => {
|
||||
#[test]
|
||||
fn $name() {
|
||||
let left = Snapshot {
|
||||
$field: Counters {
|
||||
operations: 3,
|
||||
bytes: 30,
|
||||
samples: 3,
|
||||
sampled_ns: 300,
|
||||
sampled_wall_ns: 3000,
|
||||
},
|
||||
..Snapshot::default()
|
||||
};
|
||||
let right = Snapshot {
|
||||
$field: Counters {
|
||||
operations: 4,
|
||||
bytes: 40,
|
||||
samples: 4,
|
||||
sampled_ns: 400,
|
||||
sampled_wall_ns: 4000,
|
||||
},
|
||||
..Snapshot::default()
|
||||
};
|
||||
let merged = left.merge(right).$field;
|
||||
assert_eq!(merged.operations, 7);
|
||||
assert_eq!(merged.bytes, 70);
|
||||
assert_eq!(merged.samples, 7);
|
||||
assert_eq!(merged.sampled_ns, 700);
|
||||
assert_eq!(merged.sampled_wall_ns, 7000);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
snapshot_merge_case!(snapshot_merge_dispatch, dispatch);
|
||||
snapshot_merge_case!(snapshot_merge_udp_rx, udp_rx);
|
||||
snapshot_merge_case!(snapshot_merge_tun_rx, tun_rx);
|
||||
snapshot_merge_case!(snapshot_merge_route_replay, route_replay);
|
||||
snapshot_merge_case!(snapshot_merge_tun_write, tun_write);
|
||||
snapshot_merge_case!(snapshot_merge_udp_queue, udp_queue);
|
||||
snapshot_merge_case!(snapshot_merge_flush, flush);
|
||||
snapshot_merge_case!(snapshot_merge_bookkeeping, bookkeeping);
|
||||
|
||||
fn proc_stat(name: &str, user_ticks: u64, system_ticks: u64) -> String {
|
||||
let mut stat = format!("42 ({name}) S");
|
||||
for _ in 0..10 {
|
||||
stat.push_str(" 0");
|
||||
}
|
||||
format!("{stat} {user_ticks} {system_ticks} 0 0")
|
||||
}
|
||||
|
||||
macro_rules! proc_stat_case {
|
||||
($name:ident, $thread_name:expr, $user:expr, $system:expr) => {
|
||||
#[test]
|
||||
fn $name() {
|
||||
let stat = proc_stat($thread_name, $user, $system);
|
||||
assert_eq!(parse_proc_stat(&stat), Some(($thread_name, $user, $system)));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
proc_stat_case!(proc_stat_parses_server_thread, "csqtt", 41, 9);
|
||||
proc_stat_case!(
|
||||
proc_stat_parses_dataplane_thread,
|
||||
"dataplane fast path",
|
||||
87,
|
||||
12
|
||||
);
|
||||
proc_stat_case!(
|
||||
proc_stat_parses_parenthesis_in_thread_name,
|
||||
"worker) 7",
|
||||
5,
|
||||
6
|
||||
);
|
||||
proc_stat_case!(
|
||||
proc_stat_parses_unicode_thread_name,
|
||||
"поток-обработчик",
|
||||
11,
|
||||
13
|
||||
);
|
||||
|
||||
#[test]
|
||||
fn profiler_fast_path_has_an_explicit_mode_contract() {
|
||||
let mut profiler = Profiler::default();
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
let previous = ALL_CLIENTS.swap(1, Ordering::AcqRel);
|
||||
profiler.refresh_enabled();
|
||||
assert!(profiler.enabled());
|
||||
let started = profiler.begin(Stage::Dispatch, 120);
|
||||
assert!(started.is_some());
|
||||
profiler.finish(Stage::Dispatch, started);
|
||||
let snapshot = profiler.snapshot();
|
||||
assert_eq!(snapshot.dispatch.operations, 1);
|
||||
assert_eq!(snapshot.dispatch.bytes, 120);
|
||||
assert_eq!(snapshot.dispatch.samples, 1);
|
||||
ALL_CLIENTS.store(previous, Ordering::Release);
|
||||
}
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
{
|
||||
profiler.refresh_enabled();
|
||||
assert!(!profiler.enabled());
|
||||
let started = profiler.begin(Stage::Dispatch, 120);
|
||||
assert!(started.is_none());
|
||||
profiler.finish(Stage::Dispatch, started);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tick_conversion_preserves_cpu_ordering() {
|
||||
let (small_user, small_system) = ticks_to_ns(12, 7).unwrap();
|
||||
let (large_user, large_system) = ticks_to_ns(13, 8).unwrap();
|
||||
assert!(large_user >= small_user);
|
||||
assert!(large_system >= small_system);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tick_conversion_saturates_at_u64_limit() {
|
||||
let (user, system) = ticks_to_ns(u64::MAX, u64::MAX).unwrap();
|
||||
assert_eq!(user, u64::MAX);
|
||||
assert_eq!(system, u64::MAX);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,8 @@
|
||||
# SPDX-FileCopyrightText: 2026 amurcanov
|
||||
# SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
[toolchain]
|
||||
channel = "1.97.1"
|
||||
profile = "minimal"
|
||||
components = ["rustfmt", "clippy"]
|
||||
targets = ["x86_64-unknown-linux-musl"]
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,404 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
use crate::{packet::extract_dst_ipv4, striped_scheduler::PacketClass};
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
pub const TUN_IFACE: &str = "csqtt1";
|
||||
pub const TUN_SUBNET: &str = "10.66.67.0/24";
|
||||
const SUBNET_PREFIX: [u8; 3] = [10, 66, 67];
|
||||
|
||||
pub type SessionId = u64;
|
||||
pub type RegistrationId = u64;
|
||||
pub type WorkerId = u16;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct RouteEndpoint {
|
||||
pub session_id: SessionId,
|
||||
pub registration_id: RegistrationId,
|
||||
pub worker_id: WorkerId,
|
||||
pub slot: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct RouteSelection {
|
||||
start: usize,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl RouteSelection {
|
||||
#[inline(always)]
|
||||
pub fn len(self) -> usize {
|
||||
self.len
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct LocalStripeCursor {
|
||||
next: usize,
|
||||
remaining: usize,
|
||||
count: usize,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct LocalStripedScheduler {
|
||||
cursors: [LocalStripeCursor; 3],
|
||||
}
|
||||
|
||||
impl LocalStripedScheduler {
|
||||
#[inline(always)]
|
||||
fn select(&mut self, count: usize, class: PacketClass) -> Option<usize> {
|
||||
if count == 0 {
|
||||
return None;
|
||||
}
|
||||
let cursor = &mut self.cursors[class.index()];
|
||||
if cursor.count != count {
|
||||
cursor.next = 0;
|
||||
cursor.remaining = 0;
|
||||
cursor.count = count;
|
||||
}
|
||||
if cursor.remaining == 0 {
|
||||
cursor.remaining = class.stream_chunk();
|
||||
}
|
||||
let selected = cursor.next;
|
||||
cursor.remaining -= 1;
|
||||
if cursor.remaining == 0 {
|
||||
cursor.next += 1;
|
||||
if cursor.next == count {
|
||||
cursor.next = 0;
|
||||
}
|
||||
}
|
||||
Some(selected)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct RouteGroup {
|
||||
endpoints: Vec<RouteEndpoint>,
|
||||
scheduler: LocalStripedScheduler,
|
||||
}
|
||||
|
||||
impl RouteGroup {
|
||||
fn register(&mut self, endpoint: RouteEndpoint) {
|
||||
self.endpoints.retain(|current| {
|
||||
current.registration_id != endpoint.registration_id
|
||||
&& current.worker_id != endpoint.worker_id
|
||||
});
|
||||
self.endpoints.push(endpoint);
|
||||
self.endpoints
|
||||
.sort_unstable_by_key(|current| current.worker_id);
|
||||
}
|
||||
|
||||
fn unregister(&mut self, registration_id: RegistrationId) -> bool {
|
||||
let previous_len = self.endpoints.len();
|
||||
self.endpoints
|
||||
.retain(|endpoint| endpoint.registration_id != registration_id);
|
||||
self.endpoints.len() != previous_len
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[inline(always)]
|
||||
fn select(&mut self, class: PacketClass) -> Option<RouteEndpoint> {
|
||||
let selection = self.select_window(class)?;
|
||||
self.endpoint_at(selection, 0)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn select_window(&mut self, class: PacketClass) -> Option<RouteSelection> {
|
||||
let len = self.endpoints.len();
|
||||
let start = self.scheduler.select(len, class)?;
|
||||
Some(RouteSelection { start, len })
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn endpoint_at(&self, selection: RouteSelection, offset: usize) -> Option<RouteEndpoint> {
|
||||
if offset >= selection.len || selection.len == 0 {
|
||||
return None;
|
||||
}
|
||||
let index = selection.start + offset;
|
||||
let index = if index >= selection.len {
|
||||
index - selection.len
|
||||
} else {
|
||||
index
|
||||
};
|
||||
self.endpoints.get(index).copied()
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
self.endpoints.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RouteTable {
|
||||
groups: Box<[Option<RouteGroup>; 256]>,
|
||||
}
|
||||
|
||||
impl RouteTable {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
groups: Box::new(std::array::from_fn(|_| None)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(
|
||||
&mut self,
|
||||
ip: [u8; 4],
|
||||
session_id: SessionId,
|
||||
registration_id: RegistrationId,
|
||||
worker_id: WorkerId,
|
||||
slot: usize,
|
||||
) -> bool {
|
||||
let Some(index) = route_index(ip) else {
|
||||
return false;
|
||||
};
|
||||
self.groups[index]
|
||||
.get_or_insert_with(RouteGroup::default)
|
||||
.register(RouteEndpoint {
|
||||
session_id,
|
||||
registration_id,
|
||||
worker_id,
|
||||
slot,
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
pub fn update_slot(
|
||||
&mut self,
|
||||
ip: [u8; 4],
|
||||
session_id: SessionId,
|
||||
registration_id: RegistrationId,
|
||||
slot: usize,
|
||||
) {
|
||||
let Some(index) = route_index(ip) else {
|
||||
return;
|
||||
};
|
||||
let Some(group) = self.groups[index].as_mut() else {
|
||||
return;
|
||||
};
|
||||
if let Some(endpoint) = group.endpoints.iter_mut().find(|endpoint| {
|
||||
endpoint.session_id == session_id && endpoint.registration_id == registration_id
|
||||
}) {
|
||||
endpoint.slot = slot;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unregister(&mut self, ip: [u8; 4], registration_id: RegistrationId) -> bool {
|
||||
let Some(index) = route_index(ip) else {
|
||||
return false;
|
||||
};
|
||||
let Some(group) = self.groups[index].as_mut() else {
|
||||
return false;
|
||||
};
|
||||
let removed = group.unregister(registration_id);
|
||||
if group.is_empty() {
|
||||
self.groups[index] = None;
|
||||
}
|
||||
removed
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn packet_key(packet: &[u8]) -> Option<usize> {
|
||||
route_index(extract_dst_ipv4(packet)?)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn tunnel_key(ip: [u8; 4]) -> Option<usize> {
|
||||
route_index(ip)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn active_path_count(&self, key: usize) -> usize {
|
||||
self.groups
|
||||
.get(key)
|
||||
.and_then(|group| group.as_ref())
|
||||
.map_or(0, |group| group.endpoints.len())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn select_key_window(&mut self, key: usize, class: PacketClass) -> Option<RouteSelection> {
|
||||
self.groups.get_mut(key)?.as_mut()?.select_window(class)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn endpoint_at(
|
||||
&self,
|
||||
key: usize,
|
||||
selection: RouteSelection,
|
||||
offset: usize,
|
||||
) -> Option<RouteEndpoint> {
|
||||
self.groups
|
||||
.get(key)?
|
||||
.as_ref()?
|
||||
.endpoint_at(selection, offset)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[inline(always)]
|
||||
pub fn select(&mut self, ip: [u8; 4], class: PacketClass) -> Option<RouteEndpoint> {
|
||||
let index = route_index(ip)?;
|
||||
self.groups[index].as_mut()?.select(class)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn stream_count(&self, ip: [u8; 4]) -> usize {
|
||||
route_index(ip).map_or(0, |key| self.active_path_count(key))
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RouteTable {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn route_index(ip: [u8; 4]) -> Option<usize> {
|
||||
(ip[..3] == SUBNET_PREFIX).then_some(ip[3] as usize)
|
||||
}
|
||||
|
||||
pub fn parse_ipv4(value: &str) -> Option<[u8; 4]> {
|
||||
Some(value.parse::<Ipv4Addr>().ok()?.octets())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ip(last: u8) -> [u8; 4] {
|
||||
[10, 66, 67, last]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn route_table_supports_all_stream_scales() {
|
||||
for count in [9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99, 108, 117, 126] {
|
||||
let mut table = RouteTable::new();
|
||||
for id in 1..=count as u64 {
|
||||
assert!(table.register(ip(2), id, id, id as u16, id as usize));
|
||||
}
|
||||
assert_eq!(table.stream_count(ip(2)), count);
|
||||
for _ in 0..100_000 {
|
||||
let selected = table.select(ip(2), PacketClass::Bulk).unwrap();
|
||||
assert!((1..=count as u64).contains(&selected.session_id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unregister_is_registration_exact() {
|
||||
let mut table = RouteTable::new();
|
||||
assert!(table.register(ip(7), 100, 10, 1, 1));
|
||||
assert!(table.register(ip(7), 200, 20, 2, 2));
|
||||
assert!(table.unregister(ip(7), 10));
|
||||
assert_eq!(table.stream_count(ip(7)), 1);
|
||||
assert_eq!(
|
||||
table.select(ip(7), PacketClass::Bulk).unwrap().session_id,
|
||||
200
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compacted_session_slot_is_updated() {
|
||||
let mut table = RouteTable::new();
|
||||
assert!(table.register(ip(7), 100, 10, 1, 3));
|
||||
table.update_slot(ip(7), 100, 10, 9);
|
||||
assert_eq!(table.select(ip(7), PacketClass::Bulk).unwrap().slot, 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn foreign_subnet_is_rejected() {
|
||||
let mut table = RouteTable::new();
|
||||
assert!(!table.register([10, 66, 68, 2], 1, 1, 1, 1));
|
||||
assert!(table.select([10, 66, 68, 2], PacketClass::Bulk).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacement_transport_atomically_keeps_one_logical_worker() {
|
||||
let mut table = RouteTable::new();
|
||||
assert!(table.register(ip(7), 100, 10, 4, 1));
|
||||
assert!(table.register(ip(7), 200, 20, 4, 2));
|
||||
|
||||
assert_eq!(table.stream_count(ip(7)), 1);
|
||||
assert_eq!(
|
||||
table.select(ip(7), PacketClass::Bulk).unwrap().session_id,
|
||||
200
|
||||
);
|
||||
assert!(!table.unregister(ip(7), 10));
|
||||
assert_eq!(
|
||||
table.select(ip(7), PacketClass::Bulk).unwrap().session_id,
|
||||
200
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bulk_selection_respects_scheduler_chunks() {
|
||||
let mut table = RouteTable::new();
|
||||
for id in 1..=2 {
|
||||
assert!(table.register(ip(2), id, id, id as u16, id as usize));
|
||||
}
|
||||
|
||||
for _ in 0..crate::striped_scheduler::BULK_STREAM_STRIPE_PACKET_CHUNK {
|
||||
assert_eq!(table.select(ip(2), PacketClass::Bulk).unwrap().worker_id, 1);
|
||||
}
|
||||
assert_eq!(table.select(ip(2), PacketClass::Bulk).unwrap().worker_id, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_scheduler_restarts_safely_after_path_count_shrinks() {
|
||||
let mut scheduler = LocalStripedScheduler::default();
|
||||
for _ in 0..crate::striped_scheduler::BULK_STREAM_STRIPE_PACKET_CHUNK {
|
||||
assert_eq!(scheduler.select(3, PacketClass::Bulk), Some(0));
|
||||
}
|
||||
assert_eq!(scheduler.select(3, PacketClass::Bulk), Some(1));
|
||||
for _ in 0..crate::striped_scheduler::BULK_STREAM_STRIPE_PACKET_CHUNK {
|
||||
assert_eq!(scheduler.select(2, PacketClass::Bulk), Some(0));
|
||||
}
|
||||
assert_eq!(scheduler.select(2, PacketClass::Bulk), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn route_selection_exposes_all_candidates_from_start() {
|
||||
let mut table = RouteTable::new();
|
||||
for id in 1..=3 {
|
||||
assert!(table.register(ip(2), id, id, id as u16, id as usize));
|
||||
}
|
||||
let key = route_index(ip(2)).unwrap();
|
||||
let selection = table.select_key_window(key, PacketClass::Bulk).unwrap();
|
||||
assert_eq!(selection.len(), 3);
|
||||
assert_eq!(table.endpoint_at(key, selection, 0).unwrap().worker_id, 1);
|
||||
assert_eq!(table.endpoint_at(key, selection, 1).unwrap().worker_id, 2);
|
||||
assert_eq!(table.endpoint_at(key, selection, 2).unwrap().worker_id, 3);
|
||||
assert!(table.endpoint_at(key, selection, 3).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_classes_keep_independent_round_robin_cursors() {
|
||||
let mut table = RouteTable::new();
|
||||
assert!(table.register(ip(2), 1, 1, 1, 1));
|
||||
assert!(table.register(ip(2), 2, 2, 2, 2));
|
||||
|
||||
for _ in 0..crate::striped_scheduler::BULK_STREAM_STRIPE_PACKET_CHUNK {
|
||||
assert_eq!(table.select(ip(2), PacketClass::Bulk).unwrap().worker_id, 1);
|
||||
}
|
||||
|
||||
for _ in 0..crate::striped_scheduler::SMALL_STREAM_STRIPE_PACKET_CHUNK {
|
||||
assert_eq!(
|
||||
table.select(ip(2), PacketClass::Small).unwrap().worker_id,
|
||||
1
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
table.select(ip(2), PacketClass::Small).unwrap().worker_id,
|
||||
2
|
||||
);
|
||||
for _ in 0..crate::striped_scheduler::MEDIUM_STREAM_STRIPE_PACKET_CHUNK {
|
||||
assert_eq!(
|
||||
table.select(ip(2), PacketClass::Medium).unwrap().worker_id,
|
||||
1
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
table.select(ip(2), PacketClass::Medium).unwrap().worker_id,
|
||||
2
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
use anyhow::Result;
|
||||
use std::{future::Future, time::Duration};
|
||||
use tokio::task::JoinError;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct RestartPolicy {
|
||||
pub initial_delay: Duration,
|
||||
pub max_delay: Duration,
|
||||
pub reset_after: Duration,
|
||||
}
|
||||
|
||||
impl Default for RestartPolicy {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
initial_delay: Duration::from_millis(250),
|
||||
max_delay: Duration::from_secs(30),
|
||||
reset_after: Duration::from_secs(60),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum UdpFailure {
|
||||
Returned,
|
||||
Error(String),
|
||||
Panic,
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for UdpFailure {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Returned => formatter.write_str("listener returned unexpectedly"),
|
||||
Self::Error(error) => write!(formatter, "listener error: {error}"),
|
||||
Self::Panic => formatter.write_str("listener task panicked"),
|
||||
Self::Cancelled => formatter.write_str("listener task was cancelled"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_join(result: std::result::Result<Result<()>, JoinError>) -> UdpFailure {
|
||||
match result {
|
||||
Ok(Ok(())) => UdpFailure::Returned,
|
||||
Ok(Err(error)) => UdpFailure::Error(format!("{error:#}")),
|
||||
Err(error) if error.is_panic() => UdpFailure::Panic,
|
||||
Err(_) => UdpFailure::Cancelled,
|
||||
}
|
||||
}
|
||||
|
||||
fn bounded_delay(policy: RestartPolicy, delay: Duration) -> Duration {
|
||||
let minimum = Duration::from_millis(1);
|
||||
delay.max(minimum).min(policy.max_delay.max(minimum))
|
||||
}
|
||||
|
||||
fn next_delay(policy: RestartPolicy, delay: Duration) -> Duration {
|
||||
bounded_delay(policy, delay.saturating_mul(2))
|
||||
}
|
||||
|
||||
pub async fn supervise<R, F, O>(
|
||||
shutdown: CancellationToken,
|
||||
policy: RestartPolicy,
|
||||
mut runner: R,
|
||||
mut on_failure: O,
|
||||
) where
|
||||
R: FnMut() -> F,
|
||||
F: Future<Output = Result<()>> + Send + 'static,
|
||||
O: FnMut(UdpFailure, Duration),
|
||||
{
|
||||
let initial_delay = bounded_delay(policy, policy.initial_delay);
|
||||
let mut delay = initial_delay;
|
||||
|
||||
loop {
|
||||
if shutdown.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
|
||||
let started = tokio::time::Instant::now();
|
||||
let mut attempt = tokio::spawn(runner());
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.cancelled() => {
|
||||
attempt.abort();
|
||||
let _ = attempt.await;
|
||||
return;
|
||||
}
|
||||
result = &mut attempt => result,
|
||||
};
|
||||
|
||||
if shutdown.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
|
||||
if started.elapsed() >= policy.reset_after {
|
||||
delay = initial_delay;
|
||||
}
|
||||
|
||||
let failure = classify_join(result);
|
||||
on_failure(failure, delay);
|
||||
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.cancelled() => return,
|
||||
_ = tokio::time::sleep(delay) => {}
|
||||
}
|
||||
|
||||
delay = next_delay(policy, delay);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use anyhow::anyhow;
|
||||
use std::{
|
||||
future::pending,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
fn test_policy() -> RestartPolicy {
|
||||
RestartPolicy {
|
||||
initial_delay: Duration::from_millis(10),
|
||||
max_delay: Duration::from_millis(40),
|
||||
reset_after: Duration::from_millis(100),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn error_backoff_is_exponential_and_capped() {
|
||||
let shutdown = CancellationToken::new();
|
||||
let (sender, mut receiver) = mpsc::unbounded_channel();
|
||||
let supervisor = tokio::spawn(supervise(
|
||||
shutdown.clone(),
|
||||
test_policy(),
|
||||
|| async { Err(anyhow!("injected recv failure")) },
|
||||
move |failure, delay| {
|
||||
sender.send((failure, delay)).unwrap();
|
||||
},
|
||||
));
|
||||
|
||||
let expected = [10, 20, 40, 40, 40];
|
||||
for milliseconds in expected {
|
||||
let (failure, delay) = receiver.recv().await.unwrap();
|
||||
assert_eq!(
|
||||
failure,
|
||||
UdpFailure::Error("injected recv failure".to_owned())
|
||||
);
|
||||
assert_eq!(delay, Duration::from_millis(milliseconds));
|
||||
tokio::time::advance(delay).await;
|
||||
}
|
||||
|
||||
shutdown.cancel();
|
||||
supervisor.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn panic_is_contained_and_next_attempt_runs() {
|
||||
let shutdown = CancellationToken::new();
|
||||
let attempts = Arc::new(AtomicUsize::new(0));
|
||||
let runner_attempts = attempts.clone();
|
||||
let (sender, mut receiver) = mpsc::unbounded_channel();
|
||||
let supervisor = tokio::spawn(supervise(
|
||||
shutdown.clone(),
|
||||
test_policy(),
|
||||
move || {
|
||||
let attempt = runner_attempts.fetch_add(1, Ordering::SeqCst);
|
||||
async move {
|
||||
if attempt == 0 {
|
||||
panic!("injected UDP panic");
|
||||
}
|
||||
pending::<Result<()>>().await
|
||||
}
|
||||
},
|
||||
move |failure, delay| {
|
||||
sender.send((failure, delay)).unwrap();
|
||||
},
|
||||
));
|
||||
|
||||
let (failure, delay) = receiver.recv().await.unwrap();
|
||||
assert_eq!(failure, UdpFailure::Panic);
|
||||
assert_eq!(delay, Duration::from_millis(10));
|
||||
tokio::time::advance(delay).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(attempts.load(Ordering::SeqCst), 2);
|
||||
|
||||
shutdown.cancel();
|
||||
supervisor.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn stable_attempt_resets_accumulated_backoff() {
|
||||
let shutdown = CancellationToken::new();
|
||||
let attempts = Arc::new(AtomicUsize::new(0));
|
||||
let runner_attempts = attempts.clone();
|
||||
let (sender, mut receiver) = mpsc::unbounded_channel();
|
||||
let supervisor = tokio::spawn(supervise(
|
||||
shutdown.clone(),
|
||||
test_policy(),
|
||||
move || {
|
||||
let attempt = runner_attempts.fetch_add(1, Ordering::SeqCst);
|
||||
async move {
|
||||
match attempt {
|
||||
0 => Err(anyhow!("short failure")),
|
||||
1 => {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
Err(anyhow!("failure after stable interval"))
|
||||
}
|
||||
_ => pending::<Result<()>>().await,
|
||||
}
|
||||
}
|
||||
},
|
||||
move |failure, delay| {
|
||||
sender.send((failure, delay)).unwrap();
|
||||
},
|
||||
));
|
||||
|
||||
let (_, first_delay) = receiver.recv().await.unwrap();
|
||||
assert_eq!(first_delay, Duration::from_millis(10));
|
||||
tokio::time::advance(first_delay).await;
|
||||
tokio::time::advance(Duration::from_millis(100)).await;
|
||||
let (failure, recovered_delay) = receiver.recv().await.unwrap();
|
||||
assert_eq!(
|
||||
failure,
|
||||
UdpFailure::Error("failure after stable interval".to_owned())
|
||||
);
|
||||
assert_eq!(recovered_delay, Duration::from_millis(10));
|
||||
tokio::time::advance(recovered_delay).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(attempts.load(Ordering::SeqCst), 3);
|
||||
|
||||
shutdown.cancel();
|
||||
supervisor.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn cancellation_aborts_hung_runner() {
|
||||
struct DropProbe(Arc<AtomicBool>);
|
||||
|
||||
impl Drop for DropProbe {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
let shutdown = CancellationToken::new();
|
||||
let attempts = Arc::new(AtomicUsize::new(0));
|
||||
let runner_attempts = attempts.clone();
|
||||
let dropped = Arc::new(AtomicBool::new(false));
|
||||
let runner_dropped = dropped.clone();
|
||||
let supervisor = tokio::spawn(supervise(
|
||||
shutdown.clone(),
|
||||
test_policy(),
|
||||
move || {
|
||||
runner_attempts.fetch_add(1, Ordering::SeqCst);
|
||||
let probe = DropProbe(runner_dropped.clone());
|
||||
async move {
|
||||
let _probe = probe;
|
||||
pending::<Result<()>>().await
|
||||
}
|
||||
},
|
||||
|_, _| {},
|
||||
));
|
||||
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(attempts.load(Ordering::SeqCst), 1);
|
||||
shutdown.cancel();
|
||||
supervisor.await.unwrap();
|
||||
assert!(dropped.load(Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn cancellation_during_backoff_prevents_restart() {
|
||||
let shutdown = CancellationToken::new();
|
||||
let attempts = Arc::new(AtomicUsize::new(0));
|
||||
let runner_attempts = attempts.clone();
|
||||
let (sender, mut receiver) = mpsc::unbounded_channel();
|
||||
let supervisor = tokio::spawn(supervise(
|
||||
shutdown.clone(),
|
||||
test_policy(),
|
||||
move || {
|
||||
runner_attempts.fetch_add(1, Ordering::SeqCst);
|
||||
async { Err(anyhow!("injected failure")) }
|
||||
},
|
||||
move |failure, delay| {
|
||||
sender.send((failure, delay)).unwrap();
|
||||
},
|
||||
));
|
||||
|
||||
let _ = receiver.recv().await.unwrap();
|
||||
shutdown.cancel();
|
||||
supervisor.await.unwrap();
|
||||
tokio::time::advance(Duration::from_secs(1)).await;
|
||||
assert_eq!(attempts.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn successful_return_is_treated_as_restartable_failure() {
|
||||
let shutdown = CancellationToken::new();
|
||||
let (sender, mut receiver) = mpsc::unbounded_channel();
|
||||
let supervisor = tokio::spawn(supervise(
|
||||
shutdown.clone(),
|
||||
test_policy(),
|
||||
|| async { Ok(()) },
|
||||
move |failure, delay| {
|
||||
sender.send((failure, delay)).unwrap();
|
||||
},
|
||||
));
|
||||
|
||||
let (failure, delay) = receiver.recv().await.unwrap();
|
||||
assert_eq!(failure, UdpFailure::Returned);
|
||||
assert_eq!(delay, Duration::from_millis(10));
|
||||
shutdown.cancel();
|
||||
supervisor.await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_initial_delay_is_bounded_by_cap() {
|
||||
let policy = RestartPolicy {
|
||||
initial_delay: Duration::from_secs(2),
|
||||
max_delay: Duration::from_millis(40),
|
||||
reset_after: Duration::from_secs(1),
|
||||
};
|
||||
assert_eq!(
|
||||
bounded_delay(policy, policy.initial_delay),
|
||||
Duration::from_millis(40)
|
||||
);
|
||||
assert_eq!(
|
||||
next_delay(policy, Duration::from_millis(40)),
|
||||
Duration::from_millis(40)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_policy_cannot_create_a_hot_loop() {
|
||||
let policy = RestartPolicy {
|
||||
initial_delay: Duration::ZERO,
|
||||
max_delay: Duration::ZERO,
|
||||
reset_after: Duration::ZERO,
|
||||
};
|
||||
assert_eq!(
|
||||
bounded_delay(policy, policy.initial_delay),
|
||||
Duration::from_millis(1)
|
||||
);
|
||||
assert_eq!(next_delay(policy, Duration::ZERO), Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user