Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b42fa20d2c |
No files matched your search
@@ -23,27 +23,13 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: actionlint handwritten workflows
|
||||
uses: raven-actions/actionlint@205b530c5d9fa8f44ae9ed59f341a0db994aa6f8
|
||||
with:
|
||||
files: >-
|
||||
.github/workflows/actions-security.yml,
|
||||
.github/workflows/ci.yml,
|
||||
.github/workflows/interop-netem.yml,
|
||||
.github/workflows/osv-scanner.yml,
|
||||
.github/workflows/rust-clippy.yml,
|
||||
.github/workflows/semver.yml,
|
||||
.github/workflows/supply-chain.yml
|
||||
- name: Run actionlint
|
||||
uses: raven-actions/actionlint@205b530c5d9fa8f44ae9ed59f341a0db994aa6f8 # v2
|
||||
|
||||
- name: actionlint generated release workflow
|
||||
uses: raven-actions/actionlint@205b530c5d9fa8f44ae9ed59f341a0db994aa6f8
|
||||
with:
|
||||
files: .github/workflows/irtt-cli-release.yml
|
||||
shellcheck: false
|
||||
zizmor:
|
||||
name: zizmor
|
||||
runs-on: ubuntu-latest
|
||||
@@ -56,11 +42,11 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Run zizmor
|
||||
uses: zizmorcore/zizmor-action@3dc1ecc9bcb9e94e9b2c709687979e1298497054 # v0.6.2
|
||||
uses: zizmorcore/zizmor-action@b1d7e1fb5de872772f31590499237e7cce841e8e # v0.5.3
|
||||
with:
|
||||
persona: regular
|
||||
+14
-84
@@ -24,12 +24,12 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Rust toolchain
|
||||
uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1
|
||||
uses: actions-rust-lang/setup-rust-toolchain@46268bd060767258de96ed93c1251119784f2ab6 # v1
|
||||
with:
|
||||
components: rustfmt
|
||||
cache-key: fmt
|
||||
@@ -44,12 +44,12 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Rust toolchain
|
||||
uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1
|
||||
uses: actions-rust-lang/setup-rust-toolchain@46268bd060767258de96ed93c1251119784f2ab6 # v1
|
||||
with:
|
||||
components: clippy
|
||||
cache-key: clippy
|
||||
@@ -63,98 +63,28 @@ jobs:
|
||||
--locked \
|
||||
-- -D warnings
|
||||
|
||||
- name: Run clippy without default features
|
||||
run: |
|
||||
cargo clippy \
|
||||
--workspace \
|
||||
--all-targets \
|
||||
--no-default-features \
|
||||
--locked \
|
||||
-- -D warnings
|
||||
|
||||
verify:
|
||||
name: cargo ${{ matrix.task }} (${{ matrix.target }})
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- task: check
|
||||
runner: ubuntu-24.04
|
||||
target: x86_64-unknown-linux-gnu
|
||||
musl: false
|
||||
|
||||
- task: test
|
||||
runner: ubuntu-24.04
|
||||
target: x86_64-unknown-linux-gnu
|
||||
musl: false
|
||||
|
||||
- task: check
|
||||
runner: ubuntu-24.04
|
||||
target: x86_64-unknown-linux-musl
|
||||
musl: true
|
||||
|
||||
- task: test
|
||||
runner: ubuntu-24.04
|
||||
target: x86_64-unknown-linux-musl
|
||||
musl: true
|
||||
|
||||
- task: check
|
||||
runner: ubuntu-24.04-arm
|
||||
target: aarch64-unknown-linux-gnu
|
||||
musl: false
|
||||
|
||||
- task: test
|
||||
runner: ubuntu-24.04-arm
|
||||
target: aarch64-unknown-linux-gnu
|
||||
musl: false
|
||||
|
||||
- task: check
|
||||
runner: ubuntu-24.04-arm
|
||||
target: aarch64-unknown-linux-musl
|
||||
musl: true
|
||||
|
||||
- task: test
|
||||
runner: ubuntu-24.04-arm
|
||||
target: aarch64-unknown-linux-musl
|
||||
musl: true
|
||||
|
||||
runs-on: ${{ matrix.runner }}
|
||||
test:
|
||||
name: cargo test
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 25
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install musl toolchain
|
||||
if: matrix.musl
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install --no-install-recommends musl-tools
|
||||
|
||||
- name: Install Rust toolchain
|
||||
uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1
|
||||
uses: actions-rust-lang/setup-rust-toolchain@46268bd060767258de96ed93c1251119784f2ab6 # v1
|
||||
with:
|
||||
target: ${{ matrix.target }}
|
||||
cache-key: ${{ matrix.task }}-${{ matrix.target }}
|
||||
cache-key: test
|
||||
|
||||
- name: Run ${{ matrix.task }} with all features
|
||||
- name: Run tests
|
||||
run: |
|
||||
cargo ${{ matrix.task }} \
|
||||
cargo test \
|
||||
--workspace \
|
||||
--all-targets \
|
||||
--all-features \
|
||||
--target ${{ matrix.target }} \
|
||||
--locked
|
||||
|
||||
- name: Run ${{ matrix.task }} without default features
|
||||
run: |
|
||||
cargo ${{ matrix.task }} \
|
||||
--workspace \
|
||||
--all-targets \
|
||||
--no-default-features \
|
||||
--target ${{ matrix.target }} \
|
||||
--locked
|
||||
|
||||
docs:
|
||||
@@ -167,12 +97,12 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Rust toolchain
|
||||
uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1
|
||||
uses: actions-rust-lang/setup-rust-toolchain@46268bd060767258de96ed93c1251119784f2ab6 # v1
|
||||
with:
|
||||
cache-key: docs
|
||||
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
name: Netem Interop
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
GOBIN: ${{ github.workspace }}/.tools/bin
|
||||
IRTT_UPSTREAM_VERSION: v0.9.1
|
||||
|
||||
jobs:
|
||||
netem:
|
||||
name: netem interop
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 25
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Rust toolchain
|
||||
uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1
|
||||
with:
|
||||
cache-key: interop-netem
|
||||
|
||||
- name: Check host tools
|
||||
run: |
|
||||
ip -V
|
||||
tc -V
|
||||
go version
|
||||
|
||||
- name: Install upstream irtt
|
||||
run: |
|
||||
mkdir -p "$GOBIN"
|
||||
go install "github.com/heistp/irtt/cmd/irtt@${IRTT_UPSTREAM_VERSION}"
|
||||
"$GOBIN/irtt" version
|
||||
|
||||
- name: Build irtt-rs CLI
|
||||
run: cargo build -p irtt-cli --locked
|
||||
|
||||
- name: Run netem interop comparisons
|
||||
run: |
|
||||
python3 scripts/run_netem_interop_ci.py \
|
||||
--all \
|
||||
--skip-build \
|
||||
--upstream-irtt "$GOBIN/irtt" \
|
||||
--irtt-rs-command "$PWD/target/debug/irtt-cli"
|
||||
|
||||
- name: Append netem interop summary
|
||||
if: always()
|
||||
run: |
|
||||
latest_summary="$(find target/interop-netem -mindepth 2 -maxdepth 2 -name github-step-summary.md -type f -print 2>/dev/null | sort | tail -n 1)"
|
||||
if [ -n "$latest_summary" ]; then
|
||||
cat "$latest_summary" >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
echo "No netem interop github-step-summary.md found." >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
|
||||
- name: Upload netem interop artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: interop-netem
|
||||
path: target/interop-netem
|
||||
@@ -31,7 +31,7 @@ permissions:
|
||||
jobs:
|
||||
scan-scheduled:
|
||||
if: ${{ github.event_name == 'push' || github.event_name == 'schedule' }}
|
||||
uses: "google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml@8deb546fdb875b9996d27d4950be7312dac076a1" # v2.5.0
|
||||
uses: "google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml@9a498708959aeaef5ef730655706c5a1df1edbc2" # v2.3.8
|
||||
with:
|
||||
# Example of specifying custom arguments
|
||||
scan-args: |-
|
||||
@@ -40,7 +40,7 @@ jobs:
|
||||
./
|
||||
scan-pr:
|
||||
if: ${{ github.event_name == 'pull_request' || github.event_name == 'merge_group' }}
|
||||
uses: "google/osv-scanner-action/.github/workflows/osv-scanner-reusable-pr.yml@8deb546fdb875b9996d27d4950be7312dac076a1" # v2.5.0
|
||||
uses: "google/osv-scanner-action/.github/workflows/osv-scanner-reusable-pr.yml@9a498708959aeaef5ef730655706c5a1df1edbc2" # v2.3.8
|
||||
with:
|
||||
# Example of specifying custom arguments
|
||||
scan-args: |-
|
||||
|
||||
@@ -42,7 +42,7 @@ on:
|
||||
pull_request:
|
||||
push:
|
||||
tags:
|
||||
- 'irtt-cli**[0-9]+.[0-9]+.[0-9]+*'
|
||||
- '**[0-9]+.[0-9]+.[0-9]+*'
|
||||
|
||||
jobs:
|
||||
# Run 'dist plan' (or host) to determine what tasks we need to do
|
||||
@@ -64,9 +64,9 @@ jobs:
|
||||
# we specify bash to get pipefail; it guards against the `curl` command
|
||||
# failing. otherwise `sh` won't catch that `curl` returned non-0
|
||||
shell: bash
|
||||
run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.32.0/cargo-dist-installer.sh | sh"
|
||||
run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.31.0/cargo-dist-installer.sh | sh"
|
||||
- name: Cache dist
|
||||
uses: actions/upload-artifact@v7
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: cargo-dist-cache
|
||||
path: ~/.cargo/bin/dist
|
||||
@@ -82,7 +82,7 @@ jobs:
|
||||
cat plan-dist-manifest.json
|
||||
echo "manifest=$(jq -c "." plan-dist-manifest.json)" >> "$GITHUB_OUTPUT"
|
||||
- name: "Upload dist-manifest.json"
|
||||
uses: actions/upload-artifact@v7
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: artifacts-plan-dist-manifest
|
||||
path: plan-dist-manifest.json
|
||||
@@ -131,7 +131,7 @@ jobs:
|
||||
run: ${{ matrix.install_dist.run }}
|
||||
# Get the dist-manifest
|
||||
- name: Fetch local artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
pattern: artifacts-*
|
||||
path: target/distrib/
|
||||
@@ -158,7 +158,7 @@ jobs:
|
||||
|
||||
cp dist-manifest.json "$BUILD_MANIFEST_NAME"
|
||||
- name: "Upload artifacts"
|
||||
uses: actions/upload-artifact@v7
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: artifacts-build-local-${{ join(matrix.targets, '_') }}
|
||||
path: |
|
||||
@@ -180,14 +180,14 @@ jobs:
|
||||
persist-credentials: false
|
||||
submodules: recursive
|
||||
- name: Install cached dist
|
||||
uses: actions/download-artifact@v8
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: cargo-dist-cache
|
||||
path: ~/.cargo/bin/
|
||||
- run: chmod +x ~/.cargo/bin/dist
|
||||
# Get all the local artifacts for the global tasks to use (for e.g. checksums)
|
||||
- name: Fetch local artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
pattern: artifacts-*
|
||||
path: target/distrib/
|
||||
@@ -205,7 +205,7 @@ jobs:
|
||||
|
||||
cp dist-manifest.json "$BUILD_MANIFEST_NAME"
|
||||
- name: "Upload artifacts"
|
||||
uses: actions/upload-artifact@v7
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: artifacts-build-global
|
||||
path: |
|
||||
@@ -230,14 +230,14 @@ jobs:
|
||||
persist-credentials: false
|
||||
submodules: recursive
|
||||
- name: Install cached dist
|
||||
uses: actions/download-artifact@v8
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: cargo-dist-cache
|
||||
path: ~/.cargo/bin/
|
||||
- run: chmod +x ~/.cargo/bin/dist
|
||||
# Fetch artifacts from scratch-storage
|
||||
- name: Fetch artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
pattern: artifacts-*
|
||||
path: target/distrib/
|
||||
@@ -250,14 +250,14 @@ jobs:
|
||||
cat dist-manifest.json
|
||||
echo "manifest=$(jq -c "." dist-manifest.json)" >> "$GITHUB_OUTPUT"
|
||||
- name: "Upload dist-manifest.json"
|
||||
uses: actions/upload-artifact@v7
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
# Overwrite the previous copy
|
||||
name: artifacts-dist-manifest
|
||||
path: dist-manifest.json
|
||||
# Create a GitHub Release while uploading all files to it
|
||||
- name: "Download GitHub Artifacts"
|
||||
uses: actions/download-artifact@v8
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
pattern: artifacts-*
|
||||
path: artifacts
|
||||
@@ -24,12 +24,12 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Rust toolchain
|
||||
uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1
|
||||
uses: actions-rust-lang/setup-rust-toolchain@46268bd060767258de96ed93c1251119784f2ab6 # v1
|
||||
with:
|
||||
components: clippy
|
||||
cache-key: clippy-sarif
|
||||
@@ -60,7 +60,7 @@ jobs:
|
||||
exit 0
|
||||
|
||||
- name: Upload Clippy SARIF
|
||||
uses: github/codeql-action/upload-sarif@ff2f1c621b7f889edc0d3c761ac2e6a3f8cdb0dd # v4
|
||||
uses: github/codeql-action/upload-sarif@68bde559dea0fdcac2102bfdf6230c5f70eb485e # v4
|
||||
if: always()
|
||||
with:
|
||||
sarif_file: rust-clippy-results.sarif
|
||||
|
||||
@@ -4,11 +4,7 @@ on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
tags:
|
||||
- "irtt-proto/v*.*.*"
|
||||
- "irtt-client/v*.*.*"
|
||||
- "irtt-server/v*.*.*"
|
||||
- "irtt-stats/v*.*.*"
|
||||
- "irtt-cli/v*.*.*"
|
||||
- "v*.*.*"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -21,7 +17,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
|
||||
@@ -38,12 +38,12 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Run cargo-deny
|
||||
uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2
|
||||
uses: EmbarkStudios/cargo-deny-action@6c8f9facfa5047ec02d8485b6bf52b587b7777d1 # v2
|
||||
with:
|
||||
command: check
|
||||
arguments: --all-features
|
||||
@@ -56,24 +56,9 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: actionlint handwritten workflows
|
||||
uses: raven-actions/actionlint@205b530c5d9fa8f44ae9ed59f341a0db994aa6f8
|
||||
with:
|
||||
files: >-
|
||||
.github/workflows/actions-security.yml,
|
||||
.github/workflows/ci.yml,
|
||||
.github/workflows/interop-netem.yml,
|
||||
.github/workflows/osv-scanner.yml,
|
||||
.github/workflows/rust-clippy.yml,
|
||||
.github/workflows/semver.yml,
|
||||
.github/workflows/supply-chain.yml
|
||||
|
||||
- name: actionlint generated release workflow
|
||||
uses: raven-actions/actionlint@205b530c5d9fa8f44ae9ed59f341a0db994aa6f8
|
||||
with:
|
||||
files: .github/workflows/irtt-cli-release.yml
|
||||
shellcheck: false
|
||||
- name: Run actionlint
|
||||
uses: raven-actions/actionlint@205b530c5d9fa8f44ae9ed59f341a0db994aa6f8 # v2
|
||||
@@ -1,198 +0,0 @@
|
||||
# Repository guidance
|
||||
|
||||
Repository-wide guidance for contributors and coding agents working on `irtt-rs`.
|
||||
Before editing, also check for a more specific `AGENTS.md` in the target subtree.
|
||||
|
||||
## Clean-room boundary
|
||||
|
||||
`irtt-rs` is an independent Rust implementation of an IRTT-compatible protocol stack. It began as a clean-room client reimplementation and now contains project-specific architecture and behavior beyond that original compatibility baseline.
|
||||
|
||||
- Do not inspect, quote, copy, translate, or derive implementation details from upstream `heistp/irtt` source code or upstream tests.
|
||||
- Do not use contaminated notes or source-derived pseudocode as implementation input.
|
||||
- Use the local clean-room specification, black-box verification artifacts, current `irtt-rs` code, and current tests.
|
||||
- Black-box interoperability testing against an installed upstream `irtt` binary is allowed when relevant. Treat it as an external implementation, not source material.
|
||||
- If behavior remains ambiguous, state the ambiguity instead of guessing or consulting upstream implementation code.
|
||||
|
||||
Compatibility and interoperability references:
|
||||
|
||||
- `docs/protocol/IRTT_CLIENT_PROTOCOL_SPEC.md` — verified client-side
|
||||
compatibility baseline.
|
||||
- `docs/protocol/IRTT_SERVER_PROTOCOL_SPEC.md` — verified server-side
|
||||
compatibility baseline.
|
||||
- `docs/protocol/BLACKBOX_VERIFICATION_REPORT.md` — black-box evidence and
|
||||
corrections supporting both the client and server baselines.
|
||||
- `docs/protocol/test-vectors/README.md` — captured client-facing packet
|
||||
vectors.
|
||||
- `docs/protocol/test-vectors/SERVER_BEHAVIORAL_VECTORS.md` — black-box
|
||||
server behavioral vectors, edge cases, and session behavior.
|
||||
- `docs/protocol/captures/` — packet captures referenced by the verification
|
||||
report and behavioral vectors. Behavioral vectors and captures are
|
||||
evidence/artifacts, not architecture prescriptions.
|
||||
- `docs/INTEROP_COMPARISON.md` — procedures for black-box comparison against
|
||||
the upstream `irtt` executable.
|
||||
- `docs/clean-room/CLEANROOM_NOTES.md` — provenance only; not a normative
|
||||
protocol specification.
|
||||
|
||||
The verified client spec predates later `irtt-rs` architecture and project-specific features. Its scope statements, including server implementation being out of scope, describe that document's scope and are not permanent repository restrictions.
|
||||
|
||||
For compatibility questions, the verified spec and black-box observations define the baseline. For `irtt-rs`-specific APIs, runtime architecture, resource bounds, and later features, current code and current project documentation are authoritative.
|
||||
|
||||
## Architecture
|
||||
|
||||
Main boundary:
|
||||
|
||||
> `irtt-proto` — wire semantics shared by client/server. `irtt-client` — client/session behavior. `irtt-server` — server/session behavior and Tokio runtime/orchestration. `irtt-stats` — statistics over client-facing events/results as currently designed. `irtt-cli` — presentation/orchestration.
|
||||
|
||||
- `irtt-proto`: pure protocol encoding/decoding, flags, layouts, params, varints/zigzag, HMAC-MD5, validation. No sockets, runtimes, lifecycle, stats, or presentation.
|
||||
- `irtt-client`: socket/session lifecycle, negotiation, probe send/receive, timing metadata, classification, bounded state, and events.
|
||||
- `Client`: runtime-free blocking/manual adapter.
|
||||
- `AsyncClient`: optional Tokio low-level adapter.
|
||||
- `ManagedClientTask` / `ManagedClientHandle`: unified Tokio managed driver/control surface.
|
||||
- `BlockingManagedClient`: synchronous owner using a dedicated current-thread Tokio runtime.
|
||||
- `irtt-server`: exists; see "Server architecture (`irtt-server`)" below.
|
||||
- `irtt-stats`: cumulative/rolling/finite statistics over client events. No wire/session state machine logic.
|
||||
- `irtt-cli`: argument parsing, managed orchestration, output, summaries, TUI, server applet orchestration, diagnostics, and exit behavior. Do not duplicate protocol/session state machines here.
|
||||
|
||||
Tokio must remain optional for `irtt-client`; default builds must remain runtime-free and Tokio-free unless an explicit architectural change says otherwise. This rule is specific to `irtt-client` — do not generalize it to `irtt-server`, which has the opposite policy below.
|
||||
|
||||
### Server architecture (`irtt-server`)
|
||||
|
||||
`irtt-server` is a first-class reusable server crate. It contains the deterministic OPEN/ECHO/session core — packet admission, authentication policy, open negotiation, the bounded session table, open reply construction, echo processing with its per-session receive state and timestamps, per-session rate limiting, session lifetime with idle expiry, the maximum-duration server-initiated close, and client-initiated close — plus a reusable Tokio UDP `Server` that runs one sequential `ServerCore` per listener with caller-controlled shutdown and scheduled idle maintenance. Logical expiry remains exact on authenticated, structurally valid requests, while the runtime also reclaims expired sessions once per second when no traffic arrives. Each reply carries the raw traffic class it must be sent with, which the runtime applies to the listener before every send. A wildcard listener additionally recovers each request's local destination from packet metadata and sends that request's reply from it, on Linux, macOS and FreeBSD; a wildcard bind on a target without that path is refused at construction rather than served from a routing-table source address. Explicit-address listeners are unaffected everywhere. Echo replies fill their payload from the session's negotiated server fill; the policy and its deliberate divergences are in `crates/irtt-server/AGENTS.md`. Two optional negotiation policies restrict what a session may ask the server to provide — a timestamp allowance and DSCP permission — both off by default and both settled during open negotiation rather than in the runtime. Above that one-listener primitive sits `ServerSet`, the service-level owner of one or more independent `Server`s: it binds them all or none, runs each in its own Tokio task, fans one external shutdown out to them, joins them all, and fails the group if any listener fails or stops early. Ordinary process-level polish and observability decisions are what remains of the server architecture.
|
||||
|
||||
- It shares wire semantics with the client through `irtt-proto` and follows the same clean-room boundary.
|
||||
- It must **not** depend on `irtt-client` merely to reuse protocol behavior.
|
||||
- Unlike `irtt-client`, the server has no product requirement to remain runtime-free: `irtt-server` is intentionally **Tokio-native**, and Tokio does not need to be optional for it.
|
||||
- There is currently no requirement for a blocking server API, alternate async runtimes, a runtime abstraction layer, or a runtime-free server feature. Do not build blocking/runtime variants merely for symmetry with the client, and do not invent a mirrored client-style API family (`BlockingServer`, `AsyncServer`, `ManagedServer`, `BlockingManagedServer`, or similar) ahead of agreement.
|
||||
- Protocol/session logic should be separated from socket/runtime orchestration where that materially improves deterministic testing, ownership clarity, state-machine reasoning, or maintainability. A `ServerCore`-like internal boundary is therefore desirable, but its exact name/API is not prescribed, it need not be public, it is not a promise of runtime independence, and simple code should not be tortured merely to make the core artificially pure.
|
||||
- Runtime/server orchestration belongs around that core and may freely use Tokio for UDP sockets, `recv_from`/`send_to`, IPv4/IPv6 listeners, timers, session expiry, max-duration deadlines, shutdown, bounded control/config channels where useful, and `select!`-style orchestration.
|
||||
- Ownership is layered and the layers do not blur: `Server` is the one-listener primitive (one socket, one `ServerCore`, one sequential loop), and `ServerSet` supervises one or more of them without owning protocol or session state itself. A common `ServerConfig` is cloned into each listener, so its bounds — `max_sessions` included — are per listener and not per process. Listeners share nothing else: no shared `ServerCore`, no global session table or token namespace, no shared clock, and one sequential sender per socket, which is what keeps the socket-wide reply traffic class race-free.
|
||||
- The CLI server applet exists behind the `irtt-cli` `server` feature, which is part of that crate's default build. It is thin orchestration/configuration over reusable `irtt-server` — one current-thread Tokio runtime, one repeatable `--bind`, one `ServerSet` — and must not grow a second server state machine. **It always uses `ServerSet`, including for a single bind**: there is no direct CLI-to-`Server` path and no bind-count branch, so startup, shutdown and listener-failure semantics are identical whatever was configured, and the singleton case exercises the same orchestration in normal use. Hostname resolution, interface expansion, daemonization, and configuration files are deliberately absent.
|
||||
- Resource policy: the server should use bounded session/resource policy. Upstream's observed lack of useful default session/per-peer bounds, and its never expiring a session that has not carried an echo request (see `IRTT_SERVER_PROTOCOL_SPEC.md`), are not interoperability requirements and must not be reproduced merely for compatibility.
|
||||
- Testing: prefer `irtt-server` for normal compliant fake-peer behavior where practical, as far as its implemented behavior reaches. Keep narrow adversarial/raw peers for intentionally malformed, ambiguous, or non-compliant wire behavior.
|
||||
|
||||
## Engineering rules
|
||||
|
||||
- Make the smallest coherent change that solves the requested problem.
|
||||
- Avoid unrelated cleanup and speculative abstractions.
|
||||
- Preserve public API and wire behavior unless the task explicitly changes them.
|
||||
- Treat resource bounds, wake behavior, blocking, cancellation, cleanup, and lifecycle termination as correctness concerns in long-running code.
|
||||
- Keep fallible preparation before irreversible side effects where transaction semantics require it.
|
||||
- Do not suppress compiler or Clippy warnings merely to make checks green.
|
||||
- If an apparent defect may encode an intentional design decision, inspect surrounding code/docs/history and ask rather than silently redesigning it.
|
||||
|
||||
## Testing policy
|
||||
|
||||
Tests protect durable behavior, compatibility, and important invariants. They do not exist to maximize test count or coverage percentage.
|
||||
|
||||
### Prefer behavior over internals
|
||||
|
||||
For client, managed-runtime, blocking, CLI, and TUI behavior, prefer normal-interface component/integration tests: real UDP/session exchange, emitted events/outcomes, negotiated params, multi-target lifecycle, process exit status, and user-visible diagnostics.
|
||||
|
||||
One strong behavioral test is usually better than several tests of private helpers that reconstruct the same behavior.
|
||||
|
||||
Do not add persistent tests merely because implementation code changed. Avoid tests that primarily:
|
||||
|
||||
- assert private fields, cursors, queue shapes, or exact internal representation;
|
||||
- mirror implementation steps line-for-line;
|
||||
- exercise branches/helpers solely for coverage;
|
||||
- duplicate stronger coverage at another layer;
|
||||
- pin incidental scheduling/ordering that is not contractual;
|
||||
- test standard-library/dependency behavior;
|
||||
- require production test-only observability for a fact naturally visible through packets/events/outcomes.
|
||||
|
||||
A harmless private refactor should not require widespread test rewrites unless a deliberately protected invariant changed.
|
||||
|
||||
### Unit tests where they earn it
|
||||
|
||||
Focused unit/table-driven tests are encouraged for stable pure or algorithmic behavior, especially:
|
||||
|
||||
- `irtt-proto` layouts, codecs, vectors, HMAC, parsing, malformed input, and boundaries;
|
||||
- `irtt-stats` formulas, loss accounting, IPDV, rolling windows, and bounded state;
|
||||
- hand-rolled data structures and subtle pure invariants;
|
||||
- resource/liveness guarantees that cannot be observed reliably from a higher layer.
|
||||
|
||||
If a unit test and a normal-interface test prove the same durable behavior, prefer the normal-interface test unless the unit test materially improves precision or diagnosis.
|
||||
|
||||
### Temporary implementation tests
|
||||
|
||||
Temporary narrow tests are welcome while implementing/debugging a change to prove a hypothesis, reproduce a bug, or exercise a difficult state transition.
|
||||
|
||||
Before finalizing, remove or consolidate them unless they independently protect a durable regression or invariant. A test being useful during development does not by itself justify permanent repository code.
|
||||
|
||||
### Resource/liveness tests and hooks
|
||||
|
||||
Direct low-level tests and test-only counters are justified when the invariant is otherwise not observable, e.g. bounded work per poll, no starvation/eventual progress, avoiding an otherwise O(n) hot-path operation, or exact cancellation/stop/update linearization.
|
||||
|
||||
Assert the invariant rather than the current mechanism used to achieve it. Prefer “bounded work and eventual progress” over a specific private cursor value when another fair implementation would also be valid.
|
||||
|
||||
`#[cfg(test)]` fault injection is acceptable for conditions that cannot be produced reliably through normal interfaces, such as socket-option failures, short sends, false readiness, exact cancellation points, sequence wrap, or race linearization. Do not add test-only production hooks solely for convenient observability.
|
||||
|
||||
### Fake peers and interoperability
|
||||
|
||||
Use production protocol encoders/decoders for compliant fake peers. Do not maintain shadow packet encoders in tests unless intentionally constructing malformed wire data.
|
||||
|
||||
Prefer a real `irtt-server` for normal compliant behavior once available; keep small adversarial peers for behavior a compliant server should not produce.
|
||||
|
||||
Cross-implementation tests are especially valuable because two `irtt-rs` endpoints can otherwise agree on the same mistake.
|
||||
|
||||
When compatibility is in question, prefer black-box interoperability testing
|
||||
against an upstream `irtt` executable where practical. Follow
|
||||
`docs/INTEROP_COMPARISON.md` and treat upstream only as an external executable;
|
||||
do not inspect its source or tests.
|
||||
|
||||
### Synchronization and timing
|
||||
|
||||
Prefer synchronization on actual events/state over sleeps or tiny wall-clock windows.
|
||||
|
||||
- Use channels, condvars, packet gates, or equivalent deterministic signals with bounded failure timeouts.
|
||||
- Sleeps are fine when oversleeping cannot invalidate correctness; do not sleep merely hoping another thread/process finished work.
|
||||
- Avoid wall-clock assertions that include process spawn or unrelated setup time.
|
||||
- Condition-wait loops must be bounded and fail with a useful diagnostic rather than hang.
|
||||
|
||||
When a test fails after a legitimate implementation change, determine whether production regressed or the harness encoded an invalid assumption. Do not change correct production behavior merely to satisfy a brittle test.
|
||||
|
||||
## Workflow and verification
|
||||
|
||||
For non-trivial work:
|
||||
|
||||
1. Inspect relevant code, tests, and local protocol/design references.
|
||||
2. Identify the externally meaningful contract or internal invariant.
|
||||
3. Make a short plan for multi-file or subtle lifecycle/state changes.
|
||||
4. Implement the smallest coherent patch.
|
||||
5. Run focused verification while iterating.
|
||||
6. Review the final diff for accidental scope, brittle tests, and unnecessary test hooks.
|
||||
7. Run broader verification appropriate to the risk.
|
||||
|
||||
Skip planning ceremony for tiny obvious edits. Do not add unrelated tests, abstractions, docs, or refactors merely because they are nearby.
|
||||
|
||||
Use the narrowest useful checks first. For substantive workspace changes, final verification should normally include:
|
||||
|
||||
```sh
|
||||
cargo fmt --all -- --check
|
||||
cargo check --workspace --all-targets --all-features --locked
|
||||
cargo test --workspace --all-targets --all-features --locked
|
||||
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
|
||||
```
|
||||
|
||||
Also verify `--no-default-features` when changing feature gates, optional dependencies, runtime boundaries, or code intended to build without Tokio.
|
||||
|
||||
Interop tests require an external `irtt` binary and should only run when the task concerns interoperability or explicitly requests them. Do not run repetition loops, fuzzing, Miri, Loom, mutation testing, or similar expensive checks as routine ceremony.
|
||||
|
||||
Never claim a command passed unless it actually ran successfully.
|
||||
|
||||
## Repository hygiene
|
||||
|
||||
- Do not use destructive Git operations unless explicitly requested.
|
||||
- Do not push, force-push, create/update a PR, or rewrite unrelated history unless explicitly requested.
|
||||
- Keep commits scoped to the requested work and preserve unrelated local changes.
|
||||
|
||||
## Completion
|
||||
|
||||
Report concisely:
|
||||
|
||||
1. what changed;
|
||||
2. verification actually run and its result;
|
||||
3. meaningful tests added/updated/consolidated/removed;
|
||||
4. remaining risks, ambiguities, or follow-ups.
|
||||
|
||||
Do not produce a giant changelog of incidental edits.
|
||||
-130
@@ -1,130 +0,0 @@
|
||||
# Changelog
|
||||
|
||||
This project's crates are versioned independently. Each release below is
|
||||
scoped to a single crate and tagged as `<crate>/vX.Y.Z` (see
|
||||
[Releasing](#releasing) below).
|
||||
|
||||
All notable changes to each crate are documented in its own section per
|
||||
release. The format is loosely based on
|
||||
[Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
|
||||
|
||||
## irtt-proto
|
||||
|
||||
### 0.5.0
|
||||
|
||||
#### Added
|
||||
|
||||
- New server-direction wire codecs: `decode_open_request`, `encode_open_reply`, `decode_echo_request`, `encode_echo_reply`, and `decode_close_request`, so a server implementation (now `irtt-server`) can encode/decode the same wire format the client side already used, instead of duplicating protocol logic outside this crate.
|
||||
- New `ProtoError` variants `MissingField` and `UnexpectedField` for structural validation of optional fields that must be present/absent together.
|
||||
|
||||
#### Changed
|
||||
|
||||
- `encode_echo_request` (and the request-side echo codec generally) now takes the negotiated params as a separate argument rather than bundling them into `EchoRequest` — a breaking signature change for any direct caller of the proto-level echo encoder.
|
||||
- `ProtoError::NegativePacketLength` was renamed to `ProtoError::PacketLengthUnrepresentable { length: i64 }`, reflecting that the check now rejects any length that doesn't fit the wire representation, not only negative ones — a breaking rename for callers matching on this variant.
|
||||
|
||||
#### Compatibility
|
||||
|
||||
- The echo-reply length codec now accepts upstream `irtt`'s longer midpoint-echo compatibility length instead of rejecting it, fixing an interop gap against real upstream servers/clients that send that length.
|
||||
|
||||
## irtt-client
|
||||
|
||||
### 0.5.0
|
||||
|
||||
#### Added
|
||||
|
||||
- New optional `tokio` Cargo feature adding `AsyncClient`, a low-level non-blocking/poll-based Tokio adapter alongside the existing runtime-free blocking `Client`.
|
||||
- New managed driver stack built on top of `AsyncClient`: `ManagedClientTask` / `ManagedClientHandle` (a unified Tokio-based managed driver and control surface, supporting dynamic per-target updates to a running session group) and `BlockingManagedClient` (a synchronous owner that runs a dedicated current-thread Tokio runtime internally). This replaces the project's earlier managed-client design outright rather than extending it, including changes to the `ClientError` variants it can surface.
|
||||
- Linux kernel receive-timestamp capture (`SO_TIMESTAMPING`-family ancillary data) feeding one-way-delay (OWD) calculations, and equivalent kernel transmit-timestamp capture on the send side, materially improving OWD accuracy over the previous best-effort user-space send/receive timestamps on Linux. Both require the `ancillary` feature.
|
||||
|
||||
#### Fixed
|
||||
|
||||
- DSCP wire semantics: the negotiated DSCP value was being shifted twice on the wire path (double-application of the ECN/DSCP bit layout), which produced an incorrect traffic-class byte in some configurations; the client-side DSCP handling was reworked to apply the shift exactly once and is covered by expanded DSCP/negotiation tests.
|
||||
- Post-send timestamp capture correctness fix so the locally-recorded send timestamp used for OWD/RTT calculations reflects when the probe actually left the socket rather than a timestamp that could be skewed by scheduling between encode and send.
|
||||
- A batch of managed-session liveness and lifecycle fixes: dynamic target groups no longer spin instead of blocking while idle; empty dynamic groups stay idle correctly; peer-initiated closes are now recorded and surfaced (including counters/provenance) instead of being silently dropped or racing with correlation; authenticated close is honored ahead of reply correlation; terminal outcomes are now published for targets that fail rather than being dropped silently; completed event hubs are sealed and completed-target retention is bounded (preventing unbounded growth in long multi-target runs); missed probe slots are skipped rather than mis-scheduled; dropped-subscription events are now exposed to consumers instead of being swallowed; and a timeout-budget bug in the managed opening phase was corrected.
|
||||
- Linux receive paths (blocking `Client::open`/`recv_once`/`recv_available`, `AsyncClient`'s non-blocking recv/open polling, and the MSG_ERRQUEUE TX-timestamp drain) now retry transparently on `EINTR` instead of surfacing it as a fatal socket error, while preserving each path's existing timeout/deadline contract (no retransmit, no timeout extension under repeated interruption).
|
||||
- `ClientError` failure classification was made exhaustive/more precise, giving callers a fuller and more accurate error taxonomy to match on instead of a catch-all in some paths.
|
||||
|
||||
#### Compatibility
|
||||
|
||||
- The `ancillary` (Linux socket ancillary-data) feature was hardened to only perform safe operations, closing a soundness gap in how ancillary control-message buffers were handled.
|
||||
|
||||
## irtt-server
|
||||
|
||||
### 0.5.0
|
||||
|
||||
#### Added
|
||||
|
||||
- `irtt-server` is a new first-class, reusable crate this release, built from scratch: a deterministic `ServerCore` handling OPEN/ECHO/CLOSE packet admission, authentication policy, open negotiation, a bounded session table, echo processing with per-session receive state and timestamps, per-session rate limiting, session lifetime with idle expiry, server-initiated close on maximum duration, and client-initiated close.
|
||||
- A reusable Tokio UDP `Server` runs one sequential `ServerCore` per listener with caller-controlled shutdown and once-per-second scheduled idle-session maintenance (in addition to exact logical expiry on authenticated, structurally valid requests). `ServerSet` sits above it as the service-level owner of one or more independent `Server`s: it binds them all-or-none, runs each in its own Tokio task, fans one external shutdown signal out to all of them, joins them, and fails the group if any listener fails or stops early — enabling multi-listener deployments from a single `ServerConfig`.
|
||||
- Each reply now carries the raw traffic class it must be sent with, applied to the listener socket immediately before every send.
|
||||
- Wildcard listeners recover each request's local destination from packet ancillary metadata and send that request's reply from the same address, on Linux, macOS, and FreeBSD. `Server::from_socket`/`Server::bind` are now fallible specifically because of this: a wildcard bind on a platform without that path is refused at construction (`ServerRuntimeError::WildcardSourceSelectionUnsupported`) rather than silently served from a routing-table-chosen source address. Explicit-address listeners are unaffected on all platforms.
|
||||
- Configurable echo-reply payload fill policy (`ServerFill`), controlling what bytes a session's echo replies are padded with.
|
||||
- Two optional negotiation policies, both off by default and settled during open negotiation: a timestamp allowance and a DSCP permission, restricting what a session may ask the server to provide.
|
||||
- Linux kernel receive-timestamp capture for inbound packets, feeding more accurate server-side timing metadata, mirroring the equivalent client-side capability added in `irtt-client`.
|
||||
|
||||
#### Fixed
|
||||
|
||||
- The DSCP/traffic-class byte applied to replies was corrected to match the client-side wire-semantics fix (see `irtt-client`), so server-echoed DSCP marking is now consistent with what clients expect.
|
||||
- Executable-params validation on OPEN requests was tightened so malformed/contradictory negotiated parameters are rejected during open negotiation rather than accepted and mishandled later.
|
||||
- Packet-length policy corrected so oversized/invalid negotiated lengths are rejected consistently with the updated `irtt-proto` length validation.
|
||||
- A receive-drop/backpressure policy fix for malformed or unauthenticated inbound packets, preventing them from disrupting the session table or other in-flight sessions.
|
||||
- A receive-timestamp "wall clock" fix on the kernel RX-capture path, and a 32-bit (i686) `timespec` conversion correctness fix covered by a dedicated regression test.
|
||||
- The server's ancillary receive loop now retries transparently on `EINTR` instead of terminating the listener, matching the equivalent `irtt-client` fix.
|
||||
|
||||
#### Compatibility
|
||||
|
||||
- Resource bounds are enforced by design (bounded session table, per-listener `max_sessions`, rate limiting, idle/max-duration expiry) rather than mirroring upstream `irtt`'s effectively unbounded session/per-peer behavior; this is a deliberate divergence, not an oversight, and is documented in `crates/irtt-server/AGENTS.md`.
|
||||
|
||||
## irtt-stats
|
||||
|
||||
### 0.5.0
|
||||
|
||||
#### Fixed
|
||||
|
||||
- Exact median calculation for `send_call`, `timer_error`, and `server_processing` event-duration statistics, which previously always reported `None` for these medians instead of a computed value.
|
||||
|
||||
#### Added
|
||||
|
||||
- `LateReplyMode` (`Measure` / `CountOnly`) lets a consumer choose whether replies that arrive after their probe is considered late are still fully measured into the running statistics or only counted, without affecting the other samples.
|
||||
- `StatsConfig::estimated_retained_bytes(probe_count)` gives callers an API to estimate the memory a stats configuration will retain for a given probe count, ahead of actually running a session (used by `irtt-cli`'s multi-target memory-usage warning, see below).
|
||||
|
||||
## irtt-cli
|
||||
|
||||
### 0.5.0
|
||||
|
||||
#### Added
|
||||
|
||||
- A new `server` applet (the `irtt-server` binary and `irtt-rs server` subcommand), gated behind the `server` Cargo feature which is now part of `irtt-cli`'s default feature set. It is thin orchestration over the new `irtt-server` crate: one current-thread Tokio runtime, one repeatable `--bind`, and `ServerSet` for startup/shutdown/listener-failure handling — including for a single bind.
|
||||
- Positional `[LABEL=]TARGET` argument syntax for specifying client targets.
|
||||
|
||||
#### Changed
|
||||
|
||||
- Target specification moved from a `--target LABEL=TARGET` flag to plain positional `[LABEL=]TARGET` arguments — a breaking CLI syntax change for any script invoking targets via the old flag.
|
||||
- The `Target` column is now always present in default, CSV, TSV, and JSONL output, rather than only appearing once more than one target was specified. This is a breaking output-format change for scripts that parsed single-target output and assumed no `Target` column.
|
||||
- Cargo feature flags were simplified: the separate `stats`, `full`, and `client-runtime` features were removed, and statistics support is now mandatory whenever the `client` (or `tui`) feature is enabled, rather than optional. Consumers building with `--no-default-features` and selectively re-enabling a `stats` or `client-runtime` feature will need to update their feature selection.
|
||||
- The stats-related memory-usage warning now scales with the number of configured targets (using `irtt-stats`'s new `estimated_retained_bytes`), instead of assuming a single target's worth of retained memory.
|
||||
|
||||
#### Fixed
|
||||
|
||||
- Single-target runs are now driven through the same `ManagedClient` path as multi-target runs, instead of a separate single-target code path, fixing behavioral drift between the two (e.g. continuous single-target runs now stop correctly on peer-initiated close and multi-target failures are now reported with a nonzero exit status).
|
||||
- Continuous (unbounded-duration) runs, both single- and multi-target, now stop and report correctly when the peer closes the session, instead of hanging or exiting silently.
|
||||
- The TUI's input-event draining is now bounded per tick, fixing a starvation/liveness issue where a burst of input could stall rendering or probe scheduling.
|
||||
- The TUI's live graph history buffer is now allocated lazily instead of eagerly, avoiding unnecessary upfront allocation for graphs that are never shown.
|
||||
- A managed-session terminal-state reconciliation fix in the CLI's use of the managed client, correcting a case where a target's final/terminal outcome could be reconciled incorrectly.
|
||||
|
||||
#### Compatibility
|
||||
|
||||
- MSRV raised to Rust 1.88 (from 1.85), to track `ratatui`'s minimum supported Rust version; this applies to the whole workspace, including `irtt-cli`.
|
||||
- CI test coverage was expanded to include `musl` and `aarch64` targets, increasing confidence in `irtt-cli` binaries built for those platforms (no code-level behavior change).
|
||||
|
||||
## Releasing
|
||||
|
||||
Starting with this release, crates are versioned and tagged independently
|
||||
rather than in lockstep. Each crate's release is tagged as `<crate>/vX.Y.Z`
|
||||
(e.g. `irtt-proto/v0.5.0`), pointing at the commit its version was released
|
||||
from. `irtt-proto`, `irtt-client`, `irtt-server`, and `irtt-stats` are
|
||||
libraries published to [crates.io](https://crates.io); their tags exist to
|
||||
identify the exact source for a given crates.io release and do not produce a
|
||||
GitHub Release. `irtt-cli` is the only crate with prebuilt binary artifacts:
|
||||
pushing an `irtt-cli/vX.Y.Z` tag triggers [cargo-dist](https://opensource.axo.dev/cargo-dist/)
|
||||
to build and publish a GitHub Release with platform binaries.
|
||||
@@ -1,4 +0,0 @@
|
||||
# Claude Code
|
||||
|
||||
Read and follow `AGENTS.md` before making changes. When working below a subtree
|
||||
that contains a more specific `AGENTS.md`, read and follow that file as well.
|
||||
Generated
+52
-1649
File diff suppressed because it is too large.
Load diff
+4
-7
@@ -2,26 +2,23 @@
|
||||
members = [
|
||||
"crates/irtt-proto",
|
||||
"crates/irtt-client",
|
||||
"crates/irtt-server",
|
||||
"crates/irtt-stats",
|
||||
"crates/irtt-cli",
|
||||
"crates/irtt-integration-tests",
|
||||
]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
edition = "2021"
|
||||
license = "Apache-2.0"
|
||||
rust-version = "1.88"
|
||||
rust-version = "1.75"
|
||||
repository = "https://github.com/Lochnair/irtt-rs"
|
||||
homepage = "https://github.com/Lochnair/irtt-rs"
|
||||
readme = "README.md"
|
||||
|
||||
[workspace.dependencies]
|
||||
irtt-proto = { version = "0.5.0", path = "crates/irtt-proto" }
|
||||
irtt-client = { version = "0.5.0", path = "crates/irtt-client" }
|
||||
irtt-server = { version = "0.5.0", path = "crates/irtt-server" }
|
||||
irtt-stats = { version = "0.5.0", path = "crates/irtt-stats" }
|
||||
irtt-proto = { version = "0.2.0", path = "crates/irtt-proto" }
|
||||
irtt-client = { version = "0.2.0", path = "crates/irtt-client" }
|
||||
irtt-stats = { version = "0.2.0", path = "crates/irtt-stats" }
|
||||
|
||||
[profile.release]
|
||||
opt-level = "z"
|
||||
|
||||
@@ -1,30 +1,26 @@
|
||||
# irtt-rs
|
||||
|
||||
`irtt-rs` is a Rust implementation of an IRTT-compatible client and server.
|
||||
`irtt-rs` is a Rust implementation of an IRTT-compatible client.
|
||||
|
||||
It provides command-line applets and reusable Rust libraries for finite or continuous latency probing, plus the server side those probes can run against. It is intended for interactive diagnostics, scripting, monitoring, and integration into applications such as network autorate controllers.
|
||||
It is not the upstream IRTT project. For the original implementation, protocol background, and broader project documentation, see:
|
||||
|
||||
This is not the upstream IRTT project. For the original implementation, protocol background, and broader documentation, see [heistp/irtt](https://github.com/heistp/irtt).
|
||||
<https://github.com/heistp/irtt>
|
||||
|
||||
## Features
|
||||
## Status
|
||||
|
||||
* Finite and continuous probe sessions
|
||||
* Concurrent probing of multiple targets
|
||||
* Reusable client library with a structured event stream
|
||||
* Human-readable table output
|
||||
* CSV, TSV, and JSON Lines output for scripts and monitoring systems
|
||||
* Selectable output columns
|
||||
* Automatic final summaries for eligible table-output runs
|
||||
* Optional terminal UI
|
||||
* Reusable Tokio-native server library
|
||||
* UDP server applet with explicit bind and session policy options
|
||||
* Router-friendly multi-applet binary layout
|
||||
This repository currently provides:
|
||||
|
||||
The installed dispatcher is named `irtt-rs` rather than `irtt` to avoid conflicting with or being mistaken for upstream IRTT.
|
||||
- `irtt-cli`, a command-line IRTT-compatible client
|
||||
- `irtt-client`, a Rust library for running client sessions and consuming events
|
||||
- finite and continuous probe runs
|
||||
- human, simple, machine-readable, and RTT-only output modes
|
||||
- optional local summary statistics
|
||||
|
||||
## Installation
|
||||
Server support is not implemented.
|
||||
|
||||
The build requires Rust 1.88 or newer.
|
||||
## Install
|
||||
|
||||
Requires Rust 1.75 or newer.
|
||||
|
||||
From a local checkout:
|
||||
|
||||
@@ -34,328 +30,115 @@ cd irtt-rs
|
||||
cargo install --path crates/irtt-cli
|
||||
```
|
||||
|
||||
This installs:
|
||||
|
||||
* `irtt-rs`, the canonical multi-applet dispatcher
|
||||
* `irtt-cli`, the stream and text client
|
||||
* `irtt-server`, the UDP server
|
||||
|
||||
To also install the optional terminal UI:
|
||||
Or run it directly without installing:
|
||||
|
||||
```sh
|
||||
cargo install --path crates/irtt-cli --features tui
|
||||
cargo run -p irtt-cli -- <server>
|
||||
```
|
||||
|
||||
## Quick start
|
||||
## CLI usage
|
||||
|
||||
Probe a server using the default settings:
|
||||
Basic test:
|
||||
|
||||
```sh
|
||||
irtt-cli netperf-eu.bufferbloat.net:2112
|
||||
irtt-cli <server>
|
||||
```
|
||||
|
||||
Set the test duration and probe interval:
|
||||
Set duration and interval:
|
||||
|
||||
```sh
|
||||
irtt-cli netperf-eu.bufferbloat.net:2112 \
|
||||
--duration 30s \
|
||||
--interval 100ms
|
||||
irtt-cli <server> --duration 30s --interval 100ms
|
||||
```
|
||||
|
||||
Run continuously until interrupted:
|
||||
Run continuously:
|
||||
|
||||
```sh
|
||||
irtt-cli netperf-eu.bufferbloat.net:2112 --duration 0
|
||||
irtt-cli <server> --duration 0
|
||||
```
|
||||
|
||||
Use `Ctrl-C` to stop gracefully.
|
||||
|
||||
## Multiple targets
|
||||
|
||||
Probe several targets concurrently:
|
||||
Use a specific output mode:
|
||||
|
||||
```sh
|
||||
irtt-cli host-a:2112 host-b:2112
|
||||
irtt-cli <server> --output human
|
||||
irtt-cli <server> --output simple
|
||||
irtt-cli <server> --output machine
|
||||
irtt-cli <server> --output rtt-us
|
||||
```
|
||||
|
||||
Every target argument accepts `[LABEL=]TARGET`. An optional `LABEL=` prefix assigns the logical
|
||||
target name used in output and the TUI; without it, the target string itself is used. Assign
|
||||
stable labels to targets:
|
||||
For available options:
|
||||
|
||||
```sh
|
||||
irtt-cli ams=ams.example.com:2112 sg=sg.example.com:2112
|
||||
irtt-cli --help
|
||||
```
|
||||
|
||||
Labeled and unlabeled targets can be freely mixed in one argument list:
|
||||
## Machine output
|
||||
|
||||
Use `--output machine` for line-oriented `key=value` output intended for scripts, monitoring, and autorate consumers.
|
||||
|
||||
Example:
|
||||
|
||||
```sh
|
||||
irtt-cli host-a:2112 ams=ams.example.com:2112
|
||||
irtt-cli <server> --duration 0 --interval 250ms --output machine
|
||||
```
|
||||
|
||||
Multi-target sessions use staggered pacing by default. To send each target's probes together:
|
||||
Each line represents one client event and starts with an `event` field, for example:
|
||||
|
||||
```sh
|
||||
irtt-cli host-a:2112 host-b:2112 --pacing burst
|
||||
```text
|
||||
event=echo_reply seq=4 logical_seq=4 remote=203.0.113.10:2112 raw_rtt_us=12400 effective_rtt_us=12100 adjusted_rtt_us=12100 server_processing_us=300 dscp=0 ecn=0 kernel_rx_ns=none
|
||||
```
|
||||
|
||||
Target labels are included in the default multi-target output.
|
||||
Consumers should match on `event=...` and read the fields they need. Unknown fields should be ignored.
|
||||
|
||||
## Output formats
|
||||
|
||||
The CLI supports four event-row formats:
|
||||
|
||||
* `table`: human-readable terminal output
|
||||
* `csv`: comma-separated output
|
||||
* `tsv`: tab-separated output
|
||||
* `jsonl`: one JSON object per event
|
||||
|
||||
Examples:
|
||||
For consumers that only need RTT values, use:
|
||||
|
||||
```sh
|
||||
irtt-cli <server> --format table
|
||||
irtt-cli <server> --format jsonl
|
||||
irtt-cli <server> --format csv \
|
||||
--columns event,seq,remote,effective_rtt_us
|
||||
```
|
||||
|
||||
For a stream containing only effective RTT values in microseconds:
|
||||
|
||||
```sh
|
||||
irtt-cli <server> \
|
||||
--format tsv \
|
||||
--columns effective_rtt_us \
|
||||
--header never
|
||||
```
|
||||
|
||||
List all available columns with:
|
||||
|
||||
```sh
|
||||
irtt-cli --list-columns
|
||||
```
|
||||
|
||||
Useful measurement fields include:
|
||||
|
||||
* `raw_rtt_us`: client-observed send-to-receive RTT
|
||||
* `adjusted_rtt_us`: RTT adjusted for server processing when available
|
||||
* `effective_rtt_us`: adjusted RTT when available, otherwise raw RTT
|
||||
* `sd_us` and `rd_us`: send and receive one-way delay estimates
|
||||
* `ipdv_us`: inter-packet delay variation
|
||||
* `server_processing_us`: time spent processing the packet at the server
|
||||
|
||||
Adjusted RTT can be negative when server processing exceeds the measured raw RTT. One-way delay estimates can be negative because of clock skew between the client and server.
|
||||
|
||||
Default table output prints a final summary after completed finite runs and interrupted continuous runs when the run policy permits it. CSV, TSV, and JSON Lines output do not print this summary.
|
||||
|
||||
A peer closing a finite CLI or TUI run is accepted as a terminal outcome. In
|
||||
continuous mode, peer closure exits nonzero unless the user requested
|
||||
interruption, allowing a supervisor to restart the client.
|
||||
|
||||
## Terminal UI
|
||||
|
||||
When built with the `tui` feature, `irtt-tui` provides a live cumulative dashboard:
|
||||
|
||||
```sh
|
||||
irtt-tui <server>
|
||||
```
|
||||
|
||||
It runs continuously by default. A finite duration can be selected explicitly:
|
||||
|
||||
```sh
|
||||
irtt-tui <server> --duration 30s
|
||||
```
|
||||
|
||||
Multiple targets and pacing options work the same way as in `irtt-cli`:
|
||||
|
||||
```sh
|
||||
irtt-tui host-a:2112 host-b:2112 --pacing burst
|
||||
```
|
||||
|
||||
Quit with `q` or `Ctrl-C`.
|
||||
|
||||
## Server
|
||||
|
||||
The server applet requires at least one explicit bind address:
|
||||
|
||||
```sh
|
||||
irtt-server --bind 127.0.0.1:2112
|
||||
```
|
||||
|
||||
The same applet is reachable through the dispatcher:
|
||||
|
||||
```sh
|
||||
irtt-rs server --bind 192.0.2.10:2112
|
||||
```
|
||||
|
||||
Repeat `--bind` to serve several addresses from one process, in the order given:
|
||||
|
||||
```sh
|
||||
irtt-server \
|
||||
--bind 0.0.0.0:2112 \
|
||||
--bind [::]:2112
|
||||
```
|
||||
|
||||
Every invocation runs through the same multi-listener path, so one address is an
|
||||
ordinary set of one rather than a separate mode. The policy options below are
|
||||
applied to every listener, but the listeners are otherwise independent: each has
|
||||
its own sessions and tokens, so a session belongs to the address it was opened
|
||||
on and `--max-sessions` bounds each listener rather than the process. Binding is
|
||||
all or nothing — if any address cannot be bound, none are served — and a port of
|
||||
`0` selects an unused port per listener. If a listener fails while running, the
|
||||
others are shut down with it rather than leaving a service configured for two
|
||||
families answering on one.
|
||||
|
||||
An explicit interface address works on every supported system. A wildcard bind
|
||||
such as `--bind 0.0.0.0:2112` reads each request's local destination from packet
|
||||
metadata and sends that request's reply from the same address, so a client on a
|
||||
multi-homed host is answered from the endpoint it contacted. That is implemented
|
||||
on Linux, macOS and FreeBSD; elsewhere a wildcard bind is refused rather than
|
||||
served from a routing-table source address a client would discard. Wildcard
|
||||
IPv4 and IPv6 listeners may share one port, as above.
|
||||
|
||||
Each bound endpoint is printed on startup once every listener is up, which also
|
||||
resolves a port of `0`. `Ctrl-C` stops the server gracefully.
|
||||
|
||||
Session policy is set with options that map directly onto the server library's
|
||||
configuration; anything left unset keeps the library default:
|
||||
|
||||
```sh
|
||||
irtt-server \
|
||||
--bind 192.0.2.10:2112 \
|
||||
--max-sessions 512 \
|
||||
--idle-timeout 30s
|
||||
```
|
||||
|
||||
Two optional controls restrict what the server will provide a session, and both
|
||||
are off unless asked for:
|
||||
|
||||
```sh
|
||||
irtt-server \
|
||||
--bind 192.0.2.10:2112 \
|
||||
--timestamp-allowance single \
|
||||
--no-dscp
|
||||
```
|
||||
|
||||
`--timestamp-allowance` takes `dual` (the default, honoring every requested
|
||||
placement), `single`, which provides at most one timestamp instant and answers a
|
||||
request for both receive and send timestamps with the midpoint, or `none`, which
|
||||
provides no timestamps. The requested clock source is never changed, so a single
|
||||
instant is still reported once per requested clock. `--no-dscp` negotiates any
|
||||
requested DSCP to zero, so clients are told their echo replies will be unmarked,
|
||||
and they are sent unmarked.
|
||||
|
||||
To require authentication, pass the shared key both sides use:
|
||||
|
||||
```sh
|
||||
irtt-server --bind 192.0.2.10:2112 --hmac secret
|
||||
```
|
||||
|
||||
For the full option list:
|
||||
|
||||
```sh
|
||||
irtt-server --help
|
||||
irtt-cli <server> --output rtt-us
|
||||
```
|
||||
|
||||
## Library usage
|
||||
|
||||
`irtt-client` exposes the client session and event layer independently of CLI formatting and statistics.
|
||||
`irtt-client` can be used directly from Rust code.
|
||||
|
||||
Add it from a local checkout:
|
||||
Example `Cargo.toml` dependency from a local checkout:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
irtt-client = { path = "crates/irtt-client", features = ["tokio"] }
|
||||
irtt-client = { path = "crates/irtt-client" }
|
||||
```
|
||||
|
||||
Minimal managed-client example for a synchronous frontend:
|
||||
Minimal managed-client example:
|
||||
|
||||
```rust
|
||||
use std::time::Duration;
|
||||
|
||||
use irtt_client::managed::{
|
||||
BlockingManagedClient, ManagedClientConfig, ManagedCompletionPolicy,
|
||||
ManagedTargetConfig, TargetId,
|
||||
use irtt_client::{
|
||||
ClientConfig, ClientEvent, ManagedClient, SubscriberConfig,
|
||||
};
|
||||
use irtt_client::ClientConfig;
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let config = ManagedClientConfig {
|
||||
client: ClientConfig {
|
||||
duration: Some(Duration::from_secs(10)),
|
||||
interval: Duration::from_secs(1),
|
||||
..ClientConfig::default()
|
||||
},
|
||||
completion: ManagedCompletionPolicy::FinishWhenQuiescent,
|
||||
..ManagedClientConfig::default()
|
||||
let config = ClientConfig {
|
||||
server_addr: "netperf-eu.bufferbloat.net:2112".to_owned(),
|
||||
duration: Some(Duration::from_secs(10)),
|
||||
interval: Duration::from_secs(1),
|
||||
..ClientConfig::default()
|
||||
};
|
||||
let targets = vec![ManagedTargetConfig::new(
|
||||
TargetId::from("edge"),
|
||||
"netperf-eu.bufferbloat.net:2112",
|
||||
)];
|
||||
let owner = BlockingManagedClient::start(config, targets)?;
|
||||
let outcome = owner.join()?;
|
||||
|
||||
let (session, events) =
|
||||
ManagedClient::start_with_subscription(config, SubscriberConfig::default())?;
|
||||
|
||||
while let Ok(event) = events.recv() {
|
||||
match event {
|
||||
ClientEvent::EchoReply { seq, rtt, .. } => {
|
||||
println!("seq={seq} rtt_us={}", rtt.effective.as_micros());
|
||||
}
|
||||
ClientEvent::SessionClosed { .. } => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let outcome = session.join()?;
|
||||
println!("session ended: {:?}", outcome.end_reason);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
For presentation events, use `BlockingManagedClient::start_with_subscription`,
|
||||
`ManagedEvent`, and `ManagedEventTryRecvError`, while consulting the durable
|
||||
`handle.status()` and final outcome for authoritative state. Presentation
|
||||
events are bounded and lossy, not reliable history. Dynamic desired-target
|
||||
updates are available through `ManagedClientHandle::update_targets`.
|
||||
|
||||
`BlockingManagedClient` owns a dedicated Tokio runtime and thread for
|
||||
synchronous callers. Callers that already own Tokio can drive
|
||||
`ManagedClientTask` directly.
|
||||
|
||||
## Binaries and features
|
||||
|
||||
| Build | Binaries |
|
||||
| ----------------------------------------- | ------------------------------------------------- |
|
||||
| `--no-default-features` | `irtt-rs` |
|
||||
| `--no-default-features --features server` | `irtt-rs`, `irtt-server` |
|
||||
| Default features | `irtt-rs`, `irtt-cli`, `irtt-server` |
|
||||
| `--features tui` | `irtt-rs`, `irtt-cli`, `irtt-server`, `irtt-tui` |
|
||||
| `--all-features` | `irtt-rs`, `irtt-cli`, `irtt-server`, `irtt-tui` |
|
||||
|
||||
`irtt-cli` requires the `client` feature, `irtt-server` the `server` feature,
|
||||
and `irtt-tui` the `tui` feature. The `irtt-rs` dispatcher is always built, and
|
||||
reports which applets the build actually contains.
|
||||
|
||||
For available command-line options:
|
||||
|
||||
```sh
|
||||
irtt-cli --help
|
||||
irtt-server --help
|
||||
irtt-tui --help
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
Common verification commands:
|
||||
|
||||
```sh
|
||||
cargo fmt --check
|
||||
cargo test --workspace
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo build -p irtt-cli --all-features --release
|
||||
```
|
||||
|
||||
## Project status
|
||||
|
||||
The client, event stream, machine-readable output, multi-target execution, local statistics, and optional TUI are implemented.
|
||||
|
||||
The server library and the server applet are implemented: open negotiation,
|
||||
session state, echo processing, per-session rate limiting, idle expiry, the
|
||||
maximum-duration close, HMAC authentication, the negotiated per-session reply
|
||||
traffic class, which is applied on sockets that support it, server fill,
|
||||
wildcard reply-source selection on Linux, macOS and FreeBSD, the optional
|
||||
timestamp and DSCP restriction controls, and serving several listeners from one
|
||||
process with independent sessions per listener.
|
||||
|
||||
Server replies fill their payload with the negotiated ServerFill mode: `none`,
|
||||
which is zero-filled, `rand`, or `pattern:` with a repeating hexadecimal
|
||||
pattern. Every valid descriptor is honored; a descriptor the server cannot
|
||||
parse, and a client that expresses no fill preference at all, get the default
|
||||
`pattern:69727474`.
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "irtt-cli"
|
||||
version = "0.5.0"
|
||||
description = "Command-line IRTT-compatible client and server"
|
||||
version = "0.2.0"
|
||||
description = "Command-line IRTT-compatible client"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -11,48 +11,13 @@ readme.workspace = true
|
||||
keywords = ["irtt", "networking", "latency", "rtt"]
|
||||
categories = ["command-line-utilities", "network-programming"]
|
||||
|
||||
[lib]
|
||||
doc = false
|
||||
|
||||
[[bin]]
|
||||
name = "irtt-rs"
|
||||
path = "src/bin/irtt-rs.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "irtt-cli"
|
||||
path = "src/bin/irtt-cli.rs"
|
||||
required-features = ["client"]
|
||||
|
||||
[[bin]]
|
||||
name = "irtt-tui"
|
||||
path = "src/bin/irtt-tui.rs"
|
||||
required-features = ["tui"]
|
||||
|
||||
[[bin]]
|
||||
name = "irtt-server"
|
||||
path = "src/bin/irtt-server.rs"
|
||||
required-features = ["server"]
|
||||
# This applet shares its name with the irtt-server library crate, whose rustdoc
|
||||
# output it would otherwise collide with.
|
||||
doc = false
|
||||
|
||||
[features]
|
||||
default = ["client", "server", "tui"]
|
||||
client = ["dep:irtt-client", "irtt-client/ancillary", "irtt-client/tokio", "dep:irtt-proto", "dep:irtt-stats"]
|
||||
server = ["dep:irtt-server", "dep:tokio"]
|
||||
tui =["dep:irtt-client", "irtt-client/ancillary", "irtt-client/tokio", "dep:irtt-proto", "dep:irtt-stats", "dep:ratatui", "dep:crossterm"]
|
||||
default = ["stats"]
|
||||
stats = ["dep:irtt-stats"]
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "4.6.6", features = ["derive"] }
|
||||
crossterm = { version = "0.29.0", optional = true }
|
||||
clap = { version = "4.6.1", features = ["derive"] }
|
||||
ctrlc = "3.5.2"
|
||||
irtt-client = { workspace = true, optional = true }
|
||||
irtt-proto = { workspace = true, optional = true }
|
||||
irtt-server = { workspace = true, optional = true }
|
||||
irtt-client.workspace = true
|
||||
irtt-proto.workspace = true
|
||||
irtt-stats = { workspace = true, optional = true }
|
||||
ratatui = { version = "0.30.2", optional = true }
|
||||
tokio = { version = "1.53.1", default-features = false, features = ["rt", "time"], optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
irtt-server.workspace = true
|
||||
tokio = { version = "1.53.1", default-features = false, features = ["rt", "sync"] }
|
||||
@@ -1,320 +0,0 @@
|
||||
use std::{ffi::OsString, path::Path};
|
||||
|
||||
use clap::Command;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RequestedApplet {
|
||||
Client,
|
||||
Tui,
|
||||
Server,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AppletDispatch {
|
||||
Run {
|
||||
applet: RequestedApplet,
|
||||
argv: Vec<OsString>,
|
||||
},
|
||||
Help(String),
|
||||
}
|
||||
|
||||
pub fn detect_applet_from_argv0(argv0: &str) -> Option<RequestedApplet> {
|
||||
match applet_basename(argv0) {
|
||||
"irtt-cli" => Some(RequestedApplet::Client),
|
||||
"irtt-tui" => Some(RequestedApplet::Tui),
|
||||
"irttd" | "irtt-server" => Some(RequestedApplet::Server),
|
||||
"irtt-rs" => None,
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dispatch_from_argv(argv: Vec<OsString>) -> Result<AppletDispatch, String> {
|
||||
let argv0 = argv
|
||||
.first()
|
||||
.and_then(|arg| arg.to_str())
|
||||
.unwrap_or("irtt-rs");
|
||||
|
||||
if let Some(applet) = detect_applet_from_argv0(argv0) {
|
||||
return Ok(AppletDispatch::Run { applet, argv });
|
||||
}
|
||||
|
||||
let basename = applet_basename(argv0);
|
||||
if basename.starts_with("irtt-") && basename != "irtt-rs" {
|
||||
return Err(format!(
|
||||
"unknown applet name '{basename}'. Known applet names: {}",
|
||||
known_applet_binary_names()
|
||||
));
|
||||
}
|
||||
|
||||
let Some(command) = argv.get(1).and_then(|arg| arg.to_str()) else {
|
||||
return Err(format!(
|
||||
"choose an applet: {}\n\n{}",
|
||||
applet_command_names(),
|
||||
dispatcher_help()
|
||||
));
|
||||
};
|
||||
|
||||
match command {
|
||||
"-h" | "--help" => Ok(AppletDispatch::Help(dispatcher_help())),
|
||||
"client" => Ok(AppletDispatch::Run {
|
||||
applet: RequestedApplet::Client,
|
||||
argv: applet_argv("irtt-cli", &argv[2..]),
|
||||
}),
|
||||
"tui" => Ok(AppletDispatch::Run {
|
||||
applet: RequestedApplet::Tui,
|
||||
argv: applet_argv("irtt-tui", &argv[2..]),
|
||||
}),
|
||||
"server" => Ok(AppletDispatch::Run {
|
||||
applet: RequestedApplet::Server,
|
||||
argv: applet_argv("irtt-server", &argv[2..]),
|
||||
}),
|
||||
_ => Err(format!(
|
||||
"unknown applet '{command}'. Choose one of: {}\n\n{}",
|
||||
applet_command_names(),
|
||||
dispatcher_help()
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dispatcher_help() -> String {
|
||||
let mut command = Command::new("irtt-rs")
|
||||
.about("IRTT-compatible multi-applet dispatcher")
|
||||
.subcommand(Command::new("client").about(client_applet_about()))
|
||||
.subcommand(Command::new("tui").about(tui_applet_about()))
|
||||
.subcommand(Command::new("server").about(server_applet_about()))
|
||||
.after_help(dispatcher_after_help());
|
||||
command.render_help().to_string()
|
||||
}
|
||||
|
||||
fn client_applet_about() -> &'static str {
|
||||
if cfg!(feature = "client") {
|
||||
"Run the stream client applet"
|
||||
} else {
|
||||
"Stream client applet is not available in this build"
|
||||
}
|
||||
}
|
||||
|
||||
fn tui_applet_about() -> &'static str {
|
||||
if cfg!(feature = "tui") {
|
||||
"Run the terminal UI applet"
|
||||
} else {
|
||||
"Terminal UI applet is not available in this build"
|
||||
}
|
||||
}
|
||||
|
||||
fn server_applet_about() -> &'static str {
|
||||
if cfg!(feature = "server") {
|
||||
"Run the UDP server applet"
|
||||
} else {
|
||||
"UDP server applet is not available in this build"
|
||||
}
|
||||
}
|
||||
|
||||
fn known_applet_binary_names() -> &'static str {
|
||||
"irtt-rs, irtt-cli, irtt-tui, irtt-server"
|
||||
}
|
||||
|
||||
fn applet_command_names() -> &'static str {
|
||||
"client, tui, or server"
|
||||
}
|
||||
|
||||
fn dispatcher_after_help() -> String {
|
||||
let mut help = "Recognized applet binary names: irtt-cli, irtt-tui, irtt-server".to_owned();
|
||||
|
||||
let mut missing = Vec::new();
|
||||
if !cfg!(feature = "client") {
|
||||
missing.push("irtt-cli requires the client feature");
|
||||
}
|
||||
if !cfg!(feature = "server") {
|
||||
missing.push("irtt-server requires the server feature");
|
||||
}
|
||||
if !cfg!(feature = "tui") {
|
||||
missing.push("irtt-tui requires the tui feature");
|
||||
}
|
||||
|
||||
match missing.len() {
|
||||
0 => {}
|
||||
1 => help.push_str(&format!("\nOptional applet: {}", missing[0])),
|
||||
_ => help.push_str(&format!("\nOptional applets: {}", missing.join("; "))),
|
||||
}
|
||||
help
|
||||
}
|
||||
|
||||
fn applet_basename(argv0: &str) -> &str {
|
||||
let name = Path::new(argv0)
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or(argv0);
|
||||
strip_suffix_ignoring_case(name, std::env::consts::EXE_SUFFIX)
|
||||
}
|
||||
|
||||
/// Removes the platform executable suffix from a file name.
|
||||
///
|
||||
/// The suffix is part of the file name on Windows and empty everywhere else, so
|
||||
/// this is a no-op on Unix. Without it, every applet name — including the
|
||||
/// `irtt-rs` dispatcher itself — reaches argv0 detection as `<name>.exe` and is
|
||||
/// rejected as an unknown applet. The applet names themselves are still matched
|
||||
/// exactly; only this platform artifact is case-insensitive, because it is not
|
||||
/// a name the user chose.
|
||||
///
|
||||
/// The suffix is a parameter so that Windows behavior is assertable from any
|
||||
/// host, not only where `EXE_SUFFIX` happens to be non-empty.
|
||||
fn strip_suffix_ignoring_case<'a>(name: &'a str, suffix: &str) -> &'a str {
|
||||
if suffix.is_empty() || name.len() <= suffix.len() {
|
||||
return name;
|
||||
}
|
||||
let split = name.len() - suffix.len();
|
||||
let (Some(stem), Some(tail)) = (name.get(..split), name.get(split..)) else {
|
||||
return name;
|
||||
};
|
||||
if tail.eq_ignore_ascii_case(suffix) {
|
||||
stem
|
||||
} else {
|
||||
name
|
||||
}
|
||||
}
|
||||
|
||||
fn applet_argv(applet_name: &str, args: &[OsString]) -> Vec<OsString> {
|
||||
let mut argv = Vec::with_capacity(args.len() + 1);
|
||||
argv.push(OsString::from(applet_name));
|
||||
argv.extend(args.iter().cloned());
|
||||
argv
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn applet_detection_maps_binary_names() {
|
||||
assert_eq!(
|
||||
detect_applet_from_argv0("/usr/bin/irtt-cli"),
|
||||
Some(RequestedApplet::Client)
|
||||
);
|
||||
assert_eq!(
|
||||
detect_applet_from_argv0("irtt-tui"),
|
||||
Some(RequestedApplet::Tui)
|
||||
);
|
||||
assert_eq!(
|
||||
detect_applet_from_argv0("irtt-server"),
|
||||
Some(RequestedApplet::Server)
|
||||
);
|
||||
assert_eq!(detect_applet_from_argv0("irtt-rs"), None);
|
||||
assert_eq!(detect_applet_from_argv0("custom-name"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applet_detection_ignores_the_platform_executable_suffix() {
|
||||
let exe = std::env::consts::EXE_SUFFIX;
|
||||
|
||||
assert_eq!(
|
||||
detect_applet_from_argv0(&format!("/opt/irtt/irtt-server{exe}")),
|
||||
Some(RequestedApplet::Server)
|
||||
);
|
||||
assert_eq!(
|
||||
detect_applet_from_argv0(&format!("irtt-cli{exe}")),
|
||||
Some(RequestedApplet::Client)
|
||||
);
|
||||
|
||||
// The dispatcher's own name must not be taken for an unknown applet.
|
||||
let dispatcher = format!("irtt-rs{exe}");
|
||||
assert_eq!(detect_applet_from_argv0(&dispatcher), None);
|
||||
assert!(dispatch_from_argv(vec![dispatcher.into(), "--help".into()]).is_ok());
|
||||
|
||||
// A name that merely ends in the suffix letters keeps them.
|
||||
assert!(detect_applet_from_argv0("irtt-serverexe").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_executable_suffix_handling_is_assertable_from_any_host() {
|
||||
assert_eq!(
|
||||
strip_suffix_ignoring_case("irtt-server.exe", ".exe"),
|
||||
"irtt-server"
|
||||
);
|
||||
assert_eq!(strip_suffix_ignoring_case("IRTT-RS.EXE", ".exe"), "IRTT-RS");
|
||||
assert_eq!(
|
||||
strip_suffix_ignoring_case("irtt-server", ".exe"),
|
||||
"irtt-server"
|
||||
);
|
||||
assert_eq!(
|
||||
strip_suffix_ignoring_case("irtt-serverexe", ".exe"),
|
||||
"irtt-serverexe"
|
||||
);
|
||||
assert_eq!(strip_suffix_ignoring_case(".exe", ".exe"), ".exe");
|
||||
assert_eq!(
|
||||
strip_suffix_ignoring_case("irtt-server.exe", ""),
|
||||
"irtt-server.exe"
|
||||
);
|
||||
// A multi-byte tail must not split mid-character.
|
||||
assert_eq!(strip_suffix_ignoring_case("irtt-så", ".exe"), "irtt-så");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_help_renders_dispatcher_help() {
|
||||
let dispatch = dispatch_from_argv(vec!["irtt-rs".into(), "--help".into()]).unwrap();
|
||||
let AppletDispatch::Help(help) = dispatch else {
|
||||
panic!("expected dispatcher help");
|
||||
};
|
||||
assert!(help.contains("IRTT-compatible multi-applet dispatcher"));
|
||||
assert!(help.contains("client"));
|
||||
if cfg!(feature = "tui") {
|
||||
assert!(help.contains("Run the terminal UI applet"));
|
||||
} else {
|
||||
assert!(help.contains("Terminal UI applet is not available in this build"));
|
||||
}
|
||||
assert!(help.contains("server"));
|
||||
if cfg!(feature = "server") {
|
||||
assert!(help.contains("Run the UDP server applet"));
|
||||
} else {
|
||||
assert!(help.contains("UDP server applet is not available in this build"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_without_applet_is_an_error() {
|
||||
let err = dispatch_from_argv(vec!["irtt-rs".into()]).unwrap_err();
|
||||
assert!(err.contains("choose an applet"));
|
||||
assert!(err.contains("client"));
|
||||
if cfg!(feature = "tui") {
|
||||
assert!(err.contains("tui"));
|
||||
}
|
||||
assert!(err.contains("server"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_subcommands_dispatch_to_applet_argv() {
|
||||
assert_eq!(
|
||||
dispatch_from_argv(vec!["irtt-rs".into(), "client".into(), "host:2112".into()])
|
||||
.unwrap(),
|
||||
AppletDispatch::Run {
|
||||
applet: RequestedApplet::Client,
|
||||
argv: vec!["irtt-cli".into(), "host:2112".into()],
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
dispatch_from_argv(vec!["irtt-rs".into(), "tui".into(), "host:2112".into()]).unwrap(),
|
||||
AppletDispatch::Run {
|
||||
applet: RequestedApplet::Tui,
|
||||
argv: vec!["irtt-tui".into(), "host:2112".into()],
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
dispatch_from_argv(vec!["irtt-rs".into(), "server".into()]).unwrap(),
|
||||
AppletDispatch::Run {
|
||||
applet: RequestedApplet::Server,
|
||||
argv: vec!["irtt-server".into()],
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_irtt_binary_name_is_an_error() {
|
||||
let err = dispatch_from_argv(vec!["/usr/bin/irtt-typo".into()]).unwrap_err();
|
||||
assert!(err.contains("unknown applet name 'irtt-typo'"));
|
||||
assert!(err.contains("irtt-cli"));
|
||||
if cfg!(feature = "tui") {
|
||||
assert!(err.contains("irtt-tui"));
|
||||
}
|
||||
assert!(err.contains("irtt-server"));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
use std::process::ExitCode;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
irtt_cli::entry::main()
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
use std::process::ExitCode;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
irtt_cli::entry::main()
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
use std::process::ExitCode;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
irtt_cli::entry::main()
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
use std::process::ExitCode;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
irtt_cli::entry::main()
|
||||
}
|
||||
@@ -1,306 +0,0 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::shared::client::{
|
||||
parse_target, parse_test_duration, prepare_managed_run, CommonClientArgs, GroupPacingArg,
|
||||
ManagedRunSetup, TargetArg, TargetSelection, TimestampArg,
|
||||
};
|
||||
use clap::{Parser, ValueEnum};
|
||||
|
||||
pub const DEFAULT_CLIENT_DURATION: Duration = Duration::from_secs(10);
|
||||
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
#[command(name = "irtt-cli", about = "Minimal IRTT-compatible stream client")]
|
||||
pub struct ClientArgs {
|
||||
/// Server address/host, optionally prefixed with LABEL=. Repeat for multi-target mode.
|
||||
#[arg(
|
||||
value_name = "TARGET",
|
||||
num_args = 0..,
|
||||
value_parser = parse_target,
|
||||
long_help = "Server address/host, optionally prefixed with LABEL=. Repeat for multi-target mode.\n\nExamples:\n irtt-cli host-a:2112 host-b:2112\n irtt-cli eu=host-a:2112 us=host-b:2112\n irtt-cli host-a:2112 eu=host-b:2112"
|
||||
)]
|
||||
pub targets: Vec<TargetArg>,
|
||||
|
||||
/// Managed group pacing for multi-target mode.
|
||||
#[arg(
|
||||
long,
|
||||
value_enum,
|
||||
default_value_t = GroupPacingArg::Staggered,
|
||||
long_help = "Managed group pacing for multi-target mode.\n\nstaggered spaces active targets across the probe interval. burst sends one probe to every active target back-to-back once per interval."
|
||||
)]
|
||||
pub pacing: GroupPacingArg,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
default_value = "10s",
|
||||
value_parser = parse_test_duration,
|
||||
help = "Test duration; use 0 for continuous mode",
|
||||
long_help = "Test duration; use 0 for continuous mode.\n\nFinite runs retain exact statistics for final summaries. Continuous mode uses bounded-memory running statistics and prints a final summary only when interrupted."
|
||||
)]
|
||||
pub duration: Duration,
|
||||
|
||||
#[command(flatten)]
|
||||
pub common: CommonClientArgs,
|
||||
|
||||
/// Event row output format.
|
||||
#[arg(
|
||||
long,
|
||||
value_enum,
|
||||
default_value_t = OutputFormat::Table,
|
||||
long_help = "Event row output format.\n\nTable is the default interactive format. CSV, TSV, and JSON Lines default to all columns for structured export."
|
||||
)]
|
||||
pub format: OutputFormat,
|
||||
|
||||
/// Comma-separated event row columns, or default/all.
|
||||
#[arg(
|
||||
short = 'c',
|
||||
long,
|
||||
value_name = "COLUMNS",
|
||||
long_help = "Comma-separated event row columns, or default/all.\n\nThe default table columns are compact and hide echo_sent rows. Custom table columns include all event rows. Run --list-columns to see valid names."
|
||||
)]
|
||||
pub columns: Option<String>,
|
||||
|
||||
/// List available event row columns and aliases, then exit.
|
||||
#[arg(
|
||||
long,
|
||||
long_help = "List available event row columns and aliases, then exit.\n\nA server argument is not required when listing columns."
|
||||
)]
|
||||
pub list_columns: bool,
|
||||
|
||||
/// Header policy for table, CSV, and TSV output.
|
||||
#[arg(
|
||||
long,
|
||||
value_enum,
|
||||
default_value_t = HeaderMode::Auto,
|
||||
long_help = "Header policy for table, CSV, and TSV output.\n\nJSON Lines never prints a header."
|
||||
)]
|
||||
pub header: HeaderMode,
|
||||
|
||||
/// Include extra fields in table output and final summaries.
|
||||
#[arg(long)]
|
||||
pub verbose: bool,
|
||||
}
|
||||
|
||||
impl ClientArgs {
|
||||
/// Validate the selected targets and prepare the managed run.
|
||||
///
|
||||
/// Targets are only required here. `--list-columns` returns before this is
|
||||
/// called, so listing columns still needs no target.
|
||||
pub fn prepare(&self) -> Result<ManagedRunSetup, String> {
|
||||
prepare_managed_run(
|
||||
&self.common,
|
||||
self.duration,
|
||||
TargetSelection {
|
||||
targets: &self.targets,
|
||||
pacing: self.pacing,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn is_continuous(&self) -> bool {
|
||||
self.duration == Duration::ZERO
|
||||
}
|
||||
|
||||
pub fn timestamp_mode(&self) -> TimestampArg {
|
||||
self.common.tstamp
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for ClientArgs {
|
||||
type Target = CommonClientArgs;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.common
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
|
||||
pub enum OutputFormat {
|
||||
/// Readable terminal table output.
|
||||
Table,
|
||||
/// Comma-separated event rows.
|
||||
Csv,
|
||||
/// Tab-separated event rows.
|
||||
Tsv,
|
||||
/// One JSON object per event row.
|
||||
Jsonl,
|
||||
}
|
||||
|
||||
impl OutputFormat {
|
||||
pub fn prints_summary(self) -> bool {
|
||||
matches!(self, Self::Table)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
|
||||
pub enum HeaderMode {
|
||||
/// Print headers for table, CSV, and TSV output.
|
||||
Auto,
|
||||
/// Always print headers where the format supports them.
|
||||
Always,
|
||||
/// Never print headers.
|
||||
Never,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use clap::{CommandFactory, Parser};
|
||||
use irtt_client::NegotiationPolicy;
|
||||
use irtt_proto::{Clock, ReceivedStats, StampAt};
|
||||
|
||||
fn parse(args: &[&str]) -> Result<ClientArgs, clap::Error> {
|
||||
let mut argv = vec!["irtt-cli"];
|
||||
argv.extend_from_slice(args);
|
||||
ClientArgs::try_parse_from(argv)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_parser_keeps_finite_default_duration() {
|
||||
let args = parse(&["127.0.0.1:2112"]).unwrap();
|
||||
|
||||
assert_eq!(args.targets.len(), 1);
|
||||
assert_eq!(args.targets[0].label, None);
|
||||
assert_eq!(args.targets[0].addr, "127.0.0.1:2112");
|
||||
assert_eq!(args.pacing, GroupPacingArg::Staggered);
|
||||
assert_eq!(args.duration, DEFAULT_CLIENT_DURATION);
|
||||
assert_eq!(args.interval, Duration::from_secs(1));
|
||||
assert_eq!(args.format, OutputFormat::Table);
|
||||
assert_eq!(args.columns, None);
|
||||
assert_eq!(args.header, HeaderMode::Auto);
|
||||
assert!(!args.is_continuous());
|
||||
assert_eq!(args.timestamp_mode(), TimestampArg::Both);
|
||||
|
||||
let config = args.prepare().unwrap().client;
|
||||
assert_eq!(config.duration, Some(DEFAULT_CLIENT_DURATION));
|
||||
assert_eq!(config.received_stats, ReceivedStats::Both);
|
||||
assert_eq!(config.stamp_at, StampAt::Both);
|
||||
assert_eq!(config.clock, Clock::Both);
|
||||
assert_eq!(config.negotiation_policy, NegotiationPolicy::Strict);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_parser_accepts_stream_formats_and_rejects_tui_output() {
|
||||
for format in ["table", "csv", "tsv", "jsonl"] {
|
||||
assert!(parse(&["--format", format, "127.0.0.1:2112"]).is_ok());
|
||||
}
|
||||
assert!(parse(&["--format", "tui", "127.0.0.1:2112"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_columns_does_not_require_server() {
|
||||
let args = parse(&["--list-columns"]).unwrap();
|
||||
assert!(args.targets.is_empty());
|
||||
assert!(args.list_columns);
|
||||
// The parser accepts no target; preparation is where a target becomes
|
||||
// mandatory, and the stream command returns before preparing when
|
||||
// listing columns.
|
||||
let err = args.prepare().unwrap_err();
|
||||
assert!(err.contains("--list-columns"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_positional_targets_parse_as_targets() {
|
||||
let args = parse(&["host-a:2112", "host-b:2112"]).unwrap();
|
||||
let specs = args.prepare().unwrap().targets;
|
||||
|
||||
assert_eq!(specs[0].label, "host-a:2112");
|
||||
assert_eq!(specs[0].managed.server_addr, "host-a:2112");
|
||||
assert_eq!(specs[1].label, "host-b:2112");
|
||||
assert_eq!(specs[1].managed.server_addr, "host-b:2112");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_labeled_targets_parse() {
|
||||
let args = parse(&["ams=ams.example.com:2112", "sg=sg.example.com:2112"]).unwrap();
|
||||
let specs = args.prepare().unwrap().targets;
|
||||
|
||||
assert_eq!(specs[0].label, "ams");
|
||||
assert_eq!(specs[0].managed.server_addr, "ams.example.com:2112");
|
||||
assert_eq!(specs[1].label, "sg");
|
||||
assert_eq!(specs[1].managed.server_addr, "sg.example.com:2112");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_labeled_and_unlabeled_targets_preserve_argument_order() {
|
||||
let args = parse(&["local.example", "eu=a.example", "backup.example"]).unwrap();
|
||||
let specs = args.prepare().unwrap().targets;
|
||||
|
||||
let labels: Vec<_> = specs.iter().map(|target| target.label.as_str()).collect();
|
||||
assert_eq!(labels, ["local.example", "eu", "backup.example"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_labels_are_rejected() {
|
||||
let args = parse(&["host-a:2112", "host-a:2112=host-b:2112"]).unwrap();
|
||||
let err = args.prepare().unwrap_err();
|
||||
|
||||
assert!(err.contains("duplicate target label"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_positional_target_strings_get_stable_suffixes() {
|
||||
let args = parse(&["host-a:2112", "host-a:2112"]).unwrap();
|
||||
let specs = args.prepare().unwrap().targets;
|
||||
|
||||
assert_eq!(specs[0].label, "host-a:2112");
|
||||
assert_eq!(specs[1].label, "host-a:2112#2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_target_endpoints_are_allowed() {
|
||||
let args = parse(&["127.0.0.1:2112", "127.0.0.1"]).unwrap();
|
||||
assert_eq!(args.prepare().unwrap().target_count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_labelled_target_syntax_is_rejected() {
|
||||
assert!(parse(&["=127.0.0.1:2112"]).is_err());
|
||||
assert!(parse(&["label="]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_target_option_is_rejected() {
|
||||
assert!(parse(&["--target", "eu=host.example"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pacing_option_accepts_supported_values() {
|
||||
assert_eq!(
|
||||
parse(&["--pacing", "staggered", "127.0.0.1:2112"])
|
||||
.unwrap()
|
||||
.pacing,
|
||||
GroupPacingArg::Staggered
|
||||
);
|
||||
assert_eq!(
|
||||
parse(&["--pacing", "burst", "127.0.0.1:2112"])
|
||||
.unwrap()
|
||||
.pacing,
|
||||
GroupPacingArg::Burst
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_help_lists_shared_protocol_options() {
|
||||
let help = ClientArgs::command().render_help().to_string();
|
||||
assert!(help.contains("--format <FORMAT>"));
|
||||
assert!(!help.contains("--target "));
|
||||
assert!(help.contains("--pacing <PACING>"));
|
||||
assert!(help.contains("--columns <COLUMNS>"));
|
||||
assert!(help.contains("--list-columns"));
|
||||
assert!(help.contains("--header <HEADER>"));
|
||||
assert!(help.contains("--tstamp <MODE>"));
|
||||
assert!(help.contains("--stats <STATS>"));
|
||||
assert!(help.contains("--sfill <STRING>"));
|
||||
assert!(help.contains("--dscp <0..=63>"));
|
||||
assert!(help.contains("--ttl <1..=255>"));
|
||||
assert!(help.contains("--loose"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_format_summary_policy_is_table_only() {
|
||||
assert!(OutputFormat::Table.prints_summary());
|
||||
assert!(!OutputFormat::Csv.prints_summary());
|
||||
assert!(!OutputFormat::Tsv.prints_summary());
|
||||
assert!(!OutputFormat::Jsonl.prints_summary());
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
pub mod args;
|
||||
pub mod output;
|
||||
pub mod run;
|
||||
pub mod summary;
|
||||
|
||||
pub use args::{ClientArgs, HeaderMode, OutputFormat};
|
||||
pub use run::run_stream;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,487 +0,0 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
io::{self, Write},
|
||||
sync::atomic::AtomicBool,
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use irtt_client::{
|
||||
managed::{
|
||||
BlockingManagedClient, ManagedEndReason, ManagedEvent, ManagedEventSubscription,
|
||||
ManagedEventTryRecvError, ManagedTargetEndReason, ManagedTargetOutcome, TargetInstance,
|
||||
},
|
||||
ClientEvent,
|
||||
};
|
||||
|
||||
use super::{
|
||||
args::ClientArgs,
|
||||
output::{EventRenderStats, OutputConfig},
|
||||
};
|
||||
|
||||
use crate::shared::client::expected_probe_count;
|
||||
use crate::shared::client::{
|
||||
is_shutdown_requested,
|
||||
session::{
|
||||
drain_managed_events, peer_close_run_error, request_managed_stop_for_peer_close,
|
||||
request_managed_stop_once, should_print_final_summary, ManagedDrainState,
|
||||
},
|
||||
};
|
||||
|
||||
use irtt_stats::{StatsCollector, StatsConfig};
|
||||
|
||||
const MIB: u64 = 1024 * 1024;
|
||||
|
||||
const GIB: u64 = 1024 * MIB;
|
||||
|
||||
const FINITE_STATS_MEMORY_WARNING_BYTES: u64 = 128 * MIB;
|
||||
|
||||
const FINITE_STATS_MEMORY_STRONG_WARNING_BYTES: u64 = 512 * MIB;
|
||||
|
||||
const FINITE_STATS_MEMORY_VERY_STRONG_WARNING_BYTES: u64 = GIB;
|
||||
const MANAGED_EVENT_WAIT_SLICE: Duration = Duration::from_millis(20);
|
||||
|
||||
pub fn run_stream(
|
||||
args: ClientArgs,
|
||||
shutdown_requested: &AtomicBool,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
if args.list_columns {
|
||||
print!("{}", OutputConfig::list_columns());
|
||||
return Ok(());
|
||||
}
|
||||
let setup = args
|
||||
.prepare()
|
||||
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
|
||||
let multi_target = setup.is_multi_target();
|
||||
let output_config = OutputConfig::new(
|
||||
args.format,
|
||||
args.columns.as_deref(),
|
||||
args.header,
|
||||
args.verbose,
|
||||
)
|
||||
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
|
||||
let continuous = args.is_continuous();
|
||||
let target_count = setup.target_count();
|
||||
|
||||
if let Some(warning) = finite_stats_memory_warning(&args, target_count) {
|
||||
eprintln!("{warning}");
|
||||
}
|
||||
if is_shutdown_requested(shutdown_requested) {
|
||||
return Ok(());
|
||||
}
|
||||
let (owner, mut events) = BlockingManagedClient::start_with_subscription(
|
||||
setup.managed_config(),
|
||||
setup.managed_targets(),
|
||||
)?;
|
||||
let handle = owner.handle();
|
||||
let mut stdout = io::LineWriter::new(io::stdout().lock());
|
||||
let mut stream_output = StreamOutput {
|
||||
config: output_config,
|
||||
header_printed: false,
|
||||
print_final_summary: false,
|
||||
show_running_only_summary_note: false,
|
||||
out: &mut stdout,
|
||||
};
|
||||
|
||||
let mut stats = setup
|
||||
.targets
|
||||
.iter()
|
||||
.map(|target| {
|
||||
(
|
||||
target.label.clone(),
|
||||
StatsCollector::new(stats_config(continuous)),
|
||||
)
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let mut terminal_targets = HashSet::new();
|
||||
let mut dropped_events = 0_u64;
|
||||
let mut interrupted = false;
|
||||
let mut stop_requested = false;
|
||||
let mut subscription_closed = false;
|
||||
loop {
|
||||
if is_shutdown_requested(shutdown_requested) {
|
||||
interrupted = true;
|
||||
if request_managed_stop_once(&mut stop_requested) {
|
||||
drop(handle.stop());
|
||||
}
|
||||
}
|
||||
if request_managed_stop_for_peer_close(
|
||||
continuous,
|
||||
interrupted,
|
||||
handle.status().peer_closed_target_outcomes,
|
||||
&mut stop_requested,
|
||||
) {
|
||||
drop(handle.stop());
|
||||
}
|
||||
let drain_state = drain_events(
|
||||
&mut events,
|
||||
&mut stream_output,
|
||||
&mut stats,
|
||||
&mut terminal_targets,
|
||||
&mut dropped_events,
|
||||
)?;
|
||||
match drain_state {
|
||||
ManagedDrainState::Empty => thread::sleep(MANAGED_EVENT_WAIT_SLICE),
|
||||
ManagedDrainState::Closed => subscription_closed = true,
|
||||
ManagedDrainState::BudgetExhausted => {}
|
||||
}
|
||||
if handle.status().final_outcome.is_some() || subscription_closed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if interrupted {
|
||||
eprintln!("interrupted, closing managed run...");
|
||||
}
|
||||
let outcome = owner.join()?;
|
||||
drain_final_events(
|
||||
&mut events,
|
||||
&mut stream_output,
|
||||
&mut stats,
|
||||
&mut terminal_targets,
|
||||
&mut dropped_events,
|
||||
)?;
|
||||
if let Some(warning) = dropped_event_warning(dropped_events) {
|
||||
eprintln!("{warning}");
|
||||
}
|
||||
if outcome.discarded_target_outcomes != 0 {
|
||||
eprintln!(
|
||||
"irtt-rs: warning: {} final target outcomes were discarded",
|
||||
outcome.discarded_target_outcomes
|
||||
);
|
||||
}
|
||||
for target in outcome.recent_target_outcomes.iter() {
|
||||
if terminal_targets.insert(target.target.clone()) {
|
||||
report_target_failure(target);
|
||||
}
|
||||
}
|
||||
interrupted |= is_shutdown_requested(shutdown_requested);
|
||||
let terminal_error = match &outcome.end_reason {
|
||||
ManagedEndReason::DriverFailed(failure) => {
|
||||
Some(format!("managed driver failed: {failure}"))
|
||||
}
|
||||
_ => peer_close_run_error(continuous, interrupted, outcome.peer_closed_target_outcomes)
|
||||
.or_else(|| {
|
||||
(!interrupted
|
||||
&& outcome.successful_target_outcomes == 0
|
||||
&& outcome.failed_target_outcomes > 0)
|
||||
.then(|| {
|
||||
format!(
|
||||
"no managed target completed successfully ({} failed)",
|
||||
outcome.failed_target_outcomes
|
||||
)
|
||||
})
|
||||
}),
|
||||
};
|
||||
stream_output.print_final_summary = should_print_final_summary(continuous, interrupted);
|
||||
stream_output.show_running_only_summary_note =
|
||||
continuous && interrupted && stream_output.print_final_summary;
|
||||
for (label, stats) in &stats {
|
||||
if multi_target
|
||||
&& stream_output.print_final_summary
|
||||
&& stream_output.config.prints_summary()
|
||||
{
|
||||
writeln!(stream_output.out)?;
|
||||
writeln!(stream_output.out, "target: {label}")?;
|
||||
}
|
||||
stream_output.print_summary(stats)?;
|
||||
}
|
||||
stream_output.out.flush()?;
|
||||
if let Some(error) = terminal_error {
|
||||
return Err(error.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn process_event<W: Write>(
|
||||
event: ManagedEvent,
|
||||
stream_output: &mut StreamOutput<'_, W>,
|
||||
stats: &mut BTreeMap<String, StatsCollector>,
|
||||
terminal_targets: &mut HashSet<TargetInstance>,
|
||||
) -> io::Result<()> {
|
||||
match event {
|
||||
ManagedEvent::Client { target, event } => {
|
||||
let collector = stats
|
||||
.entry(target.id.as_str().to_owned())
|
||||
.or_insert_with(|| StatsCollector::new(stats_config(false)));
|
||||
print_events_with_stats(
|
||||
stream_output,
|
||||
std::slice::from_ref(&event),
|
||||
Some(target.id.as_str()),
|
||||
collector,
|
||||
)?;
|
||||
}
|
||||
ManagedEvent::TargetFinished { outcome } => {
|
||||
terminal_targets.insert(outcome.target.clone());
|
||||
report_target_failure(&outcome);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn drain_events<W: Write>(
|
||||
events: &mut ManagedEventSubscription,
|
||||
stream_output: &mut StreamOutput<'_, W>,
|
||||
stats: &mut BTreeMap<String, StatsCollector>,
|
||||
terminal_targets: &mut HashSet<TargetInstance>,
|
||||
dropped_events: &mut u64,
|
||||
) -> io::Result<ManagedDrainState> {
|
||||
drain_managed_events(events, dropped_events, |event| {
|
||||
process_event(event, stream_output, stats, terminal_targets)
|
||||
})
|
||||
}
|
||||
|
||||
fn drain_final_events<W: Write>(
|
||||
events: &mut ManagedEventSubscription,
|
||||
stream_output: &mut StreamOutput<'_, W>,
|
||||
stats: &mut BTreeMap<String, StatsCollector>,
|
||||
terminal_targets: &mut HashSet<TargetInstance>,
|
||||
dropped_events: &mut u64,
|
||||
) -> io::Result<()> {
|
||||
loop {
|
||||
match events.try_recv() {
|
||||
Ok(event) => process_event(event, stream_output, stats, terminal_targets)?,
|
||||
Err(ManagedEventTryRecvError::Empty | ManagedEventTryRecvError::Closed) => break,
|
||||
Err(ManagedEventTryRecvError::Lagged(count)) => {
|
||||
*dropped_events = dropped_events.saturating_add(count);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn report_target_failure(target: &ManagedTargetOutcome) {
|
||||
for message in target_failure_messages(target) {
|
||||
eprintln!("{message}");
|
||||
}
|
||||
}
|
||||
|
||||
fn target_failure_messages(target: &ManagedTargetOutcome) -> Vec<String> {
|
||||
let mut messages = Vec::with_capacity(2);
|
||||
if let ManagedTargetEndReason::Failed(failure) = &target.end_reason {
|
||||
messages.push(format!(
|
||||
"irtt-rs: target {} failed ({} {}): {}",
|
||||
target.target.id, failure.phase, failure.kind, failure.message
|
||||
));
|
||||
}
|
||||
if let Some(failure) = &target.cleanup_failure {
|
||||
messages.push(format!(
|
||||
"irtt-rs: target {} cleanup failed ({} {}): {}",
|
||||
target.target.id, failure.phase, failure.kind, failure.message
|
||||
));
|
||||
}
|
||||
messages
|
||||
}
|
||||
fn dropped_event_warning(dropped_events: u64) -> Option<String> {
|
||||
(dropped_events > 0).then(|| format!("irtt-rs: warning: dropped {dropped_events} managed run event{}; output and statistics may be incomplete", if dropped_events == 1 { "" } else { "s" }))
|
||||
}
|
||||
|
||||
struct StreamOutput<'a, W: Write> {
|
||||
config: OutputConfig,
|
||||
header_printed: bool,
|
||||
print_final_summary: bool,
|
||||
show_running_only_summary_note: bool,
|
||||
out: &'a mut W,
|
||||
}
|
||||
impl<W: Write> StreamOutput<'_, W> {
|
||||
fn print_events(
|
||||
&mut self,
|
||||
events: &[ClientEvent],
|
||||
target: Option<&str>,
|
||||
stats_updates: &[EventRenderStats],
|
||||
) -> io::Result<()> {
|
||||
self.print_header()?;
|
||||
for (event, stats_update) in events.iter().zip(stats_updates) {
|
||||
if let Some(line) = self.config.render_event(event, target, Some(stats_update)) {
|
||||
writeln!(self.out, "{line}")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn print_header(&mut self) -> io::Result<()> {
|
||||
if self.header_printed {
|
||||
return Ok(());
|
||||
}
|
||||
self.header_printed = true;
|
||||
if let Some(header) = self.config.render_header() {
|
||||
writeln!(self.out, "{header}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_summary(&mut self, stats: &StatsCollector) -> io::Result<()> {
|
||||
if self.print_final_summary && self.config.prints_summary() {
|
||||
write!(
|
||||
self.out,
|
||||
"{}",
|
||||
crate::cmd::client::summary::format_summary_with_options(
|
||||
&stats.snapshot(),
|
||||
crate::cmd::client::summary::SummaryFormatOptions {
|
||||
verbose: self.config.summary_verbose(),
|
||||
show_running_only_note: self.show_running_only_summary_note
|
||||
}
|
||||
)
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn print_events_with_stats<W: Write>(
|
||||
stream_output: &mut StreamOutput<'_, W>,
|
||||
events: &[ClientEvent],
|
||||
target: Option<&str>,
|
||||
stats: &mut StatsCollector,
|
||||
) -> io::Result<()> {
|
||||
let updates = events
|
||||
.iter()
|
||||
.map(|event| EventRenderStats::from(stats.process(event)))
|
||||
.collect::<Vec<_>>();
|
||||
stream_output.print_events(events, target, &updates)
|
||||
}
|
||||
|
||||
fn stats_config(continuous: bool) -> StatsConfig {
|
||||
if continuous {
|
||||
StatsConfig::continuous()
|
||||
} else {
|
||||
StatsConfig::finite()
|
||||
}
|
||||
}
|
||||
fn finite_stats_memory_warning(args: &ClientArgs, target_count: usize) -> Option<String> {
|
||||
if args.is_continuous() || args.duration.is_zero() {
|
||||
return None;
|
||||
}
|
||||
let target_count = u64::try_from(target_count).unwrap_or(u64::MAX);
|
||||
let total_probe_count =
|
||||
expected_probe_count(args.duration, args.interval).saturating_mul(target_count);
|
||||
// Ask the stats crate what the configuration this run will actually use
|
||||
// retains; the CLI owns the probe count and the thresholds, not the
|
||||
// retention model.
|
||||
let estimated_bytes = stats_config(false).estimated_retained_bytes(total_probe_count);
|
||||
if estimated_bytes < FINITE_STATS_MEMORY_WARNING_BYTES {
|
||||
return None;
|
||||
}
|
||||
let formatted = if estimated_bytes >= GIB {
|
||||
format!("{} GiB", estimated_bytes.saturating_add(GIB / 2) / GIB)
|
||||
} else {
|
||||
format!("{} MiB", estimated_bytes.saturating_add(MIB / 2) / MIB)
|
||||
};
|
||||
let guidance = if estimated_bytes >= FINITE_STATS_MEMORY_VERY_STRONG_WARNING_BYTES {
|
||||
"this may be unsuitable on memory-constrained systems"
|
||||
} else if estimated_bytes >= FINITE_STATS_MEMORY_STRONG_WARNING_BYTES {
|
||||
"consider shortening the run, increasing the interval, or using continuous mode"
|
||||
} else {
|
||||
"use continuous mode for bounded-memory long-running tests"
|
||||
};
|
||||
Some(format!("irtt-rs: warning: finite exact statistics may retain about {formatted} for this run; {guidance}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use irtt_client::managed::{
|
||||
ManagedTargetFailure, ManagedTargetFailureKind, ManagedTargetFailurePhase, TargetId,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn long_finite_args() -> ClientArgs {
|
||||
use clap::Parser;
|
||||
|
||||
ClientArgs::try_parse_from([
|
||||
"irtt-cli",
|
||||
"--duration",
|
||||
"4200s",
|
||||
"--interval",
|
||||
"100ms",
|
||||
"127.0.0.1:2112",
|
||||
])
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Smallest target count whose aggregate estimate reaches the warning
|
||||
/// threshold, derived from the stats crate's own estimate rather than from
|
||||
/// any bytes-per-probe assumption held here.
|
||||
fn first_warning_target_count(args: &ClientArgs) -> usize {
|
||||
let probes = expected_probe_count(args.duration, args.interval);
|
||||
(1..=1024)
|
||||
.find(|targets| {
|
||||
let total = probes.saturating_mul(*targets as u64);
|
||||
stats_config(false).estimated_retained_bytes(total)
|
||||
>= FINITE_STATS_MEMORY_WARNING_BYTES
|
||||
})
|
||||
.expect("a long finite run should cross the warning threshold within 1024 targets")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finite_stats_memory_warning_accounts_for_target_count() {
|
||||
let args = long_finite_args();
|
||||
let crossing = first_warning_target_count(&args);
|
||||
|
||||
assert!(
|
||||
crossing > 1,
|
||||
"this run should need more than one target to cross the threshold, \
|
||||
otherwise the test proves nothing about target-count accounting"
|
||||
);
|
||||
assert!(
|
||||
finite_stats_memory_warning(&args, crossing - 1).is_none(),
|
||||
"an aggregate estimate below the threshold should not warn"
|
||||
);
|
||||
assert!(
|
||||
finite_stats_memory_warning(&args, crossing).is_some(),
|
||||
"an aggregate estimate at the threshold should warn"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finite_stats_memory_warning_saturates_target_count_multiplication() {
|
||||
assert!(finite_stats_memory_warning(&long_finite_args(), usize::MAX).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lagged_events_are_counted_saturatingly() {
|
||||
let mut dropped = 0_u64;
|
||||
dropped = dropped.saturating_add(7);
|
||||
dropped = dropped.saturating_add(3);
|
||||
assert_eq!(dropped, 10);
|
||||
assert_eq!(u64::MAX.saturating_add(1), u64::MAX);
|
||||
assert!(dropped_event_warning(dropped)
|
||||
.unwrap()
|
||||
.contains("dropped 10 managed run events"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_failure_diagnostics_include_primary_and_cleanup_failures() {
|
||||
let target = ManagedTargetOutcome {
|
||||
target: TargetInstance {
|
||||
id: TargetId::from("edge"),
|
||||
generation: 1,
|
||||
},
|
||||
server_addr: Arc::from("127.0.0.1:2112"),
|
||||
remote: None,
|
||||
end_reason: ManagedTargetEndReason::Failed(ManagedTargetFailure {
|
||||
phase: ManagedTargetFailurePhase::Receiving,
|
||||
kind: ManagedTargetFailureKind::Protocol,
|
||||
message: "primary failure".into(),
|
||||
}),
|
||||
packets_sent: 0,
|
||||
replies_received: 0,
|
||||
duplicates: 0,
|
||||
late: 0,
|
||||
warning_events: 0,
|
||||
cleanup_failure: Some(ManagedTargetFailure {
|
||||
phase: ManagedTargetFailurePhase::Closing,
|
||||
kind: ManagedTargetFailureKind::Socket,
|
||||
message: "cleanup failure".into(),
|
||||
}),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
target_failure_messages(&target),
|
||||
[
|
||||
"irtt-rs: target edge failed (receiving protocol): primary failure",
|
||||
"irtt-rs: target edge cleanup failed (closing socket): cleanup failure",
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
//! Scalar presentation vocabulary shared by the CLI frontends.
|
||||
//!
|
||||
//! Stream output, the run summary, and the TUI display different metrics in
|
||||
//! different layouts, but they render the same *scalars*: nanosecond-scale
|
||||
//! durations, percentages, and counts. This module owns those spellings so the
|
||||
//! frontends cannot drift apart on units, rounding, or how an absent value is
|
||||
//! rendered.
|
||||
//!
|
||||
//! It is presentation only. Nothing here belongs in `irtt-stats`, and it is
|
||||
//! deliberately not a general formatting framework: it holds exactly the
|
||||
//! vocabulary more than one frontend needs.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use irtt_client::SignedDuration;
|
||||
|
||||
/// Rendering used wherever a scalar is unavailable.
|
||||
pub(crate) const ABSENT: &str = "-";
|
||||
|
||||
/// Format a nanosecond scalar.
|
||||
///
|
||||
/// Unit selection and rounding are one policy for every frontend:
|
||||
///
|
||||
/// | magnitude | unit | precision |
|
||||
/// |-----------|------|-----------|
|
||||
/// | `< 1µs` | `ns` | whole |
|
||||
/// | `< 1ms` | `µs` | 1 decimal |
|
||||
/// | `< 1s` | `ms` | 1 decimal |
|
||||
/// | `>= 1s` | `s` | 3 decimals |
|
||||
///
|
||||
/// Negative values are meaningful (clock offsets, one-way deltas, IPDV), so
|
||||
/// the unit is selected from the magnitude and the sign is preserved. Values
|
||||
/// that are not finite render as [`ABSENT`].
|
||||
pub(crate) fn format_ns_f64(value: f64) -> String {
|
||||
if !value.is_finite() {
|
||||
return ABSENT.to_owned();
|
||||
}
|
||||
let sign = if value.is_sign_negative() { "-" } else { "" };
|
||||
let magnitude = value.abs();
|
||||
if magnitude < 1_000.0 {
|
||||
format!("{sign}{magnitude:.0}ns")
|
||||
} else if magnitude < 1_000_000.0 {
|
||||
format!("{sign}{:.1}µs", magnitude / 1_000.0)
|
||||
} else if magnitude < 1_000_000_000.0 {
|
||||
format!("{sign}{:.1}ms", magnitude / 1_000_000.0)
|
||||
} else {
|
||||
format!("{sign}{:.3}s", magnitude / 1_000_000_000.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Format an exact nanosecond scalar with [`format_ns_f64`]'s policy.
|
||||
pub(crate) fn format_ns_i128(value: i128) -> String {
|
||||
let sign = if value < 0 { "-" } else { "" };
|
||||
let magnitude = value.saturating_abs() as f64;
|
||||
format!("{sign}{}", format_ns_f64(magnitude))
|
||||
}
|
||||
|
||||
/// Format an optional nanosecond scalar, rendering `None` as [`ABSENT`].
|
||||
pub(crate) fn format_optional_ns_i128(value: Option<i128>) -> String {
|
||||
value.map(format_ns_i128).unwrap_or_else(absent)
|
||||
}
|
||||
|
||||
/// Format an optional nanosecond scalar, rendering `None` as [`ABSENT`].
|
||||
pub(crate) fn format_optional_ns_f64(value: Option<f64>) -> String {
|
||||
value.map(format_ns_f64).unwrap_or_else(absent)
|
||||
}
|
||||
|
||||
/// Format a duration as a nanosecond scalar.
|
||||
pub(crate) fn format_duration(value: Duration) -> String {
|
||||
format_ns_i128(i128::try_from(value.as_nanos()).unwrap_or(i128::MAX))
|
||||
}
|
||||
|
||||
/// Format a signed duration as a nanosecond scalar, preserving its sign.
|
||||
pub(crate) fn format_signed_duration(value: SignedDuration) -> String {
|
||||
format_ns_i128(value.as_nanos())
|
||||
}
|
||||
|
||||
/// Format a percentage with two decimals; non-finite values render as
|
||||
/// [`ABSENT`].
|
||||
pub(crate) fn format_percent(value: f64) -> String {
|
||||
if value.is_finite() {
|
||||
format!("{value:.2}%")
|
||||
} else {
|
||||
ABSENT.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// Format `value` as a percentage of `total`, capped at 100%.
|
||||
///
|
||||
/// A zero total has no percentage to report and renders as [`ABSENT`].
|
||||
pub(crate) fn format_percent_ratio(value: u64, total: u64) -> String {
|
||||
if total == 0 {
|
||||
ABSENT.to_owned()
|
||||
} else {
|
||||
format_percent((value as f64 / total as f64 * 100.0).min(100.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// Format a scalar count.
|
||||
pub(crate) fn format_count(value: u64) -> String {
|
||||
value.to_string()
|
||||
}
|
||||
|
||||
/// Format an optional scalar count, rendering `None` as [`ABSENT`].
|
||||
pub(crate) fn format_optional_count(value: Option<u64>) -> String {
|
||||
value.map(format_count).unwrap_or_else(absent)
|
||||
}
|
||||
|
||||
fn absent() -> String {
|
||||
ABSENT.to_owned()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn nanosecond_scalars_select_units_at_the_defined_boundaries() {
|
||||
assert_eq!(format_ns_f64(0.0), "0ns");
|
||||
assert_eq!(format_ns_f64(999.0), "999ns");
|
||||
assert_eq!(format_ns_f64(1_000.0), "1.0µs");
|
||||
assert_eq!(format_ns_f64(999_999.0), "1000.0µs");
|
||||
assert_eq!(format_ns_f64(1_000_000.0), "1.0ms");
|
||||
assert_eq!(format_ns_f64(999_999_999.0), "1000.0ms");
|
||||
assert_eq!(format_ns_f64(1_000_000_000.0), "1.000s");
|
||||
assert_eq!(format_ns_f64(1_500_000_000.0), "1.500s");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_nanosecond_scalars_keep_their_sign() {
|
||||
assert_eq!(format_ns_f64(-500.0), "-500ns");
|
||||
assert_eq!(format_ns_f64(-1_500.0), "-1.5µs");
|
||||
assert_eq!(format_ns_f64(-2_500_000.0), "-2.5ms");
|
||||
assert_eq!(format_ns_f64(-1_000_000_000.0), "-1.000s");
|
||||
assert_eq!(format_ns_i128(-1_500), "-1.5µs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_and_floating_nanosecond_scalars_agree() {
|
||||
for value in [0_i128, 1, 999, 1_000, 1_234_567, -1_234_567, 5_000_000_000] {
|
||||
assert_eq!(format_ns_i128(value), format_ns_f64(value as f64));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn microseconds_use_the_micro_sign() {
|
||||
assert!(format_ns_f64(1_500.0).ends_with("µs"));
|
||||
assert!(!format_ns_f64(1_500.0).contains("us"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn durations_render_as_nanosecond_scalars() {
|
||||
assert_eq!(format_duration(Duration::from_millis(25)), "25.0ms");
|
||||
assert_eq!(format_duration(Duration::from_secs(1)), "1.000s");
|
||||
assert_eq!(
|
||||
format_signed_duration(SignedDuration::from_nanos(-1_500)),
|
||||
"-1.5µs"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absent_and_non_finite_scalars_render_as_a_placeholder() {
|
||||
assert_eq!(format_optional_ns_i128(None), ABSENT);
|
||||
assert_eq!(format_optional_ns_f64(None), ABSENT);
|
||||
assert_eq!(format_optional_count(None), ABSENT);
|
||||
assert_eq!(format_ns_f64(f64::NAN), ABSENT);
|
||||
assert_eq!(format_ns_f64(f64::INFINITY), ABSENT);
|
||||
assert_eq!(format_percent(f64::NAN), ABSENT);
|
||||
assert_eq!(format_percent_ratio(1, 0), ABSENT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn percentages_and_counts_have_one_spelling() {
|
||||
assert_eq!(format_percent(0.0), "0.00%");
|
||||
assert_eq!(format_percent(12.345), "12.35%");
|
||||
assert_eq!(format_percent_ratio(1, 4), "25.00%");
|
||||
assert_eq!(format_percent_ratio(5, 4), "100.00%");
|
||||
assert_eq!(format_count(42), "42");
|
||||
assert_eq!(format_optional_count(Some(0)), "0");
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
#[cfg(feature = "client")]
|
||||
pub mod client;
|
||||
#[cfg(any(feature = "client", feature = "tui"))]
|
||||
mod format;
|
||||
#[cfg(feature = "server")]
|
||||
pub mod server;
|
||||
#[cfg(feature = "tui")]
|
||||
pub mod tui;
|
||||
|
||||
// Additional command applets belong here behind their own feature gate.
|
||||
@@ -1,413 +0,0 @@
|
||||
use std::{net::SocketAddr, time::Duration};
|
||||
|
||||
use clap::{Parser, ValueEnum};
|
||||
use irtt_server::{ServerConfig, TimestampAllowance};
|
||||
|
||||
// Every policy option is optional. An omitted option leaves the corresponding
|
||||
// `ServerConfig` default in place rather than restating it here, so library and
|
||||
// CLI defaults cannot drift apart.
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
#[command(
|
||||
name = "irtt-server",
|
||||
about = "Minimal IRTT-compatible UDP server",
|
||||
after_help = "Policy options left unset keep the irtt-server library defaults.\nRepeat --bind to serve multiple addresses in one process. All listeners use the same policy but keep independent session namespaces."
|
||||
)]
|
||||
pub struct ServerArgs {
|
||||
/// Local UDP address to bind, as ADDR:PORT. Repeatable.
|
||||
#[arg(
|
||||
long,
|
||||
required = true,
|
||||
value_name = "ADDR",
|
||||
long_help = "Local UDP address to bind, as ADDR:PORT, for example 127.0.0.1:2112 or [::1]:2112. Host names are not resolved.\n\nRepeat the option to serve several addresses from one process, in the order given. Every listener applies the same policy options, but each keeps its own sessions and tokens, so a session belongs to the address it was opened on. Binding is all or nothing: if any address cannot be bound, none are served.\n\nA wildcard bind such as 0.0.0.0:2112 answers each request from the address it was sent to, using per-packet destination metadata. That is supported on Linux, macOS and FreeBSD; on other systems a wildcard bind is refused and an explicit interface address is required.\n\nA port of 0 selects an unused port per listener, so two such binds get two different ports."
|
||||
)]
|
||||
pub bind: Vec<SocketAddr>,
|
||||
|
||||
/// HMAC key; every request must then carry a valid MAC.
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "KEY",
|
||||
long_help = "HMAC key, taken as the UTF-8 bytes of this argument.\n\nAuthentication is global: with a key configured, every request must carry a valid MAC and every reply is authenticated. Without one, authenticated requests are dropped. The key is visible in the process arguments."
|
||||
)]
|
||||
pub hmac: Option<String>,
|
||||
|
||||
/// Maximum simultaneously live sessions per listener.
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "COUNT",
|
||||
long_help = "Maximum number of simultaneously live sessions per listener. Once a listener's table is full, a session-creating open to it is dropped silently; nothing is evicted. Zero refuses every session-creating open.\n\nThis is a per-listener bound, not a process-wide one: with two --bind options, each listener admits up to this many sessions."
|
||||
)]
|
||||
pub max_sessions: Option<usize>,
|
||||
|
||||
/// Maximum echo datagram size a session may negotiate, in bytes.
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "BYTES",
|
||||
long_help = "Maximum echo datagram size a session may negotiate, in bytes. A longer requested length is reduced during negotiation, an open whose mandatory field block would not fit is refused, and inbound echo requests are admitted against the same limit. This is a resource bound, not an MTU."
|
||||
)]
|
||||
pub max_packet_length: Option<usize>,
|
||||
|
||||
/// Floor on the negotiated send interval, and the allowance refill cadence.
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "DURATION",
|
||||
value_parser = parse_duration_allow_zero,
|
||||
long_help = "Floor on the send interval a session may negotiate, and the cadence its reply allowance refills at. The negotiated interval is still capped at a quarter of the idle timeout afterwards. Use 0 for no time-based throttling."
|
||||
)]
|
||||
pub min_interval: Option<Duration>,
|
||||
|
||||
/// Echo replies a session may burst before its allowance refills.
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "COUNT",
|
||||
long_help = "Echo replies one session may have answered before its allowance has to refill. Use 0 for no allowance at all, which rate-limits every echo request whatever the interval is."
|
||||
)]
|
||||
pub burst: Option<u32>,
|
||||
|
||||
/// Release a session after this long without an echo request.
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "DURATION",
|
||||
value_parser = parse_duration_allow_zero,
|
||||
long_help = "Release a session after this long without a served or rate-limited echo request. The deadline runs from the open, and release is silent. Use 0 to expire a session at the next evaluation; it is not a way to disable expiry."
|
||||
)]
|
||||
pub idle_timeout: Option<Duration>,
|
||||
|
||||
/// Maximum test duration a session may negotiate.
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "DURATION",
|
||||
value_parser = parse_positive_duration,
|
||||
long_help = "Maximum test duration a session may negotiate. A longer request is reduced to it, and a continuous request is answered with it. Omit this flag for no maximum; a maximum of zero cannot be expressed, because a negotiated duration of zero means continuous."
|
||||
)]
|
||||
pub max_duration: Option<Duration>,
|
||||
|
||||
/// How many timestamps this server will provide.
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "MODE",
|
||||
value_enum,
|
||||
long_help = "How many timestamps this server will provide.\n\ndual: honor a request for send, receive, both or midpoint timestamps.\nsingle: provide at most one timestamp instant; a request for both is negotiated to midpoint.\nnone: provide no timestamps at all.\n\nThe requested clock source is never changed, only which instants are reported, so a single instant is still reported once per requested clock. Omit this flag to honor every requested placement."
|
||||
)]
|
||||
pub timestamp_allowance: Option<TimestampAllowanceArg>,
|
||||
|
||||
/// Refuse to provide requested DSCP marking.
|
||||
#[arg(
|
||||
long,
|
||||
long_help = "Refuse to provide requested traffic-class marking. Any requested DSCP is negotiated to zero, so the client is told its echo replies will be unmarked, and they are sent unmarked. The session is not refused."
|
||||
)]
|
||||
pub no_dscp: bool,
|
||||
}
|
||||
|
||||
/// The command-line spelling of [`TimestampAllowance`].
|
||||
///
|
||||
/// A CLI-local enum rather than a `clap` derive on the library type: `irtt-server`
|
||||
/// is a reusable crate and has no business depending on an argument parser.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
|
||||
pub enum TimestampAllowanceArg {
|
||||
/// Honor every requested timestamp placement.
|
||||
Dual,
|
||||
/// Provide at most one timestamp instant; both becomes midpoint.
|
||||
Single,
|
||||
/// Provide no timestamps.
|
||||
None,
|
||||
}
|
||||
|
||||
impl From<TimestampAllowanceArg> for TimestampAllowance {
|
||||
fn from(value: TimestampAllowanceArg) -> Self {
|
||||
match value {
|
||||
TimestampAllowanceArg::Dual => Self::Dual,
|
||||
TimestampAllowanceArg::Single => Self::Single,
|
||||
TimestampAllowanceArg::None => Self::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerArgs {
|
||||
/// Builds the server configuration this invocation asks for.
|
||||
#[must_use]
|
||||
pub fn server_config(&self) -> ServerConfig {
|
||||
let mut config = ServerConfig::default();
|
||||
if let Some(key) = self.hmac.as_ref() {
|
||||
config = config.with_hmac_key(key.as_bytes());
|
||||
}
|
||||
if let Some(value) = self.max_sessions {
|
||||
config = config.with_max_sessions(value);
|
||||
}
|
||||
if let Some(value) = self.max_packet_length {
|
||||
config = config.with_max_packet_length(value);
|
||||
}
|
||||
if let Some(value) = self.min_interval {
|
||||
config = config.with_min_send_interval(value);
|
||||
}
|
||||
if let Some(value) = self.burst {
|
||||
config = config.with_burst_allowance(value);
|
||||
}
|
||||
if let Some(value) = self.idle_timeout {
|
||||
config = config.with_idle_timeout(value);
|
||||
}
|
||||
if let Some(value) = self.max_duration {
|
||||
config = config.with_max_test_duration(value);
|
||||
}
|
||||
if let Some(value) = self.timestamp_allowance {
|
||||
config = config.with_timestamp_allowance(value.into());
|
||||
}
|
||||
// A negative capability flag, so absence is the ordinary enabled state
|
||||
// and the library default is what an unset flag leaves in place.
|
||||
if self.no_dscp {
|
||||
config = config.with_dscp_allowed(false);
|
||||
}
|
||||
config
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a duration whose zero is meaningful server policy.
|
||||
fn parse_duration_allow_zero(input: &str) -> Result<Duration, String> {
|
||||
if input == "0" {
|
||||
return Ok(Duration::ZERO);
|
||||
}
|
||||
parse_duration_units(input)
|
||||
}
|
||||
|
||||
/// Parses a duration that must be positive, where absence means "no limit".
|
||||
fn parse_positive_duration(input: &str) -> Result<Duration, String> {
|
||||
let value = if input == "0" {
|
||||
Duration::ZERO
|
||||
} else {
|
||||
parse_duration_units(input)?
|
||||
};
|
||||
if value.is_zero() {
|
||||
return Err(
|
||||
"duration must be greater than zero; omit the option for no maximum".to_owned(),
|
||||
);
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn parse_duration_units(input: &str) -> Result<Duration, String> {
|
||||
let split = input
|
||||
.find(|ch: char| !ch.is_ascii_digit())
|
||||
.ok_or_else(|| "duration must include a unit: ms, s, or m".to_owned())?;
|
||||
let (number, unit) = input.split_at(split);
|
||||
if number.is_empty() {
|
||||
return Err("duration must include a value and a unit: ms, s, or m".to_owned());
|
||||
}
|
||||
let value: u64 = number
|
||||
.parse()
|
||||
.map_err(|_| format!("invalid duration value {input:?}"))?;
|
||||
match unit {
|
||||
"ms" => Ok(Duration::from_millis(value)),
|
||||
"s" => Ok(Duration::from_secs(value)),
|
||||
"m" => value
|
||||
.checked_mul(60)
|
||||
.map(Duration::from_secs)
|
||||
.ok_or_else(|| "duration is too large".to_owned()),
|
||||
_ => Err(format!(
|
||||
"unsupported duration unit {unit:?}; use ms, s, or m"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::net::{Ipv4Addr, Ipv6Addr};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn parse(args: &[&str]) -> Result<ServerArgs, clap::Error> {
|
||||
let mut argv = vec!["irtt-server"];
|
||||
argv.extend_from_slice(args);
|
||||
ServerArgs::try_parse_from(argv)
|
||||
}
|
||||
|
||||
fn bound(args: &[&str]) -> ServerArgs {
|
||||
let mut argv = vec!["--bind", "127.0.0.1:2112"];
|
||||
argv.extend_from_slice(args);
|
||||
parse(&argv).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bind_is_required_and_parses_both_families() {
|
||||
assert!(
|
||||
parse(&[]).is_err(),
|
||||
"a server with no address serves nothing"
|
||||
);
|
||||
|
||||
let ipv4 = parse(&["--bind", "127.0.0.1:2112"]).unwrap();
|
||||
assert_eq!(ipv4.bind, [SocketAddr::from((Ipv4Addr::LOCALHOST, 2112))]);
|
||||
|
||||
let ipv6 = parse(&["--bind", "[::1]:2112"]).unwrap();
|
||||
assert_eq!(ipv6.bind, [SocketAddr::from((Ipv6Addr::LOCALHOST, 2112))]);
|
||||
|
||||
assert!(parse(&["--bind", "127.0.0.1"]).is_err());
|
||||
assert!(parse(&["--bind", "localhost:2112"]).is_err());
|
||||
// Still one address per option: comma-separated syntax is not a thing
|
||||
// here, and accepting it silently would be worse than rejecting it.
|
||||
assert!(parse(&["--bind", "127.0.0.1:2112,[::1]:2112"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bind_is_repeatable_and_keeps_the_requested_order() {
|
||||
let args = parse(&[
|
||||
"--bind",
|
||||
"[::1]:2112",
|
||||
"--bind",
|
||||
"127.0.0.1:2112",
|
||||
"--bind",
|
||||
"127.0.0.1:2113",
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
args.bind,
|
||||
[
|
||||
SocketAddr::from((Ipv6Addr::LOCALHOST, 2112)),
|
||||
SocketAddr::from((Ipv4Addr::LOCALHOST, 2112)),
|
||||
SocketAddr::from((Ipv4Addr::LOCALHOST, 2113)),
|
||||
],
|
||||
"listeners are served in the order they were requested"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_configuration_is_one_policy_however_many_listeners_there_are() {
|
||||
// Addresses never enter the server configuration: every listener is
|
||||
// built from a clone of this one value.
|
||||
let one = parse(&["--bind", "127.0.0.1:2112", "--max-sessions", "4"])
|
||||
.unwrap()
|
||||
.server_config();
|
||||
let several = parse(&[
|
||||
"--bind",
|
||||
"127.0.0.1:2112",
|
||||
"--bind",
|
||||
"[::1]:2112",
|
||||
"--max-sessions",
|
||||
"4",
|
||||
])
|
||||
.unwrap()
|
||||
.server_config();
|
||||
|
||||
assert_eq!(one, several);
|
||||
assert_eq!(several.max_sessions(), 4, "and it is a per-listener bound");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn omitted_policy_options_keep_the_library_defaults() {
|
||||
assert_eq!(bound(&[]).server_config(), ServerConfig::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn policy_options_map_onto_the_server_config() {
|
||||
let config = bound(&[
|
||||
"--hmac",
|
||||
"secret",
|
||||
"--max-sessions",
|
||||
"512",
|
||||
"--max-packet-length",
|
||||
"1472",
|
||||
"--min-interval",
|
||||
"20ms",
|
||||
"--burst",
|
||||
"3",
|
||||
"--idle-timeout",
|
||||
"30s",
|
||||
"--max-duration",
|
||||
"2m",
|
||||
])
|
||||
.server_config();
|
||||
|
||||
assert_eq!(config.hmac_key(), Some(b"secret".as_slice()));
|
||||
assert_eq!(config.max_sessions(), 512);
|
||||
assert_eq!(config.max_packet_length(), 1472);
|
||||
assert_eq!(config.min_send_interval(), Duration::from_millis(20));
|
||||
assert_eq!(config.burst_allowance(), 3);
|
||||
assert_eq!(config.idle_timeout(), Duration::from_secs(30));
|
||||
assert_eq!(config.max_test_duration(), Some(Duration::from_secs(120)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_capability_restrictions_map_onto_the_server_config() {
|
||||
let config = bound(&["--timestamp-allowance", "single", "--no-dscp"]).server_config();
|
||||
|
||||
assert_eq!(
|
||||
config.timestamp_allowance(),
|
||||
TimestampAllowance::Single,
|
||||
"a request for both timestamps is negotiated to midpoint"
|
||||
);
|
||||
assert!(!config.dscp_allowed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_timestamp_allowance_mode_parses() {
|
||||
for (argument, expected) in [
|
||||
("dual", TimestampAllowance::Dual),
|
||||
("single", TimestampAllowance::Single),
|
||||
("none", TimestampAllowance::None),
|
||||
] {
|
||||
assert_eq!(
|
||||
bound(&["--timestamp-allowance", argument])
|
||||
.server_config()
|
||||
.timestamp_allowance(),
|
||||
expected,
|
||||
"--timestamp-allowance {argument}"
|
||||
);
|
||||
}
|
||||
|
||||
assert!(parse(&[
|
||||
"--bind",
|
||||
"127.0.0.1:2112",
|
||||
"--timestamp-allowance",
|
||||
"midpoint"
|
||||
])
|
||||
.is_err());
|
||||
assert!(parse(&["--bind", "127.0.0.1:2112", "--timestamp-allowance", "both"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_capability_restrictions_are_off_when_their_flags_are_absent() {
|
||||
// Explicitly, and not only through the whole-config comparison above:
|
||||
// these are the two values that would silently change every existing
|
||||
// deployment's negotiation if the CLI restated them.
|
||||
let config = bound(&["--idle-timeout", "30s"]).server_config();
|
||||
|
||||
assert_eq!(config.timestamp_allowance(), TimestampAllowance::Dual);
|
||||
assert!(config.dscp_allowed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_zero_policy_values_are_preserved() {
|
||||
let config = bound(&[
|
||||
"--min-interval",
|
||||
"0",
|
||||
"--idle-timeout",
|
||||
"0ms",
|
||||
"--burst",
|
||||
"0",
|
||||
"--max-sessions",
|
||||
"0",
|
||||
"--max-packet-length",
|
||||
"0",
|
||||
])
|
||||
.server_config();
|
||||
|
||||
assert_eq!(config.min_send_interval(), Duration::ZERO);
|
||||
assert_eq!(config.idle_timeout(), Duration::ZERO);
|
||||
assert_eq!(config.burst_allowance(), 0);
|
||||
assert_eq!(config.max_sessions(), 0);
|
||||
assert_eq!(config.max_packet_length(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn durations_require_a_supported_unit() {
|
||||
assert!(parse(&["--bind", "127.0.0.1:2112", "--idle-timeout", "30"]).is_err());
|
||||
assert!(parse(&["--bind", "127.0.0.1:2112", "--min-interval", "20us"]).is_err());
|
||||
assert!(parse(&["--bind", "127.0.0.1:2112", "--max-duration", "2h"]).is_err());
|
||||
assert!(parse(&["--bind", "127.0.0.1:2112", "--idle-timeout", "ms"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_maximum_duration_is_not_a_spelling_of_no_maximum() {
|
||||
assert!(parse(&["--bind", "127.0.0.1:2112", "--max-duration", "0"]).is_err());
|
||||
assert!(parse(&["--bind", "127.0.0.1:2112", "--max-duration", "0s"]).is_err());
|
||||
assert_eq!(bound(&[]).server_config().max_test_duration(), None);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
pub mod args;
|
||||
pub mod run;
|
||||
|
||||
pub use args::ServerArgs;
|
||||
pub use run::run_server;
|
||||
@@ -1,85 +0,0 @@
|
||||
use std::{
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use irtt_server::ServerSet;
|
||||
|
||||
use super::args::ServerArgs;
|
||||
|
||||
/// How often the shutdown future samples the process-wide signal flag.
|
||||
///
|
||||
/// The flag a signal handler sets has no async wake mechanism, so the future
|
||||
/// polls it on a timer rather than spinning. `ServerSet::run` owns everything
|
||||
/// after that future becomes ready, including fanning it out to the listeners.
|
||||
const SHUTDOWN_POLL_INTERVAL: Duration = Duration::from_millis(50);
|
||||
|
||||
/// Runs the configured listeners until the process is asked to shut down.
|
||||
///
|
||||
/// The applet owns exactly one current-thread Tokio runtime and one
|
||||
/// [`ServerSet`], whatever number of addresses was requested. A single `--bind`
|
||||
/// is an ordinary set of one and takes the same path as a set of several: one
|
||||
/// construction, one shutdown future, one supervision rule. Listener
|
||||
/// concurrency is async I/O concurrency and needs no worker threads.
|
||||
pub fn run_server(
|
||||
args: ServerArgs,
|
||||
shutdown_requested: &AtomicBool,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
runtime.block_on(serve(args, shutdown_requested))
|
||||
}
|
||||
|
||||
async fn serve(
|
||||
args: ServerArgs,
|
||||
shutdown_requested: &AtomicBool,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let config = args.server_config();
|
||||
let set = ServerSet::bind(args.bind, config).await?;
|
||||
// Only once every listener is up. Announcing one address and then failing
|
||||
// to bind the next would report a service that never started.
|
||||
for addr in set.local_addrs() {
|
||||
eprintln!("irtt-server: listening on {addr}");
|
||||
}
|
||||
set.run(shutdown_signal(shutdown_requested)).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn shutdown_signal(shutdown_requested: &AtomicBool) {
|
||||
while !shutdown_requested.load(Ordering::Relaxed) {
|
||||
tokio::time::sleep(SHUTDOWN_POLL_INTERVAL).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use clap::Parser;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The ordinary invocation, and the one that keeps the single-listener case
|
||||
/// on the same orchestration path as every other.
|
||||
#[test]
|
||||
fn an_already_requested_shutdown_binds_one_listener_and_returns() {
|
||||
let args = ServerArgs::try_parse_from(["irtt-server", "--bind", "127.0.0.1:0"]).unwrap();
|
||||
let shutdown_requested = AtomicBool::new(true);
|
||||
|
||||
run_server(args, &shutdown_requested).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_already_requested_shutdown_binds_every_listener_and_returns() {
|
||||
let args = ServerArgs::try_parse_from([
|
||||
"irtt-server",
|
||||
"--bind",
|
||||
"127.0.0.1:0",
|
||||
"--bind",
|
||||
"127.0.0.1:0",
|
||||
])
|
||||
.unwrap();
|
||||
let shutdown_requested = AtomicBool::new(true);
|
||||
|
||||
run_server(args, &shutdown_requested).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -1,279 +0,0 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::Parser;
|
||||
|
||||
#[cfg(test)]
|
||||
use crate::shared::client::TimestampArg;
|
||||
use crate::shared::client::{
|
||||
parse_target, parse_test_duration, prepare_managed_run, CommonClientArgs, GroupPacingArg,
|
||||
ManagedRunSetup, TargetArg, TargetSelection,
|
||||
};
|
||||
|
||||
pub const DEFAULT_TUI_DURATION: Duration = Duration::ZERO;
|
||||
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
#[command(name = "irtt-tui", about = "Minimal IRTT-compatible TUI client")]
|
||||
pub struct TuiArgs {
|
||||
/// Server address/host, optionally prefixed with LABEL=. Repeat for multi-target mode.
|
||||
#[arg(
|
||||
value_name = "TARGET",
|
||||
num_args = 1..,
|
||||
required = true,
|
||||
value_parser = parse_target,
|
||||
long_help = "Server address/host, optionally prefixed with LABEL=. Repeat for multi-target mode.\n\nExplicit labels are used in the legend and status table.\n\nExamples:\n irtt-tui host.example\n irtt-tui eu=host.example\n irtt-tui eu=host-a.example us=host-b.example"
|
||||
)]
|
||||
pub targets: Vec<TargetArg>,
|
||||
|
||||
/// Managed group pacing for multi-target mode.
|
||||
#[arg(
|
||||
long,
|
||||
value_enum,
|
||||
default_value_t = GroupPacingArg::Staggered,
|
||||
long_help = "Managed group pacing for multi-target mode.\n\nstaggered spaces active targets across the probe interval. burst sends one probe to every active target back-to-back once per interval."
|
||||
)]
|
||||
pub pacing: GroupPacingArg,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
default_value = "0",
|
||||
value_parser = parse_test_duration,
|
||||
help = "Test duration; use 0 for continuous mode",
|
||||
long_help = "Test duration; use 0 for continuous mode. The TUI defaults to continuous mode."
|
||||
)]
|
||||
pub duration: Duration,
|
||||
|
||||
#[command(flatten)]
|
||||
pub common: CommonClientArgs,
|
||||
}
|
||||
|
||||
impl TuiArgs {
|
||||
/// Validate the selected targets and prepare the managed run.
|
||||
///
|
||||
/// The TUI always requires a target: the parser rejects an empty target
|
||||
/// list, and this rejects a target set that cannot be labelled uniquely.
|
||||
pub fn prepare(&self) -> Result<ManagedRunSetup, String> {
|
||||
prepare_managed_run(
|
||||
&self.common,
|
||||
self.duration,
|
||||
TargetSelection {
|
||||
targets: &self.targets,
|
||||
pacing: self.pacing,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn is_continuous(&self) -> bool {
|
||||
self.duration == Duration::ZERO
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn timestamp_mode(&self) -> TimestampArg {
|
||||
self.common.tstamp
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for TuiArgs {
|
||||
type Target = CommonClientArgs;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.common
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use clap::{CommandFactory, Parser};
|
||||
|
||||
#[derive(Parser)]
|
||||
struct SharedOnlyArgs {
|
||||
#[command(flatten)]
|
||||
common: CommonClientArgs,
|
||||
}
|
||||
|
||||
fn parse(args: &[&str]) -> Result<TuiArgs, clap::Error> {
|
||||
let mut argv = vec!["irtt-tui"];
|
||||
argv.extend_from_slice(args);
|
||||
TuiArgs::try_parse_from(argv)
|
||||
}
|
||||
|
||||
fn parse_shared(args: &[&str]) -> Result<SharedOnlyArgs, clap::Error> {
|
||||
let mut argv = vec!["shared-only"];
|
||||
argv.extend_from_slice(args);
|
||||
SharedOnlyArgs::try_parse_from(argv)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tui_parser_defaults_to_continuous_and_has_no_output_option() {
|
||||
let args = parse(&["127.0.0.1:2112"]).unwrap();
|
||||
assert_eq!(args.targets.len(), 1);
|
||||
assert_eq!(args.targets[0].label, None);
|
||||
assert_eq!(args.targets[0].addr, "127.0.0.1:2112");
|
||||
assert_eq!(args.pacing, GroupPacingArg::Staggered);
|
||||
assert_eq!(args.duration, DEFAULT_TUI_DURATION);
|
||||
assert!(args.is_continuous());
|
||||
assert_eq!(args.prepare().unwrap().client.duration, None);
|
||||
|
||||
let finite = parse(&["--duration", "30s", "127.0.0.1:2112"]).unwrap();
|
||||
assert_eq!(finite.duration, Duration::from_secs(30));
|
||||
assert_eq!(
|
||||
finite.prepare().unwrap().client.duration,
|
||||
Some(Duration::from_secs(30))
|
||||
);
|
||||
|
||||
assert!(parse(&["--output", "human", "127.0.0.1:2112"]).is_err());
|
||||
let help = TuiArgs::command().render_help().to_string();
|
||||
assert!(!help.contains("--output"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_positional_targets_parse() {
|
||||
let args = parse(&["host-a:2112", "host-b:2112"]).unwrap();
|
||||
let specs = args.prepare().unwrap().targets;
|
||||
|
||||
assert_eq!(specs[0].label, "host-a:2112");
|
||||
assert_eq!(specs[0].managed.server_addr, "host-a:2112");
|
||||
assert_eq!(specs[1].label, "host-b:2112");
|
||||
assert_eq!(specs[1].managed.server_addr, "host-b:2112");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_labeled_targets_parse() {
|
||||
let args = parse(&["ams=ams.example.com:2112", "sg=sg.example.com:2112"]).unwrap();
|
||||
let specs = args.prepare().unwrap().targets;
|
||||
|
||||
assert_eq!(specs[0].label, "ams");
|
||||
assert_eq!(specs[0].managed.server_addr, "ams.example.com:2112");
|
||||
assert_eq!(specs[1].label, "sg");
|
||||
assert_eq!(specs[1].managed.server_addr, "sg.example.com:2112");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn at_least_one_target_is_required() {
|
||||
// The TUI has no target-free mode, so this is rejected at parse time
|
||||
// rather than during preparation.
|
||||
assert!(parse(&[]).is_err());
|
||||
assert!(parse(&["ams=ams.example.com:2112"]).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_labels_are_rejected() {
|
||||
let args = parse(&["host-a:2112", "host-a:2112=host-b:2112"]).unwrap();
|
||||
let err = args.prepare().unwrap_err();
|
||||
|
||||
assert!(err.contains("duplicate target label"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_positional_target_strings_get_stable_suffixes() {
|
||||
let args = parse(&["host-a:2112", "host-a:2112"]).unwrap();
|
||||
let specs = args.prepare().unwrap().targets;
|
||||
|
||||
assert_eq!(specs[0].label, "host-a:2112");
|
||||
assert_eq!(specs[1].label, "host-a:2112#2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_target_endpoints_are_allowed() {
|
||||
let args = parse(&["127.0.0.1:2112", "127.0.0.1"]).unwrap();
|
||||
assert_eq!(args.prepare().unwrap().target_count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_labelled_target_syntax_is_rejected() {
|
||||
assert!(parse(&["=127.0.0.1:2112"]).is_err());
|
||||
assert!(parse(&["label="]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_target_option_is_rejected() {
|
||||
assert!(parse(&["--target", "eu=host.example"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pacing_option_accepts_supported_values() {
|
||||
assert_eq!(
|
||||
parse(&["--pacing", "staggered", "127.0.0.1:2112"])
|
||||
.unwrap()
|
||||
.pacing,
|
||||
GroupPacingArg::Staggered
|
||||
);
|
||||
assert_eq!(
|
||||
parse(&["--pacing", "burst", "127.0.0.1:2112"])
|
||||
.unwrap()
|
||||
.pacing,
|
||||
GroupPacingArg::Burst
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_client_options_match_tui_config_mapping() {
|
||||
let shared = [
|
||||
"--interval",
|
||||
"250ms",
|
||||
"--length",
|
||||
"128",
|
||||
"--hmac",
|
||||
"secret",
|
||||
"--clock",
|
||||
"monotonic",
|
||||
"--tstamp",
|
||||
"receive",
|
||||
"--stats",
|
||||
"count",
|
||||
"--sfill",
|
||||
"abc",
|
||||
"--dscp",
|
||||
"46",
|
||||
"--ttl",
|
||||
"64",
|
||||
"--loose",
|
||||
];
|
||||
let tui_args = [
|
||||
"--duration",
|
||||
"30s",
|
||||
"--interval",
|
||||
"250ms",
|
||||
"--length",
|
||||
"128",
|
||||
"--hmac",
|
||||
"secret",
|
||||
"--clock",
|
||||
"monotonic",
|
||||
"--tstamp",
|
||||
"receive",
|
||||
"--stats",
|
||||
"count",
|
||||
"--sfill",
|
||||
"abc",
|
||||
"--dscp",
|
||||
"46",
|
||||
"--ttl",
|
||||
"64",
|
||||
"--loose",
|
||||
"127.0.0.1:2112",
|
||||
];
|
||||
let tui = parse(&tui_args).unwrap().prepare().unwrap().client;
|
||||
let common = parse_shared(&shared).unwrap().common;
|
||||
let shared = common.to_client_config(Duration::from_secs(30));
|
||||
|
||||
assert_eq!(shared.duration, tui.duration);
|
||||
assert_eq!(shared.interval, tui.interval);
|
||||
assert_eq!(shared.length, tui.length);
|
||||
assert_eq!(shared.received_stats, tui.received_stats);
|
||||
assert_eq!(shared.stamp_at, tui.stamp_at);
|
||||
assert_eq!(shared.clock, tui.clock);
|
||||
assert_eq!(shared.dscp, tui.dscp);
|
||||
assert_eq!(shared.hmac_key, tui.hmac_key);
|
||||
assert_eq!(shared.server_fill, tui.server_fill);
|
||||
assert_eq!(shared.negotiation_policy, tui.negotiation_policy);
|
||||
assert_eq!(shared.socket_config.ttl, tui.socket_config.ttl);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tui_help_lists_multi_target_options() {
|
||||
let help = TuiArgs::command().render_help().to_string();
|
||||
assert!(!help.contains("--target "));
|
||||
assert!(help.contains("--pacing <PACING>"));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
pub mod args;
|
||||
pub mod run;
|
||||
mod ui;
|
||||
|
||||
pub use args::TuiArgs;
|
||||
pub use run::run_tui;
|
||||
@@ -1,303 +0,0 @@
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
io,
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use super::ui::{should_render, TuiConfig, TuiState, TuiStatus, TuiTerminal};
|
||||
use crate::{
|
||||
cmd::tui::args::TuiArgs,
|
||||
shared::client::{
|
||||
is_shutdown_requested,
|
||||
session::{
|
||||
drain_managed_events, peer_close_run_error, request_managed_stop_for_peer_close,
|
||||
request_managed_stop_once, ManagedDrainState,
|
||||
},
|
||||
},
|
||||
};
|
||||
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
|
||||
use irtt_client::managed::{
|
||||
BlockingManagedClient, ManagedEndReason, ManagedEvent, ManagedEventSubscription,
|
||||
ManagedEventTryRecvError, TargetInstance,
|
||||
};
|
||||
|
||||
const RENDER_INTERVAL: Duration = Duration::from_millis(250);
|
||||
const TUI_WAIT_SLICE: Duration = Duration::from_millis(20);
|
||||
const INPUT_EVENT_WORK_BUDGET: usize = 128;
|
||||
|
||||
pub fn run_tui(
|
||||
args: TuiArgs,
|
||||
shutdown_requested: &AtomicBool,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let setup = args
|
||||
.prepare()
|
||||
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
|
||||
let continuous = args.is_continuous();
|
||||
let mut terminal = TuiTerminal::enter()?;
|
||||
let mut state = TuiState::with_target_labels(
|
||||
TuiConfig::from_args(&args, &setup),
|
||||
setup.targets.iter().map(|target| target.label.clone()),
|
||||
);
|
||||
let mut next_render = Instant::now();
|
||||
if is_shutdown_requested(shutdown_requested) {
|
||||
return Ok(());
|
||||
}
|
||||
state.set_status(TuiStatus::Opening);
|
||||
render_if_due(&mut terminal, &state, &mut next_render, true)?;
|
||||
let (owner, mut events) = match BlockingManagedClient::start_with_subscription(
|
||||
setup.managed_config(),
|
||||
setup.managed_targets(),
|
||||
) {
|
||||
Ok(value) => value,
|
||||
Err(error) => {
|
||||
state.set_error(error.to_string());
|
||||
render_if_due(&mut terminal, &state, &mut next_render, true)?;
|
||||
return Err(Box::new(error));
|
||||
}
|
||||
};
|
||||
let handle = owner.handle();
|
||||
let mut interrupted = false;
|
||||
let mut stop_requested = false;
|
||||
let mut terminal_targets = HashSet::new();
|
||||
let mut dropped_events = 0;
|
||||
let mut subscription_closed = false;
|
||||
loop {
|
||||
if is_shutdown_requested(shutdown_requested) {
|
||||
interrupted = true;
|
||||
if request_managed_stop_once(&mut stop_requested) {
|
||||
drop(handle.stop());
|
||||
}
|
||||
}
|
||||
if handle_input(&mut state, shutdown_requested)? {
|
||||
render_if_due(&mut terminal, &state, &mut next_render, true)?;
|
||||
}
|
||||
if state.quit_requested {
|
||||
interrupted = true;
|
||||
if request_managed_stop_once(&mut stop_requested) {
|
||||
drop(handle.stop());
|
||||
}
|
||||
}
|
||||
if request_managed_stop_for_peer_close(
|
||||
continuous,
|
||||
interrupted,
|
||||
handle.status().peer_closed_target_outcomes,
|
||||
&mut stop_requested,
|
||||
) {
|
||||
drop(handle.stop());
|
||||
}
|
||||
let drain_state = drain_tui_events(
|
||||
&mut events,
|
||||
&mut state,
|
||||
&mut terminal_targets,
|
||||
&mut dropped_events,
|
||||
);
|
||||
match drain_state {
|
||||
ManagedDrainState::Empty => {
|
||||
thread::sleep(managed_tui_wait_duration(&next_render, state.paused));
|
||||
}
|
||||
ManagedDrainState::Closed => subscription_closed = true,
|
||||
ManagedDrainState::BudgetExhausted => {}
|
||||
}
|
||||
if handle.status().final_outcome.is_some() || subscription_closed {
|
||||
break;
|
||||
}
|
||||
render_if_due(&mut terminal, &state, &mut next_render, false)?;
|
||||
}
|
||||
if interrupted {
|
||||
state.set_status(TuiStatus::Interrupted);
|
||||
render_if_due(&mut terminal, &state, &mut next_render, true)?;
|
||||
}
|
||||
state.set_status(TuiStatus::Closing);
|
||||
render_if_due(&mut terminal, &state, &mut next_render, true)?;
|
||||
let outcome = owner.join()?;
|
||||
drain_final_tui_events(
|
||||
&mut events,
|
||||
&mut state,
|
||||
&mut terminal_targets,
|
||||
&mut dropped_events,
|
||||
);
|
||||
state.mark_dropped_managed_events(dropped_events);
|
||||
if outcome.discarded_target_outcomes != 0 {
|
||||
state.set_run_error(format!(
|
||||
"{} final target outcomes were discarded",
|
||||
outcome.discarded_target_outcomes
|
||||
));
|
||||
}
|
||||
for target in outcome.recent_target_outcomes.iter() {
|
||||
if terminal_targets.insert(target.target.clone()) {
|
||||
state.process_target_outcome(target);
|
||||
}
|
||||
}
|
||||
interrupted |= is_shutdown_requested(shutdown_requested);
|
||||
let error = match &outcome.end_reason {
|
||||
ManagedEndReason::DriverFailed(failure) => {
|
||||
Some(format!("managed driver failed: {failure}"))
|
||||
}
|
||||
_ => peer_close_run_error(continuous, interrupted, outcome.peer_closed_target_outcomes)
|
||||
.or_else(|| {
|
||||
(!interrupted
|
||||
&& outcome.successful_target_outcomes == 0
|
||||
&& outcome.failed_target_outcomes > 0)
|
||||
.then(|| {
|
||||
format!(
|
||||
"no managed target completed successfully ({} failed)",
|
||||
outcome.failed_target_outcomes
|
||||
)
|
||||
})
|
||||
}),
|
||||
};
|
||||
if let Some(error) = error {
|
||||
state.set_run_error(error.clone());
|
||||
render_if_due(&mut terminal, &state, &mut next_render, true)?;
|
||||
return Err(error.into());
|
||||
}
|
||||
state.set_status(TuiStatus::Complete);
|
||||
render_if_due(&mut terminal, &state, &mut next_render, true)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn process_tui_event(
|
||||
event: ManagedEvent,
|
||||
state: &mut TuiState,
|
||||
terminal_targets: &mut HashSet<TargetInstance>,
|
||||
) {
|
||||
match event {
|
||||
ManagedEvent::Client { target, event } => state.process_target_event(&target, &event),
|
||||
ManagedEvent::TargetFinished { outcome } => {
|
||||
terminal_targets.insert(outcome.target.clone());
|
||||
state.process_target_outcome(&outcome);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
fn drain_tui_events(
|
||||
events: &mut ManagedEventSubscription,
|
||||
state: &mut TuiState,
|
||||
terminal_targets: &mut HashSet<TargetInstance>,
|
||||
dropped_events: &mut u64,
|
||||
) -> ManagedDrainState {
|
||||
drain_managed_events(events, dropped_events, |event| {
|
||||
process_tui_event(event, state, terminal_targets);
|
||||
Ok::<(), std::convert::Infallible>(())
|
||||
})
|
||||
.expect("processing TUI managed events is infallible")
|
||||
}
|
||||
|
||||
fn drain_final_tui_events(
|
||||
events: &mut ManagedEventSubscription,
|
||||
state: &mut TuiState,
|
||||
terminal_targets: &mut HashSet<TargetInstance>,
|
||||
dropped_events: &mut u64,
|
||||
) {
|
||||
loop {
|
||||
match events.try_recv() {
|
||||
Ok(event) => process_tui_event(event, state, terminal_targets),
|
||||
Err(ManagedEventTryRecvError::Empty | ManagedEventTryRecvError::Closed) => break,
|
||||
Err(ManagedEventTryRecvError::Lagged(count)) => {
|
||||
*dropped_events = dropped_events.saturating_add(count);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn handle_input(state: &mut TuiState, shutdown_requested: &AtomicBool) -> io::Result<bool> {
|
||||
let mut force_render = false;
|
||||
for _ in 0..INPUT_EVENT_WORK_BUDGET {
|
||||
if !event::poll(Duration::ZERO)? {
|
||||
break;
|
||||
}
|
||||
let Event::Key(key) = event::read()? else {
|
||||
continue;
|
||||
};
|
||||
if key.kind == KeyEventKind::Release {
|
||||
continue;
|
||||
}
|
||||
match key.code {
|
||||
KeyCode::Char('q') | KeyCode::Char('c')
|
||||
if key.code == KeyCode::Char('q')
|
||||
|| key.modifiers.contains(KeyModifiers::CONTROL) =>
|
||||
{
|
||||
state.quit_requested = true;
|
||||
shutdown_requested.store(true, Ordering::Relaxed);
|
||||
force_render = true;
|
||||
break;
|
||||
}
|
||||
KeyCode::Char('r') => {
|
||||
state.clear_visible_history();
|
||||
force_render = true;
|
||||
}
|
||||
KeyCode::Char('p') => {
|
||||
state.toggle_pause();
|
||||
force_render = true;
|
||||
}
|
||||
KeyCode::Char('g') => {
|
||||
state.toggle_view();
|
||||
force_render = true;
|
||||
}
|
||||
KeyCode::Char('m') => {
|
||||
state.cycle_graph_metric();
|
||||
force_render = true;
|
||||
}
|
||||
KeyCode::Left => {
|
||||
state.pan_graph_left();
|
||||
force_render = true;
|
||||
}
|
||||
KeyCode::Right => {
|
||||
state.pan_graph_right();
|
||||
force_render = true;
|
||||
}
|
||||
KeyCode::PageUp => {
|
||||
state.pan_graph_page_left();
|
||||
force_render = true;
|
||||
}
|
||||
KeyCode::PageDown => {
|
||||
state.pan_graph_page_right();
|
||||
force_render = true;
|
||||
}
|
||||
KeyCode::Home => {
|
||||
state.jump_graph_oldest();
|
||||
force_render = true;
|
||||
}
|
||||
KeyCode::End => {
|
||||
state.jump_graph_live();
|
||||
force_render = true;
|
||||
}
|
||||
KeyCode::Char('+') | KeyCode::Char('=') => {
|
||||
state.zoom_graph_in();
|
||||
force_render = true;
|
||||
}
|
||||
KeyCode::Char('-') => {
|
||||
state.zoom_graph_out();
|
||||
force_render = true;
|
||||
}
|
||||
KeyCode::Char('0') => {
|
||||
state.reset_graph_window();
|
||||
force_render = true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(force_render)
|
||||
}
|
||||
fn render_if_due(
|
||||
terminal: &mut TuiTerminal,
|
||||
state: &TuiState,
|
||||
next_render: &mut Instant,
|
||||
force: bool,
|
||||
) -> io::Result<()> {
|
||||
let now = Instant::now();
|
||||
if should_render(now, *next_render, state.paused, force) {
|
||||
terminal.draw(state)?;
|
||||
*next_render = now + RENDER_INTERVAL;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn managed_tui_wait_duration(next_render: &Instant, paused: bool) -> Duration {
|
||||
let render_wait = if paused {
|
||||
TUI_WAIT_SLICE
|
||||
} else {
|
||||
next_render.saturating_duration_since(Instant::now())
|
||||
};
|
||||
render_wait.min(TUI_WAIT_SLICE)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,99 +0,0 @@
|
||||
use std::{
|
||||
env,
|
||||
ffi::OsString,
|
||||
process::ExitCode,
|
||||
sync::{atomic::AtomicBool, Arc},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
applet::{dispatch_from_argv, AppletDispatch, RequestedApplet},
|
||||
signal::install_signal_handler,
|
||||
};
|
||||
|
||||
pub fn main() -> ExitCode {
|
||||
match run_from_env() {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(err) => {
|
||||
eprintln!("irtt-rs: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_from_env() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let argv: Vec<OsString> = env::args_os().collect();
|
||||
let (requested, argv) = match dispatch_from_argv(argv)? {
|
||||
AppletDispatch::Run { applet, argv } => (applet, argv),
|
||||
AppletDispatch::Help(help) => {
|
||||
print!("{help}");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
let shutdown_requested = Arc::new(AtomicBool::new(false));
|
||||
install_signal_handler(Arc::clone(&shutdown_requested))
|
||||
.map_err(|err| format!("failed to install signal handler: {err}"))?;
|
||||
|
||||
match requested {
|
||||
RequestedApplet::Client => run_client_applet(argv, shutdown_requested.as_ref()),
|
||||
RequestedApplet::Tui => run_tui_applet(argv, shutdown_requested.as_ref()),
|
||||
RequestedApplet::Server => run_server_applet(argv, shutdown_requested.as_ref()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
fn run_client_applet(
|
||||
argv: Vec<OsString>,
|
||||
shutdown_requested: &AtomicBool,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
use clap::Parser;
|
||||
|
||||
let args = crate::cmd::client::ClientArgs::parse_from(argv);
|
||||
crate::cmd::client::run_stream(args, shutdown_requested)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "client"))]
|
||||
fn run_client_applet(
|
||||
_argv: Vec<OsString>,
|
||||
_shutdown_requested: &AtomicBool,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
Err("client applet is not available; rebuild with the client feature".into())
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
fn run_server_applet(
|
||||
argv: Vec<OsString>,
|
||||
shutdown_requested: &AtomicBool,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
use clap::Parser;
|
||||
|
||||
let args = crate::cmd::server::ServerArgs::parse_from(argv);
|
||||
crate::cmd::server::run_server(args, shutdown_requested)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "server"))]
|
||||
fn run_server_applet(
|
||||
_argv: Vec<OsString>,
|
||||
_shutdown_requested: &AtomicBool,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
Err("server applet is not available; rebuild with the server feature".into())
|
||||
}
|
||||
|
||||
#[cfg(feature = "tui")]
|
||||
fn run_tui_applet(
|
||||
argv: Vec<OsString>,
|
||||
shutdown_requested: &AtomicBool,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
use clap::Parser;
|
||||
|
||||
let args = crate::cmd::tui::TuiArgs::parse_from(argv);
|
||||
crate::cmd::tui::run_tui(args, shutdown_requested)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "tui"))]
|
||||
fn run_tui_applet(
|
||||
_argv: Vec<OsString>,
|
||||
_shutdown_requested: &AtomicBool,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
Err("TUI applet is not available; rebuild with the tui feature".into())
|
||||
}
|
||||
+1472
-6
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,479 @@
|
||||
use std::{
|
||||
io::{self, Write},
|
||||
process::ExitCode,
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use clap::Parser;
|
||||
use irtt_cli::{
|
||||
format_event, format_human_event_with_options, CliArgs, HumanOutputOptions, OutputMode,
|
||||
};
|
||||
use irtt_client::{Client, ClientEvent, OpenOutcome, RecvBudget};
|
||||
|
||||
#[cfg(test)]
|
||||
use irtt_client::ClientTimestamp;
|
||||
|
||||
#[cfg(feature = "stats")]
|
||||
use irtt_stats::{StatsCollector, StatsConfig};
|
||||
|
||||
const RECV_BUDGET: RecvBudget = RecvBudget { max_packets: 16 };
|
||||
const MAX_FINAL_DRAIN: Duration = Duration::from_secs(30);
|
||||
const IDLE_SLEEP: Duration = Duration::from_millis(5);
|
||||
const MAX_SLEEP: Duration = Duration::from_millis(20);
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args = CliArgs::parse();
|
||||
let shutdown_requested = Arc::new(AtomicBool::new(false));
|
||||
if let Err(err) = install_signal_handler(Arc::clone(&shutdown_requested)) {
|
||||
eprintln!("irtt-rs: failed to install signal handler: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
|
||||
match run(args, shutdown_requested.as_ref()) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(err) => {
|
||||
eprintln!("irtt-rs: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn install_signal_handler(shutdown_requested: Arc<AtomicBool>) -> Result<(), ctrlc::Error> {
|
||||
ctrlc::set_handler(move || {
|
||||
shutdown_requested.store(true, Ordering::Relaxed);
|
||||
})
|
||||
}
|
||||
|
||||
fn run(args: CliArgs, shutdown_requested: &AtomicBool) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mode = args.output;
|
||||
let continuous = args.is_continuous();
|
||||
let mut stdout = io::LineWriter::new(io::stdout().lock());
|
||||
#[cfg(feature = "stats")]
|
||||
let mut stats = StatsCollector::new(stats_config(continuous));
|
||||
let mut output = EventOutput {
|
||||
mode,
|
||||
human_options: HumanOutputOptions {
|
||||
verbose: args.verbose,
|
||||
},
|
||||
print_finite_summary: !continuous,
|
||||
out: &mut stdout,
|
||||
#[cfg(feature = "stats")]
|
||||
stats: &mut stats,
|
||||
};
|
||||
|
||||
if is_shutdown_requested(shutdown_requested) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut client = Client::connect(args.to_client_config())?;
|
||||
|
||||
if is_shutdown_requested(shutdown_requested) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let open = client.open()?;
|
||||
output.print_event(open_event(&open))?;
|
||||
|
||||
let mut interrupted = false;
|
||||
while should_continue_run(continuous, client.next_send_deadline(), shutdown_requested) {
|
||||
if should_send_probe(client.next_send_deadline(), shutdown_requested) {
|
||||
let events = client.send_probe()?;
|
||||
output.print_events(&events)?;
|
||||
}
|
||||
|
||||
let events = client.recv_available(RECV_BUDGET)?;
|
||||
output.print_events(&events)?;
|
||||
|
||||
let events = client.poll_timeouts()?;
|
||||
output.print_events(&events)?;
|
||||
|
||||
if is_shutdown_requested(shutdown_requested) {
|
||||
interrupted = true;
|
||||
break;
|
||||
}
|
||||
|
||||
sleep_until_next_send(client.next_send_deadline());
|
||||
}
|
||||
interrupted |= is_shutdown_requested(shutdown_requested);
|
||||
|
||||
if interrupted {
|
||||
eprintln!("interrupted, closing session...");
|
||||
}
|
||||
|
||||
if should_drain_final(continuous, interrupted) {
|
||||
drain_final_replies(&mut client, &mut output)?;
|
||||
}
|
||||
|
||||
let events = client.poll_timeouts()?;
|
||||
output.print_events(&events)?;
|
||||
|
||||
let events = client.close()?;
|
||||
output.print_events(&events)?;
|
||||
output.print_summary()?;
|
||||
output.out.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_shutdown_requested(shutdown_requested: &AtomicBool) -> bool {
|
||||
shutdown_requested.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn should_continue_run(
|
||||
continuous: bool,
|
||||
next_send_deadline: Option<Instant>,
|
||||
shutdown_requested: &AtomicBool,
|
||||
) -> bool {
|
||||
!is_shutdown_requested(shutdown_requested) && (continuous || next_send_deadline.is_some())
|
||||
}
|
||||
|
||||
fn should_send_probe(next_send_deadline: Option<Instant>, shutdown_requested: &AtomicBool) -> bool {
|
||||
!is_shutdown_requested(shutdown_requested)
|
||||
&& next_send_deadline.is_some_and(|deadline| deadline <= Instant::now())
|
||||
}
|
||||
|
||||
fn should_drain_final(continuous: bool, interrupted: bool) -> bool {
|
||||
!continuous || interrupted
|
||||
}
|
||||
|
||||
fn open_event(outcome: &OpenOutcome) -> &ClientEvent {
|
||||
match outcome {
|
||||
OpenOutcome::Started { event, .. } | OpenOutcome::NoTestCompleted { event, .. } => event,
|
||||
}
|
||||
}
|
||||
|
||||
fn drain_final_replies<W: Write>(
|
||||
client: &mut Client,
|
||||
output: &mut EventOutput<'_, W>,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let deadline = Instant::now() + final_drain_duration(client.probe_timeout());
|
||||
loop {
|
||||
let mut printed = false;
|
||||
|
||||
let events = client.recv_available(RECV_BUDGET)?;
|
||||
printed |= !events.is_empty();
|
||||
output.print_events(&events)?;
|
||||
|
||||
let events = client.poll_timeouts()?;
|
||||
printed |= !events.is_empty();
|
||||
output.print_events(&events)?;
|
||||
|
||||
if client.is_run_complete() || Instant::now() >= deadline {
|
||||
break;
|
||||
}
|
||||
|
||||
if !printed {
|
||||
thread::sleep(IDLE_SLEEP);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sleep_until_next_send(deadline: Option<Instant>) {
|
||||
let sleep_for = match deadline {
|
||||
Some(deadline) => deadline
|
||||
.saturating_duration_since(Instant::now())
|
||||
.min(MAX_SLEEP),
|
||||
None => Duration::from_millis(1),
|
||||
};
|
||||
if !sleep_for.is_zero() {
|
||||
thread::sleep(sleep_for);
|
||||
}
|
||||
}
|
||||
|
||||
struct EventOutput<'a, W: Write> {
|
||||
mode: irtt_cli::OutputMode,
|
||||
human_options: HumanOutputOptions,
|
||||
print_finite_summary: bool,
|
||||
out: &'a mut W,
|
||||
#[cfg(feature = "stats")]
|
||||
stats: &'a mut StatsCollector,
|
||||
}
|
||||
|
||||
impl<W: Write> EventOutput<'_, W> {
|
||||
fn print_events(&mut self, events: &[ClientEvent]) -> io::Result<()> {
|
||||
for event in events {
|
||||
self.print_event(event)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_event(&mut self, event: &ClientEvent) -> io::Result<()> {
|
||||
#[cfg(feature = "stats")]
|
||||
let stats_update = self.stats.process(event);
|
||||
|
||||
#[cfg(not(feature = "stats"))]
|
||||
let stats_update = irtt_cli::HumanEventStats::default();
|
||||
|
||||
let line =
|
||||
if self.mode == OutputMode::Human && !matches!(event, ClientEvent::EchoSent { .. }) {
|
||||
Some(format_human_event_with_options(
|
||||
event,
|
||||
Some(stats_update.into()),
|
||||
self.human_options,
|
||||
))
|
||||
} else {
|
||||
format_event(event, self.mode)
|
||||
};
|
||||
|
||||
if let Some(line) = line {
|
||||
writeln!(self.out, "{line}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_summary(&mut self) -> io::Result<()> {
|
||||
if !self.print_finite_summary || !self.mode.prints_summary() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
#[cfg(feature = "stats")]
|
||||
{
|
||||
write!(
|
||||
self.out,
|
||||
"{}",
|
||||
irtt_cli::summary::format_summary_with_options(
|
||||
&self.stats.snapshot(),
|
||||
irtt_cli::summary::SummaryFormatOptions {
|
||||
verbose: self.human_options.verbose,
|
||||
},
|
||||
)
|
||||
)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "stats")]
|
||||
fn stats_config(continuous: bool) -> StatsConfig {
|
||||
if continuous {
|
||||
StatsConfig::continuous()
|
||||
} else {
|
||||
StatsConfig::finite()
|
||||
}
|
||||
}
|
||||
|
||||
fn final_drain_duration(probe_timeout: Duration) -> Duration {
|
||||
probe_timeout.min(MAX_FINAL_DRAIN)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shutdown_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shutdown_flag_stops_run_loop() {
|
||||
let shutdown = AtomicBool::new(false);
|
||||
assert!(should_continue_run(true, Some(Instant::now()), &shutdown));
|
||||
|
||||
shutdown.store(true, Ordering::Relaxed);
|
||||
assert!(!should_continue_run(true, Some(Instant::now()), &shutdown));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shutdown_flag_suppresses_due_probe_send() {
|
||||
let shutdown = AtomicBool::new(false);
|
||||
let due = Instant::now() - Duration::from_millis(1);
|
||||
assert!(should_send_probe(Some(due), &shutdown));
|
||||
|
||||
shutdown.store(true, Ordering::Relaxed);
|
||||
assert!(!should_send_probe(Some(due), &shutdown));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interrupted_continuous_run_uses_final_drain_before_close() {
|
||||
assert!(should_drain_final(true, true));
|
||||
assert!(!should_drain_final(true, false));
|
||||
assert!(should_drain_final(false, false));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "stats"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use irtt_client::{PacketMeta, RttSample, SignedDuration};
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr, SocketAddr},
|
||||
time::UNIX_EPOCH,
|
||||
};
|
||||
|
||||
fn test_timestamp(offset: Duration) -> ClientTimestamp {
|
||||
ClientTimestamp {
|
||||
wall: UNIX_EPOCH + offset,
|
||||
mono: Instant::now() + offset,
|
||||
}
|
||||
}
|
||||
|
||||
fn test_remote() -> SocketAddr {
|
||||
SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 2112)
|
||||
}
|
||||
|
||||
fn reply_event(seq: u32, rtt_us: u64) -> ClientEvent {
|
||||
let sent_at = test_timestamp(Duration::from_millis(seq as u64));
|
||||
let received_at = ClientTimestamp {
|
||||
wall: sent_at.wall + Duration::from_micros(rtt_us),
|
||||
mono: sent_at.mono + Duration::from_micros(rtt_us),
|
||||
};
|
||||
ClientEvent::EchoReply {
|
||||
seq,
|
||||
remote: test_remote(),
|
||||
sent_at,
|
||||
received_at,
|
||||
rtt: RttSample {
|
||||
raw: Duration::from_micros(rtt_us),
|
||||
adjusted: None,
|
||||
effective: Duration::from_micros(rtt_us),
|
||||
adjusted_signed: None,
|
||||
effective_signed: SignedDuration {
|
||||
ns: i128::from(rtt_us) * 1_000,
|
||||
},
|
||||
},
|
||||
server_timing: None,
|
||||
one_way: None,
|
||||
received_stats: None,
|
||||
bytes: 64,
|
||||
packet_meta: PacketMeta::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_helper_streams_and_collects_events() {
|
||||
let sent_at = test_timestamp(Duration::from_secs(1));
|
||||
let received_at = test_timestamp(Duration::from_secs(1) + Duration::from_micros(1200));
|
||||
let events = [
|
||||
ClientEvent::EchoSent {
|
||||
seq: 1,
|
||||
remote: test_remote(),
|
||||
scheduled_at: sent_at.mono,
|
||||
sent_at,
|
||||
bytes: 64,
|
||||
send_call: Duration::from_micros(10),
|
||||
timer_error: Duration::ZERO,
|
||||
},
|
||||
ClientEvent::EchoReply {
|
||||
seq: 1,
|
||||
remote: test_remote(),
|
||||
sent_at,
|
||||
received_at,
|
||||
rtt: RttSample {
|
||||
raw: Duration::from_micros(1200),
|
||||
adjusted: None,
|
||||
effective: Duration::from_micros(1200),
|
||||
adjusted_signed: None,
|
||||
effective_signed: SignedDuration { ns: 1_200_000 },
|
||||
},
|
||||
server_timing: None,
|
||||
one_way: None,
|
||||
received_stats: None,
|
||||
bytes: 64,
|
||||
packet_meta: PacketMeta::default(),
|
||||
},
|
||||
];
|
||||
|
||||
let mut stats = StatsCollector::new(StatsConfig::finite());
|
||||
let mut out = Vec::new();
|
||||
{
|
||||
let mut output = EventOutput {
|
||||
mode: irtt_cli::OutputMode::RttUs,
|
||||
human_options: HumanOutputOptions::default(),
|
||||
print_finite_summary: true,
|
||||
out: &mut out,
|
||||
stats: &mut stats,
|
||||
};
|
||||
output.print_events(&events).unwrap();
|
||||
output.print_summary().unwrap();
|
||||
}
|
||||
|
||||
let rendered = String::from_utf8(out).unwrap();
|
||||
let summary = stats.snapshot();
|
||||
assert_eq!(rendered, "1200\n");
|
||||
assert_eq!(summary.packets.packets_sent, 1);
|
||||
assert_eq!(summary.packets.unique_replies, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn continuous_output_does_not_print_finite_summary() {
|
||||
let mut stats = StatsCollector::new(StatsConfig::continuous());
|
||||
let mut out = Vec::new();
|
||||
{
|
||||
let mut output = EventOutput {
|
||||
mode: irtt_cli::OutputMode::Human,
|
||||
human_options: HumanOutputOptions::default(),
|
||||
print_finite_summary: false,
|
||||
out: &mut out,
|
||||
stats: &mut stats,
|
||||
};
|
||||
output.print_summary().unwrap();
|
||||
}
|
||||
|
||||
assert!(out.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn human_output_prints_ipdv_from_stats_update() {
|
||||
let events = [reply_event(0, 1200), reply_event(1, 1250)];
|
||||
let mut stats = StatsCollector::new(StatsConfig::finite());
|
||||
let mut out = Vec::new();
|
||||
{
|
||||
let mut output = EventOutput {
|
||||
mode: irtt_cli::OutputMode::Human,
|
||||
human_options: HumanOutputOptions::default(),
|
||||
print_finite_summary: false,
|
||||
out: &mut out,
|
||||
stats: &mut stats,
|
||||
};
|
||||
output.print_events(&events).unwrap();
|
||||
}
|
||||
|
||||
let rendered = String::from_utf8(out).unwrap();
|
||||
let mut lines = rendered.lines();
|
||||
assert!(lines.next().unwrap().contains("ipdv=n/a"));
|
||||
assert!(lines.next().unwrap().contains("ipdv=50.0µs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn continuous_mode_uses_continuous_stats_config() {
|
||||
let mut collector = StatsCollector::new(stats_config(true));
|
||||
for seq in 0..5000_u32 {
|
||||
let sent_at = test_timestamp(Duration::from_micros(seq as u64));
|
||||
let received_at = test_timestamp(Duration::from_micros(seq as u64 + 1));
|
||||
collector.process(&ClientEvent::EchoReply {
|
||||
seq,
|
||||
remote: test_remote(),
|
||||
sent_at,
|
||||
received_at,
|
||||
rtt: RttSample {
|
||||
raw: Duration::from_micros(1),
|
||||
adjusted: None,
|
||||
effective: Duration::from_micros(1),
|
||||
adjusted_signed: None,
|
||||
effective_signed: SignedDuration { ns: 1_000 },
|
||||
},
|
||||
server_timing: None,
|
||||
one_way: None,
|
||||
received_stats: None,
|
||||
bytes: 64,
|
||||
packet_meta: PacketMeta::default(),
|
||||
});
|
||||
}
|
||||
|
||||
assert_eq!(collector.snapshot().rtt.primary.median_ns, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn final_drain_uses_capped_probe_timeout() {
|
||||
assert_eq!(
|
||||
final_drain_duration(Duration::from_secs(4)),
|
||||
Duration::from_secs(4)
|
||||
);
|
||||
assert_eq!(
|
||||
final_drain_duration(Duration::from_secs(60)),
|
||||
Duration::from_secs(30)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,223 +0,0 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::ValueEnum;
|
||||
use irtt_client::{MAX_DSCP_CODEPOINT, MAX_SERVER_FILL_BYTES, MAX_TTL, MAX_UDP_PAYLOAD_LENGTH};
|
||||
use irtt_proto::{Clock, ReceivedStats, StampAt};
|
||||
|
||||
#[derive(Debug, Clone, clap::Args)]
|
||||
pub struct CommonClientArgs {
|
||||
/// Probe interval.
|
||||
#[arg(long, default_value = "1s", value_parser = parse_duration)]
|
||||
pub interval: Duration,
|
||||
|
||||
/// UDP payload length.
|
||||
#[arg(long, default_value_t = 0, value_parser = parse_length)]
|
||||
pub length: u32,
|
||||
|
||||
/// HMAC key.
|
||||
#[arg(long)]
|
||||
pub hmac: Option<String>,
|
||||
|
||||
/// Clock mode to request.
|
||||
#[arg(long, value_enum, default_value_t = ClockArg::Both)]
|
||||
pub clock: ClockArg,
|
||||
|
||||
/// Timestamp mode to request.
|
||||
#[arg(
|
||||
long = "tstamp",
|
||||
visible_alias = "timestamps",
|
||||
value_enum,
|
||||
value_name = "MODE",
|
||||
default_value_t = TimestampArg::Both
|
||||
)]
|
||||
pub tstamp: TimestampArg,
|
||||
|
||||
/// Received-stats mode to request.
|
||||
#[arg(
|
||||
long = "stats",
|
||||
value_enum,
|
||||
default_value_t = ReceivedStatsArg::Both,
|
||||
help = "Server received-stats negotiation mode"
|
||||
)]
|
||||
pub stats: ReceivedStatsArg,
|
||||
|
||||
/// Server payload fill string to request, up to 32 bytes.
|
||||
#[arg(
|
||||
long = "sfill",
|
||||
visible_alias = "server-fill",
|
||||
value_name = "STRING",
|
||||
value_parser = parse_server_fill
|
||||
)]
|
||||
pub server_fill: Option<String>,
|
||||
|
||||
/// DSCP codepoint to request; this is not a raw TOS or Traffic Class byte.
|
||||
#[arg(long, default_value_t = 0, value_name = "0..=63", value_parser = parse_dscp)]
|
||||
pub dscp: u8,
|
||||
|
||||
/// Local outgoing IPv4 TTL or IPv6 unicast hop limit; not negotiated.
|
||||
#[arg(long, value_name = "1..=255", value_parser = parse_ttl)]
|
||||
pub ttl: Option<u32>,
|
||||
|
||||
/// Accept safe server restrictions during negotiation.
|
||||
#[arg(long)]
|
||||
pub loose: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
|
||||
pub enum ClockArg {
|
||||
Wall,
|
||||
Monotonic,
|
||||
Both,
|
||||
}
|
||||
|
||||
impl From<ClockArg> for Clock {
|
||||
fn from(value: ClockArg) -> Self {
|
||||
match value {
|
||||
ClockArg::Wall => Self::Wall,
|
||||
ClockArg::Monotonic => Self::Monotonic,
|
||||
ClockArg::Both => Self::Both,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
|
||||
pub enum TimestampArg {
|
||||
None,
|
||||
Send,
|
||||
Receive,
|
||||
Both,
|
||||
Midpoint,
|
||||
}
|
||||
|
||||
impl From<TimestampArg> for StampAt {
|
||||
fn from(value: TimestampArg) -> Self {
|
||||
match value {
|
||||
TimestampArg::None => Self::None,
|
||||
TimestampArg::Send => Self::Send,
|
||||
TimestampArg::Receive => Self::Receive,
|
||||
TimestampArg::Both => Self::Both,
|
||||
TimestampArg::Midpoint => Self::Midpoint,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
|
||||
pub enum ReceivedStatsArg {
|
||||
None,
|
||||
Count,
|
||||
Window,
|
||||
Both,
|
||||
}
|
||||
|
||||
impl From<ReceivedStatsArg> for ReceivedStats {
|
||||
fn from(value: ReceivedStatsArg) -> Self {
|
||||
match value {
|
||||
ReceivedStatsArg::None => Self::None,
|
||||
ReceivedStatsArg::Count => Self::Count,
|
||||
ReceivedStatsArg::Window => Self::Window,
|
||||
ReceivedStatsArg::Both => Self::Both,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_duration(input: &str) -> Result<Duration, String> {
|
||||
let (number, unit) = split_duration(input)?;
|
||||
let value: u64 = number
|
||||
.parse()
|
||||
.map_err(|_| format!("invalid duration value {input:?}"))?;
|
||||
if value == 0 {
|
||||
return Err("duration must be greater than zero".to_owned());
|
||||
}
|
||||
match unit {
|
||||
"ms" => Ok(Duration::from_millis(value)),
|
||||
"s" => Ok(Duration::from_secs(value)),
|
||||
"m" => value
|
||||
.checked_mul(60)
|
||||
.map(Duration::from_secs)
|
||||
.ok_or_else(|| "duration is too large".to_owned()),
|
||||
_ => Err(format!(
|
||||
"unsupported duration unit {unit:?}; use ms, s, or m"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_test_duration(input: &str) -> Result<Duration, String> {
|
||||
if input == "0" {
|
||||
return Ok(Duration::ZERO);
|
||||
}
|
||||
let (number, unit) = split_duration(input)?;
|
||||
let value: u64 = number
|
||||
.parse()
|
||||
.map_err(|_| format!("invalid duration value {input:?}"))?;
|
||||
if value == 0 {
|
||||
return Ok(Duration::ZERO);
|
||||
}
|
||||
match unit {
|
||||
"ms" => Ok(Duration::from_millis(value)),
|
||||
"s" => Ok(Duration::from_secs(value)),
|
||||
"m" => value
|
||||
.checked_mul(60)
|
||||
.map(Duration::from_secs)
|
||||
.ok_or_else(|| "duration is too large".to_owned()),
|
||||
_ => Err(format!(
|
||||
"unsupported duration unit {unit:?}; use ms, s, or m"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn split_duration(input: &str) -> Result<(&str, &str), String> {
|
||||
let split = input
|
||||
.find(|ch: char| !ch.is_ascii_digit())
|
||||
.ok_or_else(|| "duration must include a unit: ms, s, or m".to_owned())?;
|
||||
let (number, unit) = input.split_at(split);
|
||||
if number.is_empty() || unit.is_empty() {
|
||||
return Err("duration must include a positive value and unit".to_owned());
|
||||
}
|
||||
if number.starts_with('-') {
|
||||
return Err("duration must be greater than zero".to_owned());
|
||||
}
|
||||
Ok((number, unit))
|
||||
}
|
||||
|
||||
pub fn parse_length(input: &str) -> Result<u32, String> {
|
||||
let length: u32 = input
|
||||
.parse()
|
||||
.map_err(|_| format!("invalid packet length {input:?}"))?;
|
||||
if length > MAX_UDP_PAYLOAD_LENGTH {
|
||||
return Err(format!("packet length must be <= {MAX_UDP_PAYLOAD_LENGTH}"));
|
||||
}
|
||||
Ok(length)
|
||||
}
|
||||
|
||||
pub fn parse_server_fill(input: &str) -> Result<String, String> {
|
||||
if input.is_empty() {
|
||||
return Err("server fill must not be empty".to_owned());
|
||||
}
|
||||
let len = input.len();
|
||||
if len > MAX_SERVER_FILL_BYTES {
|
||||
return Err(format!(
|
||||
"server fill must be <= {MAX_SERVER_FILL_BYTES} bytes, got {len}"
|
||||
));
|
||||
}
|
||||
Ok(input.to_owned())
|
||||
}
|
||||
|
||||
pub fn parse_dscp(input: &str) -> Result<u8, String> {
|
||||
let value: u8 = input
|
||||
.parse()
|
||||
.map_err(|_| format!("invalid DSCP codepoint {input:?}"))?;
|
||||
if value > MAX_DSCP_CODEPOINT {
|
||||
return Err(format!("DSCP codepoint must be <= {MAX_DSCP_CODEPOINT}"));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub fn parse_ttl(input: &str) -> Result<u32, String> {
|
||||
let value: u32 = input
|
||||
.parse()
|
||||
.map_err(|_| format!("invalid TTL/hop limit {input:?}"))?;
|
||||
if value == 0 || value > MAX_TTL {
|
||||
return Err(format!("TTL/hop limit must be in range 1..={MAX_TTL}"));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use irtt_client::{ClientConfig, NegotiationPolicy, SocketConfig};
|
||||
|
||||
use super::args::CommonClientArgs;
|
||||
|
||||
pub const DEFAULT_RECV_TIMEOUT: Duration = Duration::from_millis(20);
|
||||
|
||||
impl CommonClientArgs {
|
||||
/// Build the shared client configuration template for a managed run.
|
||||
///
|
||||
/// The template carries no server address: the managed driver replaces it
|
||||
/// per target from that target's configuration, so deriving one here from
|
||||
/// an arbitrary target would be dead data.
|
||||
pub fn to_client_config(&self, duration: Duration) -> ClientConfig {
|
||||
ClientConfig {
|
||||
duration: (!duration.is_zero()).then_some(duration),
|
||||
interval: self.interval,
|
||||
length: self.length,
|
||||
received_stats: self.stats.into(),
|
||||
stamp_at: self.tstamp.into(),
|
||||
clock: self.clock.into(),
|
||||
dscp: self.dscp,
|
||||
hmac_key: self.hmac.as_ref().map(|key| key.as_bytes().to_vec()),
|
||||
server_fill: self.server_fill.clone(),
|
||||
negotiation_policy: if self.loose {
|
||||
NegotiationPolicy::Loose
|
||||
} else {
|
||||
NegotiationPolicy::Strict
|
||||
},
|
||||
socket_config: SocketConfig {
|
||||
ttl: self.ttl,
|
||||
recv_timeout: Some(DEFAULT_RECV_TIMEOUT),
|
||||
..SocketConfig::default()
|
||||
},
|
||||
..ClientConfig::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn expected_probe_count(duration: Duration, interval: Duration) -> u64 {
|
||||
let interval_nanos = interval.as_nanos();
|
||||
if interval_nanos == 0 {
|
||||
return u64::MAX;
|
||||
}
|
||||
|
||||
let expected = duration
|
||||
.as_nanos()
|
||||
.saturating_add(interval_nanos.saturating_sub(1))
|
||||
/ interval_nanos;
|
||||
expected.min(u128::from(u64::MAX)) as u64
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
pub mod args;
|
||||
pub mod config;
|
||||
pub mod prepare;
|
||||
pub mod session;
|
||||
pub mod targets;
|
||||
|
||||
pub use args::{
|
||||
parse_dscp, parse_duration, parse_length, parse_server_fill, parse_test_duration, parse_ttl,
|
||||
ClockArg, CommonClientArgs, ReceivedStatsArg, TimestampArg,
|
||||
};
|
||||
pub use config::{expected_probe_count, DEFAULT_RECV_TIMEOUT};
|
||||
pub use prepare::{prepare_managed_run, ManagedRunSetup, TargetSelection, MANAGED_EVENT_CAPACITY};
|
||||
pub use session::is_shutdown_requested;
|
||||
pub use targets::{
|
||||
parse_target, prepare_managed_targets, target_specs, GroupPacingArg, PreparedTarget, TargetArg,
|
||||
TargetSpec,
|
||||
};
|
||||
@@ -1,251 +0,0 @@
|
||||
//! One preparation step from parsed arguments to a runnable managed setup.
|
||||
//!
|
||||
//! Both client applets accept the same target and pacing arguments and then
|
||||
//! have to turn them into the same three things: a validated target set, one
|
||||
//! shared [`ClientConfig`] template, and a [`ManagedPacing`]. Doing that
|
||||
//! separately in each applet is how the CLI ended up deriving its client
|
||||
//! configuration from an arbitrary "primary" target whose address the managed
|
||||
//! driver immediately replaced per target.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use irtt_client::{
|
||||
managed::{ManagedClientConfig, ManagedCompletionPolicy, ManagedPacing},
|
||||
ClientConfig,
|
||||
};
|
||||
|
||||
use super::{
|
||||
args::CommonClientArgs,
|
||||
targets::{prepare_managed_targets, target_specs, GroupPacingArg, TargetArg},
|
||||
PreparedTarget,
|
||||
};
|
||||
|
||||
/// Capacity of the lossy managed presentation event channel.
|
||||
pub const MANAGED_EVENT_CAPACITY: usize = 16_384;
|
||||
|
||||
/// Target and pacing arguments common to the client applets.
|
||||
///
|
||||
/// Duration is deliberately absent: the applets disagree about what a duration
|
||||
/// means and what its default is, so each keeps its own.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct TargetSelection<'a> {
|
||||
pub targets: &'a [TargetArg],
|
||||
pub pacing: GroupPacingArg,
|
||||
}
|
||||
|
||||
/// Everything a managed run needs, prepared and validated together.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ManagedRunSetup {
|
||||
/// Validated targets, in the order the user gave them.
|
||||
pub targets: Vec<PreparedTarget>,
|
||||
/// Shared client configuration template.
|
||||
///
|
||||
/// The managed driver supplies each target's address and authentication
|
||||
/// from its [`ManagedTargetConfig`](irtt_client::managed::ManagedTargetConfig),
|
||||
/// so this template carries no target of its own.
|
||||
pub client: ClientConfig,
|
||||
/// Send coordination across active targets.
|
||||
pub pacing: ManagedPacing,
|
||||
}
|
||||
|
||||
impl ManagedRunSetup {
|
||||
/// Number of validated targets.
|
||||
pub fn target_count(&self) -> usize {
|
||||
self.targets.len()
|
||||
}
|
||||
|
||||
/// Whether this run drives more than one target.
|
||||
pub fn is_multi_target(&self) -> bool {
|
||||
self.targets.len() > 1
|
||||
}
|
||||
|
||||
/// Managed target configurations, in argument order.
|
||||
pub fn managed_targets(&self) -> Vec<irtt_client::managed::ManagedTargetConfig> {
|
||||
self.targets
|
||||
.iter()
|
||||
.map(|target| target.managed.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Managed driver configuration for this run.
|
||||
pub fn managed_config(&self) -> ManagedClientConfig {
|
||||
let target_count = self.target_count();
|
||||
ManagedClientConfig {
|
||||
client: self.client.clone(),
|
||||
pacing: self.pacing,
|
||||
completion: ManagedCompletionPolicy::FinishWhenQuiescent,
|
||||
event_capacity: MANAGED_EVENT_CAPACITY,
|
||||
outcome_history_limit: target_count,
|
||||
max_live_target_generations: target_count,
|
||||
..ManagedClientConfig::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate the selected targets and build the shared run setup.
|
||||
///
|
||||
/// Targets are validated before any configuration is built, so a bad target set
|
||||
/// fails before the caller can act on a half-prepared run.
|
||||
pub fn prepare_managed_run(
|
||||
common: &CommonClientArgs,
|
||||
duration: Duration,
|
||||
selection: TargetSelection<'_>,
|
||||
) -> Result<ManagedRunSetup, String> {
|
||||
let specs = target_specs(selection.targets)?;
|
||||
let targets = prepare_managed_targets(specs)?;
|
||||
Ok(ManagedRunSetup {
|
||||
targets,
|
||||
client: common.to_client_config(duration),
|
||||
pacing: selection.pacing.into(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use clap::Parser;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Parser)]
|
||||
struct CommonOnlyArgs {
|
||||
#[command(flatten)]
|
||||
common: CommonClientArgs,
|
||||
}
|
||||
|
||||
fn common(args: &[&str]) -> CommonClientArgs {
|
||||
let mut argv = vec!["common-only"];
|
||||
argv.extend_from_slice(args);
|
||||
CommonOnlyArgs::try_parse_from(argv).unwrap().common
|
||||
}
|
||||
|
||||
fn unlabeled(addr: &str) -> TargetArg {
|
||||
TargetArg {
|
||||
label: None,
|
||||
addr: addr.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn labeled(label: &str, addr: &str) -> TargetArg {
|
||||
TargetArg {
|
||||
label: Some(label.to_owned()),
|
||||
addr: addr.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare(
|
||||
targets: &[TargetArg],
|
||||
pacing: GroupPacingArg,
|
||||
duration: Duration,
|
||||
) -> Result<ManagedRunSetup, String> {
|
||||
prepare_managed_run(&common(&[]), duration, TargetSelection { targets, pacing })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_target_prepares_one_managed_target_and_a_finite_duration() {
|
||||
let setup = prepare(
|
||||
&[unlabeled("127.0.0.1:2112")],
|
||||
GroupPacingArg::Staggered,
|
||||
Duration::from_secs(30),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(setup.target_count(), 1);
|
||||
assert!(!setup.is_multi_target());
|
||||
assert_eq!(setup.targets[0].label, "127.0.0.1:2112");
|
||||
assert_eq!(setup.targets[0].managed.server_addr, "127.0.0.1:2112");
|
||||
assert_eq!(setup.client.duration, Some(Duration::from_secs(30)));
|
||||
assert_eq!(setup.pacing, ManagedPacing::Staggered);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_duration_prepares_a_continuous_client_config() {
|
||||
let setup = prepare(
|
||||
&[unlabeled("127.0.0.1:2112")],
|
||||
GroupPacingArg::Staggered,
|
||||
Duration::ZERO,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(setup.client.duration, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_targets_keep_argument_order_and_share_one_client_config() {
|
||||
let setup = prepare(
|
||||
&[
|
||||
unlabeled("host-a:2112"),
|
||||
unlabeled("host-b:2112"),
|
||||
labeled("sg", "sg.example.test:2112"),
|
||||
],
|
||||
GroupPacingArg::Burst,
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(setup.is_multi_target());
|
||||
let labels: Vec<_> = setup
|
||||
.targets
|
||||
.iter()
|
||||
.map(|target| target.label.as_str())
|
||||
.collect();
|
||||
assert_eq!(labels, ["host-a:2112", "host-b:2112", "sg"]);
|
||||
assert_eq!(setup.targets[2].managed.server_addr, "sg.example.test:2112");
|
||||
assert_eq!(setup.pacing, ManagedPacing::Burst);
|
||||
|
||||
let config = setup.managed_config();
|
||||
assert_eq!(config.outcome_history_limit, 3);
|
||||
assert_eq!(config.max_live_target_generations, 3);
|
||||
assert_eq!(config.event_capacity, MANAGED_EVENT_CAPACITY);
|
||||
assert_eq!(config.pacing, ManagedPacing::Burst);
|
||||
assert_eq!(config.client, setup.client);
|
||||
assert_eq!(setup.managed_targets().len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_shared_client_config_carries_no_target_of_its_own() {
|
||||
// The managed driver replaces the address, and the CLI's key, per
|
||||
// target, so the template must not pin either to one target.
|
||||
let targets = vec![unlabeled("host-a:2112"), unlabeled("host-b:2112")];
|
||||
let setup = prepare_managed_run(
|
||||
&common(&["--hmac", "secret"]),
|
||||
Duration::from_secs(10),
|
||||
TargetSelection {
|
||||
targets: &targets,
|
||||
pacing: GroupPacingArg::Staggered,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
setup.client.server_addr,
|
||||
ClientConfig::default().server_addr
|
||||
);
|
||||
assert_eq!(setup.client.hmac_key, Some(b"secret".to_vec()));
|
||||
// Per-target authentication is not exposed on the command line, so no
|
||||
// target carries an override of the shared key.
|
||||
assert!(setup
|
||||
.targets
|
||||
.iter()
|
||||
.all(|target| target.managed.auth.is_none()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_target_set_is_rejected_with_the_list_columns_hint() {
|
||||
let err = prepare(&[], GroupPacingArg::Staggered, Duration::from_secs(10)).unwrap_err();
|
||||
|
||||
assert!(err.contains("at least one target is required"));
|
||||
assert!(err.contains("--list-columns"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_duplicate_label_is_rejected_before_any_configuration_is_built() {
|
||||
let targets = vec![
|
||||
unlabeled("host-a:2112"),
|
||||
labeled("host-a:2112", "host-b:2112"),
|
||||
];
|
||||
let err =
|
||||
prepare(&targets, GroupPacingArg::Staggered, Duration::from_secs(10)).unwrap_err();
|
||||
|
||||
assert!(err.contains("duplicate target label"));
|
||||
}
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
#[cfg(any(feature = "client", feature = "tui"))]
|
||||
use irtt_client::managed::{ManagedEvent, ManagedEventSubscription, ManagedEventTryRecvError};
|
||||
|
||||
#[cfg(any(feature = "client", feature = "tui"))]
|
||||
pub(crate) const MANAGED_EVENT_WORK_BUDGET: usize = 128;
|
||||
|
||||
#[cfg(any(feature = "client", feature = "tui"))]
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum ManagedDrainState {
|
||||
Empty,
|
||||
Closed,
|
||||
BudgetExhausted,
|
||||
}
|
||||
|
||||
/// Drain a bounded amount of lossy presentation work before returning to the
|
||||
/// frontend control loop.
|
||||
#[cfg(any(feature = "client", feature = "tui"))]
|
||||
pub(crate) fn drain_managed_events<E>(
|
||||
events: &mut ManagedEventSubscription,
|
||||
dropped_events: &mut u64,
|
||||
mut process: impl FnMut(ManagedEvent) -> Result<(), E>,
|
||||
) -> Result<ManagedDrainState, E> {
|
||||
for _ in 0..MANAGED_EVENT_WORK_BUDGET {
|
||||
match events.try_recv() {
|
||||
Ok(event) => process(event)?,
|
||||
Err(ManagedEventTryRecvError::Lagged(count)) => {
|
||||
*dropped_events = dropped_events.saturating_add(count);
|
||||
}
|
||||
Err(ManagedEventTryRecvError::Empty) => return Ok(ManagedDrainState::Empty),
|
||||
Err(ManagedEventTryRecvError::Closed) => return Ok(ManagedDrainState::Closed),
|
||||
}
|
||||
}
|
||||
Ok(ManagedDrainState::BudgetExhausted)
|
||||
}
|
||||
|
||||
pub fn is_shutdown_requested(shutdown_requested: &AtomicBool) -> bool {
|
||||
shutdown_requested.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn should_print_final_summary(continuous: bool, interrupted: bool) -> bool {
|
||||
!continuous || interrupted
|
||||
}
|
||||
|
||||
pub fn peer_close_run_error(
|
||||
continuous: bool,
|
||||
interrupted: bool,
|
||||
peer_closed_target_outcomes: u64,
|
||||
) -> Option<String> {
|
||||
if !continuous || interrupted || peer_closed_target_outcomes == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let sessions = if peer_closed_target_outcomes == 1 {
|
||||
"target session"
|
||||
} else {
|
||||
"target sessions"
|
||||
};
|
||||
Some(format!(
|
||||
"continuous run ended because of peer closure ({peer_closed_target_outcomes} {sessions})"
|
||||
))
|
||||
}
|
||||
|
||||
pub fn request_managed_stop_for_peer_close(
|
||||
continuous: bool,
|
||||
interrupted: bool,
|
||||
peer_closed_target_outcomes: u64,
|
||||
stop_requested: &mut bool,
|
||||
) -> bool {
|
||||
if !continuous || interrupted || peer_closed_target_outcomes == 0 {
|
||||
return false;
|
||||
}
|
||||
request_managed_stop_once(stop_requested)
|
||||
}
|
||||
|
||||
pub fn request_managed_stop_once(stop_requested: &mut bool) -> bool {
|
||||
if *stop_requested {
|
||||
return false;
|
||||
}
|
||||
*stop_requested = true;
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn peer_close_run_error_is_run_mode_and_interruption_aware() {
|
||||
assert_eq!(peer_close_run_error(false, false, 1), None);
|
||||
assert_eq!(peer_close_run_error(true, false, 0), None);
|
||||
assert_eq!(peer_close_run_error(true, true, 1), None);
|
||||
assert_eq!(
|
||||
peer_close_run_error(true, false, 1).as_deref(),
|
||||
Some("continuous run ended because of peer closure (1 target session)")
|
||||
);
|
||||
assert_eq!(
|
||||
peer_close_run_error(true, false, 3).as_deref(),
|
||||
Some("continuous run ended because of peer closure (3 target sessions)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouped_peer_close_stop_policy_is_run_mode_and_one_shot() {
|
||||
let mut stop_requested = false;
|
||||
assert!(!request_managed_stop_for_peer_close(
|
||||
false,
|
||||
false,
|
||||
1,
|
||||
&mut stop_requested,
|
||||
));
|
||||
assert!(!request_managed_stop_for_peer_close(
|
||||
true,
|
||||
true,
|
||||
1,
|
||||
&mut stop_requested,
|
||||
));
|
||||
assert!(!request_managed_stop_for_peer_close(
|
||||
true,
|
||||
false,
|
||||
0,
|
||||
&mut stop_requested,
|
||||
));
|
||||
assert!(!stop_requested);
|
||||
|
||||
assert!(request_managed_stop_for_peer_close(
|
||||
true,
|
||||
false,
|
||||
1,
|
||||
&mut stop_requested,
|
||||
));
|
||||
assert!(stop_requested);
|
||||
assert!(!request_managed_stop_for_peer_close(
|
||||
true,
|
||||
false,
|
||||
1,
|
||||
&mut stop_requested,
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,226 +0,0 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use clap::ValueEnum;
|
||||
use irtt_client::managed::{ManagedPacing, ManagedTargetConfig, TargetId};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TargetArg {
|
||||
pub label: Option<String>,
|
||||
pub addr: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TargetSpec {
|
||||
pub label: String,
|
||||
pub addr: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PreparedTarget {
|
||||
pub label: String,
|
||||
pub managed: ManagedTargetConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
|
||||
pub enum GroupPacingArg {
|
||||
Staggered,
|
||||
Burst,
|
||||
}
|
||||
|
||||
impl From<GroupPacingArg> for ManagedPacing {
|
||||
fn from(value: GroupPacingArg) -> Self {
|
||||
match value {
|
||||
GroupPacingArg::Staggered => Self::Staggered,
|
||||
GroupPacingArg::Burst => Self::Burst,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse one positional target argument, as `TARGET` or `LABEL=TARGET`.
|
||||
pub fn parse_target(input: &str) -> Result<TargetArg, String> {
|
||||
match input.split_once('=') {
|
||||
None => Ok(TargetArg {
|
||||
label: None,
|
||||
addr: input.to_owned(),
|
||||
}),
|
||||
Some((label, addr)) => {
|
||||
if label.is_empty() {
|
||||
return Err("target label must not be empty".to_owned());
|
||||
}
|
||||
if addr.is_empty() {
|
||||
return Err("target address must not be empty".to_owned());
|
||||
}
|
||||
Ok(TargetArg {
|
||||
label: Some(label.to_owned()),
|
||||
addr: addr.to_owned(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn target_specs(targets: &[TargetArg]) -> Result<Vec<TargetSpec>, String> {
|
||||
let mut specs = Vec::with_capacity(targets.len());
|
||||
let mut unlabeled_counts = std::collections::HashMap::<&str, usize>::new();
|
||||
for target in targets {
|
||||
let label = match &target.label {
|
||||
Some(label) => label.clone(),
|
||||
None => {
|
||||
let count = unlabeled_counts.entry(target.addr.as_str()).or_default();
|
||||
*count += 1;
|
||||
if *count == 1 {
|
||||
target.addr.clone()
|
||||
} else {
|
||||
format!("{}#{}", target.addr, *count)
|
||||
}
|
||||
}
|
||||
};
|
||||
specs.push(TargetSpec {
|
||||
label,
|
||||
addr: target.addr.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
if specs.is_empty() {
|
||||
return Err("at least one target is required unless --list-columns is set".to_owned());
|
||||
}
|
||||
|
||||
let mut labels = HashSet::new();
|
||||
for spec in &specs {
|
||||
if !labels.insert(spec.label.clone()) {
|
||||
return Err(format!("duplicate target label {:?}", spec.label));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(specs)
|
||||
}
|
||||
|
||||
pub fn prepare_managed_targets(specs: Vec<TargetSpec>) -> Result<Vec<PreparedTarget>, String> {
|
||||
let mut targets = Vec::with_capacity(specs.len());
|
||||
for spec in specs {
|
||||
targets.push(PreparedTarget {
|
||||
label: spec.label.clone(),
|
||||
managed: ManagedTargetConfig::new(TargetId::from(spec.label), spec.addr),
|
||||
});
|
||||
}
|
||||
Ok(targets)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn unlabeled(addr: &str) -> TargetArg {
|
||||
TargetArg {
|
||||
label: None,
|
||||
addr: addr.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn labeled(label: &str, addr: &str) -> TargetArg {
|
||||
TargetArg {
|
||||
label: Some(label.to_owned()),
|
||||
addr: addr.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_target_without_equals_is_unlabeled() {
|
||||
let target = parse_target("host.example").unwrap();
|
||||
assert_eq!(target.label, None);
|
||||
assert_eq!(target.addr, "host.example");
|
||||
|
||||
let target = parse_target("host.example:2112").unwrap();
|
||||
assert_eq!(target.label, None);
|
||||
assert_eq!(target.addr, "host.example:2112");
|
||||
|
||||
let target = parse_target("[::1]:2112").unwrap();
|
||||
assert_eq!(target.label, None);
|
||||
assert_eq!(target.addr, "[::1]:2112");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_target_with_equals_splits_on_first() {
|
||||
let target = parse_target("eu=host.example").unwrap();
|
||||
assert_eq!(target.label, Some("eu".to_owned()));
|
||||
assert_eq!(target.addr, "host.example");
|
||||
|
||||
let target = parse_target("eu=host.example:2112").unwrap();
|
||||
assert_eq!(target.label, Some("eu".to_owned()));
|
||||
assert_eq!(target.addr, "host.example:2112");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_target_rejects_empty_label_or_address() {
|
||||
assert!(parse_target("=host.example").is_err());
|
||||
assert!(parse_target("eu=").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_specs_suffix_repeated_unlabeled_and_reject_duplicate_labels() {
|
||||
let targets = vec![unlabeled("host-a:2112"), unlabeled("host-a:2112")];
|
||||
let specs = target_specs(&targets).unwrap();
|
||||
|
||||
assert_eq!(specs[0].label, "host-a:2112");
|
||||
assert_eq!(specs[1].label, "host-a:2112#2");
|
||||
|
||||
let targets = vec![
|
||||
unlabeled("host-a:2112"),
|
||||
labeled("host-a:2112", "host-b:2112"),
|
||||
];
|
||||
let err = target_specs(&targets).unwrap_err();
|
||||
assert!(err.contains("duplicate target label"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_specs_preserve_argument_order_with_mixed_labels() {
|
||||
let targets = vec![
|
||||
unlabeled("local"),
|
||||
labeled("eu", "eu.example"),
|
||||
unlabeled("backup"),
|
||||
labeled("us", "us.example"),
|
||||
];
|
||||
let specs = target_specs(&targets).unwrap();
|
||||
|
||||
let labels: Vec<_> = specs.iter().map(|spec| spec.label.as_str()).collect();
|
||||
assert_eq!(labels, ["local", "eu", "backup", "us"]);
|
||||
let addrs: Vec<_> = specs.iter().map(|spec| spec.addr.as_str()).collect();
|
||||
assert_eq!(addrs, ["local", "eu.example", "backup", "us.example"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_specs_count_unlabeled_occurrences_independently_of_explicit_labels() {
|
||||
let targets = vec![unlabeled("foo"), labeled("eu", "foo"), unlabeled("foo")];
|
||||
let specs = target_specs(&targets).unwrap();
|
||||
|
||||
let labels: Vec<_> = specs.iter().map(|spec| spec.label.as_str()).collect();
|
||||
assert_eq!(labels, ["foo", "eu", "foo#2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_specs_reject_generated_suffix_collisions() {
|
||||
let targets = vec![
|
||||
unlabeled("host.example"),
|
||||
unlabeled("host.example"),
|
||||
labeled("host.example#2", "other.example"),
|
||||
];
|
||||
let err = target_specs(&targets).unwrap_err();
|
||||
assert!(err.contains("duplicate target label"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_preparation_preserves_hostname_and_allows_duplicate_endpoints() {
|
||||
let specs = vec![
|
||||
TargetSpec {
|
||||
label: "a".to_owned(),
|
||||
addr: "example.test".to_owned(),
|
||||
},
|
||||
TargetSpec {
|
||||
label: "b".to_owned(),
|
||||
addr: "example.test".to_owned(),
|
||||
},
|
||||
];
|
||||
let targets = prepare_managed_targets(specs).unwrap();
|
||||
assert_eq!(targets[0].managed.server_addr, "example.test");
|
||||
assert_eq!(targets[1].managed.server_addr, "example.test");
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
#[cfg(any(feature = "client", feature = "tui"))]
|
||||
pub mod client;
|
||||
@@ -1,10 +0,0 @@
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
pub fn install_signal_handler(shutdown_requested: Arc<AtomicBool>) -> Result<(), ctrlc::Error> {
|
||||
ctrlc::set_handler(move || {
|
||||
shutdown_requested.store(true, Ordering::Relaxed);
|
||||
})
|
||||
}
|
||||
@@ -2,11 +2,6 @@ use std::fmt::Write as _;
|
||||
|
||||
use irtt_stats::{Snapshot, TimeStats};
|
||||
|
||||
use crate::cmd::format::{
|
||||
format_ns_f64, format_optional_ns_f64 as format_ns_f64_opt,
|
||||
format_optional_ns_i128 as format_ns_i128, format_percent,
|
||||
};
|
||||
|
||||
pub fn format_summary(summary: &Snapshot) -> String {
|
||||
format_summary_with_options(summary, SummaryFormatOptions::default())
|
||||
}
|
||||
@@ -14,7 +9,6 @@ pub fn format_summary(summary: &Snapshot) -> String {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct SummaryFormatOptions {
|
||||
pub verbose: bool,
|
||||
pub show_running_only_note: bool,
|
||||
}
|
||||
|
||||
pub fn format_summary_with_options(summary: &Snapshot, options: SummaryFormatOptions) -> String {
|
||||
@@ -24,13 +18,6 @@ pub fn format_summary_with_options(summary: &Snapshot, options: SummaryFormatOpt
|
||||
|
||||
writeln!(out).unwrap();
|
||||
writeln!(out, "irtt-rs summary").unwrap();
|
||||
if options.show_running_only_note {
|
||||
writeln!(
|
||||
out,
|
||||
"note: medians unavailable in continuous mode; running statistics are bounded-memory"
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
writeln!(out).unwrap();
|
||||
writeln!(
|
||||
out,
|
||||
@@ -122,6 +109,34 @@ fn write_time_row(out: &mut String, label: &str, value: &TimeStats) {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn format_percent(value: f64) -> String {
|
||||
format!("{value:.2}%")
|
||||
}
|
||||
|
||||
fn format_ns_i128(value: Option<i128>) -> String {
|
||||
value
|
||||
.map(|value| format_ns_f64(value as f64))
|
||||
.unwrap_or_else(|| "-".to_owned())
|
||||
}
|
||||
|
||||
fn format_ns_f64_opt(value: Option<f64>) -> String {
|
||||
value.map(format_ns_f64).unwrap_or_else(|| "-".to_owned())
|
||||
}
|
||||
|
||||
fn format_ns_f64(value: f64) -> String {
|
||||
let sign = if value.is_sign_negative() { "-" } else { "" };
|
||||
let value = value.abs();
|
||||
if value < 1_000.0 {
|
||||
format!("{sign}{value:.0}ns")
|
||||
} else if value < 1_000_000.0 {
|
||||
format!("{sign}{:.1}µs", value / 1_000.0)
|
||||
} else if value < 1_000_000_000.0 {
|
||||
format!("{sign}{:.1}ms", value / 1_000_000.0)
|
||||
} else {
|
||||
format!("{sign}{:.3}s", value / 1_000_000_000.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -183,8 +198,10 @@ mod tests {
|
||||
received_at,
|
||||
rtt: RttSample {
|
||||
raw: Duration::from_micros(1500),
|
||||
adjusted: Some(SignedDuration::from_nanos(1_200_000)),
|
||||
effective: SignedDuration::from_nanos(1_200_000),
|
||||
adjusted: Some(Duration::from_micros(1200)),
|
||||
effective: Duration::from_micros(1200),
|
||||
adjusted_signed: Some(SignedDuration { ns: 1_200_000 }),
|
||||
effective_signed: SignedDuration { ns: 1_200_000 },
|
||||
},
|
||||
server_timing: Some(ServerTiming {
|
||||
receive_wall_ns: None,
|
||||
@@ -215,98 +232,6 @@ mod tests {
|
||||
assert!(output.contains("10.0µs"));
|
||||
assert!(output.contains("timer error"));
|
||||
assert!(output.contains("2.0µs"));
|
||||
assert!(!output.contains("medians unavailable"));
|
||||
}
|
||||
|
||||
/// Returns the Median cell of the row with this label.
|
||||
fn median_cell(output: &str, label: &str) -> String {
|
||||
let row = output
|
||||
.lines()
|
||||
.find(|line| line.trim_start().starts_with(label))
|
||||
.unwrap_or_else(|| panic!("summary should contain a {label:?} row:\n{output}"));
|
||||
// Metric, Count, Min, Mean, Median, ...
|
||||
// Counting from the right keeps multi-word labels out of the way.
|
||||
row.split_whitespace()
|
||||
.rev()
|
||||
.nth(2)
|
||||
.unwrap_or_else(|| panic!("row {row:?} should have a Median cell"))
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
/// Collects probes whose send-call, timer-error, and server-processing
|
||||
/// values each have a median distinct from their min, mean, and max, so
|
||||
/// the rendered cell can only come from a real median calculation.
|
||||
fn spread_finite_summary(config: StatsConfig) -> Snapshot {
|
||||
let mut collector = StatsCollector::new(config);
|
||||
for (seq, (send_call_us, timer_error_us, processing_us)) in
|
||||
[(10_u64, 2_u64, 100_u64), (40, 12, 700), (20, 4, 300)]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let seq = seq as u32;
|
||||
let offset = Duration::from_secs(1) + Duration::from_millis(u64::from(seq));
|
||||
let sent_at = test_timestamp(offset);
|
||||
let received_at = test_timestamp(offset + Duration::from_micros(1500));
|
||||
|
||||
collector.process(&ClientEvent::EchoSent {
|
||||
seq,
|
||||
remote: test_remote(),
|
||||
scheduled_at: sent_at.mono,
|
||||
sent_at,
|
||||
bytes: 64,
|
||||
send_call: Duration::from_micros(send_call_us),
|
||||
timer_error: Duration::from_micros(timer_error_us),
|
||||
});
|
||||
collector.process(&ClientEvent::EchoReply {
|
||||
seq,
|
||||
remote: test_remote(),
|
||||
sent_at,
|
||||
received_at,
|
||||
rtt: RttSample {
|
||||
raw: Duration::from_micros(1500),
|
||||
adjusted: None,
|
||||
effective: SignedDuration::from_nanos(1_500_000),
|
||||
},
|
||||
server_timing: Some(ServerTiming {
|
||||
receive_wall_ns: None,
|
||||
receive_mono_ns: None,
|
||||
send_wall_ns: None,
|
||||
send_mono_ns: None,
|
||||
midpoint_wall_ns: None,
|
||||
midpoint_mono_ns: None,
|
||||
processing: Some(Duration::from_micros(processing_us)),
|
||||
}),
|
||||
one_way: None,
|
||||
received_stats: None,
|
||||
bytes: 64,
|
||||
packet_meta: PacketMeta::default(),
|
||||
});
|
||||
}
|
||||
collector.snapshot()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finite_summary_shows_medians_for_send_call_timer_error_and_processing() {
|
||||
let output = format_summary(&spread_finite_summary(StatsConfig::finite()));
|
||||
|
||||
// Medians of 10/20/40, 2/4/12, and 100/300/700 µs. None of these
|
||||
// equals the row's min, mean, or max.
|
||||
assert_eq!(median_cell(&output, "send call"), "20.0µs");
|
||||
assert_eq!(median_cell(&output, "timer error"), "4.0µs");
|
||||
assert_eq!(median_cell(&output, "server processing"), "300.0µs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn continuous_summary_still_shows_no_medians_for_those_rows() {
|
||||
let output = format_summary(&spread_finite_summary(StatsConfig::continuous()));
|
||||
|
||||
for label in ["send call", "timer error", "server processing"] {
|
||||
assert_eq!(
|
||||
median_cell(&output, label),
|
||||
"-",
|
||||
"continuous mode retains no exact samples for {label}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -320,8 +245,10 @@ mod tests {
|
||||
received_at,
|
||||
rtt: RttSample {
|
||||
raw: Duration::from_micros(1500),
|
||||
adjusted: Some(SignedDuration::from_nanos(1_200_000)),
|
||||
effective: SignedDuration::from_nanos(1_200_000),
|
||||
adjusted: Some(Duration::from_micros(1200)),
|
||||
effective: Duration::from_micros(1200),
|
||||
adjusted_signed: Some(SignedDuration { ns: 1_200_000 }),
|
||||
effective_signed: SignedDuration { ns: 1_200_000 },
|
||||
},
|
||||
server_timing: None,
|
||||
one_way: None,
|
||||
@@ -332,32 +259,13 @@ mod tests {
|
||||
|
||||
let output = format_summary_with_options(
|
||||
&collector.snapshot(),
|
||||
SummaryFormatOptions {
|
||||
verbose: true,
|
||||
..SummaryFormatOptions::default()
|
||||
},
|
||||
SummaryFormatOptions { verbose: true },
|
||||
);
|
||||
|
||||
assert!(output.contains("raw RTT"));
|
||||
assert!(output.contains("adjusted RTT"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn running_only_note_is_format_option() {
|
||||
let summary = StatsCollector::new(StatsConfig::continuous()).snapshot();
|
||||
let output = format_summary_with_options(
|
||||
&summary,
|
||||
SummaryFormatOptions {
|
||||
show_running_only_note: true,
|
||||
..SummaryFormatOptions::default()
|
||||
},
|
||||
);
|
||||
|
||||
assert!(output.contains("irtt-rs summary"));
|
||||
assert!(output.contains("medians unavailable"));
|
||||
assert!(output.contains("continuous mode"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_stats_can_format_negative_values() {
|
||||
let stats = TimeStats {
|
||||
@@ -1,211 +0,0 @@
|
||||
use std::process::{Command, Output};
|
||||
|
||||
fn irtt_rs() -> Command {
|
||||
Command::new(env!("CARGO_BIN_EXE_irtt-rs"))
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn irtt_rs_with_arg0(arg0: &str) -> Command {
|
||||
use std::os::unix::process::CommandExt;
|
||||
|
||||
let mut command = irtt_rs();
|
||||
command.arg0(arg0);
|
||||
command
|
||||
}
|
||||
|
||||
fn output_text(output: &Output) -> String {
|
||||
let mut text = String::new();
|
||||
text.push_str(&String::from_utf8_lossy(&output.stdout));
|
||||
text.push_str(&String::from_utf8_lossy(&output.stderr));
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_help_shows_dispatcher_help() {
|
||||
let output = irtt_rs().arg("--help").output().unwrap();
|
||||
let text = output_text(&output);
|
||||
|
||||
assert!(output.status.success(), "{text}");
|
||||
assert!(text.contains("IRTT-compatible multi-applet dispatcher"));
|
||||
assert!(text.contains("client"));
|
||||
assert!(text.contains("tui"));
|
||||
assert!(text.contains("server"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_without_applet_errors() {
|
||||
let output = irtt_rs().output().unwrap();
|
||||
let text = output_text(&output);
|
||||
|
||||
assert!(!output.status.success());
|
||||
assert!(text.contains("choose an applet"), "{text}");
|
||||
assert!(text.contains("client"));
|
||||
assert!(text.contains("tui"));
|
||||
assert!(text.contains("server"));
|
||||
}
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
#[test]
|
||||
fn canonical_client_subcommand_dispatches_to_client() {
|
||||
let output = irtt_rs().args(["client", "--help"]).output().unwrap();
|
||||
let text = output_text(&output);
|
||||
|
||||
assert!(output.status.success(), "{text}");
|
||||
assert!(text.contains("Minimal IRTT-compatible stream client"));
|
||||
assert!(text.contains("--format <FORMAT>"));
|
||||
assert!(text.contains("--columns <COLUMNS>"));
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "client"))]
|
||||
#[test]
|
||||
fn canonical_client_subcommand_reports_unavailable_when_disabled() {
|
||||
let output = irtt_rs().args(["client", "--help"]).output().unwrap();
|
||||
let text = output_text(&output);
|
||||
|
||||
assert!(!output.status.success());
|
||||
assert!(
|
||||
text.contains("client applet is not available; rebuild with the client feature"),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
#[test]
|
||||
fn canonical_server_subcommand_dispatches_to_server() {
|
||||
let output = irtt_rs().args(["server", "--help"]).output().unwrap();
|
||||
let text = output_text(&output);
|
||||
|
||||
assert!(output.status.success(), "{text}");
|
||||
assert!(text.contains("Minimal IRTT-compatible UDP server"));
|
||||
assert!(text.contains("--bind <ADDR>"));
|
||||
assert!(text.contains("--max-sessions <COUNT>"));
|
||||
assert!(text.contains("--idle-timeout <DURATION>"));
|
||||
assert!(text.contains("--timestamp-allowance <MODE>"));
|
||||
assert!(text.contains("--no-dscp"));
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "server"))]
|
||||
#[test]
|
||||
fn canonical_server_subcommand_reports_unavailable_when_disabled() {
|
||||
let output = irtt_rs().args(["server", "--help"]).output().unwrap();
|
||||
let text = output_text(&output);
|
||||
|
||||
assert!(!output.status.success());
|
||||
assert!(
|
||||
text.contains("server applet is not available; rebuild with the server feature"),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
#[test]
|
||||
fn standalone_server_binary_exposes_the_same_arguments() {
|
||||
let output = std::process::Command::new(env!("CARGO_BIN_EXE_irtt-server"))
|
||||
.arg("--help")
|
||||
.output()
|
||||
.unwrap();
|
||||
let text = output_text(&output);
|
||||
|
||||
assert!(output.status.success(), "{text}");
|
||||
assert!(text.contains("Minimal IRTT-compatible UDP server"));
|
||||
assert!(text.contains("--bind <ADDR>"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[cfg(feature = "client")]
|
||||
#[test]
|
||||
fn client_applet_name_dispatches_to_client() {
|
||||
let output = irtt_rs_with_arg0("irtt-cli")
|
||||
.arg("--help")
|
||||
.output()
|
||||
.unwrap();
|
||||
let text = output_text(&output);
|
||||
|
||||
assert!(output.status.success(), "{text}");
|
||||
assert!(text.contains("Minimal IRTT-compatible stream client"));
|
||||
assert!(text.contains("--format <FORMAT>"));
|
||||
assert!(text.contains("--columns <COLUMNS>"));
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(feature = "client")))]
|
||||
#[test]
|
||||
fn client_applet_name_reports_unavailable_when_disabled() {
|
||||
let output = irtt_rs_with_arg0("irtt-cli")
|
||||
.arg("--help")
|
||||
.output()
|
||||
.unwrap();
|
||||
let text = output_text(&output);
|
||||
|
||||
assert!(!output.status.success());
|
||||
assert!(
|
||||
text.contains("client applet is not available; rebuild with the client feature"),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(all(unix, feature = "tui"))]
|
||||
#[test]
|
||||
fn tui_applet_name_dispatches_to_tui_when_enabled() {
|
||||
let output = irtt_rs_with_arg0("irtt-tui")
|
||||
.arg("--help")
|
||||
.output()
|
||||
.unwrap();
|
||||
let text = output_text(&output);
|
||||
|
||||
assert!(output.status.success(), "{text}");
|
||||
assert!(text.contains("Minimal IRTT-compatible TUI client"));
|
||||
assert!(text.contains("--duration <DURATION>"));
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(feature = "tui")))]
|
||||
#[test]
|
||||
fn tui_applet_name_reports_unavailable_when_disabled() {
|
||||
let output = irtt_rs_with_arg0("irtt-tui")
|
||||
.arg("--help")
|
||||
.output()
|
||||
.unwrap();
|
||||
let text = output_text(&output);
|
||||
|
||||
assert!(!output.status.success());
|
||||
assert!(text.contains("TUI applet is not available"), "{text}");
|
||||
}
|
||||
|
||||
#[cfg(all(unix, feature = "server"))]
|
||||
#[test]
|
||||
fn server_applet_name_dispatches_to_server_when_enabled() {
|
||||
let output = irtt_rs_with_arg0("irtt-server")
|
||||
.arg("--help")
|
||||
.output()
|
||||
.unwrap();
|
||||
let text = output_text(&output);
|
||||
|
||||
assert!(output.status.success(), "{text}");
|
||||
assert!(text.contains("Minimal IRTT-compatible UDP server"));
|
||||
assert!(text.contains("--bind <ADDR>"));
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(feature = "server")))]
|
||||
#[test]
|
||||
fn server_applet_name_reports_unavailable_when_disabled() {
|
||||
let output = irtt_rs_with_arg0("irtt-server")
|
||||
.arg("--help")
|
||||
.output()
|
||||
.unwrap();
|
||||
let text = output_text(&output);
|
||||
|
||||
assert!(!output.status.success());
|
||||
assert!(text.contains("server applet is not available"), "{text}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn unknown_irtt_applet_name_errors() {
|
||||
let output = irtt_rs_with_arg0("irtt-typo").output().unwrap();
|
||||
let text = output_text(&output);
|
||||
|
||||
assert!(!output.status.success());
|
||||
assert!(text.contains("unknown applet name 'irtt-typo'"), "{text}");
|
||||
assert!(text.contains("irtt-cli"));
|
||||
assert!(text.contains("irtt-tui"));
|
||||
assert!(text.contains("irtt-server"));
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,74 +0,0 @@
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr, SocketAddr},
|
||||
sync::mpsc,
|
||||
thread::{self, JoinHandle},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use irtt_server::{Server, ServerConfig};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
const STARTUP_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
pub struct InTreeServer {
|
||||
pub addr: SocketAddr,
|
||||
shutdown: Option<oneshot::Sender<()>>,
|
||||
done: Option<JoinHandle<Result<(), irtt_server::ServerRuntimeError>>>,
|
||||
}
|
||||
|
||||
impl InTreeServer {
|
||||
pub fn start() -> Self {
|
||||
let (startup_tx, startup_rx) = mpsc::sync_channel(1);
|
||||
let (shutdown_tx, shutdown_rx) = oneshot::channel();
|
||||
let done = thread::spawn(move || {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("failed to build in-tree test server runtime");
|
||||
runtime.block_on(async move {
|
||||
let bind_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0);
|
||||
let mut server = Server::bind(bind_addr, ServerConfig::default()).await?;
|
||||
startup_tx
|
||||
.send(server.local_addr()?)
|
||||
.expect("test stopped waiting for in-tree server startup");
|
||||
server
|
||||
.run(async {
|
||||
let _ = shutdown_rx.await;
|
||||
})
|
||||
.await
|
||||
})
|
||||
});
|
||||
|
||||
let addr = match startup_rx.recv_timeout(STARTUP_TIMEOUT) {
|
||||
Ok(addr) => addr,
|
||||
Err(error) => {
|
||||
let _ = shutdown_tx.send(());
|
||||
let result = done.join().expect("in-tree test server thread panicked");
|
||||
panic!("in-tree test server failed before startup ({error}): {result:?}");
|
||||
}
|
||||
};
|
||||
|
||||
Self {
|
||||
addr,
|
||||
shutdown: Some(shutdown_tx),
|
||||
done: Some(done),
|
||||
}
|
||||
}
|
||||
|
||||
fn stop(&mut self) {
|
||||
if let Some(shutdown) = self.shutdown.take() {
|
||||
let _ = shutdown.send(());
|
||||
}
|
||||
if let Some(done) = self.done.take() {
|
||||
done.join()
|
||||
.expect("in-tree test server thread panicked")
|
||||
.expect("in-tree test server stopped with an error");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for InTreeServer {
|
||||
fn drop(&mut self) {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
# `irtt-client` guidance
|
||||
|
||||
Repository-wide guidance in the root `AGENTS.md` also applies here.
|
||||
|
||||
## Linux kernel TX timestamp capture
|
||||
|
||||
On Linux, with the `ancillary` feature, the client best-effort upgrades its
|
||||
socket from RX-only `SO_TIMESTAMPING` to RX+TX immediately after a successful
|
||||
Open, before the first Echo probe can be sent:
|
||||
|
||||
```
|
||||
socket created
|
||||
-> RX timestamping configured (RX_SOFTWARE | SOFTWARE)
|
||||
-> Open attempts/retries (untimestamped)
|
||||
-> successful Open
|
||||
-> best-effort enable TX timestamping (+ TX_SOFTWARE | OPT_ID | OPT_TSONLY)
|
||||
-> first Echo probe
|
||||
```
|
||||
|
||||
`TX_SOFTWARE` asks the kernel for a software send timestamp; `OPT_ID` asks it
|
||||
to tag each notification with an automatically incrementing per-socket ID;
|
||||
`OPT_TSONLY` means the notification never needs to carry the original
|
||||
payload, so a zero-length receive buffer is enough. The upgrade is entirely
|
||||
best-effort: if it fails, the client keeps operating on the original RX-only
|
||||
configuration (`try_enable_tx_timestamping` restores it explicitly) and
|
||||
timing falls back to userspace `sent_at` as it always has. TX capability
|
||||
failure is never a public error and is never logged from the library.
|
||||
|
||||
### Correlation invariant: kernel ID == wire sequence
|
||||
|
||||
The client uses the kernel's automatic `OPT_ID` directly as the probe's wire
|
||||
sequence number — no separate correlation map. This is safe because:
|
||||
|
||||
- **A failed/nonblocking send never consumes an ID.** Linux increments the
|
||||
per-socket ID counter (`sk->sk_tskey`) speculatively while building a
|
||||
datagram and rolls the increment back (`atomic_dec`) on every error path
|
||||
out of `__ip_append_data`/`__ip6_append_data`
|
||||
(`net/ipv4/ip_output.c`, `net/ipv6/ip6_output.c`), guarded by a local
|
||||
`hold_tskey` flag. A `WouldBlock` `try_send` therefore can never leave a
|
||||
gap in, or otherwise advance, the ID the kernel will assign to the next
|
||||
*successful* submission. (`include/net/sock.h`'s `_sock_tx_timestamp`
|
||||
performs the same increment for the non-corked path.) Client-side, the
|
||||
existing send transaction only calls `commit_probe_sent` — which is the
|
||||
only thing that advances `next_wire_seq` — after a successful socket send;
|
||||
a `WouldBlock` result never reaches it.
|
||||
- **The two counters start together and advance together.** `wire_seq`
|
||||
starts at 0 on every successful Open (`SessionMachine::commit_open` builds
|
||||
a fresh `ActiveSession` with `next_wire_seq: 0`) and advances by exactly 1
|
||||
only via `commit_probe_sent`, which only runs after a confirmed successful
|
||||
send — the same condition under which the kernel's counter advances by 1.
|
||||
TX timestamping is enabled only after that same successful Open and before
|
||||
any probe is sent, so both counters' zero points line up exactly.
|
||||
- **One socket, one session, no reopen.** `SessionMachine`'s state machine
|
||||
only reaches `Open` from `Connected`, and `commit_open`/`commit_local_close`
|
||||
never route back to `Connected`. A `Client`/`AsyncClient` cannot reopen a
|
||||
second session on the same socket, so there is no second epoch of wire
|
||||
sequence numbers to collide with a stale kernel ID.
|
||||
- **The one extra send (Close) is harmless.** `Close` sends one datagram
|
||||
after TX timestamping is already enabled, generating one TX timestamp
|
||||
record with no corresponding `wire_seq` (`Close` does not advance
|
||||
`next_wire_seq`). Because the session is terminal immediately after,
|
||||
nothing will ever look up that ID; `record_kernel_tx_timestamp`'s
|
||||
"unknown ID -> ignore" rule discards it safely.
|
||||
|
||||
## MSG_ERRQUEUE drains
|
||||
|
||||
`receive::linux::error_queue` decodes one `MSG_ERRQUEUE` record at a time
|
||||
(`try_recv_error_queue_record`) and classifies it: a genuine send-timestamp
|
||||
completion (`TxTimestamp`), a timestamp-origin record that is not a usable
|
||||
`SND` completion (`MalformedOrUnsupportedTimestamp` — never treated as
|
||||
fatal, since this client only ever requests `TX_SOFTWARE`/`SND`, so anything
|
||||
else on that origin is unexpected metadata, not a network error), a genuine
|
||||
non-timestamp socket/network error (`SocketError`), or nothing (`Ignored`).
|
||||
Origin (`SO_EE_ORIGIN_TIMESTAMPING` or not) is the only thing that decides
|
||||
between the last two categories.
|
||||
|
||||
`receive::linux::drain_tx_timestamps` reads up to
|
||||
`MAX_TX_TIMESTAMP_RECORDS_PER_DRAIN` (32) records per call: nonblocking, one
|
||||
record at a time, no heap allocation, stopping early once the queue is
|
||||
empty. It is a starvation guard, not a queue-capacity promise — one TX
|
||||
timestamp is generated per successful probe, and drains happen at several
|
||||
natural choke points, so a modest constant comfortably covers realistic
|
||||
backlog. `Client`/`AsyncClient` call it after a successful probe send,
|
||||
before processing an inbound reply, and before evaluating timeouts; it never
|
||||
waits for a timestamp; an absent timestamp after all of those opportunities
|
||||
simply stays absent. A genuine `SocketError` record stops the drain and is
|
||||
surfaced through the ordinary `ClientError::Socket` path.
|
||||
|
||||
The Tokio adapter uses the same raw nonblocking `recvmsg(MSG_ERRQUEUE |
|
||||
MSG_DONTWAIT)` rather than `try_io`/`poll_recv_ready`: error-queue readiness
|
||||
is not ordinary read readiness, and driving it through the Tokio reactor
|
||||
risks clearing readiness state that the normal Echo receive path depends on.
|
||||
There is no background task or second `AsyncFd` around the Tokio-owned
|
||||
socket.
|
||||
|
||||
## Retained state
|
||||
|
||||
`PendingProbe` carries an optional `kernel_tx_timestamp: Option<SystemTime>`
|
||||
alongside the userspace `sent_at`. It survives pending -> timed-out retention
|
||||
(`SessionMachine::record_kernel_tx_timestamp` updates whichever of
|
||||
`PendingMap`/`TimedOutMap` still holds the probe) and is otherwise bounded by
|
||||
the same limits those maps already enforce — no new unbounded state. First
|
||||
valid observation wins on duplicates.
|
||||
|
||||
### Pre-send anchor vs. post-send `sent_at` (F-04)
|
||||
|
||||
The probe send transaction splits into two timestamps around the socket
|
||||
send, not one:
|
||||
|
||||
- A **private pre-send anchor**, sampled immediately before the fallible
|
||||
commit preflight (`SessionMachine::finalize_probe_commit`) that must
|
||||
happen before the socket send: timeout deadline `checked_add` arithmetic
|
||||
(so `DurationOverflow` still guarantees nothing was transmitted) and the
|
||||
kernel TX lower-plausibility bound. Its monotonic half becomes
|
||||
`PendingProbe::timeout_at`'s basis; its wall half becomes
|
||||
`PendingProbe::tx_not_before_wall`. It is never exposed publicly.
|
||||
- The **public `sent_at`**, a paired wall/monotonic `ClientTimestamp`
|
||||
captured immediately after the socket send returns successfully
|
||||
(`SessionMachine::commit_probe_sent`, which is infallible — all fallible
|
||||
work already happened against the pre-send anchor). This is the RTT
|
||||
endpoint, the userspace upstream-OWD fallback endpoint, `timer_error`'s
|
||||
basis, and the value surfaced on `EchoSent`/`EchoReply`/`EchoLoss`/
|
||||
`LateReply`.
|
||||
|
||||
So `timeout_at` is deliberately **not** derived from `sent_at.mono` — it
|
||||
remains anchored to before the send, on purpose, so the existing pre-send
|
||||
timeout/overflow/no-send contract is unchanged. Only the *measurement*
|
||||
`sent_at` moved to after the send. A `WouldBlock` `try_send` (Tokio) never
|
||||
samples a `sent_at`, never calls `finalize_probe_commit`'s matching
|
||||
`commit_probe_sent`, and never advances the machine or schedule; each retry
|
||||
gets its own fresh pre-send anchor, and only a successful attempt's anchor
|
||||
and `sent_at` are ever retained.
|
||||
|
||||
**The kernel TX timestamp is eligible for exactly one measurement: the
|
||||
upstream (`client_to_server`) one-way delay send endpoint.**
|
||||
`compute_one_way`'s private `preferred_send_wall` helper prefers it over the
|
||||
userspace `sent_at.wall` sample when
|
||||
|
||||
tx_not_before_wall <= kernel_tx_timestamp <= reply_received_at.wall
|
||||
|
||||
(inclusive, compared only against the client's own wall clock — never
|
||||
against the remote server's wall timestamp). The lower bound is the
|
||||
pre-send `tx_not_before_wall`, not the post-send `sent_at.wall`: a
|
||||
legitimate `TX_SOFTWARE` timestamp can be generated while the send syscall
|
||||
is still in flight, so it can legitimately precede the post-send `sent_at`
|
||||
sample without being implausible. Otherwise, including when no kernel
|
||||
timestamp was observed, the upstream endpoint falls back to `sent_at.wall`
|
||||
(the post-send sample); a rejected observation is never erased from
|
||||
`PendingProbe`, only skipped for that measurement. There is no
|
||||
maximum-lag bound: unlike the kernel receive side, legitimate client
|
||||
send-to-reply time can exceed a second.
|
||||
|
||||
`sent_at` remains the RTT endpoint and the userspace fallback for the
|
||||
upstream (`client_to_server`) one-way delay, exactly as before this
|
||||
capability existed. It is not an input to the downstream
|
||||
(`server_to_client`) one-way delay, which is derived solely from
|
||||
`ReceiveMeta::preferred_receive_wall` and the negotiated server send
|
||||
timestamp — unaffected by this capability or by F-04. `TX_SOFTWARE` is
|
||||
still a software kernel timestamp near the driver handoff, not a NIC
|
||||
hardware transmit time. `irtt-stats`'s `ReplySample`
|
||||
copies public `sent_at` straight into `client_send_mono`/`client_send_wall_ns`,
|
||||
which `send_ipdv_ns` compares across probes for the upstream IPDV component —
|
||||
so that component shifts endpoint along with `sent_at` itself (pre-send vs.
|
||||
post-send) exactly as RTT and the upstream OWD fallback do; it is not a
|
||||
separate invariant. A normal
|
||||
reply and a measurable late reply (one whose `PendingProbe` is still
|
||||
retained in `TimedOutMap`) apply the identical selection policy; an
|
||||
untracked late reply has no retained probe and stays unmeasurable, and a
|
||||
kernel timestamp that arrives after a reply has already been processed is
|
||||
simply never observed by that reply.
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "irtt-client"
|
||||
version = "0.5.0"
|
||||
version = "0.2.0"
|
||||
description = "IRTT-compatible Rust client library"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -13,21 +13,13 @@ categories = ["network-programming"]
|
||||
|
||||
[dependencies]
|
||||
irtt-proto.workspace = true
|
||||
socket2 = { version = "0.6.5", features = ["all"] }
|
||||
thiserror = "2.0.20"
|
||||
tokio = { version = "1.53.1", default-features = false, features = ["rt", "net", "time", "sync"], optional = true}
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
nix = { version = "0.31.3", default-features = false, features = ["net", "uio"], optional = true }
|
||||
libc = { version = "0.2.186", optional = true }
|
||||
socket2 = { version = "0.6.3", features = ["all"] }
|
||||
thiserror = "2.0.18"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
ancillary = ["dep:nix"]
|
||||
tokio = ["dep:tokio"]
|
||||
ancillary = ["dep:libc"]
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
|
||||
[dev-dependencies]
|
||||
irtt-server.workspace = true
|
||||
tokio = { version = "1.53.1", default-features = false, features = ["rt", "sync"] }
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,82 +0,0 @@
|
||||
//! A real `irtt-server` running in-process, for tests that need to prove
|
||||
//! `AsyncClient` and the blocking `Client` are equivalent against a real peer.
|
||||
//!
|
||||
//! This duplicates `crates/irtt-integration-tests/tests/support/in_tree_server.rs`
|
||||
//! rather than depending on it: this module backs private (`super::*`) unit
|
||||
//! tests here, while the integration crate covers black-box client/server
|
||||
//! behavior, and neither can depend on the other's test-only code.
|
||||
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr, SocketAddr},
|
||||
sync::mpsc,
|
||||
thread::{self, JoinHandle},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use irtt_server::{Server, ServerConfig};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
const STARTUP_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
pub struct InTreeServer {
|
||||
pub addr: SocketAddr,
|
||||
shutdown: Option<oneshot::Sender<()>>,
|
||||
done: Option<JoinHandle<Result<(), irtt_server::ServerRuntimeError>>>,
|
||||
}
|
||||
|
||||
impl InTreeServer {
|
||||
pub fn start(config: ServerConfig) -> Self {
|
||||
let (startup_tx, startup_rx) = mpsc::sync_channel(1);
|
||||
let (shutdown_tx, shutdown_rx) = oneshot::channel();
|
||||
let done = thread::spawn(move || {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("failed to build in-tree test server runtime");
|
||||
runtime.block_on(async move {
|
||||
let bind_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0);
|
||||
let mut server = Server::bind(bind_addr, config).await?;
|
||||
startup_tx
|
||||
.send(server.local_addr()?)
|
||||
.expect("test stopped waiting for in-tree server startup");
|
||||
server
|
||||
.run(async {
|
||||
let _ = shutdown_rx.await;
|
||||
})
|
||||
.await
|
||||
})
|
||||
});
|
||||
|
||||
let addr = match startup_rx.recv_timeout(STARTUP_TIMEOUT) {
|
||||
Ok(addr) => addr,
|
||||
Err(error) => {
|
||||
let _ = shutdown_tx.send(());
|
||||
let result = done.join().expect("in-tree test server thread panicked");
|
||||
panic!("in-tree test server failed before startup ({error}): {result:?}");
|
||||
}
|
||||
};
|
||||
|
||||
Self {
|
||||
addr,
|
||||
shutdown: Some(shutdown_tx),
|
||||
done: Some(done),
|
||||
}
|
||||
}
|
||||
|
||||
fn stop_inner(&mut self) {
|
||||
if let Some(shutdown) = self.shutdown.take() {
|
||||
let _ = shutdown.send(());
|
||||
}
|
||||
if let Some(done) = self.done.take() {
|
||||
done.join()
|
||||
.expect("in-tree test server thread panicked")
|
||||
.expect("in-tree test server stopped with an error");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for InTreeServer {
|
||||
fn drop(&mut self) {
|
||||
self.stop_inner();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+803
-793
File diff suppressed because it is too large.
Load diff
@@ -1,318 +0,0 @@
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::{error::ClientError, session::NegotiatedParams};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ProbeSchedule {
|
||||
start_at: Instant,
|
||||
end_at: Option<Instant>,
|
||||
interval: Duration,
|
||||
next_send_at: Option<Instant>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ScheduleCommit {
|
||||
pub(crate) scheduled_at: Instant,
|
||||
pub(crate) next_send_at: Option<Instant>,
|
||||
}
|
||||
|
||||
impl ProbeSchedule {
|
||||
pub(crate) fn new(
|
||||
start_at: Instant,
|
||||
negotiated: &NegotiatedParams,
|
||||
) -> Result<Self, ClientError> {
|
||||
let interval_ns = u64::try_from(negotiated.params.interval_ns)
|
||||
.expect("validated positive negotiated interval");
|
||||
let interval = Duration::from_nanos(interval_ns);
|
||||
let end_at = if negotiated.params.duration_ns > 0 {
|
||||
let duration_ns = u64::try_from(negotiated.params.duration_ns)
|
||||
.expect("validated positive negotiated duration");
|
||||
Some(
|
||||
start_at
|
||||
.checked_add(Duration::from_nanos(duration_ns))
|
||||
.ok_or_else(|| ClientError::NegotiationRejected {
|
||||
reason: "duration is too large to schedule".to_owned(),
|
||||
})?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
start_at,
|
||||
end_at,
|
||||
interval,
|
||||
next_send_at: Some(start_at),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn next_send_deadline(&self) -> Option<Instant> {
|
||||
self.next_send_at
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
pub(crate) fn interval(&self) -> Duration {
|
||||
self.interval
|
||||
}
|
||||
|
||||
pub(crate) fn permit_probe_at(&mut self, now: Instant) -> bool {
|
||||
if self.next_send_at.is_none() {
|
||||
return false;
|
||||
}
|
||||
if self.end_at.is_some_and(|end| now >= end) {
|
||||
self.next_send_at = None;
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn preflight_caller_commit(
|
||||
&self,
|
||||
next_packets_sent: u64,
|
||||
) -> Result<ScheduleCommit, ClientError> {
|
||||
let scheduled_at = self
|
||||
.next_send_at
|
||||
.expect("a caller schedule commit requires a permitted probe");
|
||||
let interval_ns =
|
||||
u64::try_from(self.interval.as_nanos()).map_err(|_| ClientError::DurationOverflow)?;
|
||||
let next_send_at = next_probe_deadline(self.start_at, interval_ns, next_packets_sent)?;
|
||||
Ok(self.finish_commit(scheduled_at, next_send_at))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "tokio", test))]
|
||||
pub(crate) fn preflight_managed_commit(
|
||||
&self,
|
||||
scheduled_at: Instant,
|
||||
permission_at: Instant,
|
||||
) -> Result<ScheduleCommit, ClientError> {
|
||||
let (scheduled_at, next_send_at, _) =
|
||||
advance_cadence(scheduled_at, self.interval, permission_at)?;
|
||||
Ok(self.finish_commit(scheduled_at, next_send_at))
|
||||
}
|
||||
|
||||
pub(crate) fn commit(&mut self, commit: ScheduleCommit) {
|
||||
self.next_send_at = commit.next_send_at;
|
||||
}
|
||||
|
||||
pub(crate) fn is_finished(&self) -> bool {
|
||||
self.next_send_at.is_none()
|
||||
}
|
||||
|
||||
fn finish_commit(&self, scheduled_at: Instant, next_send_at: Instant) -> ScheduleCommit {
|
||||
ScheduleCommit {
|
||||
scheduled_at,
|
||||
next_send_at: if self.end_at.is_some_and(|end| next_send_at >= end) {
|
||||
None
|
||||
} else {
|
||||
Some(next_send_at)
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn next_probe_deadline(
|
||||
start: Instant,
|
||||
interval_ns: u64,
|
||||
packets_sent: u64,
|
||||
) -> Result<Instant, ClientError> {
|
||||
let offset_ns = interval_ns
|
||||
.checked_mul(packets_sent)
|
||||
.ok_or(ClientError::DurationOverflow)?;
|
||||
start
|
||||
.checked_add(Duration::from_nanos(offset_ns))
|
||||
.ok_or(ClientError::DurationOverflow)
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "tokio", test))]
|
||||
pub(crate) fn advance_cadence(
|
||||
deadline: Instant,
|
||||
interval: Duration,
|
||||
now: Instant,
|
||||
) -> Result<(Instant, Instant, u128), ClientError> {
|
||||
if interval.is_zero() {
|
||||
return Err(ClientError::InvalidConfig {
|
||||
reason: "probe interval must be greater than zero".to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
let elapsed_slots = now
|
||||
.checked_duration_since(deadline)
|
||||
.map_or(0, |elapsed| elapsed.as_nanos() / interval.as_nanos());
|
||||
let scheduled_offset = duration_from_nanos(
|
||||
interval
|
||||
.as_nanos()
|
||||
.checked_mul(elapsed_slots)
|
||||
.ok_or(ClientError::DurationOverflow)?,
|
||||
)?;
|
||||
let next_offset = duration_from_nanos(
|
||||
interval
|
||||
.as_nanos()
|
||||
.checked_mul(
|
||||
elapsed_slots
|
||||
.checked_add(1)
|
||||
.ok_or(ClientError::DurationOverflow)?,
|
||||
)
|
||||
.ok_or(ClientError::DurationOverflow)?,
|
||||
)?;
|
||||
let scheduled_at = deadline
|
||||
.checked_add(scheduled_offset)
|
||||
.ok_or(ClientError::DurationOverflow)?;
|
||||
let next_at = deadline
|
||||
.checked_add(next_offset)
|
||||
.ok_or(ClientError::DurationOverflow)?;
|
||||
Ok((scheduled_at, next_at, elapsed_slots))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "tokio", test))]
|
||||
fn duration_from_nanos(nanos: u128) -> Result<Duration, ClientError> {
|
||||
const NANOS_PER_SECOND: u128 = 1_000_000_000;
|
||||
let seconds =
|
||||
u64::try_from(nanos / NANOS_PER_SECOND).map_err(|_| ClientError::DurationOverflow)?;
|
||||
let subsec_nanos = u32::try_from(nanos % NANOS_PER_SECOND)
|
||||
.expect("nanosecond remainder is always less than one second");
|
||||
Ok(Duration::new(seconds, subsec_nanos))
|
||||
}
|
||||
|
||||
pub(crate) fn instant_abs_diff(left: Instant, right: Instant) -> Duration {
|
||||
left.checked_duration_since(right)
|
||||
.or_else(|| right.checked_duration_since(left))
|
||||
.unwrap_or(Duration::ZERO)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use irtt_proto::Params;
|
||||
|
||||
fn negotiated(interval_ns: i64, duration_ns: i64) -> NegotiatedParams {
|
||||
NegotiatedParams {
|
||||
params: Params {
|
||||
interval_ns,
|
||||
duration_ns,
|
||||
..Params::default()
|
||||
},
|
||||
restrictions: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initial_deadline_is_the_opening_time() {
|
||||
let opened_at = Instant::now();
|
||||
|
||||
let schedule = ProbeSchedule::new(opened_at, &negotiated(10_000_000, 0)).unwrap();
|
||||
|
||||
assert_eq!(schedule.next_send_deadline(), Some(opened_at));
|
||||
assert!(!schedule.is_finished());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caller_preflight_keeps_absolute_cadence_without_mutation() {
|
||||
let start = Instant::now();
|
||||
let schedule = ProbeSchedule::new(start, &negotiated(10_000_000, 0)).unwrap();
|
||||
|
||||
let commit = schedule.preflight_caller_commit(3).unwrap();
|
||||
|
||||
assert_eq!(commit.scheduled_at, start);
|
||||
assert_eq!(commit.next_send_at, Some(start + Duration::from_millis(30)));
|
||||
assert_eq!(schedule.next_send_deadline(), Some(start));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caller_commit_advances_exactly_one_cadence_slot() {
|
||||
let start = Instant::now();
|
||||
let mut schedule = ProbeSchedule::new(start, &negotiated(10_000_000, 0)).unwrap();
|
||||
|
||||
let commit = schedule.preflight_caller_commit(1).unwrap();
|
||||
assert_eq!(schedule.next_send_deadline(), Some(start));
|
||||
|
||||
schedule.commit(commit);
|
||||
assert_eq!(
|
||||
schedule.next_send_deadline(),
|
||||
Some(start + Duration::from_millis(10))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finite_duration_uses_an_exclusive_end_boundary() {
|
||||
let start = Instant::now();
|
||||
let mut schedule = ProbeSchedule::new(start, &negotiated(10_000_000, 20_000_000)).unwrap();
|
||||
|
||||
let first = schedule.preflight_caller_commit(1).unwrap();
|
||||
schedule.commit(first);
|
||||
assert_eq!(
|
||||
schedule.next_send_deadline(),
|
||||
Some(start + Duration::from_millis(10))
|
||||
);
|
||||
|
||||
let second = schedule.preflight_caller_commit(2).unwrap();
|
||||
schedule.commit(second);
|
||||
|
||||
assert!(schedule.is_finished());
|
||||
assert_eq!(schedule.next_send_deadline(), None);
|
||||
assert!(!schedule.permit_probe_at(start + Duration::from_millis(20)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permit_at_exclusive_end_finishes_schedule_without_a_send() {
|
||||
let start = Instant::now();
|
||||
let mut schedule = ProbeSchedule::new(start, &negotiated(10_000_000, 20_000_000)).unwrap();
|
||||
|
||||
assert!(!schedule.permit_probe_at(start + Duration::from_millis(20)));
|
||||
assert!(schedule.is_finished());
|
||||
assert_eq!(schedule.next_send_deadline(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_preflight_skips_missed_slots_without_mutation() {
|
||||
let start = Instant::now();
|
||||
let schedule = ProbeSchedule::new(start, &negotiated(10_000_000, 0)).unwrap();
|
||||
let sent_at = start + Duration::from_millis(45);
|
||||
|
||||
let commit = schedule.preflight_managed_commit(start, sent_at).unwrap();
|
||||
|
||||
assert_eq!(commit.scheduled_at, start + Duration::from_millis(40));
|
||||
assert_eq!(commit.next_send_at, Some(start + Duration::from_millis(50)));
|
||||
assert_eq!(schedule.next_send_deadline(), Some(start));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delayed_managed_commit_does_not_replay_catch_up_slots() {
|
||||
let start = Instant::now();
|
||||
let mut schedule = ProbeSchedule::new(start, &negotiated(10_000_000, 0)).unwrap();
|
||||
let delayed_send = start + Duration::from_millis(45);
|
||||
|
||||
let commit = schedule
|
||||
.preflight_managed_commit(start, delayed_send)
|
||||
.unwrap();
|
||||
schedule.commit(commit);
|
||||
|
||||
assert_eq!(
|
||||
schedule.next_send_deadline(),
|
||||
Some(start + Duration::from_millis(50))
|
||||
);
|
||||
assert!(schedule.next_send_deadline().unwrap() > delayed_send);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deadline_arithmetic_overflow_is_detected_before_commit() {
|
||||
let start = Instant::now();
|
||||
let schedule = ProbeSchedule::new(start, &negotiated(2, 0)).unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
schedule.preflight_caller_commit(u64::MAX),
|
||||
Err(ClientError::DurationOverflow)
|
||||
));
|
||||
assert_eq!(schedule.next_send_deadline(), Some(start));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timer_error_is_adapter_owned() {
|
||||
let scheduled_at = Instant::now();
|
||||
let sent_at = scheduled_at + Duration::from_millis(7);
|
||||
|
||||
assert_eq!(
|
||||
instant_abs_diff(sent_at, scheduled_at),
|
||||
Duration::from_millis(7)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -29,23 +29,8 @@ fn close_sends_one_close_packet_with_negotiated_token() {
|
||||
});
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
let sent_at = ClientTimestamp {
|
||||
wall: SystemTime::UNIX_EPOCH + Duration::from_secs(1_234),
|
||||
mono: Instant::now() + Duration::from_secs(5),
|
||||
};
|
||||
client.test_hooks.close_sent_at.set(Some(sent_at));
|
||||
let events = client.close().unwrap();
|
||||
assert!(matches!(
|
||||
events.as_slice(),
|
||||
[ClientEvent::SessionClosed {
|
||||
token: TOKEN,
|
||||
at,
|
||||
..
|
||||
}] if *at == sent_at
|
||||
));
|
||||
assert!(!client.runtime.is_open());
|
||||
assert!(client.schedule.is_none());
|
||||
assert_eq!(client.applied_traffic_class, None);
|
||||
assert_eq!(events.len(), 1);
|
||||
let packets: Vec<_> = server.rx.iter().take(2).collect();
|
||||
let close = &packets[1];
|
||||
assert_eq!(close[3], flags::FLAG_CLOSE);
|
||||
@@ -53,155 +38,6 @@ fn close_sends_one_close_packet_with_negotiated_token() {
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_event_reservation_failure_precedes_dscp_clear_and_send() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
let _ = recv_request(&socket, &tx);
|
||||
});
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
client.test_hooks.fail_close_event_reserve.set(true);
|
||||
client.test_hooks.fail_close_dscp_clear.set(true);
|
||||
|
||||
assert!(matches!(
|
||||
client.close(),
|
||||
Err(ClientError::AllocationFailed {
|
||||
operation: "close event result",
|
||||
..
|
||||
})
|
||||
));
|
||||
assert_eq!(client.test_hooks.close_send_attempts.get(), 0);
|
||||
assert!(client.test_hooks.fail_close_dscp_clear.get());
|
||||
assert!(client.runtime.is_open());
|
||||
assert!(client.schedule.is_some());
|
||||
assert_eq!(client.applied_traffic_class, Some(0));
|
||||
|
||||
client.test_hooks.fail_close_dscp_clear.set(false);
|
||||
client.close().unwrap();
|
||||
assert_eq!(client.test_hooks.close_send_attempts.get(), 1);
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_dscp_clear_failure_precedes_send_and_preserves_open_state() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
let _ = recv_request(&socket, &tx);
|
||||
});
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
client.test_hooks.fail_close_dscp_clear.set(true);
|
||||
|
||||
assert!(matches!(
|
||||
client.close(),
|
||||
Err(ClientError::SocketOption { .. })
|
||||
));
|
||||
assert_eq!(client.test_hooks.close_send_attempts.get(), 0);
|
||||
assert!(client.runtime.is_open());
|
||||
assert!(client.schedule.is_some());
|
||||
assert_eq!(client.applied_traffic_class, Some(0));
|
||||
|
||||
client.close().unwrap();
|
||||
assert_eq!(client.test_hooks.close_send_attempts.get(), 1);
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_send_failure_leaves_machine_and_schedule_open_for_retry() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
let _ = recv_request(&socket, &tx);
|
||||
});
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
let sent_at = ClientTimestamp {
|
||||
wall: SystemTime::UNIX_EPOCH + Duration::from_secs(2_345),
|
||||
mono: Instant::now() + Duration::from_secs(6),
|
||||
};
|
||||
client.test_hooks.close_sent_at.set(Some(sent_at));
|
||||
client.test_hooks.fail_close_send.set(true);
|
||||
|
||||
assert!(matches!(client.close(), Err(ClientError::Socket(_))));
|
||||
assert_eq!(client.test_hooks.close_sent_at.get(), Some(sent_at));
|
||||
assert!(client.runtime.is_open());
|
||||
assert!(client.schedule.is_some());
|
||||
assert_eq!(client.applied_traffic_class, Some(0));
|
||||
assert_eq!(client.test_hooks.close_send_attempts.get(), 1);
|
||||
|
||||
assert!(matches!(
|
||||
client.close().unwrap().as_slice(),
|
||||
[ClientEvent::SessionClosed {
|
||||
token: TOKEN,
|
||||
at,
|
||||
..
|
||||
}] if *at == sent_at
|
||||
));
|
||||
assert_eq!(client.test_hooks.close_sent_at.get(), None);
|
||||
assert_eq!(client.test_hooks.close_send_attempts.get(), 2);
|
||||
assert!(matches!(client.close(), Err(ClientError::AlreadyClosed)));
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_successful_close_commits_before_length_mismatch() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
let _ = recv_request(&socket, &tx);
|
||||
});
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
let expected = client.runtime.prepare_close().unwrap().bytes.len();
|
||||
let sent_at = ClientTimestamp {
|
||||
wall: SystemTime::UNIX_EPOCH + Duration::from_secs(3_456),
|
||||
mono: Instant::now() + Duration::from_secs(7),
|
||||
};
|
||||
client.test_hooks.close_sent_at.set(Some(sent_at));
|
||||
client.test_hooks.close_reported_len.set(Some(expected - 1));
|
||||
|
||||
assert!(matches!(
|
||||
client.close(),
|
||||
Err(ClientError::DatagramLengthMismatch {
|
||||
expected: error_expected,
|
||||
actual,
|
||||
}) if error_expected == expected && actual + 1 == expected
|
||||
));
|
||||
assert!(!client.runtime.is_open());
|
||||
assert!(client.schedule.is_none());
|
||||
assert_eq!(client.applied_traffic_class, None);
|
||||
assert_eq!(client.test_hooks.close_sent_at.get(), None);
|
||||
assert!(matches!(client.close(), Err(ClientError::AlreadyClosed)));
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_probe_fails_after_close() {
|
||||
let params = default_params();
|
||||
@@ -232,6 +68,31 @@ fn send_probe_fails_after_close() {
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_clears_timed_out_metadata() {
|
||||
let params = default_params();
|
||||
let server = silent_open_server(params);
|
||||
let config = ClientConfig {
|
||||
probe_timeout: Duration::from_millis(40),
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(50)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
client.send_probe().unwrap();
|
||||
thread::sleep(Duration::from_millis(60));
|
||||
client.poll_timeouts().unwrap();
|
||||
assert_eq!(client.session.as_ref().unwrap().timed_out.len(), 1);
|
||||
|
||||
client.close().unwrap();
|
||||
assert!(client.session.is_none());
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_flagged_echo_reply_emits_reply_then_closes_without_sending_close() {
|
||||
let params = default_params();
|
||||
@@ -282,7 +143,6 @@ fn close_flagged_echo_reply_emits_reply_then_closes_without_sending_close() {
|
||||
));
|
||||
assert_eq!(events.len(), 2);
|
||||
assert!(client.next_send_deadline().is_none());
|
||||
assert!(client.schedule.is_none());
|
||||
assert!(matches!(
|
||||
client.send_probe(),
|
||||
Err(ClientError::AlreadyClosed)
|
||||
@@ -296,117 +156,6 @@ fn close_flagged_echo_reply_emits_reply_then_closes_without_sending_close() {
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_close_dscp_cleanup_failure_preserves_events_and_closed_state() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server({
|
||||
let params = params.clone();
|
||||
move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
let (request, _) = recv_request(&socket, &tx);
|
||||
let seq = u32::from_le_bytes(request[12..16].try_into().unwrap());
|
||||
socket
|
||||
.send_to(
|
||||
&echo_reply_packet_with_flags(
|
||||
TOKEN,
|
||||
seq,
|
||||
¶ms,
|
||||
&TimestampFields::default(),
|
||||
None,
|
||||
FLAG_REPLY | flags::FLAG_CLOSE,
|
||||
),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
socket
|
||||
.set_read_timeout(Some(Duration::from_millis(250)))
|
||||
.unwrap();
|
||||
while recv_request_timeout(&socket, &tx).is_some() {}
|
||||
}
|
||||
});
|
||||
let mut client = Client::connect(ClientConfig {
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(200)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
})
|
||||
.unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
client.send_probe().unwrap();
|
||||
client.test_hooks.fail_close_dscp_clear.set(true);
|
||||
|
||||
assert!(matches!(
|
||||
client.recv_once().unwrap().as_slice(),
|
||||
[
|
||||
ClientEvent::EchoReply { .. },
|
||||
ClientEvent::SessionClosed { token: TOKEN, .. }
|
||||
]
|
||||
));
|
||||
assert!(client.is_peer_closed());
|
||||
assert!(client.schedule.is_none());
|
||||
assert_eq!(client.applied_traffic_class, Some(0));
|
||||
assert_eq!(client.test_hooks.close_send_attempts.get(), 0);
|
||||
let open = server.rx.recv_timeout(Duration::from_millis(100)).unwrap();
|
||||
let echo = server.rx.recv_timeout(Duration::from_millis(100)).unwrap();
|
||||
assert_ne!(open[3] & FLAG_OPEN, 0);
|
||||
assert_eq!(echo[3] & flags::FLAG_CLOSE, 0);
|
||||
assert!(server.rx.recv_timeout(Duration::from_millis(400)).is_err());
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recv_available_stops_after_peer_close() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server({
|
||||
let params = params.clone();
|
||||
move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
let (request, _) = recv_request(&socket, &tx);
|
||||
let seq = u32::from_le_bytes(request[12..16].try_into().unwrap());
|
||||
let close = echo_reply_packet_with_flags(
|
||||
TOKEN,
|
||||
seq,
|
||||
¶ms,
|
||||
&TimestampFields::default(),
|
||||
None,
|
||||
FLAG_REPLY | flags::FLAG_CLOSE,
|
||||
);
|
||||
socket.send_to(&close, peer).unwrap();
|
||||
socket.send_to(&close, peer).unwrap();
|
||||
}
|
||||
});
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
client.send_probe().unwrap();
|
||||
|
||||
let events = client
|
||||
.recv_available(RecvBudget { max_packets: 8 })
|
||||
.unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
events.as_slice(),
|
||||
[
|
||||
ClientEvent::EchoReply { .. },
|
||||
ClientEvent::SessionClosed { token: TOKEN, .. }
|
||||
]
|
||||
));
|
||||
assert!(client.is_peer_closed());
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_echo_reply_does_not_close_session() {
|
||||
let params = default_params();
|
||||
@@ -421,334 +170,3 @@ fn normal_echo_reply_does_not_close_session() {
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_flagged_duplicate_emits_duplicate_then_closes() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server({
|
||||
let params = params.clone();
|
||||
move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let (request, _) = recv_request(&socket, &tx);
|
||||
let seq = u32::from_le_bytes(request[12..16].try_into().unwrap());
|
||||
let normal = echo_reply_packet(TOKEN, seq, ¶ms, &TimestampFields::default(), None);
|
||||
let close = echo_reply_packet_with_flags(
|
||||
TOKEN,
|
||||
seq,
|
||||
¶ms,
|
||||
&TimestampFields::default(),
|
||||
None,
|
||||
FLAG_REPLY | flags::FLAG_CLOSE,
|
||||
);
|
||||
socket.send_to(&normal, peer).unwrap();
|
||||
socket.send_to(&close, peer).unwrap();
|
||||
}
|
||||
});
|
||||
let mut client = Client::connect(ClientConfig {
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(200)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
})
|
||||
.unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
client.send_probe().unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
client.recv_once().unwrap().as_slice(),
|
||||
[ClientEvent::EchoReply { seq: 0, .. }]
|
||||
));
|
||||
assert!(matches!(
|
||||
client.recv_once().unwrap().as_slice(),
|
||||
[
|
||||
ClientEvent::DuplicateReply { seq: 0, .. },
|
||||
ClientEvent::SessionClosed { token: TOKEN, .. }
|
||||
]
|
||||
));
|
||||
assert!(client.is_peer_closed());
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_flagged_retained_timeout_emits_late_then_closes() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server({
|
||||
let params = params.clone();
|
||||
move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let (request, _) = recv_request(&socket, &tx);
|
||||
let seq = u32::from_le_bytes(request[12..16].try_into().unwrap());
|
||||
socket
|
||||
.send_to(
|
||||
&echo_reply_packet_with_flags(
|
||||
TOKEN,
|
||||
seq,
|
||||
¶ms,
|
||||
&TimestampFields::default(),
|
||||
None,
|
||||
FLAG_REPLY | flags::FLAG_CLOSE,
|
||||
),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
let mut client = Client::connect(ClientConfig {
|
||||
probe_timeout: Duration::from_millis(50),
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(200)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
})
|
||||
.unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
let sent = client.send_probe().unwrap();
|
||||
let ClientEvent::EchoSent { sent_at, .. } = &sent[0] else {
|
||||
panic!("expected EchoSent");
|
||||
};
|
||||
assert!(matches!(
|
||||
client
|
||||
.poll_timeouts_at(sent_at.mono + client.probe_timeout())
|
||||
.unwrap()
|
||||
.as_slice(),
|
||||
[ClientEvent::EchoLoss { seq: 0, .. }]
|
||||
));
|
||||
|
||||
assert!(matches!(
|
||||
client.recv_once().unwrap().as_slice(),
|
||||
[
|
||||
ClientEvent::LateReply {
|
||||
seq: 0,
|
||||
sent_at: Some(_),
|
||||
..
|
||||
},
|
||||
ClientEvent::SessionClosed { token: TOKEN, .. }
|
||||
]
|
||||
));
|
||||
assert!(client.is_peer_closed());
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_flagged_evicted_sequence_emits_late_then_closes() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server({
|
||||
let params = params.clone();
|
||||
move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let (first, _) = recv_request(&socket, &tx);
|
||||
let first_seq = u32::from_le_bytes(first[12..16].try_into().unwrap());
|
||||
socket
|
||||
.send_to(
|
||||
&echo_reply_packet(
|
||||
TOKEN,
|
||||
first_seq,
|
||||
¶ms,
|
||||
&TimestampFields::default(),
|
||||
None,
|
||||
),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let (second, _) = recv_request(&socket, &tx);
|
||||
let second_seq = u32::from_le_bytes(second[12..16].try_into().unwrap());
|
||||
socket
|
||||
.send_to(
|
||||
&echo_reply_packet(
|
||||
TOKEN,
|
||||
second_seq,
|
||||
¶ms,
|
||||
&TimestampFields::default(),
|
||||
None,
|
||||
),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
socket
|
||||
.send_to(
|
||||
&echo_reply_packet_with_flags(
|
||||
TOKEN,
|
||||
first_seq,
|
||||
¶ms,
|
||||
&TimestampFields::default(),
|
||||
None,
|
||||
FLAG_REPLY | flags::FLAG_CLOSE,
|
||||
),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
let mut client = Client::connect(ClientConfig {
|
||||
max_pending_probes: 1,
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(200)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
})
|
||||
.unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
client.send_probe().unwrap();
|
||||
assert!(matches!(
|
||||
client.recv_once().unwrap().as_slice(),
|
||||
[ClientEvent::EchoReply { seq: 0, .. }]
|
||||
));
|
||||
client.send_probe().unwrap();
|
||||
assert!(matches!(
|
||||
client.recv_once().unwrap().as_slice(),
|
||||
[ClientEvent::EchoReply { seq: 1, .. }]
|
||||
));
|
||||
assert!(matches!(
|
||||
client.recv_once().unwrap().as_slice(),
|
||||
[
|
||||
ClientEvent::LateReply {
|
||||
seq: 0,
|
||||
sent_at: None,
|
||||
rtt: None,
|
||||
..
|
||||
},
|
||||
ClientEvent::SessionClosed { token: TOKEN, .. }
|
||||
]
|
||||
));
|
||||
assert!(client.is_peer_closed());
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_flagged_untracked_sequence_emits_warning_then_closes() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server({
|
||||
let params = params.clone();
|
||||
move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
socket
|
||||
.send_to(
|
||||
&echo_reply_packet_with_flags(
|
||||
TOKEN,
|
||||
42,
|
||||
¶ms,
|
||||
&TimestampFields::default(),
|
||||
None,
|
||||
FLAG_REPLY | flags::FLAG_CLOSE,
|
||||
),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
let mut client = Client::connect(ClientConfig {
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(200)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
})
|
||||
.unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
assert!(matches!(
|
||||
client.recv_once().unwrap().as_slice(),
|
||||
[
|
||||
ClientEvent::Warning {
|
||||
kind: WarningKind::UntrackedReply,
|
||||
..
|
||||
},
|
||||
ClientEvent::SessionClosed { token: TOKEN, .. }
|
||||
]
|
||||
));
|
||||
assert!(client.is_peer_closed());
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_token_close_flag_does_not_close_session() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server({
|
||||
let params = params.clone();
|
||||
move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let (request, _) = recv_request(&socket, &tx);
|
||||
let seq = u32::from_le_bytes(request[12..16].try_into().unwrap());
|
||||
socket
|
||||
.send_to(
|
||||
&echo_reply_packet_with_flags(
|
||||
TOKEN.wrapping_add(1),
|
||||
seq,
|
||||
¶ms,
|
||||
&TimestampFields::default(),
|
||||
None,
|
||||
FLAG_REPLY | flags::FLAG_CLOSE,
|
||||
),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let _ = recv_request(&socket, &tx);
|
||||
let _ = recv_request(&socket, &tx);
|
||||
}
|
||||
});
|
||||
let mut client = Client::connect(ClientConfig {
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(200)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
})
|
||||
.unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
client.send_probe().unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
client.recv_once().unwrap().as_slice(),
|
||||
[ClientEvent::Warning {
|
||||
kind: WarningKind::WrongToken,
|
||||
..
|
||||
}]
|
||||
));
|
||||
assert!(!client.is_peer_closed());
|
||||
assert!(matches!(
|
||||
client.send_probe().unwrap().as_slice(),
|
||||
[ClientEvent::EchoSent { seq: 1, .. }]
|
||||
));
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
@@ -42,10 +42,7 @@ fn params_from_config_maps_compatibility_fields() {
|
||||
assert_eq!(params.received_stats, ReceivedStats::Window);
|
||||
assert_eq!(params.stamp_at, StampAt::Midpoint);
|
||||
assert_eq!(params.clock, Clock::Wall);
|
||||
assert_eq!(
|
||||
params.dscp, 184,
|
||||
"config DSCP codepoint 46 must be shifted into raw wire byte 184"
|
||||
);
|
||||
assert_eq!(params.dscp, 46, "config DSCP codepoint must not be shifted");
|
||||
assert_eq!(
|
||||
params.server_fill.as_ref().map(|fill| fill.value.as_str()),
|
||||
Some("rand")
|
||||
@@ -54,7 +51,7 @@ fn params_from_config_maps_compatibility_fields() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_from_config_accepts_boundary_values() {
|
||||
fn params_from_config_accepts_udp_payload_length_boundary_values() {
|
||||
for length in [0, 1, 1472, 4096, MAX_UDP_PAYLOAD_LENGTH] {
|
||||
let config = ClientConfig {
|
||||
length,
|
||||
@@ -65,16 +62,18 @@ fn params_from_config_accepts_boundary_values() {
|
||||
i64::from(length)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_from_config_rejects_oversized_udp_payload_length() {
|
||||
let config = ClientConfig {
|
||||
dscp: 63,
|
||||
length: MAX_UDP_PAYLOAD_LENGTH + 1,
|
||||
..ClientConfig::default()
|
||||
};
|
||||
assert_eq!(
|
||||
params_from_config(&config).unwrap().dscp,
|
||||
252,
|
||||
"boundary codepoint 63 must be shifted into raw wire byte 252"
|
||||
);
|
||||
assert!(matches!(
|
||||
params_from_config(&config),
|
||||
Err(ClientError::InvalidConfig { reason }) if reason.contains("packet length")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -87,95 +86,97 @@ fn params_from_config_encodes_continuous_duration_as_zero() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_from_config_rejects_invalid_values() {
|
||||
let i64_max_ns = u64::try_from(i64::MAX).unwrap();
|
||||
let too_large = Duration::from_nanos(i64_max_ns) + Duration::from_nanos(1);
|
||||
let cases = [
|
||||
(
|
||||
"oversized UDP payload",
|
||||
ClientConfig {
|
||||
length: MAX_UDP_PAYLOAD_LENGTH + 1,
|
||||
..ClientConfig::default()
|
||||
},
|
||||
"packet length",
|
||||
),
|
||||
(
|
||||
"zero finite duration",
|
||||
ClientConfig {
|
||||
duration: Some(Duration::ZERO),
|
||||
..ClientConfig::default()
|
||||
},
|
||||
"duration must be greater than zero; use None for continuous mode",
|
||||
),
|
||||
(
|
||||
"zero interval",
|
||||
ClientConfig {
|
||||
interval: Duration::ZERO,
|
||||
..ClientConfig::default()
|
||||
},
|
||||
"interval must be greater than zero",
|
||||
),
|
||||
(
|
||||
"duration nanosecond overflow",
|
||||
ClientConfig {
|
||||
duration: Some(too_large),
|
||||
..ClientConfig::default()
|
||||
},
|
||||
"duration is too large to encode as nanoseconds",
|
||||
),
|
||||
(
|
||||
"interval nanosecond overflow",
|
||||
ClientConfig {
|
||||
interval: too_large,
|
||||
..ClientConfig::default()
|
||||
},
|
||||
"interval is too large to encode as nanoseconds",
|
||||
),
|
||||
(
|
||||
"invalid DSCP codepoint",
|
||||
ClientConfig {
|
||||
dscp: 64,
|
||||
..ClientConfig::default()
|
||||
},
|
||||
"dscp",
|
||||
),
|
||||
(
|
||||
// The unspecified clock is the absent-tag wire default, not a
|
||||
// client mode; a client that needs timestamps must name a clock.
|
||||
"unspecified clock",
|
||||
ClientConfig {
|
||||
clock: Clock::Unspecified,
|
||||
..ClientConfig::default()
|
||||
},
|
||||
"clock must be wall, monotonic, or both",
|
||||
),
|
||||
(
|
||||
"empty server fill",
|
||||
ClientConfig {
|
||||
server_fill: Some("".to_owned()),
|
||||
..ClientConfig::default()
|
||||
},
|
||||
"server_fill",
|
||||
),
|
||||
(
|
||||
"oversized server fill",
|
||||
ClientConfig {
|
||||
server_fill: Some("0123456789abcdef0123456789abcdefx".to_owned()),
|
||||
..ClientConfig::default()
|
||||
},
|
||||
"server_fill",
|
||||
),
|
||||
];
|
||||
fn params_from_config_rejects_zero_finite_duration() {
|
||||
let config = ClientConfig {
|
||||
duration: Some(Duration::ZERO),
|
||||
..ClientConfig::default()
|
||||
};
|
||||
assert!(matches!(
|
||||
params_from_config(&config),
|
||||
Err(ClientError::InvalidConfig { reason })
|
||||
if reason == "duration must be greater than zero; use None for continuous mode"
|
||||
));
|
||||
}
|
||||
|
||||
for (name, config, expected_reason) in cases {
|
||||
assert!(
|
||||
matches!(
|
||||
params_from_config(&config),
|
||||
Err(ClientError::InvalidConfig { reason }) if reason.contains(expected_reason)
|
||||
),
|
||||
"{name} should fail with InvalidConfig containing {expected_reason:?}"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn params_from_config_rejects_zero_interval() {
|
||||
let config = ClientConfig {
|
||||
interval: Duration::ZERO,
|
||||
..ClientConfig::default()
|
||||
};
|
||||
assert!(matches!(
|
||||
params_from_config(&config),
|
||||
Err(ClientError::InvalidConfig { reason }) if reason == "interval must be greater than zero"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_from_config_rejects_nanosecond_encoding_overflow_as_invalid_config() {
|
||||
let i64_max_ns = u64::try_from(i64::MAX).unwrap();
|
||||
let config = ClientConfig {
|
||||
duration: Some(Duration::from_nanos(i64_max_ns) + Duration::from_nanos(1)),
|
||||
..ClientConfig::default()
|
||||
};
|
||||
assert!(matches!(
|
||||
params_from_config(&config),
|
||||
Err(ClientError::InvalidConfig { reason })
|
||||
if reason == "duration is too large to encode as nanoseconds"
|
||||
));
|
||||
|
||||
let config = ClientConfig {
|
||||
interval: Duration::from_nanos(i64_max_ns) + Duration::from_nanos(1),
|
||||
..ClientConfig::default()
|
||||
};
|
||||
assert!(matches!(
|
||||
params_from_config(&config),
|
||||
Err(ClientError::InvalidConfig { reason })
|
||||
if reason == "interval is too large to encode as nanoseconds"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_from_config_accepts_max_dscp_codepoint() {
|
||||
let config = ClientConfig {
|
||||
dscp: 63,
|
||||
..ClientConfig::default()
|
||||
};
|
||||
assert_eq!(params_from_config(&config).unwrap().dscp, 63);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_from_config_rejects_invalid_dscp_codepoint() {
|
||||
let config = ClientConfig {
|
||||
dscp: 64,
|
||||
..ClientConfig::default()
|
||||
};
|
||||
assert!(matches!(
|
||||
params_from_config(&config),
|
||||
Err(ClientError::InvalidConfig { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_from_config_rejects_empty_server_fill() {
|
||||
let config = ClientConfig {
|
||||
server_fill: Some("".to_owned()),
|
||||
..ClientConfig::default()
|
||||
};
|
||||
assert!(matches!(
|
||||
params_from_config(&config),
|
||||
Err(ClientError::InvalidConfig { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_from_config_rejects_oversized_server_fill() {
|
||||
let config = ClientConfig {
|
||||
server_fill: Some("0123456789abcdef0123456789abcdefx".to_owned()),
|
||||
..ClientConfig::default()
|
||||
};
|
||||
assert!(matches!(
|
||||
params_from_config(&config),
|
||||
Err(ClientError::InvalidConfig { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -9,11 +9,9 @@ use crate::socket_options::socket_traffic_class;
|
||||
target_os = "illumos",
|
||||
target_os = "haiku",
|
||||
)))]
|
||||
fn normal_open_applies_negotiated_traffic_class_after_open_and_close_clears_it() {
|
||||
fn normal_open_applies_negotiated_dscp_after_open_and_close_clears_it() {
|
||||
let mut params = default_params();
|
||||
// Raw wire TOS/Traffic Class byte for DSCP codepoint 46 (EF): a
|
||||
// compliant server echoes back the raw byte it received, unchanged.
|
||||
params.dscp = 184;
|
||||
params.dscp = 46;
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
let reply = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None);
|
||||
@@ -50,7 +48,7 @@ fn normal_open_applies_negotiated_traffic_class_after_open_and_close_clears_it()
|
||||
target_os = "illumos",
|
||||
target_os = "haiku",
|
||||
)))]
|
||||
fn normal_open_uses_negotiated_traffic_class_not_requested_dscp() {
|
||||
fn normal_open_uses_negotiated_dscp_not_requested_dscp() {
|
||||
let mut returned = default_params();
|
||||
returned.dscp = 0;
|
||||
let server = open_success_server(returned);
|
||||
@@ -75,134 +73,3 @@ fn normal_open_uses_negotiated_traffic_class_not_requested_dscp() {
|
||||
);
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(any(
|
||||
target_os = "fuchsia",
|
||||
target_os = "redox",
|
||||
target_os = "solaris",
|
||||
target_os = "illumos",
|
||||
target_os = "haiku",
|
||||
)))]
|
||||
fn failed_close_send_restores_negotiated_traffic_class_and_keeps_session_open() {
|
||||
let mut params = default_params();
|
||||
// Raw wire TOS/Traffic Class byte for DSCP codepoint 46 (EF).
|
||||
params.dscp = 184;
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
let _ = recv_request(&socket, &tx);
|
||||
});
|
||||
let mut config = default_test_config(server.addr);
|
||||
config.dscp = 46;
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
client.test_hooks.fail_close_send.set(true);
|
||||
|
||||
let error = client.close().unwrap_err();
|
||||
|
||||
assert!(matches!(error, ClientError::Socket(_)));
|
||||
assert!(client.runtime.is_open());
|
||||
assert!(client.schedule.is_some());
|
||||
assert_eq!(client.applied_traffic_class, Some(184));
|
||||
assert_eq!(
|
||||
socket_traffic_class(&client.socket, client.remote).unwrap() & 0xfc,
|
||||
184
|
||||
);
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_close_keeps_send_error_primary_when_dscp_restoration_also_fails() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
let _ = recv_request(&socket, &tx);
|
||||
});
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
client.test_hooks.fail_close_send.set(true);
|
||||
client.test_hooks.fail_dscp_restore.set(true);
|
||||
|
||||
let error = client.close().unwrap_err();
|
||||
|
||||
assert!(matches!(error, ClientError::Socket(_)));
|
||||
assert!(error.to_string().contains("injected close send failure"));
|
||||
assert!(client.runtime.is_open());
|
||||
assert!(client.schedule.is_some());
|
||||
assert_eq!(client.applied_traffic_class, Some(0));
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(any(
|
||||
target_os = "fuchsia",
|
||||
target_os = "redox",
|
||||
target_os = "solaris",
|
||||
target_os = "illumos",
|
||||
target_os = "haiku",
|
||||
)))]
|
||||
fn authenticated_peer_close_clears_schedule_and_negotiated_traffic_class() {
|
||||
let mut params = default_params();
|
||||
// Raw wire TOS/Traffic Class byte for DSCP codepoint 46 (EF).
|
||||
params.dscp = 184;
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
let (request, _) = recv_request(&socket, &tx);
|
||||
let seq = u32::from_le_bytes(request[12..16].try_into().unwrap());
|
||||
socket
|
||||
.send_to(
|
||||
&echo_reply_packet_with_flags(
|
||||
TOKEN,
|
||||
seq,
|
||||
¶ms,
|
||||
&TimestampFields::default(),
|
||||
None,
|
||||
FLAG_REPLY | flags::FLAG_CLOSE,
|
||||
),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
let mut config = default_test_config(server.addr);
|
||||
config.dscp = 46;
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
client.send_probe().unwrap();
|
||||
|
||||
let events = client.recv_once().unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
events.as_slice(),
|
||||
[
|
||||
ClientEvent::EchoReply { .. },
|
||||
ClientEvent::SessionClosed { .. }
|
||||
]
|
||||
));
|
||||
assert!(client.schedule.is_none());
|
||||
assert_eq!(client.applied_traffic_class, None);
|
||||
assert_eq!(
|
||||
socket_traffic_class(&client.socket, client.remote).unwrap(),
|
||||
0
|
||||
);
|
||||
server.join();
|
||||
}
|
||||
@@ -8,7 +8,7 @@ fn hmac_open_success() {
|
||||
let params = params_from_config(&config).unwrap();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (request, peer) = recv_request(&socket, &tx);
|
||||
verify_packet_hmac(&key, &request).unwrap();
|
||||
verify_hmac(&key, &request, HMAC_OFFSET).unwrap();
|
||||
let reply = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, Some(&key));
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
});
|
||||
@@ -19,77 +19,45 @@ fn hmac_open_success() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hmac_open_ignores_missing_hmac_before_valid_reply() {
|
||||
fn hmac_open_rejects_missing_hmac() {
|
||||
let key = b"secret".to_vec();
|
||||
let mut config = default_test_config(SocketAddr::from(([127, 0, 0, 1], 1)));
|
||||
config.hmac_key = Some(key.clone());
|
||||
config.hmac_key = Some(key);
|
||||
let params = params_from_config(&config).unwrap();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
let missing = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None);
|
||||
let valid = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, Some(&key));
|
||||
socket.send_to(&missing, peer).unwrap();
|
||||
socket.send_to(&valid, peer).unwrap();
|
||||
let reply = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None);
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
});
|
||||
config.server_addr = server.addr.to_string();
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
assert_eq!(server.rx.iter().take(1).count(), 1);
|
||||
assert!(server.rx.try_recv().is_err());
|
||||
assert!(matches!(
|
||||
client.open(),
|
||||
Err(ClientError::Protocol(
|
||||
irtt_proto::ProtoError::HmacPresenceMismatch
|
||||
))
|
||||
));
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hmac_open_ignores_bad_hmac_before_valid_reply() {
|
||||
fn hmac_open_rejects_bad_hmac() {
|
||||
let key = b"secret".to_vec();
|
||||
let wrong_key = b"wrong".to_vec();
|
||||
let mut config = default_test_config(SocketAddr::from(([127, 0, 0, 1], 1)));
|
||||
config.hmac_key = Some(key.clone());
|
||||
config.hmac_key = Some(key);
|
||||
let params = params_from_config(&config).unwrap();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
let bad = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, Some(&wrong_key));
|
||||
let valid = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, Some(&key));
|
||||
socket.send_to(&bad, peer).unwrap();
|
||||
socket.send_to(&valid, peer).unwrap();
|
||||
});
|
||||
config.server_addr = server.addr.to_string();
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
assert_eq!(server.rx.iter().take(1).count(), 1);
|
||||
assert!(server.rx.try_recv().is_err());
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn post_token_hmac_negotiation_failure_sends_authenticated_cleanup_close() {
|
||||
let key = b"secret".to_vec();
|
||||
let mut config = default_test_config(SocketAddr::from(([127, 0, 0, 1], 1)));
|
||||
config.hmac_key = Some(key.clone());
|
||||
let mut returned = params_from_config(&config).unwrap();
|
||||
returned.interval_ns += 1;
|
||||
let server_key = key.clone();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
let reply = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, &returned, Some(&server_key));
|
||||
let reply = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, Some(&wrong_key));
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
let _ = recv_request(&socket, &tx);
|
||||
});
|
||||
config.server_addr = server.addr.to_string();
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
client.open(),
|
||||
Err(ClientError::NegotiationRejected { .. })
|
||||
Err(ClientError::Protocol(irtt_proto::ProtoError::BadHmac))
|
||||
));
|
||||
let packets: Vec<_> = server.rx.iter().take(2).collect();
|
||||
let cleanup = &packets[1];
|
||||
assert_eq!(cleanup[3], flags::FLAG_CLOSE | FLAG_HMAC);
|
||||
verify_packet_hmac(&key, cleanup).unwrap();
|
||||
assert_eq!(
|
||||
u64::from_le_bytes(cleanup[4 + HMAC_SIZE..12 + HMAC_SIZE].try_into().unwrap()),
|
||||
TOKEN
|
||||
);
|
||||
server.join();
|
||||
}
|
||||
|
||||
@@ -113,7 +81,7 @@ fn hmac_close_packet_includes_valid_hmac() {
|
||||
let packets: Vec<_> = server.rx.iter().take(2).collect();
|
||||
let close = &packets[1];
|
||||
assert_eq!(close[3], flags::FLAG_CLOSE | FLAG_HMAC);
|
||||
verify_packet_hmac(&key, close).unwrap();
|
||||
verify_hmac(&key, close, HMAC_OFFSET).unwrap();
|
||||
assert_eq!(
|
||||
u64::from_le_bytes(close[4 + HMAC_SIZE..12 + HMAC_SIZE].try_into().unwrap()),
|
||||
TOKEN
|
||||
@@ -144,14 +112,7 @@ fn bad_hmac_reply_is_dropped() {
|
||||
.unwrap(),
|
||||
);
|
||||
let ts = TimestampFields::default();
|
||||
let reply_packet = echo_reply_packet_with_flags(
|
||||
TOKEN,
|
||||
seq,
|
||||
¶ms,
|
||||
&ts,
|
||||
Some(&wrong_key),
|
||||
FLAG_REPLY | flags::FLAG_CLOSE,
|
||||
);
|
||||
let reply_packet = echo_reply_packet(TOKEN, seq, ¶ms, &ts, Some(&wrong_key));
|
||||
socket.send_to(&reply_packet, peer).unwrap();
|
||||
}
|
||||
});
|
||||
@@ -170,8 +131,6 @@ fn bad_hmac_reply_is_dropped() {
|
||||
let events = client.recv_once().unwrap();
|
||||
assert_eq!(events.len(), 1);
|
||||
assert!(matches!(&events[0], ClientEvent::Warning { .. }));
|
||||
assert!(!client.is_peer_closed());
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
@@ -191,7 +150,7 @@ fn hmac_echo_request_reply_works() {
|
||||
let mut buf = [0_u8; 2048];
|
||||
if let Ok((size, _)) = socket.recv_from(&mut buf) {
|
||||
tx.send(buf[..size].to_vec()).unwrap();
|
||||
verify_packet_hmac(&server_key, &buf[..size]).unwrap();
|
||||
verify_hmac(&server_key, &buf[..size], HMAC_OFFSET).unwrap();
|
||||
let seq = u32::from_le_bytes(
|
||||
buf[4 + HMAC_SIZE + 8..4 + HMAC_SIZE + 12]
|
||||
.try_into()
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::*;
|
||||
use crate::config::{NegotiationPolicy, DEFAULT_OPEN_TIMEOUTS};
|
||||
use irtt_proto::{
|
||||
flags::FLAG_HMAC, flags::FLAG_OPEN, flags::FLAG_REPLY, verify_packet_hmac, Clock,
|
||||
ReceivedStats, StampAt, HMAC_SIZE, MAGIC,
|
||||
flags::FLAG_HMAC, flags::FLAG_OPEN, flags::FLAG_REPLY, verify_hmac, Clock, ReceivedStats,
|
||||
StampAt, HMAC_SIZE, MAGIC,
|
||||
};
|
||||
use std::{thread, time::SystemTime};
|
||||
|
||||
|
||||
@@ -33,17 +33,13 @@ fn strict_negotiation_rejects_changed_params() {
|
||||
..ClientConfig::default()
|
||||
};
|
||||
let requested = params_from_config(&config).unwrap();
|
||||
assert_eq!(
|
||||
requested.dscp, 184,
|
||||
"codepoint 46 must become raw wire byte 184"
|
||||
);
|
||||
let mut returned = requested.clone();
|
||||
returned.dscp = 0;
|
||||
assert_eq!(
|
||||
rejection_reason(&requested, &returned, NegotiationPolicy::Strict),
|
||||
NegotiationRestriction::DscpChanged {
|
||||
requested: 46,
|
||||
negotiated: 0,
|
||||
requested: requested.dscp,
|
||||
negotiated: returned.dscp,
|
||||
}
|
||||
.message()
|
||||
);
|
||||
@@ -187,34 +183,17 @@ fn strict_negotiation_rejects_negative_returned_length() {
|
||||
|
||||
#[test]
|
||||
fn loose_negotiation_rejects_runtime_invalid_returned_dscp() {
|
||||
let config = ClientConfig {
|
||||
dscp: 46,
|
||||
..ClientConfig::default()
|
||||
};
|
||||
let config = ClientConfig::default();
|
||||
let requested = params_from_config(&config).unwrap();
|
||||
assert_eq!(
|
||||
requested.dscp, 184,
|
||||
"codepoint 46 must become raw wire byte 184"
|
||||
);
|
||||
|
||||
for dscp in [-1, 256] {
|
||||
for dscp in [-1, 64] {
|
||||
let mut returned = requested.clone();
|
||||
returned.dscp = dscp;
|
||||
assert_eq!(
|
||||
rejection_reason(&requested, &returned, NegotiationPolicy::Loose),
|
||||
"dscp must be in range 0..=255"
|
||||
"dscp must be in range 0..=63"
|
||||
);
|
||||
}
|
||||
|
||||
// A raw returned value of 184 must be accepted even though it exceeds the
|
||||
// 0..=63 codepoint range; it is the correctly negotiated wire value for
|
||||
// codepoint 46 and is not subject to the codepoint bound at all.
|
||||
let returned = requested.clone();
|
||||
assert!(
|
||||
assert_negotiates(&requested, &returned, NegotiationPolicy::Loose)
|
||||
.restrictions
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,5 +1,20 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn no_test_open_close_succeeds_on_open_reply_close() {
|
||||
let mut config = default_test_config(SocketAddr::from(([127, 0, 0, 1], 1)));
|
||||
config.run_mode = RunMode::NoTest;
|
||||
let params = params_from_config(&config).unwrap();
|
||||
let server = no_test_server(params.clone(), 0);
|
||||
config.server_addr = server.addr.to_string();
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
let negotiated = assert_no_test_completed(client.open().unwrap());
|
||||
assert_eq!(negotiated.params, params);
|
||||
assert_eq!(client.negotiated.as_ref(), Some(&negotiated));
|
||||
assert!(matches!(client.close(), Err(ClientError::NotOpen)));
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_test_success_validates_params() {
|
||||
let mut config = default_test_config(SocketAddr::from(([127, 0, 0, 1], 1)));
|
||||
@@ -8,12 +23,8 @@ fn no_test_success_validates_params() {
|
||||
let server = no_test_server(params.clone(), 0);
|
||||
config.server_addr = server.addr.to_string();
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert!(client.next_send_deadline().is_none());
|
||||
let negotiated = assert_no_test_completed(client.open().unwrap());
|
||||
assert_eq!(negotiated.params, params);
|
||||
assert!(client.next_send_deadline().is_none());
|
||||
assert!(client.schedule.is_none());
|
||||
assert_eq!(client.applied_traffic_class, None);
|
||||
server.join();
|
||||
}
|
||||
|
||||
@@ -22,55 +33,13 @@ fn no_test_rejects_non_close_open_reply() {
|
||||
let mut config = default_test_config(SocketAddr::from(([127, 0, 0, 1], 1)));
|
||||
config.run_mode = RunMode::NoTest;
|
||||
let params = params_from_config(&config).unwrap();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
let _ = recv_request(&socket, &tx);
|
||||
});
|
||||
let server = open_success_server(params);
|
||||
config.server_addr = server.addr.to_string();
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert!(matches!(
|
||||
client.open(),
|
||||
Err(ClientError::UnexpectedNoTestReply)
|
||||
));
|
||||
let packets: Vec<_> = server.rx.iter().take(2).collect();
|
||||
assert_eq!(packets[1][3], flags::FLAG_CLOSE);
|
||||
assert_eq!(
|
||||
u64::from_le_bytes(packets[1][4..12].try_into().unwrap()),
|
||||
TOKEN
|
||||
);
|
||||
assert!(client.runtime.prepare_open_request().is_ok());
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_test_cleanup_send_failure_preserves_unexpected_reply() {
|
||||
let mut config = default_test_config(SocketAddr::from(([127, 0, 0, 1], 1)));
|
||||
config.run_mode = RunMode::NoTest;
|
||||
let params = params_from_config(&config).unwrap();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
config.server_addr = server.addr.to_string();
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
client.test_hooks.fail_cleanup_send.set(true);
|
||||
|
||||
assert!(matches!(
|
||||
client.open(),
|
||||
Err(ClientError::UnexpectedNoTestReply)
|
||||
));
|
||||
assert!(client.runtime.prepare_open_request().is_ok());
|
||||
server.join();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn address_resolution_connects_to_local_fake_server() {
|
||||
let server = start_fake_server(|socket, tx| {
|
||||
let _ = recv_request(&socket, &tx);
|
||||
});
|
||||
let client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
client.socket.send(b"ping").unwrap();
|
||||
assert_eq!(server.rx.recv().unwrap(), b"ping");
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_open_handshake() {
|
||||
let config = default_test_config(SocketAddr::from(([127, 0, 0, 1], 1)));
|
||||
@@ -9,26 +20,7 @@ fn successful_open_handshake() {
|
||||
|
||||
let negotiated = assert_open_started(client.open().unwrap());
|
||||
assert_eq!(negotiated.params, params);
|
||||
assert!(client.schedule.is_some());
|
||||
assert_eq!(client.applied_traffic_class, Some(0));
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_open_restores_configured_receive_timeout() {
|
||||
let config = default_test_config(SocketAddr::from(([127, 0, 0, 1], 1)));
|
||||
let params = params_from_config(&config).unwrap();
|
||||
let server = open_success_server(params);
|
||||
let mut config = default_test_config(server.addr);
|
||||
config.socket_config.recv_timeout = Some(Duration::from_millis(75));
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
assert_eq!(
|
||||
client.test_hooks.last_restored_read_timeout.get(),
|
||||
Some(Duration::from_millis(75))
|
||||
);
|
||||
assert!(matches!(client.phase, ClientPhase::Open { token: TOKEN }));
|
||||
server.join();
|
||||
}
|
||||
|
||||
@@ -64,81 +56,37 @@ fn open_retries_after_first_timeout() {
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_survives_interrupted_receive_within_same_attempt() {
|
||||
let server = start_fake_server(|socket, tx| {
|
||||
let (first, peer) = recv_request(&socket, &tx);
|
||||
let params = Params::decode(&first[4..]).unwrap();
|
||||
let reply = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None);
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
});
|
||||
let config = ClientConfig {
|
||||
open_timeouts: vec![Duration::from_millis(500)],
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
// Several interrupted receive attempts before the real reply arrives
|
||||
// must not be treated as a timeout, must not retransmit the open
|
||||
// request, and must not advance to a next configured attempt.
|
||||
client.test_hooks.inject_recv_interrupted.set(5);
|
||||
|
||||
let outcome = client.open().unwrap();
|
||||
assert_open_started(outcome);
|
||||
// Exactly one request reached the server: interruptions were absorbed
|
||||
// inside the single configured attempt.
|
||||
assert_eq!(server.rx.iter().take(1).count(), 1);
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_interrupted_receive_does_not_extend_the_attempt_deadline() {
|
||||
// A fake server that never replies: with a short attempt timeout, the
|
||||
// real question is whether interruptions can push the effective wait
|
||||
// past the configured deadline. They must not: the deadline stays
|
||||
// absolute across any number of interruptions.
|
||||
let server = start_fake_server(|socket, tx| {
|
||||
let _ = recv_request(&socket, &tx);
|
||||
});
|
||||
let config = ClientConfig {
|
||||
open_timeouts: vec![Duration::from_millis(200)],
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
// Each interruption carries no timing information of its own, so the
|
||||
// loop must keep re-checking the real deadline rather than treating an
|
||||
// interruption as "more time available" or a reason to fail outright.
|
||||
client.test_hooks.inject_recv_interrupted.set(20);
|
||||
|
||||
let started = Instant::now();
|
||||
let result = client.open();
|
||||
let elapsed = started.elapsed();
|
||||
|
||||
assert!(matches!(result, Err(ClientError::OpenTimeout)));
|
||||
assert!(
|
||||
elapsed < Duration::from_millis(800),
|
||||
"interrupted receives must not extend the attempt deadline, took {elapsed:?}"
|
||||
);
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_timeout_after_all_timeouts() {
|
||||
let server = timeout_server(Duration::from_millis(700));
|
||||
let config = ClientConfig {
|
||||
open_timeouts: vec![Duration::from_millis(200), Duration::from_millis(200)],
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(50)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert!(matches!(client.open(), Err(ClientError::OpenTimeout)));
|
||||
assert_eq!(server.rx.iter().take(2).count(), 2);
|
||||
assert_eq!(
|
||||
client.test_hooks.last_restored_read_timeout.get(),
|
||||
Some(Duration::from_millis(50))
|
||||
);
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_restores_configured_read_timeout_after_timeout() {
|
||||
let server = timeout_server(Duration::from_millis(700));
|
||||
let config = ClientConfig {
|
||||
open_timeouts: vec![Duration::from_millis(200)],
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(450)),
|
||||
..crate::SocketConfig::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert!(matches!(client.open(), Err(ClientError::OpenTimeout)));
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let mut buf = [0_u8; 1];
|
||||
assert!(client.socket.recv(&mut buf).is_err());
|
||||
assert!(start.elapsed() >= Duration::from_millis(350));
|
||||
server.join();
|
||||
}
|
||||
|
||||
@@ -154,8 +102,6 @@ fn protocol_version_mismatch_fails() {
|
||||
client.open(),
|
||||
Err(ClientError::ProtocolVersionMismatch { received: 2, .. })
|
||||
));
|
||||
assert_eq!(server.rx.iter().take(1).count(), 1);
|
||||
assert!(client.runtime.prepare_open_request().is_ok());
|
||||
server.join();
|
||||
}
|
||||
|
||||
@@ -170,353 +116,5 @@ fn server_rejection_fails_in_normal_mode() {
|
||||
});
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
assert!(matches!(client.open(), Err(ClientError::ServerRejected)));
|
||||
assert_eq!(server.rx.iter().take(1).count(), 1);
|
||||
assert!(client.runtime.prepare_open_request().is_ok());
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_untrusted_datagrams_before_valid_reply_use_one_attempt() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
let valid = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None);
|
||||
let mut wrong_type = valid.clone();
|
||||
wrong_type[3] = FLAG_REPLY;
|
||||
let mut reserved_flags = valid.clone();
|
||||
reserved_flags[3] |= 0x10;
|
||||
let mut bad_magic = valid.clone();
|
||||
bad_magic[0] ^= 0xff;
|
||||
let unexpected_hmac =
|
||||
open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, Some(b"unexpected"));
|
||||
|
||||
for packet in [
|
||||
vec![0_u8],
|
||||
bad_magic,
|
||||
wrong_type,
|
||||
reserved_flags,
|
||||
unexpected_hmac,
|
||||
valid,
|
||||
] {
|
||||
socket.send_to(&packet, peer).unwrap();
|
||||
}
|
||||
});
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
|
||||
assert_open_started(client.open().unwrap());
|
||||
assert_eq!(server.rx.iter().take(1).count(), 1);
|
||||
assert!(server.rx.try_recv().is_err());
|
||||
assert!(client.schedule.is_some());
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignored_datagrams_do_not_restart_the_attempt_deadline() {
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
thread::sleep(Duration::from_millis(150));
|
||||
socket.send_to(&[0_u8], peer).unwrap();
|
||||
thread::sleep(Duration::from_millis(150));
|
||||
socket.send_to(&[0_u8], peer).unwrap();
|
||||
let _ = recv_request(&socket, &tx);
|
||||
});
|
||||
let config = ClientConfig {
|
||||
open_timeouts: vec![Duration::from_millis(250), Duration::from_millis(250)],
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
let started = Instant::now();
|
||||
|
||||
assert!(matches!(client.open(), Err(ClientError::OpenTimeout)));
|
||||
let requests: Vec<_> = server.rx.iter().take(2).collect();
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_millis(700),
|
||||
"ignored datagrams restarted an attempt deadline"
|
||||
);
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_ignored_open_datagrams_eventually_time_out() {
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
for _ in 0..2 {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket.send_to(&[0_u8], peer).unwrap();
|
||||
socket.send_to(&MAGIC, peer).unwrap();
|
||||
}
|
||||
thread::sleep(Duration::from_millis(300));
|
||||
});
|
||||
let config = ClientConfig {
|
||||
open_timeouts: vec![Duration::from_millis(200), Duration::from_millis(200)],
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(50)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
|
||||
assert!(matches!(client.open(), Err(ClientError::OpenTimeout)));
|
||||
assert_eq!(server.rx.iter().take(2).count(), 2);
|
||||
assert!(server.rx.try_recv().is_err());
|
||||
assert_eq!(
|
||||
client.test_hooks.last_restored_read_timeout.get(),
|
||||
Some(Duration::from_millis(50))
|
||||
);
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trusted_zero_token_normal_reply_is_terminal() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
// encode_open_reply rejects a zero token without FLAG_CLOSE, so this
|
||||
// deliberately non-compliant reply is built by encoding a normal
|
||||
// reply with a placeholder token and then zeroing the token field.
|
||||
let mut reply = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None);
|
||||
reply[HMAC_OFFSET..HMAC_OFFSET + 8].copy_from_slice(&0_u64.to_le_bytes());
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
});
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
client.open(),
|
||||
Err(ClientError::Protocol(irtt_proto::ProtoError::ZeroToken))
|
||||
));
|
||||
assert_eq!(server.rx.iter().take(1).count(), 1);
|
||||
assert!(client.runtime.prepare_open_request().is_ok());
|
||||
assert!(client.schedule.is_none());
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_deadline_overflow_occurs_before_send() {
|
||||
let server = timeout_server(Duration::from_millis(250));
|
||||
let config = ClientConfig {
|
||||
open_timeouts: vec![Duration::MAX],
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
|
||||
assert!(matches!(client.open(), Err(ClientError::DurationOverflow)));
|
||||
assert!(server.rx.try_recv().is_err());
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schedule_duration_overflow_cannot_partially_open() {
|
||||
let server = start_fake_server(|_socket, _tx| {});
|
||||
let client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
let reply = irtt_proto::OpenReply {
|
||||
flags: FLAG_OPEN | FLAG_REPLY,
|
||||
token: TOKEN,
|
||||
params: params_from_config(client.runtime.config()).unwrap(),
|
||||
};
|
||||
let mut latest = Instant::now();
|
||||
let mut step = Duration::MAX;
|
||||
while !step.is_zero() {
|
||||
if let Some(candidate) = latest.checked_add(step) {
|
||||
latest = candidate;
|
||||
}
|
||||
step /= 2;
|
||||
}
|
||||
let opened_at = ClientTimestamp {
|
||||
mono: latest,
|
||||
wall: SystemTime::now(),
|
||||
};
|
||||
let machine = client
|
||||
.runtime
|
||||
.prepare_open_acceptance(reply, opened_at)
|
||||
.unwrap();
|
||||
let previous_recv_len = client.recv_buffer.len();
|
||||
|
||||
let failure = client.prepare_client_open(machine, opened_at).unwrap_err();
|
||||
|
||||
assert!(matches!(
|
||||
failure.primary,
|
||||
ClientError::NegotiationRejected { .. }
|
||||
));
|
||||
assert!(failure.machine.cleanup_close_packet().is_some());
|
||||
assert!(client.runtime.prepare_open_request().is_ok());
|
||||
assert!(client.schedule.is_none());
|
||||
assert_eq!(client.applied_traffic_class, None);
|
||||
assert_eq!(client.recv_buffer.len(), previous_recv_len);
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn post_token_negotiation_failure_sends_cleanup_close() {
|
||||
let mut returned = default_params();
|
||||
returned.interval_ns += 1;
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, &returned, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
let _ = recv_request(&socket, &tx);
|
||||
});
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
client.open(),
|
||||
Err(ClientError::NegotiationRejected { .. })
|
||||
));
|
||||
let packets: Vec<_> = server.rx.iter().take(2).collect();
|
||||
assert_eq!(packets[1][3], flags::FLAG_CLOSE);
|
||||
assert_eq!(
|
||||
u64::from_le_bytes(packets[1][4..12].try_into().unwrap()),
|
||||
TOKEN
|
||||
);
|
||||
assert!(client.runtime.prepare_open_request().is_ok());
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_send_failure_does_not_replace_primary_open_error() {
|
||||
let mut returned = default_params();
|
||||
returned.interval_ns += 1;
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, &returned, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
client.test_hooks.fail_cleanup_send.set(true);
|
||||
|
||||
assert!(matches!(
|
||||
client.open(),
|
||||
Err(ClientError::NegotiationRejected { .. })
|
||||
));
|
||||
assert!(client.runtime.prepare_open_request().is_ok());
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receive_buffer_reservation_failure_precedes_dscp_application() {
|
||||
let mut returned = default_params();
|
||||
// Raw wire TOS/Traffic Class byte for DSCP codepoint 46 (EF), matching
|
||||
// what the client below requests so negotiation succeeds unchanged.
|
||||
returned.dscp = 184;
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, &returned, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
let _ = recv_request(&socket, &tx);
|
||||
});
|
||||
let mut config = default_test_config(server.addr);
|
||||
config.dscp = 46;
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
client
|
||||
.test_hooks
|
||||
.recv_buffer_len_override
|
||||
.set(Some(usize::MAX));
|
||||
client.test_hooks.fail_open_dscp.set(true);
|
||||
|
||||
assert!(matches!(
|
||||
client.open(),
|
||||
Err(ClientError::AllocationFailed {
|
||||
operation: "negotiated receive buffer",
|
||||
..
|
||||
})
|
||||
));
|
||||
assert!(client.test_hooks.fail_open_dscp.get());
|
||||
assert!(client.runtime.prepare_open_request().is_ok());
|
||||
assert!(client.schedule.is_none());
|
||||
assert_eq!(client.applied_traffic_class, None);
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dscp_application_failure_leaves_machine_connected() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
let _ = recv_request(&socket, &tx);
|
||||
});
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
client.test_hooks.fail_open_dscp.set(true);
|
||||
|
||||
assert!(matches!(
|
||||
client.open(),
|
||||
Err(ClientError::SocketOption {
|
||||
operation: "set negotiated DSCP",
|
||||
..
|
||||
})
|
||||
));
|
||||
assert!(client.test_hooks.prepared_active_session_before_dscp.get());
|
||||
assert!(client.runtime.prepare_open_request().is_ok());
|
||||
assert!(client.schedule.is_none());
|
||||
assert_eq!(client.applied_traffic_class, None);
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_timeout_restoration_failure_leaves_machine_connected() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
let _ = recv_request(&socket, &tx);
|
||||
});
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
client.test_hooks.fail_open_timeout_restore.set(true);
|
||||
|
||||
assert!(matches!(
|
||||
client.open(),
|
||||
Err(ClientError::ReadTimeoutRestore { .. })
|
||||
));
|
||||
assert!(client.runtime.prepare_open_request().is_ok());
|
||||
assert!(client.schedule.is_none());
|
||||
assert_eq!(client.applied_traffic_class, None);
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dscp_rollback_failure_keeps_timeout_restoration_primary() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
let _ = recv_request(&socket, &tx);
|
||||
});
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
client.test_hooks.fail_open_timeout_restore.set(true);
|
||||
client.test_hooks.fail_dscp_restore.set(true);
|
||||
|
||||
let error = client.open().unwrap_err();
|
||||
|
||||
assert!(matches!(error, ClientError::ReadTimeoutRestore { .. }));
|
||||
assert!(client.runtime.prepare_open_request().is_ok());
|
||||
assert!(client.schedule.is_none());
|
||||
assert_eq!(client.applied_traffic_class, None);
|
||||
server.join();
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,54 +0,0 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn recv_available_drains_burst_replies() {
|
||||
let params = default_params();
|
||||
let (mut client, server) = open_client_with_echo_server(¶ms);
|
||||
|
||||
client.send_probe().unwrap();
|
||||
client.send_probe().unwrap();
|
||||
client.send_probe().unwrap();
|
||||
thread::sleep(Duration::from_millis(80));
|
||||
|
||||
let events = client
|
||||
.recv_available(RecvBudget { max_packets: 8 })
|
||||
.unwrap();
|
||||
assert_eq!(events.len(), 3);
|
||||
for (seq, event) in events.iter().enumerate() {
|
||||
assert!(matches!(
|
||||
event,
|
||||
ClientEvent::EchoReply {
|
||||
seq: actual_seq,
|
||||
..
|
||||
} if *actual_seq == seq as u32
|
||||
));
|
||||
}
|
||||
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recv_available_respects_packet_budget() {
|
||||
let params = default_params();
|
||||
let (mut client, server) = open_client_with_echo_server(¶ms);
|
||||
|
||||
client.send_probe().unwrap();
|
||||
client.send_probe().unwrap();
|
||||
thread::sleep(Duration::from_millis(80));
|
||||
|
||||
let first = client
|
||||
.recv_available(RecvBudget { max_packets: 1 })
|
||||
.unwrap();
|
||||
assert_eq!(first.len(), 1);
|
||||
assert!(matches!(&first[0], ClientEvent::EchoReply { seq: 0, .. }));
|
||||
|
||||
let second = client
|
||||
.recv_available(RecvBudget { max_packets: 8 })
|
||||
.unwrap();
|
||||
assert_eq!(second.len(), 1);
|
||||
assert!(matches!(&second[0], ClientEvent::EchoReply { seq: 1, .. }));
|
||||
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
use super::*;
|
||||
|
||||
/// An interrupted receive (`io::ErrorKind::Interrupted`, e.g. `EINTR`) must be
|
||||
/// invisible to the caller: retried transparently, with the eventual reply
|
||||
/// classified exactly as if no interruption had occurred.
|
||||
#[test]
|
||||
fn interrupted_receive_is_retried_and_the_reply_is_still_classified() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
let reply = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None);
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
|
||||
let mut buf = [0_u8; 2048];
|
||||
let (size, _) = socket.recv_from(&mut buf).unwrap();
|
||||
let seq = u32::from_le_bytes(buf[12..16].try_into().unwrap());
|
||||
let _ = size;
|
||||
let ts = TimestampFields::default();
|
||||
let reply_packet = echo_reply_packet(TOKEN, seq, ¶ms, &ts, None);
|
||||
socket.send_to(&reply_packet, peer).unwrap();
|
||||
});
|
||||
let config = ClientConfig {
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_secs(2)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
client.send_probe().unwrap();
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
|
||||
client.test_hooks.inject_recv_interrupted.set(10);
|
||||
let events = client.recv_once().unwrap();
|
||||
|
||||
assert_eq!(events.len(), 1);
|
||||
assert!(
|
||||
matches!(&events[0], ClientEvent::EchoReply { seq: 0, .. }),
|
||||
"expected a normal EchoReply despite interrupted receive attempts, got {:?}",
|
||||
events[0]
|
||||
);
|
||||
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
/// One logical receive keeps one timeout budget: repeated interruptions must
|
||||
/// not extend a `recv_once` call past its configured receive timeout.
|
||||
#[test]
|
||||
fn interrupted_receive_does_not_extend_the_configured_timeout() {
|
||||
let params = default_params();
|
||||
let server = silent_open_server(params);
|
||||
let config = ClientConfig {
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(100)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
// No reply is ever coming; only interrupted attempts occur before the
|
||||
// real socket takes over and legitimately times out.
|
||||
client.test_hooks.inject_recv_interrupted.set(20);
|
||||
let started = Instant::now();
|
||||
let events = client.recv_once().unwrap();
|
||||
let elapsed = started.elapsed();
|
||||
|
||||
assert!(events.is_empty());
|
||||
assert!(
|
||||
elapsed < Duration::from_millis(500),
|
||||
"interrupted receives must not extend the configured receive timeout, took {elapsed:?}"
|
||||
);
|
||||
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
use super::*;
|
||||
use support::echo_packet_len;
|
||||
|
||||
#[cfg(not(all(target_os = "linux", feature = "ancillary")))]
|
||||
fn assert_packet_meta_unavailable(packet_meta: &crate::event::PacketMeta) {
|
||||
assert_eq!(packet_meta.traffic_class, None);
|
||||
assert_eq!(packet_meta.dscp, None);
|
||||
assert_eq!(packet_meta.ecn, None);
|
||||
assert_eq!(packet_meta.kernel_rx_timestamp, None);
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "linux", feature = "ancillary"))]
|
||||
fn metadata_unavailable_skip(test_name: &str) {
|
||||
eprintln!("{test_name}: skipping metadata assertion because kernel did not provide traffic class metadata");
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "linux", feature = "ancillary"))]
|
||||
fn kernel_rx_timestamp_unavailable_skip(test_name: &str) {
|
||||
eprintln!("{test_name}: skipping kernel timestamp assertion because kernel did not provide SCM_TIMESTAMPNS");
|
||||
}
|
||||
|
||||
mod burst_recv;
|
||||
mod interrupted_receive;
|
||||
mod packet_length;
|
||||
mod probe_schedule;
|
||||
mod reply_classification;
|
||||
mod reply_decode;
|
||||
mod reply_metadata;
|
||||
mod timeouts;
|
||||
mod timing_math;
|
||||
@@ -1,190 +0,0 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn minimal_negotiated_layout_works() {
|
||||
let params = Params {
|
||||
protocol_version: 1,
|
||||
duration_ns: 3_000_000_000,
|
||||
interval_ns: 1_000_000_000,
|
||||
received_stats: ReceivedStats::None,
|
||||
stamp_at: StampAt::None,
|
||||
clock: Clock::Both,
|
||||
..Params::default()
|
||||
};
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
let reply = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None);
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
|
||||
socket
|
||||
.set_read_timeout(Some(Duration::from_secs(2)))
|
||||
.unwrap();
|
||||
let mut buf = [0_u8; 2048];
|
||||
if let Ok((size, _)) = socket.recv_from(&mut buf) {
|
||||
tx.send(buf[..size].to_vec()).unwrap();
|
||||
let seq = u32::from_le_bytes(buf[12..16].try_into().unwrap());
|
||||
let ts = TimestampFields::default();
|
||||
let reply_packet = echo_reply_packet(TOKEN, seq, ¶ms, &ts, None);
|
||||
socket.send_to(&reply_packet, peer).unwrap();
|
||||
}
|
||||
});
|
||||
let config = ClientConfig {
|
||||
received_stats: ReceivedStats::None,
|
||||
stamp_at: StampAt::None,
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(200)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
client.send_probe().unwrap();
|
||||
thread::sleep(Duration::from_millis(30));
|
||||
let events = client.recv_once().unwrap();
|
||||
assert_eq!(events.len(), 1);
|
||||
if let ClientEvent::EchoReply {
|
||||
received_stats,
|
||||
server_timing,
|
||||
..
|
||||
} = &events[0]
|
||||
{
|
||||
assert!(received_stats.is_none());
|
||||
assert!(server_timing.is_none());
|
||||
} else {
|
||||
panic!("expected EchoReply");
|
||||
}
|
||||
server.join();
|
||||
}
|
||||
|
||||
// ---------- Regression tests ----------
|
||||
|
||||
#[test]
|
||||
fn short_echo_reply_does_not_emit_echo_reply() {
|
||||
let params = Params {
|
||||
length: 64,
|
||||
..default_params()
|
||||
};
|
||||
let server = start_fake_server({
|
||||
let params = params.clone();
|
||||
move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
let reply = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None);
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
let (request, _) = recv_request(&socket, &tx);
|
||||
let seq = u32::from_le_bytes(request[12..16].try_into().unwrap());
|
||||
let mut reply =
|
||||
echo_reply_packet(TOKEN, seq, ¶ms, &TimestampFields::default(), None);
|
||||
reply.truncate(echo_packet_len(false, ¶ms) - 1);
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
}
|
||||
});
|
||||
let config = ClientConfig {
|
||||
length: 64,
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(200)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
client.send_probe().unwrap();
|
||||
|
||||
let events = client.recv_once().unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
events.as_slice(),
|
||||
[ClientEvent::Warning {
|
||||
kind: WarningKind::MalformedOrUnrelatedPacket,
|
||||
..
|
||||
}]
|
||||
));
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlong_datagram_detection_uses_extra_receive_byte() {
|
||||
let params = Params {
|
||||
length: 4096,
|
||||
..default_params()
|
||||
};
|
||||
let server = start_fake_server({
|
||||
let params = params.clone();
|
||||
move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
let reply = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None);
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
let (request, _) = recv_request(&socket, &tx);
|
||||
let seq = u32::from_le_bytes(request[12..16].try_into().unwrap());
|
||||
let mut reply =
|
||||
echo_reply_packet(TOKEN, seq, ¶ms, &TimestampFields::default(), None);
|
||||
reply.push(0);
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
let _ = recv_request_timeout(&socket, &tx);
|
||||
}
|
||||
});
|
||||
let config = ClientConfig {
|
||||
length: 4096,
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(200)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
client.send_probe().unwrap();
|
||||
|
||||
let events = client.recv_once().unwrap();
|
||||
assert!(matches!(
|
||||
events.as_slice(),
|
||||
[ClientEvent::Warning {
|
||||
kind: WarningKind::MalformedOrUnrelatedPacket,
|
||||
..
|
||||
}]
|
||||
));
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_length_echo_reply_still_emits_echo_reply() {
|
||||
let params = Params {
|
||||
length: 4096,
|
||||
..default_params()
|
||||
};
|
||||
let server = start_fake_server({
|
||||
let params = params.clone();
|
||||
move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
let reply = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None);
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
let (request, _) = recv_request(&socket, &tx);
|
||||
let seq = u32::from_le_bytes(request[12..16].try_into().unwrap());
|
||||
let reply = echo_reply_packet(TOKEN, seq, ¶ms, &TimestampFields::default(), None);
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
let _ = recv_request_timeout(&socket, &tx);
|
||||
}
|
||||
});
|
||||
let config = ClientConfig {
|
||||
length: 4096,
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(200)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
client.send_probe().unwrap();
|
||||
|
||||
let events = client.recv_once().unwrap();
|
||||
assert!(matches!(
|
||||
events.as_slice(),
|
||||
[ClientEvent::EchoReply { bytes, .. }] if *bytes == echo_packet_len(false, ¶ms)
|
||||
));
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
@@ -1,487 +0,0 @@
|
||||
use super::*;
|
||||
|
||||
fn probe_timestamps(permission_at: Instant, sent_at: ClientTimestamp) -> ProbeSendTimestamps {
|
||||
ProbeSendTimestamps {
|
||||
permission_at,
|
||||
send_anchor: sent_at,
|
||||
sent_at,
|
||||
send_call_start: sent_at.mono,
|
||||
send_finished_at: sent_at.mono,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_probe_fails_before_open() {
|
||||
let server = start_fake_server(|_socket, _tx| {});
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
assert!(matches!(client.send_probe(), Err(ClientError::NotOpen)));
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_probe_sends_valid_echo_request() {
|
||||
let params = default_params();
|
||||
let server = silent_open_server(params.clone());
|
||||
let config = ClientConfig {
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(200)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert!(client.next_send_deadline().is_none());
|
||||
assert_open_started(client.open().unwrap());
|
||||
let events = client.send_probe().unwrap();
|
||||
assert_eq!(events.len(), 1);
|
||||
match &events[0] {
|
||||
ClientEvent::EchoSent {
|
||||
seq, remote, bytes, ..
|
||||
} => {
|
||||
assert_eq!(*seq, 0);
|
||||
assert_eq!(*remote, server.addr);
|
||||
assert_eq!(*bytes, echo_packet_len(false, ¶ms));
|
||||
}
|
||||
other => panic!("expected EchoSent, got {other:?}"),
|
||||
}
|
||||
thread::sleep(Duration::from_millis(30));
|
||||
let packets: Vec<_> = server.rx.try_iter().collect();
|
||||
let echo_reqs: Vec<_> = packets
|
||||
.iter()
|
||||
.filter(|p| p.len() >= 4 && p[3] & FLAG_OPEN == 0)
|
||||
.collect();
|
||||
let echo_req = echo_reqs.first().unwrap();
|
||||
assert_eq!(&echo_req[..3], &MAGIC);
|
||||
assert_eq!(echo_req[3], 0x00);
|
||||
let req_token = u64::from_le_bytes(echo_req[4..12].try_into().unwrap());
|
||||
assert_eq!(req_token, TOKEN);
|
||||
let seq = u32::from_le_bytes(echo_req[12..16].try_into().unwrap());
|
||||
assert_eq!(seq, 0);
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_short_probe_commits_before_presentation_length_error() {
|
||||
let params = default_params();
|
||||
let server = silent_open_server(params.clone());
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
let expected = echo_packet_len(false, ¶ms);
|
||||
let initial_deadline = client.next_send_deadline().unwrap();
|
||||
client.probe_reported_len = Some(expected - 1);
|
||||
|
||||
assert!(matches!(
|
||||
client.send_probe(),
|
||||
Err(ClientError::DatagramLengthMismatch {
|
||||
expected: error_expected,
|
||||
actual,
|
||||
}) if error_expected == expected && actual + 1 == expected
|
||||
));
|
||||
assert_eq!(client.runtime.packets_sent(), 1);
|
||||
assert_eq!(
|
||||
client.next_send_deadline(),
|
||||
Some(initial_deadline + client.runtime.config().interval)
|
||||
);
|
||||
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_failed_probe_send_preserves_machine_and_schedule() {
|
||||
let params = default_params();
|
||||
let server = silent_open_server(params);
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
let initial_deadline = client.next_send_deadline().unwrap();
|
||||
client.probe_send_error = true;
|
||||
|
||||
assert!(matches!(client.send_probe(), Err(ClientError::Socket(_))));
|
||||
assert_eq!(client.runtime.packets_sent(), 0);
|
||||
assert_eq!(client.next_send_deadline(), Some(initial_deadline));
|
||||
|
||||
assert!(matches!(
|
||||
client.send_probe().unwrap().as_slice(),
|
||||
[ClientEvent::EchoSent { seq: 0, .. }]
|
||||
));
|
||||
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_timeout_finalization_overflow_does_not_send_or_commit() {
|
||||
let params = default_params();
|
||||
let server = silent_open_server(params);
|
||||
let config = ClientConfig {
|
||||
probe_timeout: Duration::MAX,
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
let initial_deadline = client.next_send_deadline().unwrap();
|
||||
let sent_at = ClientTimestamp {
|
||||
mono: Instant::now(),
|
||||
wall: SystemTime::now(),
|
||||
};
|
||||
|
||||
assert!(matches!(
|
||||
client.send_probe_at(probe_timestamps(initial_deadline, sent_at)),
|
||||
Err(ClientError::DurationOverflow)
|
||||
));
|
||||
assert_eq!(client.runtime.packets_sent(), 0);
|
||||
assert_eq!(client.next_send_deadline(), Some(initial_deadline));
|
||||
thread::sleep(Duration::from_millis(30));
|
||||
assert!(server
|
||||
.rx
|
||||
.try_iter()
|
||||
.all(|packet| packet.len() >= 4 && packet[3] & FLAG_OPEN != 0));
|
||||
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_probe_separates_permission_committed_send_and_send_call_timing() {
|
||||
let duration = Duration::from_secs(1);
|
||||
let interval = Duration::from_millis(100);
|
||||
let params = Params {
|
||||
duration_ns: 1_000_000_000,
|
||||
interval_ns: 100_000_000,
|
||||
..default_params()
|
||||
};
|
||||
let server = silent_open_server(params.clone());
|
||||
let config = ClientConfig {
|
||||
duration: Some(duration),
|
||||
interval,
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
let opened_mono = Instant::now()
|
||||
.checked_sub(Duration::from_secs(2))
|
||||
.expect("test host monotonic clock has at least two seconds of history");
|
||||
client.schedule = Some(
|
||||
ProbeSchedule::new(
|
||||
opened_mono,
|
||||
&NegotiatedParams {
|
||||
params,
|
||||
restrictions: Vec::new(),
|
||||
},
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let permission_at = opened_mono + Duration::from_millis(500);
|
||||
// Distinct pre-send anchor and post-send `sent_at`: the anchor drives
|
||||
// the operational timeout deadline, while `sent_at` (captured after the
|
||||
// send call) is the public measurement/timer_error endpoint. They are
|
||||
// deliberately decoupled by this PR.
|
||||
let send_anchor = ClientTimestamp {
|
||||
wall: SystemTime::now(),
|
||||
mono: opened_mono + Duration::from_millis(525),
|
||||
};
|
||||
let sent_at = ClientTimestamp {
|
||||
wall: SystemTime::now(),
|
||||
mono: opened_mono + Duration::from_millis(534),
|
||||
};
|
||||
let timestamps = ProbeSendTimestamps {
|
||||
permission_at,
|
||||
send_anchor,
|
||||
sent_at,
|
||||
send_call_start: opened_mono + Duration::from_millis(526),
|
||||
send_finished_at: opened_mono + Duration::from_millis(533),
|
||||
};
|
||||
|
||||
let events = client.send_probe_at(timestamps).unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
events.as_slice(),
|
||||
[ClientEvent::EchoSent {
|
||||
scheduled_at,
|
||||
sent_at: event_sent_at,
|
||||
send_call,
|
||||
timer_error,
|
||||
..
|
||||
}] if *scheduled_at == opened_mono
|
||||
&& *event_sent_at == sent_at
|
||||
&& *send_call == Duration::from_millis(7)
|
||||
&& *timer_error == Duration::from_millis(534)
|
||||
));
|
||||
assert_eq!(client.next_send_deadline(), Some(opened_mono + interval));
|
||||
assert_eq!(client.runtime.packets_sent(), 1);
|
||||
// The timeout deadline is anchored to the pre-send `send_anchor`, not
|
||||
// to the post-send `sent_at` captured 9ms later.
|
||||
let timeout_at = send_anchor.mono + client.probe_timeout();
|
||||
assert_ne!(timeout_at, sent_at.mono + client.probe_timeout());
|
||||
assert!(client
|
||||
.poll_timeouts_at(timeout_at - Duration::from_nanos(1))
|
||||
.unwrap()
|
||||
.is_empty());
|
||||
assert!(matches!(
|
||||
client.poll_timeouts_at(timeout_at).unwrap().as_slice(),
|
||||
[ClientEvent::EchoLoss {
|
||||
sent_at: loss_sent_at,
|
||||
..
|
||||
}] if *loss_sent_at == sent_at
|
||||
));
|
||||
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_send_call_excludes_wrapped_history_cleanup() {
|
||||
let params = default_params();
|
||||
let server = silent_open_server(params);
|
||||
let mut client = Client::connect(default_test_config(server.addr)).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
let scheduled_at = client.next_send_deadline().unwrap();
|
||||
let sent_at = ClientTimestamp {
|
||||
wall: SystemTime::now(),
|
||||
mono: scheduled_at + Duration::from_millis(5),
|
||||
};
|
||||
client.runtime.seed_wrapped_probe_history_for_test(sent_at);
|
||||
let timestamps = ProbeSendTimestamps {
|
||||
permission_at: scheduled_at,
|
||||
send_anchor: sent_at,
|
||||
sent_at,
|
||||
send_call_start: scheduled_at + Duration::from_millis(6),
|
||||
send_finished_at: scheduled_at + Duration::from_millis(13),
|
||||
};
|
||||
|
||||
let events = client.send_probe_at(timestamps).unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
events.as_slice(),
|
||||
[ClientEvent::EchoSent {
|
||||
seq: 0,
|
||||
send_call,
|
||||
..
|
||||
}] if *send_call == Duration::from_millis(7)
|
||||
));
|
||||
assert!(!client.runtime.has_timed_out_metadata());
|
||||
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_probe_respects_finite_duration_exclusive_end() {
|
||||
let params = Params {
|
||||
protocol_version: 1,
|
||||
duration_ns: 1_000_000_000,
|
||||
interval_ns: 500_000_000,
|
||||
received_stats: ReceivedStats::Both,
|
||||
stamp_at: StampAt::Both,
|
||||
clock: Clock::Both,
|
||||
..Params::default()
|
||||
};
|
||||
let server = silent_open_server(params.clone());
|
||||
let config = ClientConfig {
|
||||
duration: Some(Duration::from_secs(1)),
|
||||
interval: Duration::from_millis(500),
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(200)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
let start = client.next_send_deadline().unwrap();
|
||||
let interval = Duration::from_millis(500);
|
||||
|
||||
let now0 = ClientTimestamp {
|
||||
mono: start,
|
||||
wall: SystemTime::now(),
|
||||
};
|
||||
assert!(client
|
||||
.send_probe_at(probe_timestamps(now0.mono, now0))
|
||||
.is_ok());
|
||||
|
||||
let now1 = ClientTimestamp {
|
||||
mono: start + interval,
|
||||
wall: SystemTime::now(),
|
||||
};
|
||||
assert!(client
|
||||
.send_probe_at(probe_timestamps(now1.mono, now1))
|
||||
.is_ok());
|
||||
|
||||
let now2 = ClientTimestamp {
|
||||
mono: start + Duration::from_secs(1),
|
||||
wall: SystemTime::now(),
|
||||
};
|
||||
let events = client
|
||||
.send_probe_at(probe_timestamps(now2.mono, now2))
|
||||
.unwrap();
|
||||
assert!(events.is_empty());
|
||||
assert!(client.next_send_deadline().is_none());
|
||||
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_probe_skips_missed_schedule_slots() {
|
||||
let interval = Duration::from_millis(10);
|
||||
let params = Params {
|
||||
protocol_version: 1,
|
||||
duration_ns: 0,
|
||||
interval_ns: 10_000_000,
|
||||
received_stats: ReceivedStats::Both,
|
||||
stamp_at: StampAt::Both,
|
||||
clock: Clock::Both,
|
||||
..Params::default()
|
||||
};
|
||||
let server = echo_server(params);
|
||||
let config = ClientConfig {
|
||||
duration: None,
|
||||
interval,
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
let first_deadline = client.next_send_deadline().unwrap();
|
||||
let permission_at = first_deadline + Duration::from_millis(45);
|
||||
let delayed_send = ClientTimestamp {
|
||||
mono: first_deadline + Duration::from_millis(48),
|
||||
wall: SystemTime::now(),
|
||||
};
|
||||
let timestamps = ProbeSendTimestamps {
|
||||
permission_at,
|
||||
send_anchor: delayed_send,
|
||||
sent_at: delayed_send,
|
||||
send_call_start: first_deadline + Duration::from_millis(49),
|
||||
send_finished_at: first_deadline + Duration::from_millis(55),
|
||||
};
|
||||
let events = client
|
||||
.send_managed_probe_at(first_deadline, timestamps)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(events.len(), 1);
|
||||
assert!(matches!(
|
||||
events[0],
|
||||
ClientEvent::EchoSent {
|
||||
seq: 0,
|
||||
scheduled_at,
|
||||
sent_at,
|
||||
send_call,
|
||||
timer_error,
|
||||
..
|
||||
} if scheduled_at == first_deadline + Duration::from_millis(40)
|
||||
&& sent_at == delayed_send
|
||||
&& send_call == Duration::from_millis(6)
|
||||
&& timer_error == Duration::from_millis(8)
|
||||
));
|
||||
assert_eq!(
|
||||
client.next_send_deadline(),
|
||||
Some(first_deadline + Duration::from_millis(50))
|
||||
);
|
||||
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_probe_skip_preserves_finite_run_end() {
|
||||
let interval = Duration::from_millis(10);
|
||||
let duration = Duration::from_millis(50);
|
||||
let params = Params {
|
||||
protocol_version: 1,
|
||||
duration_ns: 50_000_000,
|
||||
interval_ns: 10_000_000,
|
||||
received_stats: ReceivedStats::Both,
|
||||
stamp_at: StampAt::Both,
|
||||
clock: Clock::Both,
|
||||
..Params::default()
|
||||
};
|
||||
let server = echo_server(params);
|
||||
let config = ClientConfig {
|
||||
duration: Some(duration),
|
||||
interval,
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
let first_deadline = client.next_send_deadline().unwrap();
|
||||
let delayed_send = ClientTimestamp {
|
||||
mono: first_deadline + Duration::from_millis(45),
|
||||
wall: SystemTime::now(),
|
||||
};
|
||||
let first = client
|
||||
.send_managed_probe_at(
|
||||
first_deadline,
|
||||
probe_timestamps(delayed_send.mono, delayed_send),
|
||||
)
|
||||
.unwrap();
|
||||
let second_sent_at = ClientTimestamp {
|
||||
mono: first_deadline + Duration::from_millis(46),
|
||||
wall: SystemTime::now(),
|
||||
};
|
||||
let second = client
|
||||
.send_managed_probe_at(
|
||||
first_deadline + duration,
|
||||
probe_timestamps(second_sent_at.mono, second_sent_at),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(first.len(), 1);
|
||||
assert!(second.is_empty());
|
||||
assert!(client.next_send_deadline().is_none());
|
||||
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receive_wait_is_bounded_by_next_ten_millisecond_deadline() {
|
||||
let now = Instant::now();
|
||||
let deadline = now + Duration::from_millis(10);
|
||||
|
||||
assert_eq!(
|
||||
bounded_receive_timeout(
|
||||
Some(deadline),
|
||||
Some(Duration::from_millis(20)),
|
||||
Duration::from_millis(20),
|
||||
now,
|
||||
),
|
||||
Some(Duration::from_millis(10))
|
||||
);
|
||||
assert_eq!(
|
||||
bounded_receive_timeout(
|
||||
Some(now),
|
||||
Some(Duration::from_millis(20)),
|
||||
Duration::from_millis(20),
|
||||
now,
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_rejects_invalid_probe_limits() {
|
||||
for config in [
|
||||
ClientConfig {
|
||||
max_pending_probes: 0,
|
||||
..ClientConfig::default()
|
||||
},
|
||||
ClientConfig {
|
||||
probe_timeout: Duration::ZERO,
|
||||
..ClientConfig::default()
|
||||
},
|
||||
] {
|
||||
assert!(matches!(
|
||||
Client::connect(config),
|
||||
Err(ClientError::InvalidConfig { .. })
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn duplicate_reply_emits_duplicate_event() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
let reply = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None);
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
|
||||
socket
|
||||
.set_read_timeout(Some(Duration::from_secs(2)))
|
||||
.unwrap();
|
||||
let mut buf = [0_u8; 2048];
|
||||
if let Ok((size, _)) = socket.recv_from(&mut buf) {
|
||||
tx.send(buf[..size].to_vec()).unwrap();
|
||||
let seq = u32::from_le_bytes(buf[12..16].try_into().unwrap());
|
||||
let ts = TimestampFields::default();
|
||||
let reply_packet = echo_reply_packet(TOKEN, seq, ¶ms, &ts, None);
|
||||
socket.send_to(&reply_packet, peer).unwrap();
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
socket.send_to(&reply_packet, peer).unwrap();
|
||||
}
|
||||
});
|
||||
let config = ClientConfig {
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(200)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
client.send_probe().unwrap();
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
|
||||
let events1 = client.recv_once().unwrap();
|
||||
assert_eq!(events1.len(), 1);
|
||||
assert!(matches!(&events1[0], ClientEvent::EchoReply { .. }));
|
||||
|
||||
thread::sleep(Duration::from_millis(30));
|
||||
let events2 = client.recv_once().unwrap();
|
||||
assert_eq!(events2.len(), 1);
|
||||
assert!(matches!(
|
||||
&events2[0],
|
||||
ClientEvent::DuplicateReply { seq: 0, .. }
|
||||
));
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_order_reply_emits_late_event() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
let reply = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None);
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
|
||||
socket
|
||||
.set_read_timeout(Some(Duration::from_secs(2)))
|
||||
.unwrap();
|
||||
|
||||
let mut seqs = Vec::new();
|
||||
for _ in 0..2 {
|
||||
let mut buf = [0_u8; 2048];
|
||||
if let Ok((size, _)) = socket.recv_from(&mut buf) {
|
||||
tx.send(buf[..size].to_vec()).unwrap();
|
||||
let seq = u32::from_le_bytes(buf[12..16].try_into().unwrap());
|
||||
seqs.push(seq);
|
||||
}
|
||||
}
|
||||
let ts = TimestampFields::default();
|
||||
let reply1 = echo_reply_packet(TOKEN, seqs[1], ¶ms, &ts, None);
|
||||
socket.send_to(&reply1, peer).unwrap();
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
let reply0 = echo_reply_packet(TOKEN, seqs[0], ¶ms, &ts, None);
|
||||
socket.send_to(&reply0, peer).unwrap();
|
||||
});
|
||||
let config = ClientConfig {
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(200)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
client.send_probe().unwrap();
|
||||
client.send_probe().unwrap();
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
|
||||
let ev1 = client.recv_once().unwrap();
|
||||
assert_eq!(ev1.len(), 1);
|
||||
assert!(matches!(&ev1[0], ClientEvent::EchoReply { seq: 1, .. }));
|
||||
|
||||
thread::sleep(Duration::from_millis(30));
|
||||
let ev2 = client.recv_once().unwrap();
|
||||
assert_eq!(ev2.len(), 1);
|
||||
match &ev2[0] {
|
||||
ClientEvent::LateReply {
|
||||
seq,
|
||||
highest_seen,
|
||||
rtt,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(*seq, 0);
|
||||
assert_eq!(*highest_seen, 1);
|
||||
assert!(rtt.is_some());
|
||||
}
|
||||
other => panic!("expected LateReply, got {other:?}"),
|
||||
}
|
||||
server.join();
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn recv_once_returns_empty_on_timeout() {
|
||||
let params = default_params();
|
||||
let server = open_success_server(params);
|
||||
let config = ClientConfig {
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(50)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
let events = client.recv_once().unwrap();
|
||||
assert!(events.is_empty());
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recv_once_decodes_echo_reply_and_emits_event() {
|
||||
let params = default_params();
|
||||
let (mut client, server) = open_client_with_echo_server(¶ms);
|
||||
|
||||
client.send_probe().unwrap();
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
|
||||
let events = client.recv_once().unwrap();
|
||||
assert_eq!(events.len(), 1);
|
||||
match &events[0] {
|
||||
ClientEvent::EchoReply {
|
||||
seq,
|
||||
rtt,
|
||||
received_stats,
|
||||
server_timing,
|
||||
bytes,
|
||||
packet_meta,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(*seq, 0);
|
||||
assert_eq!(*bytes, echo_packet_len(false, ¶ms));
|
||||
assert!(rtt.raw > Duration::ZERO);
|
||||
assert_eq!(
|
||||
rtt.effective,
|
||||
rtt.adjusted
|
||||
.unwrap_or_else(|| SignedDuration::from_duration(rtt.raw))
|
||||
);
|
||||
assert!(received_stats.is_some());
|
||||
let stats = received_stats.as_ref().unwrap();
|
||||
assert_eq!(stats.count, Some(42));
|
||||
assert_eq!(stats.window, Some(0x07));
|
||||
assert!(server_timing.is_some());
|
||||
let st = server_timing.as_ref().unwrap();
|
||||
assert!(st.processing.is_some());
|
||||
#[cfg(not(all(target_os = "linux", feature = "ancillary")))]
|
||||
{
|
||||
assert_eq!(packet_meta.traffic_class, None);
|
||||
assert_eq!(packet_meta.dscp, None);
|
||||
assert_eq!(packet_meta.ecn, None);
|
||||
assert_eq!(packet_meta.kernel_rx_timestamp, None);
|
||||
}
|
||||
#[cfg(all(target_os = "linux", feature = "ancillary"))]
|
||||
{
|
||||
assert_eq!(
|
||||
packet_meta.dscp,
|
||||
packet_meta.traffic_class.map(|tc| tc >> 2)
|
||||
);
|
||||
assert_eq!(
|
||||
packet_meta.ecn,
|
||||
packet_meta.traffic_class.map(|tc| tc & 0b11)
|
||||
);
|
||||
}
|
||||
}
|
||||
other => panic!("expected EchoReply, got {other:?}"),
|
||||
}
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recv_once_decodes_only_received_bytes_after_longer_datagram() {
|
||||
let params = default_params();
|
||||
let server_params = params.clone();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
let reply = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, &server_params, None);
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
|
||||
let mut seqs = Vec::new();
|
||||
for _ in 0..2 {
|
||||
let (packet, _) = recv_request(&socket, &tx);
|
||||
seqs.push(u32::from_le_bytes(packet[12..16].try_into().unwrap()));
|
||||
}
|
||||
|
||||
let mut longer = echo_reply_packet(
|
||||
TOKEN,
|
||||
seqs[0],
|
||||
&server_params,
|
||||
&TimestampFields::default(),
|
||||
None,
|
||||
);
|
||||
longer.extend_from_slice(b"trailing bytes");
|
||||
socket.send_to(&longer, peer).unwrap();
|
||||
|
||||
let shorter = echo_reply_packet(
|
||||
TOKEN,
|
||||
seqs[1],
|
||||
&server_params,
|
||||
&TimestampFields::default(),
|
||||
None,
|
||||
);
|
||||
socket.send_to(&shorter, peer).unwrap();
|
||||
});
|
||||
let config = ClientConfig {
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(200)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
client.send_probe().unwrap();
|
||||
client.send_probe().unwrap();
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
|
||||
let _ = client.recv_once().unwrap();
|
||||
let events = client.recv_once().unwrap();
|
||||
assert_eq!(events.len(), 1);
|
||||
match &events[0] {
|
||||
ClientEvent::EchoReply { seq, bytes, .. } => {
|
||||
assert_eq!(*seq, 1);
|
||||
assert_eq!(*bytes, echo_packet_len(false, ¶ms));
|
||||
}
|
||||
other => panic!("expected EchoReply after shorter datagram, got {other:?}"),
|
||||
}
|
||||
server.join();
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
#[cfg(all(target_os = "linux", feature = "ancillary"))]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[cfg(all(target_os = "linux", feature = "ancillary"))]
|
||||
fn echo_reply_metadata_propagates_observed_dscp_with_ancillary() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
let reply = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None);
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
|
||||
let mut buf = [0_u8; 2048];
|
||||
let (size, _) = socket.recv_from(&mut buf).unwrap();
|
||||
tx.send(buf[..size].to_vec()).unwrap();
|
||||
let seq = u32::from_le_bytes(buf[12..16].try_into().unwrap());
|
||||
crate::socket_options::apply_traffic_class_to_socket(&socket, peer, 184).unwrap();
|
||||
let reply_packet =
|
||||
echo_reply_packet(TOKEN, seq, ¶ms, &TimestampFields::default(), None);
|
||||
socket.send_to(&reply_packet, peer).unwrap();
|
||||
});
|
||||
let config = ClientConfig {
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(200)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
client.send_probe().unwrap();
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
|
||||
let events = client.recv_once().unwrap();
|
||||
assert_eq!(events.len(), 1);
|
||||
match &events[0] {
|
||||
ClientEvent::EchoReply { packet_meta, .. } => {
|
||||
let Some(traffic_class) = packet_meta.traffic_class else {
|
||||
metadata_unavailable_skip(
|
||||
"echo_reply_metadata_propagates_observed_dscp_with_ancillary",
|
||||
);
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
return;
|
||||
};
|
||||
assert_eq!(traffic_class, 184);
|
||||
assert_eq!(packet_meta.dscp, Some(46));
|
||||
assert_eq!(packet_meta.ecn, Some(0));
|
||||
}
|
||||
other => panic!("expected EchoReply, got {other:?}"),
|
||||
}
|
||||
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(all(target_os = "linux", feature = "ancillary"))]
|
||||
fn echo_reply_metadata_propagates_kernel_rx_timestamp_with_ancillary() {
|
||||
let params = default_params();
|
||||
let (mut client, server) = open_client_with_echo_server(¶ms);
|
||||
|
||||
client.send_probe().unwrap();
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
|
||||
let events = client.recv_once().unwrap();
|
||||
assert_eq!(events.len(), 1);
|
||||
match &events[0] {
|
||||
ClientEvent::EchoReply { packet_meta, .. } => {
|
||||
let Some(timestamp) = packet_meta.kernel_rx_timestamp else {
|
||||
kernel_rx_timestamp_unavailable_skip(
|
||||
"echo_reply_metadata_propagates_kernel_rx_timestamp_with_ancillary",
|
||||
);
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
return;
|
||||
};
|
||||
assert!(timestamp.duration_since(SystemTime::UNIX_EPOCH).is_ok());
|
||||
}
|
||||
other => panic!("expected EchoReply, got {other:?}"),
|
||||
}
|
||||
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn poll_timeouts_emits_echo_loss() {
|
||||
let params = default_params();
|
||||
let server = silent_open_server(params);
|
||||
let config = ClientConfig {
|
||||
probe_timeout: Duration::from_millis(100),
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(50)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
client.send_probe().unwrap();
|
||||
client.send_probe().unwrap();
|
||||
|
||||
let no_loss = client.poll_timeouts().unwrap();
|
||||
assert!(no_loss.is_empty());
|
||||
|
||||
thread::sleep(Duration::from_millis(150));
|
||||
let events = client.poll_timeouts().unwrap();
|
||||
assert_eq!(events.len(), 2);
|
||||
for event in &events {
|
||||
assert!(matches!(event, ClientEvent::EchoLoss { .. }));
|
||||
}
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn late_reply_after_timeout_preserves_measurement_metadata() {
|
||||
let params = default_params();
|
||||
let server = start_fake_server(move |socket, tx| {
|
||||
let (_, peer) = recv_request(&socket, &tx);
|
||||
let reply = open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms, None);
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
|
||||
let mut buf = [0_u8; 2048];
|
||||
let (size, _) = socket.recv_from(&mut buf).unwrap();
|
||||
tx.send(buf[..size].to_vec()).unwrap();
|
||||
let seq = u32::from_le_bytes(buf[12..16].try_into().unwrap());
|
||||
|
||||
thread::sleep(Duration::from_millis(90));
|
||||
let ts = TimestampFields {
|
||||
recv_wall: Some(1_000_000_000),
|
||||
recv_mono: Some(100_000),
|
||||
send_wall: Some(1_000_100_000),
|
||||
send_mono: Some(200_000),
|
||||
..Default::default()
|
||||
};
|
||||
let reply_packet = echo_reply_packet(TOKEN, seq, ¶ms, &ts, None);
|
||||
socket.send_to(&reply_packet, peer).unwrap();
|
||||
socket.send_to(&reply_packet, peer).unwrap();
|
||||
});
|
||||
let config = ClientConfig {
|
||||
probe_timeout: Duration::from_millis(40),
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(200)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
client.send_probe().unwrap();
|
||||
thread::sleep(Duration::from_millis(60));
|
||||
let losses = client.poll_timeouts().unwrap();
|
||||
assert!(matches!(&losses[0], ClientEvent::EchoLoss { seq: 0, .. }));
|
||||
|
||||
let late = client.recv_once().unwrap();
|
||||
match &late[0] {
|
||||
ClientEvent::LateReply {
|
||||
seq,
|
||||
sent_at,
|
||||
rtt,
|
||||
server_timing,
|
||||
one_way,
|
||||
bytes,
|
||||
packet_meta,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(*seq, 0);
|
||||
assert!(sent_at.is_some());
|
||||
assert!(rtt.is_some());
|
||||
assert!(server_timing.is_some());
|
||||
assert!(one_way.is_some());
|
||||
assert_eq!(*bytes, echo_packet_len(false, &default_params()));
|
||||
let _ = packet_meta;
|
||||
#[cfg(not(all(target_os = "linux", feature = "ancillary")))]
|
||||
assert_packet_meta_unavailable(packet_meta);
|
||||
}
|
||||
other => panic!("expected stats-eligible LateReply, got {other:?}"),
|
||||
}
|
||||
let duplicate = client.recv_once().unwrap();
|
||||
assert!(matches!(
|
||||
&duplicate[0],
|
||||
ClientEvent::DuplicateReply {
|
||||
seq: 0,
|
||||
bytes,
|
||||
..
|
||||
} if *bytes == echo_packet_len(false, &default_params())
|
||||
));
|
||||
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_full_does_not_send_packet() {
|
||||
let params = Params {
|
||||
duration_ns: 60_000_000_000,
|
||||
..default_params()
|
||||
};
|
||||
let server = silent_open_server(params);
|
||||
let config = ClientConfig {
|
||||
duration: Some(Duration::from_secs(60)),
|
||||
max_pending_probes: 2,
|
||||
socket_config: crate::SocketConfig {
|
||||
recv_timeout: Some(Duration::from_millis(50)),
|
||||
..Default::default()
|
||||
},
|
||||
..default_test_config(server.addr)
|
||||
};
|
||||
let mut client = Client::connect(config).unwrap();
|
||||
assert_open_started(client.open().unwrap());
|
||||
|
||||
client.send_probe().unwrap();
|
||||
client.send_probe().unwrap();
|
||||
|
||||
thread::sleep(Duration::from_millis(30));
|
||||
let before_count: Vec<_> = server.rx.try_iter().collect();
|
||||
let echo_before: Vec<_> = before_count
|
||||
.iter()
|
||||
.filter(|p| p.len() >= 4 && p[3] & FLAG_OPEN == 0 && p[3] & flags::FLAG_CLOSE == 0)
|
||||
.collect();
|
||||
assert_eq!(echo_before.len(), 2);
|
||||
|
||||
assert!(matches!(
|
||||
client.send_probe(),
|
||||
Err(ClientError::PendingLimitExceeded { limit: 2 })
|
||||
));
|
||||
|
||||
thread::sleep(Duration::from_millis(30));
|
||||
let after: Vec<_> = server.rx.try_iter().collect();
|
||||
let echo_after: Vec<_> = after
|
||||
.iter()
|
||||
.filter(|p| p.len() >= 4 && p[3] & FLAG_OPEN == 0 && p[3] & flags::FLAG_CLOSE == 0)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
echo_after.len(),
|
||||
0,
|
||||
"no packet should be sent when pending is full"
|
||||
);
|
||||
|
||||
client.close().unwrap();
|
||||
server.join();
|
||||
}
|
||||
@@ -1,192 +0,0 @@
|
||||
use super::*;
|
||||
use crate::metadata::ReceiveMeta;
|
||||
|
||||
#[test]
|
||||
fn server_processing_greater_than_raw_does_not_underflow() {
|
||||
let base = Instant::now();
|
||||
let rtt = compute_rtt(
|
||||
&ClientTimestamp {
|
||||
mono: base,
|
||||
wall: SystemTime::now(),
|
||||
},
|
||||
&ClientTimestamp {
|
||||
mono: base + Duration::from_nanos(1),
|
||||
wall: SystemTime::now(),
|
||||
},
|
||||
&TimestampFields {
|
||||
recv_mono: Some(0),
|
||||
send_mono: Some(1_000_000_000),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(rtt.adjusted, Some(SignedDuration::from_nanos(-999_999_999)));
|
||||
assert_eq!(rtt.effective, SignedDuration::from_nanos(-999_999_999));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effective_rtt_uses_raw_when_adjusted_rtt_is_unavailable() {
|
||||
let base = Instant::now();
|
||||
let rtt = compute_rtt(
|
||||
&ClientTimestamp {
|
||||
mono: base,
|
||||
wall: SystemTime::now(),
|
||||
},
|
||||
&ClientTimestamp {
|
||||
mono: base + Duration::from_nanos(42),
|
||||
wall: SystemTime::now(),
|
||||
},
|
||||
&TimestampFields::default(),
|
||||
);
|
||||
|
||||
assert_eq!(rtt.adjusted, None);
|
||||
assert_eq!(rtt.effective, SignedDuration::from_duration(rtt.raw));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unix_epoch_ns_i64_rejects_out_of_range_wall_time() {
|
||||
let i64_max_ns = u64::try_from(i64::MAX).unwrap();
|
||||
let max = SystemTime::UNIX_EPOCH + Duration::from_nanos(i64_max_ns);
|
||||
let overflow = max + Duration::from_nanos(1);
|
||||
|
||||
assert_eq!(unix_epoch_ns_i64(max), Some(i64::MAX));
|
||||
assert_eq!(unix_epoch_ns_i64(overflow), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_one_way_omits_samples_when_client_wall_time_overflows_i64() {
|
||||
let i64_max_ns = u64::try_from(i64::MAX).unwrap();
|
||||
let overflow_wall =
|
||||
SystemTime::UNIX_EPOCH + Duration::from_nanos(i64_max_ns) + Duration::from_nanos(1);
|
||||
let sent_at = ClientTimestamp {
|
||||
mono: Instant::now(),
|
||||
wall: overflow_wall,
|
||||
};
|
||||
let received_at = ClientTimestamp {
|
||||
mono: sent_at.mono + Duration::from_millis(40),
|
||||
wall: overflow_wall + Duration::from_millis(40),
|
||||
};
|
||||
let ts = TimestampFields {
|
||||
recv_wall: Some(i64::MAX),
|
||||
send_wall: Some(i64::MAX),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
compute_one_way(
|
||||
&sent_at,
|
||||
sent_at.wall,
|
||||
&received_at,
|
||||
None,
|
||||
&ReceiveMeta::default(),
|
||||
&ts
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_one_way_returns_available_direction_samples() {
|
||||
let sent_at = ClientTimestamp {
|
||||
mono: Instant::now(),
|
||||
wall: SystemTime::UNIX_EPOCH + Duration::from_secs(10),
|
||||
};
|
||||
let received_at = ClientTimestamp {
|
||||
mono: sent_at.mono + Duration::from_millis(40),
|
||||
wall: SystemTime::UNIX_EPOCH + Duration::from_secs(10) + Duration::from_millis(40),
|
||||
};
|
||||
let ts = TimestampFields {
|
||||
recv_wall: Some(10_000_000_000 + 15_000_000),
|
||||
send_wall: Some(10_000_000_000 + 25_000_000),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let sample = compute_one_way(
|
||||
&sent_at,
|
||||
sent_at.wall,
|
||||
&received_at,
|
||||
None,
|
||||
&ReceiveMeta::default(),
|
||||
&ts,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
sample.client_to_server,
|
||||
Some(SignedDuration::from_nanos(15_000_000))
|
||||
);
|
||||
assert_eq!(
|
||||
sample.server_to_client,
|
||||
Some(SignedDuration::from_nanos(15_000_000))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_one_way_preserves_negative_client_to_server_delay() {
|
||||
let sent_at = ClientTimestamp {
|
||||
mono: Instant::now(),
|
||||
wall: SystemTime::UNIX_EPOCH + Duration::from_secs(10),
|
||||
};
|
||||
let received_at = ClientTimestamp {
|
||||
mono: sent_at.mono + Duration::from_millis(40),
|
||||
wall: SystemTime::UNIX_EPOCH + Duration::from_secs(10) + Duration::from_millis(40),
|
||||
};
|
||||
let ts = TimestampFields {
|
||||
recv_wall: Some(10_000_000_000 - 5_000_000),
|
||||
send_wall: Some(10_000_000_000 + 25_000_000),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let sample = compute_one_way(
|
||||
&sent_at,
|
||||
sent_at.wall,
|
||||
&received_at,
|
||||
None,
|
||||
&ReceiveMeta::default(),
|
||||
&ts,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
sample.client_to_server,
|
||||
Some(SignedDuration::from_nanos(-5_000_000))
|
||||
);
|
||||
assert_eq!(
|
||||
sample.server_to_client,
|
||||
Some(SignedDuration::from_nanos(15_000_000))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_one_way_preserves_negative_server_to_client_delay() {
|
||||
let sent_at = ClientTimestamp {
|
||||
mono: Instant::now(),
|
||||
wall: SystemTime::UNIX_EPOCH + Duration::from_secs(10),
|
||||
};
|
||||
let received_at = ClientTimestamp {
|
||||
mono: sent_at.mono + Duration::from_millis(40),
|
||||
wall: SystemTime::UNIX_EPOCH + Duration::from_secs(10) + Duration::from_millis(40),
|
||||
};
|
||||
let ts = TimestampFields {
|
||||
recv_wall: Some(10_000_000_000 + 15_000_000),
|
||||
send_wall: Some(10_000_000_000 + 45_000_000),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let sample = compute_one_way(
|
||||
&sent_at,
|
||||
sent_at.wall,
|
||||
&received_at,
|
||||
None,
|
||||
&ReceiveMeta::default(),
|
||||
&ts,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
sample.client_to_server,
|
||||
Some(SignedDuration::from_nanos(15_000_000))
|
||||
);
|
||||
assert_eq!(
|
||||
sample.server_to_client,
|
||||
Some(SignedDuration::from_nanos(-5_000_000))
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,10 @@
|
||||
use super::*;
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::{
|
||||
probe::{CompletedSet, PendingMap, TimedOutMap},
|
||||
session::ActiveSession,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn sequence_ordering_handles_normal_and_wrapped_values() {
|
||||
@@ -18,10 +24,21 @@ fn sequence_ordering_handles_normal_and_wrapped_values() {
|
||||
|
||||
#[test]
|
||||
fn highest_received_seq_updates_across_wrap() {
|
||||
let mut highest = Some(u32::MAX);
|
||||
let mut session = ActiveSession {
|
||||
next_wire_seq: 0,
|
||||
highest_received_seq: Some(u32::MAX),
|
||||
packets_sent: 0,
|
||||
start_mono: Instant::now(),
|
||||
end_mono: None,
|
||||
next_send_at: Instant::now(),
|
||||
pending: PendingMap::new(8),
|
||||
timed_out: TimedOutMap::new(8),
|
||||
completed: CompletedSet::new(8),
|
||||
sending_done: false,
|
||||
};
|
||||
|
||||
update_highest_received(&mut highest, 0);
|
||||
assert_eq!(highest, Some(0));
|
||||
update_highest_received(&mut highest, u32::MAX);
|
||||
assert_eq!(highest, Some(0));
|
||||
update_highest_received(&mut session, 0);
|
||||
assert_eq!(session.highest_received_seq, Some(0));
|
||||
update_highest_received(&mut session, u32::MAX);
|
||||
assert_eq!(session.highest_received_seq, Some(0));
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::*;
|
||||
use irtt_proto::{
|
||||
echo_packet_len as checked_echo_packet_len, encode_echo_reply, encode_open_reply,
|
||||
flags::FLAG_OPEN, flags::FLAG_REPLY, layout::PacketLayout, Clock, EchoReply, OpenReply,
|
||||
ReceivedStats, StampAt,
|
||||
compute_hmac_in_place, echo_packet_len as checked_echo_packet_len, flags::FLAG_HMAC,
|
||||
flags::FLAG_OPEN, flags::FLAG_REPLY, layout::PacketLayout, Clock, ReceivedStats, StampAt,
|
||||
HMAC_SIZE, MAGIC,
|
||||
};
|
||||
use std::{
|
||||
net::UdpSocket,
|
||||
@@ -61,21 +61,23 @@ pub(super) fn open_reply(
|
||||
params: &Params,
|
||||
hmac_key: Option<&[u8]>,
|
||||
) -> Vec<u8> {
|
||||
encode_open_reply(
|
||||
&OpenReply {
|
||||
flags,
|
||||
token,
|
||||
params: params.clone(),
|
||||
},
|
||||
hmac_key,
|
||||
)
|
||||
.unwrap()
|
||||
let mut packet = Vec::new();
|
||||
packet.extend_from_slice(&MAGIC);
|
||||
packet.push(flags | hmac_key.map_or(0, |_| FLAG_HMAC));
|
||||
if hmac_key.is_some() {
|
||||
packet.extend_from_slice(&[0_u8; HMAC_SIZE]);
|
||||
}
|
||||
packet.extend_from_slice(&token.to_le_bytes());
|
||||
packet.extend_from_slice(¶ms.encode());
|
||||
if let Some(key) = hmac_key {
|
||||
compute_hmac_in_place(key, &mut packet, HMAC_OFFSET).unwrap();
|
||||
}
|
||||
packet
|
||||
}
|
||||
|
||||
/// Test params always name a representable length, so the platform
|
||||
/// representability check cannot fire here.
|
||||
pub(crate) fn echo_packet_len(hmac: bool, params: &Params) -> usize {
|
||||
checked_echo_packet_len(hmac, params).expect("test params must have a representable length")
|
||||
checked_echo_packet_len(hmac, params)
|
||||
.expect("test params must have a non-negative packet length")
|
||||
}
|
||||
|
||||
pub(super) fn echo_reply_packet(
|
||||
@@ -96,28 +98,55 @@ pub(super) fn echo_reply_packet_with_flags(
|
||||
hmac_key: Option<&[u8]>,
|
||||
flags: u8,
|
||||
) -> Vec<u8> {
|
||||
let layout = PacketLayout::echo(hmac_key.is_some(), params);
|
||||
let reply = EchoReply {
|
||||
flags,
|
||||
token,
|
||||
sequence: seq,
|
||||
recv_count: layout.recv_count.then_some(42),
|
||||
recv_window: layout.recv_window.then_some(0x07),
|
||||
timestamps: TimestampFields {
|
||||
recv_wall: layout.recv_wall.then(|| timestamps.recv_wall.unwrap_or(0)),
|
||||
recv_mono: layout.recv_mono.then(|| timestamps.recv_mono.unwrap_or(0)),
|
||||
midpoint_wall: layout
|
||||
.midpoint_wall
|
||||
.then(|| timestamps.midpoint_wall.unwrap_or(0)),
|
||||
midpoint_mono: layout
|
||||
.midpoint_mono
|
||||
.then(|| timestamps.midpoint_mono.unwrap_or(0)),
|
||||
send_wall: layout.send_wall.then(|| timestamps.send_wall.unwrap_or(0)),
|
||||
send_mono: layout.send_mono.then(|| timestamps.send_mono.unwrap_or(0)),
|
||||
},
|
||||
payload: Vec::new(),
|
||||
};
|
||||
encode_echo_reply(&reply, params, hmac_key).unwrap()
|
||||
let has_hmac = hmac_key.is_some();
|
||||
let layout = PacketLayout::echo(has_hmac, params);
|
||||
let packet_len = echo_packet_len(has_hmac, params);
|
||||
let mut packet = Vec::with_capacity(packet_len);
|
||||
|
||||
let mut flags = flags;
|
||||
if has_hmac {
|
||||
flags |= FLAG_HMAC;
|
||||
}
|
||||
packet.extend_from_slice(&MAGIC);
|
||||
packet.push(flags);
|
||||
if has_hmac {
|
||||
packet.extend_from_slice(&[0_u8; HMAC_SIZE]);
|
||||
}
|
||||
packet.extend_from_slice(&token.to_le_bytes());
|
||||
packet.extend_from_slice(&seq.to_le_bytes());
|
||||
|
||||
if layout.recv_count {
|
||||
packet.extend_from_slice(&42_u32.to_le_bytes());
|
||||
}
|
||||
if layout.recv_window {
|
||||
packet.extend_from_slice(&0x07_u64.to_le_bytes());
|
||||
}
|
||||
|
||||
if layout.recv_wall {
|
||||
packet.extend_from_slice(×tamps.recv_wall.unwrap_or(0).to_le_bytes());
|
||||
}
|
||||
if layout.recv_mono {
|
||||
packet.extend_from_slice(×tamps.recv_mono.unwrap_or(0).to_le_bytes());
|
||||
}
|
||||
if layout.midpoint_wall {
|
||||
packet.extend_from_slice(×tamps.midpoint_wall.unwrap_or(0).to_le_bytes());
|
||||
}
|
||||
if layout.midpoint_mono {
|
||||
packet.extend_from_slice(×tamps.midpoint_mono.unwrap_or(0).to_le_bytes());
|
||||
}
|
||||
if layout.send_wall {
|
||||
packet.extend_from_slice(×tamps.send_wall.unwrap_or(0).to_le_bytes());
|
||||
}
|
||||
if layout.send_mono {
|
||||
packet.extend_from_slice(×tamps.send_mono.unwrap_or(0).to_le_bytes());
|
||||
}
|
||||
|
||||
packet.resize(packet_len, 0);
|
||||
|
||||
if let Some(key) = hmac_key {
|
||||
compute_hmac_in_place(key, &mut packet, HMAC_OFFSET).unwrap();
|
||||
}
|
||||
packet
|
||||
}
|
||||
|
||||
pub(super) fn open_success_server(params: Params) -> FakeServer {
|
||||
|
||||
@@ -1,33 +1,12 @@
|
||||
use std::{net::SocketAddr, time::Duration};
|
||||
|
||||
/// Protocol compatibility bound for a requested `server_fill` value, in UTF-8
|
||||
/// bytes.
|
||||
///
|
||||
/// This is the maximum encoded server-fill string accepted by this client and
|
||||
/// protocol decoder. [`ClientConfig::server_fill`] enforces the same bound
|
||||
/// before opening a session.
|
||||
pub use irtt_proto::MAX_SERVER_FILL_BYTES;
|
||||
use irtt_proto::{Clock, ReceivedStats, StampAt};
|
||||
|
||||
pub(crate) const DEFAULT_PORT: u16 = 2112;
|
||||
/// Largest valid DSCP codepoint accepted by client configuration.
|
||||
///
|
||||
/// DSCP is a six-bit value in the range `0..=63`. The client shifts it left
|
||||
/// by two bits into the raw IP TOS / Traffic Class byte carried by
|
||||
/// [`irtt_proto::Params::dscp`] and applied to the socket during the active
|
||||
/// test phase.
|
||||
pub const MAX_DSCP_CODEPOINT: u8 = 63;
|
||||
/// Largest IPv4 TTL or IPv6 hop-limit value accepted by client configuration.
|
||||
///
|
||||
/// This is the public user-configuration bound for
|
||||
/// [`SocketConfig::ttl`]. A value of zero is rejected separately because socket
|
||||
/// TTL and hop-limit settings are configured as `1..=255`.
|
||||
pub const MAX_TTL: u32 = 255;
|
||||
/// Largest UDP payload length accepted by client configuration, in bytes.
|
||||
///
|
||||
/// This is the maximum UDP payload size excluding IP and UDP headers. It caps
|
||||
/// [`ClientConfig::length`] before protocol packets are encoded or sent.
|
||||
pub const MAX_UDP_PAYLOAD_LENGTH: u32 = 65_507;
|
||||
pub const MAX_SERVER_FILL_BYTES: usize = 32;
|
||||
pub(crate) const DEFAULT_DURATION: Duration = Duration::from_secs(3);
|
||||
pub(crate) const DEFAULT_INTERVAL: Duration = Duration::from_secs(1);
|
||||
pub(crate) const DEFAULT_OPEN_TIMEOUTS: [Duration; 4] = [
|
||||
@@ -40,114 +19,26 @@ pub(crate) const MIN_OPEN_TIMEOUT: Duration = Duration::from_millis(200);
|
||||
pub(crate) const DEFAULT_PROBE_TIMEOUT: Duration = Duration::from_secs(4);
|
||||
pub(crate) const DEFAULT_MAX_PENDING: usize = 4096;
|
||||
|
||||
/// Configuration for opening and running an IRTT client session.
|
||||
///
|
||||
/// This type describes both the protocol parameters sent in the IRTT open
|
||||
/// request and the local client behavior used to drive the UDP socket. Values
|
||||
/// that are negotiated by the server are available after opening the session
|
||||
/// through [`NegotiatedParams`](crate::NegotiatedParams).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientConfig {
|
||||
/// Remote server name or address.
|
||||
///
|
||||
/// If no port is present, the default IRTT port 2112 is used. IPv6
|
||||
/// literals may be supplied either bracketed or unbracketed when the
|
||||
/// default port should be used.
|
||||
pub server_addr: String,
|
||||
/// Requested run duration.
|
||||
///
|
||||
/// `Some(duration)` requests a finite test and must be greater than zero.
|
||||
/// `None` requests continuous mode and is encoded on the wire as a zero
|
||||
/// duration. Use [`RunMode::NoTest`] when the caller wants negotiation only
|
||||
/// without sending probes.
|
||||
pub duration: Option<Duration>,
|
||||
/// Requested spacing between probe sends.
|
||||
///
|
||||
/// The interval is encoded as nanoseconds in the open request and must be
|
||||
/// greater than zero. The server may return a different interval depending
|
||||
/// on the negotiated policy and server restrictions.
|
||||
pub interval: Duration,
|
||||
/// Requested echo packet payload length, in bytes.
|
||||
///
|
||||
/// The value must fit within the UDP payload limit after protocol overhead.
|
||||
/// A server may reduce the requested length during negotiation.
|
||||
pub length: u32,
|
||||
/// Requested server receive-statistics fields in echo replies.
|
||||
pub received_stats: ReceivedStats,
|
||||
/// Requested timestamp placement in echo replies.
|
||||
pub stamp_at: StampAt,
|
||||
/// Requested server clock sources for timestamp fields.
|
||||
///
|
||||
/// [`Clock::Unspecified`] is the wire default meaning "no clock tag was
|
||||
/// sent" and is not a client mode; opening a session with it is rejected.
|
||||
/// Request [`Clock::Wall`], [`Clock::Monotonic`], or [`Clock::Both`].
|
||||
pub clock: Clock,
|
||||
/// Requested DSCP codepoint.
|
||||
///
|
||||
/// This is the six-bit DSCP value, not the full traffic-class byte, and
|
||||
/// must be less than or equal to [`MAX_DSCP_CODEPOINT`].
|
||||
pub dscp: u8,
|
||||
/// Optional HMAC key used to authenticate IRTT packets.
|
||||
///
|
||||
/// When present, open, echo, and close packets are encoded and decoded with
|
||||
/// HMAC authentication. The peer must be configured with the same key.
|
||||
pub hmac_key: Option<Vec<u8>>,
|
||||
/// Optional server payload fill request.
|
||||
///
|
||||
/// `None` leaves server fill behavior unspecified. `Some(value)` requests
|
||||
/// a non-empty server fill mode/value and must not exceed
|
||||
/// [`MAX_SERVER_FILL_BYTES`] bytes when UTF-8 encoded.
|
||||
pub server_fill: Option<String>,
|
||||
/// Per-attempt receive timeouts used while opening the session.
|
||||
///
|
||||
/// The client sends an open request for each entry until a valid open reply
|
||||
/// is received. The list must not be empty, and each timeout must be at
|
||||
/// least 200 ms.
|
||||
pub open_timeouts: Vec<Duration>,
|
||||
/// Whether opening the session should start a probe test or perform a
|
||||
/// negotiation-only no-test exchange.
|
||||
pub run_mode: RunMode,
|
||||
/// Policy for server changes to negotiable protocol parameters.
|
||||
pub negotiation_policy: NegotiationPolicy,
|
||||
/// Local UDP socket configuration.
|
||||
pub socket_config: SocketConfig,
|
||||
/// Time after sending a probe before the client reports it as lost.
|
||||
///
|
||||
/// This timeout is local client behavior; it is not negotiated with the
|
||||
/// server. It must be greater than zero.
|
||||
pub probe_timeout: Duration,
|
||||
/// Maximum number of probes tracked as pending/timed-out/completed.
|
||||
///
|
||||
/// This bounds memory used for reply classification and must be greater
|
||||
/// than zero. A very small value can reject sends when replies are still
|
||||
/// outstanding.
|
||||
pub max_pending_probes: usize,
|
||||
}
|
||||
|
||||
/// Authentication settings used by client sessions.
|
||||
///
|
||||
/// `ClientConfig` keeps its existing top-level HMAC field for source
|
||||
/// compatibility. Managed multi-target callers can use this smaller type for
|
||||
/// per-target auth overrides without carrying a full independent
|
||||
/// [`ClientConfig`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub struct ClientAuthConfig {
|
||||
/// Optional HMAC key used to authenticate IRTT packets.
|
||||
pub hmac_key: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl From<Option<Vec<u8>>> for ClientAuthConfig {
|
||||
fn from(hmac_key: Option<Vec<u8>>) -> Self {
|
||||
Self { hmac_key }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ClientAuthConfig> for Option<Vec<u8>> {
|
||||
fn from(auth: ClientAuthConfig) -> Self {
|
||||
auth.hmac_key
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ClientConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
@@ -171,65 +62,29 @@ impl Default for ClientConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Local UDP socket options used by [`ClientConfig`].
|
||||
///
|
||||
/// These settings affect how the client binds, resolves, and receives from the
|
||||
/// socket. They do not change the IRTT protocol parameters negotiated with the
|
||||
/// server.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub struct SocketConfig {
|
||||
/// Local address to bind before connecting the UDP socket.
|
||||
///
|
||||
/// `None` binds to an unspecified address with an ephemeral port matching
|
||||
/// the selected remote address family.
|
||||
pub bind_addr: Option<SocketAddr>,
|
||||
/// Optional IPv4 TTL or IPv6 hop limit applied to sent packets.
|
||||
///
|
||||
/// `None` leaves the platform default unchanged. Values must fit in the
|
||||
/// platform socket option range; [`MAX_TTL`] is the public configuration
|
||||
/// bound used by this crate.
|
||||
pub ttl: Option<u32>,
|
||||
/// Restrict name resolution to IPv4 addresses.
|
||||
pub ipv4_only: bool,
|
||||
/// Restrict name resolution to IPv6 addresses and set IPV6_V6ONLY for IPv6
|
||||
/// sockets.
|
||||
pub ipv6_only: bool,
|
||||
/// Socket read timeout used after the session is open.
|
||||
///
|
||||
/// `None` leaves reads blocking for APIs that perform a single receive.
|
||||
/// Managed sessions may replace `None` or long timeouts with a short
|
||||
/// timeout so cooperative cancellation can be observed promptly.
|
||||
pub recv_timeout: Option<Duration>,
|
||||
}
|
||||
|
||||
/// How strictly to handle server-side negotiation restrictions.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum NegotiationPolicy {
|
||||
/// Reject any negotiated parameter that is more restrictive or different
|
||||
/// than requested.
|
||||
Strict,
|
||||
/// Accept documented server restrictions and report them in
|
||||
/// [`NegotiatedParams`](crate::NegotiatedParams).
|
||||
Loose,
|
||||
}
|
||||
|
||||
/// Mode requested during the IRTT open exchange.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RunMode {
|
||||
/// Open a session and send echo probes for the negotiated run duration.
|
||||
Normal,
|
||||
/// Complete negotiation without running the echo probe test.
|
||||
NoTest,
|
||||
}
|
||||
|
||||
/// Bound for a single receive-drain operation.
|
||||
///
|
||||
/// This is used by lower-level callers that drive [`Client`](crate::Client)
|
||||
/// directly and want to cap how many datagrams are processed before returning
|
||||
/// to their own event loop.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct RecvBudget {
|
||||
/// Maximum number of datagrams to process before returning.
|
||||
pub max_packets: usize,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,189 +1,67 @@
|
||||
use std::{collections::TryReserveError, io, time::Duration};
|
||||
use std::{io, time::Duration};
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
/// Failure reported while configuring, opening, running, receiving, closing, or
|
||||
/// joining an IRTT client session.
|
||||
///
|
||||
/// Configuration validation errors usually require changing
|
||||
/// [`ClientConfig`](crate::ClientConfig) or related options before retrying.
|
||||
/// Network, protocol, and runtime errors may be transient, but can also reflect
|
||||
/// peer incompatibility or an invalid session state.
|
||||
#[derive(Debug, Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum ClientError {
|
||||
/// A Tokio-backed client operation was polled without a current runtime.
|
||||
#[cfg(feature = "tokio")]
|
||||
#[error("Tokio AsyncClient requires a current Tokio runtime")]
|
||||
NoTokioRuntime,
|
||||
/// The configured server address could not be resolved to a socket address.
|
||||
///
|
||||
/// Check the host, port, address-family restrictions, and name service
|
||||
/// configuration before retrying.
|
||||
#[error("failed to resolve server address {addr:?}")]
|
||||
Resolve { addr: String },
|
||||
/// A UDP socket operation failed while binding, connecting, sending, or
|
||||
/// receiving.
|
||||
///
|
||||
/// This can be a transient network or OS error, but may also reflect local
|
||||
/// permissions, routing, or socket configuration.
|
||||
#[error("socket error: {0}")]
|
||||
Socket(#[from] io::Error),
|
||||
/// Applying or reading a socket option failed.
|
||||
///
|
||||
/// This is usually caused by an unsupported option, an invalid local value,
|
||||
/// or a platform-specific socket limitation. Changing socket configuration
|
||||
/// is more likely to help than retrying unchanged.
|
||||
#[error("socket option error while trying to {operation} for {remote}: {source}")]
|
||||
SocketOption {
|
||||
operation: &'static str,
|
||||
remote: std::net::SocketAddr,
|
||||
source: io::Error,
|
||||
},
|
||||
/// Restoring the configured read timeout after open negotiation failed.
|
||||
///
|
||||
/// The prepared session was not committed, and the client remains
|
||||
/// connected rather than partially open.
|
||||
#[error("failed to restore configured socket read timeout after open negotiation: {source}")]
|
||||
ReadTimeoutRestore { source: io::Error },
|
||||
/// A packet failed IRTT protocol parsing or authentication.
|
||||
///
|
||||
/// Likely causes include malformed input, unsupported protocol data, or an
|
||||
/// HMAC mismatch between client and server.
|
||||
#[error("protocol error: {0}")]
|
||||
Protocol(#[from] irtt_proto::ProtoError),
|
||||
/// No valid open reply was received before all configured open attempts
|
||||
/// timed out.
|
||||
///
|
||||
/// Retrying can succeed when the server or network is temporarily
|
||||
/// unavailable. Persistent failures usually require changing the address,
|
||||
/// authentication key, server configuration, or timeout settings.
|
||||
#[error("all open requests timed out")]
|
||||
OpenTimeout,
|
||||
/// An open-attempt timeout is below the client's supported minimum.
|
||||
///
|
||||
/// Increase the configured timeout before retrying.
|
||||
#[error("open timeout {timeout:?} is below the minimum {minimum:?}")]
|
||||
OpenTimeoutTooSmall {
|
||||
timeout: Duration,
|
||||
minimum: Duration,
|
||||
},
|
||||
/// The configured open-attempt timeout list is empty.
|
||||
///
|
||||
/// Provide at least one timeout before opening the session.
|
||||
#[error("open_timeouts must not be empty")]
|
||||
NoOpenTimeouts,
|
||||
/// The server explicitly rejected the open request.
|
||||
///
|
||||
/// Retrying unchanged is unlikely to help unless the server configuration or
|
||||
/// load has changed.
|
||||
#[error("server rejected the open request")]
|
||||
ServerRejected,
|
||||
/// A no-test open request received a reply that did not have no-test close
|
||||
/// semantics.
|
||||
///
|
||||
/// This indicates an incompatible or unexpected peer response.
|
||||
#[error("unexpected no-test open reply")]
|
||||
UnexpectedNoTestReply,
|
||||
/// A no-test open reply included a connection token.
|
||||
///
|
||||
/// No-test negotiation must not establish a probe session, so a non-zero
|
||||
/// token indicates an incompatible or unexpected peer response.
|
||||
#[error("no-test reply included a non-zero connection token: {token}")]
|
||||
NonZeroNoTestToken { token: u64 },
|
||||
/// The peer replied with a protocol version different from the requested
|
||||
/// version.
|
||||
///
|
||||
/// This is a protocol compatibility error and requires compatible client
|
||||
/// and server versions.
|
||||
#[error("protocol version mismatch: requested {requested}, received {received}")]
|
||||
ProtocolVersionMismatch { requested: i64, received: i64 },
|
||||
/// The server returned a zero connection token for a normal test session.
|
||||
///
|
||||
/// A normal session requires a non-zero token to correlate echo traffic, so
|
||||
/// this indicates an invalid peer response.
|
||||
#[error("server returned a zero connection token")]
|
||||
ZeroToken,
|
||||
/// Negotiated parameters were rejected by the configured negotiation policy.
|
||||
///
|
||||
/// Use a less restrictive configuration or
|
||||
/// [`NegotiationPolicy::Loose`](crate::NegotiationPolicy::Loose) when the
|
||||
/// caller accepts documented server restrictions.
|
||||
#[error("strict negotiation rejected changed params: {reason}")]
|
||||
NegotiationRejected { reason: String },
|
||||
/// The requested operation requires an open session, but the client is only
|
||||
/// connected.
|
||||
#[error("client is not open")]
|
||||
NotOpen,
|
||||
/// The session is already open.
|
||||
///
|
||||
/// Continue running, receiving, or closing the existing session instead of
|
||||
/// opening it again.
|
||||
#[error("client session is already open")]
|
||||
AlreadyOpen,
|
||||
/// The no-test session has already completed.
|
||||
///
|
||||
/// Create a new client session to perform another negotiation.
|
||||
#[error("client session is already completed")]
|
||||
AlreadyCompleted,
|
||||
/// The session is already closed.
|
||||
///
|
||||
/// Create a new client session before opening or running another test.
|
||||
#[error("client session is already closed")]
|
||||
AlreadyClosed,
|
||||
/// A duration could not be represented as nanoseconds for scheduling or
|
||||
/// protocol encoding.
|
||||
///
|
||||
/// Use smaller configured or negotiated durations.
|
||||
#[error("duration is too large to encode as nanoseconds")]
|
||||
DurationOverflow,
|
||||
/// A client-maintained counter would overflow.
|
||||
///
|
||||
/// This is a runtime limit rather than a network failure. Start a new
|
||||
/// session if the test duration or send volume reaches this limit.
|
||||
#[error("counter {counter} overflowed")]
|
||||
CounterOverflow { counter: &'static str },
|
||||
/// Sending another probe would exceed the configured pending-probe limit.
|
||||
///
|
||||
/// Increase [`ClientConfig::max_pending_probes`](crate::ClientConfig::max_pending_probes),
|
||||
/// reduce send rate, or receive replies and timeouts more often before
|
||||
/// sending again.
|
||||
#[error("pending probe limit exceeded ({limit})")]
|
||||
PendingLimitExceeded { limit: usize },
|
||||
/// A wrapping wire sequence is still represented by an in-flight probe.
|
||||
///
|
||||
/// The existing probe must be replied to or timed out before that sequence
|
||||
/// can be reused.
|
||||
#[error("wire sequence {seq} is still pending")]
|
||||
PendingSequenceCollision { seq: u32 },
|
||||
/// A prepared probe no longer matches the session's next wire sequence.
|
||||
///
|
||||
/// Prepare the probe again after any intervening successful send.
|
||||
#[error(
|
||||
"prepared probe sequence {prepared_seq} is stale; next wire sequence is {next_wire_seq}"
|
||||
)]
|
||||
StalePreparedProbe {
|
||||
prepared_seq: u32,
|
||||
next_wire_seq: u32,
|
||||
},
|
||||
/// Reserving memory required by an operation failed before any datagram was
|
||||
/// sent or logical protocol state was changed.
|
||||
#[error("failed to reserve memory for {operation}: {source}")]
|
||||
AllocationFailed {
|
||||
operation: &'static str,
|
||||
#[source]
|
||||
source: TryReserveError,
|
||||
},
|
||||
/// UDP reported successful acceptance of a datagram with an unexpected
|
||||
/// byte count.
|
||||
///
|
||||
/// The send is committed locally before this transport invariant failure
|
||||
/// is returned because the kernel reported success.
|
||||
#[error("UDP accepted {actual} bytes for a {expected}-byte datagram")]
|
||||
DatagramLengthMismatch { expected: usize, actual: usize },
|
||||
/// Client configuration failed validation before the requested operation.
|
||||
///
|
||||
/// The reported reason names a value that must be changed before retrying.
|
||||
#[error("invalid configuration: {reason}")]
|
||||
InvalidConfig { reason: String },
|
||||
#[error("managed client worker thread panicked")]
|
||||
WorkerPanicked,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EventSubscriptionError {
|
||||
#[error("event subscription is disconnected")]
|
||||
Disconnected,
|
||||
}
|
||||
+23
-253
@@ -5,378 +5,139 @@ use std::{
|
||||
|
||||
use crate::{session::NegotiatedParams, timing::ClientTimestamp};
|
||||
|
||||
/// Result of the IRTT open exchange.
|
||||
///
|
||||
/// The lower-level [`Client`](crate::Client) API returns this before any echo
|
||||
/// probes are driven. Managed sessions publish the contained lifecycle event to
|
||||
/// subscribers immediately after a successful open.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum OpenOutcome {
|
||||
/// A normal probe session was opened.
|
||||
Started {
|
||||
/// Resolved remote socket address used by the UDP socket.
|
||||
remote: SocketAddr,
|
||||
/// Session token assigned by the server and used on echo/close packets.
|
||||
token: u64,
|
||||
/// Parameters returned by the server after negotiation.
|
||||
negotiated: NegotiatedParams,
|
||||
/// Lifecycle event corresponding to this outcome.
|
||||
event: ClientEvent,
|
||||
},
|
||||
/// A no-test open exchange completed without starting a probe session.
|
||||
NoTestCompleted {
|
||||
/// Resolved remote socket address used by the UDP socket.
|
||||
remote: SocketAddr,
|
||||
/// Parameters returned by the server after negotiation.
|
||||
negotiated: NegotiatedParams,
|
||||
/// Lifecycle event corresponding to this outcome.
|
||||
event: ClientEvent,
|
||||
},
|
||||
}
|
||||
|
||||
/// Event emitted by an IRTT client session.
|
||||
///
|
||||
/// Events form the public lifecycle and measurement stream for callers. UIs
|
||||
/// usually display lifecycle, warning, and per-packet events directly; summary
|
||||
/// reporting should aggregate `EchoSent`, `EchoReply`, `EchoLoss`,
|
||||
/// `LateReply`, and `DuplicateReply` events or pass the stream to
|
||||
/// `irtt-stats`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ClientEvent {
|
||||
/// A normal session has opened and is ready to send echo probes.
|
||||
SessionStarted {
|
||||
/// Resolved remote socket address.
|
||||
remote: SocketAddr,
|
||||
/// Session token assigned by the server.
|
||||
token: u64,
|
||||
/// Negotiated protocol parameters for this session.
|
||||
negotiated: NegotiatedParams,
|
||||
/// Client timestamp when the open reply was accepted.
|
||||
at: ClientTimestamp,
|
||||
},
|
||||
/// A negotiation-only no-test exchange completed.
|
||||
///
|
||||
/// No `EchoSent`, `EchoReply`, `EchoLoss`, or `SessionClosed` events are
|
||||
/// expected for this open outcome.
|
||||
NoTestCompleted {
|
||||
/// Resolved remote socket address.
|
||||
remote: SocketAddr,
|
||||
/// Negotiated protocol parameters returned by the server.
|
||||
negotiated: NegotiatedParams,
|
||||
/// Client timestamp when the open reply was accepted.
|
||||
at: ClientTimestamp,
|
||||
},
|
||||
/// The session closed locally or through an authenticated peer close.
|
||||
///
|
||||
/// For a peer close-flagged echo reply, the reply's measurement or
|
||||
/// classification event is emitted immediately before this event.
|
||||
/// Managed sessions disconnect event subscribers after the worker exits,
|
||||
/// while leaving already queued events available to drain.
|
||||
SessionClosed {
|
||||
/// Resolved remote socket address.
|
||||
remote: SocketAddr,
|
||||
/// Session token that was closed.
|
||||
token: u64,
|
||||
/// Client timestamp when the close request was sent.
|
||||
at: ClientTimestamp,
|
||||
},
|
||||
|
||||
/// An echo request was sent.
|
||||
///
|
||||
/// This records local scheduling and send-call timing. It does not imply a
|
||||
/// reply will arrive; callers should pair it with `EchoReply`, `EchoLoss`,
|
||||
/// `LateReply`, or `DuplicateReply` by sequence number when displaying
|
||||
/// packet lifecycle state.
|
||||
EchoSent {
|
||||
/// Wire sequence number sent in the echo request.
|
||||
seq: u32,
|
||||
/// Resolved remote socket address.
|
||||
remote: SocketAddr,
|
||||
/// Monotonic deadline at which the probe was scheduled to be sent.
|
||||
scheduled_at: Instant,
|
||||
/// Paired client wall/monotonic timestamp captured immediately after
|
||||
/// the successful UDP send completed. This is the RTT and userspace
|
||||
/// upstream one-way-delay fallback endpoint. The operational probe
|
||||
/// timeout deadline is computed from an earlier, private, pre-send
|
||||
/// timestamp instead — see the client crate's `AGENTS.md`.
|
||||
sent_at: ClientTimestamp,
|
||||
/// Number of bytes passed to the UDP socket.
|
||||
bytes: usize,
|
||||
/// Elapsed time spent in the socket send call, excluding protocol and
|
||||
/// scheduler commit work.
|
||||
send_call: Duration,
|
||||
/// Absolute difference between the scheduled send time and the
|
||||
/// post-send `sent_at` timestamp above.
|
||||
timer_error: Duration,
|
||||
},
|
||||
|
||||
/// First in-window reply for a pending echo request.
|
||||
///
|
||||
/// This is the primary successful measurement event. RTT and optional
|
||||
/// server timing/statistics fields should generally be aggregated from this
|
||||
/// variant.
|
||||
EchoReply {
|
||||
/// Wire sequence number from the echo reply.
|
||||
seq: u32,
|
||||
/// Resolved remote socket address.
|
||||
remote: SocketAddr,
|
||||
/// Client timestamp recorded immediately after the matching request
|
||||
/// finished sending (see `ClientEvent::EchoSent::sent_at`).
|
||||
sent_at: ClientTimestamp,
|
||||
/// Client timestamp recorded when the reply was received.
|
||||
received_at: ClientTimestamp,
|
||||
/// Round-trip timing sample for this reply.
|
||||
rtt: RttSample,
|
||||
/// Optional server-reported timestamps and processing time.
|
||||
server_timing: Option<ServerTiming>,
|
||||
/// Optional one-way delay values derived from client/server wall clocks.
|
||||
one_way: Option<OneWayDelaySample>,
|
||||
/// Optional server-reported received-statistics sample.
|
||||
received_stats: Option<ReceivedStatsSample>,
|
||||
/// UDP datagram size received from the socket.
|
||||
bytes: usize,
|
||||
/// Receive-side metadata observed outside the IRTT wire payload.
|
||||
packet_meta: PacketMeta,
|
||||
},
|
||||
|
||||
/// A sent echo request exceeded the local probe timeout before a reply was
|
||||
/// matched.
|
||||
///
|
||||
/// A later datagram for the same sequence may still arrive and will be
|
||||
/// reported as [`ClientEvent::LateReply`] rather than changing this event.
|
||||
EchoLoss {
|
||||
/// Wire sequence number that timed out.
|
||||
seq: u32,
|
||||
/// Client timestamp recorded immediately after the request finished
|
||||
/// sending (see `ClientEvent::EchoSent::sent_at`). The timeout
|
||||
/// deadline below is anchored to an earlier, private, pre-send
|
||||
/// timestamp, not to this one.
|
||||
sent_at: ClientTimestamp,
|
||||
/// Monotonic deadline at which the probe was declared lost.
|
||||
timeout_at: std::time::Instant,
|
||||
},
|
||||
|
||||
/// Additional reply for a sequence that was already completed.
|
||||
///
|
||||
/// Duplicates are not primary RTT samples. They are useful for diagnostics
|
||||
/// and packet counters, but should not be aggregated as successful first
|
||||
/// replies.
|
||||
DuplicateReply {
|
||||
/// Wire sequence number from the duplicate reply.
|
||||
seq: u32,
|
||||
/// Resolved remote socket address.
|
||||
remote: SocketAddr,
|
||||
/// Client timestamp recorded when the duplicate was received.
|
||||
received_at: ClientTimestamp,
|
||||
/// UDP datagram size received from the socket.
|
||||
bytes: usize,
|
||||
},
|
||||
|
||||
/// Reply for a sequence that was no longer pending.
|
||||
///
|
||||
/// This commonly means the probe had already been reported as lost, or the
|
||||
/// reply arrived out of the client's current tracking window. When the
|
||||
/// original send metadata is still retained, RTT and one-way timing are
|
||||
/// included; otherwise those fields are `None`.
|
||||
LateReply {
|
||||
/// Wire sequence number from the late reply.
|
||||
seq: u32,
|
||||
/// Highest sequence number accepted as an in-window first reply so far.
|
||||
highest_seen: u32,
|
||||
/// Resolved remote socket address.
|
||||
remote: SocketAddr,
|
||||
/// Original post-send client timestamp, when still retained (see
|
||||
/// `ClientEvent::EchoSent::sent_at`).
|
||||
sent_at: Option<ClientTimestamp>,
|
||||
/// Client timestamp recorded when the late reply was received.
|
||||
received_at: ClientTimestamp,
|
||||
/// RTT sample computed when the original send timestamp is available.
|
||||
rtt: Option<RttSample>,
|
||||
/// Optional server-reported timestamps and processing time.
|
||||
server_timing: Option<ServerTiming>,
|
||||
/// Optional one-way delay values derived from client/server wall clocks.
|
||||
one_way: Option<OneWayDelaySample>,
|
||||
/// Optional server-reported received-statistics sample.
|
||||
received_stats: Option<ReceivedStatsSample>,
|
||||
/// UDP datagram size received from the socket.
|
||||
bytes: usize,
|
||||
/// Receive-side metadata observed outside the IRTT wire payload.
|
||||
packet_meta: PacketMeta,
|
||||
},
|
||||
|
||||
/// Non-fatal condition observed while receiving or classifying packets.
|
||||
///
|
||||
/// Warning events are diagnostic. They do not close the session by
|
||||
/// themselves and are not measurement samples.
|
||||
Warning {
|
||||
/// Machine-readable warning category.
|
||||
kind: WarningKind,
|
||||
/// Human-readable diagnostic text.
|
||||
message: String,
|
||||
/// Client timestamp when the warning was emitted.
|
||||
at: ClientTimestamp,
|
||||
},
|
||||
}
|
||||
|
||||
/// Category for a non-fatal [`ClientEvent::Warning`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum WarningKind {
|
||||
/// A received datagram could not be decoded as a relevant IRTT packet.
|
||||
MalformedOrUnrelatedPacket,
|
||||
/// A decoded packet used a token that does not match the open session.
|
||||
WrongToken,
|
||||
/// A decoded reply could not be matched to tracked probe state.
|
||||
UntrackedReply,
|
||||
}
|
||||
|
||||
/// Round-trip timing for one echo reply.
|
||||
///
|
||||
/// `raw` is the client-observed elapsed time from sending the echo request to
|
||||
/// receiving the reply and is therefore non-negative. When the server reports
|
||||
/// enough monotonic timing to compute processing time, `adjusted` subtracts
|
||||
/// that server processing from `raw`. `effective` is the value used by reporting
|
||||
/// and statistics: adjusted when available, otherwise raw converted to a signed
|
||||
/// value.
|
||||
///
|
||||
/// Adjusted and effective RTT values are signed. They may be negative if the
|
||||
/// reported server processing time is greater than the raw client-observed RTT.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct RttSample {
|
||||
/// Client-observed RTT from send to receive.
|
||||
pub raw: Duration,
|
||||
/// Signed RTT adjusted for server processing when server processing is available.
|
||||
pub adjusted: Option<SignedDuration>,
|
||||
/// Signed effective RTT used by stats and CLI reporting.
|
||||
///
|
||||
/// This is `adjusted` when server processing is available, otherwise `raw`
|
||||
/// converted to a signed duration.
|
||||
pub effective: SignedDuration,
|
||||
pub adjusted: Option<Duration>,
|
||||
pub effective: Duration,
|
||||
pub adjusted_signed: Option<SignedDuration>,
|
||||
pub effective_signed: SignedDuration,
|
||||
}
|
||||
|
||||
/// Signed nanosecond-backed duration used for derived timing values.
|
||||
///
|
||||
/// This type preserves negative values that can arise after subtracting server
|
||||
/// processing time or comparing wall-clock timestamps from different hosts. It
|
||||
/// should not be used to represent raw elapsed wall-clock or monotonic time,
|
||||
/// which is non-negative and represented by [`Duration`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct SignedDuration {
|
||||
ns: i128,
|
||||
pub ns: i128,
|
||||
}
|
||||
|
||||
impl SignedDuration {
|
||||
/// Construct a signed duration from nanoseconds.
|
||||
pub const fn from_nanos(ns: i128) -> Self {
|
||||
Self { ns }
|
||||
}
|
||||
|
||||
/// Convert a non-negative [`Duration`] into a signed duration.
|
||||
///
|
||||
/// Durations larger than `i128::MAX` nanoseconds saturate to `i128::MAX`.
|
||||
pub fn from_duration(duration: Duration) -> Self {
|
||||
Self {
|
||||
ns: i128::try_from(duration.as_nanos()).unwrap_or(i128::MAX),
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the duration in nanoseconds.
|
||||
pub const fn as_nanos(self) -> i128 {
|
||||
self.ns
|
||||
}
|
||||
|
||||
/// Return the duration in whole microseconds, truncated toward zero.
|
||||
pub const fn as_micros(self) -> i128 {
|
||||
self.ns / 1_000
|
||||
}
|
||||
|
||||
/// Return the duration in whole milliseconds, truncated toward zero.
|
||||
pub const fn as_millis(self) -> i128 {
|
||||
self.ns / 1_000_000
|
||||
}
|
||||
|
||||
/// Return whether this duration is less than zero.
|
||||
pub const fn is_negative(self) -> bool {
|
||||
self.ns < 0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Duration> for SignedDuration {
|
||||
fn from(value: Duration) -> Self {
|
||||
Self::from_duration(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Server-reported timing fields decoded from an echo reply.
|
||||
///
|
||||
/// These values are optional because the negotiated timestamp mode, clock mode,
|
||||
/// server implementation, or packet contents may omit individual fields.
|
||||
/// Timestamp values are nanoseconds in the server's reported wall-clock or
|
||||
/// monotonic clock domain. `None` means unavailable; `Some(0)` means the server
|
||||
/// reported a zero timestamp.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ServerTiming {
|
||||
/// Server wall-clock receive timestamp, in nanoseconds.
|
||||
pub receive_wall_ns: Option<i64>,
|
||||
/// Server monotonic receive timestamp, in nanoseconds.
|
||||
pub receive_mono_ns: Option<i64>,
|
||||
/// Server wall-clock send timestamp, in nanoseconds.
|
||||
pub send_wall_ns: Option<i64>,
|
||||
/// Server monotonic send timestamp, in nanoseconds.
|
||||
pub send_mono_ns: Option<i64>,
|
||||
/// Server wall-clock midpoint timestamp, in nanoseconds.
|
||||
pub midpoint_wall_ns: Option<i64>,
|
||||
/// Server monotonic midpoint timestamp, in nanoseconds.
|
||||
pub midpoint_mono_ns: Option<i64>,
|
||||
/// Server processing time computed from monotonic receive/send timestamps.
|
||||
///
|
||||
/// `None` means the required monotonic timestamps were unavailable or
|
||||
/// unusable. `Some(Duration::ZERO)` means the computed processing interval
|
||||
/// was available and zero.
|
||||
pub processing: Option<Duration>,
|
||||
}
|
||||
|
||||
/// Directional one-way delay samples computed from wall-clock timestamps.
|
||||
///
|
||||
/// Each directional field is an `Option<SignedDuration>`. `None` means the
|
||||
/// required client or server wall-clock timestamp was unavailable, or the
|
||||
/// timestamp arithmetic was out of range. `Some(value)` means the delay was
|
||||
/// computed from available timestamps.
|
||||
///
|
||||
/// Negative computed values are preserved as `Some` instead of being clamped to
|
||||
/// zero or dropped. A negative one-way delay usually indicates wall-clock skew
|
||||
/// between the client and server.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct OneWayDelaySample {
|
||||
/// Client-to-server delay.
|
||||
///
|
||||
/// This is computed from the client send wall time and the server receive
|
||||
/// wall time when both are available.
|
||||
pub client_to_server: Option<SignedDuration>,
|
||||
/// Server-to-client delay.
|
||||
///
|
||||
/// This is computed from the server send wall time and the client receive
|
||||
/// wall time when both are available. The client receive endpoint is the
|
||||
/// kernel receive timestamp reported with the datagram when one is
|
||||
/// available and plausible for this receive, and the userspace receive wall
|
||||
/// time otherwise. RTT is unaffected and remains a userspace monotonic
|
||||
/// measurement.
|
||||
pub server_to_client: Option<SignedDuration>,
|
||||
pub client_to_server: Option<Duration>,
|
||||
pub server_to_client: Option<Duration>,
|
||||
}
|
||||
|
||||
/// Server-reported receive counters decoded from an echo reply.
|
||||
///
|
||||
/// These fields are optional because the negotiated received-statistics mode or
|
||||
/// server implementation may omit them. `None` means unavailable; `Some(0)`
|
||||
/// means the server reported the value and it was zero.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ReceivedStatsSample {
|
||||
/// Server-reported count of received packets, when available.
|
||||
pub count: Option<u32>,
|
||||
/// Raw server-reported receive window bitmap, when available.
|
||||
///
|
||||
/// The bitmap is preserved exactly as it appeared on the wire; the client
|
||||
/// does not interpret its bits.
|
||||
pub window: Option<u64>,
|
||||
}
|
||||
|
||||
@@ -389,11 +150,20 @@ pub struct PacketMeta {
|
||||
pub traffic_class: Option<u8>,
|
||||
pub dscp: Option<u8>,
|
||||
pub ecn: Option<u8>,
|
||||
/// Kernel software receive timestamp reported with the datagram, where the
|
||||
/// platform provides one.
|
||||
///
|
||||
/// This is the raw observed value, reported whether or not it was accepted
|
||||
/// as the downstream one-way delay endpoint. It is a kernel software
|
||||
/// timestamp, not a NIC hardware ingress time.
|
||||
pub kernel_rx_timestamp: Option<std::time::SystemTime>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::PacketMeta;
|
||||
|
||||
#[test]
|
||||
fn packet_meta_default_is_unavailable() {
|
||||
let meta = PacketMeta::default();
|
||||
|
||||
assert_eq!(meta.traffic_class, None);
|
||||
assert_eq!(meta.dscp, None);
|
||||
assert_eq!(meta.ecn, None);
|
||||
assert_eq!(meta.kernel_rx_timestamp, None);
|
||||
}
|
||||
}
|
||||
@@ -1,32 +1,14 @@
|
||||
//! Reusable client/session/event layer for IRTT-compatible probes.
|
||||
//!
|
||||
//! `irtt-client` opens IRTT-compatible sessions, sends echo probes, receives
|
||||
//! replies, classifies loss/late/duplicate packets, and emits [`ClientEvent`]
|
||||
//! values for callers to consume directly or aggregate with `irtt-stats`.
|
||||
//! With the `tokio` feature enabled, `AsyncClient` provides the same low-level
|
||||
//! lifecycle for callers that own a Tokio runtime and drive readiness directly.
|
||||
//!
|
||||
//! Timing values intentionally preserve signed measurement semantics. When
|
||||
//! server timing is available, [`RttSample::effective`] is adjusted for server
|
||||
//! processing and can be negative if the reported server processing time exceeds
|
||||
//! the raw client-observed RTT. Directional [`OneWayDelaySample`] values are
|
||||
//! also signed when the required wall-clock timestamps are available; negative
|
||||
//! values usually indicate client/server clock skew.
|
||||
//!
|
||||
//! [`Client`] is the runtime-free low-level blocking adapter. With the
|
||||
//! `tokio` feature, `AsyncClient` provides the corresponding Tokio adapter;
|
||||
//! [`managed`] contains the unified managed task/handle implementation,
|
||||
//! including the dedicated-runtime blocking frontend for synchronous callers.
|
||||
//!
|
||||
#![forbid(unsafe_code)]
|
||||
#![cfg_attr(
|
||||
not(all(target_os = "linux", feature = "ancillary")),
|
||||
forbid(unsafe_code)
|
||||
)]
|
||||
#![cfg_attr(all(target_os = "linux", feature = "ancillary"), deny(unsafe_code))]
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
mod async_client;
|
||||
mod client;
|
||||
mod config;
|
||||
mod error;
|
||||
mod event;
|
||||
pub mod managed;
|
||||
mod managed;
|
||||
mod metadata;
|
||||
mod probe;
|
||||
mod receive;
|
||||
@@ -35,17 +17,19 @@ mod socket;
|
||||
mod socket_options;
|
||||
mod timing;
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
pub use async_client::AsyncClient;
|
||||
pub use client::Client;
|
||||
pub use config::{
|
||||
ClientAuthConfig, ClientConfig, NegotiationPolicy, RecvBudget, RunMode, SocketConfig,
|
||||
MAX_DSCP_CODEPOINT, MAX_SERVER_FILL_BYTES, MAX_TTL, MAX_UDP_PAYLOAD_LENGTH,
|
||||
ClientConfig, NegotiationPolicy, RecvBudget, RunMode, SocketConfig, MAX_DSCP_CODEPOINT,
|
||||
MAX_SERVER_FILL_BYTES, MAX_TTL, MAX_UDP_PAYLOAD_LENGTH,
|
||||
};
|
||||
pub use error::ClientError;
|
||||
pub use error::{ClientError, EventSubscriptionError};
|
||||
pub use event::{
|
||||
ClientEvent, OneWayDelaySample, OpenOutcome, PacketMeta, ReceivedStatsSample, RttSample,
|
||||
ServerTiming, SignedDuration, WarningKind,
|
||||
};
|
||||
pub use managed::{
|
||||
CancellationToken, EventHub, EventSubscription, ManagedClient, ManagedClientSession,
|
||||
SessionEndReason, SessionOutcome, SubscriberConfig, SubscriberOverflow,
|
||||
};
|
||||
pub use session::{NegotiatedParams, NegotiationRestriction};
|
||||
pub use timing::ClientTimestamp;
|
||||
@@ -1,183 +0,0 @@
|
||||
use std::{
|
||||
thread::{self, JoinHandle},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use thiserror::Error;
|
||||
use tokio::runtime::{Builder, Runtime};
|
||||
|
||||
use super::{
|
||||
ManagedClient, ManagedClientConfig, ManagedClientHandle, ManagedClientTask, ManagedConfigError,
|
||||
ManagedEventSubscription, ManagedOutcome, ManagedSubscribeError, ManagedTargetConfig,
|
||||
};
|
||||
|
||||
const BLOCKING_RUNTIME_SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(100);
|
||||
|
||||
/// Owns the runtime used exclusively by the blocking managed worker.
|
||||
pub(super) struct WorkerRuntime {
|
||||
runtime: Option<Runtime>,
|
||||
}
|
||||
|
||||
impl WorkerRuntime {
|
||||
pub(super) fn new(runtime: Runtime) -> Self {
|
||||
Self {
|
||||
runtime: Some(runtime),
|
||||
}
|
||||
}
|
||||
|
||||
fn block_on<F: std::future::Future>(&self, task: F) -> F::Output {
|
||||
self.runtime
|
||||
.as_ref()
|
||||
.expect("worker runtime is available until shutdown")
|
||||
.block_on(task)
|
||||
}
|
||||
|
||||
/// Shut down residual runtime work without delaying managed completion indefinitely.
|
||||
pub(super) fn shutdown(mut self) {
|
||||
self.runtime
|
||||
.take()
|
||||
.expect("worker runtime is available until shutdown")
|
||||
.shutdown_timeout(BLOCKING_RUNTIME_SHUTDOWN_TIMEOUT);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WorkerRuntime {
|
||||
fn drop(&mut self) {
|
||||
if let Some(runtime) = self.runtime.take() {
|
||||
runtime.shutdown_background();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Failure to start a blocking managed client owner.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum BlockingManagedStartError {
|
||||
/// The managed task configuration was invalid.
|
||||
#[error(transparent)]
|
||||
Config(#[from] ManagedConfigError),
|
||||
|
||||
/// The managed event subscription could not be created before startup.
|
||||
#[error(transparent)]
|
||||
Subscribe(#[from] ManagedSubscribeError),
|
||||
|
||||
/// The dedicated Tokio runtime could not be created.
|
||||
#[error("failed to create blocking managed Tokio runtime: {source}")]
|
||||
Runtime {
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
|
||||
/// The dedicated worker thread could not be spawned.
|
||||
#[error("failed to spawn blocking managed worker thread: {source}")]
|
||||
ThreadSpawn {
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
}
|
||||
|
||||
/// Failure to obtain completion from a blocking managed client owner.
|
||||
#[derive(Debug, Error, Eq, PartialEq)]
|
||||
pub enum BlockingManagedJoinError {
|
||||
/// The dedicated managed worker thread panicked.
|
||||
#[error("blocking managed worker thread panicked")]
|
||||
WorkerPanicked,
|
||||
}
|
||||
|
||||
/// Blocking completion owner for one unified managed Tokio task.
|
||||
///
|
||||
/// This owner runs exactly one [`ManagedClient`] task on one dedicated OS thread
|
||||
/// with its own current-thread Tokio runtime. Dropping a live owner requests a
|
||||
/// graceful stop and synchronously joins that worker, so drop may block while
|
||||
/// bounded managed cleanup completes.
|
||||
#[must_use = "dropping the blocking managed owner requests stop and joins its worker"]
|
||||
pub struct BlockingManagedClient {
|
||||
handle: ManagedClientHandle,
|
||||
worker: Option<JoinHandle<ManagedOutcome>>,
|
||||
}
|
||||
|
||||
impl BlockingManagedClient {
|
||||
/// Validate configuration, create a dedicated runtime, and start its worker.
|
||||
pub fn start(
|
||||
config: ManagedClientConfig,
|
||||
targets: Vec<ManagedTargetConfig>,
|
||||
) -> Result<Self, BlockingManagedStartError> {
|
||||
let (task, handle) = ManagedClient::task(config, targets)?;
|
||||
Self::start_task(task, handle)
|
||||
}
|
||||
|
||||
/// Validate configuration, subscribe to presentation events, and start a
|
||||
/// dedicated managed worker.
|
||||
///
|
||||
/// The returned subscription exists before the managed task receives its
|
||||
/// first poll, so it cannot miss startup events because of subscription
|
||||
/// ordering.
|
||||
pub fn start_with_subscription(
|
||||
config: ManagedClientConfig,
|
||||
targets: Vec<ManagedTargetConfig>,
|
||||
) -> Result<(Self, ManagedEventSubscription), BlockingManagedStartError> {
|
||||
let (task, handle) = ManagedClient::task(config, targets)?;
|
||||
let subscription = handle.subscribe()?;
|
||||
let owner = Self::start_task(task, handle)?;
|
||||
Ok((owner, subscription))
|
||||
}
|
||||
|
||||
fn start_task(
|
||||
task: ManagedClientTask,
|
||||
handle: ManagedClientHandle,
|
||||
) -> Result<Self, BlockingManagedStartError> {
|
||||
let runtime = Builder::new_current_thread()
|
||||
.enable_io()
|
||||
.enable_time()
|
||||
.build()
|
||||
.map_err(|source| BlockingManagedStartError::Runtime { source })?;
|
||||
let runtime = WorkerRuntime::new(runtime);
|
||||
let worker = thread::Builder::new()
|
||||
.name("irtt-managed".to_owned())
|
||||
.spawn(move || {
|
||||
let outcome = runtime.block_on(task);
|
||||
runtime.shutdown();
|
||||
outcome
|
||||
})
|
||||
.map_err(|source| BlockingManagedStartError::ThreadSpawn { source })?;
|
||||
|
||||
Ok(Self {
|
||||
handle,
|
||||
worker: Some(worker),
|
||||
})
|
||||
}
|
||||
|
||||
/// Return a cloned managed control and observation capability.
|
||||
pub fn handle(&self) -> ManagedClientHandle {
|
||||
self.handle.clone()
|
||||
}
|
||||
|
||||
/// Wait synchronously for the managed task's authoritative outcome.
|
||||
pub fn join(mut self) -> Result<ManagedOutcome, BlockingManagedJoinError> {
|
||||
self.join_worker()
|
||||
}
|
||||
|
||||
fn join_worker(&mut self) -> Result<ManagedOutcome, BlockingManagedJoinError> {
|
||||
join_worker(
|
||||
self.worker
|
||||
.take()
|
||||
.expect("blocking managed worker is joined at most once"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn join_worker(
|
||||
worker: JoinHandle<ManagedOutcome>,
|
||||
) -> Result<ManagedOutcome, BlockingManagedJoinError> {
|
||||
worker
|
||||
.join()
|
||||
.map_err(|_| BlockingManagedJoinError::WorkerPanicked)
|
||||
}
|
||||
|
||||
impl Drop for BlockingManagedClient {
|
||||
fn drop(&mut self) {
|
||||
if self.worker.is_some() {
|
||||
let _receipt = self.handle.stop();
|
||||
let _ = self.join_worker();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,393 +0,0 @@
|
||||
use std::{
|
||||
net::{SocketAddr, UdpSocket},
|
||||
sync::{mpsc::sync_channel, Arc, Condvar, Mutex},
|
||||
thread::{self, JoinHandle},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use irtt_proto::{
|
||||
decode_request, encode_echo_reply, encode_open_reply, flags, DecodedRequestKind, EchoReply,
|
||||
OpenReply, Params, ReceivedStats, StampAt, TimestampFields,
|
||||
};
|
||||
use tokio::{runtime::Builder, time::timeout};
|
||||
|
||||
use super::{
|
||||
blocking::{join_worker, WorkerRuntime},
|
||||
BlockingManagedClient, BlockingManagedJoinError, ManagedClientConfig, ManagedCompletionPolicy,
|
||||
ManagedEndReason, ManagedEvent, ManagedLifecycle, ManagedPacing, ManagedTargetConfig,
|
||||
ManagedTargetEndReason,
|
||||
};
|
||||
use crate::ClientConfig;
|
||||
|
||||
const TOKEN: u64 = 0x1234_5678_90ab_cdef;
|
||||
|
||||
struct Signal {
|
||||
value: Mutex<bool>,
|
||||
ready: Condvar,
|
||||
}
|
||||
|
||||
impl Signal {
|
||||
fn set(&self) {
|
||||
*self.value.lock().unwrap() = true;
|
||||
self.ready.notify_all();
|
||||
}
|
||||
|
||||
fn wait(&self) {
|
||||
let value = self.value.lock().unwrap();
|
||||
let (value, timeout) = self
|
||||
.ready
|
||||
.wait_timeout_while(value, Duration::from_secs(2), |value| !*value)
|
||||
.unwrap();
|
||||
assert!(*value && !timeout.timed_out());
|
||||
}
|
||||
}
|
||||
|
||||
struct EchoServer {
|
||||
addr: SocketAddr,
|
||||
probe: Arc<Signal>,
|
||||
close: Arc<Signal>,
|
||||
worker: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl EchoServer {
|
||||
fn start() -> Self {
|
||||
let socket = UdpSocket::bind("127.0.0.1:0").unwrap();
|
||||
socket
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.unwrap();
|
||||
let addr = socket.local_addr().unwrap();
|
||||
let probe = Arc::new(Signal {
|
||||
value: Mutex::new(false),
|
||||
ready: Condvar::new(),
|
||||
});
|
||||
let close = Arc::new(Signal {
|
||||
value: Mutex::new(false),
|
||||
ready: Condvar::new(),
|
||||
});
|
||||
let worker_probe = Arc::clone(&probe);
|
||||
let worker_close = Arc::clone(&close);
|
||||
let worker = thread::spawn(move || {
|
||||
let mut buffer = [0_u8; 8192];
|
||||
let (open_len, peer) = socket.recv_from(&mut buffer).unwrap();
|
||||
let negotiated = match decode_request(&buffer[..open_len]).unwrap().kind {
|
||||
DecodedRequestKind::Open { params, .. } => Params::decode(params).unwrap(),
|
||||
other => panic!("expected an open request, got {other:?}"),
|
||||
};
|
||||
let reply = encode_open_reply(
|
||||
&OpenReply {
|
||||
flags: flags::FLAG_OPEN | flags::FLAG_REPLY,
|
||||
token: TOKEN,
|
||||
params: negotiated.clone(),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
socket.send_to(&reply, peer).unwrap();
|
||||
|
||||
loop {
|
||||
let (len, packet_peer) = socket.recv_from(&mut buffer).unwrap();
|
||||
let Ok(request) = decode_request(&buffer[..len]) else {
|
||||
continue;
|
||||
};
|
||||
match request.kind {
|
||||
DecodedRequestKind::Echo { sequence, .. } => {
|
||||
worker_probe.set();
|
||||
let reply = encode_echo_reply(
|
||||
&EchoReply {
|
||||
flags: flags::FLAG_REPLY,
|
||||
token: TOKEN,
|
||||
sequence,
|
||||
recv_count: None,
|
||||
recv_window: None,
|
||||
timestamps: TimestampFields::default(),
|
||||
payload: Vec::new(),
|
||||
},
|
||||
&negotiated,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
socket.send_to(&reply, packet_peer).unwrap();
|
||||
}
|
||||
DecodedRequestKind::Close { .. } => {
|
||||
worker_close.set();
|
||||
return;
|
||||
}
|
||||
DecodedRequestKind::Open { .. } => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
Self {
|
||||
addr,
|
||||
probe,
|
||||
close,
|
||||
worker,
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_probe(&self) {
|
||||
self.probe.wait();
|
||||
}
|
||||
|
||||
fn wait_close(&self) {
|
||||
self.close.wait();
|
||||
}
|
||||
|
||||
fn finish(self) {
|
||||
self.worker.join().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn test_runtime() -> tokio::runtime::Runtime {
|
||||
Builder::new_current_thread()
|
||||
.enable_io()
|
||||
.enable_time()
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn config(completion: ManagedCompletionPolicy) -> ManagedClientConfig {
|
||||
ManagedClientConfig {
|
||||
client: ClientConfig {
|
||||
duration: Some(Duration::from_millis(120)),
|
||||
interval: Duration::from_millis(20),
|
||||
probe_timeout: Duration::from_millis(40),
|
||||
open_timeouts: vec![Duration::from_millis(200)],
|
||||
received_stats: ReceivedStats::None,
|
||||
stamp_at: StampAt::None,
|
||||
..ClientConfig::default()
|
||||
},
|
||||
pacing: ManagedPacing::Burst,
|
||||
completion,
|
||||
final_drain: Duration::from_millis(5),
|
||||
..ManagedClientConfig::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn target(server: &EchoServer) -> ManagedTargetConfig {
|
||||
ManagedTargetConfig::new("target", server.addr.to_string())
|
||||
}
|
||||
|
||||
fn assert_stopped(outcome: &super::ManagedOutcome) {
|
||||
assert_eq!(outcome.end_reason, ManagedEndReason::StopRequested);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starts_without_caller_runtime_and_finishes_naturally() {
|
||||
let server = EchoServer::start();
|
||||
let owner = BlockingManagedClient::start(
|
||||
config(ManagedCompletionPolicy::FinishWhenQuiescent),
|
||||
vec![target(&server)],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
server.wait_probe();
|
||||
let outcome = owner.join().unwrap();
|
||||
assert_eq!(outcome.end_reason, ManagedEndReason::TargetsComplete);
|
||||
assert_eq!(outcome.recent_target_outcomes.len(), 1);
|
||||
assert_eq!(
|
||||
outcome.recent_target_outcomes[0].end_reason,
|
||||
ManagedTargetEndReason::TestComplete
|
||||
);
|
||||
server.wait_close();
|
||||
server.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subscribed_start_captures_events_from_a_short_run() {
|
||||
let server = EchoServer::start();
|
||||
let (owner, mut events) = BlockingManagedClient::start_with_subscription(
|
||||
config(ManagedCompletionPolicy::FinishWhenQuiescent),
|
||||
vec![target(&server)],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
server.wait_probe();
|
||||
let outcome = owner.join().unwrap();
|
||||
assert_eq!(outcome.end_reason, ManagedEndReason::TargetsComplete);
|
||||
|
||||
let mut saw_started = false;
|
||||
let mut saw_finished = false;
|
||||
let mut saw_completed = false;
|
||||
while let Ok(event) = events.try_recv() {
|
||||
match event {
|
||||
ManagedEvent::Started => saw_started = true,
|
||||
ManagedEvent::TargetFinished { .. } => saw_finished = true,
|
||||
ManagedEvent::Completed { .. } => saw_completed = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert!(saw_started && saw_finished && saw_completed);
|
||||
server.wait_close();
|
||||
server.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_handle_stop_ends_with_graceful_close() {
|
||||
let server = EchoServer::start();
|
||||
let owner = BlockingManagedClient::start(
|
||||
config(ManagedCompletionPolicy::ExplicitStop),
|
||||
vec![target(&server)],
|
||||
)
|
||||
.unwrap();
|
||||
let handle = owner.handle();
|
||||
|
||||
server.wait_probe();
|
||||
test_runtime().block_on(async {
|
||||
timeout(Duration::from_secs(2), handle.stop())
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
let outcome = owner.join().unwrap();
|
||||
assert_stopped(&outcome);
|
||||
server.wait_close();
|
||||
server.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_update_reaches_background_worker() {
|
||||
let server = EchoServer::start();
|
||||
let owner = BlockingManagedClient::start(config(ManagedCompletionPolicy::ExplicitStop), vec![])
|
||||
.unwrap();
|
||||
let handle = owner.handle();
|
||||
|
||||
let acknowledgement = test_runtime().block_on(async {
|
||||
timeout(
|
||||
Duration::from_secs(2),
|
||||
handle.update_targets(vec![target(&server)]).unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
});
|
||||
assert_eq!(acknowledgement.sequence, 1);
|
||||
server.wait_probe();
|
||||
test_runtime().block_on(async {
|
||||
timeout(Duration::from_secs(2), owner.handle().stop())
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
assert_stopped(&owner.join().unwrap());
|
||||
server.wait_close();
|
||||
server.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_external_handles_does_not_stop_owner() {
|
||||
let server = EchoServer::start();
|
||||
let owner = BlockingManagedClient::start(
|
||||
config(ManagedCompletionPolicy::FinishWhenQuiescent),
|
||||
vec![target(&server)],
|
||||
)
|
||||
.unwrap();
|
||||
drop(owner.handle());
|
||||
drop(owner.handle());
|
||||
|
||||
server.wait_probe();
|
||||
assert_eq!(
|
||||
owner.join().unwrap().end_reason,
|
||||
ManagedEndReason::TargetsComplete
|
||||
);
|
||||
server.wait_close();
|
||||
server.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_owner_stops_and_joins_worker() {
|
||||
let server = EchoServer::start();
|
||||
let owner = BlockingManagedClient::start(
|
||||
config(ManagedCompletionPolicy::ExplicitStop),
|
||||
vec![target(&server)],
|
||||
)
|
||||
.unwrap();
|
||||
let handle = owner.handle();
|
||||
|
||||
server.wait_probe();
|
||||
drop(owner);
|
||||
let status = handle.status();
|
||||
assert_eq!(status.lifecycle, ManagedLifecycle::Completed);
|
||||
assert_eq!(
|
||||
status.final_outcome.as_ref().unwrap().end_reason,
|
||||
ManagedEndReason::StopRequested
|
||||
);
|
||||
server.wait_close();
|
||||
server.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_panic_is_a_join_error() {
|
||||
let worker = thread::spawn(|| -> super::ManagedOutcome { panic!("test worker panic") });
|
||||
assert_eq!(
|
||||
join_worker(worker),
|
||||
Err(BlockingManagedJoinError::WorkerPanicked)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_worker_runtime_inside_async_context_does_not_panic() {
|
||||
test_runtime().block_on(async {
|
||||
let runtime = Builder::new_current_thread()
|
||||
.enable_io()
|
||||
.enable_time()
|
||||
.build()
|
||||
.unwrap();
|
||||
drop(WorkerRuntime::new(runtime));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_runtime_shutdown_is_bounded_with_blocking_work() {
|
||||
let runtime = Builder::new_current_thread()
|
||||
.enable_io()
|
||||
.enable_time()
|
||||
.build()
|
||||
.unwrap();
|
||||
let (started_send, started_receive) = sync_channel(0);
|
||||
let (release_send, release_receive) = sync_channel(0);
|
||||
|
||||
runtime.block_on(async move {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
started_send.send(()).unwrap();
|
||||
release_receive.recv().unwrap();
|
||||
});
|
||||
});
|
||||
started_receive
|
||||
.recv_timeout(Duration::from_secs(2))
|
||||
.unwrap();
|
||||
|
||||
let started = Instant::now();
|
||||
WorkerRuntime::new(runtime).shutdown();
|
||||
assert!(started.elapsed() < Duration::from_secs(2));
|
||||
release_send.send(()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_after_natural_completion_preserves_outcome() {
|
||||
let server = EchoServer::start();
|
||||
let owner = BlockingManagedClient::start(
|
||||
config(ManagedCompletionPolicy::FinishWhenQuiescent),
|
||||
vec![target(&server)],
|
||||
)
|
||||
.unwrap();
|
||||
let handle = owner.handle();
|
||||
server.wait_probe();
|
||||
server.wait_close();
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
let status = loop {
|
||||
let status = handle.status();
|
||||
if status.lifecycle == ManagedLifecycle::Completed && status.final_outcome.is_some() {
|
||||
break status;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "managed worker did not complete");
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
};
|
||||
assert_eq!(
|
||||
status.final_outcome.as_ref().unwrap().end_reason,
|
||||
ManagedEndReason::TargetsComplete
|
||||
);
|
||||
drop(owner);
|
||||
assert_eq!(
|
||||
handle.status().final_outcome.as_ref().unwrap().end_reason,
|
||||
ManagedEndReason::TargetsComplete
|
||||
);
|
||||
server.finish();
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CancellationToken {
|
||||
cancelled: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl CancellationToken {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn cancel(&self) {
|
||||
self.cancelled.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn is_cancelled(&self) -> bool {
|
||||
self.cancelled.load(Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn token_starts_uncancelled() {
|
||||
assert!(!CancellationToken::new().is_cancelled());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_is_idempotent_and_visible_through_clones() {
|
||||
let token = CancellationToken::new();
|
||||
let clone = token.clone();
|
||||
|
||||
token.cancel();
|
||||
token.cancel();
|
||||
|
||||
assert!(token.is_cancelled());
|
||||
assert!(clone.is_cancelled());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
use std::{
|
||||
collections::{HashMap, VecDeque},
|
||||
sync::{
|
||||
atomic::{AtomicU64, Ordering},
|
||||
Arc, Condvar, Mutex, Weak,
|
||||
},
|
||||
};
|
||||
|
||||
use crate::{error::EventSubscriptionError, event::ClientEvent};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct SubscriberConfig {
|
||||
pub capacity: usize,
|
||||
pub overflow: SubscriberOverflow,
|
||||
}
|
||||
|
||||
impl Default for SubscriberConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
capacity: 1024,
|
||||
overflow: SubscriberOverflow::DropNewest,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Overflow behavior for a bounded event subscription queue.
|
||||
///
|
||||
/// These policies are applied independently per subscriber when that
|
||||
/// subscriber's queue is full.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SubscriberOverflow {
|
||||
/// Leave the existing queue unchanged and discard the newly published event.
|
||||
DropNewest,
|
||||
/// Remove the oldest queued event and enqueue the newly published event.
|
||||
DropOldest,
|
||||
/// Disconnect the subscriber and clear its queue.
|
||||
Disconnect,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EventHub {
|
||||
inner: Arc<HubInner>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct HubInner {
|
||||
next_id: AtomicU64,
|
||||
subscribers: Mutex<HashMap<u64, Arc<SubscriberInner>>>,
|
||||
}
|
||||
|
||||
/// Handle for receiving managed client events.
|
||||
///
|
||||
/// Each subscription has its own bounded queue configured by
|
||||
/// [`SubscriberConfig`]. The configured [`SubscriberOverflow`] policy applies
|
||||
/// when that queue is full. Dropping the handle unregisters the subscriber.
|
||||
#[must_use = "dropping the subscription unregisters it"]
|
||||
#[derive(Debug)]
|
||||
pub struct EventSubscription {
|
||||
id: u64,
|
||||
hub: Weak<HubInner>,
|
||||
inner: Arc<SubscriberInner>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SubscriberInner {
|
||||
state: Mutex<SubscriberState>,
|
||||
available: Condvar,
|
||||
config: SubscriberConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SubscriberState {
|
||||
queue: VecDeque<ClientEvent>,
|
||||
connected: bool,
|
||||
}
|
||||
|
||||
impl EventHub {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
inner: Arc::new(HubInner {
|
||||
next_id: AtomicU64::new(1),
|
||||
subscribers: Mutex::new(HashMap::new()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn subscribe(
|
||||
&self,
|
||||
config: SubscriberConfig,
|
||||
) -> Result<EventSubscription, crate::ClientError> {
|
||||
if config.capacity == 0 {
|
||||
return Err(crate::ClientError::InvalidConfig {
|
||||
reason: "subscriber capacity must be greater than zero".to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
let id = self.inner.next_id.fetch_add(1, Ordering::Relaxed);
|
||||
let inner = Arc::new(SubscriberInner {
|
||||
state: Mutex::new(SubscriberState {
|
||||
queue: VecDeque::with_capacity(config.capacity),
|
||||
connected: true,
|
||||
}),
|
||||
available: Condvar::new(),
|
||||
config,
|
||||
});
|
||||
self.inner
|
||||
.subscribers
|
||||
.lock()
|
||||
.expect("event hub mutex poisoned")
|
||||
.insert(id, inner.clone());
|
||||
|
||||
Ok(EventSubscription {
|
||||
id,
|
||||
hub: Arc::downgrade(&self.inner),
|
||||
inner,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn publish(&self, event: ClientEvent) {
|
||||
let subscribers: Vec<(u64, Arc<SubscriberInner>)> = self
|
||||
.inner
|
||||
.subscribers
|
||||
.lock()
|
||||
.expect("event hub mutex poisoned")
|
||||
.iter()
|
||||
.map(|(id, subscriber)| (*id, subscriber.clone()))
|
||||
.collect();
|
||||
|
||||
let mut disconnected = Vec::new();
|
||||
for (id, subscriber) in subscribers {
|
||||
// Events are cloned per subscriber; bounded queues keep slow
|
||||
// consumers from causing unbounded memory growth.
|
||||
if !subscriber.publish(event.clone()) {
|
||||
disconnected.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
if disconnected.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut subscribers = self
|
||||
.inner
|
||||
.subscribers
|
||||
.lock()
|
||||
.expect("event hub mutex poisoned");
|
||||
for id in disconnected {
|
||||
subscribers.remove(&id);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn disconnect_all(&self) {
|
||||
let subscribers: Vec<Arc<SubscriberInner>> = self
|
||||
.inner
|
||||
.subscribers
|
||||
.lock()
|
||||
.expect("event hub mutex poisoned")
|
||||
.drain()
|
||||
.map(|(_, subscriber)| subscriber)
|
||||
.collect();
|
||||
|
||||
for subscriber in subscribers {
|
||||
subscriber.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn subscriber_count(&self) -> usize {
|
||||
self.inner
|
||||
.subscribers
|
||||
.lock()
|
||||
.expect("event hub mutex poisoned")
|
||||
.len()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for EventHub {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl EventSubscription {
|
||||
/// Block until the next queued event is available.
|
||||
///
|
||||
/// If the subscription is disconnected, this returns
|
||||
/// [`EventSubscriptionError::Disconnected`] after any already queued events
|
||||
/// have been drained.
|
||||
pub fn recv(&self) -> Result<ClientEvent, EventSubscriptionError> {
|
||||
let mut state = self.inner.state.lock().expect("subscriber mutex poisoned");
|
||||
loop {
|
||||
if let Some(event) = state.queue.pop_front() {
|
||||
return Ok(event);
|
||||
}
|
||||
if !state.connected {
|
||||
return Err(EventSubscriptionError::Disconnected);
|
||||
}
|
||||
state = self
|
||||
.inner
|
||||
.available
|
||||
.wait(state)
|
||||
.expect("subscriber mutex poisoned");
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to receive one queued event without blocking.
|
||||
///
|
||||
/// Returns `Ok(None)` when the subscription is still connected but no event
|
||||
/// is queued. If the subscription is disconnected, this returns
|
||||
/// [`EventSubscriptionError::Disconnected`] after any already queued events
|
||||
/// have been drained.
|
||||
pub fn try_recv(&self) -> Result<Option<ClientEvent>, EventSubscriptionError> {
|
||||
let mut state = self.inner.state.lock().expect("subscriber mutex poisoned");
|
||||
if let Some(event) = state.queue.pop_front() {
|
||||
return Ok(Some(event));
|
||||
}
|
||||
if !state.connected {
|
||||
return Err(EventSubscriptionError::Disconnected);
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for EventSubscription {
|
||||
fn drop(&mut self) {
|
||||
self.inner.disconnect();
|
||||
if let Some(hub) = self.hub.upgrade() {
|
||||
hub.subscribers
|
||||
.lock()
|
||||
.expect("event hub mutex poisoned")
|
||||
.remove(&self.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SubscriberInner {
|
||||
fn publish(&self, event: ClientEvent) -> bool {
|
||||
let mut state = self.state.lock().expect("subscriber mutex poisoned");
|
||||
if !state.connected {
|
||||
return false;
|
||||
}
|
||||
|
||||
if state.queue.len() < self.config.capacity {
|
||||
state.queue.push_back(event);
|
||||
self.available.notify_one();
|
||||
return true;
|
||||
}
|
||||
|
||||
match self.config.overflow {
|
||||
SubscriberOverflow::DropNewest => true,
|
||||
SubscriberOverflow::DropOldest => {
|
||||
state.queue.pop_front();
|
||||
state.queue.push_back(event);
|
||||
self.available.notify_one();
|
||||
true
|
||||
}
|
||||
SubscriberOverflow::Disconnect => {
|
||||
state.queue.clear();
|
||||
state.connected = false;
|
||||
self.available.notify_all();
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn disconnect(&self) {
|
||||
let mut state = self.state.lock().expect("subscriber mutex poisoned");
|
||||
state.connected = false;
|
||||
self.available.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{ClientTimestamp, WarningKind};
|
||||
|
||||
fn event(n: usize) -> ClientEvent {
|
||||
ClientEvent::Warning {
|
||||
kind: WarningKind::UntrackedReply,
|
||||
message: format!("event-{n}"),
|
||||
at: ClientTimestamp::now(),
|
||||
}
|
||||
}
|
||||
|
||||
fn event_message(event: ClientEvent) -> String {
|
||||
match event {
|
||||
ClientEvent::Warning { message, .. } => message,
|
||||
other => panic!("unexpected event: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publishes_to_one_subscriber() {
|
||||
let hub = EventHub::new();
|
||||
let sub = hub.subscribe(SubscriberConfig::default()).unwrap();
|
||||
|
||||
hub.publish(event(1));
|
||||
|
||||
assert_eq!(event_message(sub.try_recv().unwrap().unwrap()), "event-1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publishes_to_multiple_subscribers() {
|
||||
let hub = EventHub::new();
|
||||
let a = hub.subscribe(SubscriberConfig::default()).unwrap();
|
||||
let b = hub.subscribe(SubscriberConfig::default()).unwrap();
|
||||
|
||||
hub.publish(event(1));
|
||||
|
||||
assert_eq!(event_message(a.try_recv().unwrap().unwrap()), "event-1");
|
||||
assert_eq!(event_message(b.try_recv().unwrap().unwrap()), "event-1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_newest_keeps_existing_events() {
|
||||
let hub = EventHub::new();
|
||||
let sub = hub
|
||||
.subscribe(SubscriberConfig {
|
||||
capacity: 1,
|
||||
overflow: SubscriberOverflow::DropNewest,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
hub.publish(event(1));
|
||||
hub.publish(event(2));
|
||||
|
||||
assert_eq!(event_message(sub.try_recv().unwrap().unwrap()), "event-1");
|
||||
assert!(sub.try_recv().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_oldest_replaces_existing_events() {
|
||||
let hub = EventHub::new();
|
||||
let sub = hub
|
||||
.subscribe(SubscriberConfig {
|
||||
capacity: 1,
|
||||
overflow: SubscriberOverflow::DropOldest,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
hub.publish(event(1));
|
||||
hub.publish(event(2));
|
||||
|
||||
assert_eq!(event_message(sub.try_recv().unwrap().unwrap()), "event-2");
|
||||
assert!(sub.try_recv().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disconnect_removes_full_subscriber() {
|
||||
let hub = EventHub::new();
|
||||
let sub = hub
|
||||
.subscribe(SubscriberConfig {
|
||||
capacity: 1,
|
||||
overflow: SubscriberOverflow::Disconnect,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
hub.publish(event(1));
|
||||
hub.publish(event(2));
|
||||
|
||||
assert_eq!(
|
||||
sub.try_recv().unwrap_err(),
|
||||
EventSubscriptionError::Disconnected
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_subscriber_does_not_prevent_other_delivery() {
|
||||
let hub = EventHub::new();
|
||||
let slow = hub
|
||||
.subscribe(SubscriberConfig {
|
||||
capacity: 1,
|
||||
overflow: SubscriberOverflow::DropNewest,
|
||||
})
|
||||
.unwrap();
|
||||
let fast = hub
|
||||
.subscribe(SubscriberConfig {
|
||||
capacity: 4,
|
||||
overflow: SubscriberOverflow::DropNewest,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
hub.publish(event(1));
|
||||
hub.publish(event(2));
|
||||
|
||||
assert_eq!(event_message(slow.try_recv().unwrap().unwrap()), "event-1");
|
||||
assert_eq!(event_message(fast.try_recv().unwrap().unwrap()), "event-1");
|
||||
assert_eq!(event_message(fast.try_recv().unwrap().unwrap()), "event-2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subscribing_after_events_does_not_replay() {
|
||||
let hub = EventHub::new();
|
||||
hub.publish(event(1));
|
||||
|
||||
let sub = hub.subscribe(SubscriberConfig::default()).unwrap();
|
||||
|
||||
assert!(sub.try_recv().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_subscription_unregisters_from_hub() {
|
||||
let hub = EventHub::new();
|
||||
let sub = hub.subscribe(SubscriberConfig::default()).unwrap();
|
||||
assert_eq!(hub.subscriber_count(), 1);
|
||||
|
||||
drop(sub);
|
||||
|
||||
assert_eq!(hub.subscriber_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disconnect_all_wakes_blocking_receivers() {
|
||||
let hub = EventHub::new();
|
||||
let sub = hub.subscribe(SubscriberConfig::default()).unwrap();
|
||||
hub.disconnect_all();
|
||||
|
||||
assert_eq!(
|
||||
sub.recv().unwrap_err(),
|
||||
EventSubscriptionError::Disconnected
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_closed_event_can_be_queued() {
|
||||
let hub = EventHub::new();
|
||||
let sub = hub.subscribe(SubscriberConfig::default()).unwrap();
|
||||
hub.publish(ClientEvent::SessionClosed {
|
||||
remote: "127.0.0.1:1".parse().unwrap(),
|
||||
token: 1,
|
||||
at: ClientTimestamp::now(),
|
||||
});
|
||||
|
||||
assert!(matches!(
|
||||
sub.recv().unwrap(),
|
||||
ClientEvent::SessionClosed { token: 1, .. }
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,7 @@
|
||||
mod target_id;
|
||||
mod cancellation;
|
||||
mod hub;
|
||||
mod runner;
|
||||
|
||||
pub use target_id::TargetId;
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
mod blocking;
|
||||
#[cfg(feature = "tokio")]
|
||||
mod model;
|
||||
#[cfg(feature = "tokio")]
|
||||
mod task;
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
pub use blocking::*;
|
||||
#[cfg(feature = "tokio")]
|
||||
pub use model::*;
|
||||
#[cfg(feature = "tokio")]
|
||||
pub use task::*;
|
||||
|
||||
#[cfg(all(feature = "tokio", test))]
|
||||
mod blocking_tests;
|
||||
pub use cancellation::CancellationToken;
|
||||
pub use hub::{EventHub, EventSubscription, SubscriberConfig, SubscriberOverflow};
|
||||
pub use runner::{ManagedClient, ManagedClientSession, SessionEndReason, SessionOutcome};
|
||||
@@ -1,647 +0,0 @@
|
||||
use std::{fmt, net::SocketAddr, sync::Arc, time::Duration};
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{ClientAuthConfig, ClientConfig, ClientError, ClientEvent};
|
||||
|
||||
use super::TargetId;
|
||||
|
||||
/// Default capacity of the lossy managed event channel.
|
||||
pub const DEFAULT_MANAGED_EVENT_CAPACITY: usize = 256;
|
||||
/// Default capacity of the bounded managed control queue.
|
||||
pub const DEFAULT_MANAGED_COMMAND_CAPACITY: usize = 64;
|
||||
/// Default number of recent target outcomes retained in status and output.
|
||||
pub const DEFAULT_MANAGED_OUTCOME_HISTORY_LIMIT: usize = 256;
|
||||
/// Default maximum number of simultaneously live target generations.
|
||||
pub const DEFAULT_MANAGED_MAX_LIVE_TARGET_GENERATIONS: usize = 256;
|
||||
/// Default time retained for late replies after the final committed timeout.
|
||||
pub const DEFAULT_MANAGED_FINAL_DRAIN: Duration = Duration::from_millis(100);
|
||||
|
||||
/// One globally allocated incarnation of a target within a managed task.
|
||||
///
|
||||
/// Generations increase globally across the task, not independently per ID.
|
||||
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub struct TargetInstance {
|
||||
pub id: TargetId,
|
||||
pub generation: u64,
|
||||
}
|
||||
|
||||
/// Endpoint and optional authentication override for one managed target.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ManagedTargetConfig {
|
||||
pub id: TargetId,
|
||||
pub server_addr: String,
|
||||
pub auth: Option<ClientAuthConfig>,
|
||||
}
|
||||
|
||||
impl ManagedTargetConfig {
|
||||
pub fn new(id: impl Into<TargetId>, server_addr: impl Into<String>) -> Self {
|
||||
Self {
|
||||
id: id.into(),
|
||||
server_addr: server_addr.into(),
|
||||
auth: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Coordination mode for sends across active targets.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub enum ManagedPacing {
|
||||
#[default]
|
||||
Staggered,
|
||||
Burst,
|
||||
}
|
||||
|
||||
/// Policy controlling top-level natural completion.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub enum ManagedCompletionPolicy {
|
||||
#[default]
|
||||
FinishWhenQuiescent,
|
||||
ExplicitStop,
|
||||
}
|
||||
|
||||
/// Shared configuration for one managed task.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ManagedClientConfig {
|
||||
pub client: ClientConfig,
|
||||
pub pacing: ManagedPacing,
|
||||
pub completion: ManagedCompletionPolicy,
|
||||
pub event_capacity: usize,
|
||||
pub command_capacity: usize,
|
||||
pub outcome_history_limit: usize,
|
||||
pub max_live_target_generations: usize,
|
||||
pub final_drain: Duration,
|
||||
}
|
||||
|
||||
impl Default for ManagedClientConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
client: ClientConfig::default(),
|
||||
pacing: ManagedPacing::default(),
|
||||
completion: ManagedCompletionPolicy::default(),
|
||||
event_capacity: DEFAULT_MANAGED_EVENT_CAPACITY,
|
||||
command_capacity: DEFAULT_MANAGED_COMMAND_CAPACITY,
|
||||
outcome_history_limit: DEFAULT_MANAGED_OUTCOME_HISTORY_LIMIT,
|
||||
max_live_target_generations: DEFAULT_MANAGED_MAX_LIVE_TARGET_GENERATIONS,
|
||||
final_drain: DEFAULT_MANAGED_FINAL_DRAIN,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Durable top-level lifecycle.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ManagedLifecycle {
|
||||
NotStarted,
|
||||
Running,
|
||||
Stopping,
|
||||
Completed,
|
||||
Failed,
|
||||
Abandoned,
|
||||
}
|
||||
|
||||
/// Durable lifecycle for one target generation.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ManagedTargetLifecycle {
|
||||
Pending,
|
||||
Connecting,
|
||||
Opening,
|
||||
Active,
|
||||
Draining,
|
||||
Closing,
|
||||
Terminal,
|
||||
}
|
||||
|
||||
/// Status for one target generation.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ManagedTargetStatus {
|
||||
pub target: TargetInstance,
|
||||
pub desired: bool,
|
||||
pub lifecycle: ManagedTargetLifecycle,
|
||||
pub server_addr: Arc<str>,
|
||||
pub remote: Option<SocketAddr>,
|
||||
}
|
||||
|
||||
/// Authoritative immutable managed status snapshot.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ManagedStatus {
|
||||
pub lifecycle: ManagedLifecycle,
|
||||
pub stop_requested: bool,
|
||||
pub applied_command_sequence: u64,
|
||||
pub desired_target_count: usize,
|
||||
pub connecting_target_count: usize,
|
||||
pub opening_target_count: usize,
|
||||
pub active_target_count: usize,
|
||||
pub draining_target_count: usize,
|
||||
pub closing_target_count: usize,
|
||||
pub terminal_target_count: usize,
|
||||
pub total_target_outcomes: u64,
|
||||
pub successful_target_outcomes: u64,
|
||||
pub failed_target_outcomes: u64,
|
||||
pub peer_closed_target_outcomes: u64,
|
||||
pub discarded_target_outcomes: u64,
|
||||
pub targets: Arc<[ManagedTargetStatus]>,
|
||||
pub recent_target_outcomes: Arc<[ManagedTargetOutcome]>,
|
||||
pub final_outcome: Option<Arc<ManagedOutcome>>,
|
||||
}
|
||||
|
||||
/// Lossy presentation event emitted by the managed task.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum ManagedEvent {
|
||||
Started,
|
||||
TargetStateChanged {
|
||||
target: TargetInstance,
|
||||
lifecycle: ManagedTargetLifecycle,
|
||||
},
|
||||
Client {
|
||||
target: TargetInstance,
|
||||
event: ClientEvent,
|
||||
},
|
||||
TargetFinished {
|
||||
outcome: Arc<ManagedTargetOutcome>,
|
||||
},
|
||||
Stopping,
|
||||
Completed {
|
||||
outcome: Arc<ManagedOutcome>,
|
||||
},
|
||||
Failed {
|
||||
outcome: Arc<ManagedOutcome>,
|
||||
},
|
||||
Abandoned,
|
||||
}
|
||||
|
||||
/// Receiving half of the lossy managed event stream.
|
||||
pub type ManagedEventSubscription = tokio::sync::broadcast::Receiver<ManagedEvent>;
|
||||
|
||||
/// Immediate result of attempting to receive a managed presentation event.
|
||||
pub type ManagedEventTryRecvError = tokio::sync::broadcast::error::TryRecvError;
|
||||
|
||||
/// Final authoritative outcome returned by the task.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ManagedOutcome {
|
||||
pub end_reason: ManagedEndReason,
|
||||
pub applied_command_sequence: u64,
|
||||
pub total_target_outcomes: u64,
|
||||
pub successful_target_outcomes: u64,
|
||||
pub failed_target_outcomes: u64,
|
||||
pub peer_closed_target_outcomes: u64,
|
||||
pub discarded_target_outcomes: u64,
|
||||
pub recent_target_outcomes: Arc<[ManagedTargetOutcome]>,
|
||||
}
|
||||
|
||||
/// Why the managed task ended.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum ManagedEndReason {
|
||||
TargetsComplete,
|
||||
StopRequested,
|
||||
DriverFailed(ManagedDriverFailure),
|
||||
}
|
||||
|
||||
/// Durable outcome for one target generation.
|
||||
///
|
||||
/// These counters are durable: unlike [`ManagedEvent`], which is a lossy
|
||||
/// presentation stream, they account for everything the target observed.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ManagedTargetOutcome {
|
||||
pub target: TargetInstance,
|
||||
pub server_addr: Arc<str>,
|
||||
pub remote: Option<SocketAddr>,
|
||||
pub end_reason: ManagedTargetEndReason,
|
||||
/// Probes the underlying client reported as sent.
|
||||
pub packets_sent: u64,
|
||||
/// Unique echo replies that arrived in order and before their probe timed
|
||||
/// out.
|
||||
///
|
||||
/// A unique reply that arrives behind an already-received sequence, or
|
||||
/// after its own probe timed out, is counted by `late` instead.
|
||||
pub replies_received: u64,
|
||||
/// Replies for a sequence that had already been answered.
|
||||
pub duplicates: u64,
|
||||
/// Late replies: those arriving behind an already-received sequence
|
||||
/// (reordering) or after their own probe timed out.
|
||||
///
|
||||
/// This counts every late reply, whether or not the client could still
|
||||
/// match it to retained send state.
|
||||
pub late: u64,
|
||||
/// Warning events observed for this target.
|
||||
pub warning_events: u64,
|
||||
pub cleanup_failure: Option<ManagedTargetFailure>,
|
||||
}
|
||||
|
||||
/// Why one target generation ended.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum ManagedTargetEndReason {
|
||||
TestComplete,
|
||||
NoTestComplete,
|
||||
PeerClosed,
|
||||
Removed,
|
||||
Replaced,
|
||||
Stopped,
|
||||
Failed(ManagedTargetFailure),
|
||||
}
|
||||
|
||||
/// Phase in which a target-local failure occurred.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ManagedTargetFailurePhase {
|
||||
Connecting,
|
||||
Opening,
|
||||
Sending,
|
||||
Receiving,
|
||||
Timing,
|
||||
Closing,
|
||||
}
|
||||
|
||||
impl fmt::Display for ManagedTargetFailurePhase {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let text = match self {
|
||||
Self::Connecting => "connecting",
|
||||
Self::Opening => "opening",
|
||||
Self::Sending => "sending",
|
||||
Self::Receiving => "receiving",
|
||||
Self::Timing => "timing",
|
||||
Self::Closing => "closing",
|
||||
};
|
||||
f.write_str(text)
|
||||
}
|
||||
}
|
||||
|
||||
/// Stable category for a target-local failure.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ManagedTargetFailureKind {
|
||||
Resolve,
|
||||
Socket,
|
||||
SocketOption,
|
||||
Protocol,
|
||||
Timeout,
|
||||
Configuration,
|
||||
ResourceExhausted,
|
||||
InvalidState,
|
||||
/// A failure that deliberately has no more specific category.
|
||||
///
|
||||
/// This is a classification decision, not a fallback: every current
|
||||
/// [`ClientError`] variant is classified explicitly, so nothing reaches
|
||||
/// this category by default.
|
||||
Other,
|
||||
}
|
||||
|
||||
impl fmt::Display for ManagedTargetFailureKind {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let text = match self {
|
||||
Self::Resolve => "resolve",
|
||||
Self::Socket => "socket",
|
||||
Self::SocketOption => "socket option",
|
||||
Self::Protocol => "protocol",
|
||||
Self::Timeout => "timeout",
|
||||
Self::Configuration => "configuration",
|
||||
Self::ResourceExhausted => "resource exhausted",
|
||||
Self::InvalidState => "invalid state",
|
||||
Self::Other => "other",
|
||||
};
|
||||
f.write_str(text)
|
||||
}
|
||||
}
|
||||
|
||||
/// Durable target-local failure details.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ManagedTargetFailure {
|
||||
pub phase: ManagedTargetFailurePhase,
|
||||
pub kind: ManagedTargetFailureKind,
|
||||
pub message: Arc<str>,
|
||||
}
|
||||
|
||||
/// Configuration failure detected before any runtime work begins.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ManagedConfigError {
|
||||
#[error("FinishWhenQuiescent requires at least one initial target")]
|
||||
EmptyInitialTargets,
|
||||
#[error("duplicate managed target id {id}")]
|
||||
DuplicateTargetId { id: TargetId },
|
||||
#[error("configured {configured} targets exceeds live-generation limit {limit}")]
|
||||
TooManyTargets { configured: usize, limit: usize },
|
||||
#[error("managed event capacity must be greater than zero")]
|
||||
ZeroEventCapacity,
|
||||
#[error("managed event capacity {configured} exceeds Tokio's maximum {maximum}")]
|
||||
EventCapacityTooLarge { configured: usize, maximum: usize },
|
||||
#[error("managed command capacity must be greater than zero")]
|
||||
ZeroCommandCapacity,
|
||||
#[error("managed command capacity {configured} exceeds Tokio's maximum {maximum}")]
|
||||
CommandCapacityTooLarge { configured: usize, maximum: usize },
|
||||
#[error("managed live-generation limit must be greater than zero")]
|
||||
ZeroLiveGenerationLimit,
|
||||
#[error("managed final drain {duration:?} cannot be scheduled from the current instant")]
|
||||
UnschedulableFinalDrain { duration: Duration },
|
||||
#[error("invalid managed target {id}: {source}")]
|
||||
InvalidTarget {
|
||||
id: TargetId,
|
||||
#[source]
|
||||
source: ClientError,
|
||||
},
|
||||
#[error("managed target generation space is exhausted")]
|
||||
GenerationExhausted,
|
||||
}
|
||||
|
||||
/// Immediate failure to submit a managed target update.
|
||||
#[derive(Clone, Debug, Eq, Error, PartialEq)]
|
||||
pub enum ManagedCommandError {
|
||||
#[error("managed target updates are no longer accepted")]
|
||||
Stopping,
|
||||
#[error("managed target update contains {configured} targets but the limit is {limit}")]
|
||||
TooManyTargets { configured: usize, limit: usize },
|
||||
#[error("managed command queue is full")]
|
||||
QueueFull,
|
||||
#[error("managed command receiver is closed")]
|
||||
DriverClosed,
|
||||
}
|
||||
|
||||
/// Failure while applying an accepted managed target update.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ManagedCommandApplyError {
|
||||
#[error("managed target updates are no longer accepted")]
|
||||
Stopping,
|
||||
#[error("duplicate target id {id}")]
|
||||
DuplicateTargetId { id: TargetId },
|
||||
#[error("invalid configuration for target {id}: {source}")]
|
||||
InvalidTarget {
|
||||
id: TargetId,
|
||||
#[source]
|
||||
source: ClientError,
|
||||
},
|
||||
#[error("target update requires {required} live generations but limit is {limit}")]
|
||||
LiveGenerationLimitExceeded { required: usize, limit: usize },
|
||||
#[error("managed target generation space is exhausted")]
|
||||
GenerationExhausted,
|
||||
#[error("managed command sequence is exhausted")]
|
||||
CommandSequenceExhausted,
|
||||
#[error("managed task ended before command acknowledgement")]
|
||||
AcknowledgementDisconnected,
|
||||
#[error("managed driver failed before command application: {0}")]
|
||||
DriverFailed(ManagedDriverFailure),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ManagedCommandAcknowledgement {
|
||||
pub sequence: u64,
|
||||
pub status: Arc<ManagedStatus>,
|
||||
}
|
||||
|
||||
/// Failure to create a new event subscription.
|
||||
#[derive(Clone, Debug, Eq, Error, PartialEq)]
|
||||
pub enum ManagedSubscribeError {
|
||||
#[error("managed event stream is closed")]
|
||||
Closed,
|
||||
}
|
||||
|
||||
/// Whole-driver failure.
|
||||
#[derive(Clone, Debug, Eq, Error, PartialEq)]
|
||||
pub enum ManagedDriverFailure {
|
||||
#[error("ManagedClientTask requires a current Tokio runtime")]
|
||||
NoTokioRuntime,
|
||||
#[error("managed driver exhausted resources for {operation}")]
|
||||
ResourceExhausted { operation: &'static str },
|
||||
#[error("managed driver invariant failed: {message}")]
|
||||
Internal { message: Arc<str> },
|
||||
}
|
||||
|
||||
/// Map a [`ClientError`] onto its durable managed failure classification.
|
||||
///
|
||||
/// The match is deliberately exhaustive over every [`ClientError`] variant. A
|
||||
/// new variant must fail to compile here until its real classification is
|
||||
/// chosen, rather than silently degrading to
|
||||
/// [`ManagedTargetFailureKind::Other`].
|
||||
pub(crate) fn classify_client_error(
|
||||
phase: ManagedTargetFailurePhase,
|
||||
error: &ClientError,
|
||||
) -> ManagedTargetFailure {
|
||||
let kind = match error {
|
||||
ClientError::Resolve { .. } => ManagedTargetFailureKind::Resolve,
|
||||
ClientError::Socket(_) => ManagedTargetFailureKind::Socket,
|
||||
ClientError::SocketOption { .. } | ClientError::ReadTimeoutRestore { .. } => {
|
||||
ManagedTargetFailureKind::SocketOption
|
||||
}
|
||||
ClientError::Protocol(_)
|
||||
| ClientError::ProtocolVersionMismatch { .. }
|
||||
| ClientError::ZeroToken
|
||||
| ClientError::UnexpectedNoTestReply
|
||||
| ClientError::NonZeroNoTestToken { .. }
|
||||
| ClientError::ServerRejected
|
||||
| ClientError::NegotiationRejected { .. } => ManagedTargetFailureKind::Protocol,
|
||||
ClientError::OpenTimeout => ManagedTargetFailureKind::Timeout,
|
||||
ClientError::InvalidConfig { .. }
|
||||
| ClientError::OpenTimeoutTooSmall { .. }
|
||||
| ClientError::NoOpenTimeouts => ManagedTargetFailureKind::Configuration,
|
||||
ClientError::AllocationFailed { .. }
|
||||
| ClientError::CounterOverflow { .. }
|
||||
| ClientError::DurationOverflow
|
||||
| ClientError::PendingLimitExceeded { .. } => ManagedTargetFailureKind::ResourceExhausted,
|
||||
ClientError::DatagramLengthMismatch { .. } => ManagedTargetFailureKind::Socket,
|
||||
#[cfg(feature = "tokio")]
|
||||
ClientError::NoTokioRuntime => ManagedTargetFailureKind::InvalidState,
|
||||
ClientError::NotOpen
|
||||
| ClientError::AlreadyOpen
|
||||
| ClientError::AlreadyCompleted
|
||||
| ClientError::AlreadyClosed
|
||||
| ClientError::StalePreparedProbe { .. }
|
||||
| ClientError::PendingSequenceCollision { .. } => ManagedTargetFailureKind::InvalidState,
|
||||
};
|
||||
ManagedTargetFailure {
|
||||
phase,
|
||||
kind,
|
||||
message: Arc::from(error.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{collections::TryReserveError, io};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn io_error() -> io::Error {
|
||||
io::Error::other("boom")
|
||||
}
|
||||
|
||||
fn try_reserve_error() -> TryReserveError {
|
||||
Vec::<u8>::new().try_reserve(usize::MAX).unwrap_err()
|
||||
}
|
||||
|
||||
fn classification_cases() -> Vec<(ClientError, ManagedTargetFailureKind)> {
|
||||
vec![
|
||||
(
|
||||
ClientError::Resolve {
|
||||
addr: "example.invalid:2112".to_owned(),
|
||||
},
|
||||
ManagedTargetFailureKind::Resolve,
|
||||
),
|
||||
(
|
||||
ClientError::Socket(io_error()),
|
||||
ManagedTargetFailureKind::Socket,
|
||||
),
|
||||
(
|
||||
ClientError::DatagramLengthMismatch {
|
||||
expected: 64,
|
||||
actual: 32,
|
||||
},
|
||||
ManagedTargetFailureKind::Socket,
|
||||
),
|
||||
(
|
||||
ClientError::SocketOption {
|
||||
operation: "set read timeout",
|
||||
remote: "127.0.0.1:2112".parse().unwrap(),
|
||||
source: io_error(),
|
||||
},
|
||||
ManagedTargetFailureKind::SocketOption,
|
||||
),
|
||||
(
|
||||
ClientError::ReadTimeoutRestore { source: io_error() },
|
||||
ManagedTargetFailureKind::SocketOption,
|
||||
),
|
||||
(
|
||||
ClientError::Protocol(irtt_proto::ProtoError::BadMagic),
|
||||
ManagedTargetFailureKind::Protocol,
|
||||
),
|
||||
(
|
||||
ClientError::ProtocolVersionMismatch {
|
||||
requested: 1,
|
||||
received: 2,
|
||||
},
|
||||
ManagedTargetFailureKind::Protocol,
|
||||
),
|
||||
(ClientError::ZeroToken, ManagedTargetFailureKind::Protocol),
|
||||
(
|
||||
ClientError::UnexpectedNoTestReply,
|
||||
ManagedTargetFailureKind::Protocol,
|
||||
),
|
||||
(
|
||||
ClientError::NonZeroNoTestToken { token: 7 },
|
||||
ManagedTargetFailureKind::Protocol,
|
||||
),
|
||||
(
|
||||
ClientError::ServerRejected,
|
||||
ManagedTargetFailureKind::Protocol,
|
||||
),
|
||||
(
|
||||
ClientError::NegotiationRejected {
|
||||
reason: "duration".to_owned(),
|
||||
},
|
||||
ManagedTargetFailureKind::Protocol,
|
||||
),
|
||||
(ClientError::OpenTimeout, ManagedTargetFailureKind::Timeout),
|
||||
(
|
||||
ClientError::InvalidConfig {
|
||||
reason: "interval".to_owned(),
|
||||
},
|
||||
ManagedTargetFailureKind::Configuration,
|
||||
),
|
||||
(
|
||||
ClientError::OpenTimeoutTooSmall {
|
||||
timeout: Duration::from_millis(1),
|
||||
minimum: Duration::from_millis(10),
|
||||
},
|
||||
ManagedTargetFailureKind::Configuration,
|
||||
),
|
||||
(
|
||||
ClientError::NoOpenTimeouts,
|
||||
ManagedTargetFailureKind::Configuration,
|
||||
),
|
||||
(
|
||||
ClientError::AllocationFailed {
|
||||
operation: "pending probes",
|
||||
source: try_reserve_error(),
|
||||
},
|
||||
ManagedTargetFailureKind::ResourceExhausted,
|
||||
),
|
||||
(
|
||||
ClientError::CounterOverflow {
|
||||
counter: "packets_sent",
|
||||
},
|
||||
ManagedTargetFailureKind::ResourceExhausted,
|
||||
),
|
||||
(
|
||||
ClientError::DurationOverflow,
|
||||
ManagedTargetFailureKind::ResourceExhausted,
|
||||
),
|
||||
(
|
||||
ClientError::PendingLimitExceeded { limit: 8 },
|
||||
ManagedTargetFailureKind::ResourceExhausted,
|
||||
),
|
||||
(
|
||||
ClientError::NoTokioRuntime,
|
||||
ManagedTargetFailureKind::InvalidState,
|
||||
),
|
||||
(ClientError::NotOpen, ManagedTargetFailureKind::InvalidState),
|
||||
(
|
||||
ClientError::AlreadyOpen,
|
||||
ManagedTargetFailureKind::InvalidState,
|
||||
),
|
||||
(
|
||||
ClientError::AlreadyCompleted,
|
||||
ManagedTargetFailureKind::InvalidState,
|
||||
),
|
||||
(
|
||||
ClientError::AlreadyClosed,
|
||||
ManagedTargetFailureKind::InvalidState,
|
||||
),
|
||||
(
|
||||
ClientError::StalePreparedProbe {
|
||||
prepared_seq: 3,
|
||||
next_wire_seq: 4,
|
||||
},
|
||||
ManagedTargetFailureKind::InvalidState,
|
||||
),
|
||||
(
|
||||
ClientError::PendingSequenceCollision { seq: 9 },
|
||||
ManagedTargetFailureKind::InvalidState,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_client_error_classifies_to_its_documented_kind() {
|
||||
for (error, expected) in classification_cases() {
|
||||
let failure = classify_client_error(ManagedTargetFailurePhase::Opening, &error);
|
||||
assert_eq!(
|
||||
failure.kind, expected,
|
||||
"unexpected classification for {error:?}"
|
||||
);
|
||||
assert_eq!(failure.phase, ManagedTargetFailurePhase::Opening);
|
||||
assert_eq!(&*failure.message, error.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classification_preserves_the_reported_phase() {
|
||||
for phase in [
|
||||
ManagedTargetFailurePhase::Connecting,
|
||||
ManagedTargetFailurePhase::Opening,
|
||||
ManagedTargetFailurePhase::Sending,
|
||||
ManagedTargetFailurePhase::Receiving,
|
||||
ManagedTargetFailurePhase::Timing,
|
||||
ManagedTargetFailurePhase::Closing,
|
||||
] {
|
||||
let failure = classify_client_error(phase, &ClientError::OpenTimeout);
|
||||
assert_eq!(failure.phase, phase);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn phase_and_kind_display_without_debug_spelling() {
|
||||
assert_eq!(
|
||||
ManagedTargetFailurePhase::Connecting.to_string(),
|
||||
"connecting"
|
||||
);
|
||||
assert_eq!(ManagedTargetFailurePhase::Closing.to_string(), "closing");
|
||||
assert_eq!(
|
||||
ManagedTargetFailureKind::SocketOption.to_string(),
|
||||
"socket option"
|
||||
);
|
||||
assert_eq!(
|
||||
ManagedTargetFailureKind::ResourceExhausted.to_string(),
|
||||
"resource exhausted"
|
||||
);
|
||||
assert_eq!(
|
||||
ManagedTargetFailureKind::InvalidState.to_string(),
|
||||
"invalid state"
|
||||
);
|
||||
assert_eq!(ManagedTargetFailureKind::Other.to_string(), "other");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,698 @@
|
||||
use std::{
|
||||
thread::{self, JoinHandle},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
config::{ClientConfig, RecvBudget},
|
||||
error::ClientError,
|
||||
event::{ClientEvent, OpenOutcome},
|
||||
Client,
|
||||
};
|
||||
|
||||
use super::{
|
||||
cancellation::CancellationToken,
|
||||
hub::{EventHub, EventSubscription, SubscriberConfig},
|
||||
};
|
||||
|
||||
const MANAGED_RECV_TIMEOUT: Duration = Duration::from_millis(20);
|
||||
const MANAGED_RECV_BUDGET: RecvBudget = RecvBudget { max_packets: 64 };
|
||||
const MANAGED_FINAL_DRAIN: Duration = Duration::from_millis(100);
|
||||
const IDLE_SLEEP: Duration = Duration::from_millis(1);
|
||||
const MAX_SLEEP: Duration = Duration::from_millis(20);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ManagedClient;
|
||||
|
||||
/// Running managed client session.
|
||||
///
|
||||
/// [`ManagedClientSession::join`] waits for the worker and returns the session
|
||||
/// outcome or client error. Dropping the session requests cooperative
|
||||
/// cancellation; callers that need the outcome should explicitly join instead
|
||||
/// of relying on drop.
|
||||
#[must_use = "dropping the session cancels the managed client; call join() to wait for completion"]
|
||||
#[derive(Debug)]
|
||||
pub struct ManagedClientSession {
|
||||
hub: EventHub,
|
||||
cancellation: CancellationToken,
|
||||
worker: Option<JoinHandle<Result<SessionOutcome, ClientError>>>,
|
||||
}
|
||||
|
||||
/// Outcome returned by a completed managed client session.
|
||||
///
|
||||
/// These are runner-level lifecycle counters, not statistical summaries. Use
|
||||
/// `irtt-stats` with emitted `ClientEvent` values for RTT, loss, IPDV, and
|
||||
/// related summaries.
|
||||
#[must_use = "managed session outcomes contain completion status and counters"]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SessionOutcome {
|
||||
pub end_reason: SessionEndReason,
|
||||
pub packets_sent: u64,
|
||||
pub replies_received: u64,
|
||||
pub duplicates: u64,
|
||||
pub late: u64,
|
||||
pub warning_events: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SessionEndReason {
|
||||
TestComplete,
|
||||
Cancelled,
|
||||
NoTestComplete,
|
||||
}
|
||||
|
||||
impl ManagedClient {
|
||||
pub fn start(config: ClientConfig) -> Result<ManagedClientSession, ClientError> {
|
||||
Self::start_inner(config, None).map(|(session, _)| session)
|
||||
}
|
||||
|
||||
pub fn start_with_subscription(
|
||||
config: ClientConfig,
|
||||
subscriber_config: SubscriberConfig,
|
||||
) -> Result<(ManagedClientSession, EventSubscription), ClientError> {
|
||||
let (session, subscription) = Self::start_inner(config, Some(subscriber_config))?;
|
||||
Ok((
|
||||
session,
|
||||
subscription.expect("initial subscription must be present"),
|
||||
))
|
||||
}
|
||||
|
||||
fn start_inner(
|
||||
mut config: ClientConfig,
|
||||
subscriber_config: Option<SubscriberConfig>,
|
||||
) -> Result<(ManagedClientSession, Option<EventSubscription>), ClientError> {
|
||||
if config.socket_config.recv_timeout.is_none()
|
||||
|| config.socket_config.recv_timeout > Some(MANAGED_RECV_TIMEOUT)
|
||||
{
|
||||
config.socket_config.recv_timeout = Some(MANAGED_RECV_TIMEOUT);
|
||||
}
|
||||
|
||||
let hub = EventHub::new();
|
||||
let initial_subscription = subscriber_config
|
||||
.map(|config| hub.subscribe(config))
|
||||
.transpose()?;
|
||||
|
||||
let mut client = Client::connect(config)?;
|
||||
let outcome = client.open()?;
|
||||
publish_open_outcome(&hub, &outcome);
|
||||
|
||||
let cancellation = CancellationToken::new();
|
||||
let worker_hub = hub.clone();
|
||||
let worker_cancellation = cancellation.clone();
|
||||
let worker =
|
||||
thread::spawn(move || run_client_with_cleanup(client, worker_hub, worker_cancellation));
|
||||
|
||||
Ok((
|
||||
ManagedClientSession {
|
||||
hub,
|
||||
cancellation,
|
||||
worker: Some(worker),
|
||||
},
|
||||
initial_subscription,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl ManagedClientSession {
|
||||
pub fn subscribe(&self, config: SubscriberConfig) -> Result<EventSubscription, ClientError> {
|
||||
self.hub.subscribe(config)
|
||||
}
|
||||
|
||||
pub fn stop(&self) {
|
||||
self.cancellation.cancel();
|
||||
}
|
||||
|
||||
pub fn join(mut self) -> Result<SessionOutcome, ClientError> {
|
||||
let worker = self
|
||||
.worker
|
||||
.take()
|
||||
.expect("ManagedClientSession invariant violated: worker handle missing before join");
|
||||
match worker.join() {
|
||||
Ok(outcome) => {
|
||||
self.hub.disconnect_all();
|
||||
outcome
|
||||
}
|
||||
Err(_) => {
|
||||
self.hub.disconnect_all();
|
||||
Err(ClientError::WorkerPanicked)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ManagedClientSession {
|
||||
fn drop(&mut self) {
|
||||
self.cancellation.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_open_outcome(hub: &EventHub, outcome: &OpenOutcome) {
|
||||
match outcome {
|
||||
OpenOutcome::Started { event, .. } | OpenOutcome::NoTestCompleted { event, .. } => {
|
||||
hub.publish(event.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_client(
|
||||
mut client: Client,
|
||||
hub: EventHub,
|
||||
cancellation: CancellationToken,
|
||||
) -> Result<SessionOutcome, ClientError> {
|
||||
if client.is_run_complete() {
|
||||
return Ok(SessionOutcome {
|
||||
end_reason: SessionEndReason::NoTestComplete,
|
||||
packets_sent: 0,
|
||||
replies_received: 0,
|
||||
duplicates: 0,
|
||||
late: 0,
|
||||
warning_events: 0,
|
||||
});
|
||||
}
|
||||
|
||||
let mut counters = OutcomeCounters::default();
|
||||
let mut cancelled = false;
|
||||
|
||||
loop {
|
||||
if cancellation.is_cancelled() {
|
||||
cancelled = true;
|
||||
publish_events(
|
||||
&hub,
|
||||
&mut counters,
|
||||
client.recv_available(MANAGED_RECV_BUDGET)?,
|
||||
);
|
||||
publish_events(&hub, &mut counters, client.poll_timeouts()?);
|
||||
break;
|
||||
}
|
||||
|
||||
let now = Instant::now();
|
||||
if client
|
||||
.next_send_deadline()
|
||||
.is_some_and(|deadline| deadline <= now)
|
||||
{
|
||||
let events = client.send_probe()?;
|
||||
publish_events(&hub, &mut counters, events);
|
||||
continue;
|
||||
}
|
||||
|
||||
publish_events(
|
||||
&hub,
|
||||
&mut counters,
|
||||
client.recv_available(MANAGED_RECV_BUDGET)?,
|
||||
);
|
||||
publish_events(&hub, &mut counters, client.poll_timeouts()?);
|
||||
|
||||
if client.is_run_complete() {
|
||||
break;
|
||||
}
|
||||
|
||||
sleep_until_next_wakeup(client.next_send_deadline());
|
||||
}
|
||||
|
||||
if !cancelled {
|
||||
drain_final_late_replies(&mut client, &hub, &mut counters)?;
|
||||
}
|
||||
|
||||
let packets_sent = client.packets_sent();
|
||||
let close_events = client.close()?;
|
||||
publish_events(&hub, &mut counters, close_events);
|
||||
|
||||
Ok(SessionOutcome {
|
||||
end_reason: if cancelled {
|
||||
SessionEndReason::Cancelled
|
||||
} else {
|
||||
SessionEndReason::TestComplete
|
||||
},
|
||||
packets_sent,
|
||||
replies_received: counters.replies_received,
|
||||
duplicates: counters.duplicates,
|
||||
late: counters.late,
|
||||
warning_events: counters.warning_events,
|
||||
})
|
||||
}
|
||||
|
||||
fn run_client_with_cleanup(
|
||||
client: Client,
|
||||
hub: EventHub,
|
||||
cancellation: CancellationToken,
|
||||
) -> Result<SessionOutcome, ClientError> {
|
||||
let outcome = run_client(client, hub.clone(), cancellation);
|
||||
hub.disconnect_all();
|
||||
outcome
|
||||
}
|
||||
|
||||
fn drain_final_late_replies(
|
||||
client: &mut Client,
|
||||
hub: &EventHub,
|
||||
counters: &mut OutcomeCounters,
|
||||
) -> Result<(), ClientError> {
|
||||
if !client.has_timed_out_metadata() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let deadline = Instant::now() + MANAGED_FINAL_DRAIN;
|
||||
while Instant::now() < deadline && client.has_timed_out_metadata() {
|
||||
let mut published = false;
|
||||
|
||||
let events = client.recv_available(MANAGED_RECV_BUDGET)?;
|
||||
published |= !events.is_empty();
|
||||
publish_events(hub, counters, events);
|
||||
|
||||
let events = client.poll_timeouts()?;
|
||||
published |= !events.is_empty();
|
||||
publish_events(hub, counters, events);
|
||||
|
||||
if !published {
|
||||
thread::sleep(IDLE_SLEEP);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn publish_events(hub: &EventHub, counters: &mut OutcomeCounters, events: Vec<ClientEvent>) {
|
||||
for event in events {
|
||||
counters.observe(&event);
|
||||
hub.publish(event);
|
||||
}
|
||||
}
|
||||
|
||||
fn sleep_until_next_wakeup(deadline: Option<Instant>) {
|
||||
let sleep_for = deadline
|
||||
.and_then(|deadline| deadline.checked_duration_since(Instant::now()))
|
||||
.map(|duration| duration.min(MAX_SLEEP))
|
||||
.unwrap_or(IDLE_SLEEP);
|
||||
if sleep_for > Duration::ZERO {
|
||||
thread::sleep(sleep_for);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct OutcomeCounters {
|
||||
replies_received: u64,
|
||||
duplicates: u64,
|
||||
late: u64,
|
||||
warning_events: u64,
|
||||
}
|
||||
|
||||
impl OutcomeCounters {
|
||||
fn observe(&mut self, event: &ClientEvent) {
|
||||
match event {
|
||||
ClientEvent::EchoReply { .. } => self.replies_received += 1,
|
||||
ClientEvent::DuplicateReply { .. } => self.duplicates += 1,
|
||||
ClientEvent::LateReply { .. } => self.late += 1,
|
||||
ClientEvent::Warning { .. } => self.warning_events += 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{config::NegotiationPolicy, SubscriberOverflow};
|
||||
use irtt_proto::{
|
||||
echo_packet_len,
|
||||
flags::{self, FLAG_OPEN, FLAG_REPLY},
|
||||
layout::PacketLayout,
|
||||
Clock, Params, ReceivedStats, StampAt, TimestampFields, MAGIC, PROTOCOL_VERSION,
|
||||
};
|
||||
use std::{
|
||||
net::{SocketAddr, UdpSocket},
|
||||
sync::mpsc,
|
||||
};
|
||||
|
||||
const TOKEN: u64 = 0x1234_5678_90ab_cdef;
|
||||
struct FakeServer {
|
||||
addr: SocketAddr,
|
||||
done: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl FakeServer {
|
||||
fn join(self) {
|
||||
self.done.join().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn test_echo_packet_len(hmac: bool, params: &Params) -> usize {
|
||||
echo_packet_len(hmac, params)
|
||||
.expect("managed runner test params must have a non-negative packet length")
|
||||
}
|
||||
|
||||
fn test_params(duration: Option<Duration>, interval: Duration) -> Params {
|
||||
Params {
|
||||
protocol_version: PROTOCOL_VERSION,
|
||||
duration_ns: duration.map_or(0, test_duration_ns_i64),
|
||||
interval_ns: test_duration_ns_i64(interval),
|
||||
length: 0,
|
||||
received_stats: ReceivedStats::Both,
|
||||
stamp_at: StampAt::Both,
|
||||
clock: Clock::Both,
|
||||
dscp: 0,
|
||||
server_fill: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn test_duration_ns_i64(duration: Duration) -> i64 {
|
||||
i64::try_from(duration.as_nanos()).expect("test duration fits i64 nanoseconds")
|
||||
}
|
||||
|
||||
fn config(addr: SocketAddr, duration: Option<Duration>) -> ClientConfig {
|
||||
ClientConfig {
|
||||
server_addr: addr.to_string(),
|
||||
duration,
|
||||
interval: Duration::from_millis(10),
|
||||
negotiation_policy: NegotiationPolicy::Strict,
|
||||
open_timeouts: vec![Duration::from_millis(200)],
|
||||
probe_timeout: Duration::from_millis(40),
|
||||
..ClientConfig::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn start_echo_server(params: Params) -> FakeServer {
|
||||
let socket = UdpSocket::bind("127.0.0.1:0").unwrap();
|
||||
let addr = socket.local_addr().unwrap();
|
||||
let done = thread::spawn(move || {
|
||||
let (_, peer) = recv_request(&socket);
|
||||
socket
|
||||
.send_to(&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms), peer)
|
||||
.unwrap();
|
||||
socket
|
||||
.set_read_timeout(Some(Duration::from_millis(500)))
|
||||
.unwrap();
|
||||
|
||||
while let Some((packet, peer)) = recv_request_timeout(&socket) {
|
||||
if packet[3] & flags::FLAG_CLOSE != 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
let seq = u32::from_le_bytes(packet[12..16].try_into().unwrap());
|
||||
let ts = TimestampFields {
|
||||
recv_wall: Some(1_000_000_000),
|
||||
recv_mono: Some(100_000),
|
||||
send_wall: Some(1_000_000_000),
|
||||
send_mono: Some(100_000),
|
||||
..Default::default()
|
||||
};
|
||||
socket
|
||||
.send_to(&echo_reply_packet(TOKEN, seq, ¶ms, &ts), peer)
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
FakeServer { addr, done }
|
||||
}
|
||||
|
||||
fn start_delayed_reply_server(params: Params, delay: Duration) -> FakeServer {
|
||||
let socket = UdpSocket::bind("127.0.0.1:0").unwrap();
|
||||
let addr = socket.local_addr().unwrap();
|
||||
let done = thread::spawn(move || {
|
||||
let (_, peer) = recv_request(&socket);
|
||||
socket
|
||||
.send_to(&open_reply(FLAG_OPEN | FLAG_REPLY, TOKEN, ¶ms), peer)
|
||||
.unwrap();
|
||||
socket
|
||||
.set_read_timeout(Some(Duration::from_millis(500)))
|
||||
.unwrap();
|
||||
|
||||
let Some((packet, peer)) = recv_request_timeout(&socket) else {
|
||||
return;
|
||||
};
|
||||
let seq = u32::from_le_bytes(packet[12..16].try_into().unwrap());
|
||||
thread::sleep(delay);
|
||||
let ts = TimestampFields {
|
||||
recv_wall: Some(1_000_000_000),
|
||||
recv_mono: Some(100_000),
|
||||
send_wall: Some(1_001_000_000),
|
||||
send_mono: Some(1_100_000),
|
||||
..Default::default()
|
||||
};
|
||||
socket
|
||||
.send_to(&echo_reply_packet(TOKEN, seq, ¶ms, &ts), peer)
|
||||
.unwrap();
|
||||
|
||||
while let Some((packet, _)) = recv_request_timeout(&socket) {
|
||||
if packet[3] & flags::FLAG_CLOSE != 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
FakeServer { addr, done }
|
||||
}
|
||||
|
||||
fn recv_request(socket: &UdpSocket) -> (Vec<u8>, SocketAddr) {
|
||||
let mut buf = [0_u8; 2048];
|
||||
let (size, peer) = socket.recv_from(&mut buf).unwrap();
|
||||
(buf[..size].to_vec(), peer)
|
||||
}
|
||||
|
||||
fn recv_request_timeout(socket: &UdpSocket) -> Option<(Vec<u8>, SocketAddr)> {
|
||||
let mut buf = [0_u8; 2048];
|
||||
socket
|
||||
.recv_from(&mut buf)
|
||||
.ok()
|
||||
.map(|(size, peer)| (buf[..size].to_vec(), peer))
|
||||
}
|
||||
|
||||
fn open_reply(flags: u8, token: u64, params: &Params) -> Vec<u8> {
|
||||
let mut packet = Vec::new();
|
||||
packet.extend_from_slice(&MAGIC);
|
||||
packet.push(flags);
|
||||
packet.extend_from_slice(&token.to_le_bytes());
|
||||
packet.extend_from_slice(¶ms.encode());
|
||||
packet
|
||||
}
|
||||
|
||||
fn echo_reply_packet(
|
||||
token: u64,
|
||||
seq: u32,
|
||||
params: &Params,
|
||||
timestamps: &TimestampFields,
|
||||
) -> Vec<u8> {
|
||||
let layout = PacketLayout::echo(false, params);
|
||||
let packet_len = test_echo_packet_len(false, params);
|
||||
let mut packet = Vec::with_capacity(packet_len);
|
||||
|
||||
packet.extend_from_slice(&MAGIC);
|
||||
packet.push(FLAG_REPLY);
|
||||
packet.extend_from_slice(&token.to_le_bytes());
|
||||
packet.extend_from_slice(&seq.to_le_bytes());
|
||||
|
||||
if layout.recv_count {
|
||||
packet.extend_from_slice(&42_u32.to_le_bytes());
|
||||
}
|
||||
if layout.recv_window {
|
||||
packet.extend_from_slice(&0x07_u64.to_le_bytes());
|
||||
}
|
||||
if layout.recv_wall {
|
||||
packet.extend_from_slice(×tamps.recv_wall.unwrap_or(0).to_le_bytes());
|
||||
}
|
||||
if layout.recv_mono {
|
||||
packet.extend_from_slice(×tamps.recv_mono.unwrap_or(0).to_le_bytes());
|
||||
}
|
||||
if layout.midpoint_wall {
|
||||
packet.extend_from_slice(×tamps.midpoint_wall.unwrap_or(0).to_le_bytes());
|
||||
}
|
||||
if layout.midpoint_mono {
|
||||
packet.extend_from_slice(×tamps.midpoint_mono.unwrap_or(0).to_le_bytes());
|
||||
}
|
||||
if layout.send_wall {
|
||||
packet.extend_from_slice(×tamps.send_wall.unwrap_or(0).to_le_bytes());
|
||||
}
|
||||
if layout.send_mono {
|
||||
packet.extend_from_slice(×tamps.send_mono.unwrap_or(0).to_le_bytes());
|
||||
}
|
||||
|
||||
packet.resize(packet_len, 0);
|
||||
packet
|
||||
}
|
||||
|
||||
fn recv_event_with_timeout(sub: &EventSubscription) -> ClientEvent {
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
loop {
|
||||
match sub.try_recv() {
|
||||
Ok(Some(event)) => return event,
|
||||
Ok(None) if Instant::now() < deadline => {
|
||||
thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
Ok(None) => panic!("timed out waiting for managed client event"),
|
||||
Err(err) => panic!("subscription ended while waiting for event: {err}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_until_closed(sub: &EventSubscription) -> Vec<ClientEvent> {
|
||||
let mut events = Vec::new();
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
while Instant::now() < deadline {
|
||||
match sub.try_recv() {
|
||||
Ok(Some(event)) => {
|
||||
let closed = matches!(event, ClientEvent::SessionClosed { .. });
|
||||
events.push(event);
|
||||
if closed {
|
||||
return events;
|
||||
}
|
||||
}
|
||||
Ok(None) => thread::sleep(Duration::from_millis(1)),
|
||||
Err(_) => return events,
|
||||
}
|
||||
}
|
||||
panic!("timed out waiting for session close event");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stop_is_idempotent() {
|
||||
let server = start_echo_server(test_params(None, Duration::from_millis(10)));
|
||||
let session = ManagedClient::start(config(server.addr, None)).unwrap();
|
||||
session.stop();
|
||||
session.stop();
|
||||
let outcome = session.join().unwrap();
|
||||
server.join();
|
||||
|
||||
assert_eq!(outcome.end_reason, SessionEndReason::Cancelled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finite_managed_run_emits_session_probe_and_close_events() {
|
||||
let duration = Duration::from_millis(35);
|
||||
let server = start_echo_server(test_params(Some(duration), Duration::from_millis(10)));
|
||||
let (session, sub) = ManagedClient::start_with_subscription(
|
||||
config(server.addr, Some(duration)),
|
||||
SubscriberConfig {
|
||||
capacity: 16,
|
||||
overflow: SubscriberOverflow::DropNewest,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let events = collect_until_closed(&sub);
|
||||
let outcome = session.join().unwrap();
|
||||
server.join();
|
||||
|
||||
assert_eq!(outcome.end_reason, SessionEndReason::TestComplete);
|
||||
assert!(events
|
||||
.iter()
|
||||
.any(|event| matches!(event, ClientEvent::SessionStarted { .. })));
|
||||
assert!(events
|
||||
.iter()
|
||||
.any(|event| matches!(event, ClientEvent::EchoReply { .. })));
|
||||
assert!(events
|
||||
.iter()
|
||||
.any(|event| matches!(event, ClientEvent::SessionClosed { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finite_managed_run_drains_late_reply_after_timeout_before_close() {
|
||||
let duration = Duration::from_millis(1);
|
||||
let params = test_params(Some(duration), Duration::from_millis(10));
|
||||
let server = start_delayed_reply_server(params, Duration::from_millis(60));
|
||||
let mut cfg = config(server.addr, Some(duration));
|
||||
cfg.probe_timeout = Duration::from_millis(20);
|
||||
|
||||
let (session, sub) = ManagedClient::start_with_subscription(
|
||||
cfg,
|
||||
SubscriberConfig {
|
||||
capacity: 16,
|
||||
overflow: SubscriberOverflow::DropNewest,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let events = collect_until_closed(&sub);
|
||||
let outcome = session.join().unwrap();
|
||||
server.join();
|
||||
|
||||
assert_eq!(outcome.end_reason, SessionEndReason::TestComplete);
|
||||
assert!(events
|
||||
.iter()
|
||||
.any(|event| matches!(event, ClientEvent::EchoLoss { seq: 0, .. })));
|
||||
assert!(events.iter().any(|event| matches!(
|
||||
event,
|
||||
ClientEvent::LateReply {
|
||||
seq: 0,
|
||||
sent_at: Some(_),
|
||||
rtt: Some(_),
|
||||
..
|
||||
}
|
||||
)));
|
||||
let late_before_close = events
|
||||
.iter()
|
||||
.position(|event| matches!(event, ClientEvent::LateReply { rtt: Some(_), .. }));
|
||||
let close = events
|
||||
.iter()
|
||||
.position(|event| matches!(event, ClientEvent::SessionClosed { .. }));
|
||||
let late_before_close = late_before_close.expect("missing stats-eligible LateReply");
|
||||
let close = close.expect("missing SessionClosed");
|
||||
assert!(late_before_close < close);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn continuous_managed_run_can_be_stopped_cleanly() {
|
||||
let server = start_echo_server(test_params(None, Duration::from_millis(10)));
|
||||
let session = ManagedClient::start(config(server.addr, None)).unwrap();
|
||||
let sub = session
|
||||
.subscribe(SubscriberConfig {
|
||||
capacity: 16,
|
||||
overflow: SubscriberOverflow::DropNewest,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
loop {
|
||||
if matches!(recv_event_with_timeout(&sub), ClientEvent::EchoReply { .. }) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
session.stop();
|
||||
let events = collect_until_closed(&sub);
|
||||
let outcome = session.join().unwrap();
|
||||
server.join();
|
||||
|
||||
assert_eq!(outcome.end_reason, SessionEndReason::Cancelled);
|
||||
assert!(events
|
||||
.iter()
|
||||
.any(|event| matches!(event, ClientEvent::SessionClosed { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn join_reports_worker_panic() {
|
||||
let hub = EventHub::new();
|
||||
let cancellation = CancellationToken::new();
|
||||
let worker = thread::spawn(|| -> Result<SessionOutcome, ClientError> {
|
||||
panic!("intentional managed worker panic")
|
||||
});
|
||||
let session = ManagedClientSession {
|
||||
hub,
|
||||
cancellation,
|
||||
worker: Some(worker),
|
||||
};
|
||||
|
||||
assert!(matches!(session.join(), Err(ClientError::WorkerPanicked)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_test_managed_run_returns_no_test_outcome() {
|
||||
use crate::RunMode;
|
||||
|
||||
let params = test_params(Some(Duration::from_millis(10)), Duration::from_millis(10));
|
||||
let socket = UdpSocket::bind("127.0.0.1:0").unwrap();
|
||||
let addr = socket.local_addr().unwrap();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let done = thread::spawn(move || {
|
||||
let (request, peer) = recv_request(&socket);
|
||||
tx.send(request[3] & flags::FLAG_CLOSE != 0).unwrap();
|
||||
socket
|
||||
.send_to(
|
||||
&open_reply(FLAG_OPEN | FLAG_REPLY | flags::FLAG_CLOSE, 0, ¶ms),
|
||||
peer,
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
|
||||
let mut cfg = config(addr, Some(Duration::from_millis(10)));
|
||||
cfg.run_mode = RunMode::NoTest;
|
||||
let session = ManagedClient::start(cfg).unwrap();
|
||||
assert!(rx.recv_timeout(Duration::from_secs(2)).unwrap());
|
||||
let outcome = session.join().unwrap();
|
||||
done.join().unwrap();
|
||||
|
||||
assert_eq!(outcome.end_reason, SessionEndReason::NoTestComplete);
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
use std::{fmt, sync::Arc};
|
||||
|
||||
/// Caller-owned stable target identity.
|
||||
#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub struct TargetId(Arc<str>);
|
||||
|
||||
impl TargetId {
|
||||
/// Construct a target identifier.
|
||||
pub fn new(value: impl Into<Arc<str>>) -> Self {
|
||||
Self(value.into())
|
||||
}
|
||||
|
||||
/// Borrow the identifier as a string slice.
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for TargetId {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_tuple("TargetId").field(&self.0).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for TargetId {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for TargetId {
|
||||
fn from(value: &str) -> Self {
|
||||
Self::new(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for TargetId {
|
||||
fn from(value: String) -> Self {
|
||||
Self::new(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<str> for TargetId {
|
||||
fn as_ref(&self) -> &str {
|
||||
self.as_str()
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,51 +1,13 @@
|
||||
use std::time::{Duration, SystemTime};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use crate::event::PacketMeta;
|
||||
|
||||
/// Largest lag behind the paired userspace receive sample that a kernel
|
||||
/// receive timestamp may show and still be used as a measurement endpoint.
|
||||
///
|
||||
/// This is a sanity guard, not an expected kernel-to-userspace wakeup
|
||||
/// latency: ordinary wakeup latency is orders of magnitude smaller. A kernel
|
||||
/// timestamp this far behind the userspace sample most likely reflects a
|
||||
/// realtime clock discontinuity or otherwise unusable metadata, and falling
|
||||
/// back is preferable to injecting a bad cross-host timing sample.
|
||||
const MAX_KERNEL_RX_LAG: Duration = Duration::from_secs(1);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub(crate) struct ReceiveMeta {
|
||||
pub(crate) traffic_class: Option<u8>,
|
||||
pub(crate) kernel_rx_timestamp: Option<SystemTime>,
|
||||
}
|
||||
|
||||
impl ReceiveMeta {
|
||||
/// Receive wall-clock endpoint to use for downstream one-way delay.
|
||||
///
|
||||
/// Prefers an observed kernel receive timestamp, which is sampled earlier
|
||||
/// than the userspace receive instant and therefore excludes socket wakeup
|
||||
/// latency from the measured server-to-client delay. The kernel value is
|
||||
/// only used when it is plausible for the datagram that produced
|
||||
/// `userspace_wall`: it cannot be later than the userspace sample that
|
||||
/// observed the datagram, and it may not lag it by more than
|
||||
/// [`MAX_KERNEL_RX_LAG`]. Anything else falls back to `userspace_wall`.
|
||||
///
|
||||
/// Rejecting a kernel timestamp here never discards it as observed
|
||||
/// metadata: [`PacketMeta::kernel_rx_timestamp`] still reports the raw
|
||||
/// value.
|
||||
pub(crate) fn preferred_receive_wall(&self, userspace_wall: SystemTime) -> SystemTime {
|
||||
let Some(kernel_wall) = self.kernel_rx_timestamp else {
|
||||
return userspace_wall;
|
||||
};
|
||||
// `duration_since` fails exactly when the kernel timestamp is later
|
||||
// than the userspace sample, which cannot happen for a datagram that
|
||||
// sample observed.
|
||||
match userspace_wall.duration_since(kernel_wall) {
|
||||
Ok(lag) if lag <= MAX_KERNEL_RX_LAG => kernel_wall,
|
||||
_ => userspace_wall,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ReceiveMeta> for PacketMeta {
|
||||
fn from(meta: ReceiveMeta) -> Self {
|
||||
Self {
|
||||
@@ -59,125 +21,18 @@ impl From<ReceiveMeta> for PacketMeta {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use super::{ReceiveMeta, MAX_KERNEL_RX_LAG};
|
||||
use super::ReceiveMeta;
|
||||
use crate::event::PacketMeta;
|
||||
|
||||
fn userspace_wall() -> SystemTime {
|
||||
SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000)
|
||||
}
|
||||
|
||||
fn meta_with_kernel_rx(kernel_rx_timestamp: SystemTime) -> ReceiveMeta {
|
||||
ReceiveMeta {
|
||||
traffic_class: None,
|
||||
kernel_rx_timestamp: Some(kernel_rx_timestamp),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_receive_wall_without_kernel_timestamp_uses_userspace_sample() {
|
||||
let userspace = userspace_wall();
|
||||
fn metadata_default_is_unavailable() {
|
||||
let meta = ReceiveMeta::default();
|
||||
let packet_meta = PacketMeta::from(meta);
|
||||
|
||||
assert_eq!(
|
||||
ReceiveMeta::default().preferred_receive_wall(userspace),
|
||||
userspace
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_receive_wall_uses_plausible_earlier_kernel_timestamp() {
|
||||
let userspace = userspace_wall();
|
||||
let kernel = userspace - Duration::from_micros(80);
|
||||
|
||||
assert_eq!(
|
||||
meta_with_kernel_rx(kernel).preferred_receive_wall(userspace),
|
||||
kernel
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_receive_wall_accepts_kernel_timestamp_equal_to_userspace_sample() {
|
||||
let userspace = userspace_wall();
|
||||
|
||||
assert_eq!(
|
||||
meta_with_kernel_rx(userspace).preferred_receive_wall(userspace),
|
||||
userspace
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_receive_wall_rejects_kernel_timestamp_later_than_userspace_sample() {
|
||||
let userspace = userspace_wall();
|
||||
let kernel = userspace + Duration::from_nanos(1);
|
||||
|
||||
assert_eq!(
|
||||
meta_with_kernel_rx(kernel).preferred_receive_wall(userspace),
|
||||
userspace
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_receive_wall_accepts_kernel_timestamp_exactly_at_the_lag_bound() {
|
||||
// The bound is inclusive: a lag of exactly MAX_KERNEL_RX_LAG is
|
||||
// still accepted, one nanosecond more is not.
|
||||
let userspace = userspace_wall();
|
||||
let at_bound = userspace - MAX_KERNEL_RX_LAG;
|
||||
let past_bound = userspace - MAX_KERNEL_RX_LAG - Duration::from_nanos(1);
|
||||
|
||||
assert_eq!(
|
||||
meta_with_kernel_rx(at_bound).preferred_receive_wall(userspace),
|
||||
at_bound
|
||||
);
|
||||
assert_eq!(
|
||||
meta_with_kernel_rx(past_bound).preferred_receive_wall(userspace),
|
||||
userspace
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_receive_wall_rejects_implausibly_old_kernel_timestamp() {
|
||||
let userspace = userspace_wall();
|
||||
let kernel = SystemTime::UNIX_EPOCH;
|
||||
|
||||
assert_eq!(
|
||||
meta_with_kernel_rx(kernel).preferred_receive_wall(userspace),
|
||||
userspace
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_receive_wall_handles_extreme_timestamps_without_panicking() {
|
||||
let userspace = userspace_wall();
|
||||
let far_future = SystemTime::UNIX_EPOCH + Duration::from_secs(u64::from(u32::MAX)) * 4;
|
||||
let before_epoch = SystemTime::UNIX_EPOCH - Duration::from_secs(u64::from(u32::MAX));
|
||||
|
||||
assert_eq!(
|
||||
meta_with_kernel_rx(far_future).preferred_receive_wall(userspace),
|
||||
userspace
|
||||
);
|
||||
assert_eq!(
|
||||
meta_with_kernel_rx(before_epoch).preferred_receive_wall(userspace),
|
||||
userspace
|
||||
);
|
||||
assert_eq!(
|
||||
ReceiveMeta::default().preferred_receive_wall(before_epoch),
|
||||
before_epoch
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_preserves_kernel_timestamp_rejected_for_measurement() {
|
||||
let userspace = userspace_wall();
|
||||
let rejected = userspace + Duration::from_secs(30);
|
||||
let meta = meta_with_kernel_rx(rejected);
|
||||
|
||||
assert_eq!(meta.preferred_receive_wall(userspace), userspace);
|
||||
assert_eq!(
|
||||
PacketMeta::from(meta).kernel_rx_timestamp,
|
||||
Some(rejected),
|
||||
"observed metadata must survive rejection as a measurement endpoint"
|
||||
);
|
||||
assert_eq!(packet_meta.traffic_class, None);
|
||||
assert_eq!(packet_meta.dscp, None);
|
||||
assert_eq!(packet_meta.ecn, None);
|
||||
assert_eq!(packet_meta.kernel_rx_timestamp, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+42
-460
@@ -1,6 +1,6 @@
|
||||
use std::{
|
||||
collections::{HashMap, HashSet, TryReserveError, VecDeque},
|
||||
time::{Instant, SystemTime},
|
||||
collections::{HashMap, HashSet, VecDeque},
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
use crate::{error::ClientError, timing::ClientTimestamp};
|
||||
@@ -8,59 +8,13 @@ use crate::{error::ClientError, timing::ClientTimestamp};
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct PendingProbe {
|
||||
pub wire_seq: u32,
|
||||
/// Paired client wall/monotonic timestamp captured immediately after the
|
||||
/// successful UDP send completed. This is the RTT endpoint (via
|
||||
/// `compute_rtt`), the userspace fallback endpoint for upstream one-way
|
||||
/// delay, `timer_error`'s basis, and the value surfaced on the public
|
||||
/// `EchoSent`/`EchoReply`/`EchoLoss`/`LateReply` events. It is *not* the
|
||||
/// input to `timeout_at` below — see that field's doc.
|
||||
pub sent_at: ClientTimestamp,
|
||||
/// Operational timeout deadline, computed from the pre-send send
|
||||
/// anchor's monotonic timestamp plus the configured probe timeout
|
||||
/// (`SessionMachine::finalize_probe_commit`), not from `sent_at.mono`
|
||||
/// above. Timeout semantics deliberately stay anchored to before the
|
||||
/// socket send so that fallible deadline arithmetic (and its overflow
|
||||
/// check) still runs, and a `PendingProbe` is only ever created, before
|
||||
/// the datagram is transmitted.
|
||||
pub timeout_at: Instant,
|
||||
/// Local wall-clock lower bound for validating an asynchronous Linux
|
||||
/// kernel `TX_SOFTWARE` timestamp, sampled at the same pre-send send
|
||||
/// anchor as `timeout_at` — i.e. before the socket send, not from
|
||||
/// `sent_at.wall` above. A legitimate `TX_SOFTWARE` timestamp can be
|
||||
/// generated during the send path and therefore observed earlier than
|
||||
/// the post-send `sent_at.wall` sample; using this earlier pre-send
|
||||
/// bound instead of `sent_at.wall` avoids rejecting such a timestamp
|
||||
/// merely because userspace samples `sent_at` after `send()` returns.
|
||||
/// See `compute_one_way`'s `preferred_send_wall`.
|
||||
pub tx_not_before_wall: SystemTime,
|
||||
/// Observed Linux kernel TX_SOFTWARE wall timestamp for this probe's
|
||||
/// send, when the socket has TX timestamping enabled and a matching
|
||||
/// `MSG_ERRQUEUE` record has been drained. Optional observed metadata,
|
||||
/// eligible only for upstream one-way delay after local plausibility
|
||||
/// validation against `tx_not_before_wall` (see `compute_one_way`'s
|
||||
/// `preferred_send_wall`). `sent_at` remains the userspace fallback for
|
||||
/// upstream one-way delay when this is absent or implausible.
|
||||
pub kernel_tx_timestamp: Option<SystemTime>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PendingEntry {
|
||||
probe: PendingProbe,
|
||||
previous: Option<u32>,
|
||||
next: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ExpiredBatch {
|
||||
pub probes: Vec<PendingProbe>,
|
||||
pub more_due: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct PendingMap {
|
||||
map: HashMap<u32, PendingEntry>,
|
||||
first: Option<u32>,
|
||||
last: Option<u32>,
|
||||
map: HashMap<u32, PendingProbe>,
|
||||
max_capacity: usize,
|
||||
}
|
||||
|
||||
@@ -68,200 +22,49 @@ impl PendingMap {
|
||||
pub fn new(max_capacity: usize) -> Self {
|
||||
Self {
|
||||
map: HashMap::new(),
|
||||
first: None,
|
||||
last: None,
|
||||
max_capacity,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn preflight_insert(&mut self, wire_seq: u32) -> Result<(), ClientError> {
|
||||
if self.map.contains_key(&wire_seq) {
|
||||
return Err(ClientError::PendingSequenceCollision { seq: wire_seq });
|
||||
}
|
||||
pub fn check_capacity(&self) -> Result<(), ClientError> {
|
||||
if self.map.len() >= self.max_capacity {
|
||||
return Err(ClientError::PendingLimitExceeded {
|
||||
limit: self.max_capacity,
|
||||
});
|
||||
}
|
||||
if self.map.len() == self.map.capacity() {
|
||||
self.map.try_reserve(1).map_err(pending_allocation_failed)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn commit_insert(&mut self, probe: PendingProbe) {
|
||||
let wire_seq = probe.wire_seq;
|
||||
let previous = self.last;
|
||||
if let Some(previous) = previous {
|
||||
let previous = self
|
||||
.map
|
||||
.get_mut(&previous)
|
||||
.expect("pending list tail remains present");
|
||||
// probe_timeout is fixed for an open session and committed sends
|
||||
// have nondecreasing monotonic timestamps, so deadlines append.
|
||||
debug_assert!(previous.probe.timeout_at <= probe.timeout_at);
|
||||
debug_assert!(
|
||||
previous.next.is_none(),
|
||||
"pending list tail has no successor"
|
||||
);
|
||||
previous.next = Some(wire_seq);
|
||||
} else {
|
||||
debug_assert!(self.first.is_none(), "empty pending list has no head");
|
||||
self.first = Some(wire_seq);
|
||||
}
|
||||
|
||||
let replaced = self.map.insert(
|
||||
wire_seq,
|
||||
PendingEntry {
|
||||
probe,
|
||||
previous,
|
||||
next: None,
|
||||
},
|
||||
);
|
||||
debug_assert!(replaced.is_none(), "preflight rejected pending collision");
|
||||
self.last = Some(wire_seq);
|
||||
self.assert_links_consistent();
|
||||
pub fn insert(&mut self, probe: PendingProbe) -> Result<(), ClientError> {
|
||||
self.check_capacity()?;
|
||||
self.map.insert(probe.wire_seq, probe);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, wire_seq: u32) -> Option<PendingProbe> {
|
||||
let PendingEntry {
|
||||
probe,
|
||||
previous,
|
||||
next,
|
||||
} = self.map.remove(&wire_seq)?;
|
||||
|
||||
if let Some(previous) = previous {
|
||||
let previous = self
|
||||
.map
|
||||
.get_mut(&previous)
|
||||
.expect("pending list predecessor remains present");
|
||||
debug_assert_eq!(previous.next, Some(wire_seq));
|
||||
previous.next = next;
|
||||
} else {
|
||||
debug_assert_eq!(self.first, Some(wire_seq));
|
||||
self.first = next;
|
||||
}
|
||||
if let Some(next) = next {
|
||||
let next = self
|
||||
.map
|
||||
.get_mut(&next)
|
||||
.expect("pending list successor remains present");
|
||||
debug_assert_eq!(next.previous, Some(wire_seq));
|
||||
next.previous = previous;
|
||||
} else {
|
||||
debug_assert_eq!(self.last, Some(wire_seq));
|
||||
self.last = previous;
|
||||
}
|
||||
|
||||
self.assert_links_consistent();
|
||||
Some(probe)
|
||||
self.map.remove(&wire_seq)
|
||||
}
|
||||
|
||||
pub(crate) fn drain_expired_bounded(&mut self, now: Instant, limit: usize) -> ExpiredBatch {
|
||||
let mut probes = Vec::with_capacity(limit.min(self.map.len()));
|
||||
while probes.len() < limit {
|
||||
let Some(wire_seq) = self.first else {
|
||||
break;
|
||||
};
|
||||
let timeout_at = self
|
||||
.map
|
||||
.get(&wire_seq)
|
||||
.expect("pending list head remains present")
|
||||
.probe
|
||||
.timeout_at;
|
||||
if timeout_at > now {
|
||||
break;
|
||||
pub fn drain_expired(&mut self, now: Instant) -> Vec<PendingProbe> {
|
||||
let expired_keys: Vec<u32> = self
|
||||
.map
|
||||
.iter()
|
||||
.filter(|(_, probe)| probe.timeout_at <= now)
|
||||
.map(|(key, _)| *key)
|
||||
.collect();
|
||||
let mut expired = Vec::with_capacity(expired_keys.len());
|
||||
for key in expired_keys {
|
||||
if let Some(probe) = self.map.remove(&key) {
|
||||
expired.push(probe);
|
||||
}
|
||||
|
||||
let probe = self
|
||||
.remove(wire_seq)
|
||||
.expect("pending list head remains present");
|
||||
probes.push(probe);
|
||||
}
|
||||
let more_due = self
|
||||
.first
|
||||
.and_then(|wire_seq| self.map.get(&wire_seq))
|
||||
.is_some_and(|entry| entry.probe.timeout_at <= now);
|
||||
ExpiredBatch { probes, more_due }
|
||||
expired.sort_by_key(|p| p.sent_at.mono);
|
||||
expired
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.map.len()
|
||||
}
|
||||
|
||||
/// Mutable access to a still-pending probe by wire sequence, without
|
||||
/// disturbing its position in the timeout order. Used to attach an
|
||||
/// observed kernel TX timestamp to a probe that has not yet completed or
|
||||
/// timed out.
|
||||
pub fn get_mut(&mut self, wire_seq: u32) -> Option<&mut PendingProbe> {
|
||||
self.map.get_mut(&wire_seq).map(|entry| &mut entry.probe)
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "tokio", test))]
|
||||
pub fn next_timeout_deadline(&self) -> Option<Instant> {
|
||||
self.first
|
||||
.and_then(|wire_seq| self.map.get(&wire_seq))
|
||||
.map(|entry| entry.probe.timeout_at)
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "tokio", test))]
|
||||
pub fn latest_timeout_deadline(&self) -> Option<Instant> {
|
||||
self.last
|
||||
.and_then(|wire_seq| self.map.get(&wire_seq))
|
||||
.map(|entry| entry.probe.timeout_at)
|
||||
}
|
||||
|
||||
fn assert_links_consistent(&self) {
|
||||
debug_assert_eq!(self.first.is_none(), self.map.is_empty());
|
||||
debug_assert_eq!(self.last.is_none(), self.map.is_empty());
|
||||
if let Some(first) = self.first {
|
||||
debug_assert_eq!(
|
||||
self.map
|
||||
.get(&first)
|
||||
.expect("pending list head remains present")
|
||||
.previous,
|
||||
None
|
||||
);
|
||||
}
|
||||
if let Some(last) = self.last {
|
||||
debug_assert_eq!(
|
||||
self.map
|
||||
.get(&last)
|
||||
.expect("pending list tail remains present")
|
||||
.next,
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn contains(&self, wire_seq: u32) -> bool {
|
||||
self.map.contains_key(&wire_seq)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn capacity(&self) -> usize {
|
||||
self.map.capacity()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn linkage(&self) -> (Option<u32>, Option<u32>) {
|
||||
(self.first, self.last)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn entry_links(&self, wire_seq: u32) -> Option<(Option<u32>, Option<u32>)> {
|
||||
self.map
|
||||
.get(&wire_seq)
|
||||
.map(|entry| (entry.previous, entry.next))
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_allocation_failed(source: TryReserveError) -> ClientError {
|
||||
ClientError::AllocationFailed {
|
||||
operation: "pending probe storage",
|
||||
source,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -305,33 +108,15 @@ impl TimedOutMap {
|
||||
removed
|
||||
}
|
||||
|
||||
/// Mutable access to a still-retained timed-out probe by wire sequence,
|
||||
/// without disturbing eviction order. Used to attach an observed kernel
|
||||
/// TX timestamp that arrives after the probe has already timed out.
|
||||
pub fn get_mut(&mut self, wire_seq: u32) -> Option<&mut PendingProbe> {
|
||||
self.map.get_mut(&wire_seq)
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.map.clear();
|
||||
self.insertion_order.clear();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn len(&self) -> usize {
|
||||
self.map.len()
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
pub fn latest_timeout_deadline(&self) -> Option<Instant> {
|
||||
self.map.values().map(|probe| probe.timeout_at).max()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn contains(&self, wire_seq: u32) -> bool {
|
||||
self.map.contains_key(&wire_seq)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn insertion_order_len(&self) -> usize {
|
||||
self.insertion_order.len()
|
||||
@@ -379,14 +164,6 @@ impl CompletedSet {
|
||||
self.set.contains(&seq)
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, seq: u32) -> bool {
|
||||
let removed = self.set.remove(&seq);
|
||||
if removed {
|
||||
self.insertion_order.retain(|entry| *entry != seq);
|
||||
}
|
||||
removed
|
||||
}
|
||||
|
||||
fn evict_oldest(&mut self) {
|
||||
while let Some(oldest_seq) = self.insertion_order.pop_front() {
|
||||
if self.set.remove(&oldest_seq) {
|
||||
@@ -409,239 +186,41 @@ mod tests {
|
||||
}
|
||||
|
||||
fn pending(seq: u32, timeout_at: Instant) -> PendingProbe {
|
||||
let sent_at = ts(timeout_at - Duration::from_secs(1));
|
||||
PendingProbe {
|
||||
wire_seq: seq,
|
||||
sent_at,
|
||||
sent_at: ts(timeout_at - Duration::from_secs(1)),
|
||||
timeout_at,
|
||||
tx_not_before_wall: sent_at.wall,
|
||||
kernel_tx_timestamp: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn insert(map: &mut PendingMap, probe: PendingProbe) {
|
||||
map.preflight_insert(probe.wire_seq).unwrap();
|
||||
map.commit_insert(probe);
|
||||
#[test]
|
||||
fn pending_map_insert_and_remove() {
|
||||
let mut map = PendingMap::new(10);
|
||||
let now = Instant::now();
|
||||
let probe = pending(0, now + Duration::from_secs(4));
|
||||
map.insert(probe).unwrap();
|
||||
assert_eq!(map.len(), 1);
|
||||
assert!(map.remove(0).is_some());
|
||||
assert_eq!(map.len(), 0);
|
||||
assert!(map.remove(0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_map_rejects_over_capacity() {
|
||||
let mut map = PendingMap::new(2);
|
||||
let now = Instant::now();
|
||||
map.preflight_insert(0).unwrap();
|
||||
map.commit_insert(pending(0, now + Duration::from_secs(4)));
|
||||
map.preflight_insert(1).unwrap();
|
||||
map.commit_insert(pending(1, now + Duration::from_secs(4)));
|
||||
map.insert(pending(0, now + Duration::from_secs(4)))
|
||||
.unwrap();
|
||||
map.insert(pending(1, now + Duration::from_secs(4)))
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
map.preflight_insert(2),
|
||||
map.insert(pending(2, now + Duration::from_secs(4))),
|
||||
Err(ClientError::PendingLimitExceeded { limit: 2 })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_map_preflight_reserves_without_changing_contents() {
|
||||
let mut map = PendingMap::new(2);
|
||||
let initial_capacity = map.capacity();
|
||||
|
||||
map.preflight_insert(7).unwrap();
|
||||
let reserved_capacity = map.capacity();
|
||||
assert!(reserved_capacity >= initial_capacity);
|
||||
assert_eq!(map.len(), 0);
|
||||
assert!(!map.contains(7));
|
||||
|
||||
map.preflight_insert(7).unwrap();
|
||||
assert_eq!(map.capacity(), reserved_capacity);
|
||||
assert_eq!(map.len(), 0);
|
||||
assert!(!map.contains(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_map_preflight_rejects_sequence_collision() {
|
||||
let mut map = PendingMap::new(2);
|
||||
let now = Instant::now();
|
||||
map.preflight_insert(9).unwrap();
|
||||
map.commit_insert(pending(9, now));
|
||||
|
||||
assert!(matches!(
|
||||
map.preflight_insert(9),
|
||||
Err(ClientError::PendingSequenceCollision { seq: 9 })
|
||||
));
|
||||
assert_eq!(map.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_map_allocation_failure_maps_to_dedicated_error() {
|
||||
let mut map = HashMap::<u32, PendingProbe>::new();
|
||||
let source = map.try_reserve(usize::MAX).unwrap_err();
|
||||
|
||||
assert!(matches!(
|
||||
pending_allocation_failed(source),
|
||||
ClientError::AllocationFailed {
|
||||
operation: "pending probe storage",
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_map_unlinks_head_middle_and_tail_and_updates_extrema() {
|
||||
let mut map = PendingMap::new(4);
|
||||
let now = Instant::now();
|
||||
insert(&mut map, pending(1, now + Duration::from_secs(1)));
|
||||
insert(&mut map, pending(2, now + Duration::from_secs(2)));
|
||||
insert(&mut map, pending(3, now + Duration::from_secs(3)));
|
||||
|
||||
assert_eq!(
|
||||
map.next_timeout_deadline(),
|
||||
Some(now + Duration::from_secs(1))
|
||||
);
|
||||
assert_eq!(
|
||||
map.latest_timeout_deadline(),
|
||||
Some(now + Duration::from_secs(3))
|
||||
);
|
||||
assert_eq!(map.linkage(), (Some(1), Some(3)));
|
||||
assert_eq!(map.entry_links(1), Some((None, Some(2))));
|
||||
assert_eq!(map.entry_links(2), Some((Some(1), Some(3))));
|
||||
assert_eq!(map.entry_links(3), Some((Some(2), None)));
|
||||
|
||||
assert!(map.remove(2).is_some());
|
||||
assert_eq!(
|
||||
map.next_timeout_deadline(),
|
||||
Some(now + Duration::from_secs(1))
|
||||
);
|
||||
assert_eq!(
|
||||
map.latest_timeout_deadline(),
|
||||
Some(now + Duration::from_secs(3))
|
||||
);
|
||||
assert_eq!(map.linkage(), (Some(1), Some(3)));
|
||||
assert_eq!(map.entry_links(1), Some((None, Some(3))));
|
||||
assert_eq!(map.entry_links(3), Some((Some(1), None)));
|
||||
|
||||
assert!(map.remove(1).is_some());
|
||||
assert_eq!(
|
||||
map.next_timeout_deadline(),
|
||||
Some(now + Duration::from_secs(3))
|
||||
);
|
||||
assert_eq!(
|
||||
map.latest_timeout_deadline(),
|
||||
Some(now + Duration::from_secs(3))
|
||||
);
|
||||
assert_eq!(map.linkage(), (Some(3), Some(3)));
|
||||
assert_eq!(map.entry_links(3), Some((None, None)));
|
||||
|
||||
assert!(map.remove(3).is_some());
|
||||
assert_eq!(map.next_timeout_deadline(), None);
|
||||
assert_eq!(map.latest_timeout_deadline(), None);
|
||||
assert_eq!(map.linkage(), (None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_map_bounded_expiration_matches_exhaustive_order() {
|
||||
let now = Instant::now();
|
||||
let probes = [
|
||||
pending(1, now + Duration::from_secs(1)),
|
||||
pending(2, now + Duration::from_secs(2)),
|
||||
pending(3, now + Duration::from_secs(3)),
|
||||
pending(4, now + Duration::from_secs(4)),
|
||||
];
|
||||
let mut bounded = PendingMap::new(probes.len());
|
||||
let mut exhaustive = PendingMap::new(probes.len());
|
||||
for probe in probes.iter().cloned() {
|
||||
insert(&mut bounded, probe.clone());
|
||||
insert(&mut exhaustive, probe);
|
||||
}
|
||||
|
||||
let empty = bounded.drain_expired_bounded(now + Duration::from_secs(4), 0);
|
||||
assert!(empty.probes.is_empty());
|
||||
assert!(empty.more_due);
|
||||
assert_eq!(bounded.linkage(), (Some(1), Some(4)));
|
||||
|
||||
let mut actual = Vec::new();
|
||||
loop {
|
||||
let batch = bounded.drain_expired_bounded(now + Duration::from_secs(4), 2);
|
||||
actual.extend(batch.probes.into_iter().map(|probe| probe.wire_seq));
|
||||
if !batch.more_due {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let expected = exhaustive
|
||||
.drain_expired_bounded(now + Duration::from_secs(4), usize::MAX)
|
||||
.probes
|
||||
.into_iter()
|
||||
.map(|probe| probe.wire_seq)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(actual, expected);
|
||||
assert_eq!(actual, vec![1, 2, 3, 4]);
|
||||
assert_eq!(bounded.linkage(), (None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_map_sequence_reuse_leaves_no_stale_link() {
|
||||
let mut map = PendingMap::new(1);
|
||||
let now = Instant::now();
|
||||
insert(&mut map, pending(7, now));
|
||||
assert!(map.remove(7).is_some());
|
||||
insert(&mut map, pending(7, now + Duration::from_secs(1)));
|
||||
|
||||
assert!(map.drain_expired_bounded(now, usize::MAX).probes.is_empty());
|
||||
assert_eq!(map.linkage(), (Some(7), Some(7)));
|
||||
assert_eq!(map.entry_links(7), Some((None, None)));
|
||||
assert_eq!(
|
||||
map.drain_expired_bounded(now + Duration::from_secs(1), usize::MAX)
|
||||
.probes
|
||||
.into_iter()
|
||||
.map(|probe| probe.wire_seq)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![7]
|
||||
);
|
||||
assert_eq!(map.linkage(), (None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_map_commit_uses_only_preflighted_map_capacity() {
|
||||
let mut map = PendingMap::new(2);
|
||||
let now = Instant::now();
|
||||
map.preflight_insert(7).unwrap();
|
||||
let capacity = map.capacity();
|
||||
|
||||
map.commit_insert(pending(7, now));
|
||||
|
||||
assert_eq!(map.capacity(), capacity);
|
||||
assert_eq!(map.len(), 1);
|
||||
assert_eq!(map.linkage(), (Some(7), Some(7)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_map_mixed_removals_preserve_links() {
|
||||
let mut map = PendingMap::new(4);
|
||||
let now = Instant::now();
|
||||
for seq in 1..=4 {
|
||||
insert(
|
||||
&mut map,
|
||||
pending(seq, now + Duration::from_secs(u64::from(seq))),
|
||||
);
|
||||
}
|
||||
|
||||
assert!(map.remove(2).is_some());
|
||||
assert_eq!(map.entry_links(1), Some((None, Some(3))));
|
||||
assert_eq!(map.entry_links(3), Some((Some(1), Some(4))));
|
||||
let expired = map.drain_expired_bounded(now + Duration::from_secs(3), usize::MAX);
|
||||
assert_eq!(
|
||||
expired
|
||||
.probes
|
||||
.into_iter()
|
||||
.map(|probe| probe.wire_seq)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![1, 3]
|
||||
);
|
||||
assert_eq!(map.linkage(), (Some(4), Some(4)));
|
||||
assert!(map.remove(4).is_some());
|
||||
assert_eq!(map.linkage(), (None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_probe_tracking_evicts_oldest_entries() {
|
||||
fn completed_set_tracks_and_evicts() {
|
||||
let mut set = CompletedSet::new(3);
|
||||
set.insert(0);
|
||||
set.insert(1);
|
||||
@@ -653,7 +232,10 @@ mod tests {
|
||||
assert_eq!(set.set.len(), 3);
|
||||
assert!(!set.contains(0));
|
||||
assert!(set.contains(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timed_out_map_tracks_and_evicts() {
|
||||
let mut map = TimedOutMap::new(2);
|
||||
let now = Instant::now();
|
||||
map.insert(pending(0, now));
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use std::{
|
||||
io,
|
||||
net::{SocketAddr, UdpSocket},
|
||||
time::SystemTime,
|
||||
};
|
||||
|
||||
use crate::{metadata::ReceiveMeta, timing::ClientTimestamp};
|
||||
@@ -39,32 +38,6 @@ pub(crate) fn recv_datagram(
|
||||
linux::recv_datagram(socket, buf)
|
||||
}
|
||||
|
||||
#[cfg(all(
|
||||
feature = "tokio",
|
||||
not(all(target_os = "linux", feature = "ancillary"))
|
||||
))]
|
||||
pub(crate) fn try_recv_tokio_datagram(
|
||||
socket: &tokio::net::UdpSocket,
|
||||
buf: &mut [u8],
|
||||
) -> Result<ReceivedDatagram, io::Error> {
|
||||
let len = socket.try_recv(buf)?;
|
||||
let received_at = ClientTimestamp::now();
|
||||
|
||||
Ok(ReceivedDatagram {
|
||||
len,
|
||||
received_at,
|
||||
meta: ReceiveMeta::default(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "tokio", target_os = "linux", feature = "ancillary"))]
|
||||
pub(crate) fn try_recv_tokio_datagram(
|
||||
socket: &tokio::net::UdpSocket,
|
||||
buf: &mut [u8],
|
||||
) -> Result<ReceivedDatagram, io::Error> {
|
||||
linux::try_recv_tokio_datagram(socket, buf)
|
||||
}
|
||||
|
||||
#[cfg(not(all(target_os = "linux", feature = "ancillary")))]
|
||||
pub(crate) fn configure_receive_metadata(
|
||||
_socket: &UdpSocket,
|
||||
@@ -78,40 +51,6 @@ pub(crate) fn configure_receive_metadata(socket: &UdpSocket, remote: SocketAddr)
|
||||
linux::configure_receive_metadata(socket, remote)
|
||||
}
|
||||
|
||||
/// Best-effort upgrade a socket from RX-only to RX+TX kernel software
|
||||
/// timestamping. Returns whether the upgrade succeeded; a caller should
|
||||
/// track this to skip later drains entirely rather than perform harmless
|
||||
/// no-op ones. Always returns `false` off Linux or without the `ancillary`
|
||||
/// feature, so callers never need their own platform `cfg`.
|
||||
#[cfg(not(all(target_os = "linux", feature = "ancillary")))]
|
||||
pub(crate) fn try_enable_tx_timestamping<S>(_socket: &S) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "linux", feature = "ancillary"))]
|
||||
pub(crate) fn try_enable_tx_timestamping<S: std::os::fd::AsFd>(socket: &S) -> bool {
|
||||
linux::try_enable_tx_timestamping(socket)
|
||||
}
|
||||
|
||||
/// Bounded, nonblocking drain of `socket`'s `MSG_ERRQUEUE`, reporting each
|
||||
/// usable TX timestamp completion to `on_timestamp`. Always a no-op off
|
||||
/// Linux or without the `ancillary` feature.
|
||||
#[cfg(not(all(target_os = "linux", feature = "ancillary")))]
|
||||
pub(crate) fn drain_tx_timestamps<S>(
|
||||
_socket: &S,
|
||||
_on_timestamp: impl FnMut(u32, SystemTime),
|
||||
) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "linux", feature = "ancillary"))]
|
||||
pub(crate) fn drain_tx_timestamps<S: std::os::fd::AsRawFd>(
|
||||
socket: &S,
|
||||
on_timestamp: impl FnMut(u32, SystemTime),
|
||||
) -> io::Result<()> {
|
||||
linux::drain_tx_timestamps(socket, on_timestamp)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::net::UdpSocket;
|
||||
@@ -162,29 +101,4 @@ mod tests {
|
||||
assert!(datagram.received_at.mono >= before.mono);
|
||||
assert!(datagram.received_at.mono <= after.mono);
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
#[test]
|
||||
fn tokio_try_receive_preserves_fallback_metadata_and_would_block() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_io()
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
runtime.block_on(async {
|
||||
let (sender, receiver) = connected_loopback_pair();
|
||||
receiver.set_nonblocking(true).unwrap();
|
||||
let receiver = tokio::net::UdpSocket::from_std(receiver).unwrap();
|
||||
sender.send(b"tokio").unwrap();
|
||||
receiver.readable().await.unwrap();
|
||||
|
||||
let mut buf = [0_u8; 16];
|
||||
let datagram = super::try_recv_tokio_datagram(&receiver, &mut buf).unwrap();
|
||||
assert_eq!(&buf[..datagram.len], b"tokio");
|
||||
assert_eq!(datagram.meta, ReceiveMeta::default());
|
||||
|
||||
let error = super::try_recv_tokio_datagram(&receiver, &mut buf).unwrap_err();
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::WouldBlock);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,133 +1,18 @@
|
||||
//! Linux ancillary receive and transmit metadata.
|
||||
//!
|
||||
//! Receive kernel timing uses `SO_TIMESTAMPING` with `RX_SOFTWARE` +
|
||||
//! `SOFTWARE` (reported via `SCM_TIMESTAMPING`), not the older
|
||||
//! `SO_TIMESTAMPNS`/`SCM_TIMESTAMPNS`. Linux documents fallback quirks when
|
||||
//! `SO_TIMESTAMP[NS]` and `SO_TIMESTAMPING` are both enabled on one socket,
|
||||
//! so this establishes one unambiguous software-timestamp facility. `ReceiveMeta`'s
|
||||
//! semantics — an optional observed kernel receive wall time, used for
|
||||
//! downstream one-way delay only when plausible relative to the userspace
|
||||
//! receive sample — are unchanged by any of this module's TX-side additions.
|
||||
//!
|
||||
//! After a successful Open, the client adapter best-effort upgrades the
|
||||
//! socket from [`RX_TIMESTAMPING_FLAGS`] to [`error_queue::TX_TIMESTAMPING_FLAGS`]
|
||||
//! via [`try_enable_tx_timestamping`]. When that succeeds, the automatic
|
||||
//! `SOF_TIMESTAMPING_OPT_ID` counter the kernel assigns to each successfully
|
||||
//! submitted datagram is used directly as the probe's wire sequence number
|
||||
//! (see the client crate's `AGENTS.md` for the correlation invariant this
|
||||
//! relies on). [`drain_tx_timestamps`] performs a small bounded, nonblocking
|
||||
//! read of `MSG_ERRQUEUE` so the adapter can opportunistically collect those
|
||||
//! timestamps without ever waiting for one. The observed kernel TX wall time
|
||||
//! is retained as metadata only; it is not consumed by any measurement in
|
||||
//! this change.
|
||||
|
||||
#![allow(unsafe_code)]
|
||||
use std::{
|
||||
io::{self, IoSliceMut},
|
||||
io, mem,
|
||||
net::{SocketAddr, UdpSocket},
|
||||
os::fd::{AsFd, AsRawFd, RawFd},
|
||||
os::fd::AsRawFd,
|
||||
ptr,
|
||||
time::{Duration, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
use nix::sys::{
|
||||
socket::{
|
||||
cmsg_space, recvmsg, setsockopt, sockopt, ControlMessageOwned, MsgFlags, RecvMsg,
|
||||
TimestampingFlag, Timestamps,
|
||||
},
|
||||
time::TimeSpec,
|
||||
};
|
||||
|
||||
use crate::{metadata::ReceiveMeta, receive::ReceivedDatagram, timing::ClientTimestamp};
|
||||
|
||||
pub(crate) mod error_queue;
|
||||
|
||||
use error_queue::ErrorQueueRecord;
|
||||
|
||||
/// Starvation guard on one opportunistic `MSG_ERRQUEUE` drain.
|
||||
///
|
||||
/// Each successfully submitted, TX-timestamped datagram generates at most
|
||||
/// one record, and drains happen at several natural choke points (after a
|
||||
/// probe send, after a normal receive, before timeout expiry), so this is
|
||||
/// not a queue-capacity promise: it just bounds the work one drain call can
|
||||
/// do. A handful of in-flight probes' worth of backlog is the realistic
|
||||
/// case between choke points, so a small constant comfortably covers it
|
||||
/// without any unbounded loop.
|
||||
pub(crate) const MAX_TX_TIMESTAMP_RECORDS_PER_DRAIN: usize = 32;
|
||||
|
||||
/// Best-effort upgrade from RX-only to RX+TX `SO_TIMESTAMPING` flags.
|
||||
///
|
||||
/// Returns `true` when the upgrade succeeded and the caller may now expect
|
||||
/// `MSG_ERRQUEUE` TX timestamp records for subsequent sends. On failure, the
|
||||
/// original [`RX_TIMESTAMPING_FLAGS`] are best-effort restored so a failed
|
||||
/// upgrade cannot leave the socket without the RX timestamping this client
|
||||
/// already depends on; that restore's own failure is not observable here
|
||||
/// (both leave the caller without TX capability, which this return value
|
||||
/// already reports).
|
||||
pub(crate) fn try_enable_tx_timestamping<S: AsFd>(socket: &S) -> bool {
|
||||
if setsockopt(
|
||||
socket,
|
||||
sockopt::Timestamping,
|
||||
&error_queue::TX_TIMESTAMPING_FLAGS,
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let _ = setsockopt(socket, sockopt::Timestamping, &RX_TIMESTAMPING_FLAGS);
|
||||
false
|
||||
}
|
||||
|
||||
/// Bounded, nonblocking drain of `fd`'s `MSG_ERRQUEUE`.
|
||||
///
|
||||
/// Reads and classifies up to [`MAX_TX_TIMESTAMP_RECORDS_PER_DRAIN`] records,
|
||||
/// one at a time with no intermediate allocation. Each usable TX timestamp
|
||||
/// completion is reported to `on_timestamp` immediately. Malformed or
|
||||
/// unsupported timestamp notifications and unrelated records are silently
|
||||
/// dropped: timestamp metadata is optional and never fails a probe. A
|
||||
/// genuine non-timestamp socket/network error stops the drain and is
|
||||
/// returned to the caller, which decides how to surface it.
|
||||
pub(crate) fn drain_tx_timestamps<S: AsRawFd>(
|
||||
socket: &S,
|
||||
mut on_timestamp: impl FnMut(u32, SystemTime),
|
||||
) -> io::Result<()> {
|
||||
let fd = socket.as_raw_fd();
|
||||
for _ in 0..MAX_TX_TIMESTAMP_RECORDS_PER_DRAIN {
|
||||
match error_queue::try_recv_error_queue_record(fd)? {
|
||||
None => return Ok(()),
|
||||
Some(ErrorQueueRecord::TxTimestamp { id, timestamp }) => on_timestamp(id, timestamp),
|
||||
Some(ErrorQueueRecord::MalformedOrUnsupportedTimestamp | ErrorQueueRecord::Ignored) => {
|
||||
}
|
||||
Some(ErrorQueueRecord::SocketError { errno, .. }) => {
|
||||
return Err(io::Error::from_raw_os_error(errno));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `SO_TIMESTAMPING` flags requested on every production socket at
|
||||
/// connect time, before any TX upgrade is attempted.
|
||||
///
|
||||
/// `SOF_TIMESTAMPING_RX_SOFTWARE` asks the kernel to generate a software
|
||||
/// receive timestamp for each datagram; `SOF_TIMESTAMPING_SOFTWARE` asks it
|
||||
/// to report that timestamp back via `SCM_TIMESTAMPING`. Mixing this API with
|
||||
/// the older `SO_TIMESTAMP`/`SO_TIMESTAMPNS` on the same socket has
|
||||
/// documented fallback quirks, so the client uses `SO_TIMESTAMPING`
|
||||
/// exclusively for receive timing. Hardware and TX-side flags are
|
||||
/// deliberately excluded here: a fresh socket is receive-only until (and
|
||||
/// unless) [`try_enable_tx_timestamping`] later upgrades it.
|
||||
const RX_TIMESTAMPING_FLAGS: TimestampingFlag = TimestampingFlag::SOF_TIMESTAMPING_RX_SOFTWARE
|
||||
.union(TimestampingFlag::SOF_TIMESTAMPING_SOFTWARE);
|
||||
|
||||
/// Control buffer capacity for a normal receive: one `SCM_TIMESTAMPING`
|
||||
/// record (three `TimeSpec`s) plus one traffic-class record. Only one of
|
||||
/// `IP_TOS` (`u8`) or `IPV6_TCLASS` (`i32`) is ever requested on a given
|
||||
/// socket, but `cmsg_space` already rounds both up to the same aligned
|
||||
/// space, so sizing on the larger of the two costs nothing and covers
|
||||
/// either family.
|
||||
const CONTROL_LEN: usize = cmsg_space::<Timestamps>() + cmsg_space::<i32>();
|
||||
const CONTROL_LEN: usize = 128;
|
||||
|
||||
pub(crate) fn configure_receive_metadata(socket: &UdpSocket, remote: SocketAddr) -> io::Result<()> {
|
||||
setsockopt(socket, sockopt::Timestamping, &RX_TIMESTAMPING_FLAGS)?;
|
||||
enable_kernel_rx_timestamps(socket)?;
|
||||
let socket = socket2::SockRef::from(socket);
|
||||
if remote.is_ipv4() {
|
||||
socket.set_recv_tos_v4(true)
|
||||
@@ -136,80 +21,136 @@ pub(crate) fn configure_receive_metadata(socket: &UdpSocket, remote: SocketAddr)
|
||||
}
|
||||
}
|
||||
|
||||
fn enable_kernel_rx_timestamps(socket: &UdpSocket) -> io::Result<()> {
|
||||
let enabled: libc::c_int = 1;
|
||||
let result = unsafe {
|
||||
// SAFETY: The file descriptor is borrowed from a valid `UdpSocket`.
|
||||
// `enabled` is a properly aligned `c_int`, and the length matches the
|
||||
// pointed-to value for the `SO_TIMESTAMPNS` boolean socket option.
|
||||
libc::setsockopt(
|
||||
socket.as_raw_fd(),
|
||||
libc::SOL_SOCKET,
|
||||
libc::SO_TIMESTAMPNS,
|
||||
(&enabled as *const libc::c_int).cast(),
|
||||
mem::size_of_val(&enabled) as libc::socklen_t,
|
||||
)
|
||||
};
|
||||
if result == -1 {
|
||||
Err(io::Error::last_os_error())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn recv_datagram(
|
||||
socket: &UdpSocket,
|
||||
buf: &mut [u8],
|
||||
) -> Result<ReceivedDatagram, io::Error> {
|
||||
recv_datagram_fd(socket.as_raw_fd(), buf, MsgFlags::empty())
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
pub(crate) fn try_recv_tokio_datagram(
|
||||
socket: &tokio::net::UdpSocket,
|
||||
buf: &mut [u8],
|
||||
) -> Result<ReceivedDatagram, io::Error> {
|
||||
socket.try_io(tokio::io::Interest::READABLE, || {
|
||||
recv_datagram_fd(socket.as_raw_fd(), buf, MsgFlags::MSG_DONTWAIT)
|
||||
})
|
||||
}
|
||||
|
||||
fn recv_datagram_fd(
|
||||
socket_fd: RawFd,
|
||||
buf: &mut [u8],
|
||||
flags: MsgFlags,
|
||||
) -> Result<ReceivedDatagram, io::Error> {
|
||||
let mut control = ControlBuffer::new();
|
||||
let mut iov = [IoSliceMut::new(buf)];
|
||||
let mut iov = libc::iovec {
|
||||
iov_base: buf.as_mut_ptr().cast(),
|
||||
iov_len: buf.len(),
|
||||
};
|
||||
let mut msg: libc::msghdr = unsafe { mem::zeroed() };
|
||||
msg.msg_iov = &mut iov;
|
||||
msg.msg_iovlen = 1;
|
||||
msg.msg_control = control.as_mut_ptr().cast();
|
||||
msg.msg_controllen = control.len();
|
||||
|
||||
// The socket is connected, so the source address is not needed; `()` skips
|
||||
// copying it out.
|
||||
let msg = recvmsg::<()>(socket_fd, &mut iov, Some(control.as_mut_slice()), flags)?;
|
||||
let len = unsafe {
|
||||
// SAFETY: `msg` points to one writable iovec backed by `buf`, and the
|
||||
// control buffer is writable and lives until `recvmsg` returns. The
|
||||
// socket file descriptor is borrowed from a valid `UdpSocket`.
|
||||
libc::recvmsg(socket.as_raw_fd(), &mut msg, 0)
|
||||
};
|
||||
if len < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let len = usize::try_from(len).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"recvmsg returned an unrepresentable datagram length",
|
||||
)
|
||||
})?;
|
||||
let received_at = ClientTimestamp::now();
|
||||
|
||||
Ok(ReceivedDatagram {
|
||||
len: msg.bytes,
|
||||
received_at,
|
||||
meta: receive_meta(&msg),
|
||||
})
|
||||
}
|
||||
|
||||
fn receive_meta<S>(msg: &RecvMsg<'_, '_, S>) -> ReceiveMeta {
|
||||
let mut meta = ReceiveMeta::default();
|
||||
// A control buffer the kernel had to truncate (`MSG_CTRUNC`) cannot be
|
||||
// walked reliably, so `cmsgs` refuses to parse it. The datagram itself is
|
||||
// still valid; report it without ancillary metadata.
|
||||
let Ok(cmsgs) = msg.cmsgs() else {
|
||||
return meta;
|
||||
let meta = unsafe {
|
||||
// SAFETY: `msg` was initialized by a successful `recvmsg` call. The
|
||||
// parser only reads cmsghdr entries within `msg_controllen` and ignores
|
||||
// short or unrelated control messages.
|
||||
parse_receive_meta(&msg)
|
||||
};
|
||||
|
||||
for cmsg in cmsgs {
|
||||
match cmsg {
|
||||
ControlMessageOwned::ScmTimestampsns(timestamps) => {
|
||||
meta.kernel_rx_timestamp = system_time_from_timespec(timestamps.system);
|
||||
}
|
||||
ControlMessageOwned::Ipv4Tos(tos) => {
|
||||
meta.traffic_class = Some(tos);
|
||||
}
|
||||
ControlMessageOwned::Ipv6TClass(traffic_class) => {
|
||||
meta.traffic_class = u8::try_from(traffic_class).ok();
|
||||
}
|
||||
_ => {}
|
||||
Ok(ReceivedDatagram {
|
||||
len,
|
||||
received_at,
|
||||
meta,
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn parse_receive_meta(msg: &libc::msghdr) -> ReceiveMeta {
|
||||
let mut meta = ReceiveMeta::default();
|
||||
let mut cmsg = libc::CMSG_FIRSTHDR(msg);
|
||||
while !cmsg.is_null() {
|
||||
let cmsg_ref = &*cmsg;
|
||||
let header_len = libc::CMSG_LEN(0) as usize;
|
||||
if cmsg_ref.cmsg_len < header_len {
|
||||
cmsg = libc::CMSG_NXTHDR(msg, cmsg);
|
||||
continue;
|
||||
}
|
||||
let data_len = cmsg_ref.cmsg_len - header_len;
|
||||
if is_traffic_class_cmsg(cmsg_ref) {
|
||||
meta.traffic_class = read_int_cmsg_low_byte(cmsg, data_len);
|
||||
} else if is_kernel_rx_timestamp_cmsg(cmsg_ref) {
|
||||
meta.kernel_rx_timestamp = read_timespec_cmsg(cmsg, data_len);
|
||||
}
|
||||
cmsg = libc::CMSG_NXTHDR(msg, cmsg);
|
||||
}
|
||||
meta
|
||||
}
|
||||
|
||||
fn system_time_from_timespec(timespec: TimeSpec) -> Option<SystemTime> {
|
||||
let seconds = u64::try_from(timespec.tv_sec()).ok()?;
|
||||
let nanos = u32::try_from(timespec.tv_nsec()).ok()?;
|
||||
if nanos >= 1_000_000_000 {
|
||||
fn is_traffic_class_cmsg(cmsg: &libc::cmsghdr) -> bool {
|
||||
(cmsg.cmsg_level == libc::IPPROTO_IP && cmsg.cmsg_type == libc::IP_TOS)
|
||||
|| (cmsg.cmsg_level == libc::IPPROTO_IPV6 && cmsg.cmsg_type == libc::IPV6_TCLASS)
|
||||
}
|
||||
|
||||
fn is_kernel_rx_timestamp_cmsg(cmsg: &libc::cmsghdr) -> bool {
|
||||
cmsg.cmsg_level == libc::SOL_SOCKET && cmsg.cmsg_type == libc::SCM_TIMESTAMPNS
|
||||
}
|
||||
|
||||
unsafe fn read_u8_cmsg(cmsg: *mut libc::cmsghdr, data_len: usize) -> Option<u8> {
|
||||
if data_len >= mem::size_of::<u8>() {
|
||||
Some(*libc::CMSG_DATA(cmsg).cast::<u8>())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn read_int_cmsg_low_byte(cmsg: *mut libc::cmsghdr, data_len: usize) -> Option<u8> {
|
||||
if data_len >= mem::size_of::<libc::c_int>() {
|
||||
let value = ptr::read_unaligned(libc::CMSG_DATA(cmsg).cast::<libc::c_int>());
|
||||
Some((value & 0xff) as u8)
|
||||
} else {
|
||||
read_u8_cmsg(cmsg, data_len)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn read_timespec_cmsg(cmsg: *mut libc::cmsghdr, data_len: usize) -> Option<SystemTime> {
|
||||
if data_len < mem::size_of::<libc::timespec>() {
|
||||
return None;
|
||||
}
|
||||
let timespec = ptr::read_unaligned(libc::CMSG_DATA(cmsg).cast::<libc::timespec>());
|
||||
system_time_from_timespec(timespec)
|
||||
}
|
||||
|
||||
fn system_time_from_timespec(timespec: libc::timespec) -> Option<SystemTime> {
|
||||
if timespec.tv_sec < 0 || timespec.tv_nsec < 0 || timespec.tv_nsec >= 1_000_000_000 {
|
||||
return None;
|
||||
}
|
||||
let seconds = u64::try_from(timespec.tv_sec).ok()?;
|
||||
let nanos = u32::try_from(timespec.tv_nsec).ok()?;
|
||||
UNIX_EPOCH.checked_add(Duration::new(seconds, nanos))
|
||||
}
|
||||
|
||||
/// Reusable per-receive control buffer. `recvmsg` control data must satisfy
|
||||
/// `cmsghdr` alignment, which 8-byte alignment covers on supported targets.
|
||||
#[repr(align(8))]
|
||||
struct ControlBuffer([u8; CONTROL_LEN]);
|
||||
|
||||
@@ -218,8 +159,12 @@ impl ControlBuffer {
|
||||
Self([0; CONTROL_LEN])
|
||||
}
|
||||
|
||||
fn as_mut_slice(&mut self) -> &mut [u8] {
|
||||
&mut self.0
|
||||
fn as_mut_ptr(&mut self) -> *mut u8 {
|
||||
self.0.as_mut_ptr()
|
||||
}
|
||||
|
||||
fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,12 +176,10 @@ mod tests {
|
||||
time::{Duration, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
use nix::sys::time::TimeSpec;
|
||||
|
||||
use crate::{
|
||||
event::PacketMeta,
|
||||
receive::{configure_receive_metadata, recv_datagram},
|
||||
socket_options::apply_traffic_class_to_socket,
|
||||
socket_options::apply_dscp_to_socket,
|
||||
timing::ClientTimestamp,
|
||||
};
|
||||
|
||||
@@ -318,52 +261,6 @@ mod tests {
|
||||
assert!(datagram.received_at.mono <= after.mono);
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
#[test]
|
||||
fn tokio_recvmsg_would_block_clears_readiness() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_io()
|
||||
.enable_time()
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
runtime.block_on(async {
|
||||
let (sender, receiver) = connected_ipv4_loopback_pair();
|
||||
configure_receive_metadata(&receiver, sender.local_addr().unwrap()).unwrap();
|
||||
receiver.set_nonblocking(true).unwrap();
|
||||
let receiver = tokio::net::UdpSocket::from_std(receiver).unwrap();
|
||||
let mut buf = [0_u8; 16];
|
||||
|
||||
sender.send(b"first").unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(1), receiver.readable())
|
||||
.await
|
||||
.expect("initial readability timed out")
|
||||
.unwrap();
|
||||
|
||||
let first = super::try_recv_tokio_datagram(&receiver, &mut buf).unwrap();
|
||||
assert_eq!(&buf[..first.len], b"first");
|
||||
|
||||
let error = super::try_recv_tokio_datagram(&receiver, &mut buf).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::WouldBlock);
|
||||
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(20), receiver.readable())
|
||||
.await
|
||||
.is_err(),
|
||||
"readable completed from stale readiness after recvmsg WouldBlock"
|
||||
);
|
||||
|
||||
sender.send(b"second").unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(1), receiver.readable())
|
||||
.await
|
||||
.expect("second readability timed out")
|
||||
.unwrap();
|
||||
|
||||
let second = super::try_recv_tokio_datagram(&receiver, &mut buf).unwrap();
|
||||
assert_eq!(&buf[..second.len], b"second");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kernel_rx_timestamp_metadata_is_observed_when_kernel_provides_it() {
|
||||
let (sender, receiver) = connected_ipv4_loopback_pair();
|
||||
@@ -376,7 +273,7 @@ mod tests {
|
||||
assert_eq!(&buf[..datagram.len], b"stamp");
|
||||
let Some(timestamp) = datagram.meta.kernel_rx_timestamp else {
|
||||
eprintln!(
|
||||
"skipping kernel timestamp assertion: kernel did not provide SCM_TIMESTAMPING"
|
||||
"skipping kernel timestamp assertion: kernel did not provide SCM_TIMESTAMPNS"
|
||||
);
|
||||
return;
|
||||
};
|
||||
@@ -385,36 +282,11 @@ mod tests {
|
||||
assert!(duration.as_nanos() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kernel_rx_timestamp_and_traffic_class_coexist() {
|
||||
let (sender, receiver) = connected_ipv4_loopback_pair();
|
||||
configure_receive_metadata(&receiver, sender.local_addr().unwrap()).unwrap();
|
||||
apply_traffic_class_to_socket(&sender, receiver.local_addr().unwrap(), 184).unwrap();
|
||||
sender.send(b"both").unwrap();
|
||||
|
||||
let mut buf = [0_u8; 16];
|
||||
let datagram = recv_datagram(&receiver, &mut buf).unwrap();
|
||||
assert_eq!(&buf[..datagram.len], b"both");
|
||||
|
||||
// Both cmsgs are requested on this socket; the parser must not
|
||||
// depend on the order the kernel emits them in to observe either.
|
||||
if datagram.meta.kernel_rx_timestamp.is_none() {
|
||||
eprintln!("skipping combined assertion: kernel did not provide SCM_TIMESTAMPING");
|
||||
return;
|
||||
}
|
||||
if datagram.meta.traffic_class.is_none() {
|
||||
eprintln!("skipping combined assertion: kernel did not provide IP_TOS");
|
||||
return;
|
||||
}
|
||||
assert!(datagram.meta.kernel_rx_timestamp.is_some());
|
||||
assert_eq!(datagram.meta.traffic_class.unwrap() & 0xfc, 184);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ipv4_traffic_class_metadata_is_observed_when_kernel_provides_it() {
|
||||
let (sender, receiver) = connected_ipv4_loopback_pair();
|
||||
configure_receive_metadata(&receiver, sender.local_addr().unwrap()).unwrap();
|
||||
apply_traffic_class_to_socket(&sender, receiver.local_addr().unwrap(), 184).unwrap();
|
||||
apply_dscp_to_socket(&sender, receiver.local_addr().unwrap(), 46).unwrap();
|
||||
sender.send(b"dscp").unwrap();
|
||||
|
||||
let mut buf = [0_u8; 16];
|
||||
@@ -436,7 +308,7 @@ mod tests {
|
||||
return;
|
||||
};
|
||||
configure_receive_metadata(&receiver, sender.local_addr().unwrap()).unwrap();
|
||||
apply_traffic_class_to_socket(&sender, receiver.local_addr().unwrap(), 184).unwrap();
|
||||
apply_dscp_to_socket(&sender, receiver.local_addr().unwrap(), 46).unwrap();
|
||||
sender.send(b"dscp").unwrap();
|
||||
|
||||
let mut buf = [0_u8; 16];
|
||||
@@ -476,7 +348,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn timespec_conversion_accepts_valid_unix_timestamp() {
|
||||
let timestamp = super::system_time_from_timespec(TimeSpec::new(1, 2)).unwrap();
|
||||
let timestamp = super::system_time_from_timespec(libc::timespec {
|
||||
tv_sec: 1,
|
||||
tv_nsec: 2,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
timestamp.duration_since(UNIX_EPOCH).unwrap(),
|
||||
@@ -486,10 +362,25 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn timespec_conversion_rejects_negative_or_invalid_values() {
|
||||
assert_eq!(super::system_time_from_timespec(TimeSpec::new(-1, 0)), None);
|
||||
assert_eq!(super::system_time_from_timespec(TimeSpec::new(0, -1)), None);
|
||||
assert_eq!(
|
||||
super::system_time_from_timespec(TimeSpec::new(0, 1_000_000_000)),
|
||||
super::system_time_from_timespec(libc::timespec {
|
||||
tv_sec: -1,
|
||||
tv_nsec: 0,
|
||||
}),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
super::system_time_from_timespec(libc::timespec {
|
||||
tv_sec: 0,
|
||||
tv_nsec: -1,
|
||||
}),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
super::system_time_from_timespec(libc::timespec {
|
||||
tv_sec: 0,
|
||||
tv_nsec: 1_000_000_000,
|
||||
}),
|
||||
None
|
||||
);
|
||||
}
|
||||
@@ -500,55 +391,4 @@ mod tests {
|
||||
io::ErrorKind::AddrNotAvailable | io::ErrorKind::Unsupported
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn try_enable_tx_timestamping_then_drain_reports_ids_through_the_adapter_api() {
|
||||
let (socket, _peer) = connected_ipv4_loopback_pair();
|
||||
// Mirrors production: RX-only first, then a best-effort upgrade.
|
||||
configure_receive_metadata(&socket, socket.peer_addr().unwrap()).unwrap();
|
||||
|
||||
if !super::try_enable_tx_timestamping(&socket) {
|
||||
eprintln!(
|
||||
"skipping adapter-level TX timestamping smoke test: kernel/container denied \
|
||||
SO_TIMESTAMPING TX flags"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if let Err(error) = socket.send(b"one") {
|
||||
eprintln!("skipping adapter-level TX timestamping smoke test: send failed: {error}");
|
||||
return;
|
||||
}
|
||||
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(2);
|
||||
let mut observed = None;
|
||||
while observed.is_none() && std::time::Instant::now() < deadline {
|
||||
super::drain_tx_timestamps(&socket, |id, timestamp| {
|
||||
observed = Some((id, timestamp));
|
||||
})
|
||||
.unwrap();
|
||||
std::thread::yield_now();
|
||||
}
|
||||
|
||||
let Some((id, timestamp)) = observed else {
|
||||
eprintln!(
|
||||
"skipping adapter-level TX timestamping smoke test: no TX timestamp record \
|
||||
arrived within the poll deadline"
|
||||
);
|
||||
return;
|
||||
};
|
||||
assert_eq!(id, 0);
|
||||
assert!(timestamp.duration_since(UNIX_EPOCH).unwrap() > Duration::ZERO);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drain_tx_timestamps_is_a_bounded_nonblocking_no_op_on_an_untouched_socket() {
|
||||
let (socket, _peer) = connected_ipv4_loopback_pair();
|
||||
configure_receive_metadata(&socket, socket.peer_addr().unwrap()).unwrap();
|
||||
|
||||
let mut calls = 0_usize;
|
||||
super::drain_tx_timestamps(&socket, |_, _| calls += 1).unwrap();
|
||||
|
||||
assert_eq!(calls, 0);
|
||||
}
|
||||
}
|
||||
@@ -1,645 +0,0 @@
|
||||
//! Safe `MSG_ERRQUEUE` primitives backing the client's TX timestamp capture.
|
||||
//!
|
||||
//! A production socket that successfully upgraded to
|
||||
//! [`TX_TIMESTAMPING_FLAGS`] receives one extended-error record per
|
||||
//! successfully submitted timestamped datagram on `MSG_ERRQUEUE`.
|
||||
//! [`try_recv_error_queue_record`] performs one nonblocking read of that
|
||||
//! queue and [`classify`] turns its ancillary data into an
|
||||
//! [`ErrorQueueRecord`] without ever panicking or requiring the caller to
|
||||
//! understand cmsg layout.
|
||||
|
||||
use std::{
|
||||
io::{self, IoSliceMut},
|
||||
os::fd::RawFd,
|
||||
time::SystemTime,
|
||||
};
|
||||
|
||||
use nix::{
|
||||
errno::Errno,
|
||||
sys::socket::{
|
||||
cmsg_space, recvmsg, ControlMessageOwned, MsgFlags, TimestampingFlag, Timestamps,
|
||||
},
|
||||
};
|
||||
|
||||
use super::system_time_from_timespec;
|
||||
|
||||
/// `SO_TIMESTAMPING` configuration for a TX-timestamped socket. Combines the
|
||||
/// module's RX flags with the TX-side flags TX capture needs: `TX_SOFTWARE`
|
||||
/// to generate a send timestamp, `OPT_ID` for automatic per-datagram
|
||||
/// correlation, and `OPT_TSONLY` so the notification does not need to
|
||||
/// retain or copy the original payload.
|
||||
pub(crate) const TX_TIMESTAMPING_FLAGS: TimestampingFlag =
|
||||
TimestampingFlag::SOF_TIMESTAMPING_RX_SOFTWARE
|
||||
.union(TimestampingFlag::SOF_TIMESTAMPING_SOFTWARE)
|
||||
.union(TimestampingFlag::SOF_TIMESTAMPING_TX_SOFTWARE)
|
||||
.union(TimestampingFlag::SOF_TIMESTAMPING_OPT_ID)
|
||||
.union(TimestampingFlag::SOF_TIMESTAMPING_OPT_TSONLY);
|
||||
|
||||
/// `SCM_TSTAMP_SND`, the send-timestamp completion kind reported in the
|
||||
/// `ee_info` field of a `SO_EE_ORIGIN_TIMESTAMPING` extended error.
|
||||
///
|
||||
/// Not exposed by `libc` or `nix`. Value verified against the kernel UAPI
|
||||
/// enum in `include/uapi/linux/errqueue.h`:
|
||||
/// `enum { SCM_TSTAMP_SND, SCM_TSTAMP_SCHED, SCM_TSTAMP_ACK };`, so
|
||||
/// `SCM_TSTAMP_SND == 0`. This is a stable, long-documented UAPI value, not
|
||||
/// a guess.
|
||||
const SCM_TSTAMP_SND: u32 = 0;
|
||||
|
||||
/// A large-enough placeholder for the offender address `sock_extended_err`
|
||||
/// is followed by in the kernel's error-queue cmsg payload (the address is
|
||||
/// present for network-originated errors, absent for local/timestamp
|
||||
/// ones). Sized generously so `cmsg_space` reserves enough control-buffer
|
||||
/// capacity for either an `IPv4` or `IPv6` offender address; never read.
|
||||
#[repr(C)]
|
||||
struct ExtendedErrWithAddr {
|
||||
_err: nix::libc::sock_extended_err,
|
||||
_addr: nix::libc::sockaddr_in6,
|
||||
}
|
||||
|
||||
/// Control buffer capacity for one error-queue receive: one extended-error
|
||||
/// record (with room for the largest possible offender address) plus one
|
||||
/// `SCM_TIMESTAMPING` record.
|
||||
const ERROR_QUEUE_CONTROL_LEN: usize =
|
||||
cmsg_space::<ExtendedErrWithAddr>() + cmsg_space::<Timestamps>();
|
||||
|
||||
/// A classified record read from a socket's `MSG_ERRQUEUE`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum ErrorQueueRecord {
|
||||
/// A genuine send-timestamp completion: the extended error's origin was
|
||||
/// `SO_EE_ORIGIN_TIMESTAMPING`, its kind was `SCM_TSTAMP_SND`, and a
|
||||
/// usable software timestamp accompanied it.
|
||||
TxTimestamp { id: u32, timestamp: SystemTime },
|
||||
/// The extended error's origin was `SO_EE_ORIGIN_TIMESTAMPING` (i.e. this
|
||||
/// is unambiguously a timestamp facility record, never a real
|
||||
/// socket/network error), but it was not a usable send-timestamp
|
||||
/// completion: the completion kind was not `SCM_TSTAMP_SND` (this client
|
||||
/// requests only `TX_SOFTWARE`, so only `SND` is expected, but an
|
||||
/// unrequested kind must not be mistaken for a socket failure), the
|
||||
/// `SCM_TIMESTAMPING` cmsg was missing, or its value failed to convert
|
||||
/// to a `SystemTime`. An accuracy failure, not a socket failure.
|
||||
MalformedOrUnsupportedTimestamp,
|
||||
/// An extended error whose origin was not `SO_EE_ORIGIN_TIMESTAMPING`: a
|
||||
/// real network, local, or ICMP error surfaced on the error queue. Must
|
||||
/// not be misclassified as malformed timing metadata.
|
||||
SocketError { errno: i32, origin: u8 },
|
||||
/// No extended error was present in this record's control data (e.g.
|
||||
/// only unrelated/unknown cmsgs).
|
||||
Ignored,
|
||||
}
|
||||
|
||||
/// Classify a decoded set of cmsgs from one `MSG_ERRQUEUE` datagram.
|
||||
///
|
||||
/// Collects the extended error and any accompanying timestamp
|
||||
/// independently before classifying, so cmsg order never matters. Origin is
|
||||
/// the sole discriminator between a timestamp facility record and a real
|
||||
/// socket error: any `SO_EE_ORIGIN_TIMESTAMPING` record is timing metadata,
|
||||
/// however unexpected its `errno`/`ee_info`, and only ever becomes
|
||||
/// [`ErrorQueueRecord::MalformedOrUnsupportedTimestamp`] on the way to
|
||||
/// `None` — never [`ErrorQueueRecord::SocketError`]. A timestamp is only
|
||||
/// ever attached to a timestamp-origin record reporting `SCM_TSTAMP_SND`.
|
||||
pub(crate) fn classify(cmsgs: impl Iterator<Item = ControlMessageOwned>) -> ErrorQueueRecord {
|
||||
let mut extended_error: Option<(u32, u8, u32, u32)> = None;
|
||||
let mut timestamp: Option<Timestamps> = None;
|
||||
|
||||
for cmsg in cmsgs {
|
||||
match cmsg {
|
||||
ControlMessageOwned::Ipv4RecvErr(err, _) => {
|
||||
extended_error = Some((err.ee_errno, err.ee_origin, err.ee_info, err.ee_data));
|
||||
}
|
||||
ControlMessageOwned::Ipv6RecvErr(err, _) => {
|
||||
extended_error = Some((err.ee_errno, err.ee_origin, err.ee_info, err.ee_data));
|
||||
}
|
||||
ControlMessageOwned::ScmTimestampsns(observed) => {
|
||||
timestamp = Some(observed);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let Some((errno, origin, info, id)) = extended_error else {
|
||||
return ErrorQueueRecord::Ignored;
|
||||
};
|
||||
|
||||
if origin != nix::libc::SO_EE_ORIGIN_TIMESTAMPING {
|
||||
return ErrorQueueRecord::SocketError {
|
||||
errno: errno as i32,
|
||||
origin,
|
||||
};
|
||||
}
|
||||
|
||||
let is_send_completion = errno == nix::libc::ENOMSG as u32 && info == SCM_TSTAMP_SND;
|
||||
if !is_send_completion {
|
||||
return ErrorQueueRecord::MalformedOrUnsupportedTimestamp;
|
||||
}
|
||||
|
||||
match timestamp.and_then(|observed| system_time_from_timespec(observed.system)) {
|
||||
Some(timestamp) => ErrorQueueRecord::TxTimestamp { id, timestamp },
|
||||
None => ErrorQueueRecord::MalformedOrUnsupportedTimestamp,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reusable per-receive control buffer. `recvmsg` control data must satisfy
|
||||
/// `cmsghdr` alignment; a plain `[u8; N]` only guarantees byte alignment, so
|
||||
/// this mirrors the parent module's `ControlBuffer` rather than reading
|
||||
/// `cmsghdr`s out of unaligned storage.
|
||||
#[repr(align(8))]
|
||||
struct ErrorQueueControlBuffer([u8; ERROR_QUEUE_CONTROL_LEN]);
|
||||
|
||||
impl ErrorQueueControlBuffer {
|
||||
fn new() -> Self {
|
||||
Self([0; ERROR_QUEUE_CONTROL_LEN])
|
||||
}
|
||||
}
|
||||
|
||||
/// Nonblocking drain of a single record from `fd`'s `MSG_ERRQUEUE`.
|
||||
///
|
||||
/// Returns `Ok(None)` when the queue is empty (`EAGAIN`/`EWOULDBLOCK`) — the
|
||||
/// caller in [`super::drain_tx_timestamps`] stops its drain there, exactly
|
||||
/// as it always has. An interrupted read (`EINTR`) is different: it says
|
||||
/// nothing about whether the queue is empty, so treating it the same as
|
||||
/// `EWOULDBLOCK` could end a drain early and strand a still-queued record
|
||||
/// past the point its matching probe is looked up and removed (see the
|
||||
/// crate's `AGENTS.md`). TX timestamp capture is optional best-effort
|
||||
/// metadata, not a network operation, so an interruption here must also
|
||||
/// never become a socket/network error; instead it is reported as
|
||||
/// [`ErrorQueueRecord::Ignored`], which consumes one attempt of the bounded
|
||||
/// caller's existing per-drain work budget and lets the loop immediately
|
||||
/// retry the same slot rather than stopping or spinning unboundedly.
|
||||
/// `SOF_TIMESTAMPING_OPT_TSONLY` notifications carry no meaningful payload,
|
||||
/// so a zero-length iovec is enough: correlation is by `id`, never by
|
||||
/// payload content.
|
||||
pub(crate) fn try_recv_error_queue_record(fd: RawFd) -> io::Result<Option<ErrorQueueRecord>> {
|
||||
let mut payload: [u8; 0] = [];
|
||||
let mut iov = [IoSliceMut::new(&mut payload)];
|
||||
let mut control = ErrorQueueControlBuffer::new();
|
||||
|
||||
match recvmsg::<()>(
|
||||
fd,
|
||||
&mut iov,
|
||||
Some(&mut control.0),
|
||||
MsgFlags::MSG_ERRQUEUE | MsgFlags::MSG_DONTWAIT,
|
||||
) {
|
||||
Ok(msg) => {
|
||||
let cmsgs = msg
|
||||
.cmsgs()
|
||||
.map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?;
|
||||
Ok(Some(classify(cmsgs)))
|
||||
}
|
||||
Err(Errno::EWOULDBLOCK) => Ok(None),
|
||||
Err(Errno::EINTR) => Ok(Some(ErrorQueueRecord::Ignored)),
|
||||
Err(errno) => Err(io::Error::from(errno)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
net::{SocketAddr, UdpSocket},
|
||||
os::fd::AsRawFd,
|
||||
time::{Duration, Instant, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
use nix::sys::{
|
||||
socket::{setsockopt, sockopt},
|
||||
time::TimeSpec,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn extended_error(
|
||||
errno: u32,
|
||||
origin: u8,
|
||||
info: u32,
|
||||
data: u32,
|
||||
) -> nix::libc::sock_extended_err {
|
||||
nix::libc::sock_extended_err {
|
||||
ee_errno: errno,
|
||||
ee_origin: origin,
|
||||
ee_type: 0,
|
||||
ee_code: 0,
|
||||
ee_pad: 0,
|
||||
ee_info: info,
|
||||
ee_data: data,
|
||||
}
|
||||
}
|
||||
|
||||
fn timestamps_with_system(system: TimeSpec) -> Timestamps {
|
||||
Timestamps {
|
||||
system,
|
||||
hw_trans: TimeSpec::new(0, 0),
|
||||
hw_raw: TimeSpec::new(0, 0),
|
||||
}
|
||||
}
|
||||
|
||||
fn send_timestamp_error(id: u32) -> ControlMessageOwned {
|
||||
ControlMessageOwned::Ipv4RecvErr(
|
||||
extended_error(
|
||||
nix::libc::ENOMSG as u32,
|
||||
nix::libc::SO_EE_ORIGIN_TIMESTAMPING,
|
||||
SCM_TSTAMP_SND,
|
||||
id,
|
||||
),
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_valid_send_timestamp_completion() {
|
||||
let cmsgs = vec![
|
||||
send_timestamp_error(7),
|
||||
ControlMessageOwned::ScmTimestampsns(timestamps_with_system(TimeSpec::new(1, 2))),
|
||||
];
|
||||
|
||||
let record = classify(cmsgs.into_iter());
|
||||
|
||||
assert_eq!(
|
||||
record,
|
||||
ErrorQueueRecord::TxTimestamp {
|
||||
id: 7,
|
||||
timestamp: UNIX_EPOCH + Duration::new(1, 2),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_timestamp_origin_without_timestamp_as_malformed() {
|
||||
let cmsgs = vec![send_timestamp_error(3)];
|
||||
|
||||
assert_eq!(
|
||||
classify(cmsgs.into_iter()),
|
||||
ErrorQueueRecord::MalformedOrUnsupportedTimestamp
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_timestamp_origin_with_invalid_timespec_as_malformed() {
|
||||
let cmsgs = vec![
|
||||
send_timestamp_error(3),
|
||||
ControlMessageOwned::ScmTimestampsns(timestamps_with_system(TimeSpec::new(-1, 0))),
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
classify(cmsgs.into_iter()),
|
||||
ErrorQueueRecord::MalformedOrUnsupportedTimestamp
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_non_timestamp_extended_error_as_socket_error() {
|
||||
let cmsgs = vec![ControlMessageOwned::Ipv4RecvErr(
|
||||
extended_error(
|
||||
nix::libc::ECONNREFUSED as u32,
|
||||
nix::libc::SO_EE_ORIGIN_ICMP,
|
||||
0,
|
||||
0,
|
||||
),
|
||||
None,
|
||||
)];
|
||||
|
||||
assert_eq!(
|
||||
classify(cmsgs.into_iter()),
|
||||
ErrorQueueRecord::SocketError {
|
||||
errno: nix::libc::ECONNREFUSED,
|
||||
origin: nix::libc::SO_EE_ORIGIN_ICMP,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_timestamping_origin_with_wrong_completion_kind_as_malformed() {
|
||||
// Same origin byte as a send-timestamp completion, but a different
|
||||
// `ee_info` (e.g. SCM_TSTAMP_SCHED/ACK, which this client never
|
||||
// requests). A timestamping-origin record must never become a
|
||||
// fatal SocketError merely because it reports a completion kind we
|
||||
// did not ask for; it stays timing metadata.
|
||||
let cmsgs = vec![ControlMessageOwned::Ipv4RecvErr(
|
||||
extended_error(
|
||||
nix::libc::ENOMSG as u32,
|
||||
nix::libc::SO_EE_ORIGIN_TIMESTAMPING,
|
||||
1,
|
||||
0,
|
||||
),
|
||||
None,
|
||||
)];
|
||||
|
||||
assert_eq!(
|
||||
classify(cmsgs.into_iter()),
|
||||
ErrorQueueRecord::MalformedOrUnsupportedTimestamp
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_timestamping_origin_with_unexpected_errno_as_malformed() {
|
||||
// Origin is the sole discriminator: even an origin==TIMESTAMPING
|
||||
// record with a surprising errno (the kernel always reports ENOMSG
|
||||
// for this origin, but classification must not assume that) is
|
||||
// still timing metadata, never a real socket error.
|
||||
let cmsgs = vec![ControlMessageOwned::Ipv4RecvErr(
|
||||
extended_error(
|
||||
nix::libc::ECONNREFUSED as u32,
|
||||
nix::libc::SO_EE_ORIGIN_TIMESTAMPING,
|
||||
SCM_TSTAMP_SND,
|
||||
0,
|
||||
),
|
||||
None,
|
||||
)];
|
||||
|
||||
assert_eq!(
|
||||
classify(cmsgs.into_iter()),
|
||||
ErrorQueueRecord::MalformedOrUnsupportedTimestamp
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_records_without_any_extended_error() {
|
||||
let cmsgs = vec![ControlMessageOwned::Ipv4Tos(0)];
|
||||
|
||||
assert_eq!(classify(cmsgs.into_iter()), ErrorQueueRecord::Ignored);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_cmsgs_do_not_affect_classification() {
|
||||
let cmsgs = vec![
|
||||
ControlMessageOwned::Ipv4Tos(0),
|
||||
send_timestamp_error(4),
|
||||
ControlMessageOwned::ScmTimestampsns(timestamps_with_system(TimeSpec::new(9, 0))),
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
classify(cmsgs.into_iter()),
|
||||
ErrorQueueRecord::TxTimestamp {
|
||||
id: 4,
|
||||
timestamp: UNIX_EPOCH + Duration::new(9, 0),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmsg_order_does_not_affect_classification() {
|
||||
let forward = classify(
|
||||
vec![
|
||||
send_timestamp_error(9),
|
||||
ControlMessageOwned::ScmTimestampsns(timestamps_with_system(TimeSpec::new(5, 0))),
|
||||
]
|
||||
.into_iter(),
|
||||
);
|
||||
let reversed = classify(
|
||||
vec![
|
||||
ControlMessageOwned::ScmTimestampsns(timestamps_with_system(TimeSpec::new(5, 0))),
|
||||
send_timestamp_error(9),
|
||||
]
|
||||
.into_iter(),
|
||||
);
|
||||
|
||||
assert_eq!(forward, reversed);
|
||||
}
|
||||
|
||||
/// Bounded poll for one error-queue record, since software TX timestamp
|
||||
/// delivery is asynchronous even on loopback. Never sleeps hoping
|
||||
/// delivery "probably" happened; it keeps polling until either a
|
||||
/// record appears or the overall deadline passes.
|
||||
fn poll_for_record(fd: RawFd, overall_timeout: Duration) -> Option<ErrorQueueRecord> {
|
||||
let deadline = Instant::now() + overall_timeout;
|
||||
loop {
|
||||
if let Some(record) = try_recv_error_queue_record(fd).unwrap() {
|
||||
return Some(record);
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return None;
|
||||
}
|
||||
std::thread::yield_now();
|
||||
}
|
||||
}
|
||||
|
||||
fn tx_timestamped_loopback_socket() -> Option<(UdpSocket, UdpSocket)> {
|
||||
let socket = UdpSocket::bind(SocketAddr::from(([127, 0, 0, 1], 0))).unwrap();
|
||||
// Held for the caller's lifetime: if this peer socket were dropped,
|
||||
// its port would close and subsequent sends would fail with
|
||||
// ECONNREFUSED once the kernel reports ICMP port-unreachable.
|
||||
let peer = UdpSocket::bind(SocketAddr::from(([127, 0, 0, 1], 0))).unwrap();
|
||||
socket.connect(peer.local_addr().unwrap()).unwrap();
|
||||
|
||||
match setsockopt(&socket, sockopt::Timestamping, &TX_TIMESTAMPING_FLAGS) {
|
||||
Ok(()) => Some((socket, peer)),
|
||||
Err(error) => {
|
||||
eprintln!(
|
||||
"skipping TX timestamping smoke test: kernel/container denied \
|
||||
SO_TIMESTAMPING TX flags: {error}"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_opt_id_increments_sequentially_across_separate_sends() {
|
||||
let Some((socket, _peer)) = tx_timestamped_loopback_socket() else {
|
||||
return;
|
||||
};
|
||||
let fd = socket.as_raw_fd();
|
||||
|
||||
// Under heavy parallel test load, loopback UDP sends can
|
||||
// occasionally surface a stale ICMP-derived socket error unrelated
|
||||
// to this test's own sockets. That is an environmental condition,
|
||||
// not a claim this test makes about kernel TX timestamp behavior,
|
||||
// so it is a skip rather than a failure.
|
||||
if let Err(error) = socket.send(b"first") {
|
||||
eprintln!("skipping automatic OPT_ID assertion: first send failed: {error}");
|
||||
return;
|
||||
}
|
||||
let Some(first) = poll_for_record(fd, Duration::from_secs(2)) else {
|
||||
eprintln!(
|
||||
"skipping automatic OPT_ID assertion: no TX timestamp record was \
|
||||
delivered within the poll deadline"
|
||||
);
|
||||
return;
|
||||
};
|
||||
assert!(
|
||||
matches!(first, ErrorQueueRecord::TxTimestamp { id: 0, .. }),
|
||||
"expected first send to report id 0, got {first:?}"
|
||||
);
|
||||
|
||||
if let Err(error) = socket.send(b"second") {
|
||||
eprintln!("skipping automatic OPT_ID assertion: second send failed: {error}");
|
||||
return;
|
||||
}
|
||||
let Some(second) = poll_for_record(fd, Duration::from_secs(2)) else {
|
||||
eprintln!(
|
||||
"skipping automatic OPT_ID assertion: no TX timestamp record was \
|
||||
delivered for the second send within the poll deadline"
|
||||
);
|
||||
return;
|
||||
};
|
||||
assert!(
|
||||
matches!(second, ErrorQueueRecord::TxTimestamp { id: 1, .. }),
|
||||
"expected second send to report id 1, got {second:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rx_only_sends_before_tx_enable_do_not_consume_the_later_tx_id_namespace() {
|
||||
let socket = UdpSocket::bind(SocketAddr::from(([127, 0, 0, 1], 0))).unwrap();
|
||||
let peer = UdpSocket::bind(SocketAddr::from(([127, 0, 0, 1], 0))).unwrap();
|
||||
socket.connect(peer.local_addr().unwrap()).unwrap();
|
||||
setsockopt(
|
||||
&socket,
|
||||
sockopt::Timestamping,
|
||||
&super::super::RX_TIMESTAMPING_FLAGS,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Ordinary pre-enable sends: TX_SOFTWARE is not yet requested, so
|
||||
// none of these may leave anything on the error queue for the
|
||||
// later-enabled OPT_ID counter to have skipped past.
|
||||
for _ in 0..3 {
|
||||
if let Err(error) = socket.send(b"pre-enable") {
|
||||
eprintln!("skipping pre-enable send/RX-only smoke test: {error}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
try_recv_error_queue_record(socket.as_raw_fd()).unwrap(),
|
||||
None,
|
||||
"RX-only sends must never populate MSG_ERRQUEUE"
|
||||
);
|
||||
|
||||
// This mirrors production: RX-only is configured first (e.g. at
|
||||
// connect time), and only later, after a successful Open, is the
|
||||
// socket upgraded to TX_TIMESTAMPING_FLAGS.
|
||||
if setsockopt(&socket, sockopt::Timestamping, &TX_TIMESTAMPING_FLAGS).is_err() {
|
||||
eprintln!(
|
||||
"skipping pre-enable send/RX-only smoke test: kernel/container denied \
|
||||
SO_TIMESTAMPING TX flags"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if let Err(error) = socket.send(b"first-timestamped") {
|
||||
eprintln!(
|
||||
"skipping pre-enable send/RX-only smoke test: post-upgrade send failed: {error}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
let Some(record) = poll_for_record(socket.as_raw_fd(), Duration::from_secs(2)) else {
|
||||
eprintln!(
|
||||
"skipping pre-enable send/RX-only smoke test: no TX timestamp record was \
|
||||
delivered within the poll deadline"
|
||||
);
|
||||
return;
|
||||
};
|
||||
assert!(
|
||||
matches!(record, ErrorQueueRecord::TxTimestamp { id: 0, .. }),
|
||||
"expected the first send after upgrade to report id 0 (pre-enable sends must not \
|
||||
have consumed part of the namespace), got {record:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_rx_scm_timestamping_still_works_after_tx_flags_are_enabled() {
|
||||
let Some((socket, peer)) = tx_timestamped_loopback_socket() else {
|
||||
return;
|
||||
};
|
||||
peer.send_to(b"reply", socket.local_addr().unwrap())
|
||||
.unwrap();
|
||||
|
||||
let mut buf = [0_u8; 16];
|
||||
let Ok(datagram) = super::super::recv_datagram(&socket, &mut buf) else {
|
||||
eprintln!("skipping post-TX-enable RX smoke test: receive failed");
|
||||
return;
|
||||
};
|
||||
assert_eq!(&buf[..datagram.len], b"reply");
|
||||
let Some(timestamp) = datagram.meta.kernel_rx_timestamp else {
|
||||
eprintln!(
|
||||
"skipping post-TX-enable RX smoke test: kernel did not provide SCM_TIMESTAMPING"
|
||||
);
|
||||
return;
|
||||
};
|
||||
assert!(timestamp.duration_since(std::time::UNIX_EPOCH).unwrap() > Duration::ZERO);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tx_timestamp_and_normal_reply_streams_do_not_interfere() {
|
||||
let Some((socket, peer)) = tx_timestamped_loopback_socket() else {
|
||||
return;
|
||||
};
|
||||
let fd = socket.as_raw_fd();
|
||||
|
||||
if let Err(error) = socket.send(b"ping") {
|
||||
eprintln!("skipping TX/RX separation smoke test: ping send failed: {error}");
|
||||
return;
|
||||
}
|
||||
let mut incoming = [0_u8; 16];
|
||||
let Ok((len, from)) = peer.recv_from(&mut incoming) else {
|
||||
eprintln!("skipping TX/RX separation smoke test: peer never observed ping");
|
||||
return;
|
||||
};
|
||||
assert_eq!(&incoming[..len], b"ping");
|
||||
peer.send_to(b"pong", from).unwrap();
|
||||
|
||||
// Reading the normal payload must not require, wait for, or be
|
||||
// disturbed by draining MSG_ERRQUEUE first.
|
||||
let mut reply_buf = [0_u8; 16];
|
||||
let Ok(datagram) = super::super::recv_datagram(&socket, &mut reply_buf) else {
|
||||
eprintln!("skipping TX/RX separation smoke test: normal receive failed");
|
||||
return;
|
||||
};
|
||||
assert_eq!(&reply_buf[..datagram.len], b"pong");
|
||||
|
||||
// The TX timestamp for "ping" is still independently available on
|
||||
// the error queue, unconsumed by the normal receive above.
|
||||
let Some(record) = poll_for_record(fd, Duration::from_secs(2)) else {
|
||||
eprintln!("skipping TX/RX separation smoke test: no TX timestamp record arrived");
|
||||
return;
|
||||
};
|
||||
assert!(matches!(
|
||||
record,
|
||||
ErrorQueueRecord::TxTimestamp { id: 0, .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tx_timestamp_correlation_does_not_depend_on_original_payload() {
|
||||
let Some((socket, _peer)) = tx_timestamped_loopback_socket() else {
|
||||
return;
|
||||
};
|
||||
|
||||
// OPT_TSONLY notifications never carry the original payload; a
|
||||
// larger payload must classify identically to the zero-length one
|
||||
// used elsewhere, since correlation is by `id` alone.
|
||||
let payload = vec![0x5A_u8; 512];
|
||||
if let Err(error) = socket.send(&payload) {
|
||||
eprintln!("skipping OPT_TSONLY payload-independence smoke test: send failed: {error}");
|
||||
return;
|
||||
}
|
||||
let Some(record) = poll_for_record(socket.as_raw_fd(), Duration::from_secs(2)) else {
|
||||
eprintln!(
|
||||
"skipping OPT_TSONLY payload-independence smoke test: no TX timestamp record \
|
||||
arrived"
|
||||
);
|
||||
return;
|
||||
};
|
||||
assert!(matches!(
|
||||
record,
|
||||
ErrorQueueRecord::TxTimestamp { id: 0, .. }
|
||||
));
|
||||
}
|
||||
|
||||
// NOTE: a live test proving that a failed nonblocking `sendmsg` does not
|
||||
// consume an automatic OPT_ID is not included here. Forcing a reliable,
|
||||
// non-flaky `WouldBlock` on a connected loopback UDP socket (e.g. via
|
||||
// socket-buffer saturation) has no deterministic OS-level mechanism
|
||||
// available in this environment, and the repository's testing policy
|
||||
// explicitly forbids faking coverage with sleep/saturation-based
|
||||
// flakiness. That safety is instead established from Linux kernel
|
||||
// source: `_sock_tx_timestamp` (include/net/sock.h) and
|
||||
// `__ip_append_data`/`__ip6_append_data` (net/ipv4/ip_output.c,
|
||||
// net/ipv6/ip6_output.c) increment `sk->sk_tskey` speculatively before
|
||||
// a datagram is fully built and explicitly `atomic_dec` it back out on
|
||||
// every error path (tracked via a local `hold_tskey` flag), so a failed
|
||||
// send can never leave a gap in — or otherwise advance — the ID space
|
||||
// the kernel hands out to successfully submitted datagrams. See the
|
||||
// client crate's `AGENTS.md` for the full citation. The client-side
|
||||
// half of this invariant (a `WouldBlock` `try_send` never advances the
|
||||
// local wire-sequence counter used as the correlation ID) is covered by
|
||||
// a deterministic test in the adapter module that injects `WouldBlock`.
|
||||
}
|
||||
@@ -1,24 +1,16 @@
|
||||
use std::fmt;
|
||||
use std::{fmt, time::Instant};
|
||||
|
||||
use irtt_proto::{Clock, Params, ReceivedStats, StampAt, PROTOCOL_VERSION};
|
||||
|
||||
use crate::{config::NegotiationPolicy, error::ClientError};
|
||||
use crate::{
|
||||
config::{NegotiationPolicy, MAX_DSCP_CODEPOINT},
|
||||
error::ClientError,
|
||||
probe::{CompletedSet, PendingMap, TimedOutMap},
|
||||
};
|
||||
|
||||
/// Protocol parameters accepted for a session.
|
||||
///
|
||||
/// `params` contains the server-returned values that the client will use for
|
||||
/// echo packets. `restrictions` records accepted differences from the request
|
||||
/// when loose negotiation is enabled.
|
||||
///
|
||||
/// `params.dscp` is the raw IP TOS / Traffic Class byte, not a DSCP
|
||||
/// codepoint: for a configured codepoint of 46 (EF), an unrestricted
|
||||
/// negotiation leaves `params.dscp == 184`. [`NegotiationRestriction::DscpChanged`]
|
||||
/// reports codepoints instead, for consistency with [`crate::ClientConfig::dscp`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct NegotiatedParams {
|
||||
/// Server-returned protocol parameters used for the session.
|
||||
pub params: Params,
|
||||
/// Accepted server restrictions or parameter changes.
|
||||
pub restrictions: Vec<NegotiationRestriction>,
|
||||
}
|
||||
|
||||
@@ -59,17 +51,12 @@ pub enum NegotiationRestriction {
|
||||
/// Returned clock source differs from the request.
|
||||
ClockChanged { requested: Clock, negotiated: Clock },
|
||||
/// Returned DSCP codepoint differs from the request.
|
||||
///
|
||||
/// These values are DSCP codepoints (`0..=63`) for human-facing
|
||||
/// consistency with [`crate::ClientConfig::dscp`], not the raw wire
|
||||
/// `Params::dscp` byte carried by [`NegotiatedParams::params`].
|
||||
DscpChanged { requested: i64, negotiated: i64 },
|
||||
/// Returned server payload fill behavior differs from the request.
|
||||
ServerFillChanged,
|
||||
}
|
||||
|
||||
impl NegotiationRestriction {
|
||||
/// Return a human-readable description of this negotiated restriction.
|
||||
pub fn message(&self) -> String {
|
||||
self.to_string()
|
||||
}
|
||||
@@ -161,6 +148,28 @@ impl fmt::Display for NegotiationRestriction {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum ClientPhase {
|
||||
Connected,
|
||||
Open { token: u64 },
|
||||
NoTestCompleted,
|
||||
Closed,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ActiveSession {
|
||||
pub next_wire_seq: u32,
|
||||
pub highest_received_seq: Option<u32>,
|
||||
pub packets_sent: u64,
|
||||
pub start_mono: Instant,
|
||||
pub end_mono: Option<Instant>,
|
||||
pub next_send_at: Instant,
|
||||
pub pending: PendingMap,
|
||||
pub timed_out: TimedOutMap,
|
||||
pub completed: CompletedSet,
|
||||
pub sending_done: bool,
|
||||
}
|
||||
|
||||
pub(crate) fn negotiate_params(
|
||||
requested: &Params,
|
||||
returned: Params,
|
||||
@@ -274,11 +283,8 @@ pub(crate) fn negotiate_params(
|
||||
policy,
|
||||
&mut restrictions,
|
||||
NegotiationRestriction::DscpChanged {
|
||||
// `requested`/`negotiated` here are raw wire TOS/Traffic Class
|
||||
// bytes; shift back to the codepoint the user actually
|
||||
// configured for a human-facing restriction.
|
||||
requested: requested.dscp >> 2,
|
||||
negotiated: returned.dscp >> 2,
|
||||
requested: requested.dscp,
|
||||
negotiated: returned.dscp,
|
||||
},
|
||||
)?;
|
||||
}
|
||||
@@ -318,14 +324,10 @@ fn validate_duration_restriction(requested: i64, returned: i64) -> Result<(), Cl
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validates a server-returned `Params::dscp`, which is a raw IP TOS /
|
||||
/// Traffic Class byte and therefore valid across the full `0..=255` wire
|
||||
/// range, not the `0..=`[`MAX_DSCP_CODEPOINT`](crate::config::MAX_DSCP_CODEPOINT)
|
||||
/// range of the public codepoint.
|
||||
fn validate_dscp_restriction(returned: i64) -> Result<(), ClientError> {
|
||||
if !(0..=255).contains(&returned) {
|
||||
if !(0..=i64::from(MAX_DSCP_CODEPOINT)).contains(&returned) {
|
||||
return Err(ClientError::NegotiationRejected {
|
||||
reason: "dscp must be in range 0..=255".to_owned(),
|
||||
reason: format!("dscp must be in range 0..={MAX_DSCP_CODEPOINT}"),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -361,8 +363,7 @@ mod tests {
|
||||
received_stats: ReceivedStats::Both,
|
||||
stamp_at: StampAt::Both,
|
||||
clock: Clock::Both,
|
||||
// Raw wire TOS/Traffic Class byte for DSCP codepoint 46 (EF).
|
||||
dscp: 184,
|
||||
dscp: 46,
|
||||
server_fill: Some(ServerFill {
|
||||
value: "rand".to_owned(),
|
||||
}),
|
||||
@@ -416,8 +417,8 @@ mod tests {
|
||||
assert_eq!(
|
||||
rejection_reason(&requested, &returned, NegotiationPolicy::Strict),
|
||||
NegotiationRestriction::DscpChanged {
|
||||
requested: requested.dscp >> 2,
|
||||
negotiated: returned.dscp >> 2,
|
||||
requested: requested.dscp,
|
||||
negotiated: returned.dscp,
|
||||
}
|
||||
.message()
|
||||
);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +0,0 @@
|
||||
pub(crate) mod machine;
|
||||
mod negotiation;
|
||||
|
||||
pub(crate) use negotiation::negotiate_params;
|
||||
pub use negotiation::{NegotiatedParams, NegotiationRestriction};
|
||||
@@ -28,57 +28,18 @@ pub(crate) fn validate_open_timeouts(timeouts: &[Duration]) -> Result<(), Client
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_remote(config: &ClientConfig) -> Result<SocketAddr, ClientError> {
|
||||
#[cfg(all(test, feature = "tokio"))]
|
||||
SYNC_RESOLVER_CALLS.with(|calls| calls.set(calls.get() + 1));
|
||||
|
||||
let addr = normalize_server_addr(&config.server_addr);
|
||||
let mut addrs = addr
|
||||
.to_socket_addrs()
|
||||
.map_err(|_| ClientError::Resolve { addr: addr.clone() })?;
|
||||
addrs
|
||||
.find(|addr| address_family_allowed(config, *addr))
|
||||
.find(|addr| {
|
||||
(!config.socket_config.ipv4_only || addr.is_ipv4())
|
||||
&& (!config.socket_config.ipv6_only || addr.is_ipv6())
|
||||
})
|
||||
.ok_or(ClientError::Resolve { addr })
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
pub(crate) async fn resolve_remote_tokio(config: &ClientConfig) -> Result<SocketAddr, ClientError> {
|
||||
let addr = normalize_server_addr(&config.server_addr);
|
||||
if let Ok(remote) = addr.parse::<SocketAddr>() {
|
||||
return address_family_allowed(config, remote)
|
||||
.then_some(remote)
|
||||
.ok_or(ClientError::Resolve { addr });
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "tokio"))]
|
||||
TOKIO_DNS_LOOKUPS.with(|calls| calls.set(calls.get() + 1));
|
||||
|
||||
let mut addrs = tokio::net::lookup_host(&addr)
|
||||
.await
|
||||
.map_err(|_| ClientError::Resolve { addr: addr.clone() })?;
|
||||
addrs
|
||||
.find(|remote| address_family_allowed(config, *remote))
|
||||
.ok_or_else(|| ClientError::Resolve { addr: addr.clone() })
|
||||
}
|
||||
|
||||
fn address_family_allowed(config: &ClientConfig, remote: SocketAddr) -> bool {
|
||||
(!config.socket_config.ipv4_only || remote.is_ipv4())
|
||||
&& (!config.socket_config.ipv6_only || remote.is_ipv6())
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "tokio"))]
|
||||
std::thread_local! {
|
||||
static SYNC_RESOLVER_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
static TOKIO_DNS_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "tokio"))]
|
||||
pub(crate) fn resolution_call_counts() -> (usize, usize) {
|
||||
(
|
||||
SYNC_RESOLVER_CALLS.with(std::cell::Cell::get),
|
||||
TOKIO_DNS_LOOKUPS.with(std::cell::Cell::get),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn normalize_server_addr(addr: &str) -> String {
|
||||
if addr.parse::<SocketAddr>().is_ok() {
|
||||
return addr.to_owned();
|
||||
@@ -105,16 +66,16 @@ pub(crate) fn connect_udp_socket(
|
||||
config: &SocketConfig,
|
||||
remote: SocketAddr,
|
||||
) -> Result<UdpSocket, ClientError> {
|
||||
let socket = create_connected_udp_socket(config, remote)?;
|
||||
socket.set_read_timeout(config.recv_timeout)?;
|
||||
Ok(socket)
|
||||
}
|
||||
let domain = if remote.is_ipv4() {
|
||||
Domain::IPV4
|
||||
} else {
|
||||
Domain::IPV6
|
||||
};
|
||||
let socket = Socket::new(domain, Type::DGRAM, Some(Protocol::UDP))?;
|
||||
|
||||
fn create_connected_udp_socket(
|
||||
config: &SocketConfig,
|
||||
remote: SocketAddr,
|
||||
) -> Result<UdpSocket, ClientError> {
|
||||
let socket = create_prebind_udp_socket(config, remote)?;
|
||||
if config.ipv6_only && remote.is_ipv6() {
|
||||
socket.set_only_v6(true)?;
|
||||
}
|
||||
let bind_addr = config.bind_addr.unwrap_or_else(|| {
|
||||
if remote.is_ipv4() {
|
||||
SocketAddr::from(([0, 0, 0, 0], 0))
|
||||
@@ -134,36 +95,10 @@ fn create_connected_udp_socket(
|
||||
if let Some(ttl) = config.ttl {
|
||||
apply_ttl_to_socket(&socket, remote, ttl)?;
|
||||
}
|
||||
socket.set_read_timeout(config.recv_timeout)?;
|
||||
Ok(socket)
|
||||
}
|
||||
|
||||
fn create_prebind_udp_socket(
|
||||
config: &SocketConfig,
|
||||
remote: SocketAddr,
|
||||
) -> Result<Socket, ClientError> {
|
||||
let domain = if remote.is_ipv4() {
|
||||
Domain::IPV4
|
||||
} else {
|
||||
Domain::IPV6
|
||||
};
|
||||
let socket = Socket::new(domain, Type::DGRAM, Some(Protocol::UDP))?;
|
||||
|
||||
if config.ipv6_only && remote.is_ipv6() {
|
||||
socket.set_only_v6(true)?;
|
||||
}
|
||||
Ok(socket)
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
pub(crate) fn connect_tokio_udp_socket(
|
||||
config: &SocketConfig,
|
||||
remote: SocketAddr,
|
||||
) -> Result<tokio::net::UdpSocket, ClientError> {
|
||||
let socket = create_connected_udp_socket(config, remote)?;
|
||||
socket.set_nonblocking(true)?;
|
||||
Ok(tokio::net::UdpSocket::from_std(socket)?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -178,192 +113,4 @@ mod tests {
|
||||
assert_eq!(normalize_server_addr("[::1]"), "[::1]:2112");
|
||||
assert_eq!(normalize_server_addr("[::1]:1234"), "[::1]:1234");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn address_family_filtering_remains_unchanged() {
|
||||
let ipv4 = SocketAddr::from(([127, 0, 0, 1], DEFAULT_PORT));
|
||||
let ipv6 = SocketAddr::from(([0, 0, 0, 0, 0, 0, 0, 1], DEFAULT_PORT));
|
||||
let mut config = ClientConfig::default();
|
||||
|
||||
assert!(address_family_allowed(&config, ipv4));
|
||||
assert!(address_family_allowed(&config, ipv6));
|
||||
|
||||
config.socket_config.ipv4_only = true;
|
||||
assert!(address_family_allowed(&config, ipv4));
|
||||
assert!(!address_family_allowed(&config, ipv6));
|
||||
|
||||
config.socket_config.ipv4_only = false;
|
||||
config.socket_config.ipv6_only = true;
|
||||
assert!(!address_family_allowed(&config, ipv4));
|
||||
assert!(address_family_allowed(&config, ipv6));
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
#[test]
|
||||
fn tokio_ipv6_only_is_applied_before_bind() {
|
||||
let config = SocketConfig {
|
||||
ipv6_only: true,
|
||||
..SocketConfig::default()
|
||||
};
|
||||
let remote = SocketAddr::from(([0, 0, 0, 0, 0, 0, 0, 1], DEFAULT_PORT));
|
||||
|
||||
let socket = create_prebind_udp_socket(&config, remote).unwrap();
|
||||
|
||||
assert!(socket.only_v6().unwrap());
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
#[test]
|
||||
fn tokio_ipv6_socket_preserves_v6only_and_explicit_bind() {
|
||||
let bind_addr = SocketAddr::from(([0, 0, 0, 0, 0, 0, 0, 1], 0));
|
||||
let peer = match UdpSocket::bind(bind_addr) {
|
||||
Ok(peer) => peer,
|
||||
Err(error) if ipv6_loopback_unavailable(&error) => {
|
||||
eprintln!("skipping IPv6 Tokio socket test: IPv6 loopback unavailable: {error}");
|
||||
return;
|
||||
}
|
||||
Err(error) => panic!("{error}"),
|
||||
};
|
||||
let remote = peer.local_addr().unwrap();
|
||||
let config = SocketConfig {
|
||||
bind_addr: Some(bind_addr),
|
||||
ipv6_only: true,
|
||||
..SocketConfig::default()
|
||||
};
|
||||
|
||||
tokio_runtime().block_on(async {
|
||||
let socket = connect_tokio_udp_socket(&config, remote).unwrap();
|
||||
|
||||
assert!(socket2::SockRef::from(&socket).only_v6().unwrap());
|
||||
assert!(socket.local_addr().unwrap().is_ipv6());
|
||||
assert_eq!(socket.local_addr().unwrap().ip(), bind_addr.ip());
|
||||
assert_eq!(socket.peer_addr().unwrap(), remote);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
#[test]
|
||||
fn tokio_ipv4_socket_preserves_family_bind_peer_and_ttl() {
|
||||
let peer = UdpSocket::bind(SocketAddr::from(([127, 0, 0, 1], 0))).unwrap();
|
||||
let remote = peer.local_addr().unwrap();
|
||||
let bind_addr = SocketAddr::from(([127, 0, 0, 1], 0));
|
||||
let config = SocketConfig {
|
||||
bind_addr: Some(bind_addr),
|
||||
ttl: Some(64),
|
||||
..SocketConfig::default()
|
||||
};
|
||||
|
||||
tokio_runtime().block_on(async {
|
||||
let socket = connect_tokio_udp_socket(&config, remote).unwrap();
|
||||
|
||||
assert!(socket.local_addr().unwrap().is_ipv4());
|
||||
assert_eq!(socket.local_addr().unwrap().ip(), bind_addr.ip());
|
||||
assert_eq!(socket.peer_addr().unwrap(), remote);
|
||||
assert_eq!(socket2::SockRef::from(&socket).ttl_v4().unwrap(), 64);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
#[test]
|
||||
fn tokio_resolver_filters_families_without_using_blocking_resolution() {
|
||||
let mut config = ClientConfig {
|
||||
server_addr: "localhost:2112".to_owned(),
|
||||
..ClientConfig::default()
|
||||
};
|
||||
config.socket_config.ipv4_only = true;
|
||||
|
||||
tokio_runtime().block_on(async {
|
||||
let before = resolution_call_counts();
|
||||
let remote = resolve_remote_tokio(&config).await.unwrap();
|
||||
let after = resolution_call_counts();
|
||||
|
||||
assert!(remote.is_ipv4());
|
||||
assert_eq!(after.0, before.0);
|
||||
assert_eq!(after.1, before.1 + 1);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
#[test]
|
||||
fn tokio_resolver_selects_ipv6_for_ipv6_only_hostname() {
|
||||
let mut config = ClientConfig {
|
||||
server_addr: "localhost:2112".to_owned(),
|
||||
..ClientConfig::default()
|
||||
};
|
||||
config.socket_config.ipv6_only = true;
|
||||
|
||||
tokio_runtime().block_on(async {
|
||||
let remote = resolve_remote_tokio(&config).await.unwrap();
|
||||
assert!(remote.is_ipv6());
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
#[test]
|
||||
fn tokio_resolver_literal_path_bypasses_all_name_resolution() {
|
||||
let config = ClientConfig {
|
||||
server_addr: "127.0.0.1:2112".to_owned(),
|
||||
..ClientConfig::default()
|
||||
};
|
||||
|
||||
tokio_runtime().block_on(async {
|
||||
let before = resolution_call_counts();
|
||||
let remote = resolve_remote_tokio(&config).await.unwrap();
|
||||
let after = resolution_call_counts();
|
||||
|
||||
assert_eq!(remote, SocketAddr::from(([127, 0, 0, 1], 2112)));
|
||||
assert_eq!(after, before);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
#[test]
|
||||
fn tokio_resolver_rejects_disallowed_literal_family() {
|
||||
let mut config = ClientConfig {
|
||||
server_addr: "127.0.0.1:2112".to_owned(),
|
||||
..ClientConfig::default()
|
||||
};
|
||||
config.socket_config.ipv6_only = true;
|
||||
|
||||
tokio_runtime().block_on(async {
|
||||
assert!(matches!(
|
||||
resolve_remote_tokio(&config).await,
|
||||
Err(ClientError::Resolve { .. })
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
#[test]
|
||||
fn tokio_resolver_rejects_mixed_family_restrictions() {
|
||||
let mut config = ClientConfig {
|
||||
server_addr: "127.0.0.1:2112".to_owned(),
|
||||
..ClientConfig::default()
|
||||
};
|
||||
config.socket_config.ipv4_only = true;
|
||||
config.socket_config.ipv6_only = true;
|
||||
|
||||
tokio_runtime().block_on(async {
|
||||
assert!(matches!(
|
||||
resolve_remote_tokio(&config).await,
|
||||
Err(ClientError::Resolve { .. })
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
fn tokio_runtime() -> tokio::runtime::Runtime {
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_io()
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
fn ipv6_loopback_unavailable(error: &std::io::Error) -> bool {
|
||||
matches!(
|
||||
error.kind(),
|
||||
std::io::ErrorKind::AddrNotAvailable | std::io::ErrorKind::Unsupported
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -3,20 +3,11 @@ use std::{
|
||||
net::{SocketAddr, UdpSocket},
|
||||
};
|
||||
|
||||
use socket2::SockRef;
|
||||
|
||||
use crate::{
|
||||
config::{MAX_DSCP_CODEPOINT, MAX_TTL},
|
||||
error::ClientError,
|
||||
};
|
||||
|
||||
/// Converts a public DSCP codepoint (`0..=`[`MAX_DSCP_CODEPOINT`]) into the
|
||||
/// raw IP TOS / Traffic Class byte it occupies the upper six bits of.
|
||||
///
|
||||
/// This is the single place `codepoint << 2` is spelled out; both the
|
||||
/// config-to-wire conversion and any direct codepoint-based socket
|
||||
/// application go through this function so the shift cannot be duplicated or
|
||||
/// accidentally applied twice.
|
||||
pub(crate) fn dscp_codepoint_to_traffic_class(dscp: u8) -> Result<u32, ClientError> {
|
||||
if dscp > MAX_DSCP_CODEPOINT {
|
||||
return Err(ClientError::InvalidConfig {
|
||||
@@ -26,19 +17,13 @@ pub(crate) fn dscp_codepoint_to_traffic_class(dscp: u8) -> Result<u32, ClientErr
|
||||
Ok(u32::from(dscp) << 2)
|
||||
}
|
||||
|
||||
/// Applies an already-raw IP TOS / Traffic Class byte to the socket directly,
|
||||
/// without any codepoint shift.
|
||||
pub(crate) fn apply_traffic_class_to_socket(
|
||||
pub(crate) fn apply_dscp_to_socket(
|
||||
socket: &UdpSocket,
|
||||
remote: SocketAddr,
|
||||
traffic_class: u8,
|
||||
dscp_codepoint: u8,
|
||||
) -> Result<(), ClientError> {
|
||||
set_socket_traffic_class(
|
||||
socket,
|
||||
remote,
|
||||
u32::from(traffic_class),
|
||||
"set negotiated DSCP",
|
||||
)
|
||||
let traffic_class = dscp_codepoint_to_traffic_class(dscp_codepoint)?;
|
||||
set_socket_traffic_class(socket, remote, traffic_class, "set negotiated DSCP")
|
||||
}
|
||||
|
||||
pub(crate) fn clear_dscp_on_socket(
|
||||
@@ -48,30 +33,6 @@ pub(crate) fn clear_dscp_on_socket(
|
||||
set_socket_traffic_class(socket, remote, 0, "clear DSCP before close")
|
||||
}
|
||||
|
||||
/// Applies an already-raw IP TOS / Traffic Class byte to the Tokio socket
|
||||
/// directly, without any codepoint shift.
|
||||
#[cfg(feature = "tokio")]
|
||||
pub(crate) fn apply_traffic_class_to_tokio_socket(
|
||||
socket: &tokio::net::UdpSocket,
|
||||
remote: SocketAddr,
|
||||
traffic_class: u8,
|
||||
) -> Result<(), ClientError> {
|
||||
set_tokio_socket_traffic_class(
|
||||
socket,
|
||||
remote,
|
||||
u32::from(traffic_class),
|
||||
"set negotiated DSCP",
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
pub(crate) fn clear_dscp_on_tokio_socket(
|
||||
socket: &tokio::net::UdpSocket,
|
||||
remote: SocketAddr,
|
||||
) -> Result<(), ClientError> {
|
||||
set_tokio_socket_traffic_class(socket, remote, 0, "clear DSCP before close")
|
||||
}
|
||||
|
||||
pub(crate) fn validate_ttl(ttl: u32) -> Result<(), ClientError> {
|
||||
if ttl == 0 || ttl > MAX_TTL {
|
||||
return Err(ClientError::InvalidConfig {
|
||||
@@ -106,20 +67,6 @@ pub(crate) fn socket_traffic_class(
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "tokio"))]
|
||||
pub(crate) fn tokio_socket_traffic_class(
|
||||
socket: &tokio::net::UdpSocket,
|
||||
remote: SocketAddr,
|
||||
) -> Result<u32, ClientError> {
|
||||
get_socket_traffic_class_ref(SockRef::from(socket), remote).map_err(|source| {
|
||||
ClientError::SocketOption {
|
||||
operation: "read DSCP socket option",
|
||||
remote,
|
||||
source,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn socket_ttl(socket: &UdpSocket, remote: SocketAddr) -> Result<u32, ClientError> {
|
||||
get_socket_ttl(socket, remote).map_err(|source| ClientError::SocketOption {
|
||||
@@ -130,24 +77,19 @@ pub(crate) fn socket_ttl(socket: &UdpSocket, remote: SocketAddr) -> Result<u32,
|
||||
}
|
||||
|
||||
fn set_socket_ttl(socket: &UdpSocket, remote: SocketAddr, ttl: u32) -> io::Result<()> {
|
||||
set_socket_ttl_ref(SockRef::from(socket), remote, ttl)
|
||||
}
|
||||
|
||||
fn set_socket_ttl_ref(socket: SockRef<'_>, remote: SocketAddr, ttl: u32) -> io::Result<()> {
|
||||
if remote.is_ipv4() {
|
||||
socket.set_ttl_v4(ttl)
|
||||
socket2::SockRef::from(socket).set_ttl_v4(ttl)
|
||||
} else {
|
||||
socket.set_unicast_hops_v6(ttl)
|
||||
socket2::SockRef::from(socket).set_unicast_hops_v6(ttl)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn get_socket_ttl(socket: &UdpSocket, remote: SocketAddr) -> io::Result<u32> {
|
||||
let socket = SockRef::from(socket);
|
||||
if remote.is_ipv4() {
|
||||
socket.ttl_v4()
|
||||
socket2::SockRef::from(socket).ttl_v4()
|
||||
} else {
|
||||
socket.unicast_hops_v6()
|
||||
socket2::SockRef::from(socket).unicast_hops_v6()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,30 +112,6 @@ fn set_socket_traffic_class_io(
|
||||
socket: &UdpSocket,
|
||||
remote: SocketAddr,
|
||||
traffic_class: u32,
|
||||
) -> io::Result<()> {
|
||||
set_socket_traffic_class_ref(SockRef::from(socket), remote, traffic_class)
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
fn set_tokio_socket_traffic_class(
|
||||
socket: &tokio::net::UdpSocket,
|
||||
remote: SocketAddr,
|
||||
traffic_class: u32,
|
||||
operation: &'static str,
|
||||
) -> Result<(), ClientError> {
|
||||
set_socket_traffic_class_ref(SockRef::from(socket), remote, traffic_class).map_err(|source| {
|
||||
ClientError::SocketOption {
|
||||
operation,
|
||||
remote,
|
||||
source,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn set_socket_traffic_class_ref(
|
||||
socket: SockRef<'_>,
|
||||
remote: SocketAddr,
|
||||
traffic_class: u32,
|
||||
) -> io::Result<()> {
|
||||
if remote.is_ipv4() {
|
||||
set_ipv4_traffic_class(socket, traffic_class)
|
||||
@@ -209,8 +127,8 @@ fn set_socket_traffic_class_ref(
|
||||
target_os = "illumos",
|
||||
target_os = "haiku",
|
||||
)))]
|
||||
fn set_ipv4_traffic_class(socket: SockRef<'_>, traffic_class: u32) -> io::Result<()> {
|
||||
socket.set_tos_v4(traffic_class)
|
||||
fn set_ipv4_traffic_class(socket: &UdpSocket, traffic_class: u32) -> io::Result<()> {
|
||||
socket2::SockRef::from(socket).set_tos_v4(traffic_class)
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
@@ -220,7 +138,7 @@ fn set_ipv4_traffic_class(socket: SockRef<'_>, traffic_class: u32) -> io::Result
|
||||
target_os = "illumos",
|
||||
target_os = "haiku",
|
||||
))]
|
||||
fn set_ipv4_traffic_class(_socket: SockRef<'_>, traffic_class: u32) -> io::Result<()> {
|
||||
fn set_ipv4_traffic_class(_socket: &UdpSocket, traffic_class: u32) -> io::Result<()> {
|
||||
unsupported_traffic_class(traffic_class, "IPv4 DSCP socket options")
|
||||
}
|
||||
|
||||
@@ -235,8 +153,8 @@ fn set_ipv4_traffic_class(_socket: SockRef<'_>, traffic_class: u32) -> io::Resul
|
||||
target_os = "openbsd",
|
||||
target_os = "cygwin",
|
||||
))]
|
||||
fn set_ipv6_traffic_class(socket: SockRef<'_>, traffic_class: u32) -> io::Result<()> {
|
||||
socket.set_tclass_v6(traffic_class)
|
||||
fn set_ipv6_traffic_class(socket: &UdpSocket, traffic_class: u32) -> io::Result<()> {
|
||||
socket2::SockRef::from(socket).set_tclass_v6(traffic_class)
|
||||
}
|
||||
|
||||
#[cfg(not(any(
|
||||
@@ -250,7 +168,7 @@ fn set_ipv6_traffic_class(socket: SockRef<'_>, traffic_class: u32) -> io::Result
|
||||
target_os = "openbsd",
|
||||
target_os = "cygwin",
|
||||
)))]
|
||||
fn set_ipv6_traffic_class(_socket: SockRef<'_>, traffic_class: u32) -> io::Result<()> {
|
||||
fn set_ipv6_traffic_class(_socket: &UdpSocket, traffic_class: u32) -> io::Result<()> {
|
||||
unsupported_traffic_class(traffic_class, "IPv6 DSCP socket options")
|
||||
}
|
||||
|
||||
@@ -293,8 +211,8 @@ fn unsupported_traffic_class(traffic_class: u32, feature: &'static str) -> io::R
|
||||
target_os = "haiku",
|
||||
))
|
||||
))]
|
||||
fn get_ipv4_traffic_class(socket: SockRef<'_>) -> io::Result<u32> {
|
||||
socket.tos_v4()
|
||||
fn get_ipv4_traffic_class(socket: &UdpSocket) -> io::Result<u32> {
|
||||
socket2::SockRef::from(socket).tos_v4()
|
||||
}
|
||||
|
||||
#[cfg(all(
|
||||
@@ -307,7 +225,7 @@ fn get_ipv4_traffic_class(socket: SockRef<'_>) -> io::Result<u32> {
|
||||
target_os = "haiku",
|
||||
)
|
||||
))]
|
||||
fn get_ipv4_traffic_class(_socket: SockRef<'_>) -> io::Result<u32> {
|
||||
fn get_ipv4_traffic_class(_socket: &UdpSocket) -> io::Result<u32> {
|
||||
unsupported_readback("IPv4 DSCP socket option readback")
|
||||
}
|
||||
|
||||
@@ -325,8 +243,8 @@ fn get_ipv4_traffic_class(_socket: SockRef<'_>) -> io::Result<u32> {
|
||||
target_os = "cygwin",
|
||||
)
|
||||
))]
|
||||
fn get_ipv6_traffic_class(socket: SockRef<'_>) -> io::Result<u32> {
|
||||
socket.tclass_v6()
|
||||
fn get_ipv6_traffic_class(socket: &UdpSocket) -> io::Result<u32> {
|
||||
socket2::SockRef::from(socket).tclass_v6()
|
||||
}
|
||||
|
||||
#[cfg(all(
|
||||
@@ -343,17 +261,12 @@ fn get_ipv6_traffic_class(socket: SockRef<'_>) -> io::Result<u32> {
|
||||
target_os = "cygwin",
|
||||
))
|
||||
))]
|
||||
fn get_ipv6_traffic_class(_socket: SockRef<'_>) -> io::Result<u32> {
|
||||
fn get_ipv6_traffic_class(_socket: &UdpSocket) -> io::Result<u32> {
|
||||
unsupported_readback("IPv6 DSCP socket option readback")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn get_socket_traffic_class(socket: &UdpSocket, remote: SocketAddr) -> io::Result<u32> {
|
||||
get_socket_traffic_class_ref(SockRef::from(socket), remote)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn get_socket_traffic_class_ref(socket: SockRef<'_>, remote: SocketAddr) -> io::Result<u32> {
|
||||
if remote.is_ipv4() {
|
||||
get_ipv4_traffic_class(socket)
|
||||
} else {
|
||||
@@ -473,47 +386,15 @@ mod tests {
|
||||
let socket = UdpSocket::bind(SocketAddr::from(([127, 0, 0, 1], 0))).unwrap();
|
||||
socket.connect(remote).unwrap();
|
||||
|
||||
// 184 is the raw wire TOS/Traffic Class byte for DSCP codepoint 46
|
||||
// (EF); applying it directly must not shift it again.
|
||||
apply_traffic_class_to_socket(&socket, remote, 184).unwrap();
|
||||
assert_eq!(socket_traffic_class(&socket, remote).unwrap(), 184);
|
||||
apply_dscp_to_socket(&socket, remote, 46).unwrap();
|
||||
let traffic_class = socket_traffic_class(&socket, remote).unwrap();
|
||||
assert_eq!(traffic_class & 0xfc, 184);
|
||||
assert_eq!(traffic_class & 0b11, 0);
|
||||
|
||||
clear_dscp_on_socket(&socket, remote).unwrap();
|
||||
assert_eq!(socket_traffic_class(&socket, remote).unwrap(), 0);
|
||||
}
|
||||
|
||||
#[cfg(all(
|
||||
feature = "tokio",
|
||||
not(any(
|
||||
target_os = "fuchsia",
|
||||
target_os = "redox",
|
||||
target_os = "solaris",
|
||||
target_os = "illumos",
|
||||
target_os = "haiku",
|
||||
))
|
||||
))]
|
||||
#[test]
|
||||
fn tokio_ipv4_socket_option_sets_and_clears_traffic_class() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_io()
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
runtime.block_on(async {
|
||||
let remote = SocketAddr::from(([127, 0, 0, 1], 9));
|
||||
let socket = UdpSocket::bind(SocketAddr::from(([127, 0, 0, 1], 0))).unwrap();
|
||||
socket.connect(remote).unwrap();
|
||||
socket.set_nonblocking(true).unwrap();
|
||||
let socket = tokio::net::UdpSocket::from_std(socket).unwrap();
|
||||
|
||||
apply_traffic_class_to_tokio_socket(&socket, remote, 184).unwrap();
|
||||
assert_eq!(tokio_socket_traffic_class(&socket, remote).unwrap(), 184);
|
||||
|
||||
clear_dscp_on_tokio_socket(&socket, remote).unwrap();
|
||||
assert_eq!(tokio_socket_traffic_class(&socket, remote).unwrap(), 0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(
|
||||
target_os = "android",
|
||||
@@ -532,7 +413,7 @@ mod tests {
|
||||
return;
|
||||
};
|
||||
|
||||
apply_traffic_class_to_socket(&socket, remote, 184).unwrap();
|
||||
apply_dscp_to_socket(&socket, remote, 46).unwrap();
|
||||
let traffic_class = match socket_traffic_class(&socket, remote) {
|
||||
Ok(traffic_class) => traffic_class,
|
||||
Err(error) if is_unsupported_socket_readback(&error) => {
|
||||
@@ -541,7 +422,8 @@ mod tests {
|
||||
}
|
||||
Err(error) => panic!("{error}"),
|
||||
};
|
||||
assert_eq!(traffic_class, 184);
|
||||
assert_eq!(traffic_class & 0xfc, 184);
|
||||
assert_eq!(traffic_class & 0b11, 0);
|
||||
|
||||
clear_dscp_on_socket(&socket, remote).unwrap();
|
||||
assert_eq!(socket_traffic_class(&socket, remote).unwrap(), 0);
|
||||
|
||||
Loaded 100 of 207 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user