diff --git a/.cargo/config.toml b/.cargo/config.toml index 71480e92d..36a0b3d8c 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,5 +1,26 @@ [alias] cov = "llvm-cov" cov-lcov = "llvm-cov --lcov --output-path=./.coverage/lcov.info" +cov-codecov = "llvm-cov --codecov --output-path=./.coverage/codecov.json" cov-html = "llvm-cov --html" time = "build --timings --all-targets" + +[build] +rustflags = [ + "-D", + "warnings", + "-D", + "future-incompatible", + "-D", + "let-underscore", + "-D", + "nonstandard-style", + "-D", + "rust-2018-compatibility", + "-D", + "rust-2018-idioms", + "-D", + "rust-2021-compatibility", + "-D", + "unused", +] diff --git a/.dockerignore b/.dockerignore index 3d8a25cce..f42859922 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,16 +1,16 @@ -.git -.git-blame-ignore -.github -.gitignore -.vscode -bin/ -config.toml -config.toml.local -cSpell.json -data.db -docker/ -NOTICE -README.md -rustfmt.toml -storage/ -target/ +/.git +/.git-blame-ignore +/.github +/.gitignore +/.vscode +/bin/ +/tracker.* +/cSpell.json +/data.db +/docker/bin/ +/NOTICE +/README.md +/rustfmt.toml +/storage/ +/target/ +/etc/ diff --git a/.env.local b/.env.local deleted file mode 100644 index fefed56c4..000000000 --- a/.env.local +++ /dev/null @@ -1 +0,0 @@ -TORRUST_TRACKER_USER_UID=1000 \ No newline at end of file diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 000000000..2ae8963e3 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +/.github/**/* @torrust/maintainers diff --git a/.github/dependabot.yml b/.github/dependabot.yaml similarity index 64% rename from .github/dependabot.yml rename to .github/dependabot.yaml index 8f36cb692..becfbc1df 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yaml @@ -5,9 +5,15 @@ updates: schedule: interval: daily target-branch: "develop" + labels: + - "Continuous Integration" + - "Dependencies" - package-ecosystem: cargo directory: / schedule: interval: daily target-branch: "develop" + labels: + - "Build | Project System" + - "Dependencies" diff --git a/.github/labels.json b/.github/labels.json new file mode 100644 index 000000000..778c0c892 --- /dev/null +++ b/.github/labels.json @@ -0,0 +1,260 @@ +[ + { + "name": "- Admin -", + "color": "FFFFFF", + "description": "Enjoyable to Install and Setup our Software", + "aliases": [] + }, + { + "name": "- Contributor -", + "color": "FFFFFF", + "description": "Nice to support Torrust", + "aliases": [] + }, + { + "name": "- Developer -", + "color": "FFFFFF", + "description": "Torrust Improvement Experience", + "aliases": [] + }, + { + "name": "- User -", + "color": "FFFFFF", + "description": "Enjoyable to Use our Software", + "aliases": [] + }, + { + "name": "Blocked", + "color": "000000", + "description": "Has Unsatisfied Dependency", + "aliases": [] + }, + { + "name": "Bug", + "color": "a80506", + "description": "Incorrect Behavior", + "aliases": [] + }, + { + "name": "Build | Project System", + "color": "99AAAA", + "description": "Compiling and Packaging", + "aliases": ["Rust"] + }, + { + "name": "Cannot Reproduce", + "color": "D3D3D3", + "description": "Inconsistent Observations", + "aliases": [] + }, + { + "name": "Code Cleanup / Refactoring", + "color": "055a8b", + "description": "Tidying and Making Neat", + "aliases": [] + }, + { + "name": "Continuous Integration", + "color": "41c6b3", + "description": "Workflows and Automation", + "aliases": [] + }, + { + "name": "Dependencies", + "color": "d4f8f6", + "description": "Related to Dependencies", + "aliases": [] + }, + { + "name": "Documentation", + "color": "3d2133", + "description": "Improves Instructions, Guides, and Notices", + "aliases": [] + }, + { + "name": "Duplicate", + "color": "cfd3d7", + "description": "Not Unique", + "aliases": [] + }, + { + "name": "Easy", + "color": "f0cff0", + "description": "Good for Newcomers", + "aliases": [] + }, + { + "name": "Enhancement / Feature Request", + "color": "c9ecbf", + "description": "Something New", + "aliases": [] + }, + { + "name": "External Tools", + "color": "a6006b", + "description": "3rd Party Systems", + "aliases": [] + }, + { + "name": "First Time Contribution", + "color": "f1e0e6", + "description": "Welcome to Torrust", + "aliases": [] + }, + { + "name": "Fixed", + "color": "8e4c42", + "description": "Not a Concern Anymore", + "aliases": [] + }, + { + "name": "Hard", + "color": "2c2c2c", + "description": "Non-Trivial", + "aliases": [] + }, + { + "name": "Help Wanted", + "color": "00896b", + "description": "More Contributions are Appreciated", + "aliases": [] + }, + { + "name": "High Priority", + "color": "ba3fbc", + "description": "Focus Required", + "aliases": [] + }, + { + "name": "Hold Merge", + "color": "9aafbe", + "description": "We are not Ready Yet", + "aliases": [] + }, + { + "name": "Installer | Package", + "color": "ed8b24", + "description": "Distribution to Users", + "aliases": [] + }, + { + "name": "Invalid", + "color": "c1c1c1", + "description": "This doesn't seem right", + "aliases": [] + }, + { + "name": "Legal", + "color": "463e60", + "description": "Licenses and other Official Documents", + "aliases": [] + }, + { + "name": "Low Priority", + "color": "43536b", + "description": "Not our Focus Now", + "aliases": [] + }, + { + "name": "Needs Feedback", + "color": "d6946c", + "description": "What dose the Community Think?", + "aliases": [] + }, + { + "name": "Needs Rebase", + "color": "FBC002", + "description": "Base Branch has Incompatibilities", + "aliases": [] + }, + { + "name": "Needs Research", + "color": "4bc021", + "description": "We Need to Know More About This", + "aliases": [] + }, + { + "name": "Optimization", + "color": "faeba8", + "description": "Make it Faster", + "aliases": [] + }, + { + "name": "Portability", + "color": "95de82", + "description": "Distribution to More Places", + "aliases": [] + }, + { + "name": "Postponed", + "color": "dadada", + "description": "For Later", + "aliases": [] + }, + { + "name": "Quality & Assurance", + "color": "eea2e8", + "description": "Relates to QA, Testing, and CI", + "aliases": [] + }, + { + "name": "Question / Discussion", + "color": "f89d00", + "description": "Community Feedback", + "aliases": [] + }, + { + "name": "Regression", + "color": "d10588", + "description": "It dose not work anymore", + "aliases": [] + }, + { + "name": "Reviewed", + "color": "f4f4ea", + "description": "This Looks Good", + "aliases": [] + }, + { + "name": "Security", + "color": "650606", + "description": "Publicly Connected to Security", + "aliases": [] + }, + { + "name": "Testing", + "color": "c5def5", + "description": "Checking Torrust", + "aliases": [] + }, + { + "name": "Translations", + "color": "0c86af", + "description": "Localization and Cultural Adaptions", + "aliases": [] + }, + { + "name": "Trivial", + "color": "5f9685", + "description": "Something Easy", + "aliases": [] + }, + { + "name": "Won't Fix", + "color": "070003", + "description": "Something Not Relevant", + "aliases": [] + }, + { + "name": "Workaround Possible", + "color": "eae3e7", + "description": "You can still do it another way", + "aliases": [] + }, + { + "name": "good first issue", + "color": "b0fc38", + "description": "Feel free to seek assistance when needed", + "aliases": [] + } +] diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml deleted file mode 100644 index 05551bafc..000000000 --- a/.github/workflows/codecov.yml +++ /dev/null @@ -1,40 +0,0 @@ -name: Upload code coverage - -on: - push: - pull_request: - -env: - CARGO_TERM_COLOR: always - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: nightly - components: rustfmt, llvm-tools-preview - - name: Build - run: cargo build --release - env: - CARGO_INCREMENTAL: "0" - RUSTFLAGS: "-Cinstrument-coverage" - RUSTDOCFLAGS: "-Cinstrument-coverage" - - name: Test - run: cargo test --all-features --no-fail-fast - env: - CARGO_INCREMENTAL: "0" - RUSTFLAGS: "-Cinstrument-coverage" - RUSTDOCFLAGS: "-Cinstrument-coverage" - - name: Install grcov - run: if [[ ! -e ~/.cargo/bin/grcov ]]; then cargo install grcov; fi - - name: Run grcov - run: grcov . --binary-path target/debug/deps/ -s . -t lcov --branch --ignore-not-existing --ignore '../**' --ignore '/*' -o coverage.lcov - - uses: codecov/codecov-action@v3 - with: - files: ./coverage.lcov - flags: rust - fail_ci_if_error: true # optional (default = false) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml new file mode 100644 index 000000000..7e8ffa442 --- /dev/null +++ b/.github/workflows/container.yaml @@ -0,0 +1,184 @@ +name: Container + +on: + push: + branches: + - "develop" + - "main" + - "releases/**/*" + pull_request: + branches: + - "develop" + - "main" + +env: + CARGO_TERM_COLOR: always + +jobs: + test: + name: Test (Docker) + runs-on: ubuntu-latest + + strategy: + matrix: + target: [debug, release] + + steps: + - id: setup + name: Setup Toolchain + uses: docker/setup-buildx-action@v4 + + - id: build + name: Build + uses: docker/build-push-action@v7 + with: + file: ./Containerfile + push: false + load: true + target: ${{ matrix.target }} + tags: torrust-tracker:local + cache-from: type=gha + cache-to: type=gha + + - id: inspect + name: Inspect + run: docker image inspect torrust-tracker:local + + - id: checkout + name: Checkout Repository + uses: actions/checkout@v6 + + - id: compose + name: Compose + run: docker compose build + + context: + name: Context + needs: test + runs-on: ubuntu-latest + + outputs: + continue: ${{ steps.check.outputs.continue }} + type: ${{ steps.check.outputs.type }} + version: ${{ steps.check.outputs.version }} + + steps: + - id: check + name: Check Context + run: | + if [[ "${{ github.repository }}" == "torrust/torrust-tracker" ]]; then + if [[ "${{ github.event_name }}" == "push" ]]; then + if [[ "${{ github.ref }}" == "refs/heads/main" ]]; then + + echo "type=development" >> $GITHUB_OUTPUT + echo "continue=true" >> $GITHUB_OUTPUT + echo "On \`main\` Branch, Type: \`development\`" + + elif [[ "${{ github.ref }}" == "refs/heads/develop" ]]; then + + echo "type=development" >> $GITHUB_OUTPUT + echo "continue=true" >> $GITHUB_OUTPUT + echo "On \`develop\` Branch, Type: \`development\`" + + elif [[ "${{ github.ref }}" =~ ^refs/heads/releases/ ]]; then + semver_regex='^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(\.(0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?(\+([0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?$' + version=$(echo "${{ github.ref }}" | sed -n -E 's#^refs/heads/releases/##p') + + if [[ ! "$version" =~ $semver_regex ]]; then + echo "Not a valid release branch semver. Will Not Continue" + exit 0 + fi + + echo "version=$version" >> $GITHUB_OUTPUT + echo "type=release" >> $GITHUB_OUTPUT + echo "continue=true" >> $GITHUB_OUTPUT + echo "In \`releases/$version\` Branch, Type: \`release\`" + + else + echo "Not Correct Branch. Will Not Continue" + fi + else + echo "Not a Push Event. Will Not Continue" + fi + else + echo "On a Forked Repository. Will Not Continue" + fi + + publish_development: + name: Publish (Development) + environment: dockerhub-torrust + needs: context + if: needs.context.outputs.continue == 'true' && needs.context.outputs.type == 'development' + runs-on: ubuntu-latest + + steps: + - id: meta + name: Docker Meta + uses: docker/metadata-action@v6 + with: + images: | + "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" + tags: | + type=ref,event=branch + + - id: login + name: Login to Docker Hub + uses: docker/login-action@v4 + with: + username: ${{ secrets.DOCKER_HUB_USERNAME }} + password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} + + - id: setup + name: Setup Toolchain + uses: docker/setup-buildx-action@v4 + + - name: Build and push + uses: docker/build-push-action@v7 + with: + file: ./Containerfile + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha + + publish_release: + name: Publish (Release) + environment: dockerhub-torrust + needs: context + if: needs.context.outputs.continue == 'true' && needs.context.outputs.type == 'release' + runs-on: ubuntu-latest + + steps: + - id: meta + name: Docker Meta + uses: docker/metadata-action@v6 + with: + images: | + "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" + tags: | + type=semver,value=${{ needs.context.outputs.version }},pattern={{raw}} + type=semver,value=${{ needs.context.outputs.version }},pattern={{version}} + type=semver,value=${{ needs.context.outputs.version }},pattern=v{{major}} + type=semver,value=${{ needs.context.outputs.version }},pattern={{major}}.{{minor}} + + - id: login + name: Login to Docker Hub + uses: docker/login-action@v4 + with: + username: ${{ secrets.DOCKER_HUB_USERNAME }} + password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} + + - id: setup + name: Setup Toolchain + uses: docker/setup-buildx-action@v4 + + - name: Build and push + uses: docker/build-push-action@v7 + with: + file: ./Containerfile + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml new file mode 100644 index 000000000..4c49217c2 --- /dev/null +++ b/.github/workflows/coverage.yaml @@ -0,0 +1,57 @@ +name: Coverage + +on: + push: + branches: + - develop + +env: + CARGO_TERM_COLOR: always + +jobs: + report: + name: Generate Coverage Report + environment: coverage + runs-on: ubuntu-latest + env: + CARGO_INCREMENTAL: "0" + RUSTFLAGS: "-Cinstrument-coverage" + + steps: + - name: Checkout repository + uses: actions/checkout@v6 + + - name: Install LLVM tools + run: sudo apt-get update && sudo apt-get install -y llvm + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@nightly + with: + toolchain: nightly + components: llvm-tools-preview + + - id: cache + name: Enable Workflow Cache + uses: Swatinem/rust-cache@v2 + + - id: tools + name: Install Tools + uses: taiki-e/install-action@v2 + with: + tool: grcov,cargo-llvm-cov + + - id: coverage + name: Generate Coverage Report + run: | + cargo clean + cargo llvm-cov --all-features --workspace --codecov --output-path ./codecov.json + + - id: upload + name: Upload Coverage Report + uses: codecov/codecov-action@v5 + with: + verbose: true + token: ${{ secrets.CODECOV_TOKEN }} + files: ${{ github.workspace }}/codecov.json + fail_ci_if_error: true diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml new file mode 100644 index 000000000..b544d1da2 --- /dev/null +++ b/.github/workflows/deployment.yaml @@ -0,0 +1,83 @@ +name: Deployment + +on: + push: + branches: + - "releases/**/*" + +jobs: + test: + name: Test + runs-on: ubuntu-latest + + strategy: + matrix: + toolchain: [nightly, stable] + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v6 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: ${{ matrix.toolchain }} + + - id: test + name: Run Unit Tests + run: cargo test --tests --benches --examples --workspace --all-targets --all-features + + publish: + name: Publish + environment: deployment + needs: test + runs-on: ubuntu-latest + + strategy: + matrix: + toolchain: [stable] + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v6 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: ${{ matrix.toolchain }} + + - id: publish + name: Publish Crates + env: + CARGO_REGISTRY_TOKEN: "${{ secrets.TORRUST_UPDATE_CARGO_REGISTRY_TOKEN }}" + run: | + cargo publish -p bittorrent-http-tracker-core + cargo publish -p bittorrent-http-tracker-protocol + cargo publish -p bittorrent-tracker-client + cargo publish -p bittorrent-tracker-core + cargo publish -p bittorrent-udp-tracker-core + cargo publish -p bittorrent-udp-tracker-protocol + cargo publish -p torrust-axum-health-check-api-server + cargo publish -p torrust-axum-http-tracker-server + cargo publish -p torrust-axum-rest-tracker-api-server + cargo publish -p torrust-axum-server + cargo publish -p torrust-rest-tracker-api-client + cargo publish -p torrust-rest-tracker-api-core + cargo publish -p torrust-torrust-server-lib + cargo publish -p torrust-tracker + cargo publish -p torrust-tracker-client + cargo publish -p torrust-tracker-clock + cargo publish -p torrust-tracker-configuration + cargo publish -p torrust-tracker-contrib-bencode + cargo publish -p torrust-tracker-events + cargo publish -p torrust-tracker-located-error + cargo publish -p torrust-tracker-metrics + cargo publish -p torrust-tracker-primitives + cargo publish -p torrust-tracker-swarm-coordination-registry + cargo publish -p torrust-tracker-test-helpers + cargo publish -p torrust-tracker-torrent-benchmarking + cargo publish -p torrust-udp-tracker-server diff --git a/.github/workflows/generate_coverage_pr.yaml b/.github/workflows/generate_coverage_pr.yaml new file mode 100644 index 000000000..e07a5a755 --- /dev/null +++ b/.github/workflows/generate_coverage_pr.yaml @@ -0,0 +1,84 @@ +name: Generate Coverage Report (PR) + +on: + pull_request: + branches: + - develop + +env: + CARGO_TERM_COLOR: always + +jobs: + coverage: + name: Generate Coverage Report + environment: coverage + runs-on: ubuntu-latest + env: + CARGO_INCREMENTAL: "0" + RUSTFLAGS: "-Cinstrument-coverage" + + steps: + - name: Checkout repository + uses: actions/checkout@v6 + + - name: Install LLVM tools + run: sudo apt-get update && sudo apt-get install -y llvm + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@nightly + with: + toolchain: nightly + components: llvm-tools-preview + + - id: cache + name: Enable Workflow Cache + uses: Swatinem/rust-cache@v2 + + - id: tools + name: Install Tools + uses: taiki-e/install-action@v2 + with: + tool: grcov,cargo-llvm-cov + + - id: coverage + name: Generate Coverage Report + run: | + cargo clean + cargo llvm-cov --all-features --workspace --codecov --output-path ./codecov.json + + - name: Store PR number and commit SHA + run: | + echo "Storing PR number ${{ github.event.number }}" + echo "${{ github.event.number }}" > pr_number.txt + + echo "Storing commit SHA ${{ github.event.pull_request.head.sha }}" + echo "${{ github.event.pull_request.head.sha }}" > commit_sha.txt + + # Workaround for https://github.com/orgs/community/discussions/25220 + # Triggered sub-workflow is not able to detect the original commit/PR which is available + # in this workflow. + - name: Store PR number + uses: actions/upload-artifact@v7 + with: + name: pr_number + path: pr_number.txt + + - name: Store commit SHA + uses: actions/upload-artifact@v7 + with: + name: commit_sha + path: commit_sha.txt + + # This stores the coverage report in artifacts. The actual upload to Codecov + # is executed by a different workflow `upload_coverage.yml`. The reason for this + # split is because `on.pull_request` workflows don't have access to secrets. + - name: Store coverage report in artifacts + uses: actions/upload-artifact@v7 + with: + name: codecov_report + path: ./codecov.json + + - run: | + echo "The coverage report was stored in Github artifacts." + echo "It will be uploaded to Codecov using [upload_coverage.yml] workflow shortly." diff --git a/.github/workflows/labels.yaml b/.github/workflows/labels.yaml new file mode 100644 index 000000000..a312c335f --- /dev/null +++ b/.github/workflows/labels.yaml @@ -0,0 +1,36 @@ +name: Labels +on: + workflow_dispatch: + push: + branches: + - develop + paths: + - "/.github/labels.json" + +jobs: + export: + name: Export Existing Labels + runs-on: ubuntu-latest + + steps: + - id: backup + name: Export to Workflow Artifact + uses: EndBug/export-label-config@v1 + + sync: + name: Synchronize Labels from Repo + needs: export + runs-on: ubuntu-latest + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v6 + + - id: sync + name: Apply Labels from File + uses: EndBug/label-sync@v2 + with: + config-file: .github/labels.json + delete-other-labels: true + token: ${{ secrets.UPDATE_LABELS }} diff --git a/.github/workflows/publish_crate.yml b/.github/workflows/publish_crate.yml deleted file mode 100644 index 4d5d0772e..000000000 --- a/.github/workflows/publish_crate.yml +++ /dev/null @@ -1,57 +0,0 @@ -name: Publish crate - -on: - push: - tags: - - "v*" - -jobs: - check-secret: - runs-on: ubuntu-latest - environment: crates-io-torrust - outputs: - publish: ${{ steps.check.outputs.publish }} - steps: - - id: check - env: - CRATES_TOKEN: "${{ secrets.CRATES_TOKEN }}" - if: "${{ env.CRATES_TOKEN != '' }}" - run: echo "publish=true" >> $GITHUB_OUTPUT - - test: - needs: check-secret - if: needs.check-secret.outputs.publish == 'true' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: stable - components: llvm-tools-preview - - uses: Swatinem/rust-cache@v2 - - name: Run Tests - run: cargo test - - publish: - needs: test - if: needs.check-secret.outputs.publish == 'true' - runs-on: ubuntu-latest - environment: crates-io-torrust - steps: - - name: Checkout - uses: actions/checkout@v3 - - - name: Install stable toolchain - uses: dtolnay/rust-toolchain@stable - with: - toolchain: stable - - - name: Publish workspace packages - run: | - cargo publish -p torrust-tracker-located-error - cargo publish -p torrust-tracker-primitives - cargo publish -p torrust-tracker-configuration - cargo publish -p torrust-tracker-test-helpers - cargo publish -p torrust-tracker - env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_TOKEN }} diff --git a/.github/workflows/publish_docker_image.yml b/.github/workflows/publish_docker_image.yml deleted file mode 100644 index 1dd65e3a7..000000000 --- a/.github/workflows/publish_docker_image.yml +++ /dev/null @@ -1,86 +0,0 @@ -name: Publish docker image - -on: - push: - branches: - - "main" - - "develop" - tags: - - "v*" - -env: - # Azure file share volume mount requires the Linux container run as root - # https://learn.microsoft.com/en-us/azure/container-instances/container-instances-volume-azure-files#limitations - # TORRUST_TRACKER_RUN_AS_USER: root - TORRUST_TRACKER_RUN_AS_USER: appuser - -jobs: - check-secret: - runs-on: ubuntu-latest - environment: dockerhub-torrust - outputs: - publish: ${{ steps.check.outputs.publish }} - steps: - - id: check - env: - DOCKER_HUB_USERNAME: "${{ secrets.DOCKER_HUB_USERNAME }}" - if: "${{ env.DOCKER_HUB_USERNAME != '' }}" - run: echo "publish=true" >> $GITHUB_OUTPUT - - test: - needs: check-secret - if: needs.check-secret.outputs.publish == 'true' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: stable - components: llvm-tools-preview - - uses: Swatinem/rust-cache@v2 - - name: Run Tests - run: cargo test - - dockerhub: - needs: test - if: needs.check-secret.outputs.publish == 'true' - runs-on: ubuntu-latest - environment: dockerhub-torrust - steps: - - name: Checkout - uses: actions/checkout@v3 - - - name: Docker meta - id: meta - uses: docker/metadata-action@v4 - with: - images: | - # For example: torrust/tracker - "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" - tags: | - type=ref,event=branch - type=ref,event=pr - type=semver,pattern={{version}} - type=semver,pattern={{major}}.{{minor}} - - - name: Login to Docker Hub - uses: docker/login-action@v2 - with: - username: ${{ secrets.DOCKER_HUB_USERNAME }} - password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 - - - name: Build and push - uses: docker/build-push-action@v4 - with: - context: . - file: ./Dockerfile - build-args: | - RUN_AS_USER=${{ env.TORRUST_TRACKER_RUN_AS_USER }} - push: ${{ github.event_name != 'pull_request' }} - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha - cache-to: type=gha,mode=max diff --git a/.github/workflows/test_build_release.yml b/.github/workflows/test_build_release.yml deleted file mode 100644 index 88234b97a..000000000 --- a/.github/workflows/test_build_release.yml +++ /dev/null @@ -1,81 +0,0 @@ -name: CI - -# Only trigger, when the test workflow succeeded -on: [push, pull_request] - -jobs: - format: - runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: nightly - components: rustfmt, clippy - - uses: Swatinem/rust-cache@v2 - - name: Check Rust Formatting - run: cargo fmt --check - - test: - needs: format - runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: stable - components: llvm-tools-preview - - uses: Swatinem/rust-cache@v2 - - name: Check Rust Code - run: cargo check --all-targets - - name: Clippy Rust Code - run: cargo clippy --all-targets -- -D clippy::pedantic - - name: Test Documentation - run: cargo test --doc - - name: Run Tests - run: cargo test --workspace - - uses: taiki-e/install-action@cargo-llvm-cov - - uses: taiki-e/install-action@nextest - - name: Show coverage - run: cargo llvm-cov nextest - - build: - needs: test - if: | - github.event_name == 'push' && - github.event.base_ref == 'refs/heads/main' && - startsWith(github.ref, 'refs/tags/v') - runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: stable - - uses: Swatinem/rust-cache@v2 - - name: Build Torrust Tracker - run: cargo build --release - - name: Upload Build Artifact - uses: actions/upload-artifact@v3 - with: - name: torrust-tracker - path: ./target/release/torrust-tracker - - release: - needs: build - runs-on: ubuntu-latest - steps: - - name: Download Build Artifact - uses: actions/download-artifact@v3 - with: - name: torrust-tracker - - name: Release - uses: softprops/action-gh-release@v1 -# with: -# files: | -# torrust-tracker diff --git a/.github/workflows/test_docker.yml b/.github/workflows/test_docker.yml deleted file mode 100644 index a62965878..000000000 --- a/.github/workflows/test_docker.yml +++ /dev/null @@ -1,26 +0,0 @@ -name: Test docker build - -on: - push: - pull_request: - -jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 - - - name: Build docker image - uses: docker/build-push-action@v4 - with: - context: . - file: ./Dockerfile - push: false - cache-from: type=gha - cache-to: type=gha,mode=max - - - name: Build docker-compose images - run: docker compose build diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml new file mode 100644 index 000000000..83a290663 --- /dev/null +++ b/.github/workflows/testing.yaml @@ -0,0 +1,167 @@ +name: Testing + +on: + push: + pull_request: + +env: + CARGO_TERM_COLOR: always + +jobs: + format: + name: Formatting + runs-on: ubuntu-latest + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v6 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: nightly + components: rustfmt + + - id: cache + name: Enable Workflow Cache + uses: Swatinem/rust-cache@v2 + + - id: format + name: Run Formatting-Checks + run: cargo fmt --check + + check: + name: Linting + runs-on: ubuntu-latest + needs: format + timeout-minutes: 15 + + strategy: + matrix: + toolchain: [nightly, stable] + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v6 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: ${{ matrix.toolchain }} + components: clippy, rustfmt + + - id: node + name: Setup Node.js + uses: actions/setup-node@v5 + with: + node-version: "20" + + - id: cache + name: Enable Workflow Cache + uses: Swatinem/rust-cache@v2 + + - id: tools + name: Install Internal Linter + run: cargo install --locked --git https://github.com/torrust/torrust-linting --bin linter + + - id: lint + name: Run All Linters + run: linter all + + build: + name: Build on ${{ matrix.os }} (${{ matrix.toolchain }}) + runs-on: ${{ matrix.os }} + + strategy: + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + toolchain: [nightly, stable] + + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: ${{ matrix.toolchain }} + + - name: Build project + run: cargo build --verbose + + unit: + name: Units + runs-on: ubuntu-latest + needs: check + + strategy: + matrix: + toolchain: [nightly, stable] + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v6 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: ${{ matrix.toolchain }} + components: llvm-tools-preview + + - id: cache + name: Enable Job Cache + uses: Swatinem/rust-cache@v2 + + - id: tools + name: Install Tools + uses: taiki-e/install-action@v2 + with: + tool: cargo-llvm-cov, cargo-nextest + + - id: test-docs + name: Run Documentation Tests + run: cargo test --doc --workspace + + - id: test + name: Run Unit Tests + run: cargo test --tests --benches --examples --workspace --all-targets --all-features + + - id: database + name: Run MySQL Database Tests + run: TORRUST_TRACKER_CORE_RUN_MYSQL_DRIVER_TEST=true cargo test --package bittorrent-tracker-core + + e2e: + name: E2E + runs-on: ubuntu-latest + needs: unit + + strategy: + matrix: + toolchain: [nightly, stable] + + steps: + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: ${{ matrix.toolchain }} + components: llvm-tools-preview + + - id: cache + name: Enable Job Cache + uses: Swatinem/rust-cache@v2 + + - id: checkout + name: Checkout Repository + uses: actions/checkout@v6 + + - id: test + name: Run E2E Tests + run: cargo run --bin e2e_tests_runner -- --config-toml-path "./share/default/config/tracker.e2e.container.sqlite3.toml" diff --git a/.github/workflows/upload_coverage_pr.yaml b/.github/workflows/upload_coverage_pr.yaml new file mode 100644 index 000000000..55de02c62 --- /dev/null +++ b/.github/workflows/upload_coverage_pr.yaml @@ -0,0 +1,119 @@ +name: Upload Coverage Report (PR) + +on: + # This workflow is triggered after every successful execution + # of `Generate Coverage Report` workflow. + workflow_run: + workflows: ["Generate Coverage Report (PR)"] + types: + - completed + +permissions: + actions: write + contents: write + issues: write + pull-requests: write + +jobs: + coverage: + name: Upload Coverage Report + environment: coverage + runs-on: ubuntu-latest + steps: + - name: "Download existing coverage report" + id: prepare_report + uses: actions/github-script@v8 + with: + script: | + var fs = require('fs'); + + // List artifacts of the workflow run that triggered this workflow + var artifacts = await github.rest.actions.listWorkflowRunArtifacts({ + owner: context.repo.owner, + repo: context.repo.repo, + run_id: context.payload.workflow_run.id, + }); + + let codecovReport = artifacts.data.artifacts.filter((artifact) => { + return artifact.name == "codecov_report"; + }); + + if (codecovReport.length != 1) { + throw new Error("Unexpected number of {codecov_report} artifacts: " + codecovReport.length); + } + + var download = await github.rest.actions.downloadArtifact({ + owner: context.repo.owner, + repo: context.repo.repo, + artifact_id: codecovReport[0].id, + archive_format: 'zip', + }); + fs.writeFileSync('codecov_report.zip', Buffer.from(download.data)); + + let prNumber = artifacts.data.artifacts.filter((artifact) => { + return artifact.name == "pr_number"; + }); + + if (prNumber.length != 1) { + throw new Error("Unexpected number of {pr_number} artifacts: " + prNumber.length); + } + + var download = await github.rest.actions.downloadArtifact({ + owner: context.repo.owner, + repo: context.repo.repo, + artifact_id: prNumber[0].id, + archive_format: 'zip', + }); + fs.writeFileSync('pr_number.zip', Buffer.from(download.data)); + + let commitSha = artifacts.data.artifacts.filter((artifact) => { + return artifact.name == "commit_sha"; + }); + + if (commitSha.length != 1) { + throw new Error("Unexpected number of {commit_sha} artifacts: " + commitSha.length); + } + + var download = await github.rest.actions.downloadArtifact({ + owner: context.repo.owner, + repo: context.repo.repo, + artifact_id: commitSha[0].id, + archive_format: 'zip', + }); + fs.writeFileSync('commit_sha.zip', Buffer.from(download.data)); + + - id: parse_previous_artifacts + run: | + unzip codecov_report.zip + unzip pr_number.zip + unzip commit_sha.zip + + echo "Detected PR is: $(> "$GITHUB_OUTPUT" + echo "override_commit=$(> "$GITHUB_OUTPUT" + + - name: Checkout repository + uses: actions/checkout@v6 + with: + ref: ${{ steps.parse_previous_artifacts.outputs.override_commit || '' }} + path: repo_root + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v5 + with: + verbose: true + token: ${{ secrets.CODECOV_TOKEN }} + files: ${{ github.workspace }}/codecov.json + fail_ci_if_error: true + # Manual overrides for these parameters are needed because automatic detection + # in codecov-action does not work for non-`pull_request` workflows. + # In `main` branch push, these default to empty strings since we want to run + # the analysis on HEAD. + override_commit: ${{ steps.parse_previous_artifacts.outputs.override_commit || '' }} + override_pr: ${{ steps.parse_previous_artifacts.outputs.override_pr || '' }} + working-directory: ${{ github.workspace }}/repo_root + # Location where coverage report files are searched for + directory: ${{ github.workspace }} diff --git a/.gitignore b/.gitignore index 6b58dcb45..fd83ee918 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,20 @@ .env +*.code-workspace **/*.rs.bk /.coverage/ /.idea/ /.vscode/launch.json -/config.toml /data.db /database.db /database.json.bz2 +/flamegraph.svg /storage/ /target +/tracker.* +/tracker.toml +callgrind.out +codecov.json +integration_tests_sqlite3.db +lcov.info +perf.data* +rustc-ice-*.txt diff --git a/.markdownlint.json b/.markdownlint.json new file mode 100644 index 000000000..19ec47c2e --- /dev/null +++ b/.markdownlint.json @@ -0,0 +1,18 @@ +{ + "default": true, + "MD013": false, + "MD031": true, + "MD032": true, + "MD040": true, + "MD022": true, + "MD009": true, + "MD007": { + "indent": 2 + }, + "MD026": false, + "MD041": false, + "MD034": false, + "MD024": false, + "MD033": false, + "MD060": false +} diff --git a/.taplo.toml b/.taplo.toml new file mode 100644 index 000000000..0168711e8 --- /dev/null +++ b/.taplo.toml @@ -0,0 +1,27 @@ +# Taplo configuration file for TOML formatting +# Used by the "Even Better TOML" VS Code extension + +# Exclude generated and runtime folders from linting +exclude = [ ".coverage/**", "storage/**", "target/**" ] + +[formatting] +# Preserve blank lines that exist +allowed_blank_lines = 1 +# Don't reorder keys to maintain structure +reorder_keys = false +# Array formatting +array_auto_collapse = false +array_auto_expand = false +array_trailing_comma = true +# Inline table formatting +compact_arrays = false +compact_inline_tables = false +inline_table_expand = false +# Alignment +align_comments = true +align_entries = false +# Indentation +indent_entries = false +indent_tables = false +# Other +trailing_newline = true diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 11d11a5c5..934a43eb8 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,6 +1,7 @@ { "recommendations": [ "streetsidesoftware.code-spell-checker", - "rust-lang.rust-analyzer" + "rust-lang.rust-analyzer", + "tamasfe.even-better-toml" ] } \ No newline at end of file diff --git a/.vscode/mcp.json b/.vscode/mcp.json new file mode 100644 index 000000000..506a52259 --- /dev/null +++ b/.vscode/mcp.json @@ -0,0 +1,26 @@ +{ + "inputs": [ + { + "type": "promptString", + "id": "github_token", + "description": "GitHub Personal Access Token", + "password": true + } + ], + "servers": { + "github": { + "command": "docker", + "args": [ + "run", + "-i", + "--rm", + "-e", + "GITHUB_PERSONAL_ACCESS_TOKEN", + "ghcr.io/github/github-mcp-server" + ], + "env": { + "GITHUB_PERSONAL_ACCESS_TOKEN": "${input:github_token}" + } + } + } +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index 94f199bd6..d27d562e8 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,8 +1,21 @@ { - "[rust]": { - "editor.formatOnSave": true - }, - "rust-analyzer.checkOnSave.command": "clippy", - "rust-analyzer.checkOnSave.allTargets": true, - "rust-analyzer.checkOnSave.extraArgs": ["--","-W","clippy::pedantic"], + "[rust]": { + "editor.formatOnSave": true + }, + "[ignore]": { + "rust-analyzer.cargo.extraEnv": { + "RUSTFLAGS": "-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests", + "RUSTDOCFLAGS": "-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests", + "CARGO_INCREMENTAL": "0", + "RUST_BACKTRACE": "1" + } + }, + "rust-analyzer.checkOnSave": true, + "rust-analyzer.check.command": "clippy", + "rust-analyzer.check.allTargets": true, + "evenBetterToml.formatter.allowedBlankLines": 1, + "evenBetterToml.formatter.columnWidth": 130, + "evenBetterToml.formatter.trailingNewline": true, + "evenBetterToml.formatter.reorderKeys": true, + "evenBetterToml.formatter.reorderArrays": true, } \ No newline at end of file diff --git a/.yamllint-ci.yml b/.yamllint-ci.yml new file mode 100644 index 000000000..9380b592a --- /dev/null +++ b/.yamllint-ci.yml @@ -0,0 +1,16 @@ +extends: default + +rules: + line-length: + max: 200 # More reasonable for infrastructure code + comments: + min-spaces-from-content: 1 # Allow single space before comments + document-start: disable # Most project YAML files don't require --- + truthy: + allowed-values: ["true", "false", "yes", "no", "on", "off"] # Allow common GitHub Actions values + +# Ignore generated/runtime directories +ignore: | + target/** + storage/** + .coverage/** diff --git a/Cargo.lock b/Cargo.lock index a9d8594d4..9e0911944 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,3004 +4,5861 @@ version = 3 [[package]] name = "addr2line" -version = "0.19.0" +version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a76fd60b23679b7d19bd066031410fb7e458ccc5e958eb5c325888ce4baedc97" +checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" dependencies = [ "gimli", ] [[package]] -name = "adler" -version = "1.0.2" +name = "adler2" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "ahash" -version = "0.7.6" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" +checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" dependencies = [ - "getrandom", + "getrandom 0.2.17", "once_cell", "version_check", ] [[package]] -name = "ahash" -version = "0.8.3" +name = "aho-corasick" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c99f64d1e06488f620f932677e24bc6e2897582980441ae90a671415bd7ec2f" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" dependencies = [ - "cfg-if", - "once_cell", - "version_check", + "memchr", ] [[package]] -name = "aho-corasick" -version = "0.7.20" +name = "alloc-no-stdlib" +version = "2.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc936419f96fa211c1b9166887b38e5e40b19958e5b895be7c1f93adec7071ac" -dependencies = [ - "memchr", -] +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" [[package]] -name = "android_system_properties" -version = "0.1.5" +name = "alloc-stdlib" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" dependencies = [ - "libc", + "alloc-no-stdlib", ] [[package]] -name = "aquatic_udp_protocol" -version = "0.8.0" +name = "alloca" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2919b480121f7d20d247524da62bad1b6b7928bc3f50898f624b5c592727341" +checksum = "e5a7d05ea6aea7e9e64d25b9156ba2fee3fdd659e34e41063cd2fc7cd020d7f4" dependencies = [ - "byteorder", - "either", + "cc", ] [[package]] -name = "arc-swap" -version = "1.6.0" +name = "allocator-api2" +version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bddcadddf5e9015d310179a59bb28c4d4b9920ad0f11e8e14dbadf654890c9a6" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] -name = "arrayvec" -version = "0.7.2" +name = "android_system_properties" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] [[package]] -name = "async-trait" -version = "0.1.68" +name = "anes" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" + +[[package]] +name = "anstream" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ccdd8f2a161be9bd5c023df56f1b2a0bd1d83872ae53b71a84a12c9bf6e842" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.14", + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", ] [[package]] -name = "autocfg" -version = "1.1.0" +name = "anstyle" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" [[package]] -name = "axum" -version = "0.6.16" +name = "anstyle-parse" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "113713495a32dd0ab52baf5c10044725aa3aec00b31beda84218e469029b72a3" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" dependencies = [ - "async-trait", - "axum-core", - "bitflags", - "bytes", - "futures-util", - "http", - "http-body", - "hyper", - "itoa", - "matchit", - "memchr", - "mime", - "percent-encoding", - "pin-project-lite", - "rustversion", - "serde", - "serde_json", - "serde_path_to_error", - "serde_urlencoded", - "sync_wrapper", - "tokio", - "tower", - "tower-layer", - "tower-service", + "utf8parse", ] [[package]] -name = "axum-client-ip" -version = "0.4.0" +name = "anstyle-query" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d719fabd6813392bbc10e1fe67f2977fad52791a836e51236f7e02f2482e017" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "axum", - "forwarded-header-value", - "serde", + "windows-sys 0.61.2", ] [[package]] -name = "axum-core" -version = "0.3.4" +name = "anstyle-wincon" +version = "3.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "759fa577a247914fd3f7f76d62972792636412fbfd634cd452f6a385a74d2d2c" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ - "async-trait", - "bytes", - "futures-util", - "http", - "http-body", - "mime", - "rustversion", - "tower-layer", - "tower-service", + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", ] [[package]] -name = "axum-server" -version = "0.4.7" +name = "anyhow" +version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bace45b270e36e3c27a190c65883de6dfc9f1d18c829907c127464815dc67b24" -dependencies = [ - "arc-swap", - "bytes", - "futures-util", - "http", - "http-body", - "hyper", - "pin-project-lite", - "rustls", - "rustls-pemfile", - "tokio", - "tokio-rustls", - "tower-service", -] +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" [[package]] -name = "backtrace" -version = "0.3.67" +name = "approx" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "233d376d6d185f2a3093e58f283f60f880315b6c60075b01f36b3b85154564ca" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" dependencies = [ - "addr2line", - "cc", - "cfg-if", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", + "num-traits", ] [[package]] -name = "base64" -version = "0.13.1" +name = "aquatic_peer_id" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" +checksum = "f0732a73df221dcb25713849c6ebaf57b85355f669716652a7466f688cc06f25" +dependencies = [ + "compact_str", + "hex", + "quickcheck", + "regex", + "serde", + "zerocopy 0.7.35", +] [[package]] -name = "base64" -version = "0.21.0" +name = "aquatic_udp_protocol" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a4ddaa51a5bc52a6948f74c06d20aaaddb71924eab79b8c97a8c556e942d6a" +checksum = "0af90e5162f5fcbde33524128f08dc52a779f32512d5f8692eadd4b55c89389e" +dependencies = [ + "aquatic_peer_id", + "byteorder", + "either", + "zerocopy 0.7.35", +] [[package]] -name = "bigdecimal" -version = "0.3.0" +name = "arc-swap" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6aaf33151a6429fe9211d1b276eafdf70cdff28b071e76c0b0e1503221ea3744" +checksum = "6a3a1fd6f75306b68087b831f025c712524bcb19aad54e557b1129cfa0a2b207" dependencies = [ - "num-bigint", - "num-integer", - "num-traits", + "rustversion", ] [[package]] -name = "binascii" -version = "0.1.4" +name = "arrayvec" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" [[package]] -name = "bindgen" -version = "0.59.2" +name = "astral-tokio-tar" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bd2a9a458e8f4304c52c43ebb0cfbd520289f8379a52e329a38afda99bf8eb8" +checksum = "3c23f3af104b40a3430ccb90ed5f7bd877a8dc5c26fc92fde51a22b40890dcf9" dependencies = [ - "bitflags", - "cexpr", - "clang-sys", - "lazy_static", - "lazycell", - "peeking_take_while", - "proc-macro2", - "quote", - "regex", + "filetime", + "futures-core", + "libc", + "portable-atomic", "rustc-hash", - "shlex", + "tokio", + "tokio-stream", + "xattr", ] [[package]] -name = "bip_bencode" -version = "0.4.4" +name = "async-attributes" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6048cc5d9680544a5098a290d2845df7dae292c97687b9896b70365bad0ea416" +checksum = "a3203e79f4dd9bdda415ed03cf14dae5a2bf775c683a00f94e9cd1faf0f596e5" dependencies = [ - "error-chain", + "quote", + "syn 1.0.109", ] [[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitvec" -version = "1.0.1" +name = "async-channel" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" +checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35" dependencies = [ - "funty", - "radium", - "tap", - "wyz", + "concurrent-queue", + "event-listener 2.5.3", + "futures-core", ] [[package]] -name = "block-buffer" -version = "0.10.4" +name = "async-channel" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" dependencies = [ - "generic-array", + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", ] [[package]] -name = "borsh" -version = "0.10.3" +name = "async-compression" +version = "0.4.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4114279215a005bc675e386011e594e1d9b800918cea18fcadadcce864a2046b" +checksum = "d0f9ee0f6e02ffd7ad5816e9464499fba7b3effd01123b515c41d1697c43dad1" dependencies = [ - "borsh-derive", - "hashbrown 0.13.2", + "compression-codecs", + "compression-core", + "pin-project-lite", + "tokio", ] [[package]] -name = "borsh-derive" -version = "0.10.3" +name = "async-executor" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0754613691538d51f329cce9af41d7b7ca150bc973056f1156611489475f54f7" +checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" dependencies = [ - "borsh-derive-internal", - "borsh-schema-derive-internal", - "proc-macro-crate", - "proc-macro2", - "syn 1.0.109", + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", ] [[package]] -name = "borsh-derive-internal" -version = "0.10.3" +name = "async-global-executor" +version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afb438156919598d2c7bad7e1c0adf3d26ed3840dbc010db1a882a65583ca2fb" +checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c" dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", + "async-channel 2.5.0", + "async-executor", + "async-io", + "async-lock", + "blocking", + "futures-lite", + "once_cell", + "tokio", ] [[package]] -name = "borsh-schema-derive-internal" -version = "0.10.3" +name = "async-io" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "634205cc43f74a1b9046ef87c4540ebda95696ec0f315024860cad7c5b0f5ccd" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "windows-sys 0.61.2", ] [[package]] -name = "bufstream" -version = "0.1.4" +name = "async-lock" +version = "3.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40e38929add23cdf8a366df9b0e088953150724bcbe5fc330b0d8eb3b328eec8" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener 5.4.1", + "event-listener-strategy", + "pin-project-lite", +] [[package]] -name = "bumpalo" -version = "3.12.0" +name = "async-std" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535" +checksum = "2c8e079a4ab67ae52b7403632e4618815d6db36d2a010cfe41b02c1b1578f93b" +dependencies = [ + "async-attributes", + "async-channel 1.9.0", + "async-global-executor", + "async-io", + "async-lock", + "crossbeam-utils", + "futures-channel", + "futures-core", + "futures-io", + "futures-lite", + "gloo-timers", + "kv-log-macro", + "log", + "memchr", + "once_cell", + "pin-project-lite", + "pin-utils", + "slab", + "wasm-bindgen-futures", +] [[package]] -name = "bytecheck" -version = "0.6.10" +name = "async-stream" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13fe11640a23eb24562225322cd3e452b93a3d4091d62fab69c70542fcd17d1f" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" dependencies = [ - "bytecheck_derive", - "ptr_meta", - "simdutf8", + "async-stream-impl", + "futures-core", + "pin-project-lite", ] [[package]] -name = "bytecheck_derive" -version = "0.6.10" +name = "async-stream-impl" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31225543cb46f81a7e224762764f4a6a0f097b1db0b175f69e8065efaa42de5" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" dependencies = [ "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.117", ] [[package]] -name = "byteorder" -version = "1.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" - -[[package]] -name = "bytes" -version = "1.4.0" +name = "async-task" +version = "4.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" [[package]] -name = "cc" -version = "1.0.79" +name = "async-trait" +version = "0.1.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] [[package]] -name = "cexpr" -version = "0.6.0" +name = "atomic" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +checksum = "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340" dependencies = [ - "nom", + "bytemuck", ] [[package]] -name = "cfg-if" -version = "1.0.0" +name = "atomic-waker" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] -name = "chrono" -version = "0.4.24" +name = "autocfg" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e3c5919066adf22df73762e50cffcde3a758f2a848b113b586d1f86728b673b" -dependencies = [ - "iana-time-zone", - "num-integer", - "num-traits", - "serde", - "winapi", -] +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] -name = "clang-sys" -version = "1.6.1" +name = "aws-lc-rs" +version = "1.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c688fc74432808e3eb684cae8830a86be1d66a2bd58e1f248ed0960a590baf6f" +checksum = "a054912289d18629dc78375ba2c3726a3afe3ff71b4edba9dedfca0e3446d1fc" dependencies = [ - "glob", - "libc", - "libloading", + "aws-lc-sys", + "zeroize", ] [[package]] -name = "cmake" -version = "0.1.50" +name = "aws-lc-sys" +version = "0.39.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31c789563b815f77f4250caee12365734369f942439b7defd71e18a48197130" +checksum = "83a25cf98105baa966497416dbd42565ce3a8cf8dbfd59803ec9ad46f3126399" dependencies = [ "cc", + "cmake", + "dunce", + "fs_extra", +] + +[[package]] +name = "axum" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b52af3cb4058c895d37317bb27508dccc8e5f2d39454016b297bf4a400597b8" +dependencies = [ + "axum-core", + "axum-macros", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-client-ip" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dff8ee1869817523c8f91c20bf17fd932707f66c2e7e0b0f811b29a227289562" +dependencies = [ + "axum", + "forwarded-header-value", + "serde", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-extra" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fef252edff26ddba56bbcdf2ee3307b8129acb86f5749b68990c168a6fcc9c76" +dependencies = [ + "axum", + "axum-core", + "bytes", + "form_urlencoded", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "serde_core", + "serde_html_form", + "serde_path_to_error", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-macros" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "604fde5e028fea851ce1d8570bbdc034bec850d157f7569d10f347d06808c05c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "axum-server" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1df331683d982a0b9492b38127151e6453639cd34926eb9c07d4cd8c6d22bfc" +dependencies = [ + "arc-swap", + "bytes", + "either", + "fs-err", + "http", + "http-body", + "hyper", + "hyper-util", + "pin-project-lite", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "backtrace" +version = "0.3.76" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", + "windows-link", +] + +[[package]] +name = "backtrace-ext" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "537beee3be4a18fb023b570f80e3ae28003db9167a751266b259926e25539d50" +dependencies = [ + "backtrace", +] + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bigdecimal" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d6867f1565b3aad85681f1015055b087fcfd840d6aeee6eee7f2da317603695" +dependencies = [ + "autocfg", + "libm", + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "binascii" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" + +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex", + "syn 2.0.117", +] + +[[package]] +name = "bit-vec" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02b4ff8b16e6076c3e14220b39fbc1fabb6737522281a388998046859400895f" + +[[package]] +name = "bitflags" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" + +[[package]] +name = "bittorrent-http-tracker-core" +version = "3.0.0-develop" +dependencies = [ + "aquatic_udp_protocol", + "bittorrent-http-tracker-protocol", + "bittorrent-primitives", + "bittorrent-tracker-core", + "criterion 0.5.1", + "formatjson", + "futures", + "mockall", + "serde", + "serde_json", + "thiserror 2.0.18", + "tokio", + "tokio-util", + "torrust-tracker-clock", + "torrust-tracker-configuration", + "torrust-tracker-events", + "torrust-tracker-metrics", + "torrust-tracker-primitives", + "torrust-tracker-swarm-coordination-registry", + "torrust-tracker-test-helpers", + "tracing", +] + +[[package]] +name = "bittorrent-http-tracker-protocol" +version = "3.0.0-develop" +dependencies = [ + "aquatic_udp_protocol", + "bittorrent-primitives", + "bittorrent-tracker-core", + "derive_more", + "multimap", + "percent-encoding", + "serde", + "serde_bencode", + "thiserror 2.0.18", + "torrust-tracker-clock", + "torrust-tracker-configuration", + "torrust-tracker-contrib-bencode", + "torrust-tracker-located-error", + "torrust-tracker-primitives", +] + +[[package]] +name = "bittorrent-primitives" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdc1bd0462f0af0b57abd5f5f8f32b904ba0a17cc8be1714db160a054552f242" +dependencies = [ + "aquatic_udp_protocol", + "binascii", + "serde", + "serde_json", + "thiserror 1.0.69", + "zerocopy 0.7.35", +] + +[[package]] +name = "bittorrent-tracker-client" +version = "3.0.0-develop" +dependencies = [ + "aquatic_udp_protocol", + "bittorrent-primitives", + "derive_more", + "hyper", + "percent-encoding", + "reqwest", + "serde", + "serde_bencode", + "serde_bytes", + "serde_repr", + "thiserror 2.0.18", + "tokio", + "torrust-tracker-configuration", + "torrust-tracker-located-error", + "torrust-tracker-primitives", + "tracing", + "zerocopy 0.7.35", +] + +[[package]] +name = "bittorrent-tracker-core" +version = "3.0.0-develop" +dependencies = [ + "aquatic_udp_protocol", + "bittorrent-primitives", + "chrono", + "derive_more", + "local-ip-address", + "mockall", + "r2d2", + "r2d2_mysql", + "r2d2_sqlite", + "rand 0.10.0", + "serde", + "serde_json", + "testcontainers", + "thiserror 2.0.18", + "tokio", + "tokio-util", + "torrust-rest-tracker-api-client", + "torrust-tracker-clock", + "torrust-tracker-configuration", + "torrust-tracker-events", + "torrust-tracker-located-error", + "torrust-tracker-metrics", + "torrust-tracker-primitives", + "torrust-tracker-swarm-coordination-registry", + "torrust-tracker-test-helpers", + "tracing", + "url", +] + +[[package]] +name = "bittorrent-udp-tracker-core" +version = "3.0.0-develop" +dependencies = [ + "aquatic_udp_protocol", + "bittorrent-primitives", + "bittorrent-tracker-core", + "bittorrent-udp-tracker-protocol", + "bloom", + "blowfish", + "cipher", + "criterion 0.5.1", + "futures", + "generic-array", + "lazy_static", + "mockall", + "rand 0.10.0", + "serde", + "thiserror 2.0.18", + "tokio", + "tokio-util", + "torrust-tracker-clock", + "torrust-tracker-configuration", + "torrust-tracker-events", + "torrust-tracker-metrics", + "torrust-tracker-primitives", + "torrust-tracker-swarm-coordination-registry", + "torrust-tracker-test-helpers", + "tracing", + "zerocopy 0.7.35", +] + +[[package]] +name = "bittorrent-udp-tracker-protocol" +version = "3.0.0-develop" +dependencies = [ + "aquatic_udp_protocol", + "torrust-tracker-clock", + "torrust-tracker-primitives", +] + +[[package]] +name = "bitvec" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "blocking" +version = "1.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21" +dependencies = [ + "async-channel 2.5.0", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "bloom" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d00ac8e5056d6d65376a3c1aa5c7c34850d6949ace17f0266953a254eb3d6fe8" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "blowfish" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e412e2cd0f2b2d93e02543ceae7917b3c70331573df19ee046bcbc35e45e87d7" +dependencies = [ + "byteorder", + "cipher", +] + +[[package]] +name = "bollard" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee04c4c84f1f811b017f2fbb7dd8815c976e7ca98593de9c1e2afad0f636bff4" +dependencies = [ + "async-stream", + "base64 0.22.1", + "bitflags", + "bollard-buildkit-proto", + "bollard-stubs", + "bytes", + "futures-core", + "futures-util", + "hex", + "home", + "http", + "http-body-util", + "hyper", + "hyper-named-pipe", + "hyper-rustls", + "hyper-util", + "hyperlocal", + "log", + "num", + "pin-project-lite", + "rand 0.9.2", + "rustls", + "rustls-native-certs", + "rustls-pki-types", + "serde", + "serde_derive", + "serde_json", + "serde_urlencoded", + "thiserror 2.0.18", + "time", + "tokio", + "tokio-stream", + "tokio-util", + "tonic", + "tower-service", + "url", + "winapi", +] + +[[package]] +name = "bollard-buildkit-proto" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85a885520bf6249ab931a764ffdb87b0ceef48e6e7d807cfdb21b751e086e1ad" +dependencies = [ + "prost", + "prost-types", + "tonic", + "tonic-prost", + "ureq", +] + +[[package]] +name = "bollard-stubs" +version = "1.52.1-rc.29.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f0a8ca8799131c1837d1282c3f81f31e76ceb0ce426e04a7fe1ccee3287c066" +dependencies = [ + "base64 0.22.1", + "bollard-buildkit-proto", + "bytes", + "prost", + "serde", + "serde_json", + "serde_repr", + "time", +] + +[[package]] +name = "borsh" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfd1e3f8955a5d7de9fab72fc8373fade9fb8a703968cb200ae3dc6cf08e185a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfcfdc083699101d5a7965e49925975f2f55060f94f9a05e7187be95d530ca59" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "brotli" +version = "8.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "btoi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dd6407f73a9b8b6162d8a2ef999fe6afd7cc15902ebf42c5cd296addf17e0ad" +dependencies = [ + "num-traits", +] + +[[package]] +name = "bufstream" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40e38929add23cdf8a366df9b0e088953150724bcbe5fc330b0d8eb3b328eec8" + +[[package]] +name = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[package]] +name = "bytecheck" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23cdc57ce23ac53c931e88a43d06d070a6fd142f2617be5855eb75efc9beb1c2" +dependencies = [ + "bytecheck_derive", + "ptr_meta", + "simdutf8", +] + +[[package]] +name = "bytecheck_derive" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3db406d29fbcd95542e92559bed4d8ad92636d1ca8b3b72ede10b4bcc010e659" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "bytemuck" +version = "1.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "camino" +version = "1.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0b03af37dad7a14518b7691d81acb0f8222604ad3d1b02f6b4bed5188c0cd5" +dependencies = [ + "serde", +] + +[[package]] +name = "cast" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" + +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cc" +version = "1.2.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7a4d3ec6524d28a329fc53654bbadc9bdd7b0431f5d65f1a56ffb28a1ee5283" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "chacha20" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "rand_core 0.10.0", +] + +[[package]] +name = "chrono" +version = "0.4.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" +dependencies = [ + "iana-time-zone", + "num-traits", + "serde", + "windows-link", +] + +[[package]] +name = "ciborium" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + +[[package]] +name = "ciborium-ll" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "clang-sys" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "clap" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b193af5b67834b676abd72466a96c1024e6a6ad978a1f484bd90b85c94041351" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1110bd8a634a1ab8cb04345d8d878267d57c3cf1b38d91b71af6686408bbca6a" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "compact_str" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f86b9c4c00838774a6d902ef931eff7470720c51d90c2e32cfe15dc304737b3f" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "ryu", + "static_assertions", +] + +[[package]] +name = "compression-codecs" +version = "0.4.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb7b51a7d9c967fc26773061ba86150f19c50c0d65c887cb1fbe295fd16619b7" +dependencies = [ + "brotli", + "compression-core", + "flate2", + "memchr", + "zstd", + "zstd-safe", +] + +[[package]] +name = "compression-core" +version = "0.4.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75984efb6ed102a0d42db99afb6c1948f0380d1d91808d5529916e6c08b49d8d" + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "criterion" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f" +dependencies = [ + "anes", + "cast", + "ciborium", + "clap", + "criterion-plot 0.5.0", + "futures", + "is-terminal", + "itertools 0.10.5", + "num-traits", + "once_cell", + "oorandom", + "plotters", + "rayon", + "regex", + "serde", + "serde_derive", + "serde_json", + "tinytemplate", + "tokio", + "walkdir", +] + +[[package]] +name = "criterion" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "950046b2aa2492f9a536f5f4f9a3de7b9e2476e575e05bd6c333371add4d98f3" +dependencies = [ + "alloca", + "anes", + "cast", + "ciborium", + "clap", + "criterion-plot 0.8.2", + "itertools 0.13.0", + "num-traits", + "oorandom", + "page_size", + "plotters", + "rayon", + "regex", + "serde", + "serde_json", + "tinytemplate", + "tokio", + "walkdir", +] + +[[package]] +name = "criterion-plot" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" +dependencies = [ + "cast", + "itertools 0.10.5", +] + +[[package]] +name = "criterion-plot" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8d80a2f4f5b554395e47b5d8305bc3d27813bacb73493eb1001e8f76dae29ea" +dependencies = [ + "cast", + "itertools 0.13.0", +] + +[[package]] +name = "crossbeam" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1137cd7e7fc0fb5d3c5a8678be38ec56e819125d8d7907411fe24ccb943faca8" +dependencies = [ + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-epoch", + "crossbeam-queue", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-skiplist" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df29de440c58ca2cc6e587ec3d22347551a32435fbde9d2bff64e78a9ffa151b" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core 0.20.11", + "darling_macro 0.20.11", +] + +[[package]] +name = "darling" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core 0.23.0", + "darling_macro 0.23.0", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.117", +] + +[[package]] +name = "darling_core" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.117", +] + +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core 0.20.11", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "darling_macro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" +dependencies = [ + "darling_core 0.23.0", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "dashmap" +version = "6.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf" +dependencies = [ + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "powerfmt", + "serde_core", +] + +[[package]] +name = "derive_builder" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" +dependencies = [ + "derive_builder_macro", +] + +[[package]] +name = "derive_builder_core" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" +dependencies = [ + "darling 0.20.11", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "derive_builder_macro" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" +dependencies = [ + "derive_builder_core", + "syn 2.0.117", +] + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.117", + "unicode-xid", +] + +[[package]] +name = "derive_utils" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "362f47930db19fe7735f527e6595e4900316b893ebf6d48ad3d31be928d57dd6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "diff" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "docker_credential" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d89dfcba45b4afad7450a99b39e751590463e45c04728cf555d36bb66940de8" +dependencies = [ + "base64 0.21.7", + "serde", + "serde_json", +] + +[[package]] +name = "downcast" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "env_filter" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e90c2accc4b07a8456ea0debdc2e7587bdd890680d71173a15d4ae604f6eef" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0621c04f2196ac3f488dd583365b9c09be011a4ab8b9f37248ffcc8f6198b56a" +dependencies = [ + "env_filter", + "log", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "etcetera" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de48cc4d1c1d97a20fd819def54b890cadde72ed3ad0c614822a0a433361be96" +dependencies = [ + "cfg-if", + "windows-sys 0.61.2", +] + +[[package]] +name = "event-listener" +version = "2.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" + +[[package]] +name = "event-listener" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +dependencies = [ + "concurrent-queue", + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener 5.4.1", + "pin-project-lite", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + +[[package]] +name = "ferroid" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb330bbd4cb7a5b9f559427f06f98a4f853a137c8298f3bd3f8ca57663e21986" +dependencies = [ + "portable-atomic", + "rand 0.9.2", + "web-time", +] + +[[package]] +name = "figment" +version = "0.10.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cb01cd46b0cf372153850f4c6c272d9cbea2da513e07538405148f95bd789f3" +dependencies = [ + "atomic", + "parking_lot", + "pear", + "serde", + "tempfile", + "toml 0.8.23", + "uncased", + "version_check", +] + +[[package]] +name = "filetime" +version = "0.2.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f98844151eee8917efc50bd9e8318cb963ae8b297431495d3f758616ea5c57db" +dependencies = [ + "cfg-if", + "libc", + "libredox", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "flate2" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +dependencies = [ + "crc32fast", + "libz-sys", + "miniz_oxide", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "formatjson" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d3ba17cfe2aff8969f35b2bffec13b34756c51ea53eadcc5d5446f71370e2ed" +dependencies = [ + "miette", + "thiserror 1.0.69", +] + +[[package]] +name = "forwarded-header-value" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8835f84f38484cc86f110a805655697908257fb9a7af005234060891557198e9" +dependencies = [ + "nonempty", + "thiserror 1.0.69", +] + +[[package]] +name = "fragile" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8878864ba14bb86e818a412bfd6f18f9eabd4ec0f008a28e8f7eb61db532fcf9" +dependencies = [ + "futures-core", +] + +[[package]] +name = "frunk" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28aef0f9aa070bce60767c12ba9cb41efeaf1a2bc6427f87b7d83f11239a16d7" +dependencies = [ + "frunk_core", + "frunk_derives", + "frunk_proc_macros", + "serde", +] + +[[package]] +name = "frunk_core" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "476eeaa382e3462b84da5d6ba3da97b5786823c2d0d3a0d04ef088d073da225c" +dependencies = [ + "serde", +] + +[[package]] +name = "frunk_derives" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0b4095fc99e1d858e5b8c7125d2638372ec85aa0fe6c807105cf10b0265ca6c" +dependencies = [ + "frunk_proc_macro_helpers", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "frunk_proc_macro_helpers" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1952b802269f2db12ab7c0bd328d0ae8feaabf19f352a7b0af7bb0c5693abfce" +dependencies = [ + "frunk_core", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "frunk_proc_macros" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3462f590fa236005bd7ca4847f81438bd6fe0febd4d04e11968d4c2e96437e78" +dependencies = [ + "frunk_core", + "frunk_proc_macro_helpers", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "fs-err" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73fde052dbfc920003cfd2c8e2c6e6d4cc7c1091538c3a24226cec0665ab08c0" +dependencies = [ + "autocfg", + "tokio", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "futures" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-executor" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-timer" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.0", + "wasip2", + "wasip3", +] + +[[package]] +name = "getset" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cf0fc11e47561d47397154977bc219f4cf809b2974facc3ccb3b89e2436f912" +dependencies = [ + "proc-macro-error2", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "gimli" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" + +[[package]] +name = "glob" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" + +[[package]] +name = "gloo-timers" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994" +dependencies = [ + "futures-channel", + "futures-core", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "h2" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap 2.13.1", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy 0.8.48", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "foldhash 0.2.0", +] + +[[package]] +name = "hashlink" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea0b22561a9c04a7cb1a302c013e0259cd3b4bb619f145b32f72b8b4bcbed230" +dependencies = [ + "hashbrown 0.16.1", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hex-literal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e712f64ec3850b98572bffac52e2c6f282b29fe6c5fa6d42334b30be438d95c1" + +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "http" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-named-pipe" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73b7d8abf35697b81a825e386fc151e0d503e8cb5fcb93cc8669c376dfd6f278" +dependencies = [ + "hex", + "hyper", + "hyper-util", + "pin-project-lite", + "tokio", + "tower-service", + "winapi", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-timeout" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" +dependencies = [ + "hyper", + "hyper-util", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2 0.6.3", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", +] + +[[package]] +name = "hyperlocal" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "986c5ce3b994526b3cd75578e62554abd09f0899d6206de48b3e96ab34ccc8c7" +dependencies = [ + "hex", + "http-body-util", + "hyper", + "hyper-util", + "pin-project-lite", + "tokio", + "tower-service", ] [[package]] -name = "codespan-reporting" -version = "0.11.1" +name = "iana-time-zone" +version = "0.1.65" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" dependencies = [ - "termcolor", - "unicode-width", + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", ] [[package]] -name = "config" -version = "0.13.3" +name = "iana-time-zone-haiku" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d379af7f68bfc21714c6c7dea883544201741d2ce8274bb12fa54f89507f52a7" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" dependencies = [ - "async-trait", - "json5", - "lazy_static", - "nom", - "pathdiff", - "ron", - "rust-ini", + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", "serde", - "serde_json", - "toml 0.5.11", - "yaml-rust", ] [[package]] -name = "convert_case" -version = "0.4.0" +name = "indexmap" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45a8a2b9cb3e0b0c1803dbb0758ffac5de2f425b23c28f518faabd9d805342ff" +dependencies = [ + "equivalent", + "hashbrown 0.16.1", + "serde", + "serde_core", +] + +[[package]] +name = "inlinable_string" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" +checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" [[package]] -name = "core-foundation" -version = "0.9.3" +name = "inout" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" dependencies = [ - "core-foundation-sys", + "generic-array", +] + +[[package]] +name = "io-enum" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7de9008599afe8527a8c9d70423437363b321649161e98473f433de802d76107" +dependencies = [ + "derive_utils", +] + +[[package]] +name = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + +[[package]] +name = "iri-string" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25e659a4bb38e810ebc252e53b5814ff908a8c58c2a9ce2fae1bbec24cbf4e20" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "is-terminal" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" +dependencies = [ + "hermit-abi", "libc", + "windows-sys 0.61.2", ] [[package]] -name = "core-foundation-sys" -version = "0.8.4" +name = "is_ci" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" +checksum = "7655c9839580ee829dfacba1d1278c2b7883e50a277ff7541299489d6bdfdc45" [[package]] -name = "cpufeatures" -version = "0.2.6" +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys 0.3.1", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.117", +] + +[[package]] +name = "jobserver" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" +dependencies = [ + "getrandom 0.3.4", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.94" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e04e2ef80ce82e13552136fabeef8a5ed1f985a96805761cbb9a2c34e7664d9" +dependencies = [ + "cfg-if", + "futures-util", + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "kv-log-macro" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de8b303297635ad57c9f5059fd9cee7a47f8e8daa09df0fcd07dd39fb22977f" +dependencies = [ + "log", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libc" +version = "0.2.184" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48f5d2a454e16a5ea0f4ced81bd44e4cfc7bd3a507b61887c99fd3538b28e4af" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "280a9f2d8b3a38871a3c8a46fb80db65e5e5ed97da80c4d08bf27fb63e35e181" +checksum = "7ddbf48fd451246b1f8c2610bd3b4ac0cc6e149d89832867093ab69a17194f08" dependencies = [ + "bitflags", "libc", + "plain", + "redox_syscall 0.7.3", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f111c8c41e7c61a49cd34e44c7619462967221a6443b0ec299e0ac30cfb9b1" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "libz-sys" +version = "1.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc3a226e576f50782b3305c5ccf458698f92798987f551c6a02efe8276721e22" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", ] [[package]] -name = "crc32fast" -version = "1.3.2" +name = "linux-raw-sys" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" -dependencies = [ - "cfg-if", -] +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] -name = "crossbeam" +name = "litemap" version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2801af0d36612ae591caa9568261fddce32ce6e08a7275ea334a06a4ad021a2c" -dependencies = [ - "cfg-if", - "crossbeam-channel", - "crossbeam-deque", - "crossbeam-epoch", - "crossbeam-queue", - "crossbeam-utils", -] +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" [[package]] -name = "crossbeam-channel" -version = "0.5.8" +name = "local-ip-address" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a33c2bf77f2df06183c3aa30d1e96c0695a313d4f9c453cc3762a6db39f99200" +checksum = "d4a59a0cb1c7f84471ad5cd38d768c2a29390d17f1ff2827cdf49bc53e8ac70b" dependencies = [ - "cfg-if", - "crossbeam-utils", + "libc", + "neli", + "windows-sys 0.61.2", ] [[package]] -name = "crossbeam-deque" -version = "0.8.3" +name = "lock_api" +version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6fd6f855243022dcecf8702fef0c297d4338e226845fe067f6341ad9fa0cef" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" dependencies = [ - "cfg-if", - "crossbeam-epoch", - "crossbeam-utils", + "scopeguard", ] [[package]] -name = "crossbeam-epoch" -version = "0.9.14" +name = "log" +version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46bd5f3f85273295a9d14aedfb86f6aadbff6d8f5295c4a9edb08e819dcf5695" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" dependencies = [ - "autocfg", - "cfg-if", - "crossbeam-utils", - "memoffset", - "scopeguard", + "value-bag", ] [[package]] -name = "crossbeam-queue" -version = "0.3.8" +name = "lru" +version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1cfb3ea8a53f37c40dea2c7bedcbd88bdfae54f5e2175d6ecaff1c988353add" +checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" dependencies = [ - "cfg-if", - "crossbeam-utils", + "hashbrown 0.15.5", ] [[package]] -name = "crossbeam-utils" -version = "0.8.15" +name = "lru-slab" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c063cd8cc95f5c377ed0d4b49a4b21f632396ff690e8470c29b3359b346984b" -dependencies = [ - "cfg-if", -] +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" [[package]] -name = "crypto-common" -version = "0.1.6" +name = "matchit" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" -dependencies = [ - "generic-array", - "typenum", -] +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" [[package]] -name = "cxx" -version = "1.0.94" +name = "miette" +version = "7.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f61f1b6389c3fe1c316bf8a4dccc90a38208354b330925bce1f74a6c4756eb93" +checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7" dependencies = [ - "cc", - "cxxbridge-flags", - "cxxbridge-macro", - "link-cplusplus", + "backtrace", + "backtrace-ext", + "cfg-if", + "miette-derive", + "owo-colors", + "supports-color", + "supports-hyperlinks", + "supports-unicode", + "terminal_size", + "textwrap", + "unicode-width 0.1.14", ] [[package]] -name = "cxx-build" -version = "1.0.94" +name = "miette-derive" +version = "7.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12cee708e8962df2aeb38f594aae5d827c022b6460ac71a7a3e2c3c2aae5a07b" +checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" dependencies = [ - "cc", - "codespan-reporting", - "once_cell", "proc-macro2", "quote", - "scratch", - "syn 2.0.14", + "syn 2.0.117", ] [[package]] -name = "cxxbridge-flags" -version = "1.0.94" +name = "mime" +version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7944172ae7e4068c533afbb984114a56c46e9ccddda550499caa222902c7f7bb" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" [[package]] -name = "cxxbridge-macro" -version = "1.0.94" +name = "minimal-lexical" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2345488264226bf682893e25de0769f3360aac9957980ec49361b083ddaa5bc5" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.14", -] +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] -name = "darling" -version = "0.14.4" +name = "miniz_oxide" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ - "darling_core", - "darling_macro", + "adler2", + "simd-adler32", ] [[package]] -name = "darling_core" -version = "0.14.4" +name = "mio" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0" +checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn 1.0.109", + "libc", + "wasi", + "windows-sys 0.61.2", ] [[package]] -name = "darling_macro" -version = "0.14.4" +name = "mockall" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e" +checksum = "f58d964098a5f9c6b63d0798e5372fd04708193510a7af313c22e9f29b7b620b" dependencies = [ - "darling_core", - "quote", - "syn 1.0.109", + "cfg-if", + "downcast", + "fragile", + "mockall_derive", + "predicates", + "predicates-tree", ] [[package]] -name = "derive_more" -version = "0.99.17" +name = "mockall_derive" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" +checksum = "ca41ce716dda6a9be188b385aa78ee5260fc25cd3802cb2a8afdc6afbe6b6dbf" dependencies = [ - "convert_case", + "cfg-if", "proc-macro2", "quote", - "rustc_version", - "syn 1.0.109", + "syn 2.0.117", ] [[package]] -name = "derive_utils" -version = "0.13.0" +name = "multimap" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dff8f6a793f528719e1ad4425a52a213ac1214ac7158c5fb97a7f50a64bfc96d" +checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.14", + "serde", ] [[package]] -name = "difflib" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" - -[[package]] -name = "digest" -version = "0.10.6" +name = "mysql" +version = "25.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8168378f4e5023e7218c89c891c0fd8ecdb5e5e4f18cb78f38cf245dd021e76f" +checksum = "c6ad644efb545e459029b1ffa7c969d830975bd76906820913247620df10050b" dependencies = [ - "block-buffer", - "crypto-common", + "bufstream", + "bytes", + "crossbeam", + "flate2", + "io-enum", + "libc", + "lru", + "mysql_common", + "named_pipe", + "native-tls", + "pem", + "percent-encoding", + "serde", + "serde_json", + "socket2 0.5.10", + "twox-hash", + "url", ] [[package]] -name = "dlv-list" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0688c2a7f92e427f44895cd63841bff7b29f8d7a1648b9e7e07a4a365b2e1257" - -[[package]] -name = "downcast" -version = "0.11.0" +name = "mysql-common-derive" +version = "0.31.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" +checksum = "63c3512cf11487168e0e9db7157801bf5273be13055a9cc95356dc9e0035e49c" +dependencies = [ + "darling 0.20.11", + "heck", + "num-bigint", + "proc-macro-crate", + "proc-macro-error2", + "proc-macro2", + "quote", + "syn 2.0.117", + "termcolor", + "thiserror 1.0.69", +] [[package]] -name = "either" -version = "1.8.1" +name = "mysql_common" +version = "0.32.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91" +checksum = "478b0ff3f7d67b79da2b96f56f334431aef65e15ba4b29dd74a4236e29582bdc" +dependencies = [ + "base64 0.21.7", + "bigdecimal", + "bindgen", + "bitflags", + "bitvec", + "btoi", + "byteorder", + "bytes", + "cc", + "cmake", + "crc32fast", + "flate2", + "frunk", + "lazy_static", + "mysql-common-derive", + "num-bigint", + "num-traits", + "rand 0.8.5", + "regex", + "rust_decimal", + "saturating", + "serde", + "serde_json", + "sha1", + "sha2", + "smallvec", + "subprocess", + "thiserror 1.0.69", + "time", + "uuid", + "zstd", +] [[package]] -name = "encoding_rs" -version = "0.8.32" +name = "named_pipe" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071a31f4ee85403370b58aca746f01041ede6f0da2730960ad001edc2b71b394" +checksum = "ad9c443cce91fc3e12f017290db75dde490d685cdaaf508d7159d7cf41f0eb2b" dependencies = [ - "cfg-if", + "winapi", ] [[package]] -name = "errno" -version = "0.3.1" +name = "native-tls" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" dependencies = [ - "errno-dragonfly", "libc", - "windows-sys 0.48.0", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", ] [[package]] -name = "errno-dragonfly" -version = "0.1.2" +name = "neli" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" +checksum = "22f9786d56d972959e1408b6a93be6af13b9c1392036c5c1fafa08a1b0c6ee87" dependencies = [ - "cc", + "bitflags", + "byteorder", + "derive_builder", + "getset", "libc", + "log", + "neli-proc-macros", + "parking_lot", ] [[package]] -name = "error-chain" -version = "0.11.0" +name = "neli-proc-macros" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff511d5dc435d703f4971bc399647c9bc38e20cb41452e3b9feb4765419ed3f3" +checksum = "05d8d08c6e98f20a62417478ebf7be8e1425ec9acecc6f63e22da633f6b71609" dependencies = [ - "backtrace", + "either", + "proc-macro2", + "quote", + "serde", + "syn 2.0.117", ] [[package]] -name = "fallible-iterator" -version = "0.2.0" +name = "nom" +version = "7.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] [[package]] -name = "fallible-streaming-iterator" -version = "0.1.9" +name = "nonempty" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" +checksum = "e9e591e719385e6ebaeb5ce5d3887f7d5676fceca6411d1925ccc95745f3d6f7" [[package]] -name = "fastrand" -version = "1.9.0" +name = "nu-ansi-term" +version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "instant", + "windows-sys 0.61.2", ] [[package]] -name = "fern" -version = "0.6.2" +name = "num" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9f0c14694cbd524c8720dd69b0e3179344f04ebb5f90f2e4a440c6ea3b2f1ee" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" dependencies = [ - "log", + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", ] [[package]] -name = "flate2" -version = "1.0.25" +name = "num-bigint" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8a2db397cb1c8772f31494cb8917e48cd1e64f0fa7efac59fbd741a0a8ce841" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" dependencies = [ - "crc32fast", - "libz-sys", - "miniz_oxide", + "num-integer", + "num-traits", ] [[package]] -name = "float-cmp" -version = "0.9.0" +name = "num-complex" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" dependencies = [ "num-traits", ] [[package]] -name = "fnv" -version = "1.0.7" +name = "num-conv" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" [[package]] -name = "foreign-types" -version = "0.3.2" +name = "num-integer" +version = "0.1.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" dependencies = [ - "foreign-types-shared", + "autocfg", + "num-integer", + "num-traits", ] [[package]] -name = "foreign-types-shared" -version = "0.1.1" +name = "num-rational" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] [[package]] -name = "form_urlencoded" -version = "1.1.0" +name = "num-traits" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ - "percent-encoding", + "autocfg", ] [[package]] -name = "forwarded-header-value" -version = "0.1.1" +name = "object" +version = "0.37.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8835f84f38484cc86f110a805655697908257fb9a7af005234060891557198e9" +checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" dependencies = [ - "nonempty", - "thiserror", + "memchr", ] [[package]] -name = "fragile" -version = "2.0.0" +name = "once_cell" +version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c2141d6d6c8512188a7891b4b01590a45f6dac67afb4f255c4124dbb86d4eaa" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] -name = "frunk" -version = "0.4.1" +name = "once_cell_polyfill" +version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89c703bf50009f383a0873845357cc400a95fc535f836feddfe015d7df6e1e0" -dependencies = [ - "frunk_core", - "frunk_derives", - "frunk_proc_macros", -] +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" [[package]] -name = "frunk_core" -version = "0.4.1" +name = "oorandom" +version = "11.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a446d01a558301dca28ef43222864a9fa2bd9a2e71370f769d5d5d5ec9f3537" +checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" [[package]] -name = "frunk_derives" -version = "0.4.1" +name = "openssl" +version = "0.10.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b83164912bb4c97cfe0772913c7af7387ee2e00cb6d4636fb65a35b3d0c8f173" +checksum = "951c002c75e16ea2c65b8c7e4d3d51d5530d8dfa7d060b4776828c88cfb18ecf" dependencies = [ - "frunk_proc_macro_helpers", - "quote", - "syn 1.0.109", + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "once_cell", + "openssl-macros", + "openssl-sys", ] [[package]] -name = "frunk_proc_macro_helpers" +name = "openssl-macros" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "015425591bbeb0f5b8a75593340f1789af428e9f887a4f1e36c0c471f067ef50" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ - "frunk_core", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.117", ] [[package]] -name = "frunk_proc_macros" -version = "0.1.1" +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "openssl-sys" +version = "0.9.112" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea01524f285deab48affffb342b97f186e657b119c3f1821ac531780e0fbfae0" +checksum = "57d55af3b3e226502be1526dfdba67ab0e9c96fc293004e79576b2b9edb0dbdb" dependencies = [ - "frunk_core", - "frunk_proc_macros_impl", - "proc-macro-hack", + "cc", + "libc", + "pkg-config", + "vcpkg", ] [[package]] -name = "frunk_proc_macros_impl" -version = "0.1.1" +name = "owo-colors" +version = "4.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d211803b9b6b570f68772237e415a029d5a50c65d382910b879fb19d3271f94d" + +[[package]] +name = "page_size" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a802d974cc18ee7fe1a7868fc9ce31086294fd96ba62f8da64ecb44e92a2653" +checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da" dependencies = [ - "frunk_core", - "frunk_proc_macro_helpers", - "proc-macro-hack", - "quote", - "syn 1.0.109", + "libc", + "winapi", ] [[package]] -name = "funty" -version = "2.0.0" +name = "parking" +version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" [[package]] -name = "futures" -version = "0.3.28" +name = "parking_lot" +version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23342abe12aba583913b2e62f22225ff9c950774065e4bfb61a19cd9770fec40" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", + "lock_api", + "parking_lot_core", ] [[package]] -name = "futures-channel" -version = "0.3.28" +name = "parking_lot_core" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ - "futures-core", - "futures-sink", + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", ] [[package]] -name = "futures-core" -version = "0.3.28" +name = "parse-display" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" +checksum = "914a1c2265c98e2446911282c6ac86d8524f495792c38c5bd884f80499c7538a" +dependencies = [ + "parse-display-derive", + "regex", + "regex-syntax", +] [[package]] -name = "futures-executor" -version = "0.3.28" +name = "parse-display-derive" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccecee823288125bd88b4d7f565c9e58e41858e47ab72e8ea2d64e93624386e0" +checksum = "2ae7800a4c974efd12df917266338e79a7a74415173caf7e70aa0a0707345281" dependencies = [ - "futures-core", - "futures-task", - "futures-util", + "proc-macro2", + "quote", + "regex", + "regex-syntax", + "structmeta", + "syn 2.0.117", ] [[package]] -name = "futures-io" -version = "0.3.28" +name = "pear" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" +checksum = "bdeeaa00ce488657faba8ebf44ab9361f9365a97bd39ffb8a60663f57ff4b467" +dependencies = [ + "inlinable_string", + "pear_codegen", + "yansi", +] [[package]] -name = "futures-macro" -version = "0.3.28" +name = "pear_codegen" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" +checksum = "4bab5b985dc082b345f812b7df84e1bef27e7207b39e448439ba8bd69c93f147" dependencies = [ "proc-macro2", + "proc-macro2-diagnostics", "quote", - "syn 2.0.14", + "syn 2.0.117", ] [[package]] -name = "futures-sink" -version = "0.3.28" +name = "pem" +version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] [[package]] -name = "futures-task" -version = "0.3.28" +name = "percent-encoding" +version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" [[package]] -name = "futures-util" -version = "0.3.28" +name = "phf" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "pin-utils", - "slab", + "phf_shared", ] [[package]] -name = "generic-array" -version = "0.14.7" +name = "phf_codegen" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" dependencies = [ - "typenum", - "version_check", + "phf_generator", + "phf_shared", ] [[package]] -name = "getrandom" -version = "0.2.9" +name = "phf_generator" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c85e1d9ab2eadba7e5040d4e09cbd6d072b76a557ad64e797c2cb9d4da21d7e4" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" dependencies = [ - "cfg-if", - "libc", - "wasi", + "phf_shared", + "rand 0.8.5", ] [[package]] -name = "gimli" -version = "0.27.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad0a93d233ebf96623465aad4046a8d3aa4da22d4f4beba5388838c8a434bbb4" - -[[package]] -name = "glob" -version = "0.3.1" +name = "phf_shared" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] [[package]] -name = "h2" -version = "0.3.17" +name = "pin-project" +version = "1.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66b91535aa35fea1523ad1b86cb6b53c28e0ae566ba4a460f4457e936cad7c6f" +checksum = "f1749c7ed4bcaf4c3d0a3efc28538844fb29bcdd7d2b67b2be7e20ba861ff517" dependencies = [ - "bytes", - "fnv", - "futures-core", - "futures-sink", - "futures-util", - "http", - "indexmap", - "slab", - "tokio", - "tokio-util", - "tracing", + "pin-project-internal", ] [[package]] -name = "hashbrown" -version = "0.12.3" +name = "pin-project-internal" +version = "1.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +checksum = "d9b20ed30f105399776b9c883e68e536ef602a16ae6f596d2c473591d6ad64c6" dependencies = [ - "ahash 0.7.6", + "proc-macro2", + "quote", + "syn 2.0.117", ] [[package]] -name = "hashbrown" -version = "0.13.2" +name = "pin-project-lite" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" -dependencies = [ - "ahash 0.8.3", -] +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] -name = "hashlink" -version = "0.8.1" +name = "pin-utils" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69fe1fcf8b4278d860ad0548329f892a3631fb63f82574df68275f34cdbe0ffa" -dependencies = [ - "hashbrown 0.12.3", -] +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] -name = "hermit-abi" -version = "0.2.6" +name = "piper" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" dependencies = [ - "libc", + "atomic-waker", + "fastrand", + "futures-io", ] [[package]] -name = "hermit-abi" -version = "0.3.1" +name = "pkg-config" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" [[package]] -name = "hex" -version = "0.4.3" +name = "plain" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" [[package]] -name = "http" -version = "0.2.9" +name = "plotters" +version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd6effc99afb63425aff9b05836f029929e345a6148a14b7ecd5ab67af944482" +checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" dependencies = [ - "bytes", - "fnv", - "itoa", + "num-traits", + "plotters-backend", + "plotters-svg", + "wasm-bindgen", + "web-sys", ] [[package]] -name = "http-body" -version = "0.4.5" +name = "plotters-backend" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" + +[[package]] +name = "plotters-svg" +version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" +checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670" dependencies = [ - "bytes", - "http", - "pin-project-lite", + "plotters-backend", ] [[package]] -name = "httparse" -version = "1.8.0" +name = "polling" +version = "3.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "windows-sys 0.61.2", +] [[package]] -name = "httpdate" -version = "1.0.2" +name = "portable-atomic" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" +checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" [[package]] -name = "hyper" -version = "0.14.26" +name = "portable-atomic-util" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab302d72a6f11a3b910431ff93aae7e773078c769f0a3ef15fb9ec692ed147d4" +checksum = "091397be61a01d4be58e7841595bd4bfedb15f1cd54977d79b8271e94ed799a3" dependencies = [ - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "h2", - "http", - "http-body", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "socket2", - "tokio", - "tower-service", - "tracing", - "want", + "portable-atomic", ] [[package]] -name = "hyper-tls" -version = "0.5.0" +name = "potential_utf" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" dependencies = [ - "bytes", - "hyper", - "native-tls", - "tokio", - "tokio-native-tls", + "zerovec", ] [[package]] -name = "iana-time-zone" -version = "0.1.56" +name = "powerfmt" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0722cd7114b7de04316e7ea5456a0bbb20e4adb46fd27a3697adb812cff0f37c" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "wasm-bindgen", - "windows", +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy 0.8.48", ] [[package]] -name = "iana-time-zone-haiku" -version = "0.1.1" +name = "predicates" +version = "3.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0703ae284fc167426161c2e3f1da3ea71d94b21bedbcc9494e92b28e334e3dca" +checksum = "ada8f2932f28a27ee7b70dd6c1c39ea0675c55a36879ab92f3a715eaa1e63cfe" dependencies = [ - "cxx", - "cxx-build", + "anstyle", + "predicates-core", ] [[package]] -name = "ident_case" -version = "1.0.1" +name = "predicates-core" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" +checksum = "cad38746f3166b4031b1a0d39ad9f954dd291e7854fcc0eed52ee41a0b50d144" [[package]] -name = "idna" -version = "0.3.0" +name = "predicates-tree" +version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e14ddfc70884202db2244c223200c204c2bda1bc6e0998d11b5e024d657209e6" +checksum = "d0de1b847b39c8131db0467e9df1ff60e6d0562ab8e9a16e568ad0fdb372e2f2" dependencies = [ - "unicode-bidi", - "unicode-normalization", + "predicates-core", + "termtree", ] [[package]] -name = "indexmap" -version = "1.9.3" +name = "pretty_assertions" +version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d" dependencies = [ - "autocfg", - "hashbrown 0.12.3", - "serde", + "diff", + "yansi", ] [[package]] -name = "instant" -version = "0.1.12" +name = "prettyplease" +version = "0.2.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" dependencies = [ - "cfg-if", + "proc-macro2", + "syn 2.0.117", ] [[package]] -name = "io-enum" -version = "1.1.0" +name = "proc-macro-crate" +version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01c662c349c9c9f542e7bfd9134143beb27da4b20dfbc3b3ef5b2a5b507dafbd" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "derive_utils", - "syn 2.0.14", + "toml_edit 0.25.10+spec-1.1.0", ] [[package]] -name = "io-lifetimes" -version = "1.0.10" +name = "proc-macro-error-attr2" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c66c74d2ae7e79a5a8f7ac924adbe38ee42a859c6539ad869eb51f0b52dc220" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" dependencies = [ - "hermit-abi 0.3.1", - "libc", - "windows-sys 0.48.0", + "proc-macro2", + "quote", ] [[package]] -name = "ipnet" -version = "2.7.2" +name = "proc-macro-error2" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12b6ee2129af8d4fb011108c73d99a1b83a85977f23b82460c0ae2e25bb4b57f" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +dependencies = [ + "proc-macro-error-attr2", + "proc-macro2", + "quote", + "syn 2.0.117", +] [[package]] -name = "itertools" -version = "0.10.5" +name = "proc-macro2" +version = "1.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" dependencies = [ - "either", + "unicode-ident", ] [[package]] -name = "itoa" -version = "1.0.6" +name = "proc-macro2-diagnostics" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "version_check", + "yansi", +] [[package]] -name = "js-sys" -version = "0.3.61" +name = "prost" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "445dde2150c55e483f3d8416706b97ec8e8237c307e5b7b4b8dd15e6af2a0730" +checksum = "d2ea70524a2f82d518bce41317d0fae74151505651af45faf1ffbd6fd33f0568" dependencies = [ - "wasm-bindgen", + "bytes", + "prost-derive", ] [[package]] -name = "json5" -version = "0.4.1" +name = "prost-derive" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96b0db21af676c1ce64250b5f40f3ce2cf27e4e47cb91ed91eb6fe9350b430c1" +checksum = "27c6023962132f4b30eb4c172c91ce92d933da334c59c23cddee82358ddafb0b" dependencies = [ - "pest", - "pest_derive", - "serde", + "anyhow", + "itertools 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.117", ] [[package]] -name = "lazy_static" -version = "1.4.0" +name = "prost-types" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" +checksum = "8991c4cbdb8bc5b11f0b074ffe286c30e523de90fee5ba8132f1399f23cb3dd7" +dependencies = [ + "prost", +] [[package]] -name = "lazycell" -version = "1.3.0" +name = "ptr_meta" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" +checksum = "0738ccf7ea06b608c10564b31debd4f5bc5e197fc8bfe088f68ae5ce81e7a4f1" +dependencies = [ + "ptr_meta_derive", +] [[package]] -name = "lexical" -version = "6.1.1" +name = "ptr_meta_derive" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7aefb36fd43fef7003334742cbf77b243fcd36418a1d1bdd480d613a67968f6" +checksum = "16b845dbfca988fa33db069c0e230574d15a3088f147a87b64c7589eb662c9ac" dependencies = [ - "lexical-core", + "proc-macro2", + "quote", + "syn 1.0.109", ] [[package]] -name = "lexical-core" -version = "0.8.5" +name = "quickcheck" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cde5de06e8d4c2faabc400238f9ae1c74d5412d03a7bd067645ccbc47070e46" +checksum = "95c589f335db0f6aaa168a7cd27b1fc6920f5e1470c804f814d9cd6e62a0f70b" dependencies = [ - "lexical-parse-float", - "lexical-parse-integer", - "lexical-util", - "lexical-write-float", - "lexical-write-integer", + "env_logger", + "log", + "rand 0.10.0", ] [[package]] -name = "lexical-parse-float" -version = "0.8.5" +name = "quinn" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "683b3a5ebd0130b8fb52ba0bdc718cc56815b6a097e28ae5a6997d0ad17dc05f" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" dependencies = [ - "lexical-parse-integer", - "lexical-util", - "static_assertions", + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2 0.6.3", + "thiserror 2.0.18", + "tokio", + "tracing", + "web-time", ] [[package]] -name = "lexical-parse-integer" -version = "0.8.6" +name = "quinn-proto" +version = "0.11.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d0994485ed0c312f6d965766754ea177d07f9c00c9b82a5ee62ed5b47945ee9" +checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" dependencies = [ - "lexical-util", - "static_assertions", + "aws-lc-rs", + "bytes", + "getrandom 0.3.4", + "lru-slab", + "rand 0.9.2", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.18", + "tinyvec", + "tracing", + "web-time", ] [[package]] -name = "lexical-util" -version = "0.8.5" +name = "quinn-udp" +version = "0.5.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5255b9ff16ff898710eb9eb63cb39248ea8a5bb036bea8085b1a767ff6c4e3fc" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" dependencies = [ - "static_assertions", + "cfg_aliases", + "libc", + "once_cell", + "socket2 0.6.3", + "tracing", + "windows-sys 0.60.2", ] [[package]] -name = "lexical-write-float" -version = "0.8.5" +name = "quote" +version = "1.0.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accabaa1c4581f05a3923d1b4cfd124c329352288b7b9da09e766b0668116862" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" dependencies = [ - "lexical-util", - "lexical-write-integer", - "static_assertions", + "proc-macro2", ] [[package]] -name = "lexical-write-integer" -version = "0.8.5" +name = "r-efi" +version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1b6f3d1f4422866b68192d62f77bc5c700bee84f3069f2469d7bc8c77852446" -dependencies = [ - "lexical-util", - "static_assertions", -] +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" [[package]] -name = "libc" -version = "0.2.141" +name = "r-efi" +version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3304a64d199bb964be99741b7a14d26972741915b3649639149b2479bb46f4b5" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] -name = "libloading" -version = "0.7.4" +name = "r2d2" +version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +checksum = "51de85fb3fb6524929c8a2eb85e6b6d363de4e8c48f9e2c2eac4944abc181c93" dependencies = [ - "cfg-if", - "winapi", + "log", + "parking_lot", + "scheduled-thread-pool", ] [[package]] -name = "libsqlite3-sys" -version = "0.25.2" +name = "r2d2_mysql" +version = "25.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29f835d03d717946d28b1d1ed632eb6f0e24a299388ee623d0c23118d3e8a7fa" +checksum = "93963fe09ca35b0311d089439e944e42a6cb39bf8ea323782ddb31240ba2ae87" dependencies = [ - "cc", - "pkg-config", - "vcpkg", + "mysql", + "r2d2", ] [[package]] -name = "libz-sys" -version = "1.1.8" +name = "r2d2_sqlite" +version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9702761c3935f8cc2f101793272e202c72b99da8f4224a19ddcf1279a6450bbf" +checksum = "5576df16239e4e422c4835c8ed00be806d4491855c7847dba60b7aa8408b469b" dependencies = [ - "cc", - "pkg-config", - "vcpkg", + "r2d2", + "rusqlite", + "uuid", ] [[package]] -name = "link-cplusplus" -version = "1.0.8" +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecd207c9c713c34f95a097a5b029ac2ce6010530c7b49d7fea24d977dede04f5" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ - "cc", + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", ] [[package]] -name = "linked-hash-map" -version = "0.5.6" +name = "rand" +version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] [[package]] -name = "linux-raw-sys" -version = "0.3.1" +name = "rand" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d59d8c75012853d2e872fb56bc8a2e53718e2cafe1a4c823143141c6d90c322f" +checksum = "bc266eb313df6c5c09c1c7b1fbe2510961e5bcd3add930c1e31f7ed9da0feff8" +dependencies = [ + "chacha20", + "getrandom 0.4.2", + "rand_core 0.10.0", +] [[package]] -name = "local-ip-address" -version = "0.5.1" +name = "rand_chacha" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faa9d02443a1741e9f51dafdfcbffb3863b2a89c457d762b40337d6c5153ef81" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ - "libc", - "neli", - "thiserror", - "windows-sys 0.42.0", + "ppv-lite86", + "rand_core 0.6.4", ] [[package]] -name = "lock_api" -version = "0.4.9" +name = "rand_chacha" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ - "autocfg", - "scopeguard", + "ppv-lite86", + "rand_core 0.9.5", ] [[package]] -name = "log" -version = "0.4.17" +name = "rand_core" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ - "cfg-if", + "getrandom 0.2.17", ] [[package]] -name = "lru" -version = "0.8.1" +name = "rand_core" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6e8aaa3f231bb4bd57b84b2d5dc3ae7f350265df8aa96492e0bc394a1571909" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" dependencies = [ - "hashbrown 0.12.3", + "getrandom 0.3.4", ] [[package]] -name = "matchit" -version = "0.7.0" +name = "rand_core" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b87248edafb776e59e6ee64a79086f65890d3510f2c656c000bf2a7e8a0aea40" +checksum = "0c8d0fd677905edcbeedbf2edb6494d676f0e98d54d5cf9bda0b061cb8fb8aba" [[package]] -name = "memchr" -version = "2.5.0" +name = "rayon" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" +checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" +dependencies = [ + "either", + "rayon-core", +] [[package]] -name = "memoffset" -version = "0.8.0" +name = "rayon-core" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d61c719bcfbcf5d62b3a09efa6088de8c54bc0bfcd3ea7ae39fcc186108b8de1" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" dependencies = [ - "autocfg", + "crossbeam-deque", + "crossbeam-utils", ] [[package]] -name = "mime" -version = "0.3.17" +name = "redox_syscall" +version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] [[package]] -name = "minimal-lexical" -version = "0.2.1" +name = "redox_syscall" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" +checksum = "6ce70a74e890531977d37e532c34d45e9055d2409ed08ddba14529471ed0be16" +dependencies = [ + "bitflags", +] [[package]] -name = "miniz_oxide" -version = "0.6.2" +name = "ref-cast" +version = "1.0.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b275950c28b37e794e8c55d88aeb5e139d0ce23fdbbeda68f8d7174abdf9e8fa" +checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d" dependencies = [ - "adler", + "ref-cast-impl", ] [[package]] -name = "mio" -version = "0.8.6" +name = "ref-cast-impl" +version = "1.0.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b9d9a46eff5b4ff64b45a9e316a6d1e0bc719ef429cbec4dc630684212bfdf9" +checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da" dependencies = [ - "libc", - "log", - "wasi", - "windows-sys 0.45.0", + "proc-macro2", + "quote", + "syn 2.0.117", ] [[package]] -name = "mockall" -version = "0.11.4" +name = "regex" +version = "1.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c84490118f2ee2d74570d114f3d0493cbf02790df303d2707606c3e14e07c96" +checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" dependencies = [ - "cfg-if", - "downcast", - "fragile", - "lazy_static", - "mockall_derive", - "predicates", - "predicates-tree", + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", ] [[package]] -name = "mockall_derive" -version = "0.11.4" +name = "regex-automata" +version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22ce75669015c4f47b289fd4d4f56e894e4c96003ffdf3ac51313126f94c6cbb" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" dependencies = [ - "cfg-if", - "proc-macro2", - "quote", - "syn 1.0.109", + "aho-corasick", + "memchr", + "regex-syntax", ] [[package]] -name = "multimap" -version = "0.9.0" +name = "regex-syntax" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" + +[[package]] +name = "relative-path" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2" + +[[package]] +name = "rend" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70db9248a93dc36a36d9a47898caa007a32755c7ad140ec64eeeb50d5a730631" +checksum = "71fe3824f5629716b1589be05dacd749f6aa084c87e00e016714a8cdfccc997c" dependencies = [ - "serde", + "bytecheck", ] [[package]] -name = "mysql" -version = "23.0.1" +name = "reqwest" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f11339ca5c251941805d51362a07823605a80586ced92914ab7de84fba813f" +checksum = "ab3f43e3283ab1488b624b44b0e988d0acea0b3214e694730a055cb6b2efa801" dependencies = [ - "bufstream", + "base64 0.22.1", "bytes", - "crossbeam", - "flate2", - "io-enum", - "libc", - "lru", - "mysql_common", - "named_pipe", - "native-tls", - "once_cell", - "pem", + "encoding_rs", + "futures-core", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "mime", "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", "serde", "serde_json", - "socket2", - "twox-hash", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", ] [[package]] -name = "mysql_common" -version = "0.29.2" +name = "ring" +version = "0.17.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9006c95034ccf7b903d955f210469119f6c3477fc9c9e7a7845ce38a3e665c2a" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" dependencies = [ - "base64 0.13.1", - "bigdecimal", - "bindgen", - "bitflags", - "bitvec", - "byteorder", - "bytes", "cc", - "cmake", - "crc32fast", - "flate2", - "frunk", - "lazy_static", - "lexical", - "num-bigint", - "num-traits", - "rand", - "regex", - "rust_decimal", - "saturating", - "serde", - "serde_json", - "sha1", - "sha2", - "smallvec", - "subprocess", - "thiserror", - "time", - "uuid", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", ] [[package]] -name = "named_pipe" -version = "0.4.1" +name = "ringbuf" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad9c443cce91fc3e12f017290db75dde490d685cdaaf508d7159d7cf41f0eb2b" +checksum = "fe47b720588c8702e34b5979cb3271a8b1842c7cb6f57408efa70c779363488c" dependencies = [ - "winapi", + "crossbeam-utils", + "portable-atomic", + "portable-atomic-util", ] [[package]] -name = "native-tls" -version = "0.2.11" +name = "rkyv" +version = "0.7.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07226173c32f2926027b63cce4bcd8076c3552846cbe7925f3aaffeac0a3b92e" +checksum = "2297bf9c81a3f0dc96bc9521370b88f054168c29826a75e89c55ff196e7ed6a1" dependencies = [ - "lazy_static", - "libc", - "log", - "openssl", - "openssl-probe", - "openssl-sys", - "schannel", - "security-framework", - "security-framework-sys", - "tempfile", + "bitvec", + "bytecheck", + "bytes", + "hashbrown 0.12.3", + "ptr_meta", + "rend", + "rkyv_derive", + "seahash", + "tinyvec", + "uuid", ] [[package]] -name = "neli" -version = "0.5.3" +name = "rkyv_derive" +version = "0.7.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9053554eb5dcb7e10d9cdab1206965bde870eed5d0d341532ca035e3ba221508" +checksum = "84d7b42d4b8d06048d3ac8db0eb31bcb942cbeb709f0b5f2b2ebde398d3038f5" dependencies = [ - "byteorder", - "libc", + "proc-macro2", + "quote", + "syn 1.0.109", ] [[package]] -name = "nom" -version = "7.1.3" +name = "rsqlite-vfs" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +checksum = "a8a1f2315036ef6b1fbacd1972e8ee7688030b0a2121edfc2a6550febd41574d" dependencies = [ - "memchr", - "minimal-lexical", + "hashbrown 0.16.1", + "thiserror 2.0.18", ] [[package]] -name = "nonempty" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9e591e719385e6ebaeb5ce5d3887f7d5676fceca6411d1925ccc95745f3d6f7" - -[[package]] -name = "normalize-line-endings" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" - -[[package]] -name = "num-bigint" -version = "0.4.3" +name = "rstest" +version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f" +checksum = "6fc39292f8613e913f7df8fa892b8944ceb47c247b78e1b1ae2f09e019be789d" dependencies = [ - "autocfg", - "num-integer", - "num-traits", + "futures-timer", + "futures-util", + "rstest_macros 0.25.0", + "rustc_version", ] [[package]] -name = "num-integer" -version = "0.1.45" +name = "rstest" +version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" +checksum = "f5a3193c063baaa2a95a33f03035c8a72b83d97a54916055ba22d35ed3839d49" dependencies = [ - "autocfg", - "num-traits", + "futures-timer", + "futures-util", + "rstest_macros 0.26.1", ] [[package]] -name = "num-traits" -version = "0.2.15" +name = "rstest_macros" +version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" +checksum = "1f168d99749d307be9de54d23fd226628d99768225ef08f6ffb52e0182a27746" dependencies = [ - "autocfg", + "cfg-if", + "glob", + "proc-macro-crate", + "proc-macro2", + "quote", + "regex", + "relative-path", + "rustc_version", + "syn 2.0.117", + "unicode-ident", ] [[package]] -name = "num_cpus" -version = "1.15.0" +name = "rstest_macros" +version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" +checksum = "9c845311f0ff7951c5506121a9ad75aec44d083c31583b2ea5a30bcb0b0abba0" dependencies = [ - "hermit-abi 0.2.6", - "libc", + "cfg-if", + "glob", + "proc-macro-crate", + "proc-macro2", + "quote", + "regex", + "relative-path", + "rustc_version", + "syn 2.0.117", + "unicode-ident", ] [[package]] -name = "object" -version = "0.30.3" +name = "rusqlite" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea86265d3d3dcb6a27fc51bd29a4bf387fae9d2986b823079d4986af253eb439" +checksum = "a0d2b0146dd9661bf67bb107c0bb2a55064d556eeb3fc314151b957f313bcd4e" dependencies = [ - "memchr", + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", ] [[package]] -name = "once_cell" -version = "1.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3" - -[[package]] -name = "openssl" -version = "0.10.50" +name = "rust_decimal" +version = "1.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e30d8bc91859781f0a943411186324d580f2bbeb71b452fe91ae344806af3f1" +checksum = "2ce901f9a19d251159075a4c37af514c3b8ef99c22e02dd8c19161cf397ee94a" dependencies = [ - "bitflags", - "cfg-if", - "foreign-types", - "libc", - "once_cell", - "openssl-macros", - "openssl-sys", + "arrayvec", + "borsh", + "bytes", + "num-traits", + "rand 0.8.5", + "rkyv", + "serde", + "serde_json", + "wasm-bindgen", ] [[package]] -name = "openssl-macros" -version = "0.1.1" +name = "rustc-demangle" +version = "0.1.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.14", -] +checksum = "b50b8869d9fc858ce7266cce0194bd74df58b9d0e3f6df3a9fc8eb470d95c09d" [[package]] -name = "openssl-probe" -version = "0.1.5" +name = "rustc-hash" +version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" [[package]] -name = "openssl-src" -version = "111.25.2+1.1.1t" +name = "rustc_version" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320708a054ad9b3bf314688b5db87cf4d6683d64cfc835e2337924ae62bf4431" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" dependencies = [ - "cc", + "semver", ] [[package]] -name = "openssl-sys" -version = "0.9.85" +name = "rustix" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d3d193fb1488ad46ffe3aaabc912cc931d02ee8518fe2959aea8ef52718b0c0" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ - "cc", + "bitflags", + "errno", "libc", - "openssl-src", - "pkg-config", - "vcpkg", + "linux-raw-sys", + "windows-sys 0.61.2", ] [[package]] -name = "ordered-multimap" -version = "0.4.3" +name = "rustls" +version = "0.23.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccd746e37177e1711c20dd619a1620f34f5c8b569c53590a72dedd5344d8924a" +checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4" dependencies = [ - "dlv-list", - "hashbrown 0.12.3", + "aws-lc-rs", + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", ] [[package]] -name = "parking_lot" -version = "0.12.1" +name = "rustls-native-certs" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" +checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63" dependencies = [ - "lock_api", - "parking_lot_core", + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", ] [[package]] -name = "parking_lot_core" -version = "0.9.7" +name = "rustls-pki-types" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9069cbb9f99e3a5083476ccb29ceb1de18b9118cafa53e90c9551235de2b9521" +checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" dependencies = [ - "cfg-if", - "libc", - "redox_syscall 0.2.16", - "smallvec", - "windows-sys 0.45.0", + "web-time", + "zeroize", ] [[package]] -name = "pathdiff" -version = "0.2.1" +name = "rustls-platform-verifier" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" +checksum = "1d99feebc72bae7ab76ba994bb5e121b8d83d910ca40b36e0921f53becc41784" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] [[package]] -name = "peeking_take_while" -version = "0.1.2" +name = "rustls-platform-verifier-android" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" +checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" [[package]] -name = "pem" -version = "1.1.1" +name = "rustls-webpki" +version = "0.103.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8835c273a76a90455d7344889b0964598e3316e2a79ede8e36f16bdcf2228b8" +checksum = "df33b2b81ac578cabaf06b89b0631153a3f416b0a886e8a7a1707fb51abbd1ef" dependencies = [ - "base64 0.13.1", + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", ] [[package]] -name = "percent-encoding" -version = "2.2.0" +name = "rustversion" +version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] -name = "pest" -version = "2.5.7" +name = "ryu" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b1403e8401ad5dedea73c626b99758535b342502f8d1e361f4a2dd952749122" -dependencies = [ - "thiserror", - "ucd-trie", -] +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" [[package]] -name = "pest_derive" -version = "2.5.7" +name = "same-file" +version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be99c4c1d2fc2769b1d00239431d711d08f6efedcecb8b6e30707160aee99c15" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" dependencies = [ - "pest", - "pest_generator", + "winapi-util", ] [[package]] -name = "pest_generator" -version = "2.5.7" +name = "saturating" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e56094789873daa36164de2e822b3888c6ae4b4f9da555a1103587658c805b1e" -dependencies = [ - "pest", - "pest_meta", - "proc-macro2", - "quote", - "syn 2.0.14", -] +checksum = "ece8e78b2f38ec51c51f5d475df0a7187ba5111b2a28bdc761ee05b075d40a71" [[package]] -name = "pest_meta" -version = "2.5.7" +name = "schannel" +version = "0.1.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6733073c7cff3d8459fda0e42f13a047870242aed8b509fe98000928975f359e" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" dependencies = [ - "once_cell", - "pest", - "sha2", + "windows-sys 0.61.2", ] [[package]] -name = "pin-project" -version = "1.0.12" +name = "scheduled-thread-pool" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad29a609b6bcd67fee905812e544992d216af9d755757c05ed2d0e15a74c6ecc" +checksum = "3cbc66816425a074528352f5789333ecff06ca41b36b0b0efdfbb29edc391a19" dependencies = [ - "pin-project-internal", + "parking_lot", ] [[package]] -name = "pin-project-internal" -version = "1.0.12" +name = "schemars" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "069bdb1e05adc7a8990dce9cc75370895fbe4e3d58b9b73bf1aee56359344a55" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", + "dyn-clone", + "ref-cast", + "serde", + "serde_json", ] [[package]] -name = "pin-project-lite" -version = "0.2.9" +name = "schemars" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" +checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] [[package]] -name = "pin-utils" -version = "0.1.0" +name = "scopeguard" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] -name = "pkg-config" -version = "0.3.26" +name = "seahash" +version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160" +checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" [[package]] -name = "ppv-lite86" -version = "0.2.17" +name = "security-framework" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] [[package]] -name = "predicates" -version = "2.1.5" +name = "security-framework-sys" +version = "2.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59230a63c37f3e18569bdb90e4a89cbf5bf8b06fea0b84e65ea10cc4df47addd" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" dependencies = [ - "difflib", - "float-cmp", - "itertools", - "normalize-line-endings", - "predicates-core", - "regex", + "core-foundation-sys", + "libc", ] [[package]] -name = "predicates-core" -version = "1.0.6" +name = "semver" +version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b794032607612e7abeb4db69adb4e33590fa6cf1149e95fd7cb00e634b92f174" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" [[package]] -name = "predicates-tree" -version = "1.0.9" +name = "serde" +version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "368ba315fb8c5052ab692e68a0eefec6ec57b23a36959c14496f0b0df2c0cecf" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" dependencies = [ - "predicates-core", - "termtree", + "serde_core", + "serde_derive", ] [[package]] -name = "proc-macro-crate" -version = "0.1.5" +name = "serde_bencode" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d6ea3c4595b96363c13943497db34af4460fb474a95c43f4446ad341b8c9785" +checksum = "a70dfc7b7438b99896e7f8992363ab8e2c4ba26aa5ec675d32d1c3c2c33d413e" dependencies = [ - "toml 0.5.11", + "serde", + "serde_bytes", ] [[package]] -name = "proc-macro-hack" -version = "0.5.20+deprecated" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" - -[[package]] -name = "proc-macro2" -version = "1.0.56" +name = "serde_bytes" +version = "0.11.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b63bdb0cd06f1f4dedf69b254734f9b45af66e4a031e42a7480257d9898b435" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" dependencies = [ - "unicode-ident", + "serde", + "serde_core", ] [[package]] -name = "ptr_meta" -version = "0.1.4" +name = "serde_core" +version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0738ccf7ea06b608c10564b31debd4f5bc5e197fc8bfe088f68ae5ce81e7a4f1" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" dependencies = [ - "ptr_meta_derive", + "serde_derive", ] [[package]] -name = "ptr_meta_derive" -version = "0.1.4" +name = "serde_derive" +version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16b845dbfca988fa33db069c0e230574d15a3088f147a87b64c7589eb662c9ac" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.117", ] [[package]] -name = "quote" -version = "1.0.26" +name = "serde_html_form" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc" +checksum = "b2f2d7ff8a2140333718bb329f5c40fc5f0865b84c426183ce14c97d2ab8154f" dependencies = [ - "proc-macro2", + "form_urlencoded", + "indexmap 2.13.1", + "itoa", + "ryu", + "serde_core", ] [[package]] -name = "r2d2" -version = "0.8.10" +name = "serde_json" +version = "1.0.149" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51de85fb3fb6524929c8a2eb85e6b6d363de4e8c48f9e2c2eac4944abc181c93" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" dependencies = [ - "log", - "parking_lot", - "scheduled-thread-pool", + "indexmap 2.13.1", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", ] [[package]] -name = "r2d2_mysql" -version = "23.0.0" +name = "serde_path_to_error" +version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9733d738ce65959a744f387bae69aa690a867e18d48e5486b171c47bc7b0c575" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" dependencies = [ - "mysql", - "r2d2", + "itoa", + "serde", + "serde_core", ] [[package]] -name = "r2d2_sqlite" -version = "0.21.0" +name = "serde_repr" +version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4f5d0337e99cd5cacd91ffc326c6cc9d8078def459df560c4f9bf9ba4a51034" +checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" dependencies = [ - "r2d2", - "rusqlite", + "proc-macro2", + "quote", + "syn 2.0.117", ] [[package]] -name = "radium" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" - -[[package]] -name = "rand" -version = "0.8.5" +name = "serde_spanned" +version = "0.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" dependencies = [ - "libc", - "rand_chacha", - "rand_core", + "serde", ] [[package]] -name = "rand_chacha" -version = "0.3.1" +name = "serde_spanned" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" dependencies = [ - "ppv-lite86", - "rand_core", + "serde_core", ] [[package]] -name = "rand_core" -version = "0.6.4" +name = "serde_urlencoded" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" dependencies = [ - "getrandom", + "form_urlencoded", + "itoa", + "ryu", + "serde", ] [[package]] -name = "redox_syscall" -version = "0.2.16" +name = "serde_with" +version = "3.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" +checksum = "dd5414fad8e6907dbdd5bc441a50ae8d6e26151a03b1de04d89a5576de61d01f" dependencies = [ - "bitflags", + "base64 0.22.1", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.13.1", + "schemars 0.9.0", + "schemars 1.2.1", + "serde_core", + "serde_json", + "serde_with_macros", + "time", ] [[package]] -name = "redox_syscall" -version = "0.3.5" +name = "serde_with_macros" +version = "3.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" +checksum = "d3db8978e608f1fe7357e211969fd9abdcae80bac1ba7a3369bb7eb6b404eb65" dependencies = [ - "bitflags", + "darling 0.23.0", + "proc-macro2", + "quote", + "syn 2.0.117", ] [[package]] -name = "regex" -version = "1.7.3" +name = "sha1" +version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b1f693b24f6ac912f4893ef08244d70b6067480d2f1a46e950c9691e6749d1d" +checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", + "cfg-if", + "cpufeatures 0.2.17", + "digest", ] [[package]] -name = "regex-syntax" -version = "0.6.29" +name = "sha2" +version = "0.10.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] [[package]] -name = "rend" -version = "0.4.0" +name = "sharded-slab" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "581008d2099240d37fb08d77ad713bcaec2c4d89d50b5b21a8bb1996bbab68ab" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" dependencies = [ - "bytecheck", + "lazy_static", ] [[package]] -name = "reqwest" -version = "0.11.16" +name = "shlex" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27b71749df584b7f4cac2c426c127a7c785a5106cc98f7a8feb044115f0fa254" -dependencies = [ - "base64 0.21.0", - "bytes", - "encoding_rs", - "futures-core", - "futures-util", - "h2", - "http", - "http-body", - "hyper", - "hyper-tls", - "ipnet", - "js-sys", - "log", - "mime", - "native-tls", - "once_cell", - "percent-encoding", - "pin-project-lite", - "serde", - "serde_json", - "serde_urlencoded", - "tokio", - "tokio-native-tls", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "winreg", -] +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] -name = "ring" -version = "0.16.20" +name = "signal-hook-registry" +version = "1.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" dependencies = [ - "cc", + "errno", "libc", - "once_cell", - "spin", - "untrusted", - "web-sys", - "winapi", ] [[package]] -name = "rkyv" -version = "0.7.41" +name = "simd-adler32" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21499ed91807f07ae081880aabb2ccc0235e9d88011867d984525e9a4c3cfa3e" -dependencies = [ - "bytecheck", - "hashbrown 0.12.3", - "ptr_meta", - "rend", - "rkyv_derive", - "seahash", -] +checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" [[package]] -name = "rkyv_derive" -version = "0.7.41" +name = "simdutf8" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac1c672430eb41556291981f45ca900a0239ad007242d1cb4b4167af842db666" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" [[package]] -name = "ron" -version = "0.7.1" +name = "siphasher" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88073939a61e5b7680558e6be56b419e208420c2adb92be54921fa6b72283f1a" -dependencies = [ - "base64 0.13.1", - "bitflags", - "serde", -] +checksum = "b2aa850e253778c88a04c3d7323b043aeda9d3e30d5971937c1855769763678e" [[package]] -name = "rusqlite" -version = "0.28.0" +name = "slab" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01e213bc3ecb39ac32e81e51ebe31fd888a940515173e3a18a35f8c6e896422a" -dependencies = [ - "bitflags", - "fallible-iterator", - "fallible-streaming-iterator", - "hashlink", - "libsqlite3-sys", - "smallvec", -] +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" [[package]] -name = "rust-ini" -version = "0.18.0" +name = "socket2" +version = "0.5.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6d5f2436026b4f6e79dc829837d467cc7e9a55ee40e750d716713540715a2df" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" dependencies = [ - "cfg-if", - "ordered-multimap", + "libc", + "windows-sys 0.52.0", ] [[package]] -name = "rust_decimal" -version = "1.29.1" +name = "socket2" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26bd36b60561ee1fb5ec2817f198b6fd09fa571c897a5e86d1487cfc2b096dfc" +checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" dependencies = [ - "arrayvec", - "borsh", - "bytecheck", - "byteorder", - "bytes", - "num-traits", - "rand", - "rkyv", - "serde", - "serde_json", + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "sqlite-wasm-rs" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4206ed3a67690b9c29b77d728f6acc3ce78f16bf846d83c94f76400320181b" +dependencies = [ + "cc", + "js-sys", + "rsqlite-vfs", + "wasm-bindgen", ] [[package]] -name = "rustc-demangle" -version = "0.1.22" +name = "stable_deref_trait" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4a36c42d1873f9a77c53bde094f9664d9891bc604a45b4798fd2c389ed12e5b" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" [[package]] -name = "rustc-hash" +name = "static_assertions" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] -name = "rustc_version" -version = "0.4.0" +name = "strsim" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" -dependencies = [ - "semver", -] +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] -name = "rustix" -version = "0.37.11" +name = "structmeta" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85597d61f83914ddeba6a47b3b8ffe7365107221c2e557ed94426489fefb5f77" +checksum = "2e1575d8d40908d70f6fd05537266b90ae71b15dbbe7a8b7dffa2b759306d329" dependencies = [ - "bitflags", - "errno", - "io-lifetimes", - "libc", - "linux-raw-sys", - "windows-sys 0.48.0", + "proc-macro2", + "quote", + "structmeta-derive", + "syn 2.0.117", ] [[package]] -name = "rustls" -version = "0.20.8" +name = "structmeta-derive" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fff78fc74d175294f4e83b28343315ffcfb114b156f0185e9741cb5570f50e2f" +checksum = "152a0b65a590ff6c3da95cabe2353ee04e6167c896b28e3b14478c2636c922fc" dependencies = [ - "log", - "ring", - "sct", - "webpki", + "proc-macro2", + "quote", + "syn 2.0.117", ] [[package]] -name = "rustls-pemfile" -version = "1.0.2" +name = "subprocess" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d194b56d58803a43635bdc398cd17e383d6f71f9182b9a192c127ca42494a59b" +checksum = "2c56e8662b206b9892d7a5a3f2ecdbcb455d3d6b259111373b7e08b8055158a8" dependencies = [ - "base64 0.21.0", + "libc", + "winapi", ] [[package]] -name = "rustversion" -version = "1.0.12" +name = "subtle" +version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f3208ce4d8448b3f3e7d168a73f5e0c43a61e32930de3bceeccedb388b6bf06" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] -name = "ryu" -version = "1.0.13" +name = "supports-color" +version = "3.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041" +checksum = "c64fc7232dd8d2e4ac5ce4ef302b1d81e0b80d055b9d77c7c4f51f6aa4c867d6" +dependencies = [ + "is_ci", +] [[package]] -name = "saturating" -version = "0.1.0" +name = "supports-hyperlinks" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ece8e78b2f38ec51c51f5d475df0a7187ba5111b2a28bdc761ee05b075d40a71" +checksum = "e396b6523b11ccb83120b115a0b7366de372751aa6edf19844dfb13a6af97e91" [[package]] -name = "schannel" -version = "0.1.21" +name = "supports-unicode" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "713cfb06c7059f3588fb8044c0fad1d09e3c01d225e25b9220dbfdcf16dbb1b3" -dependencies = [ - "windows-sys 0.42.0", -] +checksum = "b7401a30af6cb5818bb64852270bb722533397edcfc7344954a38f420819ece2" [[package]] -name = "scheduled-thread-pool" -version = "0.2.7" +name = "syn" +version = "1.0.109" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cbc66816425a074528352f5789333ecff06ca41b36b0b0efdfbb29edc391a19" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" dependencies = [ - "parking_lot", + "proc-macro2", + "quote", + "unicode-ident", ] [[package]] -name = "scopeguard" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" - -[[package]] -name = "scratch" -version = "1.0.5" +name = "syn" +version = "2.0.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1792db035ce95be60c3f8853017b3999209281c24e2ba5bc8e59bf97a0c590c1" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] [[package]] -name = "sct" -version = "0.7.0" +name = "sync_wrapper" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" dependencies = [ - "ring", - "untrusted", + "futures-core", ] [[package]] -name = "seahash" -version = "4.1.0" +name = "synstructure" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] [[package]] -name = "security-framework" -version = "2.8.2" +name = "system-configuration" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a332be01508d814fed64bf28f798a146d73792121129962fdf335bb3c49a4254" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" dependencies = [ "bitflags", - "core-foundation", - "core-foundation-sys", - "libc", - "security-framework-sys", + "core-foundation 0.9.4", + "system-configuration-sys", ] [[package]] -name = "security-framework-sys" -version = "2.8.0" +name = "system-configuration-sys" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31c9bb296072e961fcbd8853511dd39c2d8be2deb1e17c6860b1d30732b323b4" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" dependencies = [ "core-foundation-sys", "libc", ] [[package]] -name = "semver" -version = "1.0.17" +name = "tap" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" [[package]] -name = "serde" -version = "1.0.160" +name = "tdyne-peer-id" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb2f3770c8bce3bcda7e149193a069a0f4365bda1fa5cd88e03bca26afc1216c" -dependencies = [ - "serde_derive", -] +checksum = "6dde285ba6f835045648f9d4f4703f778aaafb47421d9c5dff47be1534370c3e" [[package]] -name = "serde_bencode" -version = "0.2.3" +name = "tdyne-peer-id-registry" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "934d8bdbaa0126dafaea9a8833424a211d9661897717846c6bb782349ca1c30d" +checksum = "1923b2d356e080e8bee847c39b58de293309df2fe0bc9ecd859ae3210e868c25" dependencies = [ - "serde", - "serde_bytes", + "phf", + "phf_codegen", + "tdyne-peer-id", ] [[package]] -name = "serde_bytes" -version = "0.11.9" +name = "tempfile" +version = "3.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "416bda436f9aab92e02c8e10d49a15ddd339cea90b6e340fe51ed97abb548294" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ - "serde", + "fastrand", + "getrandom 0.4.2", + "once_cell", + "rustix", + "windows-sys 0.61.2", ] [[package]] -name = "serde_derive" -version = "1.0.160" +name = "termcolor" +version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291a097c63d8497e00160b166a967a4a79c64f3facdd01cbd7502231688d77df" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.14", + "winapi-util", ] [[package]] -name = "serde_json" -version = "1.0.96" +name = "terminal_size" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "057d394a50403bcac12672b2b18fb387ab6d289d957dab67dd201875391e52f1" +checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" dependencies = [ - "itoa", - "ryu", - "serde", + "rustix", + "windows-sys 0.61.2", ] [[package]] -name = "serde_path_to_error" -version = "0.1.11" +name = "termtree" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" + +[[package]] +name = "testcontainers" +version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7f05c1d5476066defcdfacce1f52fc3cae3af1d3089727100c02ae92e5abbe0" +checksum = "0bd36b06a2a6c0c3c81a83be1ab05fe86460d054d4d51bf513bc56b3e15bdc22" dependencies = [ + "astral-tokio-tar", + "async-trait", + "bollard", + "bytes", + "docker_credential", + "either", + "etcetera", + "ferroid", + "futures", + "http", + "itertools 0.14.0", + "log", + "memchr", + "parse-display", + "pin-project-lite", "serde", + "serde_json", + "serde_with", + "thiserror 2.0.18", + "tokio", + "tokio-stream", + "tokio-util", + "url", ] [[package]] -name = "serde_repr" -version = "0.1.12" +name = "textwrap" +version = "0.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcec881020c684085e55a25f7fd888954d56609ef363479dc5a1305eb0d40cab" +checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.14", + "unicode-linebreak", + "unicode-width 0.2.2", ] [[package]] -name = "serde_spanned" -version = "0.6.1" +name = "thiserror" +version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0efd8caf556a6cebd3b285caf480045fcc1ac04f6bd786b09a6f11af30c4fcf4" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" dependencies = [ - "serde", + "thiserror-impl 1.0.69", ] [[package]] -name = "serde_urlencoded" -version = "0.7.1" +name = "thiserror" +version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", + "thiserror-impl 2.0.18", ] [[package]] -name = "serde_with" -version = "2.3.2" +name = "thiserror-impl" +version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "331bb8c3bf9b92457ab7abecf07078c13f7d270ba490103e84e8b014490cd0b0" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ - "base64 0.13.1", - "chrono", - "hex", - "indexmap", - "serde", - "serde_json", - "serde_with_macros", - "time", + "proc-macro2", + "quote", + "syn 2.0.117", ] [[package]] -name = "serde_with_macros" -version = "2.3.2" +name = "thiserror-impl" +version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "859011bddcc11f289f07f467cc1fe01c7a941daa4d8f6c40d4d1c92eb6d9319c" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" dependencies = [ - "darling", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.117", ] [[package]] -name = "sha1" -version = "0.10.5" +name = "thread_local" +version = "1.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" dependencies = [ "cfg-if", - "cpufeatures", - "digest", ] [[package]] -name = "sha2" -version = "0.10.6" +name = "time" +version = "0.3.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0" +checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" dependencies = [ - "cfg-if", - "cpufeatures", - "digest", + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", ] [[package]] -name = "shlex" -version = "1.1.0" +name = "time-core" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43b2853a4d09f215c24cc5489c992ce46052d359b5109343cbafbf26bc62f8a3" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" [[package]] -name = "signal-hook-registry" -version = "1.4.1" +name = "time-macros" +version = "0.2.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" +checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" dependencies = [ - "libc", + "num-conv", + "time-core", ] [[package]] -name = "simdutf8" -version = "0.1.4" +name = "tinystr" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f27f6278552951f1f2b8cf9da965d10969b2efdea95a6ec47987ab46edfe263a" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] [[package]] -name = "slab" -version = "0.4.8" +name = "tinytemplate" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6528351c9bc8ab22353f9d776db39a20288e8d6c37ef8cfe3317cf875eecfc2d" +checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" dependencies = [ - "autocfg", + "serde", + "serde_json", ] [[package]] -name = "smallvec" -version = "1.10.0" +name = "tinyvec" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +dependencies = [ + "tinyvec_macros", +] [[package]] -name = "socket2" -version = "0.4.9" +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64a4a911eed85daf18834cfaa86a79b7d266ff93ff5ba14005426219480ed662" +checksum = "2bd1c4c0fc4a7ab90fc15ef6daaa3ec3b893f004f915f2392557ed23237820cd" dependencies = [ + "bytes", "libc", - "winapi", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2 0.6.3", + "tokio-macros", + "windows-sys 0.61.2", ] [[package]] -name = "spin" -version = "0.5.2" +name = "tokio-macros" +version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" +checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] [[package]] -name = "static_assertions" -version = "1.1.0" +name = "tokio-rustls" +version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] [[package]] -name = "strsim" -version = "0.10.0" +name = "toml" +version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", + "toml_edit 0.22.27", +] [[package]] -name = "subprocess" -version = "0.2.9" +name = "toml" +version = "0.9.12+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c2e86926081dda636c546d8c5e641661049d7562a68f5488be4a1f7f66f6086" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" dependencies = [ - "libc", - "winapi", + "indexmap 2.13.1", + "serde_core", + "serde_spanned 1.1.1", + "toml_datetime 0.7.5+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 0.7.15", ] [[package]] -name = "syn" -version = "1.0.109" +name = "toml_datetime" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", + "serde", ] [[package]] -name = "syn" -version = "2.0.14" +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcf316d5356ed6847742d036f8a39c3b8435cac10bd528a4bd461928a6ab34d5" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", + "serde_core", ] [[package]] -name = "sync_wrapper" -version = "0.1.2" +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] [[package]] -name = "tap" -version = "1.0.1" +name = "toml_edit" +version = "0.22.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap 2.13.1", + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", + "toml_write", + "winnow 0.7.15", +] [[package]] -name = "tempfile" -version = "3.5.0" +name = "toml_edit" +version = "0.25.10+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9fbec84f381d5795b08656e4912bec604d162bff9291d6189a78f4c8ab87998" +checksum = "a82418ca169e235e6c399a84e395ab6debeb3bc90edc959bf0f48647c6a32d1b" dependencies = [ - "cfg-if", - "fastrand", - "redox_syscall 0.3.5", - "rustix", - "windows-sys 0.45.0", + "indexmap 2.13.1", + "toml_datetime 1.1.1+spec-1.1.0", + "toml_parser", + "winnow 1.0.1", ] [[package]] -name = "termcolor" -version = "1.2.0" +name = "toml_parser" +version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6" +checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" dependencies = [ - "winapi-util", + "winnow 1.0.1", ] [[package]] -name = "termtree" -version = "0.4.1" +name = "toml_write" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" [[package]] -name = "thiserror" -version = "1.0.40" +name = "toml_writer" +version = "1.1.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac" +checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db" + +[[package]] +name = "tonic" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fec7c61a0695dc1887c1b53952990f3ad2e3a31453e1f49f10e75424943a93ec" dependencies = [ - "thiserror-impl", + "async-trait", + "axum", + "base64 0.22.1", + "bytes", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-timeout", + "hyper-util", + "percent-encoding", + "pin-project", + "socket2 0.6.3", + "sync_wrapper", + "tokio", + "tokio-stream", + "tower", + "tower-layer", + "tower-service", + "tracing", ] [[package]] -name = "thiserror-impl" -version = "1.0.40" +name = "tonic-prost" +version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" +checksum = "a55376a0bbaa4975a3f10d009ad763d8f4108f067c7c2e74f3001fb49778d309" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.14", + "bytes", + "prost", + "tonic", ] [[package]] -name = "time" -version = "0.3.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd0cbfecb4d19b5ea75bb31ad904eb5b9fa13f21079c3b92017ebdf4999a5890" +name = "torrust-axum-health-check-api-server" +version = "3.0.0-develop" dependencies = [ - "itoa", + "axum", + "axum-server", + "futures", + "hyper", + "reqwest", "serde", - "time-core", - "time-macros", + "serde_json", + "tokio", + "torrust-axum-health-check-api-server", + "torrust-axum-http-tracker-server", + "torrust-axum-rest-tracker-api-server", + "torrust-axum-server", + "torrust-server-lib", + "torrust-tracker-clock", + "torrust-tracker-configuration", + "torrust-tracker-primitives", + "torrust-tracker-test-helpers", + "torrust-udp-tracker-server", + "tower-http", + "tracing", + "tracing-subscriber", + "url", ] [[package]] -name = "time-core" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd" +name = "torrust-axum-http-tracker-server" +version = "3.0.0-develop" +dependencies = [ + "aquatic_udp_protocol", + "axum", + "axum-client-ip", + "axum-server", + "bittorrent-http-tracker-core", + "bittorrent-http-tracker-protocol", + "bittorrent-primitives", + "bittorrent-tracker-core", + "derive_more", + "futures", + "hyper", + "local-ip-address", + "percent-encoding", + "rand 0.10.0", + "reqwest", + "serde", + "serde_bencode", + "serde_bytes", + "serde_repr", + "tokio", + "tokio-util", + "torrust-axum-server", + "torrust-server-lib", + "torrust-tracker-clock", + "torrust-tracker-configuration", + "torrust-tracker-events", + "torrust-tracker-primitives", + "torrust-tracker-swarm-coordination-registry", + "torrust-tracker-test-helpers", + "tower", + "tower-http", + "tracing", + "uuid", + "zerocopy 0.7.35", +] [[package]] -name = "time-macros" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd80a657e71da814b8e5d60d3374fc6d35045062245d80224748ae522dd76f36" +name = "torrust-axum-rest-tracker-api-server" +version = "3.0.0-develop" dependencies = [ - "time-core", + "aquatic_udp_protocol", + "axum", + "axum-extra", + "axum-server", + "bittorrent-http-tracker-core", + "bittorrent-primitives", + "bittorrent-tracker-core", + "bittorrent-udp-tracker-core", + "derive_more", + "futures", + "hyper", + "local-ip-address", + "mockall", + "reqwest", + "serde", + "serde_json", + "serde_with", + "thiserror 2.0.18", + "tokio", + "torrust-axum-server", + "torrust-rest-tracker-api-client", + "torrust-rest-tracker-api-core", + "torrust-server-lib", + "torrust-tracker-clock", + "torrust-tracker-configuration", + "torrust-tracker-metrics", + "torrust-tracker-primitives", + "torrust-tracker-swarm-coordination-registry", + "torrust-tracker-test-helpers", + "torrust-udp-tracker-server", + "tower", + "tower-http", + "tracing", + "url", + "uuid", ] [[package]] -name = "tinyvec" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" +name = "torrust-axum-server" +version = "3.0.0-develop" dependencies = [ - "tinyvec_macros", + "axum-server", + "camino", + "futures-util", + "http-body", + "hyper", + "hyper-util", + "pin-project-lite", + "thiserror 2.0.18", + "tokio", + "torrust-server-lib", + "torrust-tracker-configuration", + "torrust-tracker-located-error", + "tower", + "tracing", ] [[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +name = "torrust-rest-tracker-api-client" +version = "3.0.0-develop" +dependencies = [ + "hyper", + "reqwest", + "serde", + "thiserror 2.0.18", + "url", + "uuid", +] [[package]] -name = "tokio" -version = "1.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0de47a4eecbe11f498978a9b29d792f0d2692d1dd003650c24c76510e3bc001" +name = "torrust-rest-tracker-api-core" +version = "3.0.0-develop" dependencies = [ - "autocfg", - "bytes", - "libc", - "mio", - "num_cpus", - "pin-project-lite", - "signal-hook-registry", - "socket2", - "tokio-macros", - "windows-sys 0.45.0", + "bittorrent-http-tracker-core", + "bittorrent-tracker-core", + "bittorrent-udp-tracker-core", + "tokio", + "tokio-util", + "torrust-tracker-configuration", + "torrust-tracker-events", + "torrust-tracker-metrics", + "torrust-tracker-primitives", + "torrust-tracker-swarm-coordination-registry", + "torrust-tracker-test-helpers", + "torrust-udp-tracker-server", ] [[package]] -name = "tokio-macros" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61a573bdc87985e9d6ddeed1b3d864e8a302c847e40d647746df2f1de209d1ce" +name = "torrust-server-lib" +version = "3.0.0-develop" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.14", + "derive_more", + "rstest 0.25.0", + "tokio", + "torrust-tracker-primitives", + "tower-http", + "tracing", ] [[package]] -name = "tokio-native-tls" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +name = "torrust-tracker" +version = "3.0.0-develop" dependencies = [ - "native-tls", + "anyhow", + "axum-server", + "bittorrent-http-tracker-core", + "bittorrent-primitives", + "bittorrent-tracker-client", + "bittorrent-tracker-core", + "bittorrent-udp-tracker-core", + "chrono", + "clap", + "local-ip-address", + "mockall", + "rand 0.10.0", + "regex", + "reqwest", + "serde", + "serde_json", + "thiserror 2.0.18", "tokio", + "tokio-util", + "torrust-axum-health-check-api-server", + "torrust-axum-http-tracker-server", + "torrust-axum-rest-tracker-api-server", + "torrust-axum-server", + "torrust-rest-tracker-api-client", + "torrust-rest-tracker-api-core", + "torrust-server-lib", + "torrust-tracker-clock", + "torrust-tracker-configuration", + "torrust-tracker-swarm-coordination-registry", + "torrust-tracker-test-helpers", + "torrust-udp-tracker-server", + "tracing", + "tracing-subscriber", ] [[package]] -name = "tokio-rustls" -version = "0.23.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59" +name = "torrust-tracker-client" +version = "3.0.0-develop" dependencies = [ - "rustls", + "anyhow", + "aquatic_udp_protocol", + "bittorrent-primitives", + "bittorrent-tracker-client", + "clap", + "futures", + "hex-literal", + "hyper", + "reqwest", + "serde", + "serde_bencode", + "serde_bytes", + "serde_json", + "thiserror 2.0.18", "tokio", - "webpki", + "torrust-tracker-configuration", + "tracing", + "tracing-subscriber", + "url", ] [[package]] -name = "tokio-util" -version = "0.7.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5427d89453009325de0d8f342c9490009f76e999cb7672d77e46267448f7e6b2" +name = "torrust-tracker-clock" +version = "3.0.0-develop" dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "pin-project-lite", - "tokio", + "chrono", + "lazy_static", + "torrust-tracker-primitives", "tracing", ] [[package]] -name = "toml" -version = "0.5.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234" +name = "torrust-tracker-configuration" +version = "3.0.0-develop" dependencies = [ + "camino", + "derive_more", + "figment", "serde", + "serde_json", + "serde_with", + "thiserror 2.0.18", + "toml 0.9.12+spec-1.1.0", + "torrust-tracker-located-error", + "tracing", + "tracing-subscriber", + "url", + "uuid", ] [[package]] -name = "toml" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b403acf6f2bb0859c93c7f0d967cb4a75a7ac552100f9322faf64dc047669b21" +name = "torrust-tracker-contrib-bencode" +version = "3.0.0-develop" dependencies = [ - "serde", - "serde_spanned", - "toml_datetime", - "toml_edit", + "criterion 0.8.2", + "thiserror 2.0.18", +] + +[[package]] +name = "torrust-tracker-events" +version = "3.0.0-develop" +dependencies = [ + "futures", + "mockall", + "tokio", +] + +[[package]] +name = "torrust-tracker-located-error" +version = "3.0.0-develop" +dependencies = [ + "thiserror 2.0.18", + "tracing", ] [[package]] -name = "toml_datetime" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ab8ed2edee10b50132aed5f331333428b011c99402b5a534154ed15746f9622" +name = "torrust-tracker-metrics" +version = "3.0.0-develop" dependencies = [ + "approx", + "chrono", + "derive_more", + "formatjson", + "pretty_assertions", + "rstest 0.25.0", "serde", + "serde_json", + "thiserror 2.0.18", + "torrust-tracker-primitives", + "tracing", ] [[package]] -name = "toml_edit" -version = "0.19.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "239410c8609e8125456927e6707163a3b1fdb40561e4b803bc041f466ccfdc13" +name = "torrust-tracker-primitives" +version = "3.0.0-develop" dependencies = [ - "indexmap", + "aquatic_udp_protocol", + "binascii", + "bittorrent-primitives", + "derive_more", + "rstest 0.25.0", "serde", - "serde_spanned", - "toml_datetime", - "winnow", + "tdyne-peer-id", + "tdyne-peer-id-registry", + "thiserror 2.0.18", + "torrust-tracker-configuration", + "url", + "zerocopy 0.7.35", ] [[package]] -name = "torrust-tracker" -version = "3.0.0-alpha.2" +name = "torrust-tracker-swarm-coordination-registry" +version = "3.0.0-develop" dependencies = [ "aquatic_udp_protocol", - "async-trait", - "axum", - "axum-client-ip", - "axum-server", - "binascii", - "bip_bencode", + "async-std", + "bittorrent-primitives", "chrono", - "config", - "derive_more", - "fern", + "criterion 0.8.2", + "crossbeam-skiplist", "futures", - "hyper", - "lazy_static", - "local-ip-address", - "log", "mockall", - "multimap", - "openssl", - "percent-encoding", - "r2d2", - "r2d2_mysql", - "r2d2_sqlite", - "rand", - "reqwest", + "rand 0.10.0", + "rstest 0.26.1", "serde", - "serde_bencode", - "serde_bytes", - "serde_json", - "serde_repr", - "serde_urlencoded", - "serde_with", - "thiserror", + "thiserror 2.0.18", "tokio", + "tokio-util", + "torrust-tracker-clock", "torrust-tracker-configuration", - "torrust-tracker-located-error", + "torrust-tracker-events", + "torrust-tracker-metrics", "torrust-tracker-primitives", "torrust-tracker-test-helpers", - "uuid", + "tracing", ] [[package]] -name = "torrust-tracker-configuration" -version = "3.0.0-alpha.2" +name = "torrust-tracker-test-helpers" +version = "3.0.0-develop" dependencies = [ - "config", - "log", - "serde", - "serde_with", - "thiserror", - "toml 0.7.3", - "torrust-tracker-located-error", - "torrust-tracker-primitives", - "uuid", + "rand 0.10.0", + "torrust-tracker-configuration", + "tracing", + "tracing-subscriber", ] [[package]] -name = "torrust-tracker-located-error" -version = "3.0.0-alpha.2" +name = "torrust-tracker-torrent-repository-benchmarking" +version = "3.0.0-develop" dependencies = [ - "log", - "thiserror", + "aquatic_udp_protocol", + "async-std", + "bittorrent-primitives", + "criterion 0.8.2", + "crossbeam-skiplist", + "dashmap", + "futures", + "parking_lot", + "rstest 0.26.1", + "tokio", + "torrust-tracker-clock", + "torrust-tracker-configuration", + "torrust-tracker-primitives", + "zerocopy 0.7.35", ] [[package]] -name = "torrust-tracker-primitives" -version = "3.0.0-alpha.2" +name = "torrust-udp-tracker-server" +version = "3.0.0-develop" dependencies = [ + "aquatic_udp_protocol", + "bittorrent-primitives", + "bittorrent-tracker-client", + "bittorrent-tracker-core", + "bittorrent-udp-tracker-core", "derive_more", + "futures", + "futures-util", + "local-ip-address", + "mockall", + "rand 0.10.0", + "ringbuf", "serde", + "thiserror 2.0.18", + "tokio", + "tokio-util", + "torrust-server-lib", + "torrust-tracker-clock", + "torrust-tracker-configuration", + "torrust-tracker-events", + "torrust-tracker-metrics", + "torrust-tracker-primitives", + "torrust-tracker-swarm-coordination-registry", + "torrust-tracker-test-helpers", + "tracing", + "url", + "uuid", + "zerocopy 0.7.35", ] [[package]] -name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.2" +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" dependencies = [ - "lazy_static", - "rand", - "torrust-tracker-configuration", - "torrust-tracker-primitives", + "futures-core", + "futures-util", + "indexmap 2.13.1", + "pin-project-lite", + "slab", + "sync_wrapper", + "tokio", + "tokio-util", + "tower-layer", + "tower-service", + "tracing", ] [[package]] -name = "tower" -version = "0.4.13" +name = "tower-http" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" +checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" dependencies = [ + "async-compression", + "bitflags", + "bytes", "futures-core", "futures-util", - "pin-project", + "http", + "http-body", + "iri-string", "pin-project-lite", "tokio", + "tokio-util", + "tower", "tower-layer", "tower-service", "tracing", + "uuid", ] [[package]] name = "tower-layer" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c20c8dbed6283a09604c3e69b4b7eeb54e298b8a600d4d5ecb5ad39de609f1d0" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" [[package]] name = "tower-service" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" [[package]] name = "tracing" -version = "0.1.37" +version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ - "cfg-if", "log", "pin-project-lite", + "tracing-attributes", "tracing-core", ] +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "tracing-core" -version = "0.1.30" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24eb03ba0eab1fd845050058ce5e616558e8f8d8fca633e6b163fe25c797213a" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" dependencies = [ + "log", "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "nu-ansi-term", + "serde", + "serde_json", + "sharded-slab", + "smallvec", + "thread_local", + "tracing-core", + "tracing-log", + "tracing-serde", ] [[package]] name = "try-lock" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "twox-hash" @@ -3010,75 +5867,149 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675" dependencies = [ "cfg-if", - "rand", + "rand 0.8.5", "static_assertions", ] [[package]] name = "typenum" -version = "1.16.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" +checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" [[package]] -name = "ucd-trie" -version = "0.1.5" +name = "uncased" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697" +dependencies = [ + "version_check", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e79c4d996edb816c91e4308506774452e55e95c3c9de07b6729e17e15a5ef81" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] -name = "unicode-bidi" -version = "0.3.13" +name = "unicode-linebreak" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" +checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" [[package]] -name = "unicode-ident" -version = "1.0.8" +name = "unicode-segmentation" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4" +checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c" [[package]] -name = "unicode-normalization" -version = "0.1.22" +name = "unicode-width" +version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" -dependencies = [ - "tinyvec", -] +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" [[package]] name = "unicode-width" -version = "0.1.10" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "unicode-xid" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" [[package]] name = "untrusted" -version = "0.7.1" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dea7109cdcd5864d4eeb1b58a1648dc9bf520360d7af16ec26d0a9354bafcfc0" +dependencies = [ + "base64 0.22.1", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", +] + +[[package]] +name = "ureq-proto" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" +checksum = "e994ba84b0bd1b1b0cf92878b7ef898a5c1760108fe7b6010327e274917a808c" +dependencies = [ + "base64 0.22.1", + "http", + "httparse", + "log", +] [[package]] name = "url" -version = "2.3.1" +version = "2.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d68c799ae75762b8c3fe375feb6600ef5602c883c5d21eb51c09f22b83c4643" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" dependencies = [ "form_urlencoded", "idna", "percent-encoding", + "serde", + "serde_derive", ] +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "uuid" -version = "1.3.1" +version = "1.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b55a3fef2a1e3b3a00ce878640918820d3c51081576ac657d23af9fc7928fdb" +checksum = "5ac8b6f42ead25368cf5b098aeb3dc8a1a2c05a3eee8a9a1a68c640edbfc79d9" dependencies = [ - "getrandom", + "getrandom 0.4.2", + "js-sys", + "rand 0.10.0", + "wasm-bindgen", ] +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "value-bag" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ba6f5989077681266825251a52748b8c1d8a4ad098cc37e440103d0ea717fc0" + [[package]] name = "vcpkg" version = "0.2.15" @@ -3087,68 +6018,82 @@ checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" [[package]] name = "version_check" -version = "0.9.4" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] [[package]] name = "want" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" dependencies = [ - "log", "try-lock", ] [[package]] name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" +version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] -name = "wasm-bindgen" -version = "0.2.84" +name = "wasip2" +version = "1.0.2+wasi-0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31f8dcbc21f30d9b8f2ea926ecb58f6b91192c17e9d33594b3df58b2007ca53b" +checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" dependencies = [ - "cfg-if", - "wasm-bindgen-macro", + "wit-bindgen", ] [[package]] -name = "wasm-bindgen-backend" -version = "0.2.84" +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95ce90fd5bcc06af55a641a86428ee4229e44e07033963a2290a8e241607ccb9" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" dependencies = [ - "bumpalo", - "log", + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0551fc1bb415591e3372d0bc4780db7e587d84e2a7e79da121051c5c4b89d0b0" +dependencies = [ + "cfg-if", "once_cell", - "proc-macro2", - "quote", - "syn 1.0.109", + "rustversion", + "serde", + "wasm-bindgen-macro", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.34" +version = "0.4.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f219e0d211ba40266969f6dbdd90636da12f75bee4fc9d6c23d1260dadb51454" +checksum = "03623de6905b7206edd0a75f69f747f134b7f0a2323392d664448bf2d3c5d87e" dependencies = [ - "cfg-if", "js-sys", "wasm-bindgen", - "web-sys", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.84" +version = "0.2.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c21f77c0bedc37fd5dc21f897894a5ca01e7bb159884559461862ae90c0b4c5" +checksum = "7fbdf9a35adf44786aecd5ff89b4563a90325f9da0923236f6104e603c7e86be" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -3156,41 +6101,87 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.84" +version = "0.2.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2aff81306fcac3c7515ad4e177f521b5c9a15f2b08f4e32d823066102f35a5f6" +checksum = "dca9693ef2bab6d4e6707234500350d8dad079eb508dca05530c85dc3a529ff2" dependencies = [ + "bumpalo", "proc-macro2", "quote", - "syn 1.0.109", - "wasm-bindgen-backend", + "syn 2.0.117", "wasm-bindgen-shared", ] [[package]] -name = "wasm-bindgen-shared" -version = "0.2.84" +name = "wasm-bindgen-shared" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39129a682a6d2d841b6c429d0c51e5cb0ed1a03829d8b3d1e69a011e62cb3d3b" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap 2.13.1", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap 2.13.1", + "semver", +] + +[[package]] +name = "web-sys" +version = "0.3.94" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0046fef7e28c3804e5e38bfa31ea2a0f73905319b677e57ebe37e49358989b5d" +checksum = "cd70027e39b12f0849461e08ffc50b9cd7688d942c1c8e3c7b22273236b4dd0a" +dependencies = [ + "js-sys", + "wasm-bindgen", +] [[package]] -name = "web-sys" -version = "0.3.61" +name = "web-time" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e33b99f4b23ba3eec1a53ac264e35a755f00e966e0065077d6027c0f575b0b97" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" dependencies = [ "js-sys", "wasm-bindgen", ] [[package]] -name = "webpki" -version = "0.22.0" +name = "webpki-root-certs" +version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd" +checksum = "804f18a4ac2676ffb4e8b5b5fa9ae38af06df08162314f96a68d2a363e21a8ca" dependencies = [ - "ring", - "untrusted", + "rustls-pki-types", ] [[package]] @@ -3211,11 +6202,11 @@ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" -version = "0.1.5" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "winapi", + "windows-sys 0.61.2", ] [[package]] @@ -3225,27 +6216,73 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] -name = "windows" -version = "0.48.0" +name = "windows-core" +version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ - "windows-targets 0.48.0", + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", ] [[package]] -name = "windows-sys" -version = "0.42.0" +name = "windows-implement" +version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", ] [[package]] @@ -3259,11 +6296,29 @@ dependencies = [ [[package]] name = "windows-sys" -version = "0.48.0" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "windows-targets 0.48.0", + "windows-link", ] [[package]] @@ -3283,17 +6338,35 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.48.0" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" dependencies = [ - "windows_aarch64_gnullvm 0.48.0", - "windows_aarch64_msvc 0.48.0", - "windows_i686_gnu 0.48.0", - "windows_i686_msvc 0.48.0", - "windows_x86_64_gnu 0.48.0", - "windows_x86_64_gnullvm 0.48.0", - "windows_x86_64_msvc 0.48.0", + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", ] [[package]] @@ -3304,9 +6377,15 @@ checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" [[package]] name = "windows_aarch64_gnullvm" -version = "0.48.0" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" [[package]] name = "windows_aarch64_msvc" @@ -3316,9 +6395,15 @@ checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" [[package]] name = "windows_aarch64_msvc" -version = "0.48.0" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" [[package]] name = "windows_i686_gnu" @@ -3328,9 +6413,27 @@ checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" [[package]] name = "windows_i686_gnu" -version = "0.48.0" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" [[package]] name = "windows_i686_msvc" @@ -3340,9 +6443,15 @@ checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" [[package]] name = "windows_i686_msvc" -version = "0.48.0" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" [[package]] name = "windows_x86_64_gnu" @@ -3352,9 +6461,15 @@ checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" [[package]] name = "windows_x86_64_gnu" -version = "0.48.0" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" [[package]] name = "windows_x86_64_gnullvm" @@ -3364,9 +6479,15 @@ checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" [[package]] name = "windows_x86_64_gnullvm" -version = "0.48.0" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" [[package]] name = "windows_x86_64_msvc" @@ -3376,28 +6497,128 @@ checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" [[package]] name = "windows_x86_64_msvc" -version = "0.48.0" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" [[package]] name = "winnow" -version = "0.4.1" +version = "0.7.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae8970b36c66498d8ff1d66685dc86b91b29db0c7739899012f63a63814b4b28" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" dependencies = [ "memchr", ] [[package]] -name = "winreg" -version = "0.10.1" +name = "winnow" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" +checksum = "09dac053f1cd375980747450bfc7250c264eaae0583872e845c0c7cd578872b5" dependencies = [ - "winapi", + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck", + "indexmap 2.13.1", + "prettyplease", + "syn 2.0.117", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.117", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags", + "indexmap 2.13.1", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap 2.13.1", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", ] +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + [[package]] name = "wyz" version = "0.5.1" @@ -3408,10 +6629,175 @@ dependencies = [ ] [[package]] -name = "yaml-rust" -version = "0.4.5" +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix", +] + +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + +[[package]] +name = "yoke" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" +dependencies = [ + "byteorder", + "zerocopy-derive 0.7.35", +] + +[[package]] +name = "zerocopy" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" +dependencies = [ + "zerocopy-derive 0.8.48", +] + +[[package]] +name = "zerocopy-derive" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "zerofrom" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "zmij" +version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.16+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" dependencies = [ - "linked-hash-map", + "cc", + "pkg-config", ] diff --git a/Cargo.toml b/Cargo.toml index ffe97a8fd..1eb5f0d35 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,74 +1,98 @@ [package] +default-run = "torrust-tracker" name = "torrust-tracker" -description = "A feature rich BitTorrent tracker." -license = "AGPL-3.0" +readme = "README.md" + authors.workspace = true +description.workspace = true +documentation.workspace = true edition.workspace = true +homepage.workspace = true +keywords.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true version.workspace = true +[lib] +name = "torrust_tracker_lib" + [workspace.package] -authors = ["Nautilus Cyberneering , Mick van Dijke "] +authors = [ "Nautilus Cyberneering , Mick van Dijke " ] +categories = [ "network-programming", "web-programming" ] +description = "A feature rich BitTorrent tracker." +documentation = "https://docs.rs/crate/torrust-tracker/" edition = "2021" +homepage = "https://torrust.com/" +keywords = [ "bittorrent", "file-sharing", "peer-to-peer", "torrent", "tracker" ] +license = "AGPL-3.0-only" +publish = true repository = "https://github.com/torrust/torrust-tracker" -version = "3.0.0-alpha.2" +rust-version = "1.72" +version = "3.0.0-develop" [dependencies] -tokio = { version = "1.26", features = ["rt-multi-thread", "net", "sync", "macros", "signal"] } -serde = { version = "1.0", features = ["derive"] } -serde_bencode = "^0.2" -serde_json = "1.0" -serde_with = "2.0" -percent-encoding = "2.2" -binascii = "0.1" -lazy_static = "1.4" -openssl = { version = "0.10", features = ["vendored"] } -config = "0.13" -log = { version = "0.4", features = ["release_max_level_info"] } -fern = "0.6" -chrono = { version = "0.4.24", default-features = false, features = ["clock"] } -r2d2 = "0.8" -r2d2_mysql = "23.0" -r2d2_sqlite = { version = "0.21", features = ["bundled"] } -rand = "0.8" -derive_more = "0.99" -thiserror = "1.0" -futures = "0.3" -async-trait = "0.1" -aquatic_udp_protocol = "0.8" -uuid = { version = "1", features = ["v4"] } -axum = "0.6.16" -axum-server = { version = "0.4", features = ["tls-rustls"] } -axum-client-ip = "0.4" -bip_bencode = "0.4" -torrust-tracker-primitives = { version = "3.0.0-alpha.2", path = "packages/primitives" } -torrust-tracker-configuration = { version = "3.0.0-alpha.2", path = "packages/configuration" } -torrust-tracker-located-error = { version = "3.0.0-alpha.2", path = "packages/located-error" } -multimap = "0.9" -hyper = "0.14" +anyhow = "1" +axum-server = { version = "0", features = [ "tls-rustls-no-provider" ] } +bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "packages/http-tracker-core" } +bittorrent-tracker-core = { version = "3.0.0-develop", path = "packages/tracker-core" } +bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "packages/udp-tracker-core" } +chrono = { version = "0", default-features = false, features = [ "clock" ] } +clap = { version = "4", features = [ "derive", "env" ] } +rand = "0" +regex = "1" +reqwest = { version = "0", features = [ "json" ] } +serde = { version = "1", features = [ "derive" ] } +serde_json = { version = "1", features = [ "preserve_order" ] } +thiserror = "2.0.12" +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } +tokio-util = "0.7.15" +torrust-axum-health-check-api-server = { version = "3.0.0-develop", path = "packages/axum-health-check-api-server" } +torrust-axum-http-tracker-server = { version = "3.0.0-develop", path = "packages/axum-http-tracker-server" } +torrust-axum-rest-tracker-api-server = { version = "3.0.0-develop", path = "packages/axum-rest-tracker-api-server" } +torrust-axum-server = { version = "3.0.0-develop", path = "packages/axum-server" } +torrust-rest-tracker-api-core = { version = "3.0.0-develop", path = "packages/rest-tracker-api-core" } +torrust-server-lib = { version = "3.0.0-develop", path = "packages/server-lib" } +torrust-tracker-clock = { version = "3.0.0-develop", path = "packages/clock" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "packages/configuration" } +torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "packages/swarm-coordination-registry" } +torrust-udp-tracker-server = { version = "3.0.0-develop", path = "packages/udp-tracker-server" } +tracing = "0" +tracing-subscriber = { version = "0", features = [ "json" ] } [dev-dependencies] -mockall = "0.11" -reqwest = { version = "0.11", features = ["json"] } -serde_urlencoded = "0.7" -serde_repr = "0.1" -serde_bytes = "0.11" -local-ip-address = "0.5" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.2", path = "packages/test-helpers" } +bittorrent-primitives = "0.1.0" +bittorrent-tracker-client = { version = "3.0.0-develop", path = "packages/tracker-client" } +local-ip-address = "0" +mockall = "0" +torrust-rest-tracker-api-client = { version = "3.0.0-develop", path = "packages/rest-tracker-api-client" } +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "packages/test-helpers" } [workspace] -members = [ - "packages/configuration", - "packages/primitives", - "packages/test-helpers", - "packages/located-error", -] +members = [ "console/tracker-client", "packages/torrent-repository-benchmarking" ] [profile.dev] debug = 1 +lto = "fat" opt-level = 1 -lto = "thin" [profile.release] debug = 1 -opt-level = 3 lto = "fat" +opt-level = 3 + +[profile.release-debug] +debug = true +inherits = "release" + +[lints.clippy] +complexity = { level = "deny", priority = -1 } +correctness = { level = "deny", priority = -1 } +pedantic = { level = "deny", priority = -1 } +perf = { level = "deny", priority = -1 } +style = { level = "deny", priority = -1 } +suspicious = { level = "deny", priority = -1 } + +# temp allow this lint +needless_return = "allow" diff --git a/Containerfile b/Containerfile new file mode 100644 index 000000000..e926a5202 --- /dev/null +++ b/Containerfile @@ -0,0 +1,145 @@ +# syntax=docker/dockerfile:latest + +# Torrust Tracker + +## Builder Image +FROM docker.io/library/rust:trixie AS chef +WORKDIR /tmp +RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash +RUN cargo binstall --no-confirm cargo-chef cargo-nextest + +## Tester Image +FROM docker.io/library/rust:slim-trixie AS tester +WORKDIR /tmp + +RUN apt-get update; apt-get install -y curl sqlite3; apt-get autoclean +RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash +RUN cargo binstall --no-confirm cargo-nextest + +COPY ./share/ /app/share/torrust +RUN mkdir -p /app/share/torrust/default/database/; \ + sqlite3 /app/share/torrust/default/database/tracker.sqlite3.db "VACUUM;" + +## Su Exe Compile +FROM docker.io/library/gcc:trixie AS gcc +COPY ./contrib/dev-tools/su-exec/ /usr/local/src/su-exec/ +RUN cc -Wall -Werror -g /usr/local/src/su-exec/su-exec.c -o /usr/local/bin/su-exec; chmod +x /usr/local/bin/su-exec + + +## Chef Prepare (look at project and see wat we need) +FROM chef AS recipe +WORKDIR /build/src +COPY . /build/src +RUN cargo chef prepare --recipe-path /build/recipe.json + + +## Cook (debug) +FROM chef AS dependencies_debug +WORKDIR /build/src +COPY --from=recipe /build/recipe.json /build/recipe.json +RUN cargo chef cook --tests --benches --examples --workspace --all-targets --all-features --recipe-path /build/recipe.json +RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/temp.tar.zst ; rm -f /build/temp.tar.zst + +## Cook (release) +FROM chef AS dependencies +WORKDIR /build/src +COPY --from=recipe /build/recipe.json /build/recipe.json +RUN cargo chef cook --tests --benches --examples --workspace --all-targets --all-features --recipe-path /build/recipe.json --release +RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/temp.tar.zst --release ; rm -f /build/temp.tar.zst + + +## Build Archive (debug) +FROM dependencies_debug AS build_debug +WORKDIR /build/src +COPY . /build/src +RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/torrust-tracker-debug.tar.zst + +## Build Archive (release) +FROM dependencies AS build +WORKDIR /build/src +COPY . /build/src +RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/torrust-tracker.tar.zst --release + + +# Extract and Test (debug) +FROM tester AS test_debug +WORKDIR /test +COPY . /test/src/ +COPY --from=build_debug \ + /build/torrust-tracker-debug.tar.zst \ + /test/torrust-tracker-debug.tar.zst +RUN cargo nextest run --workspace-remap /test/src/ --extract-to /test/src/ --no-run --archive-file /test/torrust-tracker-debug.tar.zst +RUN cargo nextest run --workspace-remap /test/src/ --target-dir-remap /test/src/target/ --cargo-metadata /test/src/target/nextest/cargo-metadata.json --binaries-metadata /test/src/target/nextest/binaries-metadata.json + +RUN mkdir -p /app/bin/; cp -l /test/src/target/debug/torrust-tracker /app/bin/torrust-tracker +RUN mkdir /app/lib/; cp -l $(realpath $(ldd /app/bin/torrust-tracker | grep "libz\.so\.1" | awk '{print $3}')) /app/lib/libz.so.1 +RUN chown -R root:root /app; chmod -R u=rw,go=r,a+X /app; chmod -R a+x /app/bin + +# Extract and Test (release) +FROM tester AS test +WORKDIR /test +COPY . /test/src +COPY --from=build \ + /build/torrust-tracker.tar.zst \ + /test/torrust-tracker.tar.zst +RUN cargo nextest run --workspace-remap /test/src/ --extract-to /test/src/ --no-run --archive-file /test/torrust-tracker.tar.zst +RUN cargo nextest run --workspace-remap /test/src/ --target-dir-remap /test/src/target/ --cargo-metadata /test/src/target/nextest/cargo-metadata.json --binaries-metadata /test/src/target/nextest/binaries-metadata.json + +RUN mkdir -p /app/bin/; cp -l /test/src/target/release/torrust-tracker /app/bin/torrust-tracker; cp -l /test/src/target/release/http_health_check /app/bin/http_health_check +RUN mkdir -p /app/lib/; cp -l $(realpath $(ldd /app/bin/torrust-tracker | grep "libz\.so\.1" | awk '{print $3}')) /app/lib/libz.so.1 +RUN chown -R root:root /app; chmod -R u=rw,go=r,a+X /app; chmod -R a+x /app/bin + + +## Runtime +FROM gcr.io/distroless/cc-debian13:debug AS runtime +RUN ["/busybox/cp", "-sp", "/busybox/sh","/busybox/cat","/busybox/ls","/busybox/env", "/bin/"] +COPY --from=gcc --chmod=0555 /usr/local/bin/su-exec /bin/su-exec + +ARG TORRUST_TRACKER_CONFIG_TOML_PATH="/etc/torrust/tracker/tracker.toml" +ARG TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER="sqlite3" +ARG USER_ID=1000 +ARG UDP_PORT=6969 +ARG HTTP_PORT=7070 +ARG API_PORT=1212 +ARG HEALTH_CHECK_API_PORT=1313 + +ENV TORRUST_TRACKER_CONFIG_TOML_PATH=${TORRUST_TRACKER_CONFIG_TOML_PATH} +ENV TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER=${TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER} +ENV USER_ID=${USER_ID} +ENV UDP_PORT=${UDP_PORT} +ENV HTTP_PORT=${HTTP_PORT} +ENV API_PORT=${API_PORT} +ENV HEALTH_CHECK_API_PORT=${HEALTH_CHECK_API_PORT} +ENV TZ=Etc/UTC + +EXPOSE ${UDP_PORT}/udp +EXPOSE ${HTTP_PORT}/tcp +EXPOSE ${API_PORT}/tcp +EXPOSE ${HEALTH_CHECK_API_PORT}/tcp + +RUN mkdir -p /var/lib/torrust/tracker /var/log/torrust/tracker /etc/torrust/tracker + +ENV ENV=/etc/profile +COPY --chmod=0555 ./share/container/entry_script_sh /usr/local/bin/entry.sh + +VOLUME ["/var/lib/torrust/tracker","/var/log/torrust/tracker","/etc/torrust/tracker"] + +ENV RUNTIME="runtime" +ENTRYPOINT ["/usr/local/bin/entry.sh"] + + +## Torrust-Tracker (debug) +FROM runtime AS debug +ENV RUNTIME="debug" +COPY --from=test_debug /app/ /usr/ +RUN env +CMD ["sh"] + +## Torrust-Tracker (release) (default) +FROM runtime AS release +ENV RUNTIME="release" +COPY --from=test /app/ /usr/ +HEALTHCHECK --interval=5s --timeout=5s --start-period=3s --retries=3 \ + CMD /usr/bin/http_health_check http://localhost:${HEALTH_CHECK_API_PORT}/health_check \ + || exit 1 +CMD ["/usr/bin/torrust-tracker"] diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 96d21fa84..000000000 --- a/Dockerfile +++ /dev/null @@ -1,80 +0,0 @@ -FROM clux/muslrust:stable AS chef -WORKDIR /app -RUN cargo install cargo-chef - - -FROM chef AS planner -WORKDIR /app -COPY . . -RUN cargo chef prepare --recipe-path recipe.json - - -FROM chef as development -WORKDIR /app -ARG UID=1000 -ARG RUN_AS_USER=appuser -ARG TRACKER_UDP_PORT=6969 -ARG TRACKER_HTTP_PORT=7070 -ARG TRACKER_API_PORT=1212 -# Add the app user for development -ENV USER=appuser -ENV UID=$UID -RUN adduser --uid "${UID}" "${USER}" -# Build dependencies -COPY --from=planner /app/recipe.json recipe.json -RUN cargo chef cook --recipe-path recipe.json -# Build the application -COPY . . -RUN cargo build --bin torrust-tracker -USER $RUN_AS_USER:$RUN_AS_USER -EXPOSE $TRACKER_UDP_PORT/udp -EXPOSE $TRACKER_HTTP_PORT/tcp -EXPOSE $TRACKER_API_PORT/tcp -CMD ["cargo", "run"] - - -FROM chef AS builder -WORKDIR /app -ARG UID=1000 -# Add the app user for production -ENV USER=appuser -ENV UID=$UID -RUN adduser \ - --disabled-password \ - --gecos "" \ - --home "/nonexistent" \ - --shell "/sbin/nologin" \ - --no-create-home \ - --uid "${UID}" \ - "${USER}" -# Build dependencies -COPY --from=planner /app/recipe.json recipe.json -RUN cargo chef cook --release --target x86_64-unknown-linux-musl --recipe-path recipe.json -# Build the application -COPY . . -RUN cargo build --release --target x86_64-unknown-linux-musl --bin torrust-tracker -# Strip the binary -# More info: https://github.com/LukeMathWalker/cargo-chef/issues/149 -RUN strip /app/target/x86_64-unknown-linux-musl/release/torrust-tracker - - -FROM alpine:latest -WORKDIR /app -ARG RUN_AS_USER=appuser -ARG TRACKER_UDP_PORT=6969 -ARG TRACKER_HTTP_PORT=7070 -ARG TRACKER_API_PORT=1212 -RUN apk --no-cache add ca-certificates -ENV TZ=Etc/UTC -ENV RUN_AS_USER=$RUN_AS_USER -COPY --from=builder /etc/passwd /etc/passwd -COPY --from=builder /etc/group /etc/group -COPY --from=builder --chown=$RUN_AS_USER \ - /app/target/x86_64-unknown-linux-musl/release/torrust-tracker \ - /app/torrust-tracker -RUN chown -R $RUN_AS_USER:$RUN_AS_USER /app -USER $RUN_AS_USER:$RUN_AS_USER -EXPOSE $TRACKER_UDP_PORT/udp -EXPOSE $TRACKER_HTTP_PORT/tcp -EXPOSE $TRACKER_API_PORT/tcp -ENTRYPOINT ["/app/torrust-tracker"] \ No newline at end of file diff --git a/README.md b/README.md index c3d0a127b..2fe28db08 100644 --- a/README.md +++ b/README.md @@ -1,82 +1,286 @@ # Torrust Tracker -[![Build & Release](https://github.com/torrust/torrust-tracker/actions/workflows/build_release.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/build_release.yml) [![CI](https://github.com/torrust/torrust-tracker/actions/workflows/test_build_release.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test_build_release.yml) [![Publish crate](https://github.com/torrust/torrust-tracker/actions/workflows/publish_crate.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/publish_crate.yml) [![Publish docker image](https://github.com/torrust/torrust-tracker/actions/workflows/publish_docker_image.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/publish_docker_image.yml) [![Test](https://github.com/torrust/torrust-tracker/actions/workflows/test.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test.yml) [![Test docker build](https://github.com/torrust/torrust-tracker/actions/workflows/test_docker.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test_docker.yml) [![Upload code coverage](https://github.com/torrust/torrust-tracker/actions/workflows/codecov.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/codecov.yml) +[![container_wf_b]][container_wf] [![coverage_wf_b]][coverage_wf] [![deployment_wf_b]][deployment_wf] [![testing_wf_b]][testing_wf] -Torrust Tracker is a lightweight but incredibly high-performance and feature-rich BitTorrent tracker written in [Rust](https://www.rust-lang.org/). +**Torrust Tracker** is a [BitTorrent][bittorrent] Tracker that matchmakes peers and collects statistics. Written in [Rust Language][rust] with the [Axum] web framework. **This tracker aims to be respectful to established standards, (both [formal][BEP 00] and [otherwise][torrent_source_felid]).** -It aims to provide a reliable and efficient solution for serving torrents to a vast number of peers while maintaining a high level of performance, robustness, extensibility, security, usability and with community-driven development. +> This is a [Torrust][torrust] project and is in active development. It is community supported as well as sponsored by [Nautilus Cyberneering][nautilus]. ## Key Features -* [X] Multiple UDP server and HTTP(S) server blocks for socket binding are possible. -* [X] Full IPv4 and IPv6 support for both UDP and HTTP(S). -* [X] Private & Whitelisted mode. -* [X] Built-in API. -* [X] Torrent whitelisting. -* [X] Peer authentication using time-bound keys. -* [X] [newTrackon](https://newtrackon.com/) check is supported for both HTTP and UDP, where IPv4 and IPv6 are properly handled. -* [X] SQLite3 and MySQL persistence, loading and saving of the torrent hashes and downloads completed count. -* [X] Comprehensive documentation. -* [X] A complete suite of tests. See [code coverage](https://app.codecov.io/gh/torrust/torrust-tracker) report. - -## Implemented BEPs - -* [BEP 3](https://www.bittorrent.org/beps/bep_0003.html): The BitTorrent Protocol. -* [BEP 7](https://www.bittorrent.org/beps/bep_0007.html): IPv6 Support. -* [BEP 15](http://www.bittorrent.org/beps/bep_0015.html): UDP Tracker Protocol for BitTorrent. -* [BEP 23](http://bittorrent.org/beps/bep_0023.html): Tracker Returns Compact Peer Lists. -* [BEP 27](http://bittorrent.org/beps/bep_0027.html): Private Torrents. -* [BEP 48](http://bittorrent.org/beps/bep_0048.html): Tracker Protocol Extension: Scrape. +- [x] High Quality and Modern Rust Codebase. +- [x] [Documentation][docs] Generated from Code Comments. +- [x] [Comprehensive Suit][coverage] of Unit and Functional Tests. +- [x] Good Performance in Busy Conditions. +- [x] Support for `UDP`, `HTTP`, and `TLS` Sockets. +- [x] Native `IPv4` and `IPv6` support. +- [x] Private & Whitelisted mode. +- [x] Tracker Management API. +- [x] Support [newTrackon][newtrackon] checks. +- [x] Persistent `SQLite3` or `MySQL` Databases. + +## Tracker Demo + +Experience the **Torrust Tracker** in action with our comprehensive demo environment! The [Torrust Demo][torrust-demo] repository provides a complete setup showcasing the tracker's capabilities in a real-world scenario. + +The demo takes full advantage of the tracker's powerful metrics system and seamless integration with [Prometheus][prometheus]. This allows you to monitor tracker performance, peer statistics, and system health in real-time. You can build sophisticated Grafana dashboards to visualize all aspects of your tracker's operation. + +![Sample Grafana Dashboard](./docs/media/demo/torrust-tracker-grafana-dashboard.png) + +**Demo Features:** + +- Complete Docker Compose setup. +- Pre-configured Prometheus metrics collection. +- Sample Grafana dashboards for monitoring. +- Real-time tracker statistics and performance metrics. +- Easy deployment for testing and evaluation. + +Visit the [Torrust Demo repository][torrust-demo] to get started with your own tracker instance and explore the monitoring capabilities. + +## Roadmap + +Core: + +- [ ] New option `want_ip_from_query_string`. See . +- [ ] Peer and torrents specific statistics. See . + +Persistence: + +- [ ] Support other databases like PostgreSQL. + +Performance: + +- [ ] More optimizations. See . + +Protocols: + +- [ ] WebTorrent. + +Integrations: + +- [x] Monitoring (Prometheus). + +Utils: + +- [ ] Tracker client. WIP. +- [ ] Tracker checker. WIP. + +Others: + +- [ ] Intensive testing for Windows. +- [ ] Docker images for other architectures. + + + +## Implemented BitTorrent Enhancement Proposals (BEPs) + +> _[Learn more about BitTorrent Enhancement Proposals][BEP 00]_ + +- [BEP 03]: The BitTorrent Protocol. +- [BEP 07]: IPv6 Support. +- [BEP 15]: UDP Tracker Protocol for BitTorrent. +- [BEP 23]: Tracker Returns Compact Peer Lists. +- [BEP 27]: Private Torrents. +- [BEP 48]: Tracker Protocol Extension: Scrape. + +## Architecture + +![Torrust Tracker Layers with main packages](./docs/media/packages/torrust-tracker-layers-with-packages.png) + +There is also extra [documentation about the packages](./docs/packages.md). ## Getting Started -Requirements: +### Container Version + +The Torrust Tracker is [deployed to DockerHub][dockerhub], you can run a demo immediately with the following commands: + +#### Docker + +```sh +docker run -it torrust/tracker:develop +``` + +> Please read our [container guide][containers.md] for more information. + +#### Podman + +```sh +podman run -it docker.io/torrust/tracker:develop +``` + +> Please read our [container guide][containers.md] for more information. + +### Development Version + +- Please ensure you have the \_\*\*[latest stable (or nightly) version of rust][rust]\_\_\_. +- Please ensure that your computer has enough RAM. \_\*\*Recommended 16GB.\_\_\_ + +#### Checkout, Test and Run + +```sh +# Checkout repository into a new folder: +git clone https://github.com/torrust/torrust-tracker.git + +# Change into directory and create an empty database file: +cd torrust-tracker +mkdir -p ./storage/tracker/lib/database/ +touch ./storage/tracker/lib/database/sqlite3.db + +# Check all tests in application: +cargo test --tests --benches --examples --workspace --all-targets --all-features + +# Run the tracker: +cargo run +``` + +#### Customization + +```sh +# Copy the default configuration into the standard location: +mkdir -p ./storage/tracker/etc/ +cp ./share/default/config/tracker.development.sqlite3.toml ./storage/tracker/etc/tracker.toml + +# Customize the tracker configuration (for example): +vim ./storage/tracker/etc/tracker.toml + +# Run the tracker with the updated configuration: +TORRUST_TRACKER_CONFIG_TOML_PATH="./storage/tracker/etc/tracker.toml" cargo run +``` + +_Optionally, you may choose to supply the entire configuration as an environmental variable:_ + +```sh +# Use a configuration supplied on an environmental variable: +TORRUST_TRACKER_CONFIG_TOML=$(cat "./storage/tracker/etc/tracker.toml") cargo run +``` -* Rust Stable `1.68` -* You might have problems compiling with a machine or docker container with low resources. It has been tested with docker containers with 6 CPUs, 7.5 GM of memory and 2GB of swap. +_For deployment, you **should** override the `api_admin_token` by using an environmental variable:_ -You can follow the [documentation](https://docs.rs/torrust-tracker/) to install and use Torrust Tracker in different ways, but if you want to give it a quick try, you can use the following commands: +```sh +# Generate a Secret Token: +gpg --armor --gen-random 1 10 | tee ./storage/tracker/lib/tracker_api_admin_token.secret +chmod go-rwx ./storage/tracker/lib/tracker_api_admin_token.secret -```s -git clone https://github.com/torrust/torrust-tracker.git \ - && cd torrust-tracker \ - && cargo build --release \ - && mkdir -p ./storage/database \ - && mkdir -p ./storage/ssl_certificates +# Override secret in configuration using an environmental variable: +TORRUST_TRACKER_CONFIG_TOML=$(cat "./storage/tracker/etc/tracker.toml") \ + TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN=$(cat "./storage/tracker/lib/tracker_api_admin_token.secret") \ + cargo run ``` -And then run `cargo run` twice. The first time to generate the `config.toml` file and the second time to run the tracker with the default configuration. +> Please view our [crate documentation][docs] for more detailed instructions. -After running the tracker these services will be available: +### Services -* UDP tracker: `udp://127.0.0.1:6969/announce`. -* HTTP tracker: `http://127.0.0.1:6969/announce`. -* API: `http://127.0.0.1:1212/api/v1/stats?token=MyAccessToken`. +The following services are provided by the default configuration: + +- UDP _(tracker)_ + - `udp://127.0.0.1:6969/announce`. +- HTTP _(tracker)_ + - `http://127.0.0.1:7070/announce`. +- API _(management)_ + - `http://127.0.0.1:1212/api/v1/stats?token=MyAccessToken`. ## Documentation -* [Crate documentation](https://docs.rs/torrust-tracker/). -* [API `v1`](https://docs.rs/torrust-tracker/3.0.0-alpha.2/torrust_tracker/servers/apis/v1). -* [HTTP Tracker](https://docs.rs/torrust-tracker/3.0.0-alpha.2/torrust_tracker/servers/http). -* [UDP Tracker](https://docs.rs/torrust-tracker/3.0.0-alpha.2/torrust_tracker/servers/udp). +You can read the [latest documentation][docs] from . + +Some specific sections: + +- [Management API (Version 1)][API] +- [Tracker (HTTP/TLS)][HTTP] +- [Tracker (UDP)][UDP] + +There is also extra documentation in the [docs](./docs) folder. + +## Benchmarking + +- [Benchmarking](./docs/benchmarking.md) ## Contributing -We welcome contributions from the community! +We are happy to support and welcome new people to our project. Please consider our [contributor guide][guide.md].
+This is an open-source community-supported project. We welcome contributions from the community! -How can you contribute? +**How can you contribute?** -* Bug reports and feature requests. -* Code contributions. You can start by looking at the issues labeled ["good first issues"](https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22). -* Documentation improvements. Check the [documentation](https://docs.rs/torrust-tracker/) and [API documentation](https://docs.rs/torrust-tracker/3.0.0-alpha.2/torrust_tracker/servers/apis/v1) for typos, errors, or missing information. -* Participation in the community. You can help by answering questions in the [discussions](https://github.com/torrust/torrust-tracker/discussions). +- Bug reports and feature requests. +- Code contributions. You can start by looking at the issues labeled "[good first issues]". +- Documentation improvements. Check the [documentation][docs] and [API documentation][API] for typos, errors, or missing information. +- Participation in the community. You can help by answering questions in the [discussions]. ## License -The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). +**Copyright (c) 2023 The Torrust Developers.** + +This program is free software: you can redistribute it and/or modify it under the terms of the [GNU Affero General Public License][AGPL_3_0] as published by the [Free Software Foundation][FSF], version 3. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the [GNU Affero General Public License][AGPL_3_0] for more details. + +You should have received a copy of the _GNU Affero General Public License_ along with this program. If not, see . -There is an ongoing discussion about the license of the project. You can follow the discussion [here](https://github.com/torrust/torrust-tracker/pull/251). +Some files include explicit copyright notices and/or license notices. + +### Legacy Exception + +For prosperity, versions of Torrust Tracker that are older than five years are automatically granted the [MIT-0][MIT_0] license in addition to the existing [AGPL-3.0-only][AGPL_3_0] license. + +## Contributor Agreement + +The copyright of the Torrust Tracker is retained by the respective authors. + +**Contributors agree:** + +- That all their contributions be granted a license(s) **compatible** with the [Torrust Trackers License](#license). +- That all contributors signal **clearly** and **explicitly** any other compilable licenses if they are not: _[AGPL-3.0-only with the legacy MIT-0 exception](#license)_. + +**The Torrust-Tracker project has no copyright assignment agreement.** + +_We kindly ask you to take time and consider The Torrust Project [Contributor Agreement][agreement.md] in full._ ## Acknowledgments -This project was a joint effort by [Nautilus Cyberneering GmbH](https://nautilus-cyberneering.de/) and [Dutch Bits](https://dutchbits.nl). Also thanks to [Naim A.](https://github.com/naim94a/udpt) and [greatest-ape](https://github.com/greatest-ape/aquatic) for some parts of the code. Further added features and functions thanks to [Power2All](https://github.com/power2all). +This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [Dutch Bits]. Also thanks to [Naim A.] and [greatest-ape] for some parts of the code. Further added features and functions thanks to [Power2All]. + +[container_wf]: ../../actions/workflows/container.yaml +[container_wf_b]: ../../actions/workflows/container.yaml/badge.svg +[coverage_wf]: ../../actions/workflows/coverage.yaml +[coverage_wf_b]: ../../actions/workflows/coverage.yaml/badge.svg +[deployment_wf]: ../../actions/workflows/deployment.yaml +[deployment_wf_b]: ../../actions/workflows/deployment.yaml/badge.svg +[testing_wf]: ../../actions/workflows/testing.yaml +[testing_wf_b]: ../../actions/workflows/testing.yaml/badge.svg +[bittorrent]: http://bittorrent.org/ +[rust]: https://www.rust-lang.org/ +[axum]: https://github.com/tokio-rs/axum +[newtrackon]: https://newtrackon.com/ +[coverage]: https://app.codecov.io/gh/torrust/torrust-tracker +[torrust]: https://torrust.com/ +[dockerhub]: https://hub.docker.com/r/torrust/tracker/tags +[torrent_source_felid]: https://github.com/qbittorrent/qBittorrent/discussions/19406 +[BEP 00]: https://www.bittorrent.org/beps/bep_0000.html +[BEP 03]: https://www.bittorrent.org/beps/bep_0003.html +[BEP 07]: https://www.bittorrent.org/beps/bep_0007.html +[BEP 15]: https://www.bittorrent.org/beps/bep_0015.html +[BEP 23]: https://www.bittorrent.org/beps/bep_0023.html +[BEP 27]: https://www.bittorrent.org/beps/bep_0027.html +[BEP 48]: https://www.bittorrent.org/beps/bep_0048.html +[containers.md]: ./docs/containers.md +[docs]: https://docs.rs/torrust-tracker/latest/ +[api]: https://docs.rs/torrust-tracker/latest/torrust_tracker/servers/apis/v1 +[http]: https://docs.rs/torrust-tracker/latest/torrust_tracker/servers/http +[udp]: https://docs.rs/torrust-tracker/latest/torrust_tracker/servers/udp +[good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 +[discussions]: https://github.com/torrust/torrust-tracker/discussions +[guide.md]: https://github.com/torrust/.github/blob/main/info/contributing.md +[agreement.md]: https://github.com/torrust/.github/blob/main/info/licensing/contributor_agreement_v01.md +[AGPL_3_0]: ./docs/licenses/LICENSE-AGPL_3_0 +[MIT_0]: ./docs/licenses/LICENSE-MIT_0 +[FSF]: https://www.fsf.org/ +[nautilus]: https://github.com/orgs/Nautilus-Cyberneering/ +[Dutch Bits]: https://dutchbits.nl +[Naim A.]: https://github.com/naim94a/udpt +[greatest-ape]: https://github.com/greatest-ape/aquatic +[Power2All]: https://github.com/power2all +[torrust-demo]: https://github.com/torrust/torrust-demo +[prometheus]: https://prometheus.io/ diff --git a/bin/install.sh b/bin/install.sh deleted file mode 100755 index d4314ce93..000000000 --- a/bin/install.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -# Generate the default settings file if it does not exist -if ! [ -f "./config.toml" ]; then - cp ./config.toml.local ./config.toml -fi - -# Generate the sqlite database if it does not exist -if ! [ -f "./storage/database/data.db" ]; then - # todo: it should get the path from config.toml and only do it when we use sqlite - touch ./storage/database/data.db - echo ";" | sqlite3 ./storage/database/data.db -fi diff --git a/cSpell.json b/cSpell.json index 2fa80b58a..43eb391d3 100644 --- a/cSpell.json +++ b/cSpell.json @@ -1,97 +1,23 @@ { - "words": [ - "appuser", - "Arvid", - "AUTOINCREMENT", - "automock", - "Avicora", - "Azureus", - "bdecode", - "bencode", - "bencoded", - "beps", - "binascii", - "Bitflu", - "bools", - "bufs", - "Buildx", - "byteorder", - "canonicalize", - "canonicalized", - "certbot", - "chrono", - "clippy", - "completei", - "connectionless", - "dockerhub", - "downloadedi", - "filesd", - "Freebox", - "hasher", - "hexlify", - "hlocalhost", - "Hydranode", - "incompletei", - "infohash", - "infohashes", - "infoschema", - "intervali", - "lcov", - "leecher", - "leechers", - "libtorrent", - "Lphant", - "metainfo", - "middlewares", - "mockall", - "multimap", - "myacicontext", - "Naim", - "nanos", - "nextest", - "nocapture", - "Norberg", - "numwant", - "oneshot", - "ostr", - "Pando", - "proot", - "Quickstart", - "Rasterbar", - "reannounce", - "repr", - "reqwest", - "rerequests", - "rngs", - "routable", - "rusqlite", - "rustfmt", - "Rustls", - "Seedable", - "Shareaza", - "sharktorrent", - "socketaddr", - "sqllite", - "subsec", - "Swatinem", - "Swiftbit", - "thiserror", - "Torrentstorm", - "torrust", - "torrustracker", - "trackerid", - "Trackon", - "typenum", - "Unamed", - "untuple", - "uroot", - "Vagaa", - "Vuze", - "whitespaces", - "XBTT", - "Xtorrent", - "Xunlei", - "xxxxxxxxxxxxxxxxxxxxd", - "yyyyyyyyyyyyyyyyyyyyd" + "$schema": "https://raw.githubusercontent.com/streetsidesoftware/cspell/main/cspell.schema.json", + "version": "0.2", + "dictionaryDefinitions": [ + { + "name": "project-words", + "path": "./project-words.txt", + "addWords": true + } + ], + "dictionaries": [ + "project-words" + ], + "enableFiletypes": [ + "dockerfile", + "shellscript", + "toml" + ], + "ignorePaths": [ + "target", + "/project-words.txt" ] -} +} \ No newline at end of file diff --git a/codecov.yaml b/codecov.yaml new file mode 100644 index 000000000..aaa25bf74 --- /dev/null +++ b/codecov.yaml @@ -0,0 +1,10 @@ +coverage: + status: + project: + default: + target: auto + threshold: 0.5% + patch: + default: + target: auto + threshold: 0.5% diff --git a/compose.yaml b/compose.yaml index 49f3055a8..c2e7c63bd 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,12 +1,11 @@ name: torrust services: - tracker: - build: - context: . - target: development - user: ${TORRUST_TRACKER_USER_UID:-1000}:${TORRUST_TRACKER_USER_UID:-1000} + image: torrust-tracker:release tty: true + environment: + - TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER=${TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER:-mysql} + - TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN=${TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN:-MyAccessToken} networks: - server_side ports: @@ -14,19 +13,24 @@ services: - 7070:7070 - 1212:1212 volumes: - - ./:/app - - ~/.cargo:/home/appuser/.cargo + - ./storage/tracker/lib:/var/lib/torrust/tracker:Z + - ./storage/tracker/log:/var/log/torrust/tracker:Z + - ./storage/tracker/etc:/etc/torrust/tracker:Z depends_on: - mysql mysql: image: mysql:8.0 - command: '--default-authentication-plugin=mysql_native_password' + command: "--default-authentication-plugin=mysql_native_password" healthcheck: - test: ['CMD-SHELL', 'mysqladmin ping -h 127.0.0.1 --password="$$(cat /run/secrets/db-password)" --silent'] + test: + [ + "CMD-SHELL", + 'mysqladmin ping -h 127.0.0.1 --password="$$(cat /run/secrets/db-password)" --silent', + ] interval: 3s retries: 5 - start_period: 30s + start_period: 30s environment: - MYSQL_ROOT_HOST=% - MYSQL_ROOT_PASSWORD=root_secret_password @@ -44,4 +48,4 @@ networks: server_side: {} volumes: - mysql_data: {} \ No newline at end of file + mysql_data: {} diff --git a/config.toml.local b/config.toml.local deleted file mode 100644 index baf272d5a..000000000 --- a/config.toml.local +++ /dev/null @@ -1,34 +0,0 @@ -log_level = "info" -mode = "public" -db_driver = "Sqlite3" -db_path = "./storage/database/data.db" -announce_interval = 120 -min_announce_interval = 120 -max_peer_timeout = 900 -on_reverse_proxy = false -external_ip = "0.0.0.0" -tracker_usage_statistics = true -persistent_torrent_completed_stat = false -inactive_peer_cleanup_interval = 600 -remove_peerless_torrents = true - -[[udp_trackers]] -enabled = false -bind_address = "0.0.0.0:6969" - -[[http_trackers]] -enabled = false -bind_address = "0.0.0.0:7070" -ssl_enabled = false -ssl_cert_path = "" -ssl_key_path = "" - -[http_api] -enabled = true -bind_address = "127.0.0.1:1212" -ssl_enabled = false -ssl_cert_path = "" -ssl_key_path = "" - -[http_api.access_tokens] -admin = "MyAccessToken" diff --git a/console/tracker-client/Cargo.toml b/console/tracker-client/Cargo.toml new file mode 100644 index 000000000..8c12227e9 --- /dev/null +++ b/console/tracker-client/Cargo.toml @@ -0,0 +1,39 @@ +[package] +description = "A collection of console clients to make requests to BitTorrent trackers." +keywords = [ "bittorrent", "client", "tracker" ] +license = "LGPL-3.0" +name = "torrust-tracker-client" +readme = "README.md" + +authors.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +anyhow = "1" +aquatic_udp_protocol = "0" +bittorrent-primitives = "0.1.0" +bittorrent-tracker-client = { version = "3.0.0-develop", path = "../../packages/tracker-client" } +clap = { version = "4", features = [ "derive", "env" ] } +futures = "0" +hex-literal = "1" +hyper = "1" +reqwest = { version = "0", features = [ "json" ] } +serde = { version = "1", features = [ "derive" ] } +serde_bencode = "0" +serde_bytes = "0" +serde_json = { version = "1", features = [ "preserve_order" ] } +thiserror = "2" +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../../packages/configuration" } +tracing = "0" +tracing-subscriber = { version = "0", features = [ "json" ] } +url = { version = "2", features = [ "serde" ] } + +[package.metadata.cargo-machete] +ignored = [ "serde_bytes" ] diff --git a/console/tracker-client/README.md b/console/tracker-client/README.md new file mode 100644 index 000000000..87722657f --- /dev/null +++ b/console/tracker-client/README.md @@ -0,0 +1,199 @@ +# Torrust Tracker Client + +A collection of console clients to make requests to BitTorrent trackers. + +> **Disclaimer**: This project is actively under development. We’re currently extracting and refining common functionality from the[Torrust Tracker](https://github.com/torrust/torrust-tracker) to make it available to the BitTorrent community in Rust. While these tools are functional, they are not yet ready for use in production or third-party projects. + +There are currently three console clients available: + +- UDP Client +- HTTP Client +- Tracker Checker + +> **Notice**: [Console apps are planned to be merge into a single tracker client in the short-term](https://github.com/torrust/torrust-tracker/discussions/660). + +## UDP Client + +`Announce` request: + +```text +cargo run --bin udp_tracker_client announce udp://127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +``` + +`Announce` response: + +```json +{ + "AnnounceIpv4": { + "transaction_id": -888840697, + "announce_interval": 120, + "leechers": 0, + "seeders": 1, + "peers": [] + } +} +``` + +`Scrape` request: + +```text +cargo run --bin udp_tracker_client scrape udp://127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +``` + +`Scrape` response: + +```json +{ + "Scrape": { + "transaction_id": -888840697, + "torrent_stats": [ + { + "seeders": 1, + "completed": 0, + "leechers": 0 + } + ] + } +} +``` + +## HTTP Client + +`Announce` request: + +```text +cargo run --bin http_tracker_client announce http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq +``` + +`Announce` response: + +```json +{ + "complete": 1, + "incomplete": 0, + "interval": 120, + "min interval": 120, + "peers": [] +} +``` + +`Scrape` request: + +```text + cargo run --bin http_tracker_client scrape http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq +``` + +`Scrape` response: + +```json +{ + "9c38422213e30bff212b30c360d26f9a02136422": { + "complete": 1, + "downloaded": 1, + "incomplete": 0 + } +} +``` + +## Tracker Checker + +The Tracker Checker is a tool to check the health of a list of trackers. + +```console +TORRUST_CHECKER_CONFIG='{ + "udp_trackers": ["127.0.0.1:6969"], + "http_trackers": ["http://127.0.0.1:7070"], + "health_checks": ["http://127.0.0.1:1212/api/health_check"] + }' cargo run --bin tracker_checker +``` + +Output: + +```json +[ + { + "Udp": { + "Ok": { + "remote_addr": "127.0.0.1:6969", + "results": [ + [ + "Setup", + { + "Ok": null + } + ], + [ + "Connect", + { + "Ok": null + } + ], + [ + "Announce", + { + "Ok": null + } + ], + [ + "Scrape", + { + "Ok": null + } + ] + ] + } + } + }, + { + "Health": { + "Ok": { + "url": "http://127.0.0.1:1212/api/health_check", + "result": { + "Ok": "200 OK" + } + } + } + }, + { + "Http": { + "Ok": { + "url": "http://127.0.0.1:7070/", + "results": [ + [ + "Announce", + { + "Ok": null + } + ], + [ + "Scrape", + { + "Ok": null + } + ] + ] + } + } + } +] +``` + +## License + +**Copyright (c) 2024 The Torrust Developers.** + +This program is free software: you can redistribute it and/or modify it under the terms of the [GNU Lesser General Public License][LGPL_3_0] as published by the [Free Software Foundation][FSF], version 3. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the [GNU Lesser General Public License][LGPL_3_0] for more details. + +You should have received a copy of the *GNU Lesser General Public License* along with this program. If not, see . + +Some files include explicit copyright notices and/or license notices. + +### Legacy Exception + +For prosperity, versions of Torrust BitTorrent Tracker Client that are older than five years are automatically granted the [MIT-0][MIT_0] license in addition to the existing [LGPL-3.0-only][LGPL_3_0] license. + +[LGPL_3_0]: ./LICENSE +[MIT_0]: ./docs/licenses/LICENSE-MIT_0 +[FSF]: https://www.fsf.org/ diff --git a/console/tracker-client/docs/licenses/LICENSE-MIT_0 b/console/tracker-client/docs/licenses/LICENSE-MIT_0 new file mode 100644 index 000000000..fc06cc4fe --- /dev/null +++ b/console/tracker-client/docs/licenses/LICENSE-MIT_0 @@ -0,0 +1,14 @@ +MIT No Attribution + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/console/tracker-client/src/bin/http_tracker_client.rs b/console/tracker-client/src/bin/http_tracker_client.rs new file mode 100644 index 000000000..be1b4821d --- /dev/null +++ b/console/tracker-client/src/bin/http_tracker_client.rs @@ -0,0 +1,7 @@ +//! Program to make request to HTTP trackers. +use torrust_tracker_client::console::clients::http::app; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + app::run().await +} diff --git a/console/tracker-client/src/bin/tracker_checker.rs b/console/tracker-client/src/bin/tracker_checker.rs new file mode 100644 index 000000000..3ff78eec1 --- /dev/null +++ b/console/tracker-client/src/bin/tracker_checker.rs @@ -0,0 +1,7 @@ +//! Program to check running trackers. +use torrust_tracker_client::console::clients::checker::app; + +#[tokio::main] +async fn main() { + app::run().await.expect("Some checks fail"); +} diff --git a/console/tracker-client/src/bin/udp_tracker_client.rs b/console/tracker-client/src/bin/udp_tracker_client.rs new file mode 100644 index 000000000..caf5ab0dc --- /dev/null +++ b/console/tracker-client/src/bin/udp_tracker_client.rs @@ -0,0 +1,7 @@ +//! Program to make request to UDP trackers. +use torrust_tracker_client::console::clients::udp::app; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + app::run().await +} diff --git a/console/tracker-client/src/console/clients/checker/app.rs b/console/tracker-client/src/console/clients/checker/app.rs new file mode 100644 index 000000000..88ce5a8ac --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/app.rs @@ -0,0 +1,120 @@ +//! Program to run checks against running trackers. +//! +//! Run providing a config file path: +//! +//! ```text +//! cargo run --bin tracker_checker -- --config-path "./share/default/config/tracker_checker.json" +//! TORRUST_CHECKER_CONFIG_PATH="./share/default/config/tracker_checker.json" cargo run --bin tracker_checker +//! ``` +//! +//! Run providing the configuration: +//! +//! ```text +//! TORRUST_CHECKER_CONFIG=$(cat "./share/default/config/tracker_checker.json") cargo run --bin tracker_checker +//! ``` +//! +//! Another real example to test the Torrust demo tracker: +//! +//! ```text +//! TORRUST_CHECKER_CONFIG='{ +//! "udp_trackers": ["144.126.245.19:6969"], +//! "http_trackers": ["https://tracker.torrust-demo.com"], +//! "health_checks": ["https://tracker.torrust-demo.com/api/health_check"] +//! }' cargo run --bin tracker_checker +//! ``` +//! +//! The output should be something like the following: +//! +//! ```json +//! { +//! "udp_trackers": [ +//! { +//! "url": "144.126.245.19:6969", +//! "status": { +//! "code": "ok", +//! "message": "" +//! } +//! } +//! ], +//! "http_trackers": [ +//! { +//! "url": "https://tracker.torrust-demo.com/", +//! "status": { +//! "code": "ok", +//! "message": "" +//! } +//! } +//! ], +//! "health_checks": [ +//! { +//! "url": "https://tracker.torrust-demo.com/api/health_check", +//! "status": { +//! "code": "ok", +//! "message": "" +//! } +//! } +//! ] +//! } +//! ``` +use std::path::PathBuf; +use std::sync::Arc; + +use anyhow::{Context, Result}; +use clap::Parser; +use tracing::level_filters::LevelFilter; + +use super::config::Configuration; +use super::console::Console; +use super::service::{CheckResult, Service}; +use crate::console::clients::checker::config::parse_from_json; + +#[derive(Parser, Debug)] +#[clap(author, version, about, long_about = None)] +struct Args { + /// Path to the JSON configuration file. + #[clap(short, long, env = "TORRUST_CHECKER_CONFIG_PATH")] + config_path: Option, + + /// Direct configuration content in JSON. + #[clap(env = "TORRUST_CHECKER_CONFIG", hide_env_values = true)] + config_content: Option, +} + +/// # Errors +/// +/// Will return an error if the configuration was not provided. +pub async fn run() -> Result> { + tracing_stdout_init(LevelFilter::INFO); + + let args = Args::parse(); + + let config = setup_config(args)?; + + let console_printer = Console {}; + + let service = Service { + config: Arc::new(config), + console: console_printer, + }; + + service.run_checks().await.context("it should run the check tasks") +} + +fn tracing_stdout_init(filter: LevelFilter) { + tracing_subscriber::fmt().with_max_level(filter).init(); + tracing::debug!("Logging initialized"); +} + +fn setup_config(args: Args) -> Result { + match (args.config_path, args.config_content) { + (Some(config_path), _) => load_config_from_file(&config_path), + (_, Some(config_content)) => parse_from_json(&config_content).context("invalid config format"), + _ => Err(anyhow::anyhow!("no configuration provided")), + } +} + +fn load_config_from_file(path: &PathBuf) -> Result { + let file_content = std::fs::read_to_string(path).with_context(|| format!("can't read config file {}", path.display()))?; + + parse_from_json(&file_content).context("invalid config format") +} diff --git a/console/tracker-client/src/console/clients/checker/checks/health.rs b/console/tracker-client/src/console/clients/checker/checks/health.rs new file mode 100644 index 000000000..b1fb79148 --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/checks/health.rs @@ -0,0 +1,77 @@ +use std::sync::Arc; +use std::time::Duration; + +use anyhow::Result; +use hyper::StatusCode; +use reqwest::{Client as HttpClient, Response}; +use serde::Serialize; +use thiserror::Error; +use url::Url; + +#[derive(Debug, Clone, Error, Serialize)] +#[serde(into = "String")] +pub enum Error { + #[error("Failed to Build a Http Client: {err:?}")] + ClientBuildingError { err: Arc }, + #[error("Heath check failed to get a response: {err:?}")] + ResponseError { err: Arc }, + #[error("Http check returned a non-success code: \"{code}\" with the response: \"{response:?}\"")] + UnsuccessfulResponse { code: StatusCode, response: Arc }, +} + +impl From for String { + fn from(value: Error) -> Self { + value.to_string() + } +} + +#[derive(Debug, Clone, Serialize)] +pub struct Checks { + url: Url, + result: Result, +} + +pub async fn run(health_checks: Vec, timeout: Duration) -> Vec> { + let mut results = Vec::default(); + + tracing::debug!("Health checks ..."); + + for url in health_checks { + let result = match run_health_check(url.clone(), timeout).await { + Ok(response) => Ok(response.status().to_string()), + Err(err) => Err(err), + }; + + let check = Checks { url, result }; + + if check.result.is_err() { + results.push(Err(check)); + } else { + results.push(Ok(check)); + } + } + + results +} + +async fn run_health_check(url: Url, timeout: Duration) -> Result { + let client = HttpClient::builder() + .timeout(timeout) + .build() + .map_err(|e| Error::ClientBuildingError { err: e.into() })?; + + let response = client + .get(url.clone()) + .send() + .await + .map_err(|e| Error::ResponseError { err: e.into() })?; + + if response.status().is_success() { + Ok(response) + } else { + Err(Error::UnsuccessfulResponse { + code: response.status(), + response: response.into(), + }) + } +} diff --git a/console/tracker-client/src/console/clients/checker/checks/http.rs b/console/tracker-client/src/console/clients/checker/checks/http.rs new file mode 100644 index 000000000..1a69d9c22 --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/checks/http.rs @@ -0,0 +1,104 @@ +use std::str::FromStr as _; +use std::time::Duration; + +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_client::http::client::responses::announce::Announce; +use bittorrent_tracker_client::http::client::responses::scrape; +use bittorrent_tracker_client::http::client::{requests, Client}; +use serde::Serialize; +use url::Url; + +use crate::console::clients::http::Error; + +#[derive(Debug, Clone, Serialize)] +pub struct Checks { + url: Url, + results: Vec<(Check, Result<(), Error>)>, +} + +#[derive(Debug, Clone, Serialize)] +pub enum Check { + Announce, + Scrape, +} + +pub async fn run(http_trackers: Vec, timeout: Duration) -> Vec> { + let mut results = Vec::default(); + + tracing::debug!("HTTP trackers ..."); + + for ref url in http_trackers { + let mut base_url = url.clone(); + base_url.set_path(""); + + let mut checks = Checks { + url: url.clone(), + results: Vec::default(), + }; + + // Announce + { + let check = check_http_announce(&base_url, timeout).await.map(|_| ()); + + checks.results.push((Check::Announce, check)); + } + + // Scrape + { + let check = check_http_scrape(&base_url, timeout).await.map(|_| ()); + + checks.results.push((Check::Scrape, check)); + } + + if checks.results.iter().any(|f| f.1.is_err()) { + results.push(Err(checks)); + } else { + results.push(Ok(checks)); + } + } + + results +} + +async fn check_http_announce(url: &Url, timeout: Duration) -> Result { + let info_hash_str = "9c38422213e30bff212b30c360d26f9a02136422".to_string(); // DevSkim: ignore DS173237 + let info_hash = InfoHash::from_str(&info_hash_str).expect("a valid info-hash is required"); + + let client = Client::new(url.clone(), timeout).map_err(|err| Error::HttpClientError { err })?; + + let response = client + .announce( + &requests::announce::QueryBuilder::with_default_values() + .with_info_hash(&info_hash) + .query(), + ) + .await + .map_err(|err| Error::HttpClientError { err })?; + + let response = response.bytes().await.map_err(|e| Error::ResponseError { err: e.into() })?; + + let response = serde_bencode::from_bytes::(&response).map_err(|e| Error::ParseBencodeError { + data: response, + err: e.into(), + })?; + + Ok(response) +} + +async fn check_http_scrape(url: &Url, timeout: Duration) -> Result { + let info_hashes: Vec = vec!["9c38422213e30bff212b30c360d26f9a02136422".to_string()]; // DevSkim: ignore DS173237 + let query = requests::scrape::Query::try_from(info_hashes).expect("a valid array of info-hashes is required"); + + let client = Client::new(url.clone(), timeout).map_err(|err| Error::HttpClientError { err })?; + + let response = client.scrape(&query).await.map_err(|err| Error::HttpClientError { err })?; + + let response = response.bytes().await.map_err(|e| Error::ResponseError { err: e.into() })?; + + let response = scrape::Response::try_from_bencoded(&response).map_err(|e| Error::BencodeParseError { + data: response, + err: e.into(), + })?; + + Ok(response) +} diff --git a/console/tracker-client/src/console/clients/checker/checks/mod.rs b/console/tracker-client/src/console/clients/checker/checks/mod.rs new file mode 100644 index 000000000..f8b03f749 --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/checks/mod.rs @@ -0,0 +1,4 @@ +pub mod health; +pub mod http; +pub mod structs; +pub mod udp; diff --git a/console/tracker-client/src/console/clients/checker/checks/structs.rs b/console/tracker-client/src/console/clients/checker/checks/structs.rs new file mode 100644 index 000000000..d28e20c04 --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/checks/structs.rs @@ -0,0 +1,12 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +pub struct Status { + pub code: String, + pub message: String, +} +#[derive(Serialize, Deserialize)] +pub struct CheckerOutput { + pub url: String, + pub status: Status, +} diff --git a/console/tracker-client/src/console/clients/checker/checks/udp.rs b/console/tracker-client/src/console/clients/checker/checks/udp.rs new file mode 100644 index 000000000..611afafc4 --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/checks/udp.rs @@ -0,0 +1,135 @@ +use std::net::SocketAddr; +use std::time::Duration; + +use aquatic_udp_protocol::TransactionId; +use hex_literal::hex; +use serde::Serialize; +use url::Url; + +use crate::console::clients::udp::checker::Client; +use crate::console::clients::udp::Error; + +#[derive(Debug, Clone, Serialize)] +pub struct Checks { + remote_addr: SocketAddr, + results: Vec<(Check, Result<(), Error>)>, +} + +#[derive(Debug, Clone, Serialize)] +pub enum Check { + Setup, + Connect, + Announce, + Scrape, +} + +#[allow(clippy::missing_panics_doc)] +pub async fn run(udp_trackers: Vec, timeout: Duration) -> Vec> { + let mut results = Vec::default(); + + tracing::debug!("UDP trackers ..."); + + #[allow(clippy::incompatible_msrv)] + let info_hash = aquatic_udp_protocol::InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422")); // DevSkim: ignore DS173237 + + for remote_url in udp_trackers { + let remote_addr = resolve_socket_addr(&remote_url); + + let mut checks = Checks { + remote_addr, + results: Vec::default(), + }; + + tracing::debug!("UDP tracker: {:?}", remote_url); + + // Setup + let client = match Client::new(remote_addr, timeout).await { + Ok(client) => { + checks.results.push((Check::Setup, Ok(()))); + client + } + Err(err) => { + checks.results.push((Check::Setup, Err(err))); + results.push(Err(checks)); + continue; + } + }; + + let transaction_id = TransactionId::new(1); + + // Connect Remote + let connection_id = match client.send_connection_request(transaction_id).await { + Ok(connection_id) => { + checks.results.push((Check::Connect, Ok(()))); + connection_id + } + Err(err) => { + checks.results.push((Check::Connect, Err(err))); + results.push(Err(checks)); + continue; + } + }; + + // Announce + { + let check = client + .send_announce_request(transaction_id, connection_id, info_hash.into()) + .await + .map(|_| ()); + + checks.results.push((Check::Announce, check)); + } + + // Scrape + { + let check = client + .send_scrape_request(connection_id, transaction_id, &[info_hash.into()]) + .await + .map(|_| ()); + + checks.results.push((Check::Scrape, check)); + } + + if checks.results.iter().any(|f| f.1.is_err()) { + results.push(Err(checks)); + } else { + results.push(Ok(checks)); + } + } + + results +} + +fn resolve_socket_addr(url: &Url) -> SocketAddr { + let socket_addr = url.socket_addrs(|| None).unwrap(); + *socket_addr.first().unwrap() +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + + use url::Url; + + use crate::console::clients::checker::checks::udp::resolve_socket_addr; + + #[test] + fn it_should_resolve_the_socket_address_for_udp_scheme_urls_containing_a_domain() { + let socket_addr = resolve_socket_addr(&Url::parse("udp://localhost:8080").unwrap()); + + assert!( + socket_addr == SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080) + || socket_addr == SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 8080) + ); + } + + #[test] + fn it_should_resolve_the_socket_address_for_udp_scheme_urls_containing_an_ip() { + let socket_addr = resolve_socket_addr(&Url::parse("udp://localhost:8080").unwrap()); + + assert!( + socket_addr == SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080) + || socket_addr == SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 8080) + ); + } +} diff --git a/console/tracker-client/src/console/clients/checker/config.rs b/console/tracker-client/src/console/clients/checker/config.rs new file mode 100644 index 000000000..154dcae85 --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/config.rs @@ -0,0 +1,282 @@ +use std::error::Error; +use std::fmt; + +use reqwest::Url as ServiceUrl; +use serde::Deserialize; + +/// It parses the configuration from a JSON format. +/// +/// # Errors +/// +/// Will return an error if the configuration is not valid. +/// +/// # Panics +/// +/// Will panic if unable to read the configuration file. +pub fn parse_from_json(json: &str) -> Result { + let plain_config: PlainConfiguration = serde_json::from_str(json).map_err(ConfigurationError::JsonParseError)?; + Configuration::try_from(plain_config) +} + +/// DTO for the configuration to serialize/deserialize configuration. +/// +/// Configuration does not need to be valid. +#[derive(Deserialize)] +struct PlainConfiguration { + pub udp_trackers: Vec, + pub http_trackers: Vec, + pub health_checks: Vec, +} + +/// Validated configuration +pub struct Configuration { + pub udp_trackers: Vec, + pub http_trackers: Vec, + pub health_checks: Vec, +} + +#[derive(Debug)] +pub enum ConfigurationError { + JsonParseError(serde_json::Error), + InvalidUdpAddress(std::net::AddrParseError), + InvalidUrl(url::ParseError), +} + +impl Error for ConfigurationError {} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ConfigurationError::JsonParseError(e) => write!(f, "JSON parse error: {e}"), + ConfigurationError::InvalidUdpAddress(e) => write!(f, "Invalid UDP address: {e}"), + ConfigurationError::InvalidUrl(e) => write!(f, "Invalid URL: {e}"), + } + } +} + +impl TryFrom for Configuration { + type Error = ConfigurationError; + + fn try_from(plain_config: PlainConfiguration) -> Result { + let udp_trackers = plain_config + .udp_trackers + .into_iter() + .map(|s| if s.starts_with("udp://") { s } else { format!("udp://{s}") }) + .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) + .collect::, _>>()?; + + let http_trackers = plain_config + .http_trackers + .into_iter() + .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) + .collect::, _>>()?; + + let health_checks = plain_config + .health_checks + .into_iter() + .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) + .collect::, _>>()?; + + Ok(Configuration { + udp_trackers, + http_trackers, + health_checks, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn configuration_should_be_build_from_plain_serializable_configuration() { + let dto = PlainConfiguration { + udp_trackers: vec!["udp://127.0.0.1:8080".to_string()], + http_trackers: vec!["http://127.0.0.1:8080".to_string()], + health_checks: vec!["http://127.0.0.1:8080/health".to_string()], + }; + + let config = Configuration::try_from(dto).expect("A valid configuration"); + + assert_eq!(config.udp_trackers, vec![ServiceUrl::parse("udp://127.0.0.1:8080").unwrap()]); + + assert_eq!( + config.http_trackers, + vec![ServiceUrl::parse("http://127.0.0.1:8080").unwrap()] + ); + + assert_eq!( + config.health_checks, + vec![ServiceUrl::parse("http://127.0.0.1:8080/health").unwrap()] + ); + } + + mod building_configuration_from_plain_configuration_for { + + mod udp_trackers { + use crate::console::clients::checker::config::{Configuration, PlainConfiguration, ServiceUrl}; + + /* The plain configuration should allow UDP URLs with: + + - IP or domain. + - With or without scheme. + - With or without `announce` suffix. + - With or without `/` at the end of the authority section (with empty path). + + For example: + + 127.0.0.1:6969 + 127.0.0.1:6969/ + 127.0.0.1:6969/announce + + localhost:6969 + localhost:6969/ + localhost:6969/announce + + udp://127.0.0.1:6969 + udp://127.0.0.1:6969/ + udp://127.0.0.1:6969/announce + + udp://localhost:6969 + udp://localhost:6969/ + udp://localhost:6969/announce + + */ + + #[test] + fn it_should_fail_when_a_tracker_udp_url_is_invalid() { + let plain_config = PlainConfiguration { + udp_trackers: vec!["invalid URL".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + assert!(Configuration::try_from(plain_config).is_err()); + } + + #[test] + fn it_should_add_the_udp_scheme_to_the_udp_url_when_it_is_missing() { + let plain_config = PlainConfiguration { + udp_trackers: vec!["127.0.0.1:6969".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!(config.udp_trackers[0], "udp://127.0.0.1:6969".parse::().unwrap()); + } + + #[test] + fn it_should_allow_using_domains() { + let plain_config = PlainConfiguration { + udp_trackers: vec!["udp://localhost:6969".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!(config.udp_trackers[0], "udp://localhost:6969".parse::().unwrap()); + } + + #[test] + fn it_should_allow_the_url_to_have_an_empty_path() { + let plain_config = PlainConfiguration { + udp_trackers: vec!["127.0.0.1:6969/".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!(config.udp_trackers[0], "udp://127.0.0.1:6969/".parse::().unwrap()); + } + + #[test] + fn it_should_allow_the_url_to_contain_a_path() { + // This is the common format for UDP tracker URLs: + // udp://domain.com:6969/announce + + let plain_config = PlainConfiguration { + udp_trackers: vec!["127.0.0.1:6969/announce".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!( + config.udp_trackers[0], + "udp://127.0.0.1:6969/announce".parse::().unwrap() + ); + } + } + + mod http_trackers { + use crate::console::clients::checker::config::{Configuration, PlainConfiguration, ServiceUrl}; + + #[test] + fn it_should_fail_when_a_tracker_http_url_is_invalid() { + let plain_config = PlainConfiguration { + udp_trackers: vec![], + http_trackers: vec!["invalid URL".to_string()], + health_checks: vec![], + }; + + assert!(Configuration::try_from(plain_config).is_err()); + } + + #[test] + fn it_should_allow_the_url_to_contain_a_path() { + // This is the common format for HTTP tracker URLs: + // http://domain.com:7070/announce + + let plain_config = PlainConfiguration { + udp_trackers: vec![], + http_trackers: vec!["http://127.0.0.1:7070/announce".to_string()], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!( + config.http_trackers[0], + "http://127.0.0.1:7070/announce".parse::().unwrap() + ); + } + + #[test] + fn it_should_allow_the_url_to_contain_an_empty_path() { + let plain_config = PlainConfiguration { + udp_trackers: vec![], + http_trackers: vec!["http://127.0.0.1:7070/".to_string()], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!( + config.http_trackers[0], + "http://127.0.0.1:7070/".parse::().unwrap() + ); + } + } + + mod health_checks { + use crate::console::clients::checker::config::{Configuration, PlainConfiguration}; + + #[test] + fn it_should_fail_when_a_health_check_http_url_is_invalid() { + let plain_config = PlainConfiguration { + udp_trackers: vec![], + http_trackers: vec![], + health_checks: vec!["invalid URL".to_string()], + }; + + assert!(Configuration::try_from(plain_config).is_err()); + } + } + } +} diff --git a/console/tracker-client/src/console/clients/checker/console.rs b/console/tracker-client/src/console/clients/checker/console.rs new file mode 100644 index 000000000..b55c559fc --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/console.rs @@ -0,0 +1,38 @@ +use super::printer::{Printer, CLEAR_SCREEN}; + +pub struct Console {} + +impl Default for Console { + fn default() -> Self { + Self::new() + } +} + +impl Console { + #[must_use] + pub fn new() -> Self { + Self {} + } +} + +impl Printer for Console { + fn clear(&self) { + self.print(CLEAR_SCREEN); + } + + fn print(&self, output: &str) { + print!("{}", &output); + } + + fn eprint(&self, output: &str) { + eprint!("{}", &output); + } + + fn println(&self, output: &str) { + println!("{}", &output); + } + + fn eprintln(&self, output: &str) { + eprintln!("{}", &output); + } +} diff --git a/console/tracker-client/src/console/clients/checker/logger.rs b/console/tracker-client/src/console/clients/checker/logger.rs new file mode 100644 index 000000000..50e97189f --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/logger.rs @@ -0,0 +1,72 @@ +use std::cell::RefCell; + +use super::printer::{Printer, CLEAR_SCREEN}; + +pub struct Logger { + output: RefCell, +} + +impl Default for Logger { + fn default() -> Self { + Self::new() + } +} + +impl Logger { + #[must_use] + pub fn new() -> Self { + Self { + output: RefCell::new(String::new()), + } + } + + pub fn log(&self) -> String { + self.output.borrow().clone() + } +} + +impl Printer for Logger { + fn clear(&self) { + self.print(CLEAR_SCREEN); + } + + fn print(&self, output: &str) { + *self.output.borrow_mut() = format!("{}{}", self.output.borrow(), &output); + } + + fn eprint(&self, output: &str) { + *self.output.borrow_mut() = format!("{}{}", self.output.borrow(), &output); + } + + fn println(&self, output: &str) { + self.print(&format!("{}/n", &output)); + } + + fn eprintln(&self, output: &str) { + self.eprint(&format!("{}/n", &output)); + } +} + +#[cfg(test)] +mod tests { + use crate::console::clients::checker::logger::Logger; + use crate::console::clients::checker::printer::{Printer, CLEAR_SCREEN}; + + #[test] + fn should_capture_the_clear_screen_command() { + let console_logger = Logger::new(); + + console_logger.clear(); + + assert_eq!(CLEAR_SCREEN, console_logger.log()); + } + + #[test] + fn should_capture_the_print_command_output() { + let console_logger = Logger::new(); + + console_logger.print("OUTPUT"); + + assert_eq!("OUTPUT", console_logger.log()); + } +} diff --git a/console/tracker-client/src/console/clients/checker/mod.rs b/console/tracker-client/src/console/clients/checker/mod.rs new file mode 100644 index 000000000..d26a4a686 --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/mod.rs @@ -0,0 +1,7 @@ +pub mod app; +pub mod checks; +pub mod config; +pub mod console; +pub mod logger; +pub mod printer; +pub mod service; diff --git a/console/tracker-client/src/console/clients/checker/printer.rs b/console/tracker-client/src/console/clients/checker/printer.rs new file mode 100644 index 000000000..d590dfedb --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/printer.rs @@ -0,0 +1,9 @@ +pub const CLEAR_SCREEN: &str = "\x1B[2J\x1B[1;1H"; + +pub trait Printer { + fn clear(&self); + fn print(&self, output: &str); + fn eprint(&self, output: &str); + fn println(&self, output: &str); + fn eprintln(&self, output: &str); +} diff --git a/console/tracker-client/src/console/clients/checker/service.rs b/console/tracker-client/src/console/clients/checker/service.rs new file mode 100644 index 000000000..acd312d8c --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/service.rs @@ -0,0 +1,62 @@ +use std::sync::Arc; + +use futures::FutureExt as _; +use serde::Serialize; +use tokio::task::{JoinError, JoinSet}; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; + +use super::checks::{health, http, udp}; +use super::config::Configuration; +use super::console::Console; +use crate::console::clients::checker::printer::Printer; + +pub struct Service { + pub(crate) config: Arc, + pub(crate) console: Console, +} + +#[derive(Debug, Clone, Serialize)] +pub enum CheckResult { + Udp(Result), + Http(Result), + Health(Result), +} + +impl Service { + /// # Errors + /// + /// It will return an error if some of the tests panic or otherwise fail to run. + /// On success it will return a vector of `Ok(())` of [`CheckResult`]. + /// + /// # Panics + /// + /// It would panic if `serde_json` produces invalid json for the `to_string_pretty` function. + pub async fn run_checks(self) -> Result, JoinError> { + tracing::info!("Running checks for trackers ..."); + + let mut check_results = Vec::default(); + + let mut checks = JoinSet::new(); + checks.spawn( + udp::run(self.config.udp_trackers.clone(), DEFAULT_TIMEOUT).map(|mut f| f.drain(..).map(CheckResult::Udp).collect()), + ); + checks.spawn( + http::run(self.config.http_trackers.clone(), DEFAULT_TIMEOUT) + .map(|mut f| f.drain(..).map(CheckResult::Http).collect()), + ); + checks.spawn( + health::run(self.config.health_checks.clone(), DEFAULT_TIMEOUT) + .map(|mut f| f.drain(..).map(CheckResult::Health).collect()), + ); + + while let Some(results) = checks.join_next().await { + check_results.append(&mut results?); + } + + let json_output = serde_json::json!(check_results); + self.console + .println(&serde_json::to_string_pretty(&json_output).expect("it should consume valid json")); + + Ok(check_results) + } +} diff --git a/console/tracker-client/src/console/clients/http/app.rs b/console/tracker-client/src/console/clients/http/app.rs new file mode 100644 index 000000000..105b18bff --- /dev/null +++ b/console/tracker-client/src/console/clients/http/app.rs @@ -0,0 +1,101 @@ +//! HTTP Tracker client: +//! +//! Examples: +//! +//! `Announce` request: +//! +//! ```text +//! cargo run --bin http_tracker_client announce http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! `Scrape` request: +//! +//! ```text +//! cargo run --bin http_tracker_client scrape http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +use std::str::FromStr; +use std::time::Duration; + +use anyhow::Context; +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_client::http::client::requests::announce::QueryBuilder; +use bittorrent_tracker_client::http::client::responses::announce::Announce; +use bittorrent_tracker_client::http::client::responses::scrape; +use bittorrent_tracker_client::http::client::{requests, Client}; +use clap::{Parser, Subcommand}; +use reqwest::Url; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; + +#[derive(Parser, Debug)] +#[command(author, version, about, long_about = None)] +struct Args { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand, Debug)] +enum Command { + Announce { tracker_url: String, info_hash: String }, + Scrape { tracker_url: String, info_hashes: Vec }, +} + +/// # Errors +/// +/// Will return an error if the command fails. +pub async fn run() -> anyhow::Result<()> { + let args = Args::parse(); + + match args.command { + Command::Announce { tracker_url, info_hash } => { + announce_command(tracker_url, info_hash, DEFAULT_TIMEOUT).await?; + } + Command::Scrape { + tracker_url, + info_hashes, + } => { + scrape_command(&tracker_url, &info_hashes, DEFAULT_TIMEOUT).await?; + } + } + + Ok(()) +} + +async fn announce_command(tracker_url: String, info_hash: String, timeout: Duration) -> anyhow::Result<()> { + let base_url = Url::parse(&tracker_url).context("failed to parse HTTP tracker base URL")?; + let info_hash = + InfoHash::from_str(&info_hash).expect("Invalid infohash. Example infohash: `9c38422213e30bff212b30c360d26f9a02136422`"); + + let response = Client::new(base_url, timeout)? + .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) + .await?; + + let body = response.bytes().await?; + + let announce_response: Announce = serde_bencode::from_bytes(&body) + .unwrap_or_else(|_| panic!("response body should be a valid announce response, got: \"{:#?}\"", &body)); + + let json = serde_json::to_string(&announce_response).context("failed to serialize scrape response into JSON")?; + + println!("{json}"); + + Ok(()) +} + +async fn scrape_command(tracker_url: &str, info_hashes: &[String], timeout: Duration) -> anyhow::Result<()> { + let base_url = Url::parse(tracker_url).context("failed to parse HTTP tracker base URL")?; + + let query = requests::scrape::Query::try_from(info_hashes).context("failed to parse infohashes")?; + + let response = Client::new(base_url, timeout)?.scrape(&query).await?; + + let body = response.bytes().await?; + + let scrape_response = scrape::Response::try_from_bencoded(&body) + .unwrap_or_else(|_| panic!("response body should be a valid scrape response, got: \"{:#?}\"", &body)); + + let json = serde_json::to_string(&scrape_response).context("failed to serialize scrape response into JSON")?; + + println!("{json}"); + + Ok(()) +} diff --git a/console/tracker-client/src/console/clients/http/mod.rs b/console/tracker-client/src/console/clients/http/mod.rs new file mode 100644 index 000000000..917c94fa8 --- /dev/null +++ b/console/tracker-client/src/console/clients/http/mod.rs @@ -0,0 +1,35 @@ +use std::sync::Arc; + +use bittorrent_tracker_client::http::client::responses::scrape::BencodeParseError; +use serde::Serialize; +use thiserror::Error; + +pub mod app; + +#[derive(Debug, Clone, Error, Serialize)] +#[serde(into = "String")] +pub enum Error { + #[error("Http request did not receive a response within the timeout: {err:?}")] + HttpClientError { + err: bittorrent_tracker_client::http::client::Error, + }, + #[error("Http failed to get a response at all: {err:?}")] + ResponseError { err: Arc }, + #[error("Failed to deserialize the bencoded response data with the error: \"{err:?}\"")] + ParseBencodeError { + data: hyper::body::Bytes, + err: Arc, + }, + + #[error("Failed to deserialize the bencoded response data with the error: \"{err:?}\"")] + BencodeParseError { + data: hyper::body::Bytes, + err: Arc, + }, +} + +impl From for String { + fn from(value: Error) -> Self { + value.to_string() + } +} diff --git a/console/tracker-client/src/console/clients/mod.rs b/console/tracker-client/src/console/clients/mod.rs new file mode 100644 index 000000000..8492f8ba5 --- /dev/null +++ b/console/tracker-client/src/console/clients/mod.rs @@ -0,0 +1,4 @@ +//! Console clients. +pub mod checker; +pub mod http; +pub mod udp; diff --git a/console/tracker-client/src/console/clients/udp/app.rs b/console/tracker-client/src/console/clients/udp/app.rs new file mode 100644 index 000000000..527f46e78 --- /dev/null +++ b/console/tracker-client/src/console/clients/udp/app.rs @@ -0,0 +1,207 @@ +//! UDP Tracker client: +//! +//! Examples: +//! +//! Announce request: +//! +//! ```text +//! cargo run --bin udp_tracker_client announce 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! Announce response: +//! +//! ```json +//! { +//! "transaction_id": -888840697 +//! "announce_interval": 120, +//! "leechers": 0, +//! "seeders": 1, +//! "peers": [ +//! "123.123.123.123:51289" +//! ], +//! } +//! ``` +//! +//! Scrape request: +//! +//! ```text +//! cargo run --bin udp_tracker_client scrape 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! Scrape response: +//! +//! ```json +//! { +//! "transaction_id": -888840697, +//! "torrent_stats": [ +//! { +//! "completed": 0, +//! "leechers": 0, +//! "seeders": 0 +//! }, +//! { +//! "completed": 0, +//! "leechers": 0, +//! "seeders": 0 +//! } +//! ] +//! } +//! ``` +//! +//! You can use an URL with instead of the socket address. For example: +//! +//! ```text +//! cargo run --bin udp_tracker_client scrape udp://localhost:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! cargo run --bin udp_tracker_client scrape udp://localhost:6969/scrape 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! The protocol (`udp://`) in the URL is mandatory. The path (`\scrape`) is optional. It always uses `\scrape`. +use std::net::{SocketAddr, ToSocketAddrs}; +use std::str::FromStr; + +use anyhow::Context; +use aquatic_udp_protocol::{Response, TransactionId}; +use bittorrent_primitives::info_hash::InfoHash as TorrustInfoHash; +use clap::{Parser, Subcommand}; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; +use tracing::level_filters::LevelFilter; +use url::Url; + +use super::Error; +use crate::console::clients::udp::checker; +use crate::console::clients::udp::responses::dto::SerializableResponse; +use crate::console::clients::udp::responses::json::ToJson; + +const RANDOM_TRANSACTION_ID: i32 = -888_840_697; + +#[derive(Parser, Debug)] +#[command(author, version, about, long_about = None)] +struct Args { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand, Debug)] +enum Command { + Announce { + #[arg(value_parser = parse_socket_addr)] + tracker_socket_addr: SocketAddr, + #[arg(value_parser = parse_info_hash)] + info_hash: TorrustInfoHash, + }, + Scrape { + #[arg(value_parser = parse_socket_addr)] + tracker_socket_addr: SocketAddr, + #[arg(value_parser = parse_info_hash, num_args = 1..=74, value_delimiter = ' ')] + info_hashes: Vec, + }, +} + +/// # Errors +/// +/// Will return an error if the command fails. +/// +/// +pub async fn run() -> anyhow::Result<()> { + tracing_stdout_init(LevelFilter::INFO); + + let args = Args::parse(); + + let response = match args.command { + Command::Announce { + tracker_socket_addr: remote_addr, + info_hash, + } => handle_announce(remote_addr, &info_hash).await?, + Command::Scrape { + tracker_socket_addr: remote_addr, + info_hashes, + } => handle_scrape(remote_addr, &info_hashes).await?, + }; + + let response: SerializableResponse = response.into(); + let response_json = response.to_json_string()?; + + print!("{response_json}"); + + Ok(()) +} + +fn tracing_stdout_init(filter: LevelFilter) { + tracing_subscriber::fmt().with_max_level(filter).init(); + tracing::debug!("Logging initialized"); +} + +async fn handle_announce(remote_addr: SocketAddr, info_hash: &TorrustInfoHash) -> Result { + let transaction_id = TransactionId::new(RANDOM_TRANSACTION_ID); + + let client = checker::Client::new(remote_addr, DEFAULT_TIMEOUT).await?; + + let connection_id = client.send_connection_request(transaction_id).await?; + + client.send_announce_request(transaction_id, connection_id, *info_hash).await +} + +async fn handle_scrape(remote_addr: SocketAddr, info_hashes: &[TorrustInfoHash]) -> Result { + let transaction_id = TransactionId::new(RANDOM_TRANSACTION_ID); + + let client = checker::Client::new(remote_addr, DEFAULT_TIMEOUT).await?; + + let connection_id = client.send_connection_request(transaction_id).await?; + + client.send_scrape_request(connection_id, transaction_id, info_hashes).await +} + +fn parse_socket_addr(tracker_socket_addr_str: &str) -> anyhow::Result { + tracing::debug!("Tracker socket address: {tracker_socket_addr_str:#?}"); + + // Check if the address is a valid URL. If so, extract the host and port. + let resolved_addr = if let Ok(url) = Url::parse(tracker_socket_addr_str) { + tracing::debug!("Tracker socket address URL: {url:?}"); + + let host = url + .host_str() + .with_context(|| format!("invalid host in URL: `{tracker_socket_addr_str}`"))? + .to_owned(); + + let port = url + .port() + .with_context(|| format!("port not found in URL: `{tracker_socket_addr_str}`"))? + .to_owned(); + + (host, port) + } else { + // If not a URL, assume it's a host:port pair. + + let parts: Vec<&str> = tracker_socket_addr_str.split(':').collect(); + + if parts.len() != 2 { + return Err(anyhow::anyhow!( + "invalid address format: `{tracker_socket_addr_str}`. Expected format is host:port" + )); + } + + let host = parts[0].to_owned(); + + let port = parts[1] + .parse::() + .with_context(|| format!("invalid port: `{}`", parts[1]))? + .to_owned(); + + (host, port) + }; + + tracing::debug!("Resolved address: {resolved_addr:#?}"); + + // Perform DNS resolution. + let socket_addrs: Vec<_> = resolved_addr.to_socket_addrs()?.collect(); + if socket_addrs.is_empty() { + Err(anyhow::anyhow!("DNS resolution failed for `{tracker_socket_addr_str}`")) + } else { + Ok(socket_addrs[0]) + } +} + +fn parse_info_hash(info_hash_str: &str) -> anyhow::Result { + TorrustInfoHash::from_str(info_hash_str) + .map_err(|e| anyhow::Error::msg(format!("failed to parse info-hash `{info_hash_str}`: {e:?}"))) +} diff --git a/console/tracker-client/src/console/clients/udp/checker.rs b/console/tracker-client/src/console/clients/udp/checker.rs new file mode 100644 index 000000000..ded5c107e --- /dev/null +++ b/console/tracker-client/src/console/clients/udp/checker.rs @@ -0,0 +1,177 @@ +use std::net::{Ipv4Addr, SocketAddr}; +use std::num::NonZeroU16; +use std::time::Duration; + +use aquatic_udp_protocol::common::InfoHash; +use aquatic_udp_protocol::{ + AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, NumberOfBytes, NumberOfPeers, + PeerId, PeerKey, Port, Response, ScrapeRequest, TransactionId, +}; +use bittorrent_primitives::info_hash::InfoHash as TorrustInfoHash; +use bittorrent_tracker_client::udp::client::UdpTrackerClient; + +use super::Error; + +/// A UDP Tracker client to make test requests (checks). +#[derive(Debug)] +pub struct Client { + client: UdpTrackerClient, +} + +impl Client { + /// Creates a new `[Client]` for checking a UDP Tracker Service + /// + /// # Errors + /// + /// It will error if unable to bind and connect to the udp remote address. + /// + pub async fn new(remote_addr: SocketAddr, timeout: Duration) -> Result { + let client = UdpTrackerClient::new(remote_addr, timeout) + .await + .map_err(|err| Error::UnableToBindAndConnect { remote_addr, err })?; + + Ok(Self { client }) + } + + /// Returns the local addr of this [`Client`]. + /// + /// # Errors + /// + /// This function will return an error if the socket is somehow not bound. + pub fn local_addr(&self) -> std::io::Result { + self.client.client.socket.local_addr() + } + + /// Sends a connection request to the UDP Tracker server. + /// + /// # Errors + /// + /// Will return and error if + /// + /// - It can't connect to the remote UDP socket. + /// - It can't make a connection request successfully to the remote UDP + /// server (after successfully connecting to the remote UDP socket). + /// + /// # Panics + /// + /// Will panic if it receives an unexpected response. + pub async fn send_connection_request(&self, transaction_id: TransactionId) -> Result { + tracing::debug!("Sending connection request with transaction id: {transaction_id:#?}"); + + let connect_request = ConnectRequest { transaction_id }; + + let _ = self + .client + .send(connect_request.into()) + .await + .map_err(|err| Error::UnableToSendConnectionRequest { err })?; + + let response = self + .client + .receive() + .await + .map_err(|err| Error::UnableToReceiveConnectResponse { err })?; + + match response { + Response::Connect(connect_response) => Ok(connect_response.connection_id), + _ => Err(Error::UnexpectedConnectionResponse { response }), + } + } + + /// Sends an announce request to the UDP Tracker server. + /// + /// # Errors + /// + /// Will return and error if the client is not connected. You have to connect + /// before calling this function. + /// + /// # Panics + /// + /// It will panic if the `local_address` has a zero port. + pub async fn send_announce_request( + &self, + transaction_id: TransactionId, + connection_id: ConnectionId, + info_hash: TorrustInfoHash, + ) -> Result { + tracing::debug!("Sending announce request with transaction id: {transaction_id:#?}"); + + let port = NonZeroU16::new( + self.client + .client + .socket + .local_addr() + .expect("it should get the local address") + .port(), + ) + .expect("it should no be zero"); + + let announce_request = AnnounceRequest { + connection_id, + action_placeholder: AnnounceActionPlaceholder::default(), + transaction_id, + info_hash: InfoHash(info_hash.bytes()), + peer_id: PeerId(*b"-qB00000000000000001"), + bytes_downloaded: NumberOfBytes(0i64.into()), + bytes_uploaded: NumberOfBytes(0i64.into()), + bytes_left: NumberOfBytes(0i64.into()), + event: AnnounceEvent::Started.into(), + ip_address: Ipv4Addr::UNSPECIFIED.into(), + key: PeerKey::new(0i32), + peers_wanted: NumberOfPeers(1i32.into()), + port: Port::new(port), + }; + + let _ = self + .client + .send(announce_request.into()) + .await + .map_err(|err| Error::UnableToSendAnnounceRequest { err })?; + + let response = self + .client + .receive() + .await + .map_err(|err| Error::UnableToReceiveAnnounceResponse { err })?; + + Ok(response) + } + + /// Sends a scrape request to the UDP Tracker server. + /// + /// # Errors + /// + /// Will return and error if the client is not connected. You have to connect + /// before calling this function. + pub async fn send_scrape_request( + &self, + connection_id: ConnectionId, + transaction_id: TransactionId, + info_hashes: &[TorrustInfoHash], + ) -> Result { + tracing::debug!("Sending scrape request with transaction id: {transaction_id:#?}"); + + let scrape_request = ScrapeRequest { + connection_id, + transaction_id, + info_hashes: info_hashes + .iter() + .map(|torrust_info_hash| InfoHash(torrust_info_hash.bytes())) + .collect(), + }; + + let _ = self + .client + .send(scrape_request.into()) + .await + .map_err(|err| Error::UnableToSendScrapeRequest { err })?; + + let response = self + .client + .receive() + .await + .map_err(|err| Error::UnableToReceiveScrapeResponse { err })?; + + Ok(response) + } +} diff --git a/console/tracker-client/src/console/clients/udp/mod.rs b/console/tracker-client/src/console/clients/udp/mod.rs new file mode 100644 index 000000000..fbfd53770 --- /dev/null +++ b/console/tracker-client/src/console/clients/udp/mod.rs @@ -0,0 +1,50 @@ +use std::net::SocketAddr; + +use aquatic_udp_protocol::Response; +use bittorrent_tracker_client::udp; +use serde::Serialize; +use thiserror::Error; + +pub mod app; +pub mod checker; +pub mod responses; + +#[derive(Error, Debug, Clone, Serialize)] +#[serde(into = "String")] +pub enum Error { + #[error("Failed to Connect to: {remote_addr}, with error: {err}")] + UnableToBindAndConnect { remote_addr: SocketAddr, err: udp::Error }, + + #[error("Failed to send a connection request, with error: {err}")] + UnableToSendConnectionRequest { err: udp::Error }, + + #[error("Failed to receive a connect response, with error: {err}")] + UnableToReceiveConnectResponse { err: udp::Error }, + + #[error("Failed to send a announce request, with error: {err}")] + UnableToSendAnnounceRequest { err: udp::Error }, + + #[error("Failed to receive a announce response, with error: {err}")] + UnableToReceiveAnnounceResponse { err: udp::Error }, + + #[error("Failed to send a scrape request, with error: {err}")] + UnableToSendScrapeRequest { err: udp::Error }, + + #[error("Failed to receive a scrape response, with error: {err}")] + UnableToReceiveScrapeResponse { err: udp::Error }, + + #[error("Failed to receive a response, with error: {err}")] + UnableToReceiveResponse { err: udp::Error }, + + #[error("Failed to get local address for connection: {err}")] + UnableToGetLocalAddr { err: udp::Error }, + + #[error("Failed to get a connection response: {response:?}")] + UnexpectedConnectionResponse { response: Response }, +} + +impl From for String { + fn from(value: Error) -> Self { + value.to_string() + } +} diff --git a/console/tracker-client/src/console/clients/udp/responses/dto.rs b/console/tracker-client/src/console/clients/udp/responses/dto.rs new file mode 100644 index 000000000..93320b0f7 --- /dev/null +++ b/console/tracker-client/src/console/clients/udp/responses/dto.rs @@ -0,0 +1,128 @@ +//! Aquatic responses are not serializable. These are the serializable wrappers. +use std::net::{Ipv4Addr, Ipv6Addr}; + +use aquatic_udp_protocol::Response::{self}; +use aquatic_udp_protocol::{AnnounceResponse, ConnectResponse, ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, ScrapeResponse}; +use serde::Serialize; + +#[derive(Serialize)] +pub enum SerializableResponse { + Connect(ConnectSerializableResponse), + AnnounceIpv4(AnnounceSerializableResponse), + AnnounceIpv6(AnnounceSerializableResponse), + Scrape(ScrapeSerializableResponse), + Error(ErrorSerializableResponse), +} + +impl From for SerializableResponse { + fn from(response: Response) -> Self { + match response { + Response::Connect(response) => SerializableResponse::Connect(ConnectSerializableResponse::from(response)), + Response::AnnounceIpv4(response) => SerializableResponse::AnnounceIpv4(AnnounceSerializableResponse::from(response)), + Response::AnnounceIpv6(response) => SerializableResponse::AnnounceIpv6(AnnounceSerializableResponse::from(response)), + Response::Scrape(response) => SerializableResponse::Scrape(ScrapeSerializableResponse::from(response)), + Response::Error(response) => SerializableResponse::Error(ErrorSerializableResponse::from(response)), + } + } +} + +#[derive(Serialize)] +pub struct ConnectSerializableResponse { + transaction_id: i32, + connection_id: i64, +} + +impl From for ConnectSerializableResponse { + fn from(connect: ConnectResponse) -> Self { + Self { + transaction_id: connect.transaction_id.0.into(), + connection_id: connect.connection_id.0.into(), + } + } +} + +#[derive(Serialize)] +pub struct AnnounceSerializableResponse { + transaction_id: i32, + announce_interval: i32, + leechers: i32, + seeders: i32, + peers: Vec, +} + +impl From> for AnnounceSerializableResponse { + fn from(announce: AnnounceResponse) -> Self { + Self { + transaction_id: announce.fixed.transaction_id.0.into(), + announce_interval: announce.fixed.announce_interval.0.into(), + leechers: announce.fixed.leechers.0.into(), + seeders: announce.fixed.seeders.0.into(), + peers: announce + .peers + .iter() + .map(|peer| format!("{}:{}", Ipv4Addr::from(peer.ip_address), peer.port.0)) + .collect::>(), + } + } +} + +impl From> for AnnounceSerializableResponse { + fn from(announce: AnnounceResponse) -> Self { + Self { + transaction_id: announce.fixed.transaction_id.0.into(), + announce_interval: announce.fixed.announce_interval.0.into(), + leechers: announce.fixed.leechers.0.into(), + seeders: announce.fixed.seeders.0.into(), + peers: announce + .peers + .iter() + .map(|peer| format!("{}:{}", Ipv6Addr::from(peer.ip_address), peer.port.0)) + .collect::>(), + } + } +} + +#[derive(Serialize)] +pub struct ScrapeSerializableResponse { + transaction_id: i32, + torrent_stats: Vec, +} + +impl From for ScrapeSerializableResponse { + fn from(scrape: ScrapeResponse) -> Self { + Self { + transaction_id: scrape.transaction_id.0.into(), + torrent_stats: scrape + .torrent_stats + .iter() + .map(|torrent_scrape_statistics| TorrentStats { + seeders: torrent_scrape_statistics.seeders.0.into(), + completed: torrent_scrape_statistics.completed.0.into(), + leechers: torrent_scrape_statistics.leechers.0.into(), + }) + .collect::>(), + } + } +} + +#[derive(Serialize)] +pub struct ErrorSerializableResponse { + transaction_id: i32, + message: String, +} + +impl From for ErrorSerializableResponse { + fn from(error: ErrorResponse) -> Self { + Self { + transaction_id: error.transaction_id.0.into(), + message: error.message.to_string(), + } + } +} + +#[derive(Serialize)] +struct TorrentStats { + seeders: i32, + completed: i32, + leechers: i32, +} diff --git a/console/tracker-client/src/console/clients/udp/responses/json.rs b/console/tracker-client/src/console/clients/udp/responses/json.rs new file mode 100644 index 000000000..5d2bd6b89 --- /dev/null +++ b/console/tracker-client/src/console/clients/udp/responses/json.rs @@ -0,0 +1,25 @@ +use anyhow::Context; +use serde::Serialize; + +use super::dto::SerializableResponse; + +#[allow(clippy::module_name_repetitions)] +pub trait ToJson { + /// + /// Returns a string with the JSON serialized version of the response + /// + /// # Errors + /// + /// Will return an error if serialization fails. + /// + fn to_json_string(&self) -> anyhow::Result + where + Self: Serialize, + { + let pretty_json = serde_json::to_string_pretty(self).context("response JSON serialization")?; + + Ok(pretty_json) + } +} + +impl ToJson for SerializableResponse {} diff --git a/console/tracker-client/src/console/clients/udp/responses/mod.rs b/console/tracker-client/src/console/clients/udp/responses/mod.rs new file mode 100644 index 000000000..e6d2e5e51 --- /dev/null +++ b/console/tracker-client/src/console/clients/udp/responses/mod.rs @@ -0,0 +1,2 @@ +pub mod dto; +pub mod json; diff --git a/console/tracker-client/src/console/mod.rs b/console/tracker-client/src/console/mod.rs new file mode 100644 index 000000000..4b4cb9de4 --- /dev/null +++ b/console/tracker-client/src/console/mod.rs @@ -0,0 +1,2 @@ +//! Console apps. +pub mod clients; diff --git a/console/tracker-client/src/lib.rs b/console/tracker-client/src/lib.rs new file mode 100644 index 000000000..5b9849fdc --- /dev/null +++ b/console/tracker-client/src/lib.rs @@ -0,0 +1 @@ +pub mod console; diff --git a/contrib/bencode/Cargo.toml b/contrib/bencode/Cargo.toml new file mode 100644 index 000000000..5fab1792d --- /dev/null +++ b/contrib/bencode/Cargo.toml @@ -0,0 +1,26 @@ +[package] +description = "(contrib) Efficient decoding and encoding for bencode." +keywords = [ "bencode", "contrib", "library" ] +name = "torrust-tracker-contrib-bencode" +readme = "README.md" + +authors = [ "Nautilus Cyberneering , Andrew " ] +license = "Apache-2.0" +repository = "https://github.com/torrust/bittorrent-infrastructure-project" + +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +publish.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +thiserror = "2" + +[dev-dependencies] +criterion = "0" + +[[bench]] +harness = false +name = "bencode_benchmark" diff --git a/contrib/bencode/README.md b/contrib/bencode/README.md new file mode 100644 index 000000000..81c09f691 --- /dev/null +++ b/contrib/bencode/README.md @@ -0,0 +1,5 @@ +# Bencode + +This library allows for the creation and parsing of bencode encodings. + +Bencode is the binary encoding used throughout bittorrent technologies from metainfo files to DHT messages. Bencode types include integers, byte arrays, lists, and dictionaries, of which the last two can hold any bencode type (they could be recursively constructed). diff --git a/contrib/bencode/benches/bencode_benchmark.rs b/contrib/bencode/benches/bencode_benchmark.rs new file mode 100644 index 000000000..b22b286a5 --- /dev/null +++ b/contrib/bencode/benches/bencode_benchmark.rs @@ -0,0 +1,29 @@ +use std::hint::black_box; + +use criterion::{criterion_group, criterion_main, Criterion}; +use torrust_tracker_contrib_bencode::{BDecodeOpt, BencodeRef}; + +const B_NESTED_LISTS: &[u8; 100] = + b"lllllllllllllllllllllllllllllllllllllllllllllllllleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"; // cspell:disable-line +const MULTI_KB_BENCODE: &[u8; 30004] = include_bytes!("multi_kb.bencode"); + +fn bench_nested_lists(bencode: &[u8]) { + BencodeRef::decode(bencode, BDecodeOpt::new(50, true, true)).unwrap(); +} + +fn bench_multi_kb_bencode(bencode: &[u8]) { + BencodeRef::decode(bencode, BDecodeOpt::default()).unwrap(); +} + +fn criterion_benchmark(c: &mut Criterion) { + c.bench_function("bencode nested lists", |b| { + b.iter(|| bench_nested_lists(black_box(B_NESTED_LISTS))); + }); + + c.bench_function("bencode multi kb", |b| { + b.iter(|| bench_multi_kb_bencode(black_box(MULTI_KB_BENCODE))); + }); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/contrib/bencode/benches/multi_kb.bencode b/contrib/bencode/benches/multi_kb.bencode new file mode 100644 index 000000000..b86f2846e --- /dev/null +++ b/contrib/bencode/benches/multi_kb.bencode @@ -0,0 +1 @@ +d7:comment17:Just Some Comment10:created by12:bip_metainfo13:creation datei1496618058e4:infod5:filesld6:lengthi1024e4:pathl1:b11:small_1.txteed6:lengthi1024e4:pathl1:b12:small_10.txteed6:lengthi1024e4:pathl1:b13:small_100.txteed6:lengthi1024e4:pathl1:b12:small_11.txteed6:lengthi1024e4:pathl1:b12:small_12.txteed6:lengthi1024e4:pathl1:b12:small_13.txteed6:lengthi1024e4:pathl1:b12:small_14.txteed6:lengthi1024e4:pathl1:b12:small_15.txteed6:lengthi1024e4:pathl1:b12:small_16.txteed6:lengthi1024e4:pathl1:b12:small_17.txteed6:lengthi1024e4:pathl1:b12:small_18.txteed6:lengthi1024e4:pathl1:b12:small_19.txteed6:lengthi1024e4:pathl1:b11:small_2.txteed6:lengthi1024e4:pathl1:b12:small_20.txteed6:lengthi1024e4:pathl1:b12:small_21.txteed6:lengthi1024e4:pathl1:b12:small_22.txteed6:lengthi1024e4:pathl1:b12:small_23.txteed6:lengthi1024e4:pathl1:b12:small_24.txteed6:lengthi1024e4:pathl1:b12:small_25.txteed6:lengthi1024e4:pathl1:b12:small_26.txteed6:lengthi1024e4:pathl1:b12:small_27.txteed6:lengthi1024e4:pathl1:b12:small_28.txteed6:lengthi1024e4:pathl1:b12:small_29.txteed6:lengthi1024e4:pathl1:b11:small_3.txteed6:lengthi1024e4:pathl1:b12:small_30.txteed6:lengthi1024e4:pathl1:b12:small_31.txteed6:lengthi1024e4:pathl1:b12:small_32.txteed6:lengthi1024e4:pathl1:b12:small_33.txteed6:lengthi1024e4:pathl1:b12:small_34.txteed6:lengthi1024e4:pathl1:b12:small_35.txteed6:lengthi1024e4:pathl1:b12:small_36.txteed6:lengthi1024e4:pathl1:b12:small_37.txteed6:lengthi1024e4:pathl1:b12:small_38.txteed6:lengthi1024e4:pathl1:b12:small_39.txteed6:lengthi1024e4:pathl1:b11:small_4.txteed6:lengthi1024e4:pathl1:b12:small_40.txteed6:lengthi1024e4:pathl1:b12:small_41.txteed6:lengthi1024e4:pathl1:b12:small_42.txteed6:lengthi1024e4:pathl1:b12:small_43.txteed6:lengthi1024e4:pathl1:b12:small_44.txteed6:lengthi1024e4:pathl1:b12:small_45.txteed6:lengthi1024e4:pathl1:b12:small_46.txteed6:lengthi1024e4:pathl1:b12:small_47.txteed6:lengthi1024e4:pathl1:b12:small_48.txteed6:lengthi1024e4:pathl1:b12:small_49.txteed6:lengthi1024e4:pathl1:b11:small_5.txteed6:lengthi1024e4:pathl1:b12:small_50.txteed6:lengthi1024e4:pathl1:b12:small_51.txteed6:lengthi1024e4:pathl1:b12:small_52.txteed6:lengthi1024e4:pathl1:b12:small_53.txteed6:lengthi1024e4:pathl1:b12:small_54.txteed6:lengthi1024e4:pathl1:b12:small_55.txteed6:lengthi1024e4:pathl1:b12:small_56.txteed6:lengthi1024e4:pathl1:b12:small_57.txteed6:lengthi1024e4:pathl1:b12:small_58.txteed6:lengthi1024e4:pathl1:b12:small_59.txteed6:lengthi1024e4:pathl1:b11:small_6.txteed6:lengthi1024e4:pathl1:b12:small_60.txteed6:lengthi1024e4:pathl1:b12:small_61.txteed6:lengthi1024e4:pathl1:b12:small_62.txteed6:lengthi1024e4:pathl1:b12:small_63.txteed6:lengthi1024e4:pathl1:b12:small_64.txteed6:lengthi1024e4:pathl1:b12:small_65.txteed6:lengthi1024e4:pathl1:b12:small_66.txteed6:lengthi1024e4:pathl1:b12:small_67.txteed6:lengthi1024e4:pathl1:b12:small_68.txteed6:lengthi1024e4:pathl1:b12:small_69.txteed6:lengthi1024e4:pathl1:b11:small_7.txteed6:lengthi1024e4:pathl1:b12:small_70.txteed6:lengthi1024e4:pathl1:b12:small_71.txteed6:lengthi1024e4:pathl1:b12:small_72.txteed6:lengthi1024e4:pathl1:b12:small_73.txteed6:lengthi1024e4:pathl1:b12:small_74.txteed6:lengthi1024e4:pathl1:b12:small_75.txteed6:lengthi1024e4:pathl1:b12:small_76.txteed6:lengthi1024e4:pathl1:b12:small_77.txteed6:lengthi1024e4:pathl1:b12:small_78.txteed6:lengthi1024e4:pathl1:b12:small_79.txteed6:lengthi1024e4:pathl1:b11:small_8.txteed6:lengthi1024e4:pathl1:b12:small_80.txteed6:lengthi1024e4:pathl1:b12:small_81.txteed6:lengthi1024e4:pathl1:b12:small_82.txteed6:lengthi1024e4:pathl1:b12:small_83.txteed6:lengthi1024e4:pathl1:b12:small_84.txteed6:lengthi1024e4:pathl1:b12:small_85.txteed6:lengthi1024e4:pathl1:b12:small_86.txteed6:lengthi1024e4:pathl1:b12:small_87.txteed6:lengthi1024e4:pathl1:b12:small_88.txteed6:lengthi1024e4:pathl1:b12:small_89.txteed6:lengthi1024e4:pathl1:b11:small_9.txteed6:lengthi1024e4:pathl1:b12:small_90.txteed6:lengthi1024e4:pathl1:b12:small_91.txteed6:lengthi1024e4:pathl1:b12:small_92.txteed6:lengthi1024e4:pathl1:b12:small_93.txteed6:lengthi1024e4:pathl1:b12:small_94.txteed6:lengthi1024e4:pathl1:b12:small_95.txteed6:lengthi1024e4:pathl1:b12:small_96.txteed6:lengthi1024e4:pathl1:b12:small_97.txteed6:lengthi1024e4:pathl1:b12:small_98.txteed6:lengthi1024e4:pathl1:b12:small_99.txteed6:lengthi5368709120e4:pathl9:large.txteee4:name1:a12:piece lengthi4194304e6:pieces25620:+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;Ã+̽/8ñ\ë}Z‰ý…õ•â;ÃZiî½c^c.>óN7’±µìee \ No newline at end of file diff --git a/contrib/bencode/src/access/bencode.rs b/contrib/bencode/src/access/bencode.rs new file mode 100644 index 000000000..728535a98 --- /dev/null +++ b/contrib/bencode/src/access/bencode.rs @@ -0,0 +1,120 @@ +use crate::access::dict::BDictAccess; +use crate::access::list::BListAccess; + +/// Abstract representation of a `BencodeRef` object. +pub enum RefKind<'a, K, V> { + /// Bencode Integer. + Int(i64), + /// Bencode Bytes. + Bytes(&'a [u8]), + /// Bencode List. + List(&'a dyn BListAccess), + /// Bencode Dictionary. + Dict(&'a dyn BDictAccess), +} + +/// Trait for read access to some bencode type. +pub trait BRefAccess: Sized { + type BKey; + type BType: BRefAccess; + + /// Access the bencode as a `BencodeRefKind`. + fn kind(&self) -> RefKind<'_, Self::BKey, Self::BType>; + + /// Attempt to access the bencode as a `str`. + fn str(&self) -> Option<&str>; + + /// Attempt to access the bencode as an `i64`. + fn int(&self) -> Option; + + /// Attempt to access the bencode as an `[u8]`. + fn bytes(&self) -> Option<&[u8]>; + + /// Attempt to access the bencode as an `BListAccess`. + fn list(&self) -> Option<&dyn BListAccess>; + + /// Attempt to access the bencode as an `BDictAccess`. + fn dict(&self) -> Option<&dyn BDictAccess>; +} + +/// Trait for extended read access to some bencode type. +/// +/// Use this trait when you want to make sure that the lifetime of +/// the underlying buffers is tied to the lifetime of the backing +/// bencode buffer. +pub trait BRefAccessExt<'a>: BRefAccess { + /// Attempt to access the bencode as a `str`. + fn str_ext(&self) -> Option<&'a str>; + + /// Attempt to access the bencode as an `[u8]`. + fn bytes_ext(&self) -> Option<&'a [u8]>; +} + +impl BRefAccess for &T +where + T: BRefAccess, +{ + type BKey = T::BKey; + type BType = T::BType; + + fn kind(&self) -> RefKind<'_, Self::BKey, Self::BType> { + (*self).kind() + } + + fn str(&self) -> Option<&str> { + (*self).str() + } + + fn int(&self) -> Option { + (*self).int() + } + + fn bytes(&self) -> Option<&[u8]> { + (*self).bytes() + } + + fn list(&self) -> Option<&dyn BListAccess> { + (*self).list() + } + + fn dict(&self) -> Option<&dyn BDictAccess> { + (*self).dict() + } +} + +impl<'a: 'b, 'b, T> BRefAccessExt<'a> for &'b T +where + T: BRefAccessExt<'a>, +{ + fn str_ext(&self) -> Option<&'a str> { + (*self).str_ext() + } + + fn bytes_ext(&self) -> Option<&'a [u8]> { + (*self).bytes_ext() + } +} + +/// Abstract representation of a `BencodeMut` object. +pub enum MutKind<'a, K, V> { + /// Bencode Integer. + Int(i64), + /// Bencode Bytes. + Bytes(&'a [u8]), + /// Bencode List. + List(&'a mut dyn BListAccess), + /// Bencode Dictionary. + Dict(&'a mut dyn BDictAccess), +} + +/// Trait for write access to some bencode type. +pub trait BMutAccess: Sized + BRefAccess { + /// Access the bencode as a `BencodeMutKind`. + fn kind_mut(&mut self) -> MutKind<'_, Self::BKey, Self::BType>; + + /// Attempt to access the bencode as a mutable `BListAccess`. + fn list_mut(&mut self) -> Option<&mut dyn BListAccess>; + + /// Attempt to access the bencode as a mutable `BDictAccess`. + fn dict_mut(&mut self) -> Option<&mut dyn BDictAccess>; +} diff --git a/contrib/bencode/src/access/convert.rs b/contrib/bencode/src/access/convert.rs new file mode 100644 index 000000000..b2eb41d15 --- /dev/null +++ b/contrib/bencode/src/access/convert.rs @@ -0,0 +1,212 @@ +#![allow(clippy::missing_errors_doc)] +use crate::access::bencode::{BRefAccess, BRefAccessExt}; +use crate::access::dict::BDictAccess; +use crate::access::list::BListAccess; +use crate::BencodeConvertError; + +/// Trait for extended casting of bencode objects and converting conversion errors into application specific errors. +pub trait BConvertExt: BConvert { + /// See `BConvert::convert_bytes`. + fn convert_bytes_ext<'a, B, E>(&self, bencode: B, error_key: E) -> Result<&'a [u8], Self::Error> + where + B: BRefAccessExt<'a>, + E: AsRef<[u8]>, + { + bencode.bytes_ext().ok_or(self.handle_error(BencodeConvertError::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "Bytes".to_owned(), + })) + } + + /// See `BConvert::convert_str`. + fn convert_str_ext<'a, B, E>(&self, bencode: &B, error_key: E) -> Result<&'a str, Self::Error> + where + B: BRefAccessExt<'a>, + E: AsRef<[u8]>, + { + bencode.str_ext().ok_or(self.handle_error(BencodeConvertError::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "UTF-8 Bytes".to_owned(), + })) + } + + /// See `BConvert::lookup_and_convert_bytes`. + fn lookup_and_convert_bytes_ext<'a, B, K1, K2>( + &self, + dictionary: &dyn BDictAccess, + key: K2, + ) -> Result<&'a [u8], Self::Error> + where + B: BRefAccessExt<'a>, + K2: AsRef<[u8]>, + { + self.convert_bytes_ext(self.lookup(dictionary, &key)?, &key) + } + + /// See `BConvert::lookup_and_convert_str`. + fn lookup_and_convert_str_ext<'a, B, K1, K2>( + &self, + dictionary: &dyn BDictAccess, + key: K2, + ) -> Result<&'a str, Self::Error> + where + B: BRefAccessExt<'a>, + K2: AsRef<[u8]>, + { + self.convert_str_ext(self.lookup(dictionary, &key)?, &key) + } +} + +/// Trait for casting bencode objects and converting conversion errors into application specific errors. +#[allow(clippy::module_name_repetitions)] +pub trait BConvert { + type Error; + + /// Convert the given conversion error into the appropriate error type. + fn handle_error(&self, error: BencodeConvertError) -> Self::Error; + + /// Attempt to convert the given bencode value into an integer. + /// + /// Error key is used to generate an appropriate error message should the operation return an error. + fn convert_int(&self, bencode: B, error_key: E) -> Result + where + B: BRefAccess, + E: AsRef<[u8]>, + { + bencode.int().ok_or(self.handle_error(BencodeConvertError::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "Integer".to_owned(), + })) + } + + /// Attempt to convert the given bencode value into bytes. + /// + /// Error key is used to generate an appropriate error message should the operation return an error. + fn convert_bytes<'a, B, E>(&self, bencode: &'a B, error_key: E) -> Result<&'a [u8], Self::Error> + where + B: BRefAccess, + E: AsRef<[u8]>, + { + bencode.bytes().ok_or(self.handle_error(BencodeConvertError::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "Bytes".to_owned(), + })) + } + + /// Attempt to convert the given bencode value into a UTF-8 string. + /// + /// Error key is used to generate an appropriate error message should the operation return an error. + fn convert_str<'a, B, E>(&self, bencode: &'a B, error_key: E) -> Result<&'a str, Self::Error> + where + B: BRefAccess, + E: AsRef<[u8]>, + { + bencode.str().ok_or(self.handle_error(BencodeConvertError::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "UTF-8 Bytes".to_owned(), + })) + } + + /// Attempt to convert the given bencode value into a list. + /// + /// Error key is used to generate an appropriate error message should the operation return an error. + fn convert_list<'a, B, E>(&self, bencode: &'a B, error_key: E) -> Result<&'a dyn BListAccess, Self::Error> + where + B: BRefAccess, + E: AsRef<[u8]>, + { + bencode.list().ok_or(self.handle_error(BencodeConvertError::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "List".to_owned(), + })) + } + + /// Attempt to convert the given bencode value into a dictionary. + /// + /// Error key is used to generate an appropriate error message should the operation return an error. + fn convert_dict<'a, B, E>(&self, bencode: &'a B, error_key: E) -> Result<&'a dyn BDictAccess, Self::Error> + where + B: BRefAccess, + E: AsRef<[u8]>, + { + bencode.dict().ok_or(self.handle_error(BencodeConvertError::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "Dictionary".to_owned(), + })) + } + + /// Look up a value in a dictionary of bencoded values using the given key. + fn lookup<'a, B, K1, K2>(&self, dictionary: &'a dyn BDictAccess, key: K2) -> Result<&'a B, Self::Error> + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + let key_ref = key.as_ref(); + + match dictionary.lookup(key_ref) { + Some(n) => Ok(n), + None => Err(self.handle_error(BencodeConvertError::MissingKey { key: key_ref.to_owned() })), + } + } + + /// Combines a lookup operation on the given key with a conversion of the value, if found, to an integer. + fn lookup_and_convert_int(&self, dictionary: &dyn BDictAccess, key: K2) -> Result + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + self.convert_int(self.lookup(dictionary, &key)?, &key) + } + + /// Combines a lookup operation on the given key with a conversion of the value, if found, to a series of bytes. + fn lookup_and_convert_bytes<'a, B, K1, K2>( + &self, + dictionary: &'a dyn BDictAccess, + key: K2, + ) -> Result<&'a [u8], Self::Error> + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + self.convert_bytes(self.lookup(dictionary, &key)?, &key) + } + + /// Combines a lookup operation on the given key with a conversion of the value, if found, to a UTF-8 string. + fn lookup_and_convert_str<'a, B, K1, K2>( + &self, + dictionary: &'a dyn BDictAccess, + key: K2, + ) -> Result<&'a str, Self::Error> + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + self.convert_str(self.lookup(dictionary, &key)?, &key) + } + + /// Combines a lookup operation on the given key with a conversion of the value, if found, to a list. + fn lookup_and_convert_list<'a, B, K1, K2>( + &self, + dictionary: &'a dyn BDictAccess, + key: K2, + ) -> Result<&'a dyn BListAccess, Self::Error> + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + self.convert_list(self.lookup(dictionary, &key)?, &key) + } + + /// Combines a lookup operation on the given key with a conversion of the value, if found, to a dictionary. + fn lookup_and_convert_dict<'a, B, K1, K2>( + &self, + dictionary: &'a dyn BDictAccess, + key: K2, + ) -> Result<&'a dyn BDictAccess, Self::Error> + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + self.convert_dict(self.lookup(dictionary, &key)?, &key) + } +} diff --git a/contrib/bencode/src/access/dict.rs b/contrib/bencode/src/access/dict.rs new file mode 100644 index 000000000..a3e56d1bb --- /dev/null +++ b/contrib/bencode/src/access/dict.rs @@ -0,0 +1,64 @@ +use std::borrow::Cow; +use std::collections::BTreeMap; + +/// Trait for working with generic map data structures. +pub trait BDictAccess { + /// Convert the dictionary to an unordered list of key/value pairs. + fn to_list(&self) -> Vec<(&K, &V)>; + + /// Lookup a value in the dictionary. + fn lookup(&self, key: &[u8]) -> Option<&V>; + + /// Lookup a mutable value in the dictionary. + fn lookup_mut(&mut self, key: &[u8]) -> Option<&mut V>; + + /// Insert a key/value pair into the dictionary. + fn insert(&mut self, key: K, value: V) -> Option; + + /// Remove a value from the dictionary and return it. + fn remove(&mut self, key: &[u8]) -> Option; +} + +impl<'a, V> BDictAccess<&'a [u8], V> for BTreeMap<&'a [u8], V> { + fn to_list(&self) -> Vec<(&&'a [u8], &V)> { + self.iter().collect() + } + + fn lookup(&self, key: &[u8]) -> Option<&V> { + self.get(key) + } + + fn lookup_mut(&mut self, key: &[u8]) -> Option<&mut V> { + self.get_mut(key) + } + + fn insert(&mut self, key: &'a [u8], value: V) -> Option { + self.insert(key, value) + } + + fn remove(&mut self, key: &[u8]) -> Option { + self.remove(key) + } +} + +impl<'a, V> BDictAccess, V> for BTreeMap, V> { + fn to_list(&self) -> Vec<(&Cow<'a, [u8]>, &V)> { + self.iter().collect() + } + + fn lookup(&self, key: &[u8]) -> Option<&V> { + self.get(key) + } + + fn lookup_mut(&mut self, key: &[u8]) -> Option<&mut V> { + self.get_mut(key) + } + + fn insert(&mut self, key: Cow<'a, [u8]>, value: V) -> Option { + self.insert(key, value) + } + + fn remove(&mut self, key: &[u8]) -> Option { + self.remove(key) + } +} diff --git a/contrib/bencode/src/access/list.rs b/contrib/bencode/src/access/list.rs new file mode 100644 index 000000000..840bffa1e --- /dev/null +++ b/contrib/bencode/src/access/list.rs @@ -0,0 +1,108 @@ +use std::ops::{Index, IndexMut}; + +/// Trait for working with generic list data structures. +pub trait BListAccess { + /// Get a list element at the given index. + fn get(&self, index: usize) -> Option<&V>; + + /// Get a mutable list element at the given index. + fn get_mut(&mut self, index: usize) -> Option<&mut V>; + + /// Remove a list element at the given index. + fn remove(&mut self, index: usize) -> Option; + + /// Insert a list element at the given index. + fn insert(&mut self, index: usize, item: V); + + /// Push an element to the back of the list. + fn push(&mut self, item: V); + + /// Get the length of the list. + fn len(&self) -> usize; + + fn is_empty(&self) -> bool; +} + +impl<'a, V: 'a> Index for &'a dyn BListAccess { + type Output = V; + + fn index(&self, index: usize) -> &V { + self.get(index).unwrap() + } +} + +impl<'a, V: 'a> Index for &'a mut dyn BListAccess { + type Output = V; + + fn index(&self, index: usize) -> &V { + self.get(index).unwrap() + } +} + +impl<'a, V: 'a> IndexMut for &'a mut dyn BListAccess { + fn index_mut(&mut self, index: usize) -> &mut V { + self.get_mut(index).unwrap() + } +} + +impl<'a, V: 'a> IntoIterator for &'a dyn BListAccess { + type Item = &'a V; + type IntoIter = BListIter<'a, V>; + + fn into_iter(self) -> BListIter<'a, V> { + BListIter { index: 0, access: self } + } +} + +pub struct BListIter<'a, V> { + index: usize, + access: &'a dyn BListAccess, +} + +impl<'a, V> Iterator for BListIter<'a, V> { + type Item = &'a V; + + fn next(&mut self) -> Option<&'a V> { + let opt_next = self.access.get(self.index); + + if opt_next.is_some() { + self.index += 1; + } + + opt_next + } +} + +impl BListAccess for Vec { + fn get(&self, index: usize) -> Option<&V> { + self[..].get(index) + } + + fn get_mut(&mut self, index: usize) -> Option<&mut V> { + self[..].get_mut(index) + } + + fn remove(&mut self, index: usize) -> Option { + if index >= self[..].len() { + None + } else { + Some(Vec::remove(self, index)) + } + } + + fn insert(&mut self, index: usize, item: V) { + Vec::insert(self, index, item); + } + + fn push(&mut self, item: V) { + Vec::push(self, item); + } + + fn len(&self) -> usize { + Vec::len(self) + } + + fn is_empty(&self) -> bool { + Vec::is_empty(self) + } +} diff --git a/contrib/bencode/src/access/mod.rs b/contrib/bencode/src/access/mod.rs new file mode 100644 index 000000000..f14b032d4 --- /dev/null +++ b/contrib/bencode/src/access/mod.rs @@ -0,0 +1,4 @@ +pub mod bencode; +pub mod convert; +pub mod dict; +pub mod list; diff --git a/contrib/bencode/src/cow.rs b/contrib/bencode/src/cow.rs new file mode 100644 index 000000000..0d38c751b --- /dev/null +++ b/contrib/bencode/src/cow.rs @@ -0,0 +1,44 @@ +use std::borrow::Cow; + +/// Trait for macros to convert owned/borrowed types to `Cow`. +/// +/// This is needed because `&str` and `String` do not have `From` +/// implements into `Cow<_, [u8]>`. One solution is to just call `AsRef<[u8]>` +/// before converting. However, then when a user specifies an owned type, +/// we will implicitly borrow that; this trait prevents that so that macro +/// behavior is intuitive, so that owned types stay owned. +pub trait BCowConvert<'a> { + fn convert(self) -> Cow<'a, [u8]>; +} + +// TODO: Enable when specialization lands. +/* +impl<'a, T> BCowConvert<'a> for T where T: AsRef<[u8]> + 'a { + fn convert(self) -> Cow<'a, [u8]> { + self.into() + } +}*/ + +impl<'a> BCowConvert<'a> for &'a [u8] { + fn convert(self) -> Cow<'a, [u8]> { + self.into() + } +} + +impl<'a> BCowConvert<'a> for &'a str { + fn convert(self) -> Cow<'a, [u8]> { + self.as_bytes().into() + } +} + +impl BCowConvert<'static> for String { + fn convert(self) -> Cow<'static, [u8]> { + self.into_bytes().into() + } +} + +impl BCowConvert<'static> for Vec { + fn convert(self) -> Cow<'static, [u8]> { + self.into() + } +} diff --git a/contrib/bencode/src/error.rs b/contrib/bencode/src/error.rs new file mode 100644 index 000000000..6e661a068 --- /dev/null +++ b/contrib/bencode/src/error.rs @@ -0,0 +1,52 @@ +use thiserror::Error; + +#[allow(clippy::module_name_repetitions)] +#[derive(Error, Debug)] +pub enum BencodeParseError { + #[error("Incomplete Number Of Bytes At {pos}")] + BytesEmpty { pos: usize }, + + #[error("Invalid Byte Found At {pos}")] + InvalidByte { pos: usize }, + + #[error("Invalid Integer Found With No Delimiter At {pos}")] + InvalidIntNoDelimiter { pos: usize }, + + #[error("Invalid Integer Found As Negative Zero At {pos}")] + InvalidIntNegativeZero { pos: usize }, + + #[error("Invalid Integer Found With Zero Padding At {pos}")] + InvalidIntZeroPadding { pos: usize }, + + #[error("Invalid Integer Found To Fail Parsing At {pos}")] + InvalidIntParseError { pos: usize }, + + #[error("Invalid Dictionary Key Ordering Found At {pos} For Key {key:?}")] + InvalidKeyOrdering { pos: usize, key: Vec }, + + #[error("Invalid Dictionary Key Found At {pos} For Key {key:?}")] + InvalidKeyDuplicates { pos: usize, key: Vec }, + + #[error("Invalid Byte Length Found As Negative At {pos}")] + InvalidLengthNegative { pos: usize }, + + #[error("Invalid Byte Length Found To Overflow Buffer Length At {pos}")] + InvalidLengthOverflow { pos: usize }, + + #[error("Invalid Recursion Limit Exceeded At {pos} For Limit {max}")] + InvalidRecursionExceeded { pos: usize, max: usize }, +} + +pub type BencodeParseResult = Result; + +#[allow(clippy::module_name_repetitions)] +#[derive(Error, Debug)] +pub enum BencodeConvertError { + #[error("Missing Key In Bencode For {key:?}")] + MissingKey { key: Vec }, + + #[error("Wrong Type In Bencode For {key:?} Expected Type {expected_type}")] + WrongType { key: Vec, expected_type: String }, +} + +pub type BencodeConvertResult = Result; diff --git a/contrib/bencode/src/lib.rs b/contrib/bencode/src/lib.rs new file mode 100644 index 000000000..c44ec07b2 --- /dev/null +++ b/contrib/bencode/src/lib.rs @@ -0,0 +1,139 @@ +//! Library for parsing and converting bencoded data. +//! +//! # Examples +//! +//! Decoding bencoded data: +//! +//! ```rust +//! extern crate torrust_tracker_contrib_bencode; +//! +//! use torrust_tracker_contrib_bencode::{BencodeRef, BRefAccess, BDecodeOpt}; +//! +//! fn main() { +//! let data = b"d12:lucky_numberi7ee"; // cspell:disable-line +//! let bencode = BencodeRef::decode(data, BDecodeOpt::default()).unwrap(); +//! +//! assert_eq!(7, bencode.dict().unwrap().lookup("lucky_number".as_bytes()) +//! .unwrap().int().unwrap()); +//! } +//! ``` +//! +//! Encoding bencoded data: +//! +//! ```rust +//! #[macro_use] +//! extern crate torrust_tracker_contrib_bencode; +//! +//! fn main() { +//! let message = (ben_map!{ +//! "lucky_number" => ben_int!(7), +//! "lucky_string" => ben_bytes!("7") +//! }).encode(); +//! +//! let data = b"d12:lucky_numberi7e12:lucky_string1:7e"; // cspell:disable-line +//! assert_eq!(&data[..], &message[..]); +//! } +//! ``` + +mod access; +mod cow; +mod error; +mod mutable; +mod reference; + +/// Traits for implementation functionality. +pub mod inner { + pub use crate::cow::BCowConvert; +} + +/// Traits for extended functionality. +pub mod ext { + #[allow(clippy::module_name_repetitions)] + pub use crate::access::bencode::BRefAccessExt; + #[allow(clippy::module_name_repetitions)] + pub use crate::access::convert::BConvertExt; +} + +#[deprecated(since = "1.0.0", note = "use `MutKind` instead.")] +pub use crate::access::bencode::MutKind as BencodeMutKind; +#[deprecated(since = "1.0.0", note = "use `RefKind` instead.")] +pub use crate::access::bencode::RefKind as BencodeRefKind; +pub use crate::access::bencode::{BMutAccess, BRefAccess, MutKind, RefKind}; +pub use crate::access::convert::BConvert; +pub use crate::access::dict::BDictAccess; +pub use crate::access::list::BListAccess; +pub use crate::error::{BencodeConvertError, BencodeConvertResult, BencodeParseError, BencodeParseResult}; +pub use crate::mutable::bencode_mut::BencodeMut; +pub use crate::reference::bencode_ref::BencodeRef; +pub use crate::reference::decode_opt::BDecodeOpt; + +const BEN_END: u8 = b'e'; +const DICT_START: u8 = b'd'; +const LIST_START: u8 = b'l'; +const INT_START: u8 = b'i'; + +const BYTE_LEN_LOW: u8 = b'0'; +const BYTE_LEN_HIGH: u8 = b'9'; +const BYTE_LEN_END: u8 = b':'; + +/// Construct a `BencodeMut` map by supplying string references as keys and `BencodeMut` as values. +#[macro_export] +macro_rules! ben_map { +( $($key:expr => $val:expr),* ) => { + { + use $crate::{BMutAccess, BencodeMut}; + use $crate::inner::BCowConvert; + + let mut bencode_map = BencodeMut::new_dict(); + { + let map = bencode_map.dict_mut().unwrap(); + $( + map.insert(BCowConvert::convert($key), $val); + )* + } + + bencode_map + } + } +} + +/// Construct a `BencodeMut` list by supplying a list of `BencodeMut` values. +#[macro_export] +macro_rules! ben_list { + ( $($ben:expr),* ) => { + { + use $crate::{BencodeMut, BMutAccess}; + + let mut bencode_list = BencodeMut::new_list(); + { + let list = bencode_list.list_mut().unwrap(); + $( + list.push($ben); + )* + } + + bencode_list + } + } +} + +/// Construct `BencodeMut` bytes by supplying a type convertible to `Vec`. +#[macro_export] +macro_rules! ben_bytes { + ( $ben:expr ) => {{ + use $crate::inner::BCowConvert; + use $crate::BencodeMut; + + BencodeMut::new_bytes(BCowConvert::convert($ben)) + }}; +} + +/// Construct a `BencodeMut` integer by supplying an `i64`. +#[macro_export] +macro_rules! ben_int { + ( $ben:expr ) => {{ + use $crate::BencodeMut; + + BencodeMut::new_int($ben) + }}; +} diff --git a/contrib/bencode/src/mutable/bencode_mut.rs b/contrib/bencode/src/mutable/bencode_mut.rs new file mode 100644 index 000000000..21e00f7b0 --- /dev/null +++ b/contrib/bencode/src/mutable/bencode_mut.rs @@ -0,0 +1,226 @@ +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::str; + +use crate::access::bencode::{BMutAccess, BRefAccess, MutKind, RefKind}; +use crate::access::dict::BDictAccess; +use crate::access::list::BListAccess; +use crate::mutable::encode; + +/// Bencode object that holds references to the underlying data. +#[derive(Debug, Eq, PartialEq, Clone, Hash)] +pub enum Inner<'a> { + /// Bencode Integer. + Int(i64), + /// Bencode Bytes. + Bytes(Cow<'a, [u8]>), + /// Bencode List. + List(Vec>), + /// Bencode Dictionary. + Dict(BTreeMap, BencodeMut<'a>>), +} + +/// `BencodeMut` object that stores references to some data. +#[derive(Debug, Eq, PartialEq, Clone, Hash)] +pub struct BencodeMut<'a> { + inner: Inner<'a>, +} + +impl<'a> BencodeMut<'a> { + fn new(inner: Inner<'a>) -> BencodeMut<'a> { + BencodeMut { inner } + } + + /// Create a new `BencodeMut` representing an `i64`. + #[must_use] + pub fn new_int(value: i64) -> BencodeMut<'a> { + BencodeMut::new(Inner::Int(value)) + } + + /// Create a new `BencodeMut` representing a `[u8]`. + #[must_use] + pub fn new_bytes(value: Cow<'a, [u8]>) -> BencodeMut<'a> { + BencodeMut::new(Inner::Bytes(value)) + } + + /// Create a new `BencodeMut` representing a `BListAccess`. + #[must_use] + pub fn new_list() -> BencodeMut<'a> { + BencodeMut::new(Inner::List(Vec::new())) + } + + /// Create a new `BencodeMut` representing a `BDictAccess`. + #[must_use] + pub fn new_dict() -> BencodeMut<'a> { + BencodeMut::new(Inner::Dict(BTreeMap::new())) + } + + /// Encode the `BencodeMut` into a buffer representing the bencode. + #[must_use] + pub fn encode(&self) -> Vec { + let mut buffer = Vec::new(); + + encode::encode(self, &mut buffer); + + buffer + } +} + +impl<'a> BRefAccess for BencodeMut<'a> { + type BKey = Cow<'a, [u8]>; + type BType = BencodeMut<'a>; + + fn kind<'b>(&'b self) -> RefKind<'b, Cow<'a, [u8]>, BencodeMut<'a>> { + match self.inner { + Inner::Int(n) => RefKind::Int(n), + Inner::Bytes(ref n) => RefKind::Bytes(n), + Inner::List(ref n) => RefKind::List(n), + Inner::Dict(ref n) => RefKind::Dict(n), + } + } + + fn str(&self) -> Option<&str> { + let bytes = self.bytes()?; + + str::from_utf8(bytes).ok() + } + + fn int(&self) -> Option { + match self.inner { + Inner::Int(n) => Some(n), + _ => None, + } + } + + fn bytes(&self) -> Option<&[u8]> { + match self.inner { + Inner::Bytes(ref n) => Some(n.as_ref()), + _ => None, + } + } + + fn list(&self) -> Option<&dyn BListAccess>> { + match self.inner { + Inner::List(ref n) => Some(n), + _ => None, + } + } + + fn dict(&self) -> Option<&dyn BDictAccess, BencodeMut<'a>>> { + match self.inner { + Inner::Dict(ref n) => Some(n), + _ => None, + } + } +} + +impl<'a> BMutAccess for BencodeMut<'a> { + fn kind_mut<'b>(&'b mut self) -> MutKind<'b, Cow<'a, [u8]>, BencodeMut<'a>> { + match self.inner { + Inner::Int(n) => MutKind::Int(n), + Inner::Bytes(ref mut n) => MutKind::Bytes((*n).as_ref()), + Inner::List(ref mut n) => MutKind::List(n), + Inner::Dict(ref mut n) => MutKind::Dict(n), + } + } + + fn list_mut(&mut self) -> Option<&mut dyn BListAccess>> { + match self.inner { + Inner::List(ref mut n) => Some(n), + _ => None, + } + } + + fn dict_mut(&mut self) -> Option<&mut dyn BDictAccess, BencodeMut<'a>>> { + match self.inner { + Inner::Dict(ref mut n) => Some(n), + _ => None, + } + } +} + +// impl<'a> From> for BencodeMut<'a> { +// fn from(value: BencodeRef<'a>) -> Self { +// let inner = match value.kind() { +// BencodeRefKind::Int(value) => InnerBencodeMut::Int(value), +// BencodeRefKind::Bytes(value) => InnerBencodeMut::Bytes(Cow::Owned(Vec::from(value))), +// BencodeRefKind::List(value) => { +// InnerBencodeMut::List(value.clone().into_iter().map(|b| BencodeMut::from(b.clone())).collect()) +// } +// BencodeRefKind::Dict(value) => InnerBencodeMut::Dict( +// value +// .to_list() +// .into_iter() +// .map(|(key, value)| (Cow::Owned(Vec::from(*key)), BencodeMut::from(value.clone()))) +// .collect(), +// ), +// }; +// BencodeMut { inner } +// } +// } + +#[cfg(test)] +mod test { + use crate::access::bencode::BMutAccess; + use crate::mutable::bencode_mut::BencodeMut; + + #[test] + fn positive_int_encode() { + let bencode_int = BencodeMut::new_int(-560); + + let int_bytes = b"i-560e"; // cspell:disable-line + assert_eq!(&int_bytes[..], &bencode_int.encode()[..]); + } + + #[test] + fn positive_bytes_encode() { + /* cspell:disable-next-line */ + let bencode_bytes = BencodeMut::new_bytes((&b"asdasd"[..]).into()); + + let bytes_bytes = b"6:asdasd"; // cspell:disable-line + assert_eq!(&bytes_bytes[..], &bencode_bytes.encode()[..]); + } + + #[test] + fn positive_empty_list_encode() { + let bencode_list = BencodeMut::new_list(); + + let list_bytes = b"le"; // cspell:disable-line + assert_eq!(&list_bytes[..], &bencode_list.encode()[..]); + } + + #[test] + fn positive_nonempty_list_encode() { + let mut bencode_list = BencodeMut::new_list(); + + { + let list_mut = bencode_list.list_mut().unwrap(); + list_mut.push(BencodeMut::new_int(56)); + } + + let list_bytes = b"li56ee"; // cspell:disable-line + assert_eq!(&list_bytes[..], &bencode_list.encode()[..]); + } + + #[test] + fn positive_empty_dict_encode() { + let bencode_dict = BencodeMut::new_dict(); + + let dict_bytes = b"de"; // cspell:disable-line + assert_eq!(&dict_bytes[..], &bencode_dict.encode()[..]); + } + + #[test] + fn positive_nonempty_dict_encode() { + let mut bencode_dict = BencodeMut::new_dict(); + + { + let dict_mut = bencode_dict.dict_mut().unwrap(); + /* cspell:disable-next-line */ + dict_mut.insert((&b"asd"[..]).into(), BencodeMut::new_bytes((&b"asdasd"[..]).into())); + } + + let dict_bytes = b"d3:asd6:asdasde"; // cspell:disable-line + assert_eq!(&dict_bytes[..], &bencode_dict.encode()[..]); + } +} diff --git a/contrib/bencode/src/mutable/encode.rs b/contrib/bencode/src/mutable/encode.rs new file mode 100644 index 000000000..811c35816 --- /dev/null +++ b/contrib/bencode/src/mutable/encode.rs @@ -0,0 +1,67 @@ +use std::iter::Extend; + +use crate::access::bencode::{BRefAccess, RefKind}; +use crate::access::dict::BDictAccess; +use crate::access::list::BListAccess; + +pub fn encode(val: T, bytes: &mut Vec) +where + T: BRefAccess, + T::BKey: AsRef<[u8]>, +{ + match val.kind() { + RefKind::Int(n) => encode_int(n, bytes), + RefKind::Bytes(n) => encode_bytes(n, bytes), + RefKind::List(n) => encode_list(n, bytes), + RefKind::Dict(n) => encode_dict(n, bytes), + } +} + +fn encode_int(val: i64, bytes: &mut Vec) { + bytes.push(crate::INT_START); + + bytes.extend(val.to_string().into_bytes()); + + bytes.push(crate::BEN_END); +} + +fn encode_bytes(list: &[u8], bytes: &mut Vec) { + bytes.extend(list.len().to_string().into_bytes()); + + bytes.push(crate::BYTE_LEN_END); + + bytes.extend(list.iter().copied()); +} + +fn encode_list(list: &dyn BListAccess, bytes: &mut Vec) +where + T: BRefAccess, + T::BKey: AsRef<[u8]>, +{ + bytes.push(crate::LIST_START); + + for i in list { + encode(i, bytes); + } + + bytes.push(crate::BEN_END); +} + +fn encode_dict(dict: &dyn BDictAccess, bytes: &mut Vec) +where + K: AsRef<[u8]>, + V: BRefAccess, + V::BKey: AsRef<[u8]>, +{ + // Need To Sort The Keys In The Map Before Encoding + let mut sort_dict = dict.to_list(); + sort_dict.sort_by(|&(a, _), &(b, _)| a.as_ref().cmp(b.as_ref())); + + bytes.push(crate::DICT_START); + // Iterate And Dictionary Encode The (String, Bencode) Pairs + for (key, value) in &sort_dict { + encode_bytes(key.as_ref(), bytes); + encode(value, bytes); + } + bytes.push(crate::BEN_END); +} diff --git a/contrib/bencode/src/mutable/mod.rs b/contrib/bencode/src/mutable/mod.rs new file mode 100644 index 000000000..329ee9f7a --- /dev/null +++ b/contrib/bencode/src/mutable/mod.rs @@ -0,0 +1,2 @@ +pub mod bencode_mut; +mod encode; diff --git a/contrib/bencode/src/reference/bencode_ref.rs b/contrib/bencode/src/reference/bencode_ref.rs new file mode 100644 index 000000000..20d102cb4 --- /dev/null +++ b/contrib/bencode/src/reference/bencode_ref.rs @@ -0,0 +1,259 @@ +use std::collections::BTreeMap; +use std::str; + +use crate::access::bencode::{BRefAccess, BRefAccessExt, RefKind}; +use crate::access::dict::BDictAccess; +use crate::access::list::BListAccess; +use crate::error::{BencodeParseError, BencodeParseResult}; +use crate::reference::decode; +use crate::reference::decode_opt::BDecodeOpt; + +/// Bencode object that holds references to the underlying data. +#[derive(Debug, Eq, PartialEq, Clone, Hash)] +pub enum Inner<'a> { + /// Bencode Integer. + Int(i64, &'a [u8]), + /// Bencode Bytes. + Bytes(&'a [u8], &'a [u8]), + /// Bencode List. + List(Vec>, &'a [u8]), + /// Bencode Dictionary. + Dict(BTreeMap<&'a [u8], BencodeRef<'a>>, &'a [u8]), +} + +impl<'a> From> for BencodeRef<'a> { + fn from(val: Inner<'a>) -> Self { + BencodeRef { inner: val } + } +} + +/// `BencodeRef` object that stores references to some buffer. +#[derive(Debug, Eq, PartialEq, Clone, Hash)] +pub struct BencodeRef<'a> { + inner: Inner<'a>, +} + +impl<'a> BencodeRef<'a> { + /// Decode the given bytes into a `BencodeRef` using the given decode options. + #[allow(clippy::missing_errors_doc)] + pub fn decode(bytes: &'a [u8], opts: BDecodeOpt) -> BencodeParseResult> { + // Apply try so any errors return before the eof check + let (bencode, end_pos) = decode::decode(bytes, 0, opts, 0)?; + + if end_pos != bytes.len() && opts.enforce_full_decode() { + return Err(BencodeParseError::BytesEmpty { pos: end_pos }); + } + + Ok(bencode) + } + + /// Get a byte slice of the current bencode byte representation. + #[must_use] + pub fn buffer(&self) -> &'a [u8] { + #[allow(clippy::match_same_arms)] + match self.inner { + Inner::Int(_, buffer) => buffer, + Inner::Bytes(_, buffer) => buffer, + Inner::List(_, buffer) => buffer, + Inner::Dict(_, buffer) => buffer, + } + } +} + +impl<'a> BRefAccess for BencodeRef<'a> { + type BKey = &'a [u8]; + type BType = BencodeRef<'a>; + + fn kind<'b>(&'b self) -> RefKind<'b, &'a [u8], BencodeRef<'a>> { + match self.inner { + Inner::Int(n, _) => RefKind::Int(n), + Inner::Bytes(n, _) => RefKind::Bytes(n), + Inner::List(ref n, _) => RefKind::List(n), + Inner::Dict(ref n, _) => RefKind::Dict(n), + } + } + + fn str(&self) -> Option<&str> { + self.str_ext() + } + + fn int(&self) -> Option { + match self.inner { + Inner::Int(n, _) => Some(n), + _ => None, + } + } + + fn bytes(&self) -> Option<&[u8]> { + self.bytes_ext() + } + + fn list(&self) -> Option<&dyn BListAccess>> { + match self.inner { + Inner::List(ref n, _) => Some(n), + _ => None, + } + } + + fn dict(&self) -> Option<&dyn BDictAccess<&'a [u8], BencodeRef<'a>>> { + match self.inner { + Inner::Dict(ref n, _) => Some(n), + _ => None, + } + } +} + +impl<'a> BRefAccessExt<'a> for BencodeRef<'a> { + fn str_ext(&self) -> Option<&'a str> { + let bytes = self.bytes_ext()?; + + str::from_utf8(bytes).ok() + } + + fn bytes_ext(&self) -> Option<&'a [u8]> { + match self.inner { + Inner::Bytes(n, _) => Some(&n[0..]), + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + + use crate::access::bencode::BRefAccess; + use crate::reference::bencode_ref::BencodeRef; + use crate::reference::decode_opt::BDecodeOpt; + + #[test] + fn positive_int_buffer() { + let int_bytes = b"i-500e"; // cspell:disable-line + let bencode = BencodeRef::decode(&int_bytes[..], BDecodeOpt::default()).unwrap(); + + assert_eq!(int_bytes, bencode.buffer()); + } + + #[test] + fn positive_bytes_buffer() { + let bytes_bytes = b"3:asd"; // cspell:disable-line + let bencode = BencodeRef::decode(&bytes_bytes[..], BDecodeOpt::default()).unwrap(); + + assert_eq!(bytes_bytes, bencode.buffer()); + } + + #[test] + fn positive_list_buffer() { + let list_bytes = b"l3:asde"; // cspell:disable-line + let bencode = BencodeRef::decode(&list_bytes[..], BDecodeOpt::default()).unwrap(); + + assert_eq!(list_bytes, bencode.buffer()); + } + + #[test] + fn positive_dict_buffer() { + let dict_bytes = b"d3:asd3:asde"; // cspell:disable-line + let bencode = BencodeRef::decode(&dict_bytes[..], BDecodeOpt::default()).unwrap(); + + assert_eq!(dict_bytes, bencode.buffer()); + } + + #[test] + fn positive_list_nested_int_buffer() { + let nested_int_bytes = b"li-500ee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_int_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_list = bencode.list().unwrap(); + let bencode_int = bencode_list.get(0).unwrap(); + + let int_bytes = b"i-500e"; // cspell:disable-line + assert_eq!(int_bytes, bencode_int.buffer()); + } + + #[test] + fn positive_dict_nested_int_buffer() { + let nested_int_bytes = b"d3:asdi-500ee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_int_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_dict = bencode.dict().unwrap(); + /* cspell:disable-next-line */ + let bencode_int = bencode_dict.lookup(&b"asd"[..]).unwrap(); + + let int_bytes = b"i-500e"; // cspell:disable-line + assert_eq!(int_bytes, bencode_int.buffer()); + } + + #[test] + fn positive_list_nested_bytes_buffer() { + let nested_bytes_bytes = b"l3:asde"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_bytes_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_list = bencode.list().unwrap(); + let bencode_bytes = bencode_list.get(0).unwrap(); + + let bytes_bytes = b"3:asd"; // cspell:disable-line + assert_eq!(bytes_bytes, bencode_bytes.buffer()); + } + + #[test] + fn positive_dict_nested_bytes_buffer() { + let nested_bytes_bytes = b"d3:asd3:asde"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_bytes_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_dict = bencode.dict().unwrap(); + /* cspell:disable-next-line */ + let bencode_bytes = bencode_dict.lookup(&b"asd"[..]).unwrap(); + + let bytes_bytes = b"3:asd"; // cspell:disable-line + assert_eq!(bytes_bytes, bencode_bytes.buffer()); + } + + #[test] + fn positive_list_nested_list_buffer() { + let nested_list_bytes = b"ll3:asdee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_list_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_list = bencode.list().unwrap(); + let bencode_list = bencode_list.get(0).unwrap(); + + let list_bytes = b"l3:asde"; // cspell:disable-line + assert_eq!(list_bytes, bencode_list.buffer()); + } + + #[test] + fn positive_dict_nested_list_buffer() { + let nested_list_bytes = b"d3:asdl3:asdee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_list_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_dict = bencode.dict().unwrap(); + /* cspell:disable-next-line */ + let bencode_list = bencode_dict.lookup(&b"asd"[..]).unwrap(); + + let list_bytes = b"l3:asde"; // cspell:disable-line + assert_eq!(list_bytes, bencode_list.buffer()); + } + + #[test] + fn positive_list_nested_dict_buffer() { + let nested_dict_bytes = b"ld3:asd3:asdee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_dict_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_list = bencode.list().unwrap(); + let bencode_dict = bencode_list.get(0).unwrap(); + + let dict_bytes = b"d3:asd3:asde"; // cspell:disable-line + assert_eq!(dict_bytes, bencode_dict.buffer()); + } + + #[test] + fn positive_dict_nested_dict_buffer() { + let nested_dict_bytes = b"d3:asdd3:asd3:asdee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_dict_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_dict = bencode.dict().unwrap(); + /* cspell:disable-next-line */ + let bencode_dict = bencode_dict.lookup(&b"asd"[..]).unwrap(); + + let dict_bytes = b"d3:asd3:asde"; // cspell:disable-line + assert_eq!(dict_bytes, bencode_dict.buffer()); + } +} diff --git a/contrib/bencode/src/reference/decode.rs b/contrib/bencode/src/reference/decode.rs new file mode 100644 index 000000000..37ca22549 --- /dev/null +++ b/contrib/bencode/src/reference/decode.rs @@ -0,0 +1,377 @@ +use std::collections::btree_map::Entry; +use std::collections::BTreeMap; +use std::str; + +use crate::error::{BencodeParseError, BencodeParseResult}; +use crate::reference::bencode_ref::{BencodeRef, Inner}; +use crate::reference::decode_opt::BDecodeOpt; + +pub fn decode(bytes: &[u8], pos: usize, opts: BDecodeOpt, depth: usize) -> BencodeParseResult<(BencodeRef<'_>, usize)> { + if depth >= opts.max_recursion() { + return Err(BencodeParseError::InvalidRecursionExceeded { pos, max: depth }); + } + let curr_byte = peek_byte(bytes, pos)?; + + match curr_byte { + crate::INT_START => { + let (bencode, next_pos) = decode_int(bytes, pos + 1, crate::BEN_END)?; + Ok((Inner::Int(bencode, &bytes[pos..next_pos]).into(), next_pos)) + } + crate::LIST_START => { + let (bencode, next_pos) = decode_list(bytes, pos + 1, opts, depth)?; + Ok((Inner::List(bencode, &bytes[pos..next_pos]).into(), next_pos)) + } + crate::DICT_START => { + let (bencode, next_pos) = decode_dict(bytes, pos + 1, opts, depth)?; + Ok((Inner::Dict(bencode, &bytes[pos..next_pos]).into(), next_pos)) + } + crate::BYTE_LEN_LOW..=crate::BYTE_LEN_HIGH => { + let (bencode, next_pos) = decode_bytes(bytes, pos)?; + // Include the length digit, don't increment position + Ok((Inner::Bytes(bencode, &bytes[pos..next_pos]).into(), next_pos)) + } + _ => Err(BencodeParseError::InvalidByte { pos }), + } +} + +fn decode_int(bytes: &[u8], pos: usize, delim: u8) -> BencodeParseResult<(i64, usize)> { + let (_, begin_decode) = bytes.split_at(pos); + + let Some(relative_end_pos) = begin_decode.iter().position(|n| *n == delim) else { + return Err(BencodeParseError::InvalidIntNoDelimiter { pos }); + }; + let int_byte_slice = &begin_decode[..relative_end_pos]; + + if int_byte_slice.len() > 1 { + // Negative zero is not allowed (this would not be caught when converting) + if int_byte_slice[0] == b'-' && int_byte_slice[1] == b'0' { + return Err(BencodeParseError::InvalidIntNegativeZero { pos }); + } + + // Zero padding is illegal, and unspecified for key lengths (we disallow both) + if int_byte_slice[0] == b'0' { + return Err(BencodeParseError::InvalidIntZeroPadding { pos }); + } + } + + let Ok(int_str) = str::from_utf8(int_byte_slice) else { + return Err(BencodeParseError::InvalidIntParseError { pos }); + }; + + // Position of end of integer type, next byte is the start of the next value + let absolute_end_pos = pos + relative_end_pos; + let next_pos = absolute_end_pos + 1; + match int_str.parse::() { + Ok(n) => Ok((n, next_pos)), + Err(_) => Err(BencodeParseError::InvalidIntParseError { pos }), + } +} + +use std::convert::TryFrom; + +fn decode_bytes(bytes: &[u8], pos: usize) -> BencodeParseResult<(&[u8], usize)> { + let (num_bytes, start_pos) = decode_int(bytes, pos, crate::BYTE_LEN_END)?; + + if num_bytes < 0 { + return Err(BencodeParseError::InvalidLengthNegative { pos }); + } + + // Use usize::try_from to handle potential overflow + let num_bytes = usize::try_from(num_bytes).map_err(|_| BencodeParseError::InvalidLengthOverflow { pos })?; + + if num_bytes > bytes[start_pos..].len() { + return Err(BencodeParseError::InvalidLengthOverflow { pos }); + } + + let next_pos = start_pos + num_bytes; + Ok((&bytes[start_pos..next_pos], next_pos)) +} + +fn decode_list(bytes: &[u8], pos: usize, opts: BDecodeOpt, depth: usize) -> BencodeParseResult<(Vec>, usize)> { + let mut bencode_list = Vec::new(); + + let mut curr_pos = pos; + let mut curr_byte = peek_byte(bytes, curr_pos)?; + + while curr_byte != crate::BEN_END { + let (bencode, next_pos) = decode(bytes, curr_pos, opts, depth + 1)?; + + bencode_list.push(bencode); + + curr_pos = next_pos; + curr_byte = peek_byte(bytes, curr_pos)?; + } + + let next_pos = curr_pos + 1; + Ok((bencode_list, next_pos)) +} + +fn decode_dict( + bytes: &[u8], + pos: usize, + opts: BDecodeOpt, + depth: usize, +) -> BencodeParseResult<(BTreeMap<&[u8], BencodeRef<'_>>, usize)> { + let mut bencode_dict = BTreeMap::new(); + + let mut curr_pos = pos; + let mut curr_byte = peek_byte(bytes, curr_pos)?; + + while curr_byte != crate::BEN_END { + let (key_bytes, next_pos) = decode_bytes(bytes, curr_pos)?; + + // Spec says that the keys must be in alphabetical order + match (bencode_dict.keys().last(), opts.check_key_sort()) { + (Some(last_key), true) if key_bytes < *last_key => { + return Err(BencodeParseError::InvalidKeyOrdering { + pos: curr_pos, + key: key_bytes.to_vec(), + }) + } + _ => (), + } + + curr_pos = next_pos; + + let (value, next_pos) = decode(bytes, curr_pos, opts, depth + 1)?; + match bencode_dict.entry(key_bytes) { + Entry::Vacant(n) => n.insert(value), + Entry::Occupied(_) => { + return Err(BencodeParseError::InvalidKeyDuplicates { + pos: curr_pos, + key: key_bytes.to_vec(), + }) + } + }; + + curr_pos = next_pos; + curr_byte = peek_byte(bytes, curr_pos)?; + } + + let next_pos = curr_pos + 1; + Ok((bencode_dict, next_pos)) +} + +fn peek_byte(bytes: &[u8], pos: usize) -> BencodeParseResult { + bytes.get(pos).copied().ok_or(BencodeParseError::BytesEmpty { pos }) +} + +#[cfg(test)] +mod tests { + + use crate::access::bencode::BRefAccess; + use crate::reference::bencode_ref::BencodeRef; + use crate::reference::decode_opt::BDecodeOpt; + + /* cSpell:disable */ + // Positive Cases + const GENERAL: &[u8] = b"d0:12:zero_len_key8:location17:udp://test.com:8011:nested dictd4:listli-500500eee6:numberi500500ee"; + const RECURSION: &[u8] = b"lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"; + const BYTES_UTF8: &[u8] = b"16:valid_utf8_bytes"; + const DICTIONARY: &[u8] = b"d9:test_dictd10:nested_key12:nested_value11:nested_listli500ei-500ei0eee8:test_key10:test_valuee"; + const LIST: &[u8] = b"l10:test_bytesi500ei0ei-500el12:nested_bytesed8:test_key10:test_valueee"; + const BYTES: &[u8] = b"5:\xC5\xE6\xBE\xE6\xF2"; + const BYTES_ZERO_LEN: &[u8] = b"0:"; + const INT: &[u8] = b"i500e"; + const INT_NEGATIVE: &[u8] = b"i-500e"; + const INT_ZERO: &[u8] = b"i0e"; + const PARTIAL: &[u8] = b"i0e_asd"; + + // Negative Cases + const BYTES_NEG_LEN: &[u8] = b"-4:test"; + const BYTES_EXTRA: &[u8] = b"l15:processed_bytese17:unprocessed_bytes"; + const BYTES_NOT_UTF8: &[u8] = b"5:\xC5\xE6\xBE\xE6\xF2"; + const INT_NAN: &[u8] = b"i500a500e"; + const INT_LEADING_ZERO: &[u8] = b"i0500e"; + const INT_DOUBLE_ZERO: &[u8] = b"i00e"; + const INT_NEGATIVE_ZERO: &[u8] = b"i-0e"; + const INT_DOUBLE_NEGATIVE: &[u8] = b"i--5e"; + const DICT_UNORDERED_KEYS: &[u8] = b"d5:z_key5:value5:a_key5:valuee"; + const DICT_DUP_KEYS_SAME_DATA: &[u8] = b"d5:a_keyi0e5:a_keyi0ee"; + const DICT_DUP_KEYS_DIFF_DATA: &[u8] = b"d5:a_keyi0e5:a_key7:a_valuee"; + /* cSpell:enable */ + + #[test] + fn positive_decode_general() { + let bencode = BencodeRef::decode(GENERAL, BDecodeOpt::default()).unwrap(); + + let ben_dict = bencode.dict().unwrap(); + assert_eq!(ben_dict.lookup("".as_bytes()).unwrap().str().unwrap(), "zero_len_key"); + assert_eq!( + ben_dict.lookup("location".as_bytes()).unwrap().str().unwrap(), + "udp://test.com:80" + ); + assert_eq!(ben_dict.lookup("number".as_bytes()).unwrap().int().unwrap(), 500_500_i64); + + let nested_dict = ben_dict.lookup("nested dict".as_bytes()).unwrap().dict().unwrap(); + let nested_list = nested_dict.lookup("list".as_bytes()).unwrap().list().unwrap(); + assert_eq!(nested_list[0].int().unwrap(), -500_500_i64); + } + + #[test] + fn positive_decode_recursion() { + BencodeRef::decode(RECURSION, BDecodeOpt::new(50, true, true)).unwrap_err(); + + // As long as we didn't overflow our call stack, we are good! + } + + #[test] + fn positive_decode_bytes_utf8() { + let bencode = BencodeRef::decode(BYTES_UTF8, BDecodeOpt::default()).unwrap(); + + assert_eq!(bencode.str().unwrap(), "valid_utf8_bytes"); + } + + #[test] + fn positive_decode_dict() { + let bencode = BencodeRef::decode(DICTIONARY, BDecodeOpt::default()).unwrap(); + let dict = bencode.dict().unwrap(); + assert_eq!(dict.lookup("test_key".as_bytes()).unwrap().str().unwrap(), "test_value"); + + let nested_dict = dict.lookup("test_dict".as_bytes()).unwrap().dict().unwrap(); + assert_eq!( + nested_dict.lookup("nested_key".as_bytes()).unwrap().str().unwrap(), + "nested_value" + ); + + let nested_list = nested_dict.lookup("nested_list".as_bytes()).unwrap().list().unwrap(); + assert_eq!(nested_list[0].int().unwrap(), 500i64); + assert_eq!(nested_list[1].int().unwrap(), -500i64); + assert_eq!(nested_list[2].int().unwrap(), 0i64); + } + + #[test] + fn positive_decode_list() { + let bencode = BencodeRef::decode(LIST, BDecodeOpt::default()).unwrap(); + let list = bencode.list().unwrap(); + + assert_eq!(list[0].str().unwrap(), "test_bytes"); + assert_eq!(list[1].int().unwrap(), 500i64); + assert_eq!(list[2].int().unwrap(), 0i64); + assert_eq!(list[3].int().unwrap(), -500i64); + + let nested_list = list[4].list().unwrap(); + assert_eq!(nested_list[0].str().unwrap(), "nested_bytes"); + + let nested_dict = list[5].dict().unwrap(); + assert_eq!( + nested_dict.lookup("test_key".as_bytes()).unwrap().str().unwrap(), + "test_value" + ); + } + + #[test] + fn positive_decode_bytes() { + let bytes = super::decode_bytes(BYTES, 0).unwrap().0; + assert_eq!(bytes.len(), 5); + assert_eq!(bytes[0] as char, 'Ã…'); + assert_eq!(bytes[1] as char, 'æ'); + assert_eq!(bytes[2] as char, '¾'); + assert_eq!(bytes[3] as char, 'æ'); + assert_eq!(bytes[4] as char, 'ò'); + } + + #[test] + fn positive_decode_bytes_zero_len() { + let bytes = super::decode_bytes(BYTES_ZERO_LEN, 0).unwrap().0; + assert_eq!(bytes.len(), 0); + } + + #[test] + fn positive_decode_int() { + let int_value = super::decode_int(INT, 1, crate::BEN_END).unwrap().0; + assert_eq!(int_value, 500i64); + } + + #[test] + fn positive_decode_int_negative() { + let int_value = super::decode_int(INT_NEGATIVE, 1, crate::BEN_END).unwrap().0; + assert_eq!(int_value, -500i64); + } + + #[test] + fn positive_decode_int_zero() { + let int_value = super::decode_int(INT_ZERO, 1, crate::BEN_END).unwrap().0; + assert_eq!(int_value, 0i64); + } + + #[test] + fn positive_decode_partial() { + let bencode = BencodeRef::decode(PARTIAL, BDecodeOpt::new(2, true, false)).unwrap(); + + assert_ne!(PARTIAL.len(), bencode.buffer().len()); + assert_eq!(3, bencode.buffer().len()); + } + + #[test] + fn positive_decode_dict_unordered_keys() { + BencodeRef::decode(DICT_UNORDERED_KEYS, BDecodeOpt::default()).unwrap(); + } + + #[test] + #[should_panic = "InvalidByte { pos: 0 }"] + fn negative_decode_bytes_neg_len() { + BencodeRef::decode(BYTES_NEG_LEN, BDecodeOpt::default()).unwrap(); + } + + #[test] + #[should_panic = "BytesEmpty { pos: 20 }"] + fn negative_decode_bytes_extra() { + BencodeRef::decode(BYTES_EXTRA, BDecodeOpt::default()).unwrap(); + } + + #[test] + fn negative_decode_bytes_not_utf8() { + let bencode = BencodeRef::decode(BYTES_NOT_UTF8, BDecodeOpt::default()).unwrap(); + + assert!(bencode.str().is_none()); + } + + #[test] + #[should_panic = "InvalidIntParseError { pos: 1 }"] + fn negative_decode_int_nan() { + super::decode_int(INT_NAN, 1, crate::BEN_END).unwrap(); + } + + #[test] + #[should_panic = "InvalidIntZeroPadding { pos: 1 }"] + fn negative_decode_int_leading_zero() { + super::decode_int(INT_LEADING_ZERO, 1, crate::BEN_END).unwrap(); + } + + #[test] + #[should_panic = "InvalidIntZeroPadding { pos: 1 }"] + fn negative_decode_int_double_zero() { + super::decode_int(INT_DOUBLE_ZERO, 1, crate::BEN_END).unwrap(); + } + + #[test] + #[should_panic = "InvalidIntNegativeZero { pos: 1 }"] + fn negative_decode_int_negative_zero() { + super::decode_int(INT_NEGATIVE_ZERO, 1, crate::BEN_END).unwrap(); + } + + #[test] + #[should_panic = " InvalidIntParseError { pos: 1 }"] + fn negative_decode_int_double_negative() { + super::decode_int(INT_DOUBLE_NEGATIVE, 1, crate::BEN_END).unwrap(); + } + + #[test] + #[should_panic = "InvalidKeyOrdering { pos: 15, key: [97, 95, 107, 101, 121] }"] + fn negative_decode_dict_unordered_keys() { + BencodeRef::decode(DICT_UNORDERED_KEYS, BDecodeOpt::new(5, true, true)).unwrap(); + } + + #[test] + #[should_panic = "InvalidKeyDuplicates { pos: 18, key: [97, 95, 107, 101, 121] }"] + fn negative_decode_dict_dup_keys_same_data() { + BencodeRef::decode(DICT_DUP_KEYS_SAME_DATA, BDecodeOpt::default()).unwrap(); + } + + #[test] + #[should_panic = "InvalidKeyDuplicates { pos: 18, key: [97, 95, 107, 101, 121] }"] + fn negative_decode_dict_dup_keys_diff_data() { + BencodeRef::decode(DICT_DUP_KEYS_DIFF_DATA, BDecodeOpt::default()).unwrap(); + } +} diff --git a/contrib/bencode/src/reference/decode_opt.rs b/contrib/bencode/src/reference/decode_opt.rs new file mode 100644 index 000000000..8409cc72c --- /dev/null +++ b/contrib/bencode/src/reference/decode_opt.rs @@ -0,0 +1,53 @@ +const DEFAULT_MAX_RECURSION: usize = 50; +const DEFAULT_CHECK_KEY_SORT: bool = false; +const DEFAULT_ENFORCE_FULL_DECODE: bool = true; + +/// Stores decoding options for modifying decode behavior. +#[derive(Copy, Clone)] +#[allow(clippy::module_name_repetitions)] +pub struct BDecodeOpt { + max_recursion: usize, + check_key_sort: bool, + enforce_full_decode: bool, +} + +impl BDecodeOpt { + /// Create a new `BDecodeOpt` object. + #[must_use] + pub fn new(max_recursion: usize, check_key_sort: bool, enforce_full_decode: bool) -> BDecodeOpt { + BDecodeOpt { + max_recursion, + check_key_sort, + enforce_full_decode, + } + } + + /// Maximum limit allowed when decoding bencode. + #[must_use] + pub fn max_recursion(&self) -> usize { + self.max_recursion + } + + /// Whether or not an error should be thrown for out of order dictionary keys. + #[must_use] + pub fn check_key_sort(&self) -> bool { + self.check_key_sort + } + + /// Whether or not we enforce that the decoded bencode must make up all of the input + /// bytes or not. + /// + /// It may be useful to disable this if for example, the input bencode is prepended to + /// some payload and you would like to disassociate it. In this case, to find where the + /// rest of the payload starts that wasn't decoded, get the bencode buffer, and call `len()`. + #[must_use] + pub fn enforce_full_decode(&self) -> bool { + self.enforce_full_decode + } +} + +impl Default for BDecodeOpt { + fn default() -> BDecodeOpt { + BDecodeOpt::new(DEFAULT_MAX_RECURSION, DEFAULT_CHECK_KEY_SORT, DEFAULT_ENFORCE_FULL_DECODE) + } +} diff --git a/contrib/bencode/src/reference/mod.rs b/contrib/bencode/src/reference/mod.rs new file mode 100644 index 000000000..6a0ae6e40 --- /dev/null +++ b/contrib/bencode/src/reference/mod.rs @@ -0,0 +1,3 @@ +pub mod bencode_ref; +pub mod decode; +pub mod decode_opt; diff --git a/contrib/bencode/tests/mod.rs b/contrib/bencode/tests/mod.rs new file mode 100644 index 000000000..14606c175 --- /dev/null +++ b/contrib/bencode/tests/mod.rs @@ -0,0 +1,18 @@ +use torrust_tracker_contrib_bencode::{ben_bytes, ben_int, ben_list, ben_map}; + +#[test] +fn positive_ben_map_macro() { + let result = (ben_map! { + "key" => ben_bytes!("value") + }) + .encode(); + + assert_eq!("d3:key5:valuee".as_bytes(), &result[..]); // cspell:disable-line +} + +#[test] +fn positive_ben_list_macro() { + let result = (ben_list!(ben_int!(5))).encode(); + + assert_eq!("li5ee".as_bytes(), &result[..]); // cspell:disable-line +} diff --git a/contrib/dev-tools/benches/run-benches.sh b/contrib/dev-tools/benches/run-benches.sh new file mode 100755 index 000000000..0de356492 --- /dev/null +++ b/contrib/dev-tools/benches/run-benches.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +# This script is only intended to be used for local development or testing environments. + +cargo bench --package torrust-tracker-torrent-repository + +cargo bench --package bittorrent-http-tracker-core + +cargo bench --package bittorrent-udp-tracker-core diff --git a/contrib/dev-tools/containers/docker-build.sh b/contrib/dev-tools/containers/docker-build.sh new file mode 100755 index 000000000..39143910f --- /dev/null +++ b/contrib/dev-tools/containers/docker-build.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +echo "Building docker image ..." + +docker build --target release --tag torrust-tracker:release --file Containerfile . diff --git a/contrib/dev-tools/containers/docker-install.sh b/contrib/dev-tools/containers/docker-install.sh new file mode 100755 index 000000000..6034e8233 --- /dev/null +++ b/contrib/dev-tools/containers/docker-install.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +./contrib/dev-tools/containers/docker-build.sh diff --git a/contrib/dev-tools/containers/docker-run-local.sh b/contrib/dev-tools/containers/docker-run-local.sh new file mode 100755 index 000000000..05e23f4a0 --- /dev/null +++ b/contrib/dev-tools/containers/docker-run-local.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ + +docker run -it \ + --env USER_ID"$(id -u)" \ + --publish 6969:6969/udp \ + --publish 7070:7070/tcp \ + --publish 1212:1212/tcp \ + --volume ./storage/tracker/lib:/var/lib/torrust/tracker:rw \ + --volume ./storage/tracker/log:/var/log/torrust/tracker:rw \ + --volume ./storage/tracker/etc:/etc/torrust/tracker:rw \ + torrust-tracker:release diff --git a/contrib/dev-tools/containers/docker-run-public.sh b/contrib/dev-tools/containers/docker-run-public.sh new file mode 100755 index 000000000..73bcf600a --- /dev/null +++ b/contrib/dev-tools/containers/docker-run-public.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ + +docker run -it \ + --env USER_ID"$(id -u)" \ + --publish 6969:6969/udp \ + --publish 7070:7070/tcp \ + --publish 1212:1212/tcp \ + --volume ./storage/tracker/lib:/var/lib/torrust/tracker:rw \ + --volume ./storage/tracker/log:/var/log/torrust/tracker:rw \ + --volume ./storage/tracker/etc:/etc/torrust/tracker:rw \ + torrust/tracker:latest diff --git a/contrib/dev-tools/git/hooks/pre-commit.sh b/contrib/dev-tools/git/hooks/pre-commit.sh new file mode 100755 index 000000000..c1b183fde --- /dev/null +++ b/contrib/dev-tools/git/hooks/pre-commit.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +cargo +nightly fmt --check && + cargo +nightly check --tests --benches --examples --workspace --all-targets --all-features && + cargo +nightly doc --no-deps --bins --examples --workspace --all-features && + cargo +nightly machete && + cargo +stable build && + CARGO_INCREMENTAL=0 cargo +stable clippy --no-deps --tests --benches --examples --workspace --all-targets --all-features -- -D clippy::correctness -D clippy::suspicious -D clippy::complexity -D clippy::perf -D clippy::style -D clippy::pedantic && + cargo +stable test --doc --workspace && + cargo +stable test --tests --benches --examples --workspace --all-targets --all-features diff --git a/contrib/dev-tools/git/hooks/pre-push.sh b/contrib/dev-tools/git/hooks/pre-push.sh new file mode 100755 index 000000000..593068cee --- /dev/null +++ b/contrib/dev-tools/git/hooks/pre-push.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +cargo +nightly fmt --check && + cargo +nightly check --tests --benches --examples --workspace --all-targets --all-features && + cargo +nightly doc --no-deps --bins --examples --workspace --all-features && + cargo +nightly machete && + cargo +stable build && + CARGO_INCREMENTAL=0 cargo +stable clippy --no-deps --tests --benches --examples --workspace --all-targets --all-features -- -D clippy::correctness -D clippy::suspicious -D clippy::complexity -D clippy::perf -D clippy::style -D clippy::pedantic && + cargo +stable test --doc --workspace && + cargo +stable test --tests --benches --examples --workspace --all-targets --all-features && + cargo +stable run --bin e2e_tests_runner -- --config-toml-path "./share/default/config/tracker.e2e.container.sqlite3.toml" diff --git a/contrib/dev-tools/init/install-local.sh b/contrib/dev-tools/init/install-local.sh new file mode 100755 index 000000000..747c357bc --- /dev/null +++ b/contrib/dev-tools/init/install-local.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +# This script is only intended to be used for local development or testing environments. + +# Generate storage directory if it does not exist +mkdir -p ./storage/tracker/lib/database + +# Generate the sqlite database if it does not exist +if ! [ -f "./storage/tracker/lib/database/sqlite3.db" ]; then + sqlite3 ./storage/tracker/lib/database/sqlite3.db "VACUUM;" +fi diff --git a/contrib/dev-tools/su-exec/LICENSE b/contrib/dev-tools/su-exec/LICENSE new file mode 100644 index 000000000..f623b904e --- /dev/null +++ b/contrib/dev-tools/su-exec/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 ncopa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/contrib/dev-tools/su-exec/Makefile b/contrib/dev-tools/su-exec/Makefile new file mode 100644 index 000000000..bda768957 --- /dev/null +++ b/contrib/dev-tools/su-exec/Makefile @@ -0,0 +1,17 @@ + +CFLAGS ?= -Wall -Werror -g +LDFLAGS ?= + +PROG := su-exec +SRCS := $(PROG).c + +all: $(PROG) + +$(PROG): $(SRCS) + $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) + +$(PROG)-static: $(SRCS) + $(CC) $(CFLAGS) -o $@ $^ -static $(LDFLAGS) + +clean: + rm -f $(PROG) $(PROG)-static diff --git a/contrib/dev-tools/su-exec/README.md b/contrib/dev-tools/su-exec/README.md new file mode 100644 index 000000000..1dd4108ac --- /dev/null +++ b/contrib/dev-tools/su-exec/README.md @@ -0,0 +1,46 @@ +# su-exec + +switch user and group id, setgroups and exec + +## Purpose + +This is a simple tool that will simply execute a program with different +privileges. The program will be executed directly and not run as a child, +like su and sudo does, which avoids TTY and signal issues (see below). + +Notice that su-exec depends on being run by the root user, non-root +users do not have permission to change uid/gid. + +## Usage + +```shell +su-exec user-spec command [ arguments... ] +``` + +`user-spec` is either a user name (e.g. `nobody`) or user name and group +name separated with colon (e.g. `nobody:ftp`). Numeric uid/gid values +can be used instead of names. Example: + +```shell +su-exec apache:1000 /usr/sbin/httpd -f /opt/www/httpd.conf +``` + +## TTY & parent/child handling + +Notice how `su` will make `ps` be a child of a shell while `su-exec` +just executes `ps` directly. + +```shell +$ docker run -it --rm alpine:edge su postgres -c 'ps aux' +PID USER TIME COMMAND + 1 postgres 0:00 ash -c ps aux + 12 postgres 0:00 ps aux +$ docker run -it --rm -v $PWD/su-exec:/sbin/su-exec:ro alpine:edge su-exec postgres ps aux +PID USER TIME COMMAND + 1 postgres 0:00 ps aux +``` + +## Why reinvent gosu? + +This does more or less exactly the same thing as [gosu](https://github.com/tianon/gosu) +but it is only 10kb instead of 1.8MB. diff --git a/contrib/dev-tools/su-exec/su-exec.c b/contrib/dev-tools/su-exec/su-exec.c new file mode 100644 index 000000000..499071c6e --- /dev/null +++ b/contrib/dev-tools/su-exec/su-exec.c @@ -0,0 +1,109 @@ +/* set user and group id and exec */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +static char *argv0; + +static void usage(int exitcode) +{ + printf("Usage: %s user-spec command [args]\n", argv0); + exit(exitcode); +} + +int main(int argc, char *argv[]) +{ + char *user, *group, **cmdargv; + char *end; + + uid_t uid = getuid(); + gid_t gid = getgid(); + + argv0 = argv[0]; + if (argc < 3) + usage(0); + + user = argv[1]; + group = strchr(user, ':'); + if (group) + *group++ = '\0'; + + cmdargv = &argv[2]; + + struct passwd *pw = NULL; + if (user[0] != '\0') { + uid_t nuid = strtol(user, &end, 10); + if (*end == '\0') + uid = nuid; + else { + pw = getpwnam(user); + if (pw == NULL) + err(1, "getpwnam(%s)", user); + } + } + if (pw == NULL) { + pw = getpwuid(uid); + } + if (pw != NULL) { + uid = pw->pw_uid; + gid = pw->pw_gid; + } + + setenv("HOME", pw != NULL ? pw->pw_dir : "/", 1); + + if (group && group[0] != '\0') { + /* group was specified, ignore grouplist for setgroups later */ + pw = NULL; + + gid_t ngid = strtol(group, &end, 10); + if (*end == '\0') + gid = ngid; + else { + struct group *gr = getgrnam(group); + if (gr == NULL) + err(1, "getgrnam(%s)", group); + gid = gr->gr_gid; + } + } + + if (pw == NULL) { + if (setgroups(1, &gid) < 0) + err(1, "setgroups(%i)", gid); + } else { + int ngroups = 0; + gid_t *glist = NULL; + + while (1) { + int r = getgrouplist(pw->pw_name, gid, glist, &ngroups); + + if (r >= 0) { + if (setgroups(ngroups, glist) < 0) + err(1, "setgroups"); + break; + } + + glist = realloc(glist, ngroups * sizeof(gid_t)); + if (glist == NULL) + err(1, "malloc"); + } + } + + if (setgid(gid) < 0) + err(1, "setgid(%i)", gid); + + if (setuid(uid) < 0) + err(1, "setuid(%i)", uid); + + execvp(cmdargv[0], cmdargv); + err(1, "%s", cmdargv[0]); + + return 1; +} diff --git a/cspell.json b/cspell.json new file mode 100644 index 000000000..02f29f7f9 --- /dev/null +++ b/cspell.json @@ -0,0 +1,27 @@ +{ + "$schema": "https://raw.githubusercontent.com/streetsidesoftware/cspell/main/cspell.schema.json", + "version": "0.2", + "dictionaryDefinitions": [ + { + "name": "project-words", + "path": "./project-words.txt", + "addWords": true + } + ], + "dictionaries": [ + "project-words" + ], + "enableFiletypes": [ + "dockerfile", + "shellscript", + "toml" + ], + "ignorePaths": [ + "target", + "docs/media/*.svg", + "contrib/bencode/benches/*.bencode", + "contrib/dev-tools/su-exec/**", + ".github/labels.json", + "/project-words.txt" + ] +} \ No newline at end of file diff --git a/docker/README.md b/docker/README.md deleted file mode 100644 index e0fee61e7..000000000 --- a/docker/README.md +++ /dev/null @@ -1,261 +0,0 @@ -# Docker - -## Requirements - -- Docker version 20.10.21 -- You need to create the `storage` directory with this structure and files: - -```s -$ tree storage/ -storage/ -├── database -│   └── data.db -└── ssl_certificates - ├── localhost.crt - └── localhost.key -``` - -> NOTE: you only need the `ssl_certificates` directory and certificates in case you have enabled SSL for the one HTTP tracker or the API. - -## Dev environment - -When using docker you have to bind the exposed ports to the wildcard address `0.0.0.0`, so you can access the application from the host machine. - -The default API configuration uses `127.0.0.1`, so you have to change it to: - -```toml -[http_api] -bind_address = "0.0.0.0:1212" -``` - -Otherwise the API will be only accessible from inside the container. - -### With docker - -Build and run locally: - -```s -docker context use default -export TORRUST_TRACKER_USER_UID=1000 -./docker/bin/build.sh $TORRUST_TRACKER_USER_UID -./bin/install.sh -./docker/bin/run.sh $TORRUST_TRACKER_USER_UID -``` - -Run using the pre-built public docker image: - -```s -export TORRUST_TRACKER_USER_UID=1000 -docker run -it \ - --user="$TORRUST_TRACKER_USER_UID" \ - --publish 6969:6969/udp \ - --publish 7070:7070/tcp \ - --publish 1212:1212/tcp \ - --volume "$(pwd)/storage":"/app/storage" \ - torrust/tracker -``` - -> NOTES: -> -> - You have to create the SQLite DB (`data.db`) and configuration (`config.toml`) before running the tracker. See `bin/install.sh`. -> - You have to replace the user UID (`1000`) with yours. -> - Remember to switch to your default docker context `docker context use default`. - -### With docker-compose - -The docker-compose configuration includes the MySQL service configuration. If you want to use MySQL instead of SQLite you have to change your `config.toml` configuration: - -```toml -db_driver = "MySQL" -db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" -``` - -If you want to inject an environment variable into docker-compose you can use the file `.env`. There is a template `.env.local`. - -Build and run it locally: - -```s -docker compose up --build -``` - -After running the "up" command you will have two running containers: - -```s -$ docker ps -CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES -06feacb91a9e torrust-tracker "cargo run" 18 minutes ago Up 4 seconds 0.0.0.0:1212->1212/tcp, :::1212->1212/tcp, 0.0.0.0:7070->7070/tcp, :::7070->7070/tcp, 0.0.0.0:6969->6969/udp, :::6969->6969/udp torrust-tracker-1 -34d29e792ee2 mysql:8.0 "docker-entrypoint.s…" 18 minutes ago Up 5 seconds (healthy) 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp torrust-mysql-1 -``` - -And you should be able to use the application, for example making a request to the API: - - - -You can stop the containers with: - -```s -docker compose down -``` - -Additionally, you can delete all resources (containers, volumes, networks) with: - -```s -docker compose down -v -``` - -### Access Mysql with docker - -These are some useful commands for MySQL. - -Open a shell in the MySQL container using docker or docker-compose. - -```s -docker exec -it torrust-mysql-1 /bin/bash -docker compose exec mysql /bin/bash -``` - -Connect to MySQL from inside the MySQL container or from the host: - -```s -mysql -h127.0.0.1 -uroot -proot_secret_password -``` - -The when MySQL container is started the first time, it creates the database, user, and permissions needed. -If you see the error "Host is not allowed to connect to this MySQL server" you can check that users have the right permissions in the database. Make sure the user `root` and `db_user` can connect from any host (`%`). - -```s -mysql> SELECT host, user FROM mysql.user; -+-----------+------------------+ -| host | user | -+-----------+------------------+ -| % | db_user | -| % | root | -| localhost | mysql.infoschema | -| localhost | mysql.session | -| localhost | mysql.sys | -| localhost | root | -+-----------+------------------+ -6 rows in set (0.00 sec) -``` - -If the database, user or permissions are not created the reason could be the MySQL container volume can be corrupted. Delete it and start again the containers. - -### SSL Certificates - -You can use a certificate for localhost. You can create your [localhost certificate](https://letsencrypt.org/docs/certificates-for-localhost/#making-and-trusting-your-own-certificates) and use it in the `storage` folder and the configuration file (`config.toml`). For example: - -The storage folder must contain your certificates: - -```s -$ tree storage/ -storage/ -├── database -│   └── data.db -└── ssl_certificates - ├── localhost.crt - └── localhost.key -``` - -You have not enabled it in your `config.toml` file: - -```toml -... -[[http_trackers]] -enabled = true -bind_address = "0.0.0.0:7070" -ssl_enabled = true -ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -ssl_key_path = "./storage/ssl_certificates/localhost.key" - -[http_api] -enabled = true -bind_address = "0.0.0.0:1212" -ssl_enabled = true -ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -ssl_key_path = "./storage/ssl_certificates/localhost.key" -... -``` - -> NOTE: you can enable it independently for each HTTP tracker or the API. - -If you enable the SSL certificate for the API, for example, you can load the API with this URL: - - - -## Prod environment - -In this section, you will learn how to deploy the tracker to a single docker container in Azure Container Instances. - -> NOTE: Azure Container Instances is a solution when you want to run an isolated container. If you need full container orchestration, including service discovery across multiple containers, automatic scaling, and coordinated application upgrades, we recommend [Kubernetes](https://kubernetes.io/). - -Deploy to Azure Container Instance following [docker documentation](https://docs.docker.com/cloud/aci-integration/). - -You have to create the ACI context and the storage: - -```s -docker context create aci myacicontext -docker context use myacicontext -docker volume create test-volume --storage-account torrustracker -``` - -You need to create all the files needed by the application in the storage dir `storage/database`. - -And finally, you can run the container: - -```s -docker run \ - --publish 6969:6969/udp \ - --publish 7070:7070/tcp \ - --publish 1212:1212/tcp \ - --volume torrustracker/test-volume:/app/storage \ - registry.hub.docker.com/torrust/tracker:latest -``` - -Detach from container logs when the container starts. By default, the command line stays attached and follows container logs. - -```s -docker run \ - --detach - --publish 6969:6969/udp \ - --publish 7070:7070/tcp \ - --publish 1212:1212/tcp \latest - --volume torrustracker/test-volume:/app/storage \ - registry.hub.docker.com/torrust/tracker:latest -``` - -You should see something like this: - -```s -[+] Running 2/2 - â ¿ Group intelligent-hawking Created 5.0s - â ¿ intelligent-hawking Created 41.7s -2022-12-08T18:39:19.697869300+00:00 [torrust_tracker::logging][INFO] logging initialized. -2022-12-08T18:39:19.712651100+00:00 [torrust_tracker::jobs::udp_tracker][INFO] Starting UDP server on: 0.0.0.0:6969 -2022-12-08T18:39:19.712792700+00:00 [torrust_tracker::jobs::tracker_api][INFO] Starting Torrust API server on: 0.0.0.0:1212 -2022-12-08T18:39:19.725124+00:00 [torrust_tracker::jobs::tracker_api][INFO] Torrust API server started -``` - -You can see the container with: - -```s -$ docker ps -CONTAINER ID IMAGE COMMAND STATUS PORTS -intelligent-hawking registry.hub.docker.com/torrust/tracker:latest Running 4.236.213.57:6969->6969/udp, 4.236.213.57:1212->1212/tcp -``` - -After a while, you can use the tracker API `http://4.236.213.57:1212/api/v1/stats?token=MyAccessToken` and the UDP tracker with your BitTorrent client using this tracker announce URL `udp://4.236.213.57:6969`. - -> NOTES: -> -> - [There is no support for mounting a single file](https://docs.docker.com/cloud/aci-container-features/#persistent-volumes), or mounting a subfolder from an `Azure File Share`. -> - [ACI does not allow port mapping](https://docs.docker.com/cloud/aci-integration/#exposing-ports). -> - [Azure file share volume mount requires the Linux container run as root](https://learn.microsoft.com/en-us/azure/container-instances/container-instances-volume-azure-files#limitations). -> - It can take some minutes until the public IP for the ACI container is available. -> - You can use the Azure web UI to download files from the storage. For example, the SQLite database. -> - [It seems you can only expose web interfaces on port 80 on Azure Container Instances](https://stackoverflow.com/a/56768087/3012842). Not official documentation! - -## Links - -- [Deploying Docker containers on Azure](https://docs.docker.com/cloud/aci-integration/). -- [Docker run options for ACI containers](https://docs.docker.com/cloud/aci-container-features/). -- [Quickstart: Deploy a container instance in Azure using the Docker CLI](https://learn.microsoft.com/en-us/azure/container-instances/quickstart-docker-cli). diff --git a/docker/bin/build.sh b/docker/bin/build.sh deleted file mode 100755 index d77d1ad34..000000000 --- a/docker/bin/build.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -TORRUST_TRACKER_USER_UID=${TORRUST_TRACKER_USER_UID:-1000} -TORRUST_TRACKER_RUN_AS_USER=${TORRUST_TRACKER_RUN_AS_USER:-appuser} - -echo "Building docker image ..." -echo "TORRUST_TRACKER_USER_UID: $TORRUST_TRACKER_USER_UID" -echo "TORRUST_TRACKER_RUN_AS_USER: $TORRUST_TRACKER_RUN_AS_USER" - -docker build \ - --build-arg UID="$TORRUST_TRACKER_USER_UID" \ - --build-arg RUN_AS_USER="$TORRUST_TRACKER_RUN_AS_USER" \ - -t torrust-tracker . diff --git a/docker/bin/install.sh b/docker/bin/install.sh deleted file mode 100755 index a58969378..000000000 --- a/docker/bin/install.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash - -./docker/bin/build.sh -./bin/install.sh diff --git a/docker/bin/run.sh b/docker/bin/run.sh deleted file mode 100755 index 86465baeb..000000000 --- a/docker/bin/run.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -TORRUST_TRACKER_USER_UID=${TORRUST_TRACKER_USER_UID:-1000} -TORRUST_TRACKER_CONFIG=$(cat config.toml) - -docker run -it \ - --user="$TORRUST_TRACKER_USER_UID" \ - --publish 6969:6969/udp \ - --publish 7070:7070/tcp \ - --publish 1212:1212/tcp \ - --env TORRUST_TRACKER_CONFIG="$TORRUST_TRACKER_CONFIG" \ - --volume "$(pwd)/storage":"/app/storage" \ - torrust-tracker diff --git a/docs/adrs/20240227164834_use_plural_for_modules_containing_collections.md b/docs/adrs/20240227164834_use_plural_for_modules_containing_collections.md new file mode 100644 index 000000000..beb3cee00 --- /dev/null +++ b/docs/adrs/20240227164834_use_plural_for_modules_containing_collections.md @@ -0,0 +1,35 @@ +# Use plural for modules containing collections of types + +## Description + +In Rust, the naming conventions for module names (mod names) generally lean +towards using the singular form, rather than plurals. This practice aligns with +Rust's emphasis on clarity and precision in code organization. The idea is that +a module name should represent a single concept or functionality, which often +means using a singular noun to describe what the module contains or does. + +However, it's important to note that conventions can vary depending on the +context or the specific project. Some projects may choose to use plural forms +for module names if they feel it more accurately represents the contents of the +module. For example, a module that contains multiple implementations of a +similar concept or utility functions related to a specific theme might be named +in the plural to reflect the diversity of its contents. + +This could have some pros anc cons. For example, for a module containing types of +requests you could refer to a concrete request with `request::Announce` or +`requests::Announce`. If you read a code line `request::Announce` is probably +better. However, if you read the filed or folder name `requests`gives you a +better idea of what the modules contains. + +## Agreement + +We agree on use plural in cases where the modules contain some types with the +same type of responsibility. For example: + +- `src/servers`. +- `src/servers/http/v1/requests`. +- `src/servers/http/v1/responses`. +- `src/servers/http/v1/services`. +- Etcetera. + +We will change them progressively. diff --git a/docs/adrs/README.md b/docs/adrs/README.md new file mode 100644 index 000000000..85986fc36 --- /dev/null +++ b/docs/adrs/README.md @@ -0,0 +1,23 @@ +# Architectural Decision Records (ADRs) + +This directory contains the architectural decision records (ADRs) for the +project. ADRs are a way to document the architectural decisions made in the +project. + +More info: . + +## How to add a new record + +For the prefix: + +```s +date -u +"%Y%m%d%H%M%S" +``` + +Then you can create a new markdown file with the following format: + +```s +20230510152112_title.md +``` + +For the time being, we are not following any specific template. diff --git a/docs/benchmarking.md b/docs/benchmarking.md new file mode 100644 index 000000000..7d0228737 --- /dev/null +++ b/docs/benchmarking.md @@ -0,0 +1,303 @@ +# Benchmarking + +We have two types of benchmarking: + +- E2E benchmarking running the UDP tracker. +- Internal torrents repository benchmarking. + +## E2E benchmarking + +We are using the scripts provided by [aquatic](https://github.com/greatest-ape/aquatic). + +How to install both commands: + +```console +cargo install aquatic_udp_load_test && cargo install aquatic_http_load_test +``` + +You can also clone and build the repos. It's the way used for the results shown +in this documentation. + +```console +git clone git@github.com:greatest-ape/aquatic.git +cd aquatic +cargo build --release -p aquatic_udp_load_test +``` + +### Run UDP load test + +Run the tracker with UDP service enabled and other services disabled and set log threshold to `error`. + +```toml +[logging] +threshold = "error" + +[[udp_trackers]] +bind_address = "0.0.0.0:6969" +``` + +Build and run the tracker: + +```console +cargo build --release +TORRUST_TRACKER_CONFIG_TOML_PATH="./share/default/config/tracker.udp.benchmarking.toml" ./target/release/torrust-tracker +``` + +Run the load test with: + +```console +./target/release/aquatic_udp_load_test +``` + +> NOTICE: You need to modify the port in the `udp_load_test` crate to use `6969` and rebuild. + +Output: + +```output +Starting client with config: Config { + server_address: 127.0.0.1:6969, + log_level: Error, + workers: 1, + duration: 0, + summarize_last: 0, + extra_statistics: true, + network: NetworkConfig { + multiple_client_ipv4s: true, + sockets_per_worker: 4, + recv_buffer: 8000000, + }, + requests: RequestConfig { + number_of_torrents: 1000000, + number_of_peers: 2000000, + scrape_max_torrents: 10, + announce_peers_wanted: 30, + weight_connect: 50, + weight_announce: 50, + weight_scrape: 1, + peer_seeder_probability: 0.75, + }, +} + +Requests out: 398367.11/second +Responses in: 358530.40/second + - Connect responses: 177567.60 + - Announce responses: 177508.08 + - Scrape responses: 3454.72 + - Error responses: 0.00 +Peers per announce response: 0.00 +Announce responses per info hash: + - p10: 1 + - p25: 1 + - p50: 1 + - p75: 1 + - p90: 2 + - p95: 3 + - p99: 105 + - p99.9: 289 + - p100: 361 +``` + +> IMPORTANT: The performance of the Torrust UDP Tracker is drastically decreased with these log threshold: `info`, `debug`, `trace`. + +```output +Requests out: 40719.21/second +Responses in: 33762.72/second + - Connect responses: 16732.76 + - Announce responses: 16692.98 + - Scrape responses: 336.98 + - Error responses: 0.00 +Peers per announce response: 0.00 +Announce responses per info hash: + - p10: 1 + - p25: 1 + - p50: 1 + - p75: 1 + - p90: 7 + - p95: 14 + - p99: 27 + - p99.9: 35 + - p100: 45 +``` + +### Comparing UDP tracker with other Rust implementations + +#### Aquatic UDP Tracker + +Running the tracker: + +```console +git clone git@github.com:greatest-ape/aquatic.git +cd aquatic +cargo build --release -p aquatic_udp +./target/release/aquatic_udp -p > "aquatic-udp-config.toml" +./target/release/aquatic_udp -c "aquatic-udp-config.toml" +``` + +Run the load test with: + +```console +./target/release/aquatic_udp_load_test +``` + +```output +Requests out: 432896.42/second +Responses in: 389577.70/second + - Connect responses: 192864.02 + - Announce responses: 192817.55 + - Scrape responses: 3896.13 + - Error responses: 0.00 +Peers per announce response: 21.55 +Announce responses per info hash: + - p10: 1 + - p25: 1 + - p50: 1 + - p75: 1 + - p90: 2 + - p95: 3 + - p99: 105 + - p99.9: 311 + - p100: 395 +``` + +#### Torrust-Actix UDP Tracker + +Run the tracker with UDP service enabled and other services disabled and set log threshold to `error`. + +```toml +[logging] +threshold = "error" + +[[udp_trackers]] +bind_address = "0.0.0.0:6969" +``` + +```console +git clone https://github.com/Power2All/torrust-actix.git +cd torrust-actix +cargo build --release +./target/release/torrust-actix --create-config +./target/release/torrust-actix +``` + +Run the load test with: + +```console +./target/release/aquatic_udp_load_test +``` + +> NOTICE: You need to modify the port in the `udp_load_test` crate to use `6969` and rebuild. + +```output +Requests out: 200953.97/second +Responses in: 180858.14/second + - Connect responses: 89517.13 + - Announce responses: 89539.67 + - Scrape responses: 1801.34 + - Error responses: 0.00 +Peers per announce response: 1.00 +Announce responses per info hash: + - p10: 1 + - p25: 1 + - p50: 1 + - p75: 1 + - p90: 2 + - p95: 7 + - p99: 87 + - p99.9: 155 + - p100: 188 +``` + +### Results + +Announce request per second: + +| Tracker | Announce | +|---------------|-----------| +| Aquatic | 192,817 | +| Torrust | 177,508 | +| Torrust-Actix | 89,539 | + +Using a PC with: + +- RAM: 64GiB +- Processor: AMD Ryzen 9 7950X x 32 +- Graphics: AMD Radeon Graphics / Intel Arc A770 Graphics (DG2) +- OS: Ubuntu 23.04 +- OS Type: 64-bit +- Kernel Version: Linux 6.2.0-20-generic + +## Repository benchmarking + +### Requirements + +You need to install the `gnuplot` package. + +```console +sudo apt install gnuplot +``` + +### Run + +You can run it with: + +```console +cargo bench -p torrust-tracker-torrent-repository +``` + +It tests the different implementations for the internal torrent storage. The output should be something like this: + +```output + Running benches/repository_benchmark.rs (target/release/deps/repository_benchmark-2f7830898bbdfba4) +add_one_torrent/RwLockStd + time: [60.936 ns 61.383 ns 61.764 ns] +Found 24 outliers among 100 measurements (24.00%) + 15 (15.00%) high mild + 9 (9.00%) high severe +add_one_torrent/RwLockStdMutexStd + time: [60.829 ns 60.937 ns 61.053 ns] +Found 1 outliers among 100 measurements (1.00%) + 1 (1.00%) high severe +add_one_torrent/RwLockStdMutexTokio + time: [96.034 ns 96.243 ns 96.545 ns] +Found 6 outliers among 100 measurements (6.00%) + 4 (4.00%) high mild + 2 (2.00%) high severe +add_one_torrent/RwLockTokio + time: [108.25 ns 108.66 ns 109.06 ns] +Found 2 outliers among 100 measurements (2.00%) + 2 (2.00%) low mild +add_one_torrent/RwLockTokioMutexStd + time: [109.03 ns 109.11 ns 109.19 ns] +Found 4 outliers among 100 measurements (4.00%) + 1 (1.00%) low mild + 1 (1.00%) high mild + 2 (2.00%) high severe +Benchmarking add_one_torrent/RwLockTokioMutexTokio: Collecting 100 samples in estimated 1.0003 s (7.1M iterationsadd_one_torrent/RwLockTokioMutexTokio + time: [139.64 ns 140.11 ns 140.62 ns] +``` + +After running it you should have a new directory containing the criterion reports: + +```console +target/criterion/ +├── add_multiple_torrents_in_parallel +├── add_one_torrent +├── report +├── update_multiple_torrents_in_parallel +└── update_one_torrent_in_parallel +``` + +You can see one report for each of the operations we are considering for benchmarking: + +- Add multiple torrents in parallel. +- Add one torrent. +- Update multiple torrents in parallel. +- Update one torrent in parallel. + +Each report look like the following: + +![Torrent repository implementations benchmarking report](./media/torrent-repository-implementations-benchmarking-report.png) + +## Other considerations + +If you are interested in knowing more about the tracker performance or contribute to improve its performance you ca join the [performance optimizations discussion](https://github.com/torrust/torrust-tracker/discussions/774). diff --git a/docs/containers.md b/docs/containers.md new file mode 100644 index 000000000..cddd2ba98 --- /dev/null +++ b/docs/containers.md @@ -0,0 +1,440 @@ +# Containers (Docker or Podman) + +## Demo environment + +It is simple to setup the tracker with the default +configuration and run it using the pre-built public docker image: + +With Docker: + +```sh +docker run -it torrust/tracker:latest +``` + +or with Podman: + +```sh +podman run -it docker.io/torrust/tracker:latest +``` + +## Requirements + +- Tested with recent versions of Docker or Podman. + +## Volumes + +The [Containerfile](../Containerfile) (i.e. the Dockerfile) Defines Three Volumes: + +```Dockerfile +VOLUME ["/var/lib/torrust/tracker","/var/log/torrust/tracker","/etc/torrust/tracker"] +``` + +When instancing the container image with the `docker run` or `podman run` command, we map these volumes to the local storage: + +```s +./storage/tracker/lib -> /var/lib/torrust/tracker +./storage/tracker/log -> /var/log/torrust/tracker +./storage/tracker/etc -> /etc/torrust/tracker +``` + +> NOTE: You can adjust this mapping for your preference, however this mapping is the default in our guides and scripts. + +### Pre-Create Host-Mapped Folders + +Please run this command where you wish to run the container: + +```sh +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ +``` + +### Matching Ownership ID's of Host Storage and Container Volumes + +It is important that the `torrust` user has the same uid `$(id -u)` as the host mapped folders. In our [entry script](../share/container/entry_script_sh), installed to `/usr/local/bin/entry.sh` inside the container, switches to the `torrust` user created based upon the `USER_UID` environmental variable. + +When running the container, you may use the `--env USER_ID="$(id -u)"` argument that gets the current user-id and passes to the container. + +### Mapped Tree Structure + +Using the standard mapping defined above produces this following mapped tree: + +```s +storage/tracker/ +├── lib +│ ├── database +│ │   └── sqlite3.db => /var/lib/torrust/tracker/database/sqlite3.db [auto populated] +│ └── tls +│ ├── localhost.crt => /var/lib/torrust/tracker/tls/localhost.crt [user supplied] +│ └── localhost.key => /var/lib/torrust/tracker/tls/localhost.key [user supplied] +├── log => /var/log/torrust/tracker (future use) +└── etc + └── tracker.toml => /etc/torrust/tracker/tracker.toml [auto populated] +``` + +> NOTE: you only need the `tls` directory and certificates in case you have enabled SSL. + +## Building the Container + +### Clone and Change into Repository + +```sh +# Inside your dev folder +git clone https://github.com/torrust/torrust-tracker.git; cd torrust-tracker +``` + +### (Docker) Setup Context + +Before starting, if you are using docker, it is helpful to reset the context to the default: + +```sh +docker context use default +``` + +### (Docker) Build + +```sh +# Release Mode +docker build --target release --tag torrust-tracker:release --file Containerfile . + +# Debug Mode +docker build --target debug --tag torrust-tracker:debug --file Containerfile . +``` + +### (Podman) Build + +```sh +# Release Mode +podman build --target release --tag torrust-tracker:release --file Containerfile . + +# Debug Mode +podman build --target debug --tag torrust-tracker:debug --file Containerfile . +``` + +## Running the Container + +### Basic Run + +No arguments are needed for simply checking the container image works: + +#### (Docker) Run Basic + +```sh +# Release Mode +docker run -it torrust-tracker:release + +# Debug Mode +docker run -it torrust-tracker:debug +``` + +#### (Podman) Run Basic + +```sh +# Release Mode +podman run -it docker.io/torrust-tracker:release + +# Debug Mode +podman run -it docker.io/torrust-tracker:debug +``` + +### Arguments + +The arguments need to be placed before the image tag. i.e. + +`run [arguments] torrust-tracker:release` + +#### Environmental Variables + +Environmental variables are loaded through the `--env`, in the format `--env VAR="value"`. + +The following environmental variables can be set: + +- `TORRUST_TRACKER_CONFIG_TOML_PATH` - The in-container path to the tracker configuration file, (default: `"/etc/torrust/tracker/tracker.toml"`). +- `TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN` - Override of the admin token. If set, this value overrides any value set in the config. +- `TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER` - The database type used for the container, (options: `sqlite3`, `mysql`, default `sqlite3`). Please Note: This dose not override the database configuration within the `.toml` config file. +- `TORRUST_TRACKER_CONFIG_TOML` - Load config from this environmental variable instead from a file, (i.e: `TORRUST_TRACKER_CONFIG_TOML=$(cat tracker-tracker.toml)`). +- `USER_ID` - The user id for the runtime crated `torrust` user. Please Note: This user id should match the ownership of the host-mapped volumes, (default `1000`). +- `UDP_PORT` - The port for the UDP tracker. This should match the port used in the configuration, (default `6969`). +- `HTTP_PORT` - The port for the HTTP tracker. This should match the port used in the configuration, (default `7070`). +- `API_PORT` - The port for the tracker API. This should match the port used in the configuration, (default `1212`). +- `HEALTH_CHECK_API_PORT` - The port for the Health Check API. This should match the port used in the configuration, (default `1313`). + +### Sockets + +Socket ports used internally within the container can be mapped to with the `--publish` argument. + +The format is: `--publish [optional_host_ip]:[host_port]:[container_port]/[optional_protocol]`, for example: `--publish 127.0.0.1:8080:80/tcp`. + +The default ports can be mapped with the following: + +```s +--publish 0.0.0.0:7070:7070/tcp \ +--publish 0.0.0.0:6969:6969/udp \ +--publish 0.0.0.0:1212:1212/tcp \ +``` + +> NOTE: Inside the container it is necessary to expose a socket with the wildcard address `0.0.0.0` so that it may be accessible from the host. Verify that the configuration that the sockets are wildcard. + +### Host-mapped Volumes + +By default the container will use install volumes for `/var/lib/torrust/tracker`, `/var/log/torrust/tracker`, and `/etc/torrust/tracker`, however for better administration it good to make these volumes host-mapped. + +The argument to host-map volumes is `--volume`, with the format: `--volume=[host-src:]container-dest[:]`. + +The default mapping can be supplied with the following arguments: + +```s +--volume ./storage/tracker/lib:/var/lib/torrust/tracker:Z \ +--volume ./storage/tracker/log:/var/log/torrust/tracker:Z \ +--volume ./storage/tracker/etc:/etc/torrust/tracker:Z \ +``` + +Please not the `:Z` at the end of the podman `--volume` mapping arguments, this is to give read-write permission on SELinux enabled systemd, if this doesn't work on your system, you can use `:rw` instead. + +## Complete Example + +### With Docker + +```sh +## Setup Docker Default Context +docker context use default + +## Build Container Image +docker build --target release --tag torrust-tracker:release --file Containerfile . + +## Setup Mapped Volumes +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ + +## Run Torrust Tracker Container Image +docker run -it \ + --env TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN="MySecretToken" \ + --env USER_ID="$(id -u)" \ + --publish 0.0.0.0:7070:7070/tcp \ + --publish 0.0.0.0:6969:6969/udp \ + --publish 0.0.0.0:1212:1212/tcp \ + --volume ./storage/tracker/lib:/var/lib/torrust/tracker:Z \ + --volume ./storage/tracker/log:/var/log/torrust/tracker:Z \ + --volume ./storage/tracker/etc:/etc/torrust/tracker:Z \ + torrust-tracker:release +``` + +### With Podman + +```sh +## Build Container Image +podman build --target release --tag torrust-tracker:release --file Containerfile . + +## Setup Mapped Volumes +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ + +## Run Torrust Tracker Container Image +podman run -it \ + --env TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN="MySecretToken" \ + --env USER_ID="$(id -u)" \ + --publish 0.0.0.0:7070:7070/tcp \ + --publish 0.0.0.0:6969:6969/udp \ + --publish 0.0.0.0:1212:1212/tcp \ + --volume ./storage/tracker/lib:/var/lib/torrust/tracker:Z \ + --volume ./storage/tracker/log:/var/log/torrust/tracker:Z \ + --volume ./storage/tracker/etc:/etc/torrust/tracker:Z \ + docker.io/torrust-tracker:release +``` + +## Docker Compose + +The docker-compose configuration includes the MySQL service configuration. If you want to use MySQL instead of SQLite you should verify the `/etc/torrust/tracker/tracker.toml` (i.e `./storage/tracker/etc/tracker.toml`) configuration: + +```toml +[core.database] +driver = "mysql" +path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" +``` + +### Build and Run: + +```sh +docker build --target release --tag torrust-tracker:release --file Containerfile . + +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ + +USER_ID=$(id -u) \ + TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN="MySecretToken" \ + docker compose up --build +``` + +After running the `compose up` command you will have two running containers: + +```s +$ docker ps +CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES +06feacb91a9e torrust-tracker "cargo run" 18 minutes ago Up 4 seconds 0.0.0.0:1212->1212/tcp, :::1212->1212/tcp, 0.0.0.0:7070->7070/tcp, :::7070->7070/tcp, 0.0.0.0:6969->6969/udp, :::6969->6969/udp torrust-tracker-1 +34d29e792ee2 mysql:8.0 "docker-entrypoint.s…" 18 minutes ago Up 5 seconds (healthy) 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp torrust-mysql-1 +``` + +And you should be able to use the application, for example making a request to the API: + + + +You can stop the containers with: + +```s +docker compose down +``` + +Additionally, you can delete all resources (containers, volumes, networks) with: + +```s +docker compose down -v +``` + +### Access Mysql with docker + +These are some useful commands for MySQL. + +Open a shell in the MySQL container using docker or docker-compose. + +```s +docker exec -it torrust-mysql-1 /bin/bash +docker compose exec mysql /bin/bash +``` + +Connect to MySQL from inside the MySQL container or from the host: + +```s +mysql -h127.0.0.1 -uroot -proot_secret_password +``` + +The when MySQL container is started the first time, it creates the database, user, and permissions needed. +If you see the error "Host is not allowed to connect to this MySQL server" you can check that users have the right permissions in the database. Make sure the user `root` and `db_user` can connect from any host (`%`). + +```s +mysql> SELECT host, user FROM mysql.user; ++-----------+------------------+ +| host | user | ++-----------+------------------+ +| % | db_user | +| % | root | +| localhost | mysql.infoschema | +| localhost | mysql.session | +| localhost | mysql.sys | +| localhost | root | ++-----------+------------------+ +6 rows in set (0.00 sec) +``` + +If the database, user or permissions are not created the reason could be the MySQL container volume can be corrupted. Delete it and start again the containers. + +### SSL Certificates + +You can use a certificate for localhost. You can create your [localhost certificate](https://letsencrypt.org/docs/certificates-for-localhost/#making-and-trusting-your-own-certificates) and use it in the `storage` folder and the configuration file (`tracker.toml`). For example: + +The storage folder must contain your certificates: + +```s +storage/tracker/lib/tls + ├── localhost.crt + └── localhost.key +storage/http_api/lib/tls + ├── localhost.crt + └── localhost.key +``` + +You have not enabled it in your `tracker.toml` file: + +```toml +[http_trackers.tsl_config] +ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" +ssl_key_path = "./storage/tracker/lib/tls/localhost.key" + +[http_api.tsl_config] +ssl_cert_path = "./storage/http_api/lib/tls/localhost.crt" +ssl_key_path = "./storage/http_api/lib/tls/localhost.key" +``` + +> NOTE: you can enable it independently for each HTTP tracker or the API. + +If you enable the SSL certificate for the API, for example, you can load the API with this URL: + + + +## Prod environment + +In this section, you will learn how to deploy the tracker to a single docker container in Azure Container Instances. + +> NOTE: Azure Container Instances is a solution when you want to run an isolated container. If you need full container orchestration, including service discovery across multiple containers, automatic scaling, and coordinated application upgrades, we recommend [Kubernetes](https://kubernetes.io/). + +Deploy to Azure Container Instance following [docker documentation](https://docs.docker.com/cloud/aci-integration/). + +You have to create the ACI context and the storage: + +```s +docker context create aci myacicontext +docker context use myacicontext +docker volume create test-volume --storage-account torrustracker +``` + +You need to create all the files needed by the application in the storage dir `storage/lib/database`. + +And finally, you can run the container: + +```s +docker run \ + --env USER_ID="$(id -u)" \ + --publish 6969:6969/udp \ + --publish 7070:7070/tcp \ + --publish 1212:1212/tcp \ + --volume torrustracker/lib:/var/lib/torrust/tracker:rw \ + --volume torrustracker/log:/var/log/torrust/tracker:rw \ + --volume torrustracker/etc:/etc/torrust/tracker:rw \ + registry.hub.docker.com/torrust/tracker:latest +``` + +Detach from container logs when the container starts. By default, the command line stays attached and follows container logs. + +```s +docker run \ + --detach + --env USER_ID="$(id -u)" \ + --publish 6969:6969/udp \ + --publish 7070:7070/tcp \ + --publish 1212:1212/tcp \latest + --volume torrustracker/lib:/var/lib/torrust/tracker:rw \ + --volume torrustracker/log:/var/log/torrust/tracker:rw \ + --volume torrustracker/etc:/etc/torrust/tracker:rw \ + registry.hub.docker.com/torrust/tracker:latest +``` + +You should see something like this: + +```s +[+] Running 2/2 + â ¿ Group intelligent-hawking Created 5.0s + â ¿ intelligent-hawking Created 41.7s +2022-12-08T18:39:19.697869300+00:00 [torrust_tracker::logging][INFO] logging initialized. +2022-12-08T18:39:19.712651100+00:00 [torrust_tracker::jobs::udp_tracker][INFO] Starting UDP server on: 0.0.0.0:6969 +2022-12-08T18:39:19.712792700+00:00 [torrust_tracker::jobs::tracker_api][INFO] Starting Torrust API server on: 0.0.0.0:1212 +2022-12-08T18:39:19.725124+00:00 [torrust_tracker::jobs::tracker_api][INFO] Torrust API server started +``` + +You can see the container with: + +```s +$ docker ps +CONTAINER ID IMAGE COMMAND STATUS PORTS +intelligent-hawking registry.hub.docker.com/torrust/tracker:latest Running 4.236.213.57:6969->6969/udp, 4.236.213.57:1212->1212/tcp +``` + +After a while, you can use the tracker API `http://4.236.213.57:1212/api/v1/stats?token=MyAccessToken` and the UDP tracker with your BitTorrent client using this tracker announce URL `udp://4.236.213.57:6969`. + +> NOTES: +> +> - [There is no support for mounting a single file](https://docs.docker.com/cloud/aci-container-features/#persistent-volumes), or mounting a subfolder from an `Azure File Share`. +> - [ACI does not allow port mapping](https://docs.docker.com/cloud/aci-integration/#exposing-ports). +> - [Azure file share volume mount requires the Linux container run as root](https://learn.microsoft.com/en-us/azure/container-instances/container-instances-volume-azure-files#limitations). +> - It can take some minutes until the public IP for the ACI container is available. +> - You can use the Azure web UI to download files from the storage. For example, the SQLite database. +> - [It seems you can only expose web interfaces on port 80 on Azure Container Instances](https://stackoverflow.com/a/56768087/3012842). Not official documentation! + +## Links + +- [Deploying Docker containers on Azure](https://docs.docker.com/cloud/aci-integration/). +- [Docker run options for ACI containers](https://docs.docker.com/cloud/aci-container-features/). +- [Quickstart: Deploy a container instance in Azure using the Docker CLI](https://learn.microsoft.com/en-us/azure/container-instances/quickstart-docker-cli). diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 000000000..873f3758b --- /dev/null +++ b/docs/index.md @@ -0,0 +1,11 @@ +# Torrust Tracker Documentation + +For more detailed instructions, please view our [crate documentation][docs]. + +- [Benchmarking](benchmarking.md) +- [Containers](containers.md) +- [Packages](packages.md) +- [Profiling](profiling.md) +- [Releases process](release_process.md) + +[docs]: https://docs.rs/torrust-tracker/latest/torrust_tracker/ diff --git a/docs/issues/523-internal-linting-tool.md b/docs/issues/523-internal-linting-tool.md new file mode 100644 index 000000000..14593e190 --- /dev/null +++ b/docs/issues/523-internal-linting-tool.md @@ -0,0 +1,141 @@ +# Issue #523 Implementation Plan (Internal Linting Tool) + +## Goal + +Replace the MegaLinter idea with Torrust internal linting tooling and integrate it into CI for this repository. + +## Scope + +- Target issue: https://github.com/torrust/torrust-tracker/issues/523 +- CI workflow to modify: .github/workflows/testing.yaml +- External reference workflow: https://raw.githubusercontent.com/torrust/torrust-tracker-deployer/refs/heads/main/.github/workflows/linting.yml + +## Tasks + +### 0) Create a local branch following GitHub branch naming conventions + +- Approved branch name: `523-internal-linting-tool` +- Commands: + - `git fetch --all --prune` + - `git checkout develop` + - `git pull --ff-only` + - `git checkout -b 523-internal-linting-tool` +- Checkpoint: + - `git branch --show-current` should output `523-internal-linting-tool`. + +### 1) Install and run the linting tool locally; verify it passes in this repo + +- Identify/install internal linting package/tool used by Torrust (likely `torrust-linting` or equivalent wrapper). +- Ensure local runtime dependencies are present (if any). +- Note: linter config files (step 2) must exist in the repo root before a full suite run; it is fine to do a first exploratory run first to discover which linters are active. +- Run the internal linting command against this repository. +- Capture the exact command and output summary for reproducibility. +- Checkpoint: + - Linting command exits with code `0`. + +### 2) Add and adapt linter configuration files + +Some linters require a config file in the repo root. Use the deployer configs as reference and adapt values to this repository. + +| File | Linter | Reference | +| -------------------- | ---------------- | ----------------------------------------------------------------------------------------------------- | +| `.markdownlint.json` | markdownlint | https://raw.githubusercontent.com/torrust/torrust-tracker-deployer/refs/heads/main/.markdownlint.json | +| `.taplo.toml` | taplo (TOML fmt) | https://raw.githubusercontent.com/torrust/torrust-tracker-deployer/refs/heads/main/.taplo.toml | +| `.yamllint-ci.yml` | yamllint | https://raw.githubusercontent.com/torrust/torrust-tracker-deployer/refs/heads/main/.yamllint-ci.yml | + +Key adaptations to make per file: + +- `.markdownlint.json`: review line-length rules and Markdown conventions used in this repo's docs. +- `.taplo.toml`: update `exclude` list to match this repo's generated/runtime folders (e.g. `target/**`, `storage/**`) instead of the deployer-specific ones (`build/**`, `data/**`, `envs/**`). +- `.yamllint-ci.yml`: update `ignore` block to reflect this repo's generated/runtime directories instead of cloud-init and deployer folders. + +Commit message: `ci(lint): add linter config files (.markdownlint.json, .taplo.toml, .yamllint-ci.yml)` + +Checkpoint: + +- Config files are present in the repo root. +- Running each individual linter against the repo with the config produces expected/controlled output. + +### 3) If local linting fails, fix all lint errors; commit fixes independently per linter + +- If the linting suite reports failures: + - Group findings by linter (for example: formatting, clippy, docs, spelling, yaml, etc.). + - Fix only one linter category at a time. + - Create one commit per linter category. +- Commit style proposal: + - `fix(lint/): resolve ` +- Constraints: + - Do not mix workflow/tooling changes with source lint fixes in the same commit. + - Keep each commit minimal and reviewable. +- Checkpoint: + - Re-run linting suite; all checks pass before moving to workflow integration. + +### 4) Review existing workflow example using internal linting + +- Read and analyze: + - https://raw.githubusercontent.com/torrust/torrust-tracker-deployer/refs/heads/main/.github/workflows/linting.yml +- Extract and adapt: + - Trigger strategy. + - Tool setup/install method. + - Cache strategy. + - Invocation command and CI fail behavior. +- Checkpoint: + - Document a short mapping from deployer workflow pattern to this repo’s `testing.yaml` job structure. + +### 5) Modify `.github/workflows/testing.yaml` to use the internal linting tool + +- Update the current `check`/lint-related section to run the internal linting command. +- Replace existing lint/check execution path with the internal linting tool in this migration (no parallel transition mode). +- Ensure matrix/toolchain compatibility is explicit (nightly/stable behavior decided and documented). +- Validate workflow syntax before commit. +- Checkpoint: + - Workflow is valid and executes linting through internal tool. + +### 6) Commit workflow changes + +- Commit only workflow-related changes in a dedicated commit. +- Commit message proposal: + - `ci(lint): switch testing workflow to internal linting tool` +- Checkpoint: + - `git show --name-only --stat HEAD` includes only expected workflow files (and any required supporting CI files if intentionally added). + +### 7) Push to remote `josecelano` and open PR into `develop` + +- Verify remote exists: + - `git remote -v` +- Push branch: + - `git push -u josecelano 523-internal-linting-tool` +- Open PR targeting `torrust/torrust-tracker:develop` with head `josecelano:523-internal-linting-tool`. +- PR content should include: + - Why internal linting over MegaLinter. + - Summary of lint-fix commits by linter. + - Summary of workflow change. + - Evidence (local run + CI status). +- Checkpoint: + - PR is open, linked to issue #523, and ready for review. + +## Execution Notes + +- Keep PR review-friendly by separating commits by concern: + 1. Linter config files (step 2) + 2. Per-linter source fixes (step 3, only if needed) + 3. CI workflow migration (step 6) +- Use Conventional Commits for all commits in this implementation. +- If lint checks differ between local and CI, align tool versions and execution flags before merging. +- Avoid broad refactors unrelated to lint failures. + +## Decisions Confirmed + +1. Branch name: `523-internal-linting-tool`. +2. CI strategy: replace existing lint/check path with internal linting. +3. Commit convention: yes, use Conventional Commits. +4. PR target: base `torrust/torrust-tracker:develop`, head `josecelano:523-internal-linting-tool`. + +## Risks and Mitigations + +- Risk: Internal linting wrapper may not be version-pinned and may produce unstable CI behavior. + - Mitigation: Pin tool version in workflow installation step. +- Risk: Internal linting may overlap with existing checks, increasing CI time. + - Mitigation: Remove redundant jobs only after verifying coverage parity. +- Risk: Tool may require secrets or environment assumptions not available in CI. + - Mitigation: Run dry-run in GitHub Actions on branch before requesting review. diff --git a/docs/licenses/LICENSE-AGPL_3_0 b/docs/licenses/LICENSE-AGPL_3_0 new file mode 100644 index 000000000..2beb9e163 --- /dev/null +++ b/docs/licenses/LICENSE-AGPL_3_0 @@ -0,0 +1,662 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. + diff --git a/docs/licenses/LICENSE-MIT_0 b/docs/licenses/LICENSE-MIT_0 new file mode 100644 index 000000000..fc06cc4fe --- /dev/null +++ b/docs/licenses/LICENSE-MIT_0 @@ -0,0 +1,14 @@ +MIT No Attribution + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/docs/media/demo/torrust-tracker-grafana-dashboard.png b/docs/media/demo/torrust-tracker-grafana-dashboard.png new file mode 100644 index 000000000..090932a8c Binary files /dev/null and b/docs/media/demo/torrust-tracker-grafana-dashboard.png differ diff --git a/docs/media/flamegraph.svg b/docs/media/flamegraph.svg new file mode 100644 index 000000000..58387ee06 --- /dev/null +++ b/docs/media/flamegraph.svg @@ -0,0 +1,491 @@ +Flame Graph Reset ZoomSearch merge_sched_in (93 samples, 0.02%)event_sched_in (68 samples, 0.02%)perf_ibs_add (50 samples, 0.01%)perf_ibs_start (41 samples, 0.01%)ctx_sched_in (117 samples, 0.03%)visit_groups_merge.constprop.0.isra.0 (114 samples, 0.03%)finish_task_switch.isra.0 (122 samples, 0.03%)__perf_event_task_sched_in (119 samples, 0.03%)profiling (170 samples, 0.04%)ret_from_fork (126 samples, 0.03%)schedule_tail (126 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (81 samples, 0.02%)[[vdso]] (750 samples, 0.20%)<torrust_tracker::shared::crypto::ephemeral_instance_keys::RANDOM_SEED as core::ops::deref::Deref>::deref::__stability::LAZY (889 samples, 0.23%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (99 samples, 0.03%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (94 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (84 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<BorrowType,K,V>::init_front (62 samples, 0.02%)[[vdso]] (968 samples, 0.26%)__GI___clock_gettime (58 samples, 0.02%)__memcpy_avx512_unaligned_erms (143 samples, 0.04%)_int_free (38 samples, 0.01%)_int_malloc (178 samples, 0.05%)core::ptr::drop_in_place<[core::option::Option<core::task::wake::Waker>: 32]> (39 samples, 0.01%)epoll_wait (676 samples, 0.18%)tokio::runtime::context::with_scheduler (85 samples, 0.02%)core::option::Option<T>::map (65 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (60 samples, 0.02%)mio::poll::Poll::poll (84 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select (84 samples, 0.02%)tokio::runtime::io::driver::Driver::turn (164 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (48 samples, 0.01%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (76 samples, 0.02%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (50 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (113 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (415 samples, 0.11%)core::sync::atomic::AtomicUsize::fetch_add (410 samples, 0.11%)core::sync::atomic::atomic_add (410 samples, 0.11%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (475 samples, 0.13%)tokio::runtime::driver::Handle::unpark (40 samples, 0.01%)tokio::runtime::driver::IoHandle::unpark (40 samples, 0.01%)__entry_text_start (99 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (180 samples, 0.05%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (169 samples, 0.04%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark_condvar (124 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (123 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (60 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::remove (53 samples, 0.01%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (53 samples, 0.01%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (122 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (75 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (287 samples, 0.08%)tokio::runtime::scheduler::multi_thread::park::Parker::park (232 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Inner::park (232 samples, 0.06%)core::cell::RefCell<T>::borrow_mut (67 samples, 0.02%)core::cell::RefCell<T>::try_borrow_mut (67 samples, 0.02%)core::cell::BorrowRefMut::new (67 samples, 0.02%)tokio::runtime::coop::budget (86 samples, 0.02%)tokio::runtime::coop::with_budget (86 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (80 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (372 samples, 0.10%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_searching (240 samples, 0.06%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::transition_worker_from_searching (133 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (103 samples, 0.03%)tokio::runtime::task::harness::Harness<T,S>::dealloc (46 samples, 0.01%)core::mem::drop (41 samples, 0.01%)core::ptr::drop_in_place<alloc::boxed::Box<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (41 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::end_processing_scheduled_tasks (77 samples, 0.02%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (210 samples, 0.06%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (210 samples, 0.06%)core::slice::<impl [T]>::contains (521 samples, 0.14%)<T as core::slice::cmp::SliceContains>::slice_contains (521 samples, 0.14%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (521 samples, 0.14%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (125 samples, 0.03%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (125 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (586 samples, 0.15%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (617 samples, 0.16%)tokio::runtime::scheduler::multi_thread::worker::Context::park (767 samples, 0.20%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (115 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_if_work_pending (78 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::is_empty (56 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::is_empty (52 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::len (45 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (38 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (105 samples, 0.03%)core::num::<impl u32>::wrapping_add (129 samples, 0.03%)core::sync::atomic::AtomicU64::compare_exchange (138 samples, 0.04%)core::sync::atomic::atomic_compare_exchange (138 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::pack (311 samples, 0.08%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (745 samples, 0.20%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (778 samples, 0.21%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (821 samples, 0.22%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (2,036 samples, 0.54%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (2,036 samples, 0.54%)tokio::runtime::scheduler::multi_thread::worker::run (2,036 samples, 0.54%)tokio::runtime::context::runtime::enter_runtime (2,036 samples, 0.54%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (2,036 samples, 0.54%)tokio::runtime::context::set_scheduler (2,036 samples, 0.54%)std::thread::local::LocalKey<T>::with (2,036 samples, 0.54%)std::thread::local::LocalKey<T>::try_with (2,036 samples, 0.54%)tokio::runtime::context::set_scheduler::{{closure}} (2,036 samples, 0.54%)tokio::runtime::context::scoped::Scoped<T>::set (2,036 samples, 0.54%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (2,036 samples, 0.54%)tokio::runtime::scheduler::multi_thread::worker::Context::run (2,036 samples, 0.54%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (2,422 samples, 0.64%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (2,422 samples, 0.64%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (58 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (58 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::poll (2,584 samples, 0.68%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (160 samples, 0.04%)tokio::runtime::task::core::Core<T,S>::set_stage (138 samples, 0.04%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (2,724 samples, 0.72%)tokio::runtime::task::harness::poll_future::{{closure}} (2,724 samples, 0.72%)tokio::runtime::task::core::Core<T,S>::store_output (140 samples, 0.04%)tokio::runtime::task::harness::poll_future (2,796 samples, 0.74%)std::panic::catch_unwind (2,788 samples, 0.74%)std::panicking::try (2,788 samples, 0.74%)std::panicking::try::do_call (2,784 samples, 0.74%)core::mem::manually_drop::ManuallyDrop<T>::take (60 samples, 0.02%)core::ptr::read (60 samples, 0.02%)tokio::runtime::task::raw::poll (2,887 samples, 0.76%)tokio::runtime::task::harness::Harness<T,S>::poll (2,876 samples, 0.76%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (2,876 samples, 0.76%)tokio::runtime::task::state::State::transition_to_running (74 samples, 0.02%)tokio::runtime::task::state::State::fetch_update_action (74 samples, 0.02%)core::array::<impl core::default::Default for [T: 32]>::default (83 samples, 0.02%)tokio::runtime::time::wheel::Wheel::poll (58 samples, 0.02%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (325 samples, 0.09%)tokio::runtime::time::Driver::park_internal (147 samples, 0.04%)tokio::runtime::time::wheel::Wheel::next_expiration (53 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (43 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (112 samples, 0.03%)alloc::vec::from_elem (42 samples, 0.01%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (42 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (42 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (42 samples, 0.01%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (42 samples, 0.01%)alloc::alloc::Global::alloc_impl (42 samples, 0.01%)alloc::alloc::alloc_zeroed (42 samples, 0.01%)__rdl_alloc_zeroed (42 samples, 0.01%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (42 samples, 0.01%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (318 samples, 0.08%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (73 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (61 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (85 samples, 0.02%)std::sync::rwlock::RwLock<T>::read (80 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read (63 samples, 0.02%)[[heap]] (8,241 samples, 2.18%)[..[[vdso]] (1,241 samples, 0.33%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (96 samples, 0.03%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (69 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (43 samples, 0.01%)<alloc::string::String as core::fmt::Write>::write_char (41 samples, 0.01%)<alloc::string::String as core::fmt::Write>::write_str (379 samples, 0.10%)alloc::string::String::push_str (45 samples, 0.01%)alloc::vec::Vec<T,A>::extend_from_slice (45 samples, 0.01%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (45 samples, 0.01%)alloc::vec::Vec<T,A>::append_elements (45 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (66 samples, 0.02%)core::num::<impl u64>::rotate_left (48 samples, 0.01%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (148 samples, 0.04%)core::num::<impl u64>::wrapping_add (42 samples, 0.01%)core::hash::sip::u8to64_le (134 samples, 0.04%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (506 samples, 0.13%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (54 samples, 0.01%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (49 samples, 0.01%)core::ops::function::FnMut::call_mut (41 samples, 0.01%)tokio::runtime::coop::poll_proceed (41 samples, 0.01%)tokio::runtime::context::budget (41 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (41 samples, 0.01%)tokio::io::ready::Ready::intersection (48 samples, 0.01%)tokio::io::ready::Ready::from_interest (46 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (297 samples, 0.08%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (83 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (83 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (67 samples, 0.02%)core::result::Result<T,E>::is_err (375 samples, 0.10%)core::result::Result<T,E>::is_ok (375 samples, 0.10%)tokio::loom::std::mutex::Mutex<T>::lock (493 samples, 0.13%)std::sync::mutex::Mutex<T>::lock (463 samples, 0.12%)std::sys::sync::mutex::futex::Mutex::lock (443 samples, 0.12%)core::sync::atomic::AtomicU32::compare_exchange (51 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (51 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (1,400 samples, 0.37%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (50 samples, 0.01%)[[vdso]] (3,493 samples, 0.92%)[profiling] (68 samples, 0.02%)core::fmt::write (51 samples, 0.01%)__GI___clock_gettime (73 samples, 0.02%)__GI___libc_free (449 samples, 0.12%)arena_for_chunk (85 samples, 0.02%)arena_for_chunk (71 samples, 0.02%)heap_for_ptr (67 samples, 0.02%)heap_max_size (49 samples, 0.01%)__GI___libc_malloc (293 samples, 0.08%)__GI___lll_lock_wait_private (144 samples, 0.04%)futex_wait (95 samples, 0.03%)__GI___lll_lock_wake_private (479 samples, 0.13%)__GI___pthread_disable_asynccancel (90 samples, 0.02%)__GI_getsockname (1,281 samples, 0.34%)__libc_calloc (42 samples, 0.01%)__libc_recvfrom (121 samples, 0.03%)__libc_sendto (602 samples, 0.16%)__memchr_evex (56 samples, 0.01%)__memcmp_evex_movbe (1,539 samples, 0.41%)__memcpy_avx512_unaligned_erms (1,154 samples, 0.30%)__memset_avx512_unaligned_erms (1,515 samples, 0.40%)__posix_memalign (131 samples, 0.03%)__posix_memalign (85 samples, 0.02%)_mid_memalign (85 samples, 0.02%)_int_free (1,524 samples, 0.40%)_int_malloc (1,484 samples, 0.39%)_int_memalign (156 samples, 0.04%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (82 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (64 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (64 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (64 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (161 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::grow_one (44 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (146 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::grow_amortized (101 samples, 0.03%)alloc::raw_vec::finish_grow (199 samples, 0.05%)core::ptr::drop_in_place<aquatic_udp_protocol::response::Response> (166 samples, 0.04%)core::ptr::drop_in_place<tokio::net::udp::UdpSocket::send_to<&core::net::socket_addr::SocketAddr>::{{closure}}> (57 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (373 samples, 0.10%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::send_response::{{closure}}> (61 samples, 0.02%)malloc_consolidate (373 samples, 0.10%)<ppv_lite86::soft::x2<W,G> as core::ops::arith::AddAssign>::add_assign (62 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::AddAssign>::add_assign (62 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::Add>::add (62 samples, 0.02%)core::core_arch::x86::avx2::_mm256_add_epi32 (62 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (46 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (46 samples, 0.01%)core::core_arch::x86::avx2::_mm256_shuffle_epi8 (46 samples, 0.01%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (40 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (40 samples, 0.01%)rand_chacha::guts::round (244 samples, 0.06%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right25 (45 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right25 (45 samples, 0.01%)core::core_arch::x86::avx2::_mm256_or_si256 (45 samples, 0.01%)rand_chacha::guts::refill_wide::impl_avx2 (346 samples, 0.09%)rand_chacha::guts::refill_wide::fn_impl (345 samples, 0.09%)rand_chacha::guts::refill_wide_impl (345 samples, 0.09%)tokio::runtime::context::with_scheduler (45 samples, 0.01%)tokio::runtime::io::driver::Driver::turn (50 samples, 0.01%)__entry_text_start (235 samples, 0.06%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (2,041 samples, 0.54%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (957 samples, 0.25%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (255 samples, 0.07%)core::sync::atomic::AtomicUsize::fetch_add (100 samples, 0.03%)core::sync::atomic::atomic_add (100 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (155 samples, 0.04%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (108 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (84 samples, 0.02%)tokio::runtime::task::core::Header::get_owner_id (38 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with (38 samples, 0.01%)tokio::runtime::task::core::Header::get_owner_id::{{closure}} (38 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (43 samples, 0.01%)tokio::runtime::task::list::OwnedTasks<S>::remove (39 samples, 0.01%)torrust_tracker::servers::udp::handlers::RequestId::make (173 samples, 0.05%)__entry_text_start (171 samples, 0.05%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (293 samples, 0.08%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (287 samples, 0.08%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (230 samples, 0.06%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (230 samples, 0.06%)tokio::runtime::task::core::Core<T,S>::set_stage (456 samples, 0.12%)core::sync::atomic::AtomicUsize::fetch_xor (54 samples, 0.01%)core::sync::atomic::atomic_xor (54 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::complete (73 samples, 0.02%)tokio::runtime::task::state::State::transition_to_complete (57 samples, 0.02%)std::sync::poison::Flag::done (103 samples, 0.03%)core::ptr::drop_in_place<tokio::util::sharded_list::ShardGuard<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>> (136 samples, 0.04%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>>> (136 samples, 0.04%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (136 samples, 0.04%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (242 samples, 0.06%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::push_front (60 samples, 0.02%)core::result::Result<T,E>::is_err (101 samples, 0.03%)core::result::Result<T,E>::is_ok (101 samples, 0.03%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (599 samples, 0.16%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (255 samples, 0.07%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (255 samples, 0.07%)tokio::loom::std::mutex::Mutex<T>::lock (252 samples, 0.07%)std::sync::mutex::Mutex<T>::lock (252 samples, 0.07%)std::sys::sync::mutex::futex::Mutex::lock (251 samples, 0.07%)core::sync::atomic::AtomicU32::compare_exchange (150 samples, 0.04%)core::sync::atomic::atomic_compare_exchange (150 samples, 0.04%)std::sync::poison::Flag::done (100 samples, 0.03%)std::thread::panicking (55 samples, 0.01%)std::panicking::panicking (55 samples, 0.01%)std::panicking::panic_count::count_is_zero (55 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (173 samples, 0.05%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (173 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::unlock (73 samples, 0.02%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (293 samples, 0.08%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (293 samples, 0.08%)core::slice::<impl [T]>::contains (631 samples, 0.17%)<T as core::slice::cmp::SliceContains>::slice_contains (631 samples, 0.17%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (631 samples, 0.17%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (134 samples, 0.04%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (134 samples, 0.04%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (844 samples, 0.22%)tokio::loom::std::mutex::Mutex<T>::lock (38 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (858 samples, 0.23%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (189 samples, 0.05%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (189 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::unlock (181 samples, 0.05%)core::sync::atomic::AtomicU32::swap (65 samples, 0.02%)core::sync::atomic::atomic_swap (65 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (44 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (43 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (38 samples, 0.01%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (253 samples, 0.07%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (42 samples, 0.01%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (42 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (48 samples, 0.01%)alloc::sync::Arc<T,A>::inner (48 samples, 0.01%)core::ptr::non_null::NonNull<T>::as_ref (48 samples, 0.01%)core::sync::atomic::AtomicU32::load (44 samples, 0.01%)core::sync::atomic::atomic_load (44 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_if_work_pending (356 samples, 0.09%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::is_empty (216 samples, 0.06%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::is_empty (168 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::len (98 samples, 0.03%)core::sync::atomic::AtomicU64::load (54 samples, 0.01%)core::sync::atomic::atomic_load (54 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (1,635 samples, 0.43%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (667 samples, 0.18%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (66 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (61 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (96 samples, 0.03%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (1,751 samples, 0.46%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (1,751 samples, 0.46%)tokio::runtime::scheduler::multi_thread::worker::run (1,751 samples, 0.46%)tokio::runtime::context::runtime::enter_runtime (1,751 samples, 0.46%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (1,751 samples, 0.46%)tokio::runtime::context::set_scheduler (1,751 samples, 0.46%)std::thread::local::LocalKey<T>::with (1,751 samples, 0.46%)std::thread::local::LocalKey<T>::try_with (1,751 samples, 0.46%)tokio::runtime::context::set_scheduler::{{closure}} (1,751 samples, 0.46%)tokio::runtime::context::scoped::Scoped<T>::set (1,751 samples, 0.46%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (1,751 samples, 0.46%)tokio::runtime::scheduler::multi_thread::worker::Context::run (1,751 samples, 0.46%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (1,772 samples, 0.47%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (1,772 samples, 0.47%)tokio::runtime::task::raw::poll (1,805 samples, 0.48%)tokio::runtime::task::harness::Harness<T,S>::poll (1,787 samples, 0.47%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (1,787 samples, 0.47%)tokio::runtime::task::harness::poll_future (1,787 samples, 0.47%)std::panic::catch_unwind (1,787 samples, 0.47%)std::panicking::try (1,787 samples, 0.47%)std::panicking::try::do_call (1,787 samples, 0.47%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (1,787 samples, 0.47%)tokio::runtime::task::harness::poll_future::{{closure}} (1,787 samples, 0.47%)tokio::runtime::task::core::Core<T,S>::poll (1,787 samples, 0.47%)tokio::runtime::time::wheel::level::Level::next_expiration (54 samples, 0.01%)tokio::runtime::time::wheel::Wheel::next_expiration (72 samples, 0.02%)torrust_tracker::core::Tracker::send_stats_event::{{closure}} (50 samples, 0.01%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (38 samples, 0.01%)<std::hash::random::DefaultHasher as core::hash::Hasher>::finish (157 samples, 0.04%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::finish (157 samples, 0.04%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::finish (157 samples, 0.04%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::d_rounds (89 samples, 0.02%)<torrust_tracker_clock::time_extent::TimeExtent as core::hash::Hash>::hash (47 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (265 samples, 0.07%)torrust_tracker::servers::udp::peer_builder::from_request (70 samples, 0.02%)torrust_tracker::servers::udp::request::AnnounceWrapper::new (101 samples, 0.03%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (74 samples, 0.02%)core::sync::atomic::AtomicUsize::fetch_add (48 samples, 0.01%)core::sync::atomic::atomic_add (48 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<tokio::net::udp::UdpSocket>> (88 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (88 samples, 0.02%)core::result::Result<T,E>::map_err (52 samples, 0.01%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (269 samples, 0.07%)torrust_tracker::core::Tracker::announce::{{closure}} (308 samples, 0.08%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (372 samples, 0.10%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (448 samples, 0.12%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (73 samples, 0.02%)core::fmt::num::imp::fmt_u64 (69 samples, 0.02%)core::fmt::num::imp::<impl core::fmt::Display for i64>::fmt (41 samples, 0.01%)<T as alloc::string::ToString>::to_string (182 samples, 0.05%)core::option::Option<T>::expect (91 samples, 0.02%)torrust_tracker_primitives::info_hash::InfoHash::to_hex_string (41 samples, 0.01%)<T as alloc::string::ToString>::to_string (41 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (450 samples, 0.12%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (1,319 samples, 0.35%)torrust_tracker::servers::udp::logging::log_response (83 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (1,808 samples, 0.48%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (293 samples, 0.08%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (283 samples, 0.07%)tokio::net::udp::UdpSocket::send_to::{{closure}} (265 samples, 0.07%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (227 samples, 0.06%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (124 samples, 0.03%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (61 samples, 0.02%)mio::net::udp::UdpSocket::send_to (61 samples, 0.02%)mio::io_source::IoSource<T>::do_io (61 samples, 0.02%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (61 samples, 0.02%)mio::net::udp::UdpSocket::send_to::{{closure}} (61 samples, 0.02%)std::net::udp::UdpSocket::send_to (61 samples, 0.02%)std::sys_common::net::UdpSocket::send_to (61 samples, 0.02%)std::sys::pal::unix::cvt (61 samples, 0.02%)<isize as std::sys::pal::unix::IsMinusOne>::is_minus_one (61 samples, 0.02%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::count::to_usize::{{closure}} (84 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats::{{closure}} (84 samples, 0.02%)torrust_tracker_primitives::peer::Peer::is_seeder (84 samples, 0.02%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::count (173 samples, 0.05%)core::iter::traits::iterator::Iterator::sum (173 samples, 0.05%)<usize as core::iter::traits::accum::Sum>::sum (173 samples, 0.05%)<core::iter::adapters::map::Map<I,F> as core::iter::traits::iterator::Iterator>::fold (173 samples, 0.05%)core::iter::traits::iterator::Iterator::fold (173 samples, 0.05%)core::iter::adapters::map::map_fold::{{closure}} (85 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (337 samples, 0.09%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (156 samples, 0.04%)core::mem::drop (39 samples, 0.01%)core::ptr::drop_in_place<core::option::Option<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (39 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (39 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (39 samples, 0.01%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (750 samples, 0.20%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (691 samples, 0.18%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (349 samples, 0.09%)core::option::Option<T>::is_some_and (106 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (105 samples, 0.03%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (101 samples, 0.03%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (101 samples, 0.03%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (61 samples, 0.02%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (84 samples, 0.02%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (84 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (181 samples, 0.05%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (181 samples, 0.05%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (181 samples, 0.05%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (181 samples, 0.05%)<u8 as core::slice::cmp::SliceOrd>::compare (181 samples, 0.05%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (76 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (551 samples, 0.15%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (506 samples, 0.13%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (506 samples, 0.13%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (572 samples, 0.15%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (751 samples, 0.20%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (64 samples, 0.02%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (83 samples, 0.02%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (83 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (216 samples, 0.06%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (216 samples, 0.06%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (216 samples, 0.06%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (216 samples, 0.06%)<u8 as core::slice::cmp::SliceOrd>::compare (216 samples, 0.06%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (87 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (539 samples, 0.14%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (527 samples, 0.14%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (501 samples, 0.13%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (501 samples, 0.13%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (640 samples, 0.17%)core::sync::atomic::AtomicU32::load (117 samples, 0.03%)core::sync::atomic::atomic_load (117 samples, 0.03%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (167 samples, 0.04%)std::sync::rwlock::RwLock<T>::read (162 samples, 0.04%)std::sys::sync::rwlock::futex::RwLock::read (158 samples, 0.04%)tracing::span::Span::log (82 samples, 0.02%)tracing::span::Span::record_all (143 samples, 0.04%)unlink_chunk (679 samples, 0.18%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (71 samples, 0.02%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (71 samples, 0.02%)rand_core::block::BlockRng<R>::generate_and_set (59 samples, 0.02%)rand::rng::Rng::gen (72 samples, 0.02%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (72 samples, 0.02%)rand::rng::Rng::gen (72 samples, 0.02%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (72 samples, 0.02%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (72 samples, 0.02%)[anon] (31,375 samples, 8.29%)[anon]uuid::v4::<impl uuid::Uuid>::new_v4 (90 samples, 0.02%)uuid::rng::bytes (87 samples, 0.02%)rand::random (87 samples, 0.02%)_int_free (938 samples, 0.25%)tcache_put (62 samples, 0.02%)hashbrown::raw::h2 (40 samples, 0.01%)hashbrown::raw::RawTable<T,A>::find_or_find_insert_slot (63 samples, 0.02%)hashbrown::raw::RawTableInner::find_or_find_insert_slot_inner (53 samples, 0.01%)hashbrown::map::HashMap<K,V,S,A>::insert (65 samples, 0.02%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (128 samples, 0.03%)[profiling] (1,452 samples, 0.38%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (104 samples, 0.03%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (89 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (70 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<BorrowType,K,V>::init_front (42 samples, 0.01%)<alloc::string::String as core::fmt::Write>::write_char (41 samples, 0.01%)alloc::vec::Vec<T,A>::reserve (49 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve (45 samples, 0.01%)<alloc::string::String as core::fmt::Write>::write_str (157 samples, 0.04%)alloc::string::String::push_str (107 samples, 0.03%)alloc::vec::Vec<T,A>::extend_from_slice (107 samples, 0.03%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (107 samples, 0.03%)alloc::vec::Vec<T,A>::append_elements (107 samples, 0.03%)core::num::<impl u64>::rotate_left (45 samples, 0.01%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (114 samples, 0.03%)core::hash::sip::u8to64_le (102 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (388 samples, 0.10%)<core::net::ip_addr::Ipv4Addr as core::hash::Hash>::hash (110 samples, 0.03%)core::array::<impl core::hash::Hash for [T: N]>::hash (109 samples, 0.03%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (109 samples, 0.03%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (93 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (93 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (93 samples, 0.02%)<core::net::socket_addr::SocketAddrV4 as core::hash::Hash>::hash (135 samples, 0.04%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (202 samples, 0.05%)tokio::runtime::context::CONTEXT::__getit (59 samples, 0.02%)core::cell::Cell<T>::get (59 samples, 0.02%)__entry_text_start (42 samples, 0.01%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (164 samples, 0.04%)core::ops::function::FnMut::call_mut (149 samples, 0.04%)tokio::runtime::coop::poll_proceed (149 samples, 0.04%)tokio::runtime::context::budget (149 samples, 0.04%)std::thread::local::LocalKey<T>::try_with (149 samples, 0.04%)tokio::runtime::context::budget::{{closure}} (73 samples, 0.02%)tokio::runtime::coop::poll_proceed::{{closure}} (73 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (218 samples, 0.06%)__entry_text_start (55 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (89 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (89 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (65 samples, 0.02%)core::sync::atomic::AtomicU32::swap (41 samples, 0.01%)core::sync::atomic::atomic_swap (41 samples, 0.01%)std::sync::mutex::MutexGuard<T>::new (41 samples, 0.01%)std::sync::poison::Flag::guard (41 samples, 0.01%)std::thread::panicking (39 samples, 0.01%)std::panicking::panicking (39 samples, 0.01%)std::panicking::panic_count::count_is_zero (39 samples, 0.01%)core::result::Result<T,E>::is_err (337 samples, 0.09%)core::result::Result<T,E>::is_ok (337 samples, 0.09%)core::sync::atomic::AtomicU32::compare_exchange (60 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (60 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (483 samples, 0.13%)std::sync::mutex::Mutex<T>::lock (456 samples, 0.12%)std::sys::sync::mutex::futex::Mutex::lock (415 samples, 0.11%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (864 samples, 0.23%)__memcpy_avx512_unaligned_erms (223 samples, 0.06%)[profiling] (233 samples, 0.06%)binascii::bin2hex (128 samples, 0.03%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (404 samples, 0.11%)__entry_text_start (811 samples, 0.21%)[[vdso]] (12,846 samples, 3.40%)[[v..__GI___clock_gettime (141 samples, 0.04%)arena_for_chunk (178 samples, 0.05%)arena_for_chunk (151 samples, 0.04%)heap_for_ptr (116 samples, 0.03%)heap_max_size (50 samples, 0.01%)__GI___libc_free (827 samples, 0.22%)arena_for_chunk (86 samples, 0.02%)arena_for_chunk (67 samples, 0.02%)heap_for_ptr (39 samples, 0.01%)__GI___libc_malloc (618 samples, 0.16%)tcache_get (96 samples, 0.03%)__GI___libc_write (225 samples, 0.06%)__GI___libc_write (234 samples, 0.06%)__GI___lll_lock_wait_private (110 samples, 0.03%)futex_wait (66 samples, 0.02%)__GI___lll_lock_wake_private (138 samples, 0.04%)__GI___pthread_disable_asynccancel (209 samples, 0.06%)__GI___pthread_enable_asynccancel (46 samples, 0.01%)__entry_text_start (46 samples, 0.01%)compiler_builtins::float::conv::int_to_float::u128_to_f64_bits (138 samples, 0.04%)__floattidf (183 samples, 0.05%)compiler_builtins::float::conv::__floattidf (172 samples, 0.05%)exp_inline (152 samples, 0.04%)log_inline (148 samples, 0.04%)__ieee754_pow_fma (333 samples, 0.09%)__libc_calloc (299 samples, 0.08%)__libc_recvfrom (1,422 samples, 0.38%)__libc_sendto (881 samples, 0.23%)__memcmp_evex_movbe (277 samples, 0.07%)__memcpy_avx512_unaligned_erms (4,073 samples, 1.08%)__posix_memalign (367 samples, 0.10%)__posix_memalign (216 samples, 0.06%)_mid_memalign (206 samples, 0.05%)arena_for_chunk (38 samples, 0.01%)__pow (75 samples, 0.02%)__entry_text_start (468 samples, 0.12%)_int_free (2,282 samples, 0.60%)tcache_put (139 samples, 0.04%)_int_malloc (2,521 samples, 0.67%)_int_memalign (241 samples, 0.06%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (125 samples, 0.03%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (165 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::set_ptr_and_cap (69 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (362 samples, 0.10%)alloc::raw_vec::RawVec<T,A>::grow_amortized (318 samples, 0.08%)alloc::raw_vec::finish_grow (233 samples, 0.06%)core::result::Result<T,E>::map_err (88 samples, 0.02%)core::mem::drop (70 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (70 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (70 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (61 samples, 0.02%)core::sync::atomic::AtomicU32::swap (59 samples, 0.02%)core::sync::atomic::atomic_swap (59 samples, 0.02%)alloc_new_heap (197 samples, 0.05%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (197 samples, 0.05%)core::fmt::Formatter::pad (45 samples, 0.01%)core::fmt::Formatter::pad_integral (93 samples, 0.02%)core::fmt::Formatter::pad_integral::write_prefix (47 samples, 0.01%)core::ptr::drop_in_place<[core::option::Option<core::task::wake::Waker>: 32]> (662 samples, 0.17%)core::ptr::drop_in_place<core::option::Option<core::task::wake::Waker>> (346 samples, 0.09%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (578 samples, 0.15%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}}> (54 samples, 0.01%)core::str::converts::from_utf8 (81 samples, 0.02%)core::str::validations::run_utf8_validation (70 samples, 0.02%)epoll_wait (87 samples, 0.02%)hashbrown::map::HashMap<K,V,S,A>::insert (52 samples, 0.01%)malloc_consolidate (109 samples, 0.03%)std::sys::pal::unix::time::Timespec::new (76 samples, 0.02%)std::sys::pal::unix::time::Timespec::now (357 samples, 0.09%)core::cmp::impls::<impl core::cmp::PartialOrd<&B> for &A>::ge (42 samples, 0.01%)core::cmp::PartialOrd::ge (42 samples, 0.01%)std::sys::pal::unix::time::Timespec::sub_timespec (202 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock_contended (233 samples, 0.06%)std::sys::sync::mutex::futex::Mutex::spin (67 samples, 0.02%)std::sys_common::net::TcpListener::socket_addr (85 samples, 0.02%)std::sys_common::net::sockname (80 samples, 0.02%)syscall (511 samples, 0.14%)core::ptr::drop_in_place<core::cell::RefMut<core::option::Option<alloc::boxed::Box<tokio::runtime::scheduler::multi_thread::worker::Core>>>> (95 samples, 0.03%)core::ptr::drop_in_place<core::cell::BorrowRefMut> (95 samples, 0.03%)<core::cell::BorrowRefMut as core::ops::drop::Drop>::drop (95 samples, 0.03%)core::cell::Cell<T>::set (95 samples, 0.03%)core::cell::Cell<T>::replace (95 samples, 0.03%)core::mem::replace (95 samples, 0.03%)core::ptr::write (95 samples, 0.03%)tokio::runtime::context::with_scheduler (369 samples, 0.10%)std::thread::local::LocalKey<T>::try_with (256 samples, 0.07%)tokio::runtime::context::with_scheduler::{{closure}} (255 samples, 0.07%)tokio::runtime::context::scoped::Scoped<T>::with (255 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (255 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (255 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (156 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (52 samples, 0.01%)tokio::io::ready::Ready::from_mio (40 samples, 0.01%)core::sync::atomic::AtomicUsize::compare_exchange (39 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (39 samples, 0.01%)tokio::runtime::io::driver::Driver::turn (609 samples, 0.16%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (439 samples, 0.12%)__entry_text_start (200 samples, 0.05%)__entry_text_start (331 samples, 0.09%)__entry_text_start (74 samples, 0.02%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (1,520 samples, 0.40%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (828 samples, 0.22%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (279 samples, 0.07%)core::mem::drop (88 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (88 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (88 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (72 samples, 0.02%)core::sync::atomic::AtomicU32::swap (65 samples, 0.02%)core::sync::atomic::atomic_swap (65 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (69 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (66 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (48 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (566 samples, 0.15%)alloc::vec::Vec<T,A>::pop (77 samples, 0.02%)core::ptr::read (48 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (50 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (50 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (46 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (46 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (4,232 samples, 1.12%)core::sync::atomic::atomic_add (4,232 samples, 1.12%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (4,298 samples, 1.14%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (4,674 samples, 1.24%)__entry_text_start (67 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (210 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (107 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark_condvar (84 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (82 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::next_remote_task (120 samples, 0.03%)tokio::runtime::scheduler::inject::shared::Shared<T>::is_empty (48 samples, 0.01%)tokio::runtime::scheduler::inject::shared::Shared<T>::len (48 samples, 0.01%)core::sync::atomic::AtomicUsize::load (48 samples, 0.01%)core::sync::atomic::atomic_load (48 samples, 0.01%)tokio::runtime::task::core::Header::get_owner_id (61 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with (61 samples, 0.02%)tokio::runtime::task::core::Header::get_owner_id::{{closure}} (61 samples, 0.02%)std::sync::poison::Flag::done (462 samples, 0.12%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>,tokio::runtime::task::core::Header>>> (540 samples, 0.14%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (540 samples, 0.14%)std::sys::sync::mutex::futex::Mutex::unlock (76 samples, 0.02%)core::sync::atomic::AtomicUsize::fetch_sub (91 samples, 0.02%)core::sync::atomic::atomic_sub (91 samples, 0.02%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (61 samples, 0.02%)core::result::Result<T,E>::is_err (88 samples, 0.02%)core::result::Result<T,E>::is_ok (88 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (884 samples, 0.23%)tokio::runtime::task::list::OwnedTasks<S>::remove (873 samples, 0.23%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (796 samples, 0.21%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (102 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (102 samples, 0.03%)std::sync::mutex::Mutex<T>::lock (102 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::lock (96 samples, 0.03%)core::cell::RefCell<T>::borrow_mut (38 samples, 0.01%)core::cell::RefCell<T>::try_borrow_mut (38 samples, 0.01%)core::cell::BorrowRefMut::new (38 samples, 0.01%)tokio::runtime::scheduler::defer::Defer::wake (86 samples, 0.02%)std::sys::pal::unix::futex::futex_wait (101 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (186 samples, 0.05%)std::sync::condvar::Condvar::wait (132 samples, 0.03%)std::sys::sync::condvar::futex::Condvar::wait (130 samples, 0.03%)std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (130 samples, 0.03%)core::sync::atomic::AtomicUsize::compare_exchange (69 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (69 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::park_driver (281 samples, 0.07%)tokio::runtime::driver::Driver::park (96 samples, 0.03%)tokio::runtime::driver::TimeDriver::park (96 samples, 0.03%)tokio::runtime::time::Driver::park (91 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Parker::park (627 samples, 0.17%)tokio::runtime::scheduler::multi_thread::park::Inner::park (627 samples, 0.17%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (1,130 samples, 0.30%)tokio::runtime::scheduler::multi_thread::worker::Core::should_notify_others (62 samples, 0.02%)core::cell::RefCell<T>::borrow_mut (84 samples, 0.02%)core::cell::RefCell<T>::try_borrow_mut (84 samples, 0.02%)core::cell::BorrowRefMut::new (84 samples, 0.02%)core::cell::RefCell<T>::borrow_mut (250 samples, 0.07%)core::cell::RefCell<T>::try_borrow_mut (250 samples, 0.07%)core::cell::BorrowRefMut::new (250 samples, 0.07%)tokio::runtime::coop::budget (368 samples, 0.10%)tokio::runtime::coop::with_budget (368 samples, 0.10%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (318 samples, 0.08%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (82 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (600 samples, 0.16%)tokio::runtime::signal::Driver::process (79 samples, 0.02%)tokio::runtime::io::driver::signal::<impl tokio::runtime::io::driver::Driver>::consume_signal_ready (49 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<tokio::net::udp::UdpSocket>> (62 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (62 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker::core::Tracker>> (140 samples, 0.04%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (140 samples, 0.04%)core::sync::atomic::AtomicUsize::fetch_sub (91 samples, 0.02%)core::sync::atomic::atomic_sub (91 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (261 samples, 0.07%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (260 samples, 0.07%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (233 samples, 0.06%)tokio::runtime::task::core::Core<T,S>::set_stage (353 samples, 0.09%)core::sync::atomic::AtomicUsize::fetch_xor (127 samples, 0.03%)core::sync::atomic::atomic_xor (127 samples, 0.03%)tokio::runtime::task::state::State::transition_to_complete (135 samples, 0.04%)core::sync::atomic::AtomicUsize::fetch_sub (44 samples, 0.01%)core::sync::atomic::atomic_sub (44 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::complete (242 samples, 0.06%)tokio::runtime::task::state::State::transition_to_terminal (67 samples, 0.02%)tokio::runtime::task::harness::Harness<T,S>::dealloc (53 samples, 0.01%)std::sync::poison::Flag::done (203 samples, 0.05%)core::ptr::drop_in_place<tokio::util::sharded_list::ShardGuard<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>> (272 samples, 0.07%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>>> (272 samples, 0.07%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (272 samples, 0.07%)std::sys::sync::mutex::futex::Mutex::unlock (65 samples, 0.02%)core::sync::atomic::AtomicU32::swap (48 samples, 0.01%)core::sync::atomic::atomic_swap (48 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (78 samples, 0.02%)core::sync::atomic::atomic_add (78 samples, 0.02%)<tokio::runtime::task::Task<S> as tokio::util::linked_list::Link>::pointers (39 samples, 0.01%)tokio::runtime::task::core::Header::get_trailer (39 samples, 0.01%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (531 samples, 0.14%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::push_front (144 samples, 0.04%)core::result::Result<T,E>::is_err (40 samples, 0.01%)core::result::Result<T,E>::is_ok (40 samples, 0.01%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (1,157 samples, 0.31%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (431 samples, 0.11%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (430 samples, 0.11%)tokio::loom::std::mutex::Mutex<T>::lock (429 samples, 0.11%)std::sync::mutex::Mutex<T>::lock (429 samples, 0.11%)std::sys::sync::mutex::futex::Mutex::lock (425 samples, 0.11%)core::sync::atomic::AtomicU32::compare_exchange (385 samples, 0.10%)core::sync::atomic::atomic_compare_exchange (385 samples, 0.10%)tokio::runtime::task::raw::drop_abort_handle (184 samples, 0.05%)tokio::runtime::task::harness::Harness<T,S>::drop_reference (167 samples, 0.04%)tokio::runtime::task::state::State::ref_dec (167 samples, 0.04%)core::sync::atomic::AtomicUsize::compare_exchange (44 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (44 samples, 0.01%)tokio::runtime::task::raw::drop_join_handle_slow (126 samples, 0.03%)tokio::runtime::task::harness::Harness<T,S>::drop_join_handle_slow (117 samples, 0.03%)tokio::runtime::task::state::State::unset_join_interested (76 samples, 0.02%)tokio::runtime::task::state::State::fetch_update (76 samples, 0.02%)core::result::Result<T,E>::is_err (53 samples, 0.01%)core::result::Result<T,E>::is_ok (53 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::maintenance (87 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (82 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (82 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (82 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (56 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (60 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (78 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (74 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (74 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (74 samples, 0.02%)core::result::Result<T,E>::is_err (60 samples, 0.02%)core::result::Result<T,E>::is_ok (60 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::park (266 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (91 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (44 samples, 0.01%)core::sync::atomic::AtomicU64::compare_exchange (98 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (98 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (272 samples, 0.07%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (339 samples, 0.09%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (549 samples, 0.15%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (980 samples, 0.26%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (980 samples, 0.26%)tokio::runtime::scheduler::multi_thread::worker::run (980 samples, 0.26%)tokio::runtime::context::runtime::enter_runtime (980 samples, 0.26%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (980 samples, 0.26%)tokio::runtime::context::set_scheduler (980 samples, 0.26%)std::thread::local::LocalKey<T>::with (980 samples, 0.26%)std::thread::local::LocalKey<T>::try_with (980 samples, 0.26%)tokio::runtime::context::set_scheduler::{{closure}} (980 samples, 0.26%)tokio::runtime::context::scoped::Scoped<T>::set (980 samples, 0.26%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (980 samples, 0.26%)tokio::runtime::scheduler::multi_thread::worker::Context::run (980 samples, 0.26%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (1,050 samples, 0.28%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (1,047 samples, 0.28%)tokio::runtime::task::core::Core<T,S>::poll (1,075 samples, 0.28%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (1,099 samples, 0.29%)tokio::runtime::task::harness::poll_future::{{closure}} (1,099 samples, 0.29%)tokio::runtime::task::harness::poll_future (1,117 samples, 0.30%)std::panic::catch_unwind (1,115 samples, 0.29%)std::panicking::try (1,115 samples, 0.29%)std::panicking::try::do_call (1,114 samples, 0.29%)tokio::runtime::task::state::State::transition_to_running (377 samples, 0.10%)tokio::runtime::task::state::State::fetch_update_action (377 samples, 0.10%)tokio::runtime::task::raw::poll (1,566 samples, 0.41%)tokio::runtime::task::harness::Harness<T,S>::poll (1,533 samples, 0.41%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (1,525 samples, 0.40%)core::array::<impl core::default::Default for [T: 32]>::default (42 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (190 samples, 0.05%)tokio::loom::std::mutex::Mutex<T>::lock (47 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (47 samples, 0.01%)tokio::runtime::time::source::TimeSource::instant_to_tick (43 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process (73 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (50 samples, 0.01%)tokio::runtime::time::Driver::park_internal (346 samples, 0.09%)core::num::<impl u64>::rotate_right (51 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_occupied_slot (441 samples, 0.12%)tokio::runtime::time::wheel::level::slot_range (99 samples, 0.03%)core::num::<impl usize>::pow (99 samples, 0.03%)tokio::runtime::time::wheel::level::level_range (154 samples, 0.04%)tokio::runtime::time::wheel::level::slot_range (146 samples, 0.04%)core::num::<impl usize>::pow (146 samples, 0.04%)tokio::runtime::time::wheel::level::Level::next_expiration (833 samples, 0.22%)tokio::runtime::time::wheel::level::slot_range (161 samples, 0.04%)core::num::<impl usize>::pow (161 samples, 0.04%)tokio::runtime::time::wheel::Wheel::next_expiration (1,138 samples, 0.30%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::is_empty (55 samples, 0.01%)core::option::Option<T>::is_some (55 samples, 0.01%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (112 samples, 0.03%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_peers_for_client (79 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_peers_for_client (48 samples, 0.01%)core::iter::traits::iterator::Iterator::collect (41 samples, 0.01%)<alloc::vec::Vec<T> as core::iter::traits::collect::FromIterator<T>>::from_iter (41 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (41 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter_nested::SpecFromIterNested<T,I>>::from_iter (41 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (234 samples, 0.06%)std::hash::random::DefaultHasher::new (108 samples, 0.03%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (98 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (75 samples, 0.02%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (415 samples, 0.11%)core::sync::atomic::AtomicUsize::fetch_add (129 samples, 0.03%)core::sync::atomic::atomic_add (129 samples, 0.03%)core::ptr::drop_in_place<alloc::sync::Arc<tokio::net::udp::UdpSocket>> (112 samples, 0.03%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (112 samples, 0.03%)core::sync::atomic::AtomicUsize::fetch_sub (49 samples, 0.01%)core::sync::atomic::atomic_sub (49 samples, 0.01%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (1,399 samples, 0.37%)<F as core::future::into_future::IntoFuture>::into_future (40 samples, 0.01%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (330 samples, 0.09%)core::sync::atomic::AtomicUsize::fetch_add (210 samples, 0.06%)core::sync::atomic::atomic_add (210 samples, 0.06%)torrust_tracker::servers::udp::handlers::handle_packet (80 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<tokio::net::udp::UdpSocket>> (212 samples, 0.06%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (212 samples, 0.06%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (321 samples, 0.08%)torrust_tracker::core::Tracker::announce::{{closure}} (434 samples, 0.11%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (635 samples, 0.17%)torrust_tracker::servers::udp::handlers::handle_connect::{{closure}} (56 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (986 samples, 0.26%)core::fmt::Formatter::new (50 samples, 0.01%)core::intrinsics::copy_nonoverlapping (39 samples, 0.01%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (208 samples, 0.05%)core::fmt::num::imp::fmt_u64 (188 samples, 0.05%)core::fmt::num::imp::<impl core::fmt::Display for i64>::fmt (131 samples, 0.03%)core::fmt::num::imp::fmt_u64 (119 samples, 0.03%)<T as alloc::string::ToString>::to_string (426 samples, 0.11%)core::option::Option<T>::expect (74 samples, 0.02%)torrust_tracker::servers::udp::logging::map_action_name (51 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (679 samples, 0.18%)<T as alloc::string::ToString>::to_string (106 samples, 0.03%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (72 samples, 0.02%)core::fmt::num::imp::fmt_u64 (58 samples, 0.02%)core::option::Option<T>::expect (38 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (2,539 samples, 0.67%)torrust_tracker::servers::udp::logging::log_response (198 samples, 0.05%)alloc::vec::from_elem (583 samples, 0.15%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (583 samples, 0.15%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (583 samples, 0.15%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (583 samples, 0.15%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (583 samples, 0.15%)alloc::alloc::Global::alloc_impl (583 samples, 0.15%)alloc::alloc::alloc_zeroed (583 samples, 0.15%)__rdl_alloc_zeroed (583 samples, 0.15%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (583 samples, 0.15%)__entry_text_start (110 samples, 0.03%)__entry_text_start (278 samples, 0.07%)std::sys::pal::unix::cvt (338 samples, 0.09%)<isize as std::sys::pal::unix::IsMinusOne>::is_minus_one (338 samples, 0.09%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (6,133 samples, 1.62%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (2,253 samples, 0.60%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (1,179 samples, 0.31%)tokio::net::udp::UdpSocket::send_to::{{closure}} (1,082 samples, 0.29%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (1,028 samples, 0.27%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (922 samples, 0.24%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (716 samples, 0.19%)mio::net::udp::UdpSocket::send_to (681 samples, 0.18%)mio::io_source::IoSource<T>::do_io (681 samples, 0.18%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (681 samples, 0.18%)mio::net::udp::UdpSocket::send_to::{{closure}} (681 samples, 0.18%)std::net::udp::UdpSocket::send_to (681 samples, 0.18%)std::sys_common::net::UdpSocket::send_to (661 samples, 0.17%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (38 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (38 samples, 0.01%)core::sync::atomic::atomic_add (38 samples, 0.01%)alloc::vec::Vec<T>::with_capacity (46 samples, 0.01%)alloc::vec::Vec<T,A>::with_capacity_in (46 samples, 0.01%)tokio::net::udp::UdpSocket::readable::{{closure}} (474 samples, 0.13%)tokio::net::udp::UdpSocket::ready::{{closure}} (454 samples, 0.12%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (655 samples, 0.17%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (79 samples, 0.02%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (58 samples, 0.02%)__rdl_alloc (49 samples, 0.01%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (49 samples, 0.01%)std::sys::pal::unix::alloc::aligned_malloc (49 samples, 0.01%)core::option::Option<T>::map (299 samples, 0.08%)tokio::task::spawn::spawn_inner::{{closure}} (299 samples, 0.08%)tokio::runtime::scheduler::Handle::spawn (299 samples, 0.08%)tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (299 samples, 0.08%)tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (299 samples, 0.08%)tokio::runtime::task::list::OwnedTasks<S>::bind (287 samples, 0.08%)tokio::runtime::task::new_task (278 samples, 0.07%)tokio::runtime::task::raw::RawTask::new (278 samples, 0.07%)tokio::runtime::task::core::Cell<T,S>::new (278 samples, 0.07%)alloc::boxed::Box<T>::new (56 samples, 0.01%)alloc::alloc::exchange_malloc (56 samples, 0.01%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (56 samples, 0.01%)alloc::alloc::Global::alloc_impl (56 samples, 0.01%)alloc::alloc::alloc (56 samples, 0.01%)torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (1,073 samples, 0.28%)torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (1,073 samples, 0.28%)torrust_tracker::servers::udp::server::Udp::spawn_request_processor (300 samples, 0.08%)tokio::task::spawn::spawn (300 samples, 0.08%)tokio::task::spawn::spawn_inner (300 samples, 0.08%)tokio::runtime::context::current::with_current (300 samples, 0.08%)std::thread::local::LocalKey<T>::try_with (300 samples, 0.08%)tokio::runtime::context::current::with_current::{{closure}} (300 samples, 0.08%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (81 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (62 samples, 0.02%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (353 samples, 0.09%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (273 samples, 0.07%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (191 samples, 0.05%)core::option::Option<T>::is_some_and (46 samples, 0.01%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (45 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (44 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (44 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (61 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (48 samples, 0.01%)core::sync::atomic::AtomicU32::load (46 samples, 0.01%)core::sync::atomic::atomic_load (46 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (74 samples, 0.02%)std::sync::rwlock::RwLock<T>::read (68 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read (65 samples, 0.02%)tracing::span::Span::log (64 samples, 0.02%)core::fmt::Arguments::new_v1 (39 samples, 0.01%)tracing_core::span::Record::is_empty (67 samples, 0.02%)tracing_core::field::ValueSet::is_empty (67 samples, 0.02%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::all (43 samples, 0.01%)tracing::span::Span::record_all (253 samples, 0.07%)unlink_chunk (517 samples, 0.14%)uuid::builder::Builder::with_variant (112 samples, 0.03%)__entry_text_start (86 samples, 0.02%)uuid::builder::Builder::from_random_bytes (150 samples, 0.04%)uuid::builder::Builder::with_version (38 samples, 0.01%)__entry_text_start (187 samples, 0.05%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (433 samples, 0.11%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (433 samples, 0.11%)rand::rng::Rng::gen (445 samples, 0.12%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (445 samples, 0.12%)rand::rng::Rng::gen (445 samples, 0.12%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (445 samples, 0.12%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (445 samples, 0.12%)[unknown] (62,585 samples, 16.54%)[unknown]uuid::v4::<impl uuid::Uuid>::new_v4 (699 samples, 0.18%)uuid::rng::bytes (533 samples, 0.14%)rand::random (533 samples, 0.14%)__entry_text_start (59 samples, 0.02%)__GI___libc_malloc (138 samples, 0.04%)__memcpy_avx512_unaligned_erms (107 samples, 0.03%)_int_free (89 samples, 0.02%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (41 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (73 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::grow_amortized (64 samples, 0.02%)__perf_event_task_sched_in (42 samples, 0.01%)ctx_sched_in (42 samples, 0.01%)visit_groups_merge.constprop.0.isra.0 (42 samples, 0.01%)__x64_sys_futex (45 samples, 0.01%)do_futex (45 samples, 0.01%)futex_wait (45 samples, 0.01%)futex_wait_queue (45 samples, 0.01%)schedule (45 samples, 0.01%)__schedule (45 samples, 0.01%)finish_task_switch.isra.0 (45 samples, 0.01%)std::sys::pal::unix::futex::futex_wait (48 samples, 0.01%)syscall (48 samples, 0.01%)entry_SYSCALL_64_after_hwframe (48 samples, 0.01%)do_syscall_64 (48 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (50 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (50 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (50 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock_contended (50 samples, 0.01%)[[vdso]] (49 samples, 0.01%)[[vdso]] (43 samples, 0.01%)[[vdso]] (1,196 samples, 0.32%)__pow (1,270 samples, 0.34%)std::f64::<impl f64>::powf (1,334 samples, 0.35%)std::time::Instant::now (43 samples, 0.01%)std::sys::pal::unix::time::Instant::now (43 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::end_processing_scheduled_tasks (1,559 samples, 0.41%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_processing_scheduled_tasks (47 samples, 0.01%)std::time::Instant::now (45 samples, 0.01%)std::sys::pal::unix::time::Instant::now (45 samples, 0.01%)std::sys::pal::unix::time::Timespec::now (40 samples, 0.01%)ep_item_poll.isra.0 (48 samples, 0.01%)ep_send_events (86 samples, 0.02%)__x64_sys_epoll_wait (135 samples, 0.04%)do_epoll_wait (131 samples, 0.03%)ep_poll (124 samples, 0.03%)mio::poll::Poll::poll (144 samples, 0.04%)mio::sys::unix::selector::epoll::Selector::select (144 samples, 0.04%)epoll_wait (143 samples, 0.04%)entry_SYSCALL_64_after_hwframe (140 samples, 0.04%)do_syscall_64 (137 samples, 0.04%)tokio::runtime::io::driver::Driver::turn (157 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (169 samples, 0.04%)tokio::runtime::scheduler::multi_thread::park::Parker::park_timeout (168 samples, 0.04%)tokio::runtime::driver::Driver::park_timeout (168 samples, 0.04%)tokio::runtime::driver::TimeDriver::park_timeout (168 samples, 0.04%)tokio::runtime::time::Driver::park_timeout (168 samples, 0.04%)tokio::runtime::time::Driver::park_internal (161 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Context::maintenance (244 samples, 0.06%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (149 samples, 0.04%)alloc::sync::Arc<T,A>::inner (149 samples, 0.04%)core::ptr::non_null::NonNull<T>::as_ref (149 samples, 0.04%)core::result::Result<T,E>::is_ok (44 samples, 0.01%)core::sync::atomic::AtomicUsize::compare_exchange (43 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (43 samples, 0.01%)core::bool::<impl bool>::then (63 samples, 0.02%)__x64_sys_futex (297 samples, 0.08%)futex_setup_timer (44 samples, 0.01%)_raw_spin_unlock (43 samples, 0.01%)futex_unqueue (124 samples, 0.03%)__futex_queue (105 samples, 0.03%)plist_add (143 samples, 0.04%)_raw_spin_lock (582 samples, 0.15%)clear_buddies (87 samples, 0.02%)__update_load_avg_cfs_rq (68 samples, 0.02%)__update_load_avg_se (74 samples, 0.02%)clear_buddies (130 samples, 0.03%)update_cfs_group (489 samples, 0.13%)reweight_entity (204 samples, 0.05%)__calc_delta (373 samples, 0.10%)__cgroup_account_cputime (50 samples, 0.01%)cpuacct_charge (423 samples, 0.11%)update_curr (1,525 samples, 0.40%)update_min_vruntime (71 samples, 0.02%)__update_load_avg_cfs_rq (489 samples, 0.13%)__update_load_avg_se (418 samples, 0.11%)update_load_avg (1,435 samples, 0.38%)dequeue_entity (4,560 samples, 1.21%)update_min_vruntime (146 samples, 0.04%)update_cfs_group (222 samples, 0.06%)update_curr (42 samples, 0.01%)dequeue_task_fair (5,294 samples, 1.40%)update_min_vruntime (65 samples, 0.02%)dequeue_task (5,351 samples, 1.41%)dequeue_task_fair (63 samples, 0.02%)_raw_spin_unlock (82 samples, 0.02%)__rcu_read_unlock (179 samples, 0.05%)perf_ibs_add (421 samples, 0.11%)perf_ibs_start (364 samples, 0.10%)perf_event_update_userpage (129 samples, 0.03%)event_sched_in (736 samples, 0.19%)merge_sched_in (889 samples, 0.23%)perf_pmu_nop_int (88 samples, 0.02%)ctx_sched_in (1,272 samples, 0.34%)visit_groups_merge.constprop.0.isra.0 (1,233 samples, 0.33%)rb_next (161 samples, 0.04%)perf_ctx_enable (43 samples, 0.01%)perf_ctx_sched_task_cb (68 samples, 0.02%)perf_pmu_nop_void (75 samples, 0.02%)__perf_event_task_sched_in (1,616 samples, 0.43%)__rcu_read_unlock (40 samples, 0.01%)_raw_spin_unlock (100 samples, 0.03%)finish_task_switch.isra.0 (2,202 samples, 0.58%)pick_next_task_fair (308 samples, 0.08%)newidle_balance (193 samples, 0.05%)__rcu_read_lock (39 samples, 0.01%)pick_next_task_idle (192 samples, 0.05%)__update_idle_core (128 samples, 0.03%)put_prev_entity (53 samples, 0.01%)check_cfs_rq_runtime (38 samples, 0.01%)check_spread.isra.0 (133 samples, 0.04%)pick_next_task (1,105 samples, 0.29%)put_prev_task_fair (422 samples, 0.11%)put_prev_entity (169 samples, 0.04%)__rcu_read_unlock (39 samples, 0.01%)_raw_spin_lock (91 samples, 0.02%)perf_ibs_del (737 samples, 0.19%)perf_ibs_stop (677 samples, 0.18%)native_read_msr (236 samples, 0.06%)event_sched_out (785 samples, 0.21%)__pmu_ctx_sched_out (1,001 samples, 0.26%)group_sched_out (928 samples, 0.25%)perf_ibs_del (73 samples, 0.02%)ctx_sched_out (1,285 samples, 0.34%)sched_clock_cpu (225 samples, 0.06%)sched_clock (194 samples, 0.05%)native_sched_clock (194 samples, 0.05%)perf_ctx_disable (116 samples, 0.03%)perf_ctx_sched_task_cb (85 samples, 0.02%)perf_pmu_nop_void (71 samples, 0.02%)__perf_event_task_sched_out (1,815 samples, 0.48%)perf_event_context_sched_out (1,620 samples, 0.43%)prepare_task_switch (1,888 samples, 0.50%)psi_group_change (82 samples, 0.02%)psi_group_change (1,810 samples, 0.48%)record_times (50 samples, 0.01%)record_times (90 samples, 0.02%)psi_task_switch (2,481 samples, 0.66%)sched_clock_cpu (300 samples, 0.08%)sched_clock (256 samples, 0.07%)native_sched_clock (256 samples, 0.07%)put_prev_task_fair (111 samples, 0.03%)rcu_note_context_switch (60 samples, 0.02%)__schedule (14,876 samples, 3.93%)__sc..update_rq_clock (114 samples, 0.03%)sched_clock_cpu (81 samples, 0.02%)sched_clock (66 samples, 0.02%)native_sched_clock (66 samples, 0.02%)futex_wait_queue (15,388 samples, 4.07%)fute..schedule (15,047 samples, 3.98%)sche..__get_user_nocheck_4 (99 samples, 0.03%)_raw_spin_lock (50 samples, 0.01%)futex_hash (258 samples, 0.07%)futex_q_lock (294 samples, 0.08%)futex_q_unlock (47 samples, 0.01%)futex_wait_setup (1,137 samples, 0.30%)get_futex_key (137 samples, 0.04%)get_futex_key (71 samples, 0.02%)futex_wait (17,298 samples, 4.57%)futex..schedule (42 samples, 0.01%)do_futex (17,499 samples, 4.62%)do_fu..__x64_sys_futex (17,785 samples, 4.70%)__x64..do_futex (50 samples, 0.01%)__put_user_8 (417 samples, 0.11%)__get_user_8 (293 samples, 0.08%)__rseq_handle_notify_resume (2,024 samples, 0.53%)rseq_ip_fixup (472 samples, 0.12%)rseq_get_rseq_cs.isra.0 (88 samples, 0.02%)blkcg_maybe_throttle_current (123 samples, 0.03%)mem_cgroup_handle_over_high (234 samples, 0.06%)exit_to_user_mode_loop (2,785 samples, 0.74%)mem_cgroup_handle_over_high (59 samples, 0.02%)exit_to_user_mode_prepare (3,301 samples, 0.87%)switch_fpu_return (62 samples, 0.02%)fpregs_assert_state_consistent (42 samples, 0.01%)do_syscall_64 (21,396 samples, 5.65%)do_sysc..syscall_exit_to_user_mode (3,407 samples, 0.90%)entry_SYSCALL_64_after_hwframe (21,799 samples, 5.76%)entry_S..std::sys::pal::unix::futex::futex_wait (22,733 samples, 6.01%)std::sys..syscall (22,455 samples, 5.93%)syscallsyscall_return_via_sysret (192 samples, 0.05%)core::result::Result<T,E>::is_err (236 samples, 0.06%)core::result::Result<T,E>::is_ok (236 samples, 0.06%)std::sync::condvar::Condvar::wait (22,990 samples, 6.08%)std::syn..std::sys::sync::condvar::futex::Condvar::wait (22,989 samples, 6.08%)std::sys..std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (22,989 samples, 6.08%)std::sys..std::sys::sync::mutex::futex::Mutex::lock (256 samples, 0.07%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (23,237 samples, 6.14%)tokio::r..tokio::loom::std::mutex::Mutex<T>::lock (175 samples, 0.05%)std::sync::mutex::Mutex<T>::lock (86 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (82 samples, 0.02%)core::sync::atomic::AtomicU32::compare_exchange (82 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (82 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (127 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Parker::park (102 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::park (102 samples, 0.03%)core::array::<impl core::default::Default for [T: 32]>::default (58 samples, 0.02%)tokio::runtime::time::wheel::level::Level::next_occupied_slot (104 samples, 0.03%)tokio::runtime::time::wheel::level::level_range (41 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_expiration (204 samples, 0.05%)tokio::runtime::time::wheel::level::slot_range (48 samples, 0.01%)core::num::<impl usize>::pow (48 samples, 0.01%)tokio::runtime::time::wheel::Wheel::next_expiration (389 samples, 0.10%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::is_empty (61 samples, 0.02%)core::option::Option<T>::is_some (61 samples, 0.02%)tokio::runtime::time::wheel::level::Level::next_expiration (60 samples, 0.02%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (597 samples, 0.16%)tokio::runtime::time::wheel::Wheel::poll_at (82 samples, 0.02%)tokio::runtime::time::wheel::Wheel::next_expiration (70 samples, 0.02%)core::option::Option<T>::map (163 samples, 0.04%)<mio::event::events::Iter as core::iter::traits::iterator::Iterator>::next (174 samples, 0.05%)core::result::Result<T,E>::map (82 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (82 samples, 0.02%)alloc::vec::Vec<T,A>::set_len (51 samples, 0.01%)[[vdso]] (152 samples, 0.04%)__GI___pthread_disable_asynccancel (86 samples, 0.02%)__x64_sys_epoll_wait (99 samples, 0.03%)__fget_light (521 samples, 0.14%)__fdget (595 samples, 0.16%)__rcu_read_unlock (60 samples, 0.02%)__put_user_nocheck_4 (916 samples, 0.24%)__put_user_nocheck_8 (1,566 samples, 0.41%)_raw_write_lock_irq (418 samples, 0.11%)queued_write_lock_slowpath (97 samples, 0.03%)_raw_write_unlock_irq (119 samples, 0.03%)ep_done_scan (55 samples, 0.01%)__pm_relax (54 samples, 0.01%)_raw_write_lock_irq (1,420 samples, 0.38%)queued_write_lock_slowpath (237 samples, 0.06%)_raw_write_unlock_irq (256 samples, 0.07%)_raw_write_lock_irq (1,302 samples, 0.34%)queued_write_lock_slowpath (356 samples, 0.09%)_raw_write_unlock_irq (135 samples, 0.04%)ep_done_scan (1,745 samples, 0.46%)eventfd_poll (107 samples, 0.03%)sock_poll (4,183 samples, 1.11%)udp_poll (3,029 samples, 0.80%)datagram_poll (2,364 samples, 0.62%)ep_item_poll.isra.0 (4,869 samples, 1.29%)udp_poll (92 samples, 0.02%)mutex_lock (697 samples, 0.18%)ep_send_events (9,657 samples, 2.55%)ep..sock_poll (71 samples, 0.02%)mutex_unlock (1,230 samples, 0.33%)_raw_spin_lock_irqsave (40 samples, 0.01%)hrtimer_init_sleeper (55 samples, 0.01%)__hrtimer_init (47 samples, 0.01%)enqueue_hrtimer (76 samples, 0.02%)timerqueue_add (55 samples, 0.01%)__hrtimer_start_range_ns (185 samples, 0.05%)_raw_spin_lock_irqsave (98 samples, 0.03%)__raw_spin_lock_irqsave (98 samples, 0.03%)hrtimer_start_range_ns (349 samples, 0.09%)rb_erase (52 samples, 0.01%)__remove_hrtimer (120 samples, 0.03%)_raw_spin_lock_irqsave (125 samples, 0.03%)__raw_spin_lock_irqsave (123 samples, 0.03%)hrtimer_try_to_cancel (380 samples, 0.10%)_raw_spin_lock (103 samples, 0.03%)clear_buddies (64 samples, 0.02%)__update_load_avg_cfs_rq (53 samples, 0.01%)__update_load_avg_se (58 samples, 0.02%)clear_buddies (87 samples, 0.02%)update_cfs_group (299 samples, 0.08%)reweight_entity (137 samples, 0.04%)__calc_delta (268 samples, 0.07%)__cgroup_account_cputime (46 samples, 0.01%)cpuacct_charge (227 samples, 0.06%)update_curr (885 samples, 0.23%)update_min_vruntime (41 samples, 0.01%)__update_load_avg_cfs_rq (348 samples, 0.09%)__update_load_avg_se (251 samples, 0.07%)update_load_avg (968 samples, 0.26%)dequeue_entity (2,967 samples, 0.78%)update_min_vruntime (92 samples, 0.02%)update_cfs_group (119 samples, 0.03%)dequeue_task_fair (3,442 samples, 0.91%)dequeue_task (3,487 samples, 0.92%)dequeue_task_fair (42 samples, 0.01%)_raw_spin_unlock (55 samples, 0.01%)perf_ibs_add (51 samples, 0.01%)perf_ibs_start (42 samples, 0.01%)event_sched_in (79 samples, 0.02%)merge_sched_in (116 samples, 0.03%)ctx_sched_in (250 samples, 0.07%)visit_groups_merge.constprop.0.isra.0 (226 samples, 0.06%)rb_next (57 samples, 0.02%)perf_ctx_sched_task_cb (49 samples, 0.01%)perf_pmu_nop_void (45 samples, 0.01%)__perf_event_task_sched_in (505 samples, 0.13%)_raw_spin_unlock (65 samples, 0.02%)finish_task_switch.isra.0 (876 samples, 0.23%)newidle_balance (124 samples, 0.03%)pick_next_task_fair (200 samples, 0.05%)pick_next_task_idle (154 samples, 0.04%)__update_idle_core (95 samples, 0.03%)put_prev_entity (44 samples, 0.01%)check_spread.isra.0 (78 samples, 0.02%)pick_next_task (735 samples, 0.19%)put_prev_task_fair (269 samples, 0.07%)put_prev_entity (106 samples, 0.03%)_raw_spin_lock (72 samples, 0.02%)perf_ibs_del (525 samples, 0.14%)perf_ibs_stop (478 samples, 0.13%)native_read_msr (186 samples, 0.05%)event_sched_out (557 samples, 0.15%)__pmu_ctx_sched_out (682 samples, 0.18%)group_sched_out (639 samples, 0.17%)perf_ibs_del (52 samples, 0.01%)ctx_sched_out (932 samples, 0.25%)sched_clock_cpu (202 samples, 0.05%)sched_clock (184 samples, 0.05%)native_sched_clock (184 samples, 0.05%)perf_ctx_disable (49 samples, 0.01%)perf_ctx_sched_task_cb (56 samples, 0.01%)__perf_event_task_sched_out (1,260 samples, 0.33%)perf_event_context_sched_out (1,125 samples, 0.30%)prepare_task_switch (1,336 samples, 0.35%)psi_group_change (71 samples, 0.02%)psi_group_change (1,302 samples, 0.34%)record_times (58 samples, 0.02%)record_times (60 samples, 0.02%)psi_task_switch (1,806 samples, 0.48%)sched_clock_cpu (152 samples, 0.04%)sched_clock (134 samples, 0.04%)native_sched_clock (134 samples, 0.04%)put_prev_task_fair (57 samples, 0.02%)__schedule (9,010 samples, 2.38%)__..update_rq_clock (151 samples, 0.04%)sched_clock_cpu (126 samples, 0.03%)sched_clock (113 samples, 0.03%)native_sched_clock (113 samples, 0.03%)schedule_hrtimeout_range (10,138 samples, 2.68%)sc..schedule_hrtimeout_range_clock (10,108 samples, 2.67%)sc..schedule (9,099 samples, 2.40%)sc..ktime_get_ts64 (80 samples, 0.02%)read_tsc (561 samples, 0.15%)select_estimate_accuracy (800 samples, 0.21%)ep_poll (25,387 samples, 6.71%)ep_pollschedule_hrtimeout_range (48 samples, 0.01%)do_epoll_wait (26,191 samples, 6.92%)do_epoll_..fput (140 samples, 0.04%)ktime_get_ts64 (245 samples, 0.06%)read_tsc (625 samples, 0.17%)__x64_sys_epoll_wait (27,553 samples, 7.28%)__x64_sys_..__put_user_8 (200 samples, 0.05%)__get_user_8 (189 samples, 0.05%)__rseq_handle_notify_resume (1,198 samples, 0.32%)rseq_ip_fixup (299 samples, 0.08%)rseq_get_rseq_cs.isra.0 (38 samples, 0.01%)mem_cgroup_handle_over_high (38 samples, 0.01%)exit_to_user_mode_loop (1,413 samples, 0.37%)exit_to_user_mode_prepare (1,731 samples, 0.46%)syscall_exit_to_user_mode (1,821 samples, 0.48%)do_syscall_64 (29,522 samples, 7.80%)do_syscall_..entry_SYSCALL_64_after_hwframe (29,687 samples, 7.85%)entry_SYSCA..syscall_return_via_sysret (120 samples, 0.03%)epoll_wait (30,473 samples, 8.05%)epoll_waitmio::poll::Poll::poll (30,680 samples, 8.11%)mio::poll::..mio::sys::unix::selector::epoll::Selector::select (30,680 samples, 8.11%)mio::sys::u..tokio::io::ready::Ready::from_mio (42 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (398 samples, 0.11%)tokio::util::bit::Pack::pack (313 samples, 0.08%)core::result::Result<T,E>::is_err (61 samples, 0.02%)core::result::Result<T,E>::is_ok (61 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (119 samples, 0.03%)std::sync::mutex::Mutex<T>::lock (117 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::lock (92 samples, 0.02%)tokio::runtime::io::driver::Driver::turn (31,755 samples, 8.39%)tokio::runti..tokio::runtime::io::scheduled_io::ScheduledIo::wake (430 samples, 0.11%)__GI___clock_gettime (38 samples, 0.01%)std::sys::pal::unix::time::Timespec::now (41 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process (52 samples, 0.01%)tokio::runtime::time::source::TimeSource::now (52 samples, 0.01%)tokio::time::clock::Clock::now (43 samples, 0.01%)tokio::time::clock::now (43 samples, 0.01%)std::time::Instant::now (43 samples, 0.01%)std::sys::pal::unix::time::Instant::now (43 samples, 0.01%)std::sys::pal::unix::time::Timespec::now (45 samples, 0.01%)tokio::runtime::time::source::TimeSource::now (56 samples, 0.01%)tokio::time::clock::Clock::now (49 samples, 0.01%)tokio::time::clock::now (49 samples, 0.01%)std::time::Instant::now (49 samples, 0.01%)std::sys::pal::unix::time::Instant::now (49 samples, 0.01%)tokio::runtime::time::Driver::park_internal (31,983 samples, 8.45%)tokio::runti..tokio::runtime::scheduler::multi_thread::park::Inner::park_driver (32,791 samples, 8.67%)tokio::runti..tokio::runtime::driver::Driver::park (32,760 samples, 8.66%)tokio::runti..tokio::runtime::driver::TimeDriver::park (32,760 samples, 8.66%)tokio::runti..tokio::runtime::time::Driver::park (32,760 samples, 8.66%)tokio::runti..tokio::runtime::scheduler::multi_thread::park::Parker::park (56,209 samples, 14.86%)tokio::runtime::schedul..tokio::runtime::scheduler::multi_thread::park::Inner::park (56,209 samples, 14.86%)tokio::runtime::schedul..tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (56,281 samples, 14.87%)tokio::runtime::schedul..core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (121 samples, 0.03%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (121 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::unlock (115 samples, 0.03%)std::sync::mutex::MutexGuard<T>::new (121 samples, 0.03%)std::sync::poison::Flag::guard (117 samples, 0.03%)std::thread::panicking (114 samples, 0.03%)std::panicking::panicking (114 samples, 0.03%)std::panicking::panic_count::count_is_zero (114 samples, 0.03%)core::sync::atomic::AtomicUsize::load (108 samples, 0.03%)core::sync::atomic::atomic_load (108 samples, 0.03%)core::result::Result<T,E>::is_err (207 samples, 0.05%)core::result::Result<T,E>::is_ok (207 samples, 0.05%)core::sync::atomic::AtomicU32::compare_exchange (128 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (128 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (599 samples, 0.16%)std::sync::mutex::Mutex<T>::lock (594 samples, 0.16%)std::sys::sync::mutex::futex::Mutex::lock (473 samples, 0.13%)std::sys::sync::mutex::futex::Mutex::lock_contended (134 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::spin (96 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::maintenance (806 samples, 0.21%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (80 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (80 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (48 samples, 0.01%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (589 samples, 0.16%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (589 samples, 0.16%)core::slice::<impl [T]>::contains (1,373 samples, 0.36%)<T as core::slice::cmp::SliceContains>::slice_contains (1,373 samples, 0.36%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (1,373 samples, 0.36%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (309 samples, 0.08%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (309 samples, 0.08%)core::result::Result<T,E>::is_err (50 samples, 0.01%)core::result::Result<T,E>::is_ok (50 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (59 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (59 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (1,625 samples, 0.43%)tokio::loom::std::mutex::Mutex<T>::lock (169 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (168 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (136 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (1,675 samples, 0.44%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (95 samples, 0.03%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (95 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::unlock (88 samples, 0.02%)core::result::Result<T,E>::is_err (163 samples, 0.04%)core::result::Result<T,E>::is_ok (163 samples, 0.04%)tokio::loom::std::mutex::Mutex<T>::lock (342 samples, 0.09%)std::sync::mutex::Mutex<T>::lock (341 samples, 0.09%)std::sys::sync::mutex::futex::Mutex::lock (318 samples, 0.08%)std::sys::sync::mutex::futex::Mutex::lock_contended (117 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::spin (81 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (512 samples, 0.14%)tokio::runtime::scheduler::multi_thread::idle::State::dec_num_unparked (67 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::is_empty (57 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::is_empty (46 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock_contended (61 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::spin (53 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (88 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (88 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (78 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_if_work_pending (287 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (201 samples, 0.05%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (201 samples, 0.05%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (100 samples, 0.03%)core::sync::atomic::AtomicUsize::fetch_add (98 samples, 0.03%)core::sync::atomic::atomic_add (98 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::park (60,093 samples, 15.88%)tokio::runtime::schedule..tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (898 samples, 0.24%)core::cell::RefCell<T>::borrow_mut (81 samples, 0.02%)core::cell::RefCell<T>::try_borrow_mut (81 samples, 0.02%)core::cell::BorrowRefMut::new (81 samples, 0.02%)tokio::runtime::context::budget (60 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (60 samples, 0.02%)[[vdso]] (62 samples, 0.02%)__memcpy_avx512_unaligned_erms (434 samples, 0.11%)__memcpy_avx512_unaligned_erms (591 samples, 0.16%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (596 samples, 0.16%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (596 samples, 0.16%)std::panic::catch_unwind (1,053 samples, 0.28%)std::panicking::try (1,053 samples, 0.28%)std::panicking::try::do_call (1,053 samples, 0.28%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (1,053 samples, 0.28%)core::ops::function::FnOnce::call_once (1,053 samples, 0.28%)tokio::runtime::task::harness::Harness<T,S>::complete::{{closure}} (1,053 samples, 0.28%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (1,053 samples, 0.28%)tokio::runtime::task::core::Core<T,S>::set_stage (1,041 samples, 0.28%)<core::option::Option<T> as core::ops::try_trait::Try>::branch (38 samples, 0.01%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (76 samples, 0.02%)core::result::Result<T,E>::is_err (750 samples, 0.20%)core::result::Result<T,E>::is_ok (750 samples, 0.20%)tokio::runtime::task::harness::Harness<T,S>::complete (2,086 samples, 0.55%)tokio::runtime::task::harness::Harness<T,S>::release (1,033 samples, 0.27%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (1,023 samples, 0.27%)tokio::runtime::task::list::OwnedTasks<S>::remove (1,023 samples, 0.27%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (892 samples, 0.24%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (788 samples, 0.21%)tokio::loom::std::mutex::Mutex<T>::lock (775 samples, 0.20%)std::sync::mutex::Mutex<T>::lock (775 samples, 0.20%)std::sys::sync::mutex::futex::Mutex::lock (771 samples, 0.20%)core::cell::RefCell<T>::borrow_mut (42 samples, 0.01%)core::cell::RefCell<T>::try_borrow_mut (42 samples, 0.01%)core::cell::BorrowRefMut::new (42 samples, 0.01%)tokio::runtime::coop::budget (46 samples, 0.01%)tokio::runtime::coop::with_budget (46 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (86 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (212 samples, 0.06%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (71 samples, 0.02%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (139 samples, 0.04%)core::sync::atomic::AtomicUsize::fetch_add (115 samples, 0.03%)core::sync::atomic::atomic_add (115 samples, 0.03%)__memcpy_avx512_unaligned_erms (138 samples, 0.04%)core::ptr::drop_in_place<alloc::sync::Arc<tokio::net::udp::UdpSocket>> (174 samples, 0.05%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (174 samples, 0.05%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker::core::Tracker>> (282 samples, 0.07%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (282 samples, 0.07%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (53 samples, 0.01%)std::io::cursor::Cursor<T>::remaining_slice (58 samples, 0.02%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (103 samples, 0.03%)std::io::impls::<impl std::io::Read for &[u8]>::read_exact (45 samples, 0.01%)byteorder::io::ReadBytesExt::read_i32 (108 samples, 0.03%)std::io::cursor::Cursor<T>::remaining_slice (55 samples, 0.01%)byteorder::io::ReadBytesExt::read_i64 (57 samples, 0.02%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (57 samples, 0.02%)aquatic_udp_protocol::request::Request::from_bytes (1,438 samples, 0.38%)__GI___lll_lock_wait_private (55 samples, 0.01%)futex_wait (38 samples, 0.01%)__x64_sys_futex (128 samples, 0.03%)_raw_spin_lock (67 samples, 0.02%)futex_hash (251 samples, 0.07%)_raw_spin_lock (190 samples, 0.05%)native_queued_spin_lock_slowpath (188 samples, 0.05%)futex_wake_mark (67 samples, 0.02%)get_futex_key (210 samples, 0.06%)_raw_spin_lock_irqsave (45 samples, 0.01%)__raw_spin_lock_irqsave (44 samples, 0.01%)__smp_call_single_queue (117 samples, 0.03%)send_call_function_single_ipi (107 samples, 0.03%)native_send_call_func_single_ipi (64 samples, 0.02%)default_send_IPI_single_phys (64 samples, 0.02%)__default_send_IPI_dest_field (54 samples, 0.01%)llist_add_batch (86 samples, 0.02%)ttwu_queue_wakelist (259 samples, 0.07%)futex_wake (1,916 samples, 0.51%)wake_up_q (702 samples, 0.19%)try_to_wake_up (671 samples, 0.18%)do_futex (2,387 samples, 0.63%)__x64_sys_futex (2,616 samples, 0.69%)futex_wake (53 samples, 0.01%)do_futex (38 samples, 0.01%)exit_to_user_mode_prepare (140 samples, 0.04%)do_syscall_64 (2,881 samples, 0.76%)syscall_exit_to_user_mode (189 samples, 0.05%)entry_SYSCALL_64_after_hwframe (3,055 samples, 0.81%)__GI___lll_lock_wake_private (3,294 samples, 0.87%)__x64_sys_futex (43 samples, 0.01%)plist_add (66 samples, 0.02%)update_cfs_group (57 samples, 0.02%)__calc_delta (40 samples, 0.01%)cpuacct_charge (53 samples, 0.01%)update_curr (190 samples, 0.05%)__update_load_avg_cfs_rq (50 samples, 0.01%)__update_load_avg_se (43 samples, 0.01%)update_load_avg (158 samples, 0.04%)dequeue_entity (565 samples, 0.15%)dequeue_task_fair (664 samples, 0.18%)dequeue_task (672 samples, 0.18%)ctx_sched_in (59 samples, 0.02%)visit_groups_merge.constprop.0.isra.0 (57 samples, 0.02%)__perf_event_task_sched_in (108 samples, 0.03%)finish_task_switch.isra.0 (172 samples, 0.05%)pick_next_task_fair (43 samples, 0.01%)pick_next_task (155 samples, 0.04%)put_prev_task_fair (50 samples, 0.01%)perf_ibs_del (92 samples, 0.02%)perf_ibs_stop (71 samples, 0.02%)event_sched_out (103 samples, 0.03%)__pmu_ctx_sched_out (133 samples, 0.04%)group_sched_out (125 samples, 0.03%)ctx_sched_out (177 samples, 0.05%)prepare_task_switch (276 samples, 0.07%)__perf_event_task_sched_out (237 samples, 0.06%)perf_event_context_sched_out (197 samples, 0.05%)psi_group_change (234 samples, 0.06%)psi_task_switch (343 samples, 0.09%)__schedule (1,782 samples, 0.47%)futex_wait_queue (1,981 samples, 0.52%)schedule (1,806 samples, 0.48%)__get_user_nocheck_4 (110 samples, 0.03%)futex_hash (112 samples, 0.03%)futex_q_lock (233 samples, 0.06%)_raw_spin_lock (85 samples, 0.02%)native_queued_spin_lock_slowpath (85 samples, 0.02%)futex_q_unlock (740 samples, 0.20%)futex_wait_setup (1,346 samples, 0.36%)futex_wait (3,533 samples, 0.93%)do_futex (3,584 samples, 0.95%)__x64_sys_futex (3,670 samples, 0.97%)__put_user_8 (52 samples, 0.01%)__rseq_handle_notify_resume (254 samples, 0.07%)exit_to_user_mode_loop (337 samples, 0.09%)exit_to_user_mode_prepare (451 samples, 0.12%)do_syscall_64 (4,206 samples, 1.11%)syscall_exit_to_user_mode (483 samples, 0.13%)entry_SYSCALL_64_after_hwframe (4,268 samples, 1.13%)__GI___lll_lock_wait_private (4,605 samples, 1.22%)futex_wait (4,488 samples, 1.19%)_int_free (5,829 samples, 1.54%)__GI___libc_free (9,251 samples, 2.44%)__..core::ptr::drop_in_place<torrust_tracker::servers::udp::UdpRequest> (9,429 samples, 2.49%)co..core::ptr::drop_in_place<alloc::vec::Vec<u8>> (9,429 samples, 2.49%)co..core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (9,429 samples, 2.49%)co..<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (9,429 samples, 2.49%)<a..<alloc::alloc::Global as core::alloc::Allocator>::deallocate (9,429 samples, 2.49%)<a..alloc::alloc::dealloc (9,429 samples, 2.49%)al..__rdl_dealloc (9,429 samples, 2.49%)__..std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (9,429 samples, 2.49%)st..tracing::span::Span::record_all (174 samples, 0.05%)unlink_chunk (168 samples, 0.04%)core::result::Result<T,E>::expect (227 samples, 0.06%)core::result::Result<T,E>::map_err (66 samples, 0.02%)__GI___clock_gettime (61 samples, 0.02%)std::sys::pal::unix::time::Timespec::now (68 samples, 0.02%)std::time::Instant::elapsed (109 samples, 0.03%)std::time::Instant::now (80 samples, 0.02%)std::sys::pal::unix::time::Instant::now (80 samples, 0.02%)std::sys::pal::unix::cvt (48 samples, 0.01%)__x64_sys_getsockname (580 samples, 0.15%)__sys_getsockname (64 samples, 0.02%)__get_user_4 (812 samples, 0.21%)__put_user_nocheck_4 (1,020 samples, 0.27%)_copy_to_user (40 samples, 0.01%)apparmor_socket_getsockname (82 samples, 0.02%)_raw_spin_lock_bh (1,657 samples, 0.44%)_raw_spin_unlock_bh (55 samples, 0.01%)ip4_datagram_release_cb (93 samples, 0.02%)dequeue_entity (62 samples, 0.02%)dequeue_task (76 samples, 0.02%)dequeue_task_fair (75 samples, 0.02%)__schedule (179 samples, 0.05%)__lock_sock (196 samples, 0.05%)schedule (180 samples, 0.05%)_raw_spin_lock_bh (83 samples, 0.02%)native_queued_spin_lock_slowpath (78 samples, 0.02%)_raw_spin_unlock_bh (125 samples, 0.03%)__local_bh_enable_ip (71 samples, 0.02%)lock_sock_nested (508 samples, 0.13%)autoremove_wake_function (166 samples, 0.04%)default_wake_function (166 samples, 0.04%)try_to_wake_up (166 samples, 0.04%)__wake_up_common (169 samples, 0.04%)__wake_up (189 samples, 0.05%)__wake_up_common_lock (188 samples, 0.05%)_raw_spin_unlock_bh (139 samples, 0.04%)__local_bh_enable_ip (118 samples, 0.03%)inet_getname (3,442 samples, 0.91%)release_sock (961 samples, 0.25%)ip4_datagram_release_cb (340 samples, 0.09%)lock_sock_nested (41 samples, 0.01%)__check_object_size.part.0 (339 samples, 0.09%)check_stack_object (284 samples, 0.08%)__check_object_size (408 samples, 0.11%)check_stack_object (69 samples, 0.02%)move_addr_to_user (2,340 samples, 0.62%)copy_user_enhanced_fast_string (1,695 samples, 0.45%)security_socket_getsockname (298 samples, 0.08%)apparmor_socket_getsockname (254 samples, 0.07%)aa_sk_perm (204 samples, 0.05%)__fget_light (1,889 samples, 0.50%)__fdget (1,912 samples, 0.51%)__sys_getsockname (10,968 samples, 2.90%)__..sockfd_lookup_light (2,045 samples, 0.54%)fput (545 samples, 0.14%)inet_getname (177 samples, 0.05%)__x64_sys_getsockname (11,723 samples, 3.10%)__x..syscall_enter_from_user_mode (48 samples, 0.01%)fpregs_assert_state_consistent (42 samples, 0.01%)exit_to_user_mode_prepare (363 samples, 0.10%)do_syscall_64 (12,453 samples, 3.29%)do_..syscall_exit_to_user_mode (571 samples, 0.15%)fpregs_assert_state_consistent (53 samples, 0.01%)entry_SYSCALL_64_after_hwframe (13,099 samples, 3.46%)ent..__GI_getsockname (13,459 samples, 3.56%)__GI..std::sys_common::net::TcpListener::socket_addr::{{closure}} (13,494 samples, 3.57%)std:..tokio::net::udp::UdpSocket::local_addr (13,569 samples, 3.59%)toki..mio::net::udp::UdpSocket::local_addr (13,568 samples, 3.59%)mio:..std::net::tcp::TcpListener::local_addr (13,568 samples, 3.59%)std:..std::sys_common::net::TcpListener::socket_addr (13,567 samples, 3.59%)std:..std::sys_common::net::sockname (13,559 samples, 3.58%)std:..[[vdso]] (338 samples, 0.09%)rand_chacha::guts::ChaCha::pos64 (177 samples, 0.05%)<ppv_lite86::soft::x2<W,G> as core::ops::arith::AddAssign>::add_assign (67 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::AddAssign>::add_assign (67 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::Add>::add (67 samples, 0.02%)core::core_arch::x86::avx2::_mm256_add_epi32 (67 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (40 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (40 samples, 0.01%)core::core_arch::x86::avx2::_mm256_shuffle_epi8 (40 samples, 0.01%)core::core_arch::x86::avx2::_mm256_or_si256 (44 samples, 0.01%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (52 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (52 samples, 0.01%)rand_chacha::guts::round (234 samples, 0.06%)rand_chacha::guts::refill_wide::impl_avx2 (472 samples, 0.12%)rand_chacha::guts::refill_wide::fn_impl (472 samples, 0.12%)rand_chacha::guts::refill_wide_impl (472 samples, 0.12%)<rand_chacha::chacha::ChaCha12Core as rand_core::block::BlockRngCore>::generate (825 samples, 0.22%)rand_chacha::guts::ChaCha::refill4 (825 samples, 0.22%)rand::rng::Rng::gen (912 samples, 0.24%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (912 samples, 0.24%)rand::rng::Rng::gen (912 samples, 0.24%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (912 samples, 0.24%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (912 samples, 0.24%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (912 samples, 0.24%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (912 samples, 0.24%)rand_core::block::BlockRng<R>::generate_and_set (848 samples, 0.22%)<rand::rngs::adapter::reseeding::ReseedingCore<R,Rsdr> as rand_core::block::BlockRngCore>::generate (847 samples, 0.22%)torrust_tracker::servers::udp::handlers::RequestId::make (941 samples, 0.25%)uuid::v4::<impl uuid::Uuid>::new_v4 (921 samples, 0.24%)uuid::rng::bytes (921 samples, 0.24%)rand::random (921 samples, 0.24%)std::sync::mutex::Mutex<T>::lock (52 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (44 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (43 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (43 samples, 0.01%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_peers_for_client (125 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_peers_for_client (68 samples, 0.02%)core::iter::traits::iterator::Iterator::collect (47 samples, 0.01%)<alloc::vec::Vec<T> as core::iter::traits::collect::FromIterator<T>>::from_iter (47 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (47 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter_nested::SpecFromIterNested<T,I>>::from_iter (47 samples, 0.01%)<core::iter::adapters::cloned::Cloned<I> as core::iter::traits::iterator::Iterator>::next (47 samples, 0.01%)<core::iter::adapters::take::Take<I> as core::iter::traits::iterator::Iterator>::next (47 samples, 0.01%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (93 samples, 0.02%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (124 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (124 samples, 0.03%)__memcmp_evex_movbe (244 samples, 0.06%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (89 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (499 samples, 0.13%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (499 samples, 0.13%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (499 samples, 0.13%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (499 samples, 0.13%)<u8 as core::slice::cmp::SliceOrd>::compare (499 samples, 0.13%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (986 samples, 0.26%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (917 samples, 0.24%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (917 samples, 0.24%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (998 samples, 0.26%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (1,222 samples, 0.32%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (1,079 samples, 0.29%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (41 samples, 0.01%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (40 samples, 0.01%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (173 samples, 0.05%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (251 samples, 0.07%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (251 samples, 0.07%)core::slice::iter::Iter<T>::post_inc_start (78 samples, 0.02%)core::ptr::non_null::NonNull<T>::add (78 samples, 0.02%)[[vdso]] (78 samples, 0.02%)__memcmp_evex_movbe (402 samples, 0.11%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (258 samples, 0.07%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (1,036 samples, 0.27%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (1,036 samples, 0.27%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (1,036 samples, 0.27%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (1,036 samples, 0.27%)<u8 as core::slice::cmp::SliceOrd>::compare (1,036 samples, 0.27%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (1,912 samples, 0.51%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (1,824 samples, 0.48%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (1,824 samples, 0.48%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Immut,K,V,Type>::keys (55 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (1,928 samples, 0.51%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (118 samples, 0.03%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (83 samples, 0.02%)__rdl_alloc (40 samples, 0.01%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (40 samples, 0.01%)alloc::sync::Arc<T>::new (70 samples, 0.02%)alloc::boxed::Box<T>::new (70 samples, 0.02%)alloc::alloc::exchange_malloc (53 samples, 0.01%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (53 samples, 0.01%)alloc::alloc::Global::alloc_impl (53 samples, 0.01%)alloc::alloc::alloc (53 samples, 0.01%)core::option::Option<T>::is_some_and (58 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (58 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (56 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (56 samples, 0.01%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (423 samples, 0.11%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (391 samples, 0.10%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (272 samples, 0.07%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (2,519 samples, 0.67%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (2,482 samples, 0.66%)torrust_tracker::core::Tracker::announce::{{closure}} (3,776 samples, 1.00%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (77 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (79 samples, 0.02%)<core::time::Nanoseconds as core::hash::Hash>::hash (91 samples, 0.02%)core::hash::impls::<impl core::hash::Hash for u32>::hash (91 samples, 0.02%)core::hash::Hasher::write_u32 (91 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (91 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (91 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (91 samples, 0.02%)<core::time::Duration as core::hash::Hash>::hash (188 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for u64>::hash (97 samples, 0.03%)core::hash::Hasher::write_u64 (97 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (97 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (97 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (102 samples, 0.03%)<torrust_tracker_clock::time_extent::TimeExtent as core::hash::Hash>::hash (292 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for u64>::hash (104 samples, 0.03%)core::hash::Hasher::write_u64 (104 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (104 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (104 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (78 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (78 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (77 samples, 0.02%)core::hash::Hasher::write_length_prefix (81 samples, 0.02%)core::hash::Hasher::write_usize (81 samples, 0.02%)core::array::<impl core::hash::Hash for [T: N]>::hash (206 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (206 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (125 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (125 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (125 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (124 samples, 0.03%)core::hash::sip::u8to64_le (47 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (589 samples, 0.16%)[[vdso]] (83 samples, 0.02%)core::num::<impl u128>::checked_div (84 samples, 0.02%)_int_free (40 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::check (748 samples, 0.20%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (154 samples, 0.04%)torrust_tracker_clock::time_extent::Make::now (154 samples, 0.04%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (70 samples, 0.02%)std::time::SystemTime::now (66 samples, 0.02%)std::sys::pal::unix::time::SystemTime::now (66 samples, 0.02%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (68 samples, 0.02%)core::array::<impl core::hash::Hash for [T: N]>::hash (68 samples, 0.02%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (68 samples, 0.02%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (68 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (68 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (68 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (68 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (4,754 samples, 1.26%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (80 samples, 0.02%)<core::net::socket_addr::SocketAddrV4 as core::hash::Hash>::hash (43 samples, 0.01%)<core::net::ip_addr::Ipv4Addr as core::hash::Hash>::hash (43 samples, 0.01%)core::array::<impl core::hash::Hash for [T: N]>::hash (42 samples, 0.01%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (42 samples, 0.01%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (126 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (86 samples, 0.02%)<core::time::Nanoseconds as core::hash::Hash>::hash (104 samples, 0.03%)core::hash::impls::<impl core::hash::Hash for u32>::hash (104 samples, 0.03%)core::hash::Hasher::write_u32 (104 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (104 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (104 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (123 samples, 0.03%)<core::time::Duration as core::hash::Hash>::hash (232 samples, 0.06%)core::hash::impls::<impl core::hash::Hash for u64>::hash (128 samples, 0.03%)core::hash::Hasher::write_u64 (127 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (127 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (127 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (115 samples, 0.03%)core::hash::sip::u8to64_le (46 samples, 0.01%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (117 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (117 samples, 0.03%)<torrust_tracker_clock::time_extent::TimeExtent as core::hash::Hash>::hash (350 samples, 0.09%)core::hash::impls::<impl core::hash::Hash for u64>::hash (118 samples, 0.03%)core::hash::Hasher::write_u64 (118 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (83 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (83 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (82 samples, 0.02%)core::hash::Hasher::write_length_prefix (86 samples, 0.02%)core::hash::Hasher::write_usize (86 samples, 0.02%)core::array::<impl core::hash::Hash for [T: N]>::hash (229 samples, 0.06%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (229 samples, 0.06%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (143 samples, 0.04%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (143 samples, 0.04%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (143 samples, 0.04%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (140 samples, 0.04%)core::hash::sip::u8to64_le (44 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (710 samples, 0.19%)[[vdso]] (68 samples, 0.02%)core::num::<impl u128>::checked_div (70 samples, 0.02%)_int_free (40 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_connect::{{closure}} (887 samples, 0.23%)torrust_tracker::servers::udp::connection_cookie::make (865 samples, 0.23%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (146 samples, 0.04%)torrust_tracker_clock::time_extent::Make::now (145 samples, 0.04%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (75 samples, 0.02%)std::time::SystemTime::now (70 samples, 0.02%)std::sys::pal::unix::time::SystemTime::now (70 samples, 0.02%)hashbrown::raw::RawTable<T,A>::reserve (47 samples, 0.01%)hashbrown::map::HashMap<K,V,S,A>::insert (59 samples, 0.02%)hashbrown::raw::RawTable<T,A>::find_or_find_insert_slot (49 samples, 0.01%)torrust_tracker::core::ScrapeData::add_file (61 samples, 0.02%)std::collections::hash::map::HashMap<K,V,S>::insert (61 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (146 samples, 0.04%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (138 samples, 0.04%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (138 samples, 0.04%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (70 samples, 0.02%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (70 samples, 0.02%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (70 samples, 0.02%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (70 samples, 0.02%)<u8 as core::slice::cmp::SliceOrd>::compare (70 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (147 samples, 0.04%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (5,947 samples, 1.57%)torrust_tracker::servers::udp::handlers::handle_scrape::{{closure}} (265 samples, 0.07%)torrust_tracker::core::Tracker::scrape::{{closure}} (243 samples, 0.06%)torrust_tracker::core::Tracker::get_swarm_metadata (176 samples, 0.05%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (156 samples, 0.04%)<alloc::string::String as core::fmt::Write>::write_str (54 samples, 0.01%)alloc::string::String::push_str (51 samples, 0.01%)alloc::vec::Vec<T,A>::extend_from_slice (51 samples, 0.01%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (51 samples, 0.01%)alloc::vec::Vec<T,A>::append_elements (51 samples, 0.01%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (186 samples, 0.05%)core::fmt::num::imp::fmt_u64 (178 samples, 0.05%)core::fmt::num::imp::<impl core::fmt::Display for i64>::fmt (85 samples, 0.02%)core::fmt::num::imp::fmt_u64 (84 samples, 0.02%)<T as alloc::string::ToString>::to_string (319 samples, 0.08%)core::option::Option<T>::expect (71 samples, 0.02%)__GI___libc_free (39 samples, 0.01%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (112 samples, 0.03%)alloc::alloc::dealloc (112 samples, 0.03%)__rdl_dealloc (112 samples, 0.03%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (112 samples, 0.03%)core::ptr::drop_in_place<alloc::string::String> (162 samples, 0.04%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (162 samples, 0.04%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (162 samples, 0.04%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (162 samples, 0.04%)torrust_tracker::servers::udp::logging::map_action_name (46 samples, 0.01%)binascii::bin2hex (128 samples, 0.03%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (45 samples, 0.01%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (45 samples, 0.01%)core::fmt::write (47 samples, 0.01%)core::fmt::Formatter::write_fmt (136 samples, 0.04%)core::str::converts::from_utf8 (64 samples, 0.02%)core::str::validations::run_utf8_validation (52 samples, 0.01%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (289 samples, 0.08%)torrust_tracker_primitives::info_hash::InfoHash::to_hex_string (293 samples, 0.08%)<T as alloc::string::ToString>::to_string (293 samples, 0.08%)torrust_tracker::servers::udp::logging::log_request (1,025 samples, 0.27%)[[vdso]] (111 samples, 0.03%)alloc::raw_vec::finish_grow (120 samples, 0.03%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (134 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::grow_amortized (134 samples, 0.04%)alloc::vec::Vec<T,A>::reserve (141 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::reserve (141 samples, 0.04%)<alloc::string::String as core::fmt::Write>::write_str (148 samples, 0.04%)alloc::string::String::push_str (145 samples, 0.04%)alloc::vec::Vec<T,A>::extend_from_slice (145 samples, 0.04%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (145 samples, 0.04%)alloc::vec::Vec<T,A>::append_elements (145 samples, 0.04%)[[vdso]] (52 samples, 0.01%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (286 samples, 0.08%)core::fmt::num::imp::fmt_u64 (277 samples, 0.07%)<T as alloc::string::ToString>::to_string (328 samples, 0.09%)core::option::Option<T>::expect (43 samples, 0.01%)core::ptr::drop_in_place<alloc::string::String> (51 samples, 0.01%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (51 samples, 0.01%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (51 samples, 0.01%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (51 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (33,755 samples, 8.92%)torrust_track..torrust_tracker::servers::udp::logging::log_response (613 samples, 0.16%)futex_wake (46 samples, 0.01%)do_futex (52 samples, 0.01%)__x64_sys_futex (57 samples, 0.02%)__GI___lll_lock_wake_private (63 samples, 0.02%)entry_SYSCALL_64_after_hwframe (60 samples, 0.02%)do_syscall_64 (60 samples, 0.02%)_int_malloc (252 samples, 0.07%)__libc_calloc (366 samples, 0.10%)__memcpy_avx512_unaligned_erms (86 samples, 0.02%)__memset_avx512_unaligned_erms (51 samples, 0.01%)alloc::vec::from_elem (589 samples, 0.16%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (589 samples, 0.16%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (589 samples, 0.16%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (589 samples, 0.16%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (562 samples, 0.15%)alloc::alloc::Global::alloc_impl (562 samples, 0.15%)alloc::alloc::alloc_zeroed (562 samples, 0.15%)__rdl_alloc_zeroed (562 samples, 0.15%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (562 samples, 0.15%)byteorder::ByteOrder::write_i32 (106 samples, 0.03%)<byteorder::BigEndian as byteorder::ByteOrder>::write_u32 (106 samples, 0.03%)core::num::<impl u32>::to_be_bytes (106 samples, 0.03%)core::num::<impl u32>::to_be (106 samples, 0.03%)core::num::<impl u32>::swap_bytes (106 samples, 0.03%)byteorder::io::WriteBytesExt::write_i32 (315 samples, 0.08%)std::io::Write::write_all (208 samples, 0.05%)<std::io::cursor::Cursor<alloc::vec::Vec<u8,A>> as std::io::Write>::write (208 samples, 0.05%)std::io::cursor::vec_write (208 samples, 0.05%)std::io::cursor::vec_write_unchecked (132 samples, 0.03%)core::ptr::mut_ptr::<impl *mut T>::copy_from (132 samples, 0.03%)core::intrinsics::copy (132 samples, 0.03%)aquatic_udp_protocol::response::Response::write (634 samples, 0.17%)byteorder::io::WriteBytesExt::write_i64 (65 samples, 0.02%)std::io::Write::write_all (43 samples, 0.01%)<std::io::cursor::Cursor<alloc::vec::Vec<u8,A>> as std::io::Write>::write (43 samples, 0.01%)std::io::cursor::vec_write (43 samples, 0.01%)std::io::cursor::vec_write_unchecked (43 samples, 0.01%)core::ptr::mut_ptr::<impl *mut T>::copy_from (43 samples, 0.01%)core::intrinsics::copy (43 samples, 0.01%)_int_free (514 samples, 0.14%)__GI___libc_free (669 samples, 0.18%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (685 samples, 0.18%)alloc::alloc::dealloc (685 samples, 0.18%)__rdl_dealloc (685 samples, 0.18%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (685 samples, 0.18%)core::ptr::drop_in_place<std::io::cursor::Cursor<alloc::vec::Vec<u8>>> (701 samples, 0.19%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (701 samples, 0.19%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (701 samples, 0.19%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (701 samples, 0.19%)std::io::cursor::Cursor<T>::new (38 samples, 0.01%)core::ptr::drop_in_place<tokio::net::udp::UdpSocket::send_to<&core::net::socket_addr::SocketAddr>::{{closure}}> (48 samples, 0.01%)<F as core::future::into_future::IntoFuture>::into_future (45 samples, 0.01%)tokio::io::ready::Ready::intersection (115 samples, 0.03%)tokio::io::ready::Ready::from_interest (112 samples, 0.03%)tokio::io::interest::Interest::is_readable (90 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (369 samples, 0.10%)__GI___pthread_disable_asynccancel (147 samples, 0.04%)__x64_sys_sendto (620 samples, 0.16%)__sys_sendto (40 samples, 0.01%)__check_object_size.part.0 (98 samples, 0.03%)check_stack_object (69 samples, 0.02%)__check_object_size (126 samples, 0.03%)_copy_from_user (248 samples, 0.07%)move_addr_to_kernel (1,485 samples, 0.39%)copy_user_enhanced_fast_string (840 samples, 0.22%)apparmor_socket_sendmsg (984 samples, 0.26%)__rcu_read_lock (164 samples, 0.04%)__rcu_read_unlock (68 samples, 0.02%)inet_send_prepare (44 samples, 0.01%)ip_make_skb (46 samples, 0.01%)ip_route_output_flow (54 samples, 0.01%)security_sk_classify_flow (48 samples, 0.01%)__ip_append_data (56 samples, 0.01%)__rcu_read_lock (60 samples, 0.02%)__rcu_read_unlock (54 samples, 0.01%)__check_object_size (55 samples, 0.01%)alloc_skb_with_frags (38 samples, 0.01%)__check_object_size.part.0 (42 samples, 0.01%)__check_heap_object (206 samples, 0.05%)__virt_addr_valid (473 samples, 0.13%)check_heap_object (1,244 samples, 0.33%)__check_object_size.part.0 (1,487 samples, 0.39%)is_vmalloc_addr (68 samples, 0.02%)__check_object_size (1,571 samples, 0.42%)check_stack_object (57 samples, 0.02%)_copy_from_iter (469 samples, 0.12%)ip_generic_getfrag (3,554 samples, 0.94%)copy_user_enhanced_fast_string (1,329 samples, 0.35%)__build_skb_around (233 samples, 0.06%)__kmalloc_node_track_caller (74 samples, 0.02%)___slab_alloc (129 samples, 0.03%)memcg_slab_post_alloc_hook (87 samples, 0.02%)__kmem_cache_alloc_node (1,044 samples, 0.28%)kmalloc_slab (40 samples, 0.01%)memset_erms (331 samples, 0.09%)__kmalloc_node_track_caller (1,662 samples, 0.44%)__kmem_cache_alloc_node (57 samples, 0.02%)kmalloc_reserve (1,865 samples, 0.49%)kmalloc_size_roundup (156 samples, 0.04%)kmalloc_slab (94 samples, 0.02%)___slab_alloc (69 samples, 0.02%)memcg_slab_post_alloc_hook (59 samples, 0.02%)kmem_cache_alloc_node (700 samples, 0.19%)memset_erms (98 samples, 0.03%)__alloc_skb (4,155 samples, 1.10%)alloc_skb_with_frags (4,425 samples, 1.17%)kmem_cache_alloc_node (48 samples, 0.01%)__ip_append_data (11,490 samples, 3.04%)__i..sock_alloc_send_pskb (6,335 samples, 1.67%)skb_set_owner_w (1,576 samples, 0.42%)__ip_select_ident (1,244 samples, 0.33%)ipv4_mtu (151 samples, 0.04%)__ip_make_skb (3,290 samples, 0.87%)siphash_3u32 (619 samples, 0.16%)ip_generic_getfrag (113 samples, 0.03%)ip_setup_cork (313 samples, 0.08%)ipv4_mtu (121 samples, 0.03%)ipv4_mtu (67 samples, 0.02%)ip_make_skb (15,572 samples, 4.12%)ip_m..__rcu_read_lock (38 samples, 0.01%)__rcu_read_unlock (50 samples, 0.01%)__mkroute_output (806 samples, 0.21%)fib_table_lookup (1,252 samples, 0.33%)fib_lookup_good_nhc (418 samples, 0.11%)ip_route_output_key_hash_rcu (2,298 samples, 0.61%)xfrm_lookup_route (258 samples, 0.07%)xfrm_lookup_with_ifid (213 samples, 0.06%)ip_route_output_flow (3,011 samples, 0.80%)security_sk_classify_flow (115 samples, 0.03%)ip_send_check (954 samples, 0.25%)ipv4_conntrack_defrag (148 samples, 0.04%)ipv4_conntrack_local (711 samples, 0.19%)ipv4_conntrack_defrag (219 samples, 0.06%)get_l4proto (223 samples, 0.06%)hash_conntrack_raw (101 samples, 0.03%)__nf_ct_refresh_acct (57 samples, 0.02%)nf_conntrack_handle_packet (676 samples, 0.18%)nf_conntrack_udp_packet (578 samples, 0.15%)nf_ct_get_tuple (65 samples, 0.02%)__nf_conntrack_find_get (1,301 samples, 0.34%)__rcu_read_lock (58 samples, 0.02%)hash_conntrack_raw (427 samples, 0.11%)nf_ct_get_tuple (421 samples, 0.11%)nf_conntrack_in (4,938 samples, 1.31%)resolve_normal_ct (3,247 samples, 0.86%)siphash_4u64 (690 samples, 0.18%)ipv4_conntrack_local (5,156 samples, 1.36%)nf_nat_inet_fn (43 samples, 0.01%)nf_hook_slow (6,435 samples, 1.70%)nf_nat_ipv4_local_fn (718 samples, 0.19%)nf_nat_inet_fn (362 samples, 0.10%)__ip_local_out (8,585 samples, 2.27%)_..nf_nat_ipv4_local_fn (174 samples, 0.05%)__rcu_read_lock (88 samples, 0.02%)__rcu_read_unlock (218 samples, 0.06%)__ip_finish_output (43 samples, 0.01%)__x86_indirect_thunk_rax (62 samples, 0.02%)apparmor_ip_postroute (470 samples, 0.12%)__usecs_to_jiffies (74 samples, 0.02%)_raw_spin_lock_irq (128 samples, 0.03%)_raw_spin_unlock_irq (76 samples, 0.02%)__netif_receive_skb_core.constprop.0 (52 samples, 0.01%)__netif_receive_skb_core.constprop.0 (564 samples, 0.15%)__rcu_read_unlock (54 samples, 0.01%)__rcu_read_unlock (89 samples, 0.02%)__rcu_read_lock (67 samples, 0.02%)__rcu_read_lock (57 samples, 0.02%)__rcu_read_unlock (105 samples, 0.03%)raw_local_deliver (389 samples, 0.10%)raw_v4_input (221 samples, 0.06%)raw_v4_input (38 samples, 0.01%)__udp4_lib_lookup (49 samples, 0.01%)__udp4_lib_lookup (504 samples, 0.13%)udp4_lib_lookup2 (352 samples, 0.09%)udp4_csum_init (812 samples, 0.21%)__udp_enqueue_schedule_skb (59 samples, 0.02%)__rcu_read_lock (61 samples, 0.02%)mem_cgroup_charge_skmem (57 samples, 0.02%)__sk_mem_raise_allocated (100 samples, 0.03%)__udp_enqueue_schedule_skb (1,313 samples, 0.35%)sock_def_readable (155 samples, 0.04%)__x86_indirect_thunk_rax (44 samples, 0.01%)__xfrm_policy_check2.constprop.0 (40 samples, 0.01%)_raw_spin_lock (493 samples, 0.13%)_raw_spin_unlock (136 samples, 0.04%)ipv4_pktinfo_prepare (380 samples, 0.10%)dst_release (281 samples, 0.07%)security_sock_rcv_skb (39 samples, 0.01%)apparmor_socket_sock_rcv_skb (106 samples, 0.03%)sk_filter_trim_cap (322 samples, 0.09%)security_sock_rcv_skb (72 samples, 0.02%)skb_pull_rcsum (53 samples, 0.01%)__udp4_lib_rcv (5,414 samples, 1.43%)udp_unicast_rcv_skb (3,792 samples, 1.00%)udp_queue_rcv_skb (3,762 samples, 0.99%)udp_queue_rcv_one_skb (3,636 samples, 0.96%)sock_def_readable (148 samples, 0.04%)udp4_csum_init (57 samples, 0.02%)ip_protocol_deliver_rcu (6,453 samples, 1.71%)udp_rcv (5,665 samples, 1.50%)udp_unicast_rcv_skb (127 samples, 0.03%)raw_local_deliver (40 samples, 0.01%)ip_local_deliver_finish (6,677 samples, 1.76%)nf_confirm (192 samples, 0.05%)nf_confirm (221 samples, 0.06%)nf_nat_inet_fn (41 samples, 0.01%)nf_hook_slow (767 samples, 0.20%)nf_nat_ipv4_local_in (316 samples, 0.08%)nf_nat_inet_fn (175 samples, 0.05%)ip_local_deliver (8,248 samples, 2.18%)i..nf_nat_ipv4_local_in (181 samples, 0.05%)ip_local_deliver_finish (75 samples, 0.02%)ip_rcv_core (309 samples, 0.08%)ip_rcv_finish_core.constprop.0 (355 samples, 0.09%)ip_sabotage_in (306 samples, 0.08%)ipv4_conntrack_defrag (138 samples, 0.04%)ipv4_conntrack_in (323 samples, 0.09%)ip_sabotage_in (69 samples, 0.02%)ipv4_conntrack_defrag (108 samples, 0.03%)ipv4_conntrack_in (282 samples, 0.07%)nf_conntrack_in (278 samples, 0.07%)nf_conntrack_in (57 samples, 0.02%)nf_hook_slow (1,381 samples, 0.36%)nf_nat_ipv4_pre_routing (432 samples, 0.11%)nf_nat_inet_fn (255 samples, 0.07%)ip_rcv (11,869 samples, 3.14%)ip_..nf_nat_ipv4_pre_routing (201 samples, 0.05%)__netif_receive_skb_one_core (12,879 samples, 3.40%)__n..nf_hook_slow (90 samples, 0.02%)__netif_receive_skb (12,980 samples, 3.43%)__n..__netif_receive_skb_one_core (61 samples, 0.02%)_raw_spin_lock_irq (716 samples, 0.19%)__napi_poll (14,705 samples, 3.89%)__na..process_backlog (14,356 samples, 3.79%)proc.._raw_spin_unlock_irq (225 samples, 0.06%)net_rx_action (15,607 samples, 4.12%)net_..process_backlog (195 samples, 0.05%)__do_softirq (16,392 samples, 4.33%)__do_..__x86_indirect_thunk_rax (38 samples, 0.01%)__local_bh_enable_ip (17,356 samples, 4.59%)__loc..do_softirq.part.0 (17,063 samples, 4.51%)do_so..net_rx_action (146 samples, 0.04%)do_softirq.part.0 (41 samples, 0.01%)__local_bh_enable_ip (78 samples, 0.02%)enqueue_to_backlog (49 samples, 0.01%)__raise_softirq_irqoff (57 samples, 0.02%)_raw_spin_unlock_irqrestore (46 samples, 0.01%)_raw_spin_lock_irqsave (321 samples, 0.08%)__raw_spin_lock_irqsave (320 samples, 0.08%)enqueue_to_backlog (898 samples, 0.24%)_raw_spin_unlock_irqrestore (120 samples, 0.03%)ktime_get_with_offset (165 samples, 0.04%)__netif_rx (2,105 samples, 0.56%)netif_rx_internal (1,977 samples, 0.52%)read_tsc (703 samples, 0.19%)__rcu_read_lock (82 samples, 0.02%)__rcu_read_unlock (38 samples, 0.01%)eth_type_trans (85 samples, 0.02%)skb_clone_tx_timestamp (158 samples, 0.04%)__wake_up_common (61 samples, 0.02%)_raw_read_unlock_irqrestore (65 samples, 0.02%)__task_rq_lock (52 samples, 0.01%)raw_spin_rq_lock_nested (48 samples, 0.01%)_raw_spin_lock (48 samples, 0.01%)native_queued_spin_lock_slowpath (48 samples, 0.01%)_raw_spin_lock_irqsave (273 samples, 0.07%)__raw_spin_lock_irqsave (273 samples, 0.07%)select_task_rq_fair (164 samples, 0.04%)wake_affine (42 samples, 0.01%)__smp_call_single_queue (224 samples, 0.06%)send_call_function_single_ipi (214 samples, 0.06%)native_send_call_func_single_ipi (117 samples, 0.03%)default_send_IPI_single_phys (115 samples, 0.03%)__default_send_IPI_dest_field (105 samples, 0.03%)llist_add_batch (149 samples, 0.04%)sched_clock_cpu (45 samples, 0.01%)sched_clock (44 samples, 0.01%)native_sched_clock (44 samples, 0.01%)ttwu_queue_wakelist (575 samples, 0.15%)try_to_wake_up (1,751 samples, 0.46%)default_wake_function (1,771 samples, 0.47%)__wake_up_common (1,874 samples, 0.50%)ep_autoremove_wake_function (1,787 samples, 0.47%)_raw_spin_lock_irqsave (179 samples, 0.05%)__raw_spin_lock_irqsave (177 samples, 0.05%)native_queued_spin_lock_slowpath (49 samples, 0.01%)__wake_up_common_lock (2,109 samples, 0.56%)__wake_up (2,115 samples, 0.56%)__raw_read_lock_irqsave (1,681 samples, 0.44%)queued_read_lock_slowpath (112 samples, 0.03%)_raw_read_lock_irqsave (1,685 samples, 0.45%)__wake_up_common (6,023 samples, 1.59%)ep_poll_callback (5,577 samples, 1.47%)_raw_read_unlock_irqrestore (549 samples, 0.15%)__raw_spin_lock_irqsave (2,457 samples, 0.65%)native_queued_spin_lock_slowpath (2,074 samples, 0.55%)_raw_spin_lock_irqsave (2,473 samples, 0.65%)_raw_spin_unlock_irqrestore (128 samples, 0.03%)__wake_up_common_lock (8,884 samples, 2.35%)_..ep_poll_callback (159 samples, 0.04%)loopback_xmit (13,069 samples, 3.45%)loo..sock_wfree (10,251 samples, 2.71%)so..__wake_up_sync_key (9,015 samples, 2.38%)__.._raw_spin_unlock_irqrestore (50 samples, 0.01%)skb_clone_tx_timestamp (43 samples, 0.01%)dev_hard_start_xmit (14,617 samples, 3.86%)dev_..sock_wfree (177 samples, 0.05%)loopback_xmit (247 samples, 0.07%)netdev_core_pick_tx (51 samples, 0.01%)qdisc_pkt_len_init (42 samples, 0.01%)netif_skb_features (232 samples, 0.06%)skb_network_protocol (98 samples, 0.03%)validate_xmit_skb (501 samples, 0.13%)validate_xmit_xfrm (46 samples, 0.01%)__dev_queue_xmit (16,029 samples, 4.24%)__dev..ip_finish_output2 (34,592 samples, 9.14%)ip_finish_out..neigh_hh_output (16,177 samples, 4.28%)neigh..ip_skb_dst_mtu (147 samples, 0.04%)__ip_finish_output (35,105 samples, 9.28%)__ip_finish_o..ip_finish_output (35,746 samples, 9.45%)ip_finish_outp..nf_confirm (341 samples, 0.09%)nf_confirm (376 samples, 0.10%)nf_hook_slow (1,736 samples, 0.46%)nf_nat_ipv4_out (902 samples, 0.24%)nf_nat_inet_fn (495 samples, 0.13%)ip_output (40,003 samples, 10.57%)ip_outputnf_nat_ipv4_out (557 samples, 0.15%)ip_send_skb (49,451 samples, 13.07%)ip_send_skbnf_hook_slow (95 samples, 0.03%)udp_send_skb (50,114 samples, 13.24%)udp_send_skbudp4_hwcsum (70 samples, 0.02%)inet_sendmsg (72,507 samples, 19.16%)inet_sendmsgudp_sendmsg (71,624 samples, 18.93%)udp_sendmsgaa_sk_perm (44 samples, 0.01%)security_socket_sendmsg (892 samples, 0.24%)apparmor_socket_sendmsg (549 samples, 0.15%)aa_sk_perm (524 samples, 0.14%)sock_sendmsg (74,871 samples, 19.79%)sock_sendmsgudp_sendmsg (43 samples, 0.01%)__fget_light (1,626 samples, 0.43%)__fdget (1,664 samples, 0.44%)__sys_sendto (79,939 samples, 21.13%)__sys_sendtosockfd_lookup_light (1,915 samples, 0.51%)__fget_light (125 samples, 0.03%)fput (954 samples, 0.25%)import_single_range (191 samples, 0.05%)sockfd_lookup_light (69 samples, 0.02%)__x64_sys_sendto (81,183 samples, 21.46%)__x64_sys_sendtoexit_to_user_mode_prepare (43 samples, 0.01%)merge_sched_in (55 samples, 0.01%)ctx_sched_in (112 samples, 0.03%)visit_groups_merge.constprop.0.isra.0 (111 samples, 0.03%)rb_next (43 samples, 0.01%)__perf_event_task_sched_in (131 samples, 0.03%)finish_task_switch.isra.0 (140 samples, 0.04%)exit_to_user_mode_loop (146 samples, 0.04%)schedule (145 samples, 0.04%)__schedule (145 samples, 0.04%)exit_to_user_mode_prepare (506 samples, 0.13%)do_syscall_64 (82,006 samples, 21.67%)do_syscall_64syscall_exit_to_user_mode (598 samples, 0.16%)syscall_enter_from_user_mode (42 samples, 0.01%)entry_SYSCALL_64_after_hwframe (82,860 samples, 21.90%)entry_SYSCALL_64_after_hwframesyscall_return_via_sysret (245 samples, 0.06%)__libc_sendto (83,829 samples, 22.16%)__libc_sendtostd::sys::pal::unix::cvt (143 samples, 0.04%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (83,973 samples, 22.19%)tokio::net::udp::UdpSocket::send_to..mio::net::udp::UdpSocket::send_to (83,973 samples, 22.19%)mio::net::udp::UdpSocket::send_tomio::io_source::IoSource<T>::do_io (83,973 samples, 22.19%)mio::io_source::IoSource<T>::do_iomio::sys::unix::stateless_io_source::IoSourceState::do_io (83,973 samples, 22.19%)mio::sys::unix::stateless_io_source..mio::net::udp::UdpSocket::send_to::{{closure}} (83,973 samples, 22.19%)mio::net::udp::UdpSocket::send_to::..std::net::udp::UdpSocket::send_to (83,973 samples, 22.19%)std::net::udp::UdpSocket::send_tostd::sys_common::net::UdpSocket::send_to (83,973 samples, 22.19%)std::sys_common::net::UdpSocket::se..core::result::Result<T,E>::is_err (368 samples, 0.10%)core::result::Result<T,E>::is_ok (368 samples, 0.10%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (420 samples, 0.11%)tokio::loom::std::mutex::Mutex<T>::lock (416 samples, 0.11%)std::sync::mutex::Mutex<T>::lock (415 samples, 0.11%)std::sys::sync::mutex::futex::Mutex::lock (412 samples, 0.11%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (85,524 samples, 22.60%)torrust_tracker::servers::udp::serve..tokio::net::udp::UdpSocket::send_to::{{closure}} (85,236 samples, 22.53%)tokio::net::udp::UdpSocket::send_to:..tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (84,989 samples, 22.46%)tokio::net::udp::UdpSocket::send_to_..tokio::runtime::io::registration::Registration::async_io::{{closure}} (84,879 samples, 22.43%)tokio::runtime::io::registration::Re..tokio::runtime::io::registration::Registration::readiness::{{closure}} (439 samples, 0.12%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (435 samples, 0.11%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (432 samples, 0.11%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (87,857 samples, 23.22%)torrust_tracker::servers::udp::server..torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (124,991 samples, 33.03%)torrust_tracker::servers::udp::server::Udp::process_r..torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (123,165 samples, 32.55%)torrust_tracker::servers::udp::server::Udp::process_v..<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (238 samples, 0.06%)core::sync::atomic::AtomicUsize::fetch_add (238 samples, 0.06%)core::sync::atomic::atomic_add (238 samples, 0.06%)futex_hash (62 samples, 0.02%)get_futex_key (42 samples, 0.01%)futex_wake (248 samples, 0.07%)wake_up_q (50 samples, 0.01%)try_to_wake_up (46 samples, 0.01%)do_futex (364 samples, 0.10%)__x64_sys_futex (407 samples, 0.11%)do_syscall_64 (468 samples, 0.12%)entry_SYSCALL_64_after_hwframe (496 samples, 0.13%)__GI___lll_lock_wake_private (552 samples, 0.15%)update_load_avg (52 samples, 0.01%)dequeue_entity (134 samples, 0.04%)dequeue_task (163 samples, 0.04%)dequeue_task_fair (160 samples, 0.04%)ctx_sched_out (43 samples, 0.01%)prepare_task_switch (66 samples, 0.02%)__perf_event_task_sched_out (59 samples, 0.02%)perf_event_context_sched_out (52 samples, 0.01%)psi_group_change (39 samples, 0.01%)psi_task_switch (63 samples, 0.02%)__schedule (390 samples, 0.10%)futex_wait_queue (413 samples, 0.11%)schedule (393 samples, 0.10%)futex_q_unlock (143 samples, 0.04%)futex_wait_setup (230 samples, 0.06%)do_futex (688 samples, 0.18%)futex_wait (678 samples, 0.18%)__x64_sys_futex (696 samples, 0.18%)__rseq_handle_notify_resume (45 samples, 0.01%)exit_to_user_mode_loop (57 samples, 0.02%)exit_to_user_mode_prepare (86 samples, 0.02%)entry_SYSCALL_64_after_hwframe (800 samples, 0.21%)do_syscall_64 (795 samples, 0.21%)syscall_exit_to_user_mode (93 samples, 0.02%)__GI___lll_lock_wait_private (860 samples, 0.23%)futex_wait (844 samples, 0.22%)_int_free (1,310 samples, 0.35%)__GI___libc_free (1,905 samples, 0.50%)syscall (58 samples, 0.02%)tokio::runtime::task::harness::Harness<T,S>::dealloc (47 samples, 0.01%)core::mem::drop (43 samples, 0.01%)core::ptr::drop_in_place<alloc::boxed::Box<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (43 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>> (43 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Core<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>> (43 samples, 0.01%)tokio::runtime::task::raw::drop_abort_handle (152 samples, 0.04%)tokio::runtime::task::harness::Harness<T,S>::drop_reference (139 samples, 0.04%)tokio::runtime::task::state::State::ref_dec (139 samples, 0.04%)core::ptr::drop_in_place<tokio::runtime::task::abort::AbortHandle> (2,198 samples, 0.58%)<tokio::runtime::task::abort::AbortHandle as core::ops::drop::Drop>::drop (2,198 samples, 0.58%)tokio::runtime::task::raw::RawTask::drop_abort_handle (2,195 samples, 0.58%)core::result::Result<T,E>::is_ok (58 samples, 0.02%)tokio::runtime::task::raw::drop_join_handle_slow (47 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::drop_join_handle_slow (43 samples, 0.01%)tokio::runtime::task::raw::RawTask::drop_join_handle_slow (78 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::join::JoinHandle<()>> (199 samples, 0.05%)<tokio::runtime::task::join::JoinHandle<T> as core::ops::drop::Drop>::drop (199 samples, 0.05%)tokio::runtime::task::state::State::drop_join_handle_fast (47 samples, 0.01%)core::sync::atomic::AtomicUsize::compare_exchange_weak (47 samples, 0.01%)core::sync::atomic::atomic_compare_exchange_weak (47 samples, 0.01%)ringbuf::ring_buffer::base::RbBase::is_full (57 samples, 0.02%)ringbuf::ring_buffer::base::RbBase::vacant_len (47 samples, 0.01%)ringbuf::consumer::Consumer<T,R>::advance (64 samples, 0.02%)ringbuf::ring_buffer::base::RbRead::advance_head (64 samples, 0.02%)ringbuf::consumer::Consumer<T,R>::as_uninit_slices (38 samples, 0.01%)ringbuf::ring_buffer::base::RbRead::occupied_slices (38 samples, 0.01%)ringbuf::ring_buffer::rb::Rb::pop (114 samples, 0.03%)ringbuf::consumer::Consumer<T,R>::pop (114 samples, 0.03%)ringbuf::producer::Producer<T,R>::advance (46 samples, 0.01%)ringbuf::ring_buffer::base::RbWrite::advance_tail (46 samples, 0.01%)ringbuf::ring_buffer::rb::Rb::push_overwrite (260 samples, 0.07%)ringbuf::ring_buffer::rb::Rb::push (89 samples, 0.02%)ringbuf::producer::Producer<T,R>::push (89 samples, 0.02%)tokio::runtime::task::state::Snapshot::is_complete (52 samples, 0.01%)tokio::runtime::task::abort::AbortHandle::is_finished (58 samples, 0.02%)tokio::runtime::task::join::JoinHandle<T>::abort_handle (122 samples, 0.03%)tokio::runtime::task::raw::RawTask::ref_inc (122 samples, 0.03%)tokio::runtime::task::state::State::ref_inc (122 samples, 0.03%)core::sync::atomic::AtomicUsize::fetch_add (44 samples, 0.01%)core::sync::atomic::atomic_add (44 samples, 0.01%)dequeue_entity (83 samples, 0.02%)dequeue_task_fair (94 samples, 0.02%)dequeue_task (97 samples, 0.03%)psi_task_switch (52 samples, 0.01%)futex_wait_queue (252 samples, 0.07%)schedule (238 samples, 0.06%)__schedule (236 samples, 0.06%)futex_q_lock (38 samples, 0.01%)futex_q_unlock (146 samples, 0.04%)futex_wait_setup (238 samples, 0.06%)do_futex (520 samples, 0.14%)futex_wait (510 samples, 0.13%)__x64_sys_futex (538 samples, 0.14%)exit_to_user_mode_prepare (51 samples, 0.01%)do_syscall_64 (595 samples, 0.16%)syscall_exit_to_user_mode (52 samples, 0.01%)entry_SYSCALL_64_after_hwframe (603 samples, 0.16%)__GI___lll_lock_wait_private (649 samples, 0.17%)futex_wait (634 samples, 0.17%)futex_hash (66 samples, 0.02%)_raw_spin_lock (46 samples, 0.01%)native_queued_spin_lock_slowpath (46 samples, 0.01%)get_futex_key (40 samples, 0.01%)__smp_call_single_queue (57 samples, 0.02%)send_call_function_single_ipi (54 samples, 0.01%)try_to_wake_up (404 samples, 0.11%)ttwu_queue_wakelist (116 samples, 0.03%)futex_wake (701 samples, 0.19%)wake_up_q (423 samples, 0.11%)do_futex (823 samples, 0.22%)__x64_sys_futex (865 samples, 0.23%)exit_to_user_mode_prepare (56 samples, 0.01%)do_syscall_64 (958 samples, 0.25%)syscall_exit_to_user_mode (63 samples, 0.02%)entry_SYSCALL_64_after_hwframe (992 samples, 0.26%)__GI___lll_lock_wake_private (1,063 samples, 0.28%)malloc_consolidate (690 samples, 0.18%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (779 samples, 0.21%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (192 samples, 0.05%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (162 samples, 0.04%)_int_malloc (2,142 samples, 0.57%)__GI___libc_malloc (3,995 samples, 1.06%)alloc::vec::Vec<T>::with_capacity (4,013 samples, 1.06%)alloc::vec::Vec<T,A>::with_capacity_in (4,013 samples, 1.06%)alloc::raw_vec::RawVec<T,A>::with_capacity_in (4,006 samples, 1.06%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (4,006 samples, 1.06%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (4,004 samples, 1.06%)alloc::alloc::Global::alloc_impl (4,004 samples, 1.06%)alloc::alloc::alloc (4,004 samples, 1.06%)__rdl_alloc (4,004 samples, 1.06%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (4,004 samples, 1.06%)core::ptr::drop_in_place<alloc::sync::Arc<tokio::net::udp::UdpSocket>> (175 samples, 0.05%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (175 samples, 0.05%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (189 samples, 0.05%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (81 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (51 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (47 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (46 samples, 0.01%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (42 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (144 samples, 0.04%)tokio::net::udp::UdpSocket::readable::{{closure}} (392 samples, 0.10%)tokio::net::udp::UdpSocket::ready::{{closure}} (390 samples, 0.10%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (181 samples, 0.05%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (172 samples, 0.05%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (135 samples, 0.04%)__GI___pthread_disable_asynccancel (75 samples, 0.02%)__x64_sys_recvfrom (179 samples, 0.05%)__sys_recvfrom (40 samples, 0.01%)__get_user_4 (139 samples, 0.04%)__put_user_nocheck_4 (875 samples, 0.23%)__check_object_size.part.0 (127 samples, 0.03%)check_stack_object (103 samples, 0.03%)__check_object_size (158 samples, 0.04%)move_addr_to_user (955 samples, 0.25%)copy_user_enhanced_fast_string (704 samples, 0.19%)apparmor_socket_recvmsg (80 samples, 0.02%)__check_object_size (53 samples, 0.01%)__skb_recv_udp (43 samples, 0.01%)__check_object_size.part.0 (45 samples, 0.01%)__check_heap_object (63 samples, 0.02%)__check_heap_object (309 samples, 0.08%)__virt_addr_valid (486 samples, 0.13%)check_heap_object (1,230 samples, 0.33%)__check_object_size.part.0 (1,550 samples, 0.41%)is_vmalloc_addr (91 samples, 0.02%)__check_object_size (1,697 samples, 0.45%)check_stack_object (122 samples, 0.03%)__skb_try_recv_from_queue (265 samples, 0.07%)_raw_spin_lock (56 samples, 0.01%)_raw_spin_unlock_bh (498 samples, 0.13%)__local_bh_enable_ip (441 samples, 0.12%)__refill_stock (48 samples, 0.01%)drain_stock (42 samples, 0.01%)__sk_mem_reduce_allocated (74 samples, 0.02%)mem_cgroup_uncharge_skmem (74 samples, 0.02%)refill_stock (61 samples, 0.02%)__skb_recv_udp (1,279 samples, 0.34%)udp_rmem_release (187 samples, 0.05%)_copy_to_iter (408 samples, 0.11%)_raw_spin_lock_bh (603 samples, 0.16%)_raw_spin_unlock_bh (38 samples, 0.01%)copy_user_enhanced_fast_string (2,356 samples, 0.62%)cmpxchg_double_slab.constprop.0.isra.0 (1,503 samples, 0.40%)__slab_free (3,062 samples, 0.81%)put_cpu_partial (75 samples, 0.02%)__unfreeze_partials (70 samples, 0.02%)cache_from_obj (75 samples, 0.02%)cmpxchg_double_slab.constprop.0.isra.0 (85 samples, 0.02%)kfree_skbmem (3,703 samples, 0.98%)kmem_cache_free (3,665 samples, 0.97%)cmpxchg_double_slab.constprop.0.isra.0 (404 samples, 0.11%)__slab_free (1,382 samples, 0.37%)put_cpu_partial (57 samples, 0.02%)__unfreeze_partials (54 samples, 0.01%)__kmem_cache_free (1,536 samples, 0.41%)__consume_stateless_skb (7,001 samples, 1.85%)_..skb_release_data (3,272 samples, 0.86%)skb_free_head (1,626 samples, 0.43%)kfree (1,609 samples, 0.43%)skb_consume_udp (7,079 samples, 1.87%)s..inet_recvmsg (15,244 samples, 4.03%)inet..udp_recvmsg (15,018 samples, 3.97%)udp_..security_socket_recvmsg (249 samples, 0.07%)apparmor_socket_recvmsg (171 samples, 0.05%)aa_sk_perm (146 samples, 0.04%)sock_recvmsg (15,648 samples, 4.14%)sock_..__fget_light (1,217 samples, 0.32%)__fdget (1,243 samples, 0.33%)__sys_recvfrom (19,882 samples, 5.25%)__sys_..sockfd_lookup_light (1,397 samples, 0.37%)__fget_light (44 samples, 0.01%)fput (482 samples, 0.13%)import_single_range (71 samples, 0.02%)__x64_sys_recvfrom (20,466 samples, 5.41%)__x64_s..exit_to_user_mode_prepare (364 samples, 0.10%)do_syscall_64 (21,043 samples, 5.56%)do_sysc..syscall_exit_to_user_mode (485 samples, 0.13%)entry_SYSCALL_64_after_hwframe (21,266 samples, 5.62%)entry_S..syscall_return_via_sysret (39 samples, 0.01%)__libc_recvfrom (21,805 samples, 5.76%)__libc_..tokio::net::udp::UdpSocket::recv_buf_from::{{closure}}::{{closure}} (21,997 samples, 5.81%)tokio::..mio::net::udp::UdpSocket::recv_from (21,912 samples, 5.79%)mio::ne..mio::io_source::IoSource<T>::do_io (21,912 samples, 5.79%)mio::io..mio::sys::unix::stateless_io_source::IoSourceState::do_io (21,912 samples, 5.79%)mio::sy..mio::net::udp::UdpSocket::recv_from::{{closure}} (21,912 samples, 5.79%)mio::ne..std::net::udp::UdpSocket::recv_from (21,912 samples, 5.79%)std::ne..std::sys_common::net::UdpSocket::recv_from (21,912 samples, 5.79%)std::sy..std::sys::pal::unix::net::Socket::recv_from (21,912 samples, 5.79%)std::sy..std::sys::pal::unix::net::Socket::recv_from_with_flags (21,912 samples, 5.79%)std::sy..std::sys_common::net::sockaddr_to_addr (45 samples, 0.01%)__GI___libc_malloc (49 samples, 0.01%)_int_malloc (51 samples, 0.01%)core::result::Result<T,E>::is_err (45 samples, 0.01%)core::result::Result<T,E>::is_ok (45 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (69 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (63 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (58 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (58 samples, 0.02%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (282 samples, 0.07%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (238 samples, 0.06%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (119 samples, 0.03%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (27,792 samples, 7.35%)torrust_tr..tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (22,942 samples, 6.06%)tokio::n..tokio::runtime::io::registration::Registration::async_io::{{closure}} (22,924 samples, 6.06%)tokio::r..__memcpy_avx512_unaligned_erms (92 samples, 0.02%)__memcpy_avx512_unaligned_erms (2,847 samples, 0.75%)__memcpy_avx512_unaligned_erms (837 samples, 0.22%)core::ptr::drop_in_place<core::cell::RefMut<core::option::Option<alloc::boxed::Box<tokio::runtime::scheduler::multi_thread::worker::Core>>>> (42 samples, 0.01%)core::ptr::drop_in_place<core::cell::BorrowRefMut> (42 samples, 0.01%)<core::cell::BorrowRefMut as core::ops::drop::Drop>::drop (42 samples, 0.01%)core::cell::Cell<T>::set (42 samples, 0.01%)core::cell::Cell<T>::replace (42 samples, 0.01%)core::mem::replace (42 samples, 0.01%)core::ptr::write (42 samples, 0.01%)__x64_sys_futex (80 samples, 0.02%)futex_hash (110 samples, 0.03%)futex_wake_mark (43 samples, 0.01%)get_futex_key (112 samples, 0.03%)wake_q_add_safe (39 samples, 0.01%)_raw_spin_lock_irqsave (93 samples, 0.02%)__raw_spin_lock_irqsave (93 samples, 0.02%)select_task_rq_fair (322 samples, 0.09%)wake_affine (103 samples, 0.03%)available_idle_cpu (73 samples, 0.02%)__smp_call_single_queue (251 samples, 0.07%)send_call_function_single_ipi (243 samples, 0.06%)native_send_call_func_single_ipi (94 samples, 0.02%)default_send_IPI_single_phys (94 samples, 0.02%)__default_send_IPI_dest_field (85 samples, 0.02%)llist_add_batch (231 samples, 0.06%)sched_clock_cpu (68 samples, 0.02%)sched_clock (61 samples, 0.02%)native_sched_clock (61 samples, 0.02%)ttwu_queue_wakelist (704 samples, 0.19%)try_to_wake_up (1,611 samples, 0.43%)futex_wake (2,206 samples, 0.58%)wake_up_q (1,679 samples, 0.44%)do_futex (2,433 samples, 0.64%)__x64_sys_futex (2,563 samples, 0.68%)do_futex (62 samples, 0.02%)do_syscall_64 (2,732 samples, 0.72%)syscall_exit_to_user_mode (68 samples, 0.02%)exit_to_user_mode_prepare (58 samples, 0.02%)entry_SYSCALL_64_after_hwframe (2,827 samples, 0.75%)syscall (2,981 samples, 0.79%)core::ptr::drop_in_place<core::option::Option<tokio::runtime::task::Notified<alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (83 samples, 0.02%)core::sync::atomic::AtomicU32::store (58 samples, 0.02%)core::sync::atomic::atomic_store (58 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::push_back_finish (83 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::push_back_or_overflow (115 samples, 0.03%)tokio::runtime::context::with_scheduler (451 samples, 0.12%)std::thread::local::LocalKey<T>::try_with (403 samples, 0.11%)tokio::runtime::context::with_scheduler::{{closure}} (394 samples, 0.10%)tokio::runtime::context::scoped::Scoped<T>::with (387 samples, 0.10%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (385 samples, 0.10%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (381 samples, 0.10%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (338 samples, 0.09%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (59 samples, 0.02%)alloc::vec::Vec<T,A>::pop (85 samples, 0.02%)core::ptr::read (56 samples, 0.01%)std::sync::mutex::MutexGuard<T>::new (55 samples, 0.01%)std::sync::poison::Flag::guard (55 samples, 0.01%)std::thread::panicking (52 samples, 0.01%)std::panicking::panicking (52 samples, 0.01%)std::panicking::panic_count::count_is_zero (52 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (156 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (145 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (90 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock_contended (43 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (2,704 samples, 0.71%)core::sync::atomic::atomic_add (2,704 samples, 0.71%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (3,112 samples, 0.82%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (2,853 samples, 0.75%)tokio::runtime::scheduler::multi_thread::idle::State::num_unparked (80 samples, 0.02%)__fget_light (82 samples, 0.02%)__fdget_pos (85 samples, 0.02%)try_to_wake_up (70 samples, 0.02%)__wake_up_common (74 samples, 0.02%)ep_autoremove_wake_function (71 samples, 0.02%)default_wake_function (71 samples, 0.02%)_raw_spin_lock_irqsave (68 samples, 0.02%)__raw_spin_lock_irqsave (68 samples, 0.02%)native_queued_spin_lock_slowpath (58 samples, 0.02%)__wake_up_common_lock (144 samples, 0.04%)__wake_up (145 samples, 0.04%)_raw_read_lock_irqsave (177 samples, 0.05%)__raw_read_lock_irqsave (177 samples, 0.05%)__wake_up_common (458 samples, 0.12%)ep_poll_callback (447 samples, 0.12%)__wake_up_locked_key (461 samples, 0.12%)_raw_spin_lock_irq (139 samples, 0.04%)eventfd_write (716 samples, 0.19%)copy_user_enhanced_fast_string (76 samples, 0.02%)__x64_sys_write (884 samples, 0.23%)ksys_write (873 samples, 0.23%)vfs_write (758 samples, 0.20%)do_syscall_64 (930 samples, 0.25%)syscall_exit_to_user_mode (40 samples, 0.01%)entry_SYSCALL_64_after_hwframe (950 samples, 0.25%)__GI___libc_write (1,017 samples, 0.27%)__GI___libc_write (1,014 samples, 0.27%)tokio::runtime::driver::Handle::unpark (1,023 samples, 0.27%)tokio::runtime::driver::IoHandle::unpark (1,023 samples, 0.27%)tokio::runtime::io::driver::Handle::unpark (1,023 samples, 0.27%)mio::waker::Waker::wake (1,022 samples, 0.27%)mio::sys::unix::waker::fdbased::Waker::wake (1,022 samples, 0.27%)mio::sys::unix::waker::eventfd::WakerInternal::wake (1,022 samples, 0.27%)<&std::fs::File as std::io::Write>::write (1,021 samples, 0.27%)std::sys::pal::unix::fs::File::write (1,021 samples, 0.27%)std::sys::pal::unix::fd::FileDesc::write (1,021 samples, 0.27%)tokio::runtime::context::with_scheduler (7,649 samples, 2.02%)t..std::thread::local::LocalKey<T>::try_with (7,636 samples, 2.02%)s..tokio::runtime::context::with_scheduler::{{closure}} (7,635 samples, 2.02%)t..tokio::runtime::context::scoped::Scoped<T>::with (7,634 samples, 2.02%)t..tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (7,634 samples, 2.02%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (7,634 samples, 2.02%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (7,591 samples, 2.01%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (7,591 samples, 2.01%)t..tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (1,047 samples, 0.28%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (1,043 samples, 0.28%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_option_task_without_yield (7,948 samples, 2.10%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task (7,946 samples, 2.10%)t..tokio::runtime::scheduler::multi_thread::worker::with_current (7,946 samples, 2.10%)t..tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (90 samples, 0.02%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::push_front (63 samples, 0.02%)core::result::Result<T,E>::is_err (409 samples, 0.11%)core::result::Result<T,E>::is_ok (409 samples, 0.11%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (992 samples, 0.26%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (797 samples, 0.21%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (781 samples, 0.21%)tokio::loom::std::mutex::Mutex<T>::lock (773 samples, 0.20%)std::sync::mutex::Mutex<T>::lock (773 samples, 0.20%)std::sys::sync::mutex::futex::Mutex::lock (769 samples, 0.20%)core::sync::atomic::AtomicU32::compare_exchange (360 samples, 0.10%)core::sync::atomic::atomic_compare_exchange (360 samples, 0.10%)__memcpy_avx512_unaligned_erms (410 samples, 0.11%)__GI___lll_lock_wake_private (103 samples, 0.03%)__memcpy_avx512_unaligned_erms (180 samples, 0.05%)update_curr (47 samples, 0.01%)update_load_avg (57 samples, 0.02%)dequeue_entity (144 samples, 0.04%)dequeue_task (169 samples, 0.04%)dequeue_task_fair (166 samples, 0.04%)ctx_sched_out (41 samples, 0.01%)prepare_task_switch (61 samples, 0.02%)__perf_event_task_sched_out (56 samples, 0.01%)perf_event_context_sched_out (48 samples, 0.01%)psi_group_change (57 samples, 0.02%)psi_task_switch (96 samples, 0.03%)__schedule (428 samples, 0.11%)futex_wait_queue (471 samples, 0.12%)schedule (433 samples, 0.11%)futex_q_lock (46 samples, 0.01%)futex_q_unlock (217 samples, 0.06%)futex_wait_setup (344 samples, 0.09%)futex_wait (864 samples, 0.23%)do_futex (877 samples, 0.23%)__x64_sys_futex (885 samples, 0.23%)__rseq_handle_notify_resume (77 samples, 0.02%)exit_to_user_mode_loop (96 samples, 0.03%)exit_to_user_mode_prepare (127 samples, 0.03%)do_syscall_64 (1,027 samples, 0.27%)syscall_exit_to_user_mode (136 samples, 0.04%)entry_SYSCALL_64_after_hwframe (1,035 samples, 0.27%)__GI___lll_lock_wait_private (1,121 samples, 0.30%)futex_wait (1,095 samples, 0.29%)futex_hash (66 samples, 0.02%)__smp_call_single_queue (40 samples, 0.01%)send_call_function_single_ipi (39 samples, 0.01%)futex_wake (608 samples, 0.16%)wake_up_q (362 samples, 0.10%)try_to_wake_up (353 samples, 0.09%)ttwu_queue_wakelist (78 samples, 0.02%)do_futex (729 samples, 0.19%)__x64_sys_futex (747 samples, 0.20%)exit_to_user_mode_prepare (44 samples, 0.01%)do_syscall_64 (822 samples, 0.22%)syscall_exit_to_user_mode (54 samples, 0.01%)entry_SYSCALL_64_after_hwframe (838 samples, 0.22%)__GI___lll_lock_wake_private (916 samples, 0.24%)_int_free (220 samples, 0.06%)__alloc_pages (48 samples, 0.01%)do_anonymous_page (127 samples, 0.03%)vma_alloc_folio (59 samples, 0.02%)__folio_alloc (52 samples, 0.01%)handle_pte_fault (132 samples, 0.03%)__handle_mm_fault (136 samples, 0.04%)handle_mm_fault (153 samples, 0.04%)do_user_addr_fault (170 samples, 0.04%)asm_exc_page_fault (177 samples, 0.05%)exc_page_fault (175 samples, 0.05%)perf_event_mmap_output (55 samples, 0.01%)perf_event_mmap_event (115 samples, 0.03%)perf_iterate_sb (111 samples, 0.03%)perf_iterate_ctx (100 samples, 0.03%)perf_event_mmap (124 samples, 0.03%)mas_preallocate (48 samples, 0.01%)mas_alloc_nodes (48 samples, 0.01%)mas_wr_store_entry.isra.0 (43 samples, 0.01%)mas_store_prealloc (73 samples, 0.02%)__vma_adjust (154 samples, 0.04%)vma_mas_store (78 samples, 0.02%)vma_merge (173 samples, 0.05%)mprotect_fixup (330 samples, 0.09%)do_mprotect_pkey (384 samples, 0.10%)__x64_sys_mprotect (390 samples, 0.10%)grow_heap (401 samples, 0.11%)__GI_mprotect (399 samples, 0.11%)entry_SYSCALL_64_after_hwframe (395 samples, 0.10%)do_syscall_64 (392 samples, 0.10%)sysmalloc (595 samples, 0.16%)_int_malloc (1,239 samples, 0.33%)unlink_chunk (55 samples, 0.01%)_int_memalign (1,518 samples, 0.40%)core::option::Option<T>::map (14,436 samples, 3.82%)core..tokio::task::spawn::spawn_inner::{{closure}} (14,430 samples, 3.81%)toki..tokio::runtime::scheduler::Handle::spawn (14,425 samples, 3.81%)toki..tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (14,422 samples, 3.81%)toki..tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (14,411 samples, 3.81%)toki..tokio::runtime::task::list::OwnedTasks<S>::bind (5,536 samples, 1.46%)tokio::runtime::task::new_task (4,490 samples, 1.19%)tokio::runtime::task::raw::RawTask::new (4,490 samples, 1.19%)tokio::runtime::task::core::Cell<T,S>::new (4,490 samples, 1.19%)alloc::boxed::Box<T>::new (4,034 samples, 1.07%)alloc::alloc::exchange_malloc (3,715 samples, 0.98%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (3,702 samples, 0.98%)alloc::alloc::Global::alloc_impl (3,702 samples, 0.98%)alloc::alloc::alloc (3,702 samples, 0.98%)__rdl_alloc (3,702 samples, 0.98%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (3,702 samples, 0.98%)std::sys::pal::unix::alloc::aligned_malloc (3,702 samples, 0.98%)__posix_memalign (3,659 samples, 0.97%)__posix_memalign (3,656 samples, 0.97%)_mid_memalign (3,656 samples, 0.97%)tokio::runtime::context::current::with_current (17,481 samples, 4.62%)tokio..std::thread::local::LocalKey<T>::try_with (17,476 samples, 4.62%)std::..tokio::runtime::context::current::with_current::{{closure}} (17,340 samples, 4.58%)tokio..tokio::task::spawn::spawn (17,548 samples, 4.64%)tokio..tokio::task::spawn::spawn_inner (17,548 samples, 4.64%)tokio..tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (173,936 samples, 45.97%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_muttokio::runtime::task::core::Core<T,S>::poll::{{closure}} (173,935 samples, 45.97%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}}torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (48,629 samples, 12.85%)torrust_tracker::se..torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (48,628 samples, 12.85%)torrust_tracker::se..torrust_tracker::servers::udp::server::Udp::spawn_request_processor (17,569 samples, 4.64%)torru..__memcpy_avx512_unaligned_erms (51 samples, 0.01%)__memcpy_avx512_unaligned_erms (2,052 samples, 0.54%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (2,067 samples, 0.55%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (2,067 samples, 0.55%)tokio::runtime::task::core::Core<T,S>::poll (176,078 samples, 46.54%)tokio::runtime::task::core::Core<T,S>::polltokio::runtime::task::core::Core<T,S>::drop_future_or_output (2,140 samples, 0.57%)tokio::runtime::task::core::Core<T,S>::set_stage (2,138 samples, 0.57%)__memcpy_avx512_unaligned_erms (48 samples, 0.01%)__memcpy_avx512_unaligned_erms (856 samples, 0.23%)__memcpy_avx512_unaligned_erms (1,693 samples, 0.45%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (1,703 samples, 0.45%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (1,702 samples, 0.45%)tokio::runtime::task::core::Core<T,S>::set_stage (2,570 samples, 0.68%)tokio::runtime::task::harness::poll_future (178,737 samples, 47.24%)tokio::runtime::task::harness::poll_futurestd::panic::catch_unwind (178,737 samples, 47.24%)std::panic::catch_unwindstd::panicking::try (178,737 samples, 47.24%)std::panicking::trystd::panicking::try::do_call (178,737 samples, 47.24%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (178,737 samples, 47.24%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<..tokio::runtime::task::harness::poll_future::{{closure}} (178,737 samples, 47.24%)tokio::runtime::task::harness::poll_future::{{closure}}tokio::runtime::task::core::Core<T,S>::store_output (2,659 samples, 0.70%)tokio::runtime::task::state::State::transition_to_running (348 samples, 0.09%)tokio::runtime::task::state::State::fetch_update_action (348 samples, 0.09%)tokio::runtime::task::raw::poll (181,363 samples, 47.93%)tokio::runtime::task::raw::polltokio::runtime::task::harness::Harness<T,S>::poll (181,220 samples, 47.90%)tokio::runtime::task::harness::Harness<T,S>::polltokio::runtime::task::harness::Harness<T,S>::poll_inner (179,097 samples, 47.33%)tokio::runtime::task::harness::Harness<T,S>::poll_innertokio::runtime::coop::budget (181,972 samples, 48.09%)tokio::runtime::coop::budgettokio::runtime::coop::with_budget (181,972 samples, 48.09%)tokio::runtime::coop::with_budgettokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (181,912 samples, 48.08%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}}tokio::runtime::task::LocalNotified<S>::run (181,909 samples, 48.08%)tokio::runtime::task::LocalNotified<S>::runtokio::runtime::task::raw::RawTask::poll (181,909 samples, 48.08%)tokio::runtime::task::raw::RawTask::polltokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (110 samples, 0.03%)__x64_sys_futex (295 samples, 0.08%)_raw_spin_lock (91 samples, 0.02%)futex_hash (195 samples, 0.05%)futex_wake_mark (84 samples, 0.02%)get_futex_key (163 samples, 0.04%)wake_q_add_safe (121 samples, 0.03%)select_task_rq_fair (60 samples, 0.02%)_raw_spin_lock_irqsave (167 samples, 0.04%)__raw_spin_lock_irqsave (164 samples, 0.04%)available_idle_cpu (62 samples, 0.02%)select_idle_sibling (121 samples, 0.03%)select_task_rq_fair (1,048 samples, 0.28%)wake_affine (382 samples, 0.10%)available_idle_cpu (315 samples, 0.08%)__smp_call_single_queue (294 samples, 0.08%)send_call_function_single_ipi (280 samples, 0.07%)native_send_call_func_single_ipi (53 samples, 0.01%)default_send_IPI_single_phys (53 samples, 0.01%)__default_send_IPI_dest_field (49 samples, 0.01%)llist_add_batch (533 samples, 0.14%)sched_clock_cpu (152 samples, 0.04%)sched_clock (144 samples, 0.04%)native_sched_clock (143 samples, 0.04%)ttwu_queue_wakelist (1,388 samples, 0.37%)try_to_wake_up (3,169 samples, 0.84%)futex_wake (4,300 samples, 1.14%)wake_up_q (3,312 samples, 0.88%)do_futex (4,709 samples, 1.24%)__x64_sys_futex (4,862 samples, 1.28%)do_futex (47 samples, 0.01%)exit_to_user_mode_prepare (62 samples, 0.02%)do_syscall_64 (5,079 samples, 1.34%)syscall_exit_to_user_mode (90 samples, 0.02%)entry_SYSCALL_64_after_hwframe (5,409 samples, 1.43%)syscall (5,655 samples, 1.49%)tokio::loom::std::mutex::Mutex<T>::lock (75 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (71 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (49 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (1,216 samples, 0.32%)core::sync::atomic::atomic_add (1,216 samples, 0.32%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (1,348 samples, 0.36%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (1,238 samples, 0.33%)fput (40 samples, 0.01%)__fget_light (155 samples, 0.04%)__fdget_pos (165 samples, 0.04%)_raw_spin_lock_irqsave (39 samples, 0.01%)__raw_spin_lock_irqsave (39 samples, 0.01%)__wake_up_common (172 samples, 0.05%)ep_autoremove_wake_function (163 samples, 0.04%)default_wake_function (162 samples, 0.04%)try_to_wake_up (159 samples, 0.04%)ttwu_queue_wakelist (43 samples, 0.01%)__wake_up_common_lock (308 samples, 0.08%)_raw_spin_lock_irqsave (131 samples, 0.03%)__raw_spin_lock_irqsave (131 samples, 0.03%)native_queued_spin_lock_slowpath (121 samples, 0.03%)__wake_up (311 samples, 0.08%)_raw_read_lock_irqsave (369 samples, 0.10%)__raw_read_lock_irqsave (368 samples, 0.10%)__wake_up_common (972 samples, 0.26%)ep_poll_callback (937 samples, 0.25%)_raw_read_unlock_irqrestore (39 samples, 0.01%)__wake_up_locked_key (989 samples, 0.26%)_copy_from_user (42 samples, 0.01%)_raw_spin_lock_irq (428 samples, 0.11%)eventfd_write (1,641 samples, 0.43%)copy_user_enhanced_fast_string (139 samples, 0.04%)ksys_write (1,936 samples, 0.51%)vfs_write (1,722 samples, 0.46%)rw_verify_area (42 samples, 0.01%)security_file_permission (38 samples, 0.01%)__x64_sys_write (1,980 samples, 0.52%)exit_to_user_mode_prepare (42 samples, 0.01%)do_syscall_64 (2,071 samples, 0.55%)syscall_exit_to_user_mode (74 samples, 0.02%)entry_SYSCALL_64_after_hwframe (2,113 samples, 0.56%)__GI___libc_write (2,270 samples, 0.60%)__GI___libc_write (2,271 samples, 0.60%)mio::sys::unix::waker::eventfd::WakerInternal::wake (2,284 samples, 0.60%)<&std::fs::File as std::io::Write>::write (2,277 samples, 0.60%)std::sys::pal::unix::fs::File::write (2,277 samples, 0.60%)std::sys::pal::unix::fd::FileDesc::write (2,277 samples, 0.60%)__entry_text_start (206 samples, 0.05%)tokio::runtime::driver::Handle::unpark (2,522 samples, 0.67%)tokio::runtime::driver::IoHandle::unpark (2,522 samples, 0.67%)tokio::runtime::io::driver::Handle::unpark (2,522 samples, 0.67%)mio::waker::Waker::wake (2,518 samples, 0.67%)mio::sys::unix::waker::fdbased::Waker::wake (2,518 samples, 0.67%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (234 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (234 samples, 0.06%)tokio::runtime::driver::Handle::unpark (233 samples, 0.06%)tokio::runtime::driver::IoHandle::unpark (233 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (2,547 samples, 0.67%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (2,543 samples, 0.67%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (191,736 samples, 50.67%)tokio::runtime::scheduler::multi_thread::worker::Context::run_tasktokio::runtime::scheduler::multi_thread::worker::Core::transition_from_searching (9,564 samples, 2.53%)to..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::transition_worker_from_searching (9,562 samples, 2.53%)to..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (9,559 samples, 2.53%)to..tokio::runtime::scheduler::multi_thread::worker::Core::tune_global_queue_interval (67 samples, 0.02%)tokio::runtime::scheduler::multi_thread::stats::Stats::tuned_global_queue_interval (65 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (162 samples, 0.04%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (201 samples, 0.05%)alloc::sync::Arc<T,A>::inner (201 samples, 0.05%)core::ptr::non_null::NonNull<T>::as_ref (201 samples, 0.05%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (327 samples, 0.09%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (327 samples, 0.09%)core::cmp::impls::<impl core::cmp::PartialOrd for usize>::lt (326 samples, 0.09%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (127 samples, 0.03%)alloc::sync::Arc<T,A>::inner (127 samples, 0.03%)core::ptr::non_null::NonNull<T>::as_ref (127 samples, 0.03%)core::num::<impl u32>::wrapping_sub (314 samples, 0.08%)core::sync::atomic::AtomicU64::load (129 samples, 0.03%)core::sync::atomic::atomic_load (129 samples, 0.03%)tokio::loom::std::atomic_u32::AtomicU32::unsync_load (110 samples, 0.03%)core::sync::atomic::AtomicU32::load (110 samples, 0.03%)core::sync::atomic::atomic_load (110 samples, 0.03%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (168 samples, 0.04%)alloc::sync::Arc<T,A>::inner (168 samples, 0.04%)core::ptr::non_null::NonNull<T>::as_ref (168 samples, 0.04%)core::num::<impl u32>::wrapping_add (92 samples, 0.02%)core::num::<impl u32>::wrapping_sub (172 samples, 0.05%)core::sync::atomic::AtomicU32::load (163 samples, 0.04%)core::sync::atomic::atomic_load (163 samples, 0.04%)core::sync::atomic::AtomicU64::load (405 samples, 0.11%)core::sync::atomic::atomic_load (405 samples, 0.11%)tokio::runtime::scheduler::multi_thread::queue::pack (166 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (2,781 samples, 0.73%)tokio::runtime::scheduler::multi_thread::queue::unpack (540 samples, 0.14%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (3,784 samples, 1.00%)tokio::runtime::scheduler::multi_thread::queue::unpack (134 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_searching (423 samples, 0.11%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_searching (99 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (8,170 samples, 2.16%)t..tokio::util::rand::FastRand::fastrand_n (71 samples, 0.02%)tokio::util::rand::FastRand::fastrand (71 samples, 0.02%)std::panic::catch_unwind (262,281 samples, 69.32%)std::panic::catch_unwindstd::panicking::try (262,281 samples, 69.32%)std::panicking::trystd::panicking::try::do_call (262,281 samples, 69.32%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (262,281 samples, 69.32%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_oncestd::thread::Builder::spawn_unchecked_::{{closure}}::{{closure}} (262,281 samples, 69.32%)std::thread::Builder::spawn_unchecked_::{{closure}}::{{closure}}std::sys_common::backtrace::__rust_begin_short_backtrace (262,281 samples, 69.32%)std::sys_common::backtrace::__rust_begin_short_backtracetokio::runtime::blocking::pool::Spawner::spawn_thread::{{closure}} (262,281 samples, 69.32%)tokio::runtime::blocking::pool::Spawner::spawn_thread::{{closure}}tokio::runtime::blocking::pool::Inner::run (262,281 samples, 69.32%)tokio::runtime::blocking::pool::Inner::runtokio::runtime::blocking::pool::Task::run (262,211 samples, 69.30%)tokio::runtime::blocking::pool::Task::runtokio::runtime::task::UnownedTask<S>::run (262,211 samples, 69.30%)tokio::runtime::task::UnownedTask<S>::runtokio::runtime::task::raw::RawTask::poll (262,211 samples, 69.30%)tokio::runtime::task::raw::RawTask::polltokio::runtime::task::raw::poll (262,211 samples, 69.30%)tokio::runtime::task::raw::polltokio::runtime::task::harness::Harness<T,S>::poll (262,211 samples, 69.30%)tokio::runtime::task::harness::Harness<T,S>::polltokio::runtime::task::harness::Harness<T,S>::poll_inner (262,211 samples, 69.30%)tokio::runtime::task::harness::Harness<T,S>::poll_innertokio::runtime::task::harness::poll_future (262,210 samples, 69.30%)tokio::runtime::task::harness::poll_futurestd::panic::catch_unwind (262,210 samples, 69.30%)std::panic::catch_unwindstd::panicking::try (262,210 samples, 69.30%)std::panicking::trystd::panicking::try::do_call (262,210 samples, 69.30%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (262,210 samples, 69.30%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_oncetokio::runtime::task::harness::poll_future::{{closure}} (262,210 samples, 69.30%)tokio::runtime::task::harness::poll_future::{{closure}}tokio::runtime::task::core::Core<T,S>::poll (262,210 samples, 69.30%)tokio::runtime::task::core::Core<T,S>::polltokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (262,210 samples, 69.30%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_muttokio::runtime::task::core::Core<T,S>::poll::{{closure}} (262,210 samples, 69.30%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}}<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (262,210 samples, 69.30%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::polltokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (262,210 samples, 69.30%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}}tokio::runtime::scheduler::multi_thread::worker::run (262,210 samples, 69.30%)tokio::runtime::scheduler::multi_thread::worker::runtokio::runtime::context::runtime::enter_runtime (262,210 samples, 69.30%)tokio::runtime::context::runtime::enter_runtimetokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (262,210 samples, 69.30%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}tokio::runtime::context::set_scheduler (262,210 samples, 69.30%)tokio::runtime::context::set_schedulerstd::thread::local::LocalKey<T>::with (262,210 samples, 69.30%)std::thread::local::LocalKey<T>::withstd::thread::local::LocalKey<T>::try_with (262,210 samples, 69.30%)std::thread::local::LocalKey<T>::try_withtokio::runtime::context::set_scheduler::{{closure}} (262,210 samples, 69.30%)tokio::runtime::context::set_scheduler::{{closure}}tokio::runtime::context::scoped::Scoped<T>::set (262,210 samples, 69.30%)tokio::runtime::context::scoped::Scoped<T>::settokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (262,210 samples, 69.30%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}}tokio::runtime::scheduler::multi_thread::worker::Context::run (262,210 samples, 69.30%)tokio::runtime::scheduler::multi_thread::worker::Context::run<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once (262,282 samples, 69.32%)<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once (262,282 samples, 69.32%)<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_oncecore::ops::function::FnOnce::call_once{{vtable.shim}} (262,282 samples, 69.32%)core::ops::function::FnOnce::call_once{{vtable.shim}}std::thread::Builder::spawn_unchecked_::{{closure}} (262,282 samples, 69.32%)std::thread::Builder::spawn_unchecked_::{{closure}}clone3 (262,316 samples, 69.33%)clone3start_thread (262,316 samples, 69.33%)start_threadstd::sys::pal::unix::thread::Thread::new::thread_start (262,299 samples, 69.32%)std::sys::pal::unix::thread::Thread::new::thread_startcore::fmt::Formatter::pad_integral (390 samples, 0.10%)core::fmt::Formatter::pad_integral::write_prefix (126 samples, 0.03%)core::fmt::Formatter::pad_integral (41 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (113 samples, 0.03%)__x64_sys_futex (173 samples, 0.05%)__x64_sys_getsockname (51 samples, 0.01%)__x64_sys_sendto (43 samples, 0.01%)__x64_sys_epoll_wait (165 samples, 0.04%)read_tsc (70 samples, 0.02%)futex_hash (127 samples, 0.03%)futex_wait_setup (101 samples, 0.03%)get_futex_key (39 samples, 0.01%)futex_wait (270 samples, 0.07%)futex_wake (506 samples, 0.13%)get_futex_key (181 samples, 0.05%)do_futex (1,060 samples, 0.28%)__x64_sys_futex (1,255 samples, 0.33%)__fget_light (87 samples, 0.02%)__fdget (88 samples, 0.02%)__sys_getsockname (168 samples, 0.04%)sockfd_lookup_light (98 samples, 0.03%)__x64_sys_getsockname (171 samples, 0.05%)__fget_light (55 samples, 0.01%)__fdget (57 samples, 0.02%)__sys_recvfrom (187 samples, 0.05%)sockfd_lookup_light (72 samples, 0.02%)__x64_sys_recvfrom (198 samples, 0.05%)__sys_sendto (165 samples, 0.04%)sockfd_lookup_light (51 samples, 0.01%)__x64_sys_sendto (177 samples, 0.05%)do_futex (48 samples, 0.01%)do_syscall_64 (2,325 samples, 0.61%)syscall_enter_from_user_mode (175 samples, 0.05%)entry_SYSCALL_64_after_hwframe (3,067 samples, 0.81%)syscall_enter_from_user_mode (207 samples, 0.05%)entry_SYSCALL_64_safe_stack (222 samples, 0.06%)rand_chacha::guts::round (69 samples, 0.02%)rand_chacha::guts::refill_wide::impl_avx2 (80 samples, 0.02%)rand_chacha::guts::refill_wide::fn_impl (80 samples, 0.02%)rand_chacha::guts::refill_wide_impl (80 samples, 0.02%)core::cell::RefCell<T>::borrow_mut (113 samples, 0.03%)core::cell::RefCell<T>::try_borrow_mut (113 samples, 0.03%)core::cell::BorrowRefMut::new (113 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (156 samples, 0.04%)tokio::runtime::coop::budget (154 samples, 0.04%)tokio::runtime::coop::with_budget (154 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (136 samples, 0.04%)std::sys::pal::unix::time::Timespec::now (305 samples, 0.08%)std::sys::pal::unix::time::Timespec::sub_timespec (148 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock_contended (110 samples, 0.03%)std::sys_common::net::TcpListener::socket_addr (40 samples, 0.01%)syscall (90 samples, 0.02%)syscall_return_via_sysret (133 samples, 0.04%)std::sync::poison::Flag::done (42 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>,tokio::runtime::task::core::Header>>> (47 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (47 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (71 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::remove (71 samples, 0.02%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (58 samples, 0.02%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (113 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (113 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::run (113 samples, 0.03%)tokio::runtime::context::runtime::enter_runtime (113 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (113 samples, 0.03%)tokio::runtime::context::set_scheduler (113 samples, 0.03%)std::thread::local::LocalKey<T>::with (113 samples, 0.03%)std::thread::local::LocalKey<T>::try_with (113 samples, 0.03%)tokio::runtime::context::set_scheduler::{{closure}} (113 samples, 0.03%)tokio::runtime::context::scoped::Scoped<T>::set (113 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (113 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::run (113 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (59 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (55 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (53 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (116 samples, 0.03%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (116 samples, 0.03%)tokio::runtime::task::harness::poll_future (119 samples, 0.03%)std::panic::catch_unwind (119 samples, 0.03%)std::panicking::try (119 samples, 0.03%)std::panicking::try::do_call (119 samples, 0.03%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (119 samples, 0.03%)tokio::runtime::task::harness::poll_future::{{closure}} (119 samples, 0.03%)tokio::runtime::task::core::Core<T,S>::poll (119 samples, 0.03%)tokio::runtime::task::raw::poll (136 samples, 0.04%)tokio::runtime::task::harness::Harness<T,S>::poll (123 samples, 0.03%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (122 samples, 0.03%)torrust_tracker::bootstrap::logging::INIT (43 samples, 0.01%)__memcpy_avx512_unaligned_erms (652 samples, 0.17%)__entry_text_start (57 samples, 0.02%)_int_free (317 samples, 0.08%)_int_malloc (313 samples, 0.08%)torrust_tracker::servers::udp::logging::log_request::__CALLSITE::META (1,319 samples, 0.35%)__GI___lll_lock_wait_private (265 samples, 0.07%)futex_wait (154 samples, 0.04%)futex_fatal_error (55 samples, 0.01%)__memcpy_avx512_unaligned_erms (1,079 samples, 0.29%)_int_free (67 samples, 0.02%)_int_malloc (120 samples, 0.03%)torrust_tracker::servers::udp::logging::log_request::__CALLSITE (1,582 samples, 0.42%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (122 samples, 0.03%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (59 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (45 samples, 0.01%)__GI___libc_malloc (123 samples, 0.03%)_int_malloc (143 samples, 0.04%)alloc::vec::Vec<T>::with_capacity (237 samples, 0.06%)alloc::vec::Vec<T,A>::with_capacity_in (237 samples, 0.06%)alloc::raw_vec::RawVec<T,A>::with_capacity_in (234 samples, 0.06%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (234 samples, 0.06%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (231 samples, 0.06%)alloc::alloc::Global::alloc_impl (231 samples, 0.06%)alloc::alloc::alloc (231 samples, 0.06%)__rdl_alloc (231 samples, 0.06%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (231 samples, 0.06%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (207 samples, 0.05%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (207 samples, 0.05%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (207 samples, 0.05%)__entry_text_start (140 samples, 0.04%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}}::{{closure}} (286 samples, 0.08%)mio::net::udp::UdpSocket::recv_from (273 samples, 0.07%)mio::io_source::IoSource<T>::do_io (273 samples, 0.07%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (273 samples, 0.07%)mio::net::udp::UdpSocket::recv_from::{{closure}} (273 samples, 0.07%)std::net::udp::UdpSocket::recv_from (273 samples, 0.07%)std::sys_common::net::UdpSocket::recv_from (273 samples, 0.07%)std::sys::pal::unix::net::Socket::recv_from (273 samples, 0.07%)std::sys::pal::unix::net::Socket::recv_from_with_flags (273 samples, 0.07%)core::mem::zeroed (131 samples, 0.03%)core::mem::maybe_uninit::MaybeUninit<T>::zeroed (131 samples, 0.03%)core::ptr::mut_ptr::<impl *mut T>::write_bytes (131 samples, 0.03%)core::intrinsics::write_bytes (131 samples, 0.03%)__entry_text_start (131 samples, 0.03%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (639 samples, 0.17%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (360 samples, 0.10%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (355 samples, 0.09%)__entry_text_start (171 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_option_task_without_yield (186 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task (186 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::with_current (186 samples, 0.05%)tokio::runtime::context::with_scheduler (185 samples, 0.05%)std::thread::local::LocalKey<T>::try_with (185 samples, 0.05%)tokio::runtime::context::with_scheduler::{{closure}} (185 samples, 0.05%)tokio::runtime::context::scoped::Scoped<T>::with (185 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (185 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (185 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (185 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (185 samples, 0.05%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (185 samples, 0.05%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (185 samples, 0.05%)tokio::runtime::driver::Handle::unpark (185 samples, 0.05%)tokio::runtime::driver::IoHandle::unpark (185 samples, 0.05%)tokio::runtime::io::driver::Handle::unpark (185 samples, 0.05%)mio::waker::Waker::wake (185 samples, 0.05%)mio::sys::unix::waker::fdbased::Waker::wake (185 samples, 0.05%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (182 samples, 0.05%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (182 samples, 0.05%)tokio::runtime::driver::Handle::unpark (178 samples, 0.05%)tokio::runtime::driver::IoHandle::unpark (178 samples, 0.05%)torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (1,051 samples, 0.28%)torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (1,045 samples, 0.28%)torrust_tracker::servers::udp::server::Udp::spawn_request_processor (319 samples, 0.08%)tokio::task::spawn::spawn (319 samples, 0.08%)tokio::task::spawn::spawn_inner (319 samples, 0.08%)tokio::runtime::context::current::with_current (319 samples, 0.08%)std::thread::local::LocalKey<T>::try_with (319 samples, 0.08%)tokio::runtime::context::current::with_current::{{closure}} (319 samples, 0.08%)core::option::Option<T>::map (319 samples, 0.08%)tokio::task::spawn::spawn_inner::{{closure}} (319 samples, 0.08%)tokio::runtime::scheduler::Handle::spawn (319 samples, 0.08%)tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (319 samples, 0.08%)tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (319 samples, 0.08%)tokio::runtime::task::list::OwnedTasks<S>::bind (133 samples, 0.04%)tokio::runtime::task::new_task (77 samples, 0.02%)tokio::runtime::task::raw::RawTask::new (77 samples, 0.02%)tokio::runtime::task::core::Cell<T,S>::new (77 samples, 0.02%)alloc::boxed::Box<T>::new (40 samples, 0.01%)all (378,369 samples, 100%)tokio-runtime-w (378,173 samples, 99.95%)tokio-runtime-w \ No newline at end of file diff --git a/docs/media/flamegraph_generated_without_sudo.svg b/docs/media/flamegraph_generated_without_sudo.svg new file mode 100644 index 000000000..e3df85866 --- /dev/null +++ b/docs/media/flamegraph_generated_without_sudo.svg @@ -0,0 +1,491 @@ +Flame Graph Reset ZoomSearch [unknown] (188 samples, 0.14%)[unknown] (187 samples, 0.14%)[unknown] (186 samples, 0.14%)[unknown] (178 samples, 0.14%)[unknown] (172 samples, 0.13%)[unknown] (158 samples, 0.12%)[unknown] (158 samples, 0.12%)[unknown] (125 samples, 0.10%)[unknown] (102 samples, 0.08%)[unknown] (93 samples, 0.07%)[unknown] (92 samples, 0.07%)[unknown] (41 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (29 samples, 0.02%)[unknown] (25 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (15 samples, 0.01%)__GI___mmap64 (18 samples, 0.01%)__GI___mmap64 (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (17 samples, 0.01%)profiling (214 samples, 0.16%)clone3 (22 samples, 0.02%)start_thread (22 samples, 0.02%)std::sys::pal::unix::thread::Thread::new::thread_start (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::Handler::new (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::imp::make_handler (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::imp::get_stack (19 samples, 0.01%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (30 samples, 0.02%)[[vdso]] (93 samples, 0.07%)<torrust_tracker::shared::crypto::ephemeral_instance_keys::RANDOM_SEED as core::ops::deref::Deref>::deref::__stability::LAZY (143 samples, 0.11%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (31 samples, 0.02%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<BorrowType,K,V>::init_front (21 samples, 0.02%)[[vdso]] (91 samples, 0.07%)__GI___clock_gettime (14 samples, 0.01%)_int_malloc (53 samples, 0.04%)epoll_wait (254 samples, 0.19%)tokio::runtime::context::with_scheduler (28 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (14 samples, 0.01%)tokio::runtime::context::with_scheduler::{{closure}} (14 samples, 0.01%)core::option::Option<T>::map (17 samples, 0.01%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (17 samples, 0.01%)mio::poll::Poll::poll (27 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select (27 samples, 0.02%)tokio::runtime::io::driver::Driver::turn (54 samples, 0.04%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (26 samples, 0.02%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (17 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (71 samples, 0.05%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (65 samples, 0.05%)core::sync::atomic::AtomicUsize::fetch_add (65 samples, 0.05%)core::sync::atomic::atomic_add (65 samples, 0.05%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (31 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark_condvar (18 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (49 samples, 0.04%)tokio::loom::std::mutex::Mutex<T>::lock (33 samples, 0.03%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (93 samples, 0.07%)tokio::runtime::scheduler::multi_thread::park::Parker::park (75 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Inner::park (75 samples, 0.06%)core::cell::RefCell<T>::borrow_mut (18 samples, 0.01%)core::cell::RefCell<T>::try_borrow_mut (18 samples, 0.01%)core::cell::BorrowRefMut::new (18 samples, 0.01%)tokio::runtime::coop::budget (26 samples, 0.02%)tokio::runtime::coop::with_budget (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (96 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_searching (27 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::transition_worker_from_searching (18 samples, 0.01%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::end_processing_scheduled_tasks (35 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::maintenance (14 samples, 0.01%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (90 samples, 0.07%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (90 samples, 0.07%)core::slice::<impl [T]>::contains (220 samples, 0.17%)<T as core::slice::cmp::SliceContains>::slice_contains (220 samples, 0.17%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (220 samples, 0.17%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (54 samples, 0.04%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (54 samples, 0.04%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (240 samples, 0.18%)tokio::runtime::scheduler::multi_thread::idle::Idle::unpark_worker_by_id (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (265 samples, 0.20%)tokio::runtime::scheduler::multi_thread::worker::Context::park (284 samples, 0.22%)core::option::Option<T>::or_else (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (40 samples, 0.03%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (17 samples, 0.01%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (17 samples, 0.01%)core::num::<impl u32>::wrapping_add (17 samples, 0.01%)core::sync::atomic::AtomicU64::compare_exchange (26 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (129 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (128 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (119 samples, 0.09%)tokio::runtime::scheduler::multi_thread::queue::pack (39 samples, 0.03%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run (613 samples, 0.47%)tokio::runtime::context::runtime::enter_runtime (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (613 samples, 0.47%)tokio::runtime::context::set_scheduler (613 samples, 0.47%)std::thread::local::LocalKey<T>::with (613 samples, 0.47%)std::thread::local::LocalKey<T>::try_with (613 samples, 0.47%)tokio::runtime::context::set_scheduler::{{closure}} (613 samples, 0.47%)tokio::runtime::context::scoped::Scoped<T>::set (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::Context::run (613 samples, 0.47%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (777 samples, 0.59%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (776 samples, 0.59%)core::ptr::drop_in_place<tokio::runtime::task::core::TaskIdGuard> (16 samples, 0.01%)<tokio::runtime::task::core::TaskIdGuard as core::ops::drop::Drop>::drop (16 samples, 0.01%)tokio::runtime::context::set_current_task_id (16 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (16 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (20 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (20 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::poll (835 samples, 0.64%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (56 samples, 0.04%)tokio::runtime::task::core::Core<T,S>::set_stage (46 samples, 0.04%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (897 samples, 0.68%)tokio::runtime::task::harness::poll_future::{{closure}} (897 samples, 0.68%)tokio::runtime::task::core::Core<T,S>::store_output (62 samples, 0.05%)tokio::runtime::task::harness::poll_future (930 samples, 0.71%)std::panic::catch_unwind (927 samples, 0.71%)std::panicking::try (927 samples, 0.71%)std::panicking::try::do_call (925 samples, 0.70%)core::mem::manually_drop::ManuallyDrop<T>::take (28 samples, 0.02%)core::ptr::read (28 samples, 0.02%)tokio::runtime::task::raw::poll (938 samples, 0.71%)tokio::runtime::task::harness::Harness<T,S>::poll (934 samples, 0.71%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (934 samples, 0.71%)core::array::<impl core::default::Default for [T: 32]>::default (26 samples, 0.02%)tokio::runtime::time::Inner::lock (16 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (15 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::time::wheel::Wheel::poll (25 samples, 0.02%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (98 samples, 0.07%)tokio::runtime::time::Driver::park_internal (51 samples, 0.04%)tokio::runtime::time::wheel::Wheel::next_expiration (15 samples, 0.01%)<F as core::future::into_future::IntoFuture>::into_future (16 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (24 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (46 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (131 samples, 0.10%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (24 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (14 samples, 0.01%)core::sync::atomic::AtomicU32::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (39 samples, 0.03%)std::sync::rwlock::RwLock<T>::read (34 samples, 0.03%)std::sys::sync::rwlock::futex::RwLock::read (32 samples, 0.02%)[[heap]] (2,361 samples, 1.80%)[..[[vdso]] (313 samples, 0.24%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (41 samples, 0.03%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (16 samples, 0.01%)<alloc::string::String as core::fmt::Write>::write_str (67 samples, 0.05%)alloc::string::String::push_str (18 samples, 0.01%)alloc::vec::Vec<T,A>::extend_from_slice (18 samples, 0.01%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (18 samples, 0.01%)alloc::vec::Vec<T,A>::append_elements (18 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (36 samples, 0.03%)core::num::<impl u64>::rotate_left (28 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (60 samples, 0.05%)core::num::<impl u64>::wrapping_add (14 samples, 0.01%)core::hash::sip::u8to64_le (60 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (184 samples, 0.14%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (15 samples, 0.01%)tokio::runtime::context::CONTEXT::__getit (19 samples, 0.01%)core::cell::Cell<T>::get (17 samples, 0.01%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (26 samples, 0.02%)core::ops::function::FnMut::call_mut (21 samples, 0.02%)tokio::runtime::coop::poll_proceed (21 samples, 0.02%)tokio::runtime::context::budget (21 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (21 samples, 0.02%)[unknown] (18 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (195 samples, 0.15%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (14 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (14 samples, 0.01%)core::result::Result<T,E>::is_err (18 samples, 0.01%)core::result::Result<T,E>::is_ok (18 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (46 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (39 samples, 0.03%)core::sync::atomic::AtomicU32::compare_exchange (19 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (19 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (245 samples, 0.19%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (26 samples, 0.02%)[[vdso]] (748 samples, 0.57%)[profiling] (34 samples, 0.03%)core::fmt::write (31 samples, 0.02%)__GI___clock_gettime (29 samples, 0.02%)__GI___libc_free (131 samples, 0.10%)arena_for_chunk (20 samples, 0.02%)arena_for_chunk (19 samples, 0.01%)heap_for_ptr (19 samples, 0.01%)heap_max_size (14 samples, 0.01%)__GI___libc_malloc (114 samples, 0.09%)__GI___libc_realloc (15 samples, 0.01%)__GI___lll_lock_wake_private (22 samples, 0.02%)__GI___pthread_disable_asynccancel (66 samples, 0.05%)__GI_getsockname (249 samples, 0.19%)__libc_calloc (15 samples, 0.01%)__libc_recvfrom (23 samples, 0.02%)__libc_sendto (130 samples, 0.10%)__memcmp_evex_movbe (451 samples, 0.34%)__memcpy_avx512_unaligned_erms (426 samples, 0.32%)__memset_avx512_unaligned_erms (215 samples, 0.16%)__posix_memalign (17 samples, 0.01%)_int_free (418 samples, 0.32%)tcache_put (24 samples, 0.02%)_int_malloc (385 samples, 0.29%)_int_memalign (31 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (26 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (15 samples, 0.01%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (15 samples, 0.01%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (15 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (54 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::grow_one (15 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (96 samples, 0.07%)alloc::raw_vec::RawVec<T,A>::grow_amortized (66 samples, 0.05%)core::num::<impl usize>::checked_add (18 samples, 0.01%)core::num::<impl usize>::overflowing_add (18 samples, 0.01%)alloc::raw_vec::finish_grow (74 samples, 0.06%)alloc::sync::Arc<T,A>::drop_slow (16 samples, 0.01%)core::mem::drop (14 samples, 0.01%)core::fmt::Formatter::pad_integral (14 samples, 0.01%)core::ptr::drop_in_place<aquatic_udp_protocol::response::Response> (93 samples, 0.07%)core::ptr::drop_in_place<tokio::net::udp::UdpSocket::send_to<&core::net::socket_addr::SocketAddr>::{{closure}}> (23 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (188 samples, 0.14%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_announce::{{closure}}> (30 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_connect::{{closure}}> (22 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_packet::{{closure}}> (20 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}}> (19 samples, 0.01%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::send_response::{{closure}}> (22 samples, 0.02%)malloc_consolidate (24 samples, 0.02%)core::core_arch::x86::avx2::_mm256_or_si256 (15 samples, 0.01%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (17 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (17 samples, 0.01%)rand_chacha::guts::round (66 samples, 0.05%)rand_chacha::guts::refill_wide::impl_avx2 (99 samples, 0.08%)rand_chacha::guts::refill_wide::fn_impl (98 samples, 0.07%)rand_chacha::guts::refill_wide_impl (98 samples, 0.07%)std::io::error::Error::kind (14 samples, 0.01%)[unknown] (42 samples, 0.03%)[unknown] (14 samples, 0.01%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (490 samples, 0.37%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (211 samples, 0.16%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (84 samples, 0.06%)tokio::runtime::task::core::Header::get_owner_id (18 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with (18 samples, 0.01%)tokio::runtime::task::core::Header::get_owner_id::{{closure}} (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (20 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::remove (19 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (31 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (29 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage (108 samples, 0.08%)tokio::runtime::task::core::TaskIdGuard::enter (14 samples, 0.01%)tokio::runtime::context::set_current_task_id (14 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (14 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::complete (21 samples, 0.02%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (32 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (54 samples, 0.04%)tokio::runtime::task::raw::drop_abort_handle (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::maintenance (17 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (22 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (22 samples, 0.02%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (79 samples, 0.06%)core::slice::<impl [T]>::contains (178 samples, 0.14%)<T as core::slice::cmp::SliceContains>::slice_contains (178 samples, 0.14%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (178 samples, 0.14%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (40 samples, 0.03%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (40 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (216 samples, 0.16%)tokio::loom::std::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (219 samples, 0.17%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (29 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (29 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (54 samples, 0.04%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (18 samples, 0.01%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (18 samples, 0.01%)core::sync::atomic::AtomicU32::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_if_work_pending (113 samples, 0.09%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::is_empty (51 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::is_empty (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::len (31 samples, 0.02%)core::sync::atomic::AtomicU64::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (447 samples, 0.34%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (174 samples, 0.13%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (19 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (489 samples, 0.37%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (489 samples, 0.37%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run (484 samples, 0.37%)tokio::runtime::context::runtime::enter_runtime (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (484 samples, 0.37%)tokio::runtime::context::set_scheduler (484 samples, 0.37%)std::thread::local::LocalKey<T>::with (484 samples, 0.37%)std::thread::local::LocalKey<T>::try_with (484 samples, 0.37%)tokio::runtime::context::set_scheduler::{{closure}} (484 samples, 0.37%)tokio::runtime::context::scoped::Scoped<T>::set (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Context::run (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (24 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (20 samples, 0.02%)tokio::runtime::task::raw::poll (515 samples, 0.39%)tokio::runtime::task::harness::Harness<T,S>::poll (493 samples, 0.38%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (493 samples, 0.38%)tokio::runtime::task::harness::poll_future (493 samples, 0.38%)std::panic::catch_unwind (493 samples, 0.38%)std::panicking::try (493 samples, 0.38%)std::panicking::try::do_call (493 samples, 0.38%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (493 samples, 0.38%)tokio::runtime::task::harness::poll_future::{{closure}} (493 samples, 0.38%)tokio::runtime::task::core::Core<T,S>::poll (493 samples, 0.38%)tokio::runtime::time::wheel::Wheel::next_expiration (16 samples, 0.01%)torrust_tracker::core::Tracker::authorize::{{closure}} (27 samples, 0.02%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (15 samples, 0.01%)torrust_tracker::core::Tracker::send_stats_event::{{closure}} (44 samples, 0.03%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (15 samples, 0.01%)<std::hash::random::DefaultHasher as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::d_rounds (29 samples, 0.02%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (74 samples, 0.06%)torrust_tracker::servers::udp::peer_builder::from_request (17 samples, 0.01%)torrust_tracker::servers::udp::request::AnnounceWrapper::new (51 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (54 samples, 0.04%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (58 samples, 0.04%)torrust_tracker::core::Tracker::announce::{{closure}} (70 samples, 0.05%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (113 samples, 0.09%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (175 samples, 0.13%)<T as alloc::string::ToString>::to_string (38 samples, 0.03%)core::option::Option<T>::expect (56 samples, 0.04%)torrust_tracker_primitives::info_hash::InfoHash::to_hex_string (18 samples, 0.01%)<T as alloc::string::ToString>::to_string (18 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (180 samples, 0.14%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (468 samples, 0.36%)torrust_tracker::servers::udp::logging::log_response (38 samples, 0.03%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (669 samples, 0.51%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (152 samples, 0.12%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (147 samples, 0.11%)tokio::net::udp::UdpSocket::send_to::{{closure}} (138 samples, 0.11%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (119 samples, 0.09%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (75 samples, 0.06%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (39 samples, 0.03%)mio::net::udp::UdpSocket::send_to (39 samples, 0.03%)mio::io_source::IoSource<T>::do_io (39 samples, 0.03%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (39 samples, 0.03%)mio::net::udp::UdpSocket::send_to::{{closure}} (39 samples, 0.03%)std::net::udp::UdpSocket::send_to (39 samples, 0.03%)std::sys_common::net::UdpSocket::send_to (39 samples, 0.03%)std::sys::pal::unix::cvt (39 samples, 0.03%)<isize as std::sys::pal::unix::IsMinusOne>::is_minus_one (39 samples, 0.03%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_stats (15 samples, 0.01%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (14 samples, 0.01%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::count::to_usize::{{closure}} (33 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats::{{closure}} (33 samples, 0.03%)torrust_tracker_primitives::peer::Peer::is_seeder (33 samples, 0.03%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::count (75 samples, 0.06%)core::iter::traits::iterator::Iterator::sum (75 samples, 0.06%)<usize as core::iter::traits::accum::Sum>::sum (75 samples, 0.06%)<core::iter::adapters::map::Map<I,F> as core::iter::traits::iterator::Iterator>::fold (75 samples, 0.06%)core::iter::traits::iterator::Iterator::fold (75 samples, 0.06%)core::iter::adapters::map::map_fold::{{closure}} (34 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (104 samples, 0.08%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (24 samples, 0.02%)core::mem::drop (15 samples, 0.01%)core::ptr::drop_in_place<core::option::Option<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (15 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (15 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (15 samples, 0.01%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (215 samples, 0.16%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (198 samples, 0.15%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (89 samples, 0.07%)core::option::Option<T>::is_some_and (32 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (31 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (30 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (30 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (26 samples, 0.02%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (34 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (34 samples, 0.03%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (58 samples, 0.04%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (58 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (58 samples, 0.04%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (58 samples, 0.04%)<u8 as core::slice::cmp::SliceOrd>::compare (58 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (20 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (238 samples, 0.18%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (236 samples, 0.18%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (208 samples, 0.16%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (208 samples, 0.16%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (282 samples, 0.21%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (67 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (53 samples, 0.04%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (53 samples, 0.04%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (22 samples, 0.02%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (22 samples, 0.02%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (22 samples, 0.02%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (22 samples, 0.02%)<u8 as core::slice::cmp::SliceOrd>::compare (22 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (18 samples, 0.01%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (23 samples, 0.02%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (23 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (43 samples, 0.03%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (43 samples, 0.03%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (43 samples, 0.03%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (43 samples, 0.03%)<u8 as core::slice::cmp::SliceOrd>::compare (43 samples, 0.03%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (17 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (151 samples, 0.12%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (145 samples, 0.11%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (137 samples, 0.10%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (137 samples, 0.10%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (266 samples, 0.20%)core::sync::atomic::AtomicU32::load (27 samples, 0.02%)core::sync::atomic::atomic_load (27 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (38 samples, 0.03%)std::sync::rwlock::RwLock<T>::read (37 samples, 0.03%)std::sys::sync::rwlock::futex::RwLock::read (36 samples, 0.03%)tracing::span::Span::log (16 samples, 0.01%)tracing::span::Span::record_all (70 samples, 0.05%)unlink_chunk (139 samples, 0.11%)rand::rng::Rng::gen (30 samples, 0.02%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (30 samples, 0.02%)rand::rng::Rng::gen (30 samples, 0.02%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (30 samples, 0.02%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (30 samples, 0.02%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (30 samples, 0.02%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (30 samples, 0.02%)rand_core::block::BlockRng<R>::generate_and_set (28 samples, 0.02%)[anon] (8,759 samples, 6.67%)[anon]uuid::v4::<impl uuid::Uuid>::new_v4 (32 samples, 0.02%)uuid::rng::bytes (32 samples, 0.02%)rand::random (32 samples, 0.02%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (15 samples, 0.01%)_int_free (338 samples, 0.26%)tcache_put (18 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (22 samples, 0.02%)hashbrown::raw::h2 (14 samples, 0.01%)hashbrown::raw::RawTable<T,A>::find_or_find_insert_slot (23 samples, 0.02%)hashbrown::raw::RawTableInner::find_or_find_insert_slot_inner (17 samples, 0.01%)hashbrown::map::HashMap<K,V,S,A>::insert (25 samples, 0.02%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (15 samples, 0.01%)[profiling] (545 samples, 0.42%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (32 samples, 0.02%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (22 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (16 samples, 0.01%)alloc::vec::Vec<T,A>::reserve (30 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve (28 samples, 0.02%)<alloc::string::String as core::fmt::Write>::write_str (83 samples, 0.06%)alloc::string::String::push_str (57 samples, 0.04%)alloc::vec::Vec<T,A>::extend_from_slice (57 samples, 0.04%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (57 samples, 0.04%)alloc::vec::Vec<T,A>::append_elements (57 samples, 0.04%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (20 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (41 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (151 samples, 0.12%)core::hash::sip::u8to64_le (50 samples, 0.04%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (33 samples, 0.03%)tokio::runtime::context::CONTEXT::__getit (35 samples, 0.03%)core::cell::Cell<T>::get (33 samples, 0.03%)[unknown] (20 samples, 0.02%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (75 samples, 0.06%)core::ops::function::FnMut::call_mut (66 samples, 0.05%)tokio::runtime::coop::poll_proceed (66 samples, 0.05%)tokio::runtime::context::budget (66 samples, 0.05%)std::thread::local::LocalKey<T>::try_with (66 samples, 0.05%)tokio::runtime::context::budget::{{closure}} (27 samples, 0.02%)tokio::runtime::coop::poll_proceed::{{closure}} (27 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (110 samples, 0.08%)[unknown] (15 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (27 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (27 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (14 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (84 samples, 0.06%)std::sync::mutex::Mutex<T>::lock (70 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock (59 samples, 0.04%)core::sync::atomic::AtomicU32::compare_exchange (55 samples, 0.04%)core::sync::atomic::atomic_compare_exchange (55 samples, 0.04%)[unknown] (33 samples, 0.03%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (214 samples, 0.16%)__memcpy_avx512_unaligned_erms (168 samples, 0.13%)[profiling] (171 samples, 0.13%)binascii::bin2hex (77 samples, 0.06%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (280 samples, 0.21%)[unknown] (317 samples, 0.24%)[[vdso]] (2,648 samples, 2.02%)[..[unknown] (669 samples, 0.51%)[unknown] (396 samples, 0.30%)[unknown] (251 samples, 0.19%)[unknown] (65 samples, 0.05%)[unknown] (30 samples, 0.02%)[unknown] (21 samples, 0.02%)__GI___clock_gettime (56 samples, 0.04%)arena_for_chunk (72 samples, 0.05%)arena_for_chunk (62 samples, 0.05%)heap_for_ptr (49 samples, 0.04%)heap_max_size (28 samples, 0.02%)__GI___libc_free (194 samples, 0.15%)arena_for_chunk (19 samples, 0.01%)checked_request2size (24 samples, 0.02%)__GI___libc_malloc (220 samples, 0.17%)tcache_get (44 samples, 0.03%)__GI___libc_write (25 samples, 0.02%)__GI___libc_write (14 samples, 0.01%)__GI___pthread_disable_asynccancel (97 samples, 0.07%)core::num::<impl u128>::leading_zeros (15 samples, 0.01%)compiler_builtins::float::conv::int_to_float::u128_to_f64_bits (72 samples, 0.05%)__floattidf (90 samples, 0.07%)compiler_builtins::float::conv::__floattidf (86 samples, 0.07%)exp_inline (40 samples, 0.03%)log_inline (64 samples, 0.05%)__ieee754_pow_fma (114 samples, 0.09%)__libc_calloc (106 samples, 0.08%)__libc_recvfrom (252 samples, 0.19%)__libc_sendto (133 samples, 0.10%)__memcmp_evex_movbe (137 samples, 0.10%)__memcpy_avx512_unaligned_erms (1,399 samples, 1.07%)__posix_memalign (172 samples, 0.13%)__posix_memalign (80 samples, 0.06%)_mid_memalign (71 samples, 0.05%)arena_for_chunk (14 samples, 0.01%)__pow (18 samples, 0.01%)__vdso_clock_gettime (40 samples, 0.03%)[unknown] (24 samples, 0.02%)_int_free (462 samples, 0.35%)tcache_put (54 samples, 0.04%)[unknown] (14 samples, 0.01%)_int_malloc (508 samples, 0.39%)_int_memalign (68 samples, 0.05%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (54 samples, 0.04%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (14 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (78 samples, 0.06%)alloc::raw_vec::RawVec<T,A>::grow_amortized (73 samples, 0.06%)alloc::raw_vec::finish_grow (91 samples, 0.07%)core::result::Result<T,E>::map_err (31 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Weak<ring::ec::curve25519::ed25519::signing::Ed25519KeyPair,&alloc::alloc::Global>> (16 samples, 0.01%)<alloc::sync::Weak<T,A> as core::ops::drop::Drop>::drop (16 samples, 0.01%)core::mem::drop (18 samples, 0.01%)alloc::sync::Arc<T,A>::drop_slow (21 samples, 0.02%)alloc_new_heap (49 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (49 samples, 0.04%)core::fmt::Formatter::pad_integral (40 samples, 0.03%)core::fmt::Formatter::pad_integral::write_prefix (19 samples, 0.01%)core::fmt::write (20 samples, 0.02%)core::ptr::drop_in_place<[core::option::Option<core::task::wake::Waker>: 32]> (155 samples, 0.12%)core::ptr::drop_in_place<core::option::Option<core::task::wake::Waker>> (71 samples, 0.05%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (245 samples, 0.19%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_announce::{{closure}}> (33 samples, 0.03%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}}> (37 samples, 0.03%)core::str::converts::from_utf8 (33 samples, 0.03%)core::str::validations::run_utf8_validation (20 samples, 0.02%)epoll_wait (31 samples, 0.02%)hashbrown::map::HashMap<K,V,S,A>::insert (17 samples, 0.01%)rand_chacha::guts::refill_wide (19 samples, 0.01%)std_detect::detect::arch::x86::__is_feature_detected::avx2 (17 samples, 0.01%)std_detect::detect::check_for (17 samples, 0.01%)std_detect::detect::cache::test (17 samples, 0.01%)std_detect::detect::cache::Cache::test (17 samples, 0.01%)core::sync::atomic::AtomicUsize::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)std::sys::pal::unix::time::Timespec::new (29 samples, 0.02%)std::sys::pal::unix::time::Timespec::now (132 samples, 0.10%)core::cmp::impls::<impl core::cmp::PartialOrd<&B> for &A>::ge (22 samples, 0.02%)core::cmp::PartialOrd::ge (22 samples, 0.02%)std::sys::pal::unix::time::Timespec::sub_timespec (67 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock_contended (18 samples, 0.01%)std::sys_common::net::TcpListener::socket_addr (29 samples, 0.02%)std::sys_common::net::sockname (28 samples, 0.02%)syscall (552 samples, 0.42%)core::ptr::drop_in_place<core::cell::RefMut<core::option::Option<alloc::boxed::Box<tokio::runtime::scheduler::multi_thread::worker::Core>>>> (74 samples, 0.06%)core::ptr::drop_in_place<core::cell::BorrowRefMut> (74 samples, 0.06%)<core::cell::BorrowRefMut as core::ops::drop::Drop>::drop (74 samples, 0.06%)core::cell::Cell<T>::set (74 samples, 0.06%)core::cell::Cell<T>::replace (74 samples, 0.06%)core::mem::replace (74 samples, 0.06%)core::ptr::write (74 samples, 0.06%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::push_back_or_overflow (14 samples, 0.01%)tokio::runtime::context::with_scheduler (176 samples, 0.13%)std::thread::local::LocalKey<T>::try_with (152 samples, 0.12%)tokio::runtime::context::with_scheduler::{{closure}} (151 samples, 0.12%)tokio::runtime::context::scoped::Scoped<T>::with (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (71 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (16 samples, 0.01%)core::option::Option<T>::map (19 samples, 0.01%)<mio::event::events::Iter as core::iter::traits::iterator::Iterator>::next (24 samples, 0.02%)mio::poll::Poll::poll (53 samples, 0.04%)mio::sys::unix::selector::epoll::Selector::select (53 samples, 0.04%)core::result::Result<T,E>::map (28 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (28 samples, 0.02%)tokio::io::ready::Ready::from_mio (14 samples, 0.01%)tokio::runtime::io::driver::Driver::turn (126 samples, 0.10%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (18 samples, 0.01%)[unknown] (51 samples, 0.04%)[unknown] (100 samples, 0.08%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (326 samples, 0.25%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (205 samples, 0.16%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (77 samples, 0.06%)[unknown] (26 samples, 0.02%)<tokio::util::linked_list::DrainFilter<T,F> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (396 samples, 0.30%)tokio::loom::std::mutex::Mutex<T>::lock (18 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (573 samples, 0.44%)core::sync::atomic::AtomicUsize::fetch_add (566 samples, 0.43%)core::sync::atomic::atomic_add (566 samples, 0.43%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (635 samples, 0.48%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (25 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::next_remote_task (44 samples, 0.03%)tokio::runtime::scheduler::inject::shared::Shared<T>::is_empty (21 samples, 0.02%)tokio::runtime::scheduler::inject::shared::Shared<T>::len (21 samples, 0.02%)core::sync::atomic::AtomicUsize::load (21 samples, 0.02%)core::sync::atomic::atomic_load (21 samples, 0.02%)tokio::runtime::task::core::Header::get_owner_id (32 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with (32 samples, 0.02%)tokio::runtime::task::core::Header::get_owner_id::{{closure}} (32 samples, 0.02%)std::sync::poison::Flag::done (32 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>,tokio::runtime::task::core::Header>>> (43 samples, 0.03%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (43 samples, 0.03%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (123 samples, 0.09%)tokio::runtime::task::list::OwnedTasks<S>::remove (117 samples, 0.09%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (80 samples, 0.06%)tokio::runtime::scheduler::defer::Defer::wake (17 samples, 0.01%)std::sys::pal::unix::futex::futex_wait (46 samples, 0.04%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (71 samples, 0.05%)std::sync::condvar::Condvar::wait (56 samples, 0.04%)std::sys::sync::condvar::futex::Condvar::wait (56 samples, 0.04%)std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (56 samples, 0.04%)core::sync::atomic::AtomicUsize::compare_exchange (37 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (37 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::park_driver (138 samples, 0.11%)tokio::runtime::driver::Driver::park (77 samples, 0.06%)tokio::runtime::driver::TimeDriver::park (77 samples, 0.06%)tokio::runtime::time::Driver::park (75 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Parker::park (266 samples, 0.20%)tokio::runtime::scheduler::multi_thread::park::Inner::park (266 samples, 0.20%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (432 samples, 0.33%)tokio::runtime::scheduler::multi_thread::worker::Core::should_notify_others (26 samples, 0.02%)core::cell::RefCell<T>::borrow_mut (94 samples, 0.07%)core::cell::RefCell<T>::try_borrow_mut (94 samples, 0.07%)core::cell::BorrowRefMut::new (94 samples, 0.07%)tokio::runtime::coop::budget (142 samples, 0.11%)tokio::runtime::coop::with_budget (142 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (121 samples, 0.09%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (44 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (208 samples, 0.16%)tokio::runtime::signal::Driver::process (30 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (46 samples, 0.04%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (46 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (35 samples, 0.03%)tokio::runtime::task::core::Core<T,S>::set_stage (75 samples, 0.06%)core::sync::atomic::AtomicUsize::fetch_xor (76 samples, 0.06%)core::sync::atomic::atomic_xor (76 samples, 0.06%)tokio::runtime::task::state::State::transition_to_complete (79 samples, 0.06%)tokio::runtime::task::harness::Harness<T,S>::complete (113 samples, 0.09%)tokio::runtime::task::state::State::transition_to_terminal (18 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::dealloc (28 samples, 0.02%)core::mem::drop (18 samples, 0.01%)core::ptr::drop_in_place<alloc::boxed::Box<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (18 samples, 0.01%)core::ptr::drop_in_place<tokio::util::sharded_list::ShardGuard<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>> (16 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>>> (16 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (16 samples, 0.01%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (53 samples, 0.04%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::push_front (21 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (113 samples, 0.09%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (15 samples, 0.01%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (15 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (15 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (15 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (14 samples, 0.01%)tokio::runtime::task::raw::drop_abort_handle (82 samples, 0.06%)tokio::runtime::task::harness::Harness<T,S>::drop_reference (23 samples, 0.02%)tokio::runtime::task::state::State::ref_dec (23 samples, 0.02%)core::sync::atomic::AtomicUsize::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::task::raw::drop_join_handle_slow (34 samples, 0.03%)tokio::runtime::task::harness::Harness<T,S>::drop_join_handle_slow (32 samples, 0.02%)tokio::runtime::task::state::State::unset_join_interested (23 samples, 0.02%)tokio::runtime::task::state::State::fetch_update (23 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (43 samples, 0.03%)core::num::<impl u32>::wrapping_add (23 samples, 0.02%)core::option::Option<T>::or_else (37 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (36 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (36 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (38 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (59 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (45 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (132 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (63 samples, 0.05%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run (290 samples, 0.22%)tokio::runtime::context::runtime::enter_runtime (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (290 samples, 0.22%)tokio::runtime::context::set_scheduler (290 samples, 0.22%)std::thread::local::LocalKey<T>::with (290 samples, 0.22%)std::thread::local::LocalKey<T>::try_with (290 samples, 0.22%)tokio::runtime::context::set_scheduler::{{closure}} (290 samples, 0.22%)tokio::runtime::context::scoped::Scoped<T>::set (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::Context::run (290 samples, 0.22%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (327 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (322 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::poll (333 samples, 0.25%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (342 samples, 0.26%)tokio::runtime::task::harness::poll_future::{{closure}} (342 samples, 0.26%)tokio::runtime::task::harness::poll_future (348 samples, 0.27%)std::panic::catch_unwind (347 samples, 0.26%)std::panicking::try (347 samples, 0.26%)std::panicking::try::do_call (347 samples, 0.26%)core::sync::atomic::AtomicUsize::compare_exchange (18 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (18 samples, 0.01%)tokio::runtime::task::state::State::transition_to_running (47 samples, 0.04%)tokio::runtime::task::state::State::fetch_update_action (47 samples, 0.04%)tokio::runtime::task::state::State::transition_to_running::{{closure}} (19 samples, 0.01%)tokio::runtime::task::raw::poll (427 samples, 0.33%)tokio::runtime::task::harness::Harness<T,S>::poll (408 samples, 0.31%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (407 samples, 0.31%)tokio::runtime::task::state::State::transition_to_idle (17 samples, 0.01%)core::array::<impl core::default::Default for [T: 32]>::default (21 samples, 0.02%)tokio::runtime::time::wheel::Wheel::poll (14 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (72 samples, 0.05%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process (23 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (15 samples, 0.01%)tokio::runtime::time::source::TimeSource::now (14 samples, 0.01%)tokio::runtime::time::Driver::park_internal (155 samples, 0.12%)tokio::runtime::time::wheel::level::Level::next_occupied_slot (96 samples, 0.07%)tokio::runtime::time::wheel::level::slot_range (35 samples, 0.03%)core::num::<impl usize>::pow (35 samples, 0.03%)tokio::runtime::time::wheel::level::level_range (39 samples, 0.03%)tokio::runtime::time::wheel::level::slot_range (33 samples, 0.03%)core::num::<impl usize>::pow (33 samples, 0.03%)tokio::runtime::time::wheel::level::Level::next_expiration (208 samples, 0.16%)tokio::runtime::time::wheel::level::slot_range (48 samples, 0.04%)core::num::<impl usize>::pow (48 samples, 0.04%)tokio::runtime::time::wheel::Wheel::next_expiration (277 samples, 0.21%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::is_empty (18 samples, 0.01%)core::option::Option<T>::is_some (18 samples, 0.01%)torrust_tracker::core::Tracker::authorize::{{closure}} (50 samples, 0.04%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (37 samples, 0.03%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_peers_for_client (27 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_peers_for_client (19 samples, 0.01%)core::iter::traits::iterator::Iterator::collect (17 samples, 0.01%)<alloc::vec::Vec<T> as core::iter::traits::collect::FromIterator<T>>::from_iter (17 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (17 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter_nested::SpecFromIterNested<T,I>>::from_iter (17 samples, 0.01%)<std::hash::random::DefaultHasher as core::hash::Hasher>::finish (20 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::finish (20 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::finish (20 samples, 0.02%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (62 samples, 0.05%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (40 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (27 samples, 0.02%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (17 samples, 0.01%)torrust_tracker::servers::udp::peer_builder::from_request (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (19 samples, 0.01%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (355 samples, 0.27%)<F as core::future::into_future::IntoFuture>::into_future (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (37 samples, 0.03%)core::sync::atomic::AtomicUsize::fetch_add (25 samples, 0.02%)core::sync::atomic::atomic_add (25 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet (14 samples, 0.01%)core::ptr::drop_in_place<torrust_tracker::servers::udp::UdpRequest> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (20 samples, 0.02%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)core::result::Result<T,E>::map_err (16 samples, 0.01%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (136 samples, 0.10%)torrust_tracker::core::Tracker::announce::{{closure}} (173 samples, 0.13%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (267 samples, 0.20%)torrust_tracker::servers::udp::handlers::handle_connect::{{closure}} (30 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (423 samples, 0.32%)core::fmt::Formatter::new (26 samples, 0.02%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (80 samples, 0.06%)core::fmt::num::imp::fmt_u64 (58 samples, 0.04%)core::intrinsics::copy_nonoverlapping (15 samples, 0.01%)core::fmt::num::imp::<impl core::fmt::Display for i64>::fmt (74 samples, 0.06%)core::fmt::num::imp::fmt_u64 (70 samples, 0.05%)<T as alloc::string::ToString>::to_string (207 samples, 0.16%)core::option::Option<T>::expect (19 samples, 0.01%)core::ptr::drop_in_place<alloc::string::String> (18 samples, 0.01%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (18 samples, 0.01%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (18 samples, 0.01%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (18 samples, 0.01%)torrust_tracker::servers::udp::logging::map_action_name (25 samples, 0.02%)alloc::str::<impl alloc::borrow::ToOwned for str>::to_owned (14 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (345 samples, 0.26%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (18 samples, 0.01%)core::fmt::num::imp::fmt_u64 (14 samples, 0.01%)<T as alloc::string::ToString>::to_string (35 samples, 0.03%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (1,067 samples, 0.81%)torrust_tracker::servers::udp::logging::log_response (72 samples, 0.05%)alloc::vec::from_elem (68 samples, 0.05%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (68 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (68 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (68 samples, 0.05%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (68 samples, 0.05%)alloc::alloc::Global::alloc_impl (68 samples, 0.05%)alloc::alloc::alloc_zeroed (68 samples, 0.05%)__rdl_alloc_zeroed (68 samples, 0.05%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (68 samples, 0.05%)[unknown] (48 samples, 0.04%)[unknown] (16 samples, 0.01%)[unknown] (28 samples, 0.02%)std::sys::pal::unix::cvt (134 samples, 0.10%)<isize as std::sys::pal::unix::IsMinusOne>::is_minus_one (134 samples, 0.10%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (1,908 samples, 1.45%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (504 samples, 0.38%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (382 samples, 0.29%)tokio::net::udp::UdpSocket::send_to::{{closure}} (344 samples, 0.26%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (332 samples, 0.25%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (304 samples, 0.23%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (215 samples, 0.16%)mio::net::udp::UdpSocket::send_to (185 samples, 0.14%)mio::io_source::IoSource<T>::do_io (185 samples, 0.14%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (185 samples, 0.14%)mio::net::udp::UdpSocket::send_to::{{closure}} (185 samples, 0.14%)std::net::udp::UdpSocket::send_to (185 samples, 0.14%)std::sys_common::net::UdpSocket::send_to (169 samples, 0.13%)alloc::vec::Vec<T>::with_capacity (17 samples, 0.01%)alloc::vec::Vec<T,A>::with_capacity_in (17 samples, 0.01%)tokio::net::udp::UdpSocket::readable::{{closure}} (104 samples, 0.08%)tokio::net::udp::UdpSocket::ready::{{closure}} (85 samples, 0.06%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (190 samples, 0.14%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (49 samples, 0.04%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (28 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (330 samples, 0.25%)torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (327 samples, 0.25%)torrust_tracker::servers::udp::server::Udp::spawn_request_processor (92 samples, 0.07%)tokio::task::spawn::spawn (92 samples, 0.07%)tokio::task::spawn::spawn_inner (92 samples, 0.07%)tokio::runtime::context::current::with_current (92 samples, 0.07%)std::thread::local::LocalKey<T>::try_with (92 samples, 0.07%)tokio::runtime::context::current::with_current::{{closure}} (92 samples, 0.07%)core::option::Option<T>::map (92 samples, 0.07%)tokio::task::spawn::spawn_inner::{{closure}} (92 samples, 0.07%)tokio::runtime::scheduler::Handle::spawn (92 samples, 0.07%)tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (92 samples, 0.07%)tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (92 samples, 0.07%)tokio::runtime::task::list::OwnedTasks<S>::bind (90 samples, 0.07%)tokio::runtime::task::new_task (89 samples, 0.07%)tokio::runtime::task::raw::RawTask::new (89 samples, 0.07%)tokio::runtime::task::core::Cell<T,S>::new (89 samples, 0.07%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (34 samples, 0.03%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (27 samples, 0.02%)alloc::sync::Arc<T>::new (21 samples, 0.02%)alloc::boxed::Box<T>::new (21 samples, 0.02%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (152 samples, 0.12%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (125 samples, 0.10%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (88 samples, 0.07%)core::option::Option<T>::is_some_and (18 samples, 0.01%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (17 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (17 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (17 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (22 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (22 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (17 samples, 0.01%)std::sync::rwlock::RwLock<T>::read (16 samples, 0.01%)std::sys::sync::rwlock::futex::RwLock::read (16 samples, 0.01%)tracing::span::Span::log (26 samples, 0.02%)core::fmt::Arguments::new_v1 (15 samples, 0.01%)tracing_core::span::Record::is_empty (34 samples, 0.03%)tracing_core::field::ValueSet::is_empty (34 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::all (22 samples, 0.02%)tracing_core::field::ValueSet::is_empty::{{closure}} (18 samples, 0.01%)core::option::Option<T>::is_none (16 samples, 0.01%)core::option::Option<T>::is_some (16 samples, 0.01%)tracing::span::Span::record_all (143 samples, 0.11%)unlink_chunk (185 samples, 0.14%)uuid::builder::Builder::with_variant (48 samples, 0.04%)[unknown] (40 samples, 0.03%)uuid::builder::Builder::from_random_bytes (77 samples, 0.06%)uuid::builder::Builder::with_version (29 samples, 0.02%)[unknown] (24 samples, 0.02%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (161 samples, 0.12%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (161 samples, 0.12%)[unknown] (92 samples, 0.07%)rand::rng::Rng::gen (162 samples, 0.12%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (162 samples, 0.12%)rand::rng::Rng::gen (162 samples, 0.12%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (162 samples, 0.12%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (162 samples, 0.12%)[unknown] (18,233 samples, 13.89%)[unknown]uuid::v4::<impl uuid::Uuid>::new_v4 (270 samples, 0.21%)uuid::rng::bytes (190 samples, 0.14%)rand::random (190 samples, 0.14%)__memcpy_avx512_unaligned_erms (69 samples, 0.05%)_int_free (23 samples, 0.02%)_int_malloc (23 samples, 0.02%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)advise_stack_range (31 samples, 0.02%)__GI_madvise (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (29 samples, 0.02%)[unknown] (28 samples, 0.02%)[unknown] (28 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (17 samples, 0.01%)std::sys::pal::unix::futex::futex_wait (31 samples, 0.02%)syscall (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (29 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (17 samples, 0.01%)std::sync::condvar::Condvar::wait_timeout (35 samples, 0.03%)std::sys::sync::condvar::futex::Condvar::wait_timeout (35 samples, 0.03%)std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (35 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (56 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (56 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (56 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock_contended (56 samples, 0.04%)std::sys::pal::unix::futex::futex_wait (56 samples, 0.04%)syscall (56 samples, 0.04%)[unknown] (56 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (53 samples, 0.04%)[unknown] (52 samples, 0.04%)[unknown] (46 samples, 0.04%)[unknown] (39 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (15 samples, 0.01%)[[vdso]] (26 samples, 0.02%)[[vdso]] (263 samples, 0.20%)__ieee754_pow_fma (26 samples, 0.02%)__pow (314 samples, 0.24%)std::f64::<impl f64>::powf (345 samples, 0.26%)__GI___clock_gettime (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::end_processing_scheduled_tasks (416 samples, 0.32%)std::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Timespec::now (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_processing_scheduled_tasks (24 samples, 0.02%)std::time::Instant::now (18 samples, 0.01%)std::sys::pal::unix::time::Instant::now (18 samples, 0.01%)mio::poll::Poll::poll (102 samples, 0.08%)mio::sys::unix::selector::epoll::Selector::select (102 samples, 0.08%)epoll_wait (99 samples, 0.08%)[unknown] (92 samples, 0.07%)[unknown] (91 samples, 0.07%)[unknown] (91 samples, 0.07%)[unknown] (88 samples, 0.07%)[unknown] (85 samples, 0.06%)[unknown] (84 samples, 0.06%)[unknown] (43 samples, 0.03%)[unknown] (29 samples, 0.02%)[unknown] (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (125 samples, 0.10%)tokio::runtime::scheduler::multi_thread::park::Parker::park_timeout (125 samples, 0.10%)tokio::runtime::driver::Driver::park_timeout (125 samples, 0.10%)tokio::runtime::driver::TimeDriver::park_timeout (125 samples, 0.10%)tokio::runtime::time::Driver::park_timeout (125 samples, 0.10%)tokio::runtime::time::Driver::park_internal (116 samples, 0.09%)tokio::runtime::io::driver::Driver::turn (116 samples, 0.09%)tokio::runtime::scheduler::multi_thread::worker::Context::maintenance (148 samples, 0.11%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (111 samples, 0.08%)alloc::sync::Arc<T,A>::inner (111 samples, 0.08%)core::ptr::non_null::NonNull<T>::as_ref (111 samples, 0.08%)core::sync::atomic::AtomicUsize::compare_exchange (16 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (16 samples, 0.01%)core::bool::<impl bool>::then (88 samples, 0.07%)std::sys::pal::unix::futex::futex_wait (13,339 samples, 10.16%)std::sys::pal::..syscall (13,003 samples, 9.90%)syscall[unknown] (12,895 samples, 9.82%)[unknown][unknown] (12,759 samples, 9.72%)[unknown][unknown] (12,313 samples, 9.38%)[unknown][unknown] (12,032 samples, 9.16%)[unknown][unknown] (11,734 samples, 8.94%)[unknown][unknown] (11,209 samples, 8.54%)[unknown][unknown] (10,265 samples, 7.82%)[unknown][unknown] (9,345 samples, 7.12%)[unknown][unknown] (8,623 samples, 6.57%)[unknown][unknown] (7,744 samples, 5.90%)[unknow..[unknown] (5,922 samples, 4.51%)[unkn..[unknown] (4,459 samples, 3.40%)[un..[unknown] (2,808 samples, 2.14%)[..[unknown] (1,275 samples, 0.97%)[unknown] (1,022 samples, 0.78%)[unknown] (738 samples, 0.56%)[unknown] (607 samples, 0.46%)[unknown] (155 samples, 0.12%)core::result::Result<T,E>::is_err (77 samples, 0.06%)core::result::Result<T,E>::is_ok (77 samples, 0.06%)std::sync::condvar::Condvar::wait (13,429 samples, 10.23%)std::sync::cond..std::sys::sync::condvar::futex::Condvar::wait (13,428 samples, 10.23%)std::sys::sync:..std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (13,428 samples, 10.23%)std::sys::sync:..std::sys::sync::mutex::futex::Mutex::lock (89 samples, 0.07%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (13,508 samples, 10.29%)tokio::runtime:..tokio::loom::std::mutex::Mutex<T>::lock (64 samples, 0.05%)std::sync::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (31 samples, 0.02%)core::sync::atomic::AtomicU32::compare_exchange (30 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (30 samples, 0.02%)core::sync::atomic::AtomicUsize::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (38 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Parker::park (34 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::park (34 samples, 0.03%)core::array::<impl core::default::Default for [T: 32]>::default (17 samples, 0.01%)core::ptr::drop_in_place<[core::option::Option<core::task::wake::Waker>: 32]> (19 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_occupied_slot (33 samples, 0.03%)tokio::runtime::time::wheel::level::slot_range (15 samples, 0.01%)core::num::<impl usize>::pow (15 samples, 0.01%)tokio::runtime::time::wheel::level::level_range (17 samples, 0.01%)tokio::runtime::time::wheel::level::slot_range (15 samples, 0.01%)core::num::<impl usize>::pow (15 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_expiration (95 samples, 0.07%)tokio::runtime::time::wheel::level::slot_range (41 samples, 0.03%)core::num::<impl usize>::pow (41 samples, 0.03%)tokio::runtime::time::wheel::Wheel::next_expiration (129 samples, 0.10%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (202 samples, 0.15%)tokio::runtime::time::wheel::Wheel::poll_at (17 samples, 0.01%)tokio::runtime::time::wheel::Wheel::next_expiration (15 samples, 0.01%)<mio::event::events::Iter as core::iter::traits::iterator::Iterator>::next (38 samples, 0.03%)core::option::Option<T>::map (38 samples, 0.03%)core::result::Result<T,E>::map (31 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (31 samples, 0.02%)alloc::vec::Vec<T,A>::set_len (17 samples, 0.01%)[[vdso]] (28 samples, 0.02%)[unknown] (11,031 samples, 8.40%)[unknown][unknown] (10,941 samples, 8.33%)[unknown][unknown] (10,850 samples, 8.26%)[unknown][unknown] (10,691 samples, 8.14%)[unknown][unknown] (10,070 samples, 7.67%)[unknown][unknown] (9,737 samples, 7.42%)[unknown][unknown] (7,659 samples, 5.83%)[unknow..[unknown] (6,530 samples, 4.97%)[unkno..[unknown] (5,633 samples, 4.29%)[unkn..[unknown] (5,055 samples, 3.85%)[unk..[unknown] (4,046 samples, 3.08%)[un..[unknown] (2,911 samples, 2.22%)[..[unknown] (2,115 samples, 1.61%)[unknown] (1,226 samples, 0.93%)[unknown] (455 samples, 0.35%)[unknown] (408 samples, 0.31%)[unknown] (249 samples, 0.19%)[unknown] (202 samples, 0.15%)[unknown] (100 samples, 0.08%)mio::poll::Poll::poll (11,328 samples, 8.63%)mio::poll::P..mio::sys::unix::selector::epoll::Selector::select (11,328 samples, 8.63%)mio::sys::un..epoll_wait (11,229 samples, 8.55%)epoll_wait__GI___pthread_disable_asynccancel (50 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (47 samples, 0.04%)tokio::util::bit::Pack::pack (38 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (25 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (23 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (19 samples, 0.01%)tokio::runtime::io::driver::Driver::turn (11,595 samples, 8.83%)tokio::runti..tokio::runtime::io::scheduled_io::ScheduledIo::wake (175 samples, 0.13%)__GI___clock_gettime (15 samples, 0.01%)std::sys::pal::unix::time::Timespec::now (18 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process (26 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (26 samples, 0.02%)tokio::time::clock::Clock::now (20 samples, 0.02%)tokio::time::clock::now (20 samples, 0.02%)std::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Instant::now (20 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (17 samples, 0.01%)tokio::runtime::time::Driver::park_internal (11,686 samples, 8.90%)tokio::runtim..tokio::runtime::scheduler::multi_thread::park::Inner::park_driver (11,957 samples, 9.11%)tokio::runtim..tokio::runtime::driver::Driver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::driver::TimeDriver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::time::Driver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::scheduler::multi_thread::park::Parker::park (25,502 samples, 19.42%)tokio::runtime::scheduler::mul..tokio::runtime::scheduler::multi_thread::park::Inner::park (25,502 samples, 19.42%)tokio::runtime::scheduler::mul..tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (25,547 samples, 19.46%)tokio::runtime::scheduler::mul..core::result::Result<T,E>::is_err (14 samples, 0.01%)core::result::Result<T,E>::is_ok (14 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (45 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (45 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (84 samples, 0.06%)std::sync::mutex::Mutex<T>::lock (81 samples, 0.06%)std::sys::sync::mutex::futex::Mutex::lock (73 samples, 0.06%)tokio::runtime::scheduler::multi_thread::worker::Core::maintenance (122 samples, 0.09%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (90 samples, 0.07%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (90 samples, 0.07%)core::slice::<impl [T]>::contains (241 samples, 0.18%)<T as core::slice::cmp::SliceContains>::slice_contains (241 samples, 0.18%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (241 samples, 0.18%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (75 samples, 0.06%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (75 samples, 0.06%)core::sync::atomic::AtomicU32::compare_exchange (20 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (283 samples, 0.22%)tokio::loom::std::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (24 samples, 0.02%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (33 samples, 0.03%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (33 samples, 0.03%)core::cmp::impls::<impl core::cmp::PartialOrd for usize>::lt (33 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::unpark_worker_by_id (98 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (401 samples, 0.31%)alloc::vec::Vec<T,A>::push (14 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (15 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (15 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::unlock (14 samples, 0.01%)core::result::Result<T,E>::is_err (15 samples, 0.01%)core::result::Result<T,E>::is_ok (15 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (22 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (22 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (63 samples, 0.05%)std::sync::mutex::Mutex<T>::lock (62 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock (59 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock_contended (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (106 samples, 0.08%)tokio::runtime::scheduler::multi_thread::idle::State::dec_num_unparked (14 samples, 0.01%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (21 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (17 samples, 0.01%)alloc::sync::Arc<T,A>::inner (17 samples, 0.01%)core::ptr::non_null::NonNull<T>::as_ref (17 samples, 0.01%)core::sync::atomic::AtomicU32::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::is_empty (68 samples, 0.05%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::is_empty (51 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::len (33 samples, 0.03%)core::sync::atomic::AtomicU64::load (16 samples, 0.01%)core::sync::atomic::atomic_load (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_if_work_pending (106 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::Context::park (26,672 samples, 20.31%)tokio::runtime::scheduler::multi..tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (272 samples, 0.21%)tokio::runtime::scheduler::multi_thread::worker::Core::has_tasks (33 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::has_tasks (24 samples, 0.02%)tokio::runtime::context::budget (18 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (18 samples, 0.01%)syscall (61 samples, 0.05%)__memcpy_avx512_unaligned_erms (172 samples, 0.13%)__memcpy_avx512_unaligned_erms (224 samples, 0.17%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (228 samples, 0.17%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (228 samples, 0.17%)std::panic::catch_unwind (415 samples, 0.32%)std::panicking::try (415 samples, 0.32%)std::panicking::try::do_call (415 samples, 0.32%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (415 samples, 0.32%)core::ops::function::FnOnce::call_once (415 samples, 0.32%)tokio::runtime::task::harness::Harness<T,S>::complete::{{closure}} (415 samples, 0.32%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (415 samples, 0.32%)tokio::runtime::task::core::Core<T,S>::set_stage (410 samples, 0.31%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (27 samples, 0.02%)core::result::Result<T,E>::is_err (43 samples, 0.03%)core::result::Result<T,E>::is_ok (43 samples, 0.03%)tokio::runtime::task::harness::Harness<T,S>::complete (570 samples, 0.43%)tokio::runtime::task::harness::Harness<T,S>::release (155 samples, 0.12%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (152 samples, 0.12%)tokio::runtime::task::list::OwnedTasks<S>::remove (152 samples, 0.12%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (103 samples, 0.08%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (65 samples, 0.05%)tokio::loom::std::mutex::Mutex<T>::lock (58 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (58 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (54 samples, 0.04%)std::io::stdio::stderr::INSTANCE (17 samples, 0.01%)tokio::runtime::coop::budget (26 samples, 0.02%)tokio::runtime::coop::with_budget (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (35 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (70 samples, 0.05%)__memcpy_avx512_unaligned_erms (42 samples, 0.03%)core::cmp::Ord::min (22 samples, 0.02%)core::cmp::min_by (22 samples, 0.02%)std::io::cursor::Cursor<T>::remaining_slice (27 samples, 0.02%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (30 samples, 0.02%)std::io::cursor::Cursor<T>::remaining_slice (24 samples, 0.02%)core::slice::index::<impl core::ops::index::Index<I> for [T]>::index (19 samples, 0.01%)<core::ops::range::RangeFrom<usize> as core::slice::index::SliceIndex<[T]>>::index (19 samples, 0.01%)<core::ops::range::RangeFrom<usize> as core::slice::index::SliceIndex<[T]>>::get_unchecked (19 samples, 0.01%)<core::ops::range::Range<usize> as core::slice::index::SliceIndex<[T]>>::get_unchecked (19 samples, 0.01%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (44 samples, 0.03%)std::io::impls::<impl std::io::Read for &[u8]>::read_exact (20 samples, 0.02%)byteorder::io::ReadBytesExt::read_i32 (46 samples, 0.04%)core::cmp::Ord::min (14 samples, 0.01%)core::cmp::min_by (14 samples, 0.01%)std::io::cursor::Cursor<T>::remaining_slice (19 samples, 0.01%)byteorder::io::ReadBytesExt::read_i64 (24 samples, 0.02%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (24 samples, 0.02%)aquatic_udp_protocol::request::Request::from_bytes (349 samples, 0.27%)__GI___lll_lock_wake_private (148 samples, 0.11%)[unknown] (139 samples, 0.11%)[unknown] (137 samples, 0.10%)[unknown] (123 samples, 0.09%)[unknown] (111 samples, 0.08%)[unknown] (98 samples, 0.07%)[unknown] (42 samples, 0.03%)[unknown] (30 samples, 0.02%)__GI___lll_lock_wait_private (553 samples, 0.42%)futex_wait (541 samples, 0.41%)[unknown] (536 samples, 0.41%)[unknown] (531 samples, 0.40%)[unknown] (524 samples, 0.40%)[unknown] (515 samples, 0.39%)[unknown] (498 samples, 0.38%)[unknown] (470 samples, 0.36%)[unknown] (435 samples, 0.33%)[unknown] (350 samples, 0.27%)[unknown] (327 samples, 0.25%)[unknown] (290 samples, 0.22%)[unknown] (222 samples, 0.17%)[unknown] (160 samples, 0.12%)[unknown] (104 samples, 0.08%)[unknown] (33 samples, 0.03%)[unknown] (25 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (703 samples, 0.54%)__GI___libc_free (866 samples, 0.66%)tracing::span::Span::record_all (30 samples, 0.02%)unlink_chunk (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::UdpRequest> (899 samples, 0.68%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (899 samples, 0.68%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (899 samples, 0.68%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (899 samples, 0.68%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (899 samples, 0.68%)alloc::alloc::dealloc (899 samples, 0.68%)__rdl_dealloc (899 samples, 0.68%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (899 samples, 0.68%)core::result::Result<T,E>::expect (91 samples, 0.07%)core::result::Result<T,E>::map_err (28 samples, 0.02%)[[vdso]] (28 samples, 0.02%)__GI___clock_gettime (47 samples, 0.04%)std::time::Instant::elapsed (67 samples, 0.05%)std::time::Instant::now (54 samples, 0.04%)std::sys::pal::unix::time::Instant::now (54 samples, 0.04%)std::sys::pal::unix::time::Timespec::now (53 samples, 0.04%)std::sys::pal::unix::cvt (23 samples, 0.02%)__GI_getsockname (3,792 samples, 2.89%)__..[unknown] (3,714 samples, 2.83%)[u..[unknown] (3,661 samples, 2.79%)[u..[unknown] (3,557 samples, 2.71%)[u..[unknown] (3,416 samples, 2.60%)[u..[unknown] (2,695 samples, 2.05%)[..[unknown] (2,063 samples, 1.57%)[unknown] (891 samples, 0.68%)[unknown] (270 samples, 0.21%)[unknown] (99 samples, 0.08%)[unknown] (94 samples, 0.07%)[unknown] (84 samples, 0.06%)[unknown] (77 samples, 0.06%)[unknown] (25 samples, 0.02%)[unknown] (16 samples, 0.01%)std::sys_common::net::TcpListener::socket_addr::{{closure}} (3,800 samples, 2.89%)st..tokio::net::udp::UdpSocket::local_addr (3,838 samples, 2.92%)to..mio::net::udp::UdpSocket::local_addr (3,838 samples, 2.92%)mi..std::net::tcp::TcpListener::local_addr (3,838 samples, 2.92%)st..std::sys_common::net::TcpListener::socket_addr (3,838 samples, 2.92%)st..std::sys_common::net::sockname (3,835 samples, 2.92%)st..[[vdso]] (60 samples, 0.05%)rand_chacha::guts::ChaCha::pos64 (168 samples, 0.13%)<ppv_lite86::soft::x2<W,G> as core::ops::arith::AddAssign>::add_assign (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::AddAssign>::add_assign (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::Add>::add (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_add_epi32 (26 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_shuffle_epi8 (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_or_si256 (29 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (31 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (31 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right24 (18 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right24 (18 samples, 0.01%)core::core_arch::x86::avx2::_mm256_shuffle_epi8 (18 samples, 0.01%)rand_chacha::guts::round (118 samples, 0.09%)rand_chacha::guts::refill_wide::impl_avx2 (312 samples, 0.24%)rand_chacha::guts::refill_wide::fn_impl (312 samples, 0.24%)rand_chacha::guts::refill_wide_impl (312 samples, 0.24%)<rand_chacha::chacha::ChaCha12Core as rand_core::block::BlockRngCore>::generate (384 samples, 0.29%)rand_chacha::guts::ChaCha::refill4 (384 samples, 0.29%)rand::rng::Rng::gen (432 samples, 0.33%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (432 samples, 0.33%)rand::rng::Rng::gen (432 samples, 0.33%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (432 samples, 0.33%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (432 samples, 0.33%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (432 samples, 0.33%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (432 samples, 0.33%)rand_core::block::BlockRng<R>::generate_and_set (392 samples, 0.30%)<rand::rngs::adapter::reseeding::ReseedingCore<R,Rsdr> as rand_core::block::BlockRngCore>::generate (392 samples, 0.30%)torrust_tracker::servers::udp::handlers::RequestId::make (440 samples, 0.34%)uuid::v4::<impl uuid::Uuid>::new_v4 (436 samples, 0.33%)uuid::rng::bytes (435 samples, 0.33%)rand::random (435 samples, 0.33%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_peers_for_client (34 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_peers_for_client (22 samples, 0.02%)core::iter::traits::iterator::Iterator::collect (16 samples, 0.01%)<alloc::vec::Vec<T> as core::iter::traits::collect::FromIterator<T>>::from_iter (16 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (16 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter_nested::SpecFromIterNested<T,I>>::from_iter (16 samples, 0.01%)<core::iter::adapters::cloned::Cloned<I> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)<core::iter::adapters::take::Take<I> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::next (15 samples, 0.01%)core::iter::traits::iterator::Iterator::find (15 samples, 0.01%)core::iter::traits::iterator::Iterator::try_fold (15 samples, 0.01%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (31 samples, 0.02%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (45 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (45 samples, 0.03%)core::slice::iter::Iter<T>::post_inc_start (14 samples, 0.01%)core::ptr::non_null::NonNull<T>::add (14 samples, 0.01%)__memcmp_evex_movbe (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (26 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (165 samples, 0.13%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (165 samples, 0.13%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (165 samples, 0.13%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (165 samples, 0.13%)<u8 as core::slice::cmp::SliceOrd>::compare (165 samples, 0.13%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (339 samples, 0.26%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (308 samples, 0.23%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (308 samples, 0.23%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (342 samples, 0.26%)std::sys::sync::rwlock::futex::RwLock::spin_read (25 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_until (25 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read_contended (28 samples, 0.02%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (436 samples, 0.33%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (397 samples, 0.30%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (29 samples, 0.02%)std::sync::rwlock::RwLock<T>::read (29 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read (29 samples, 0.02%)__memcmp_evex_movbe (31 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (52 samples, 0.04%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (52 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (52 samples, 0.04%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (52 samples, 0.04%)<u8 as core::slice::cmp::SliceOrd>::compare (52 samples, 0.04%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (103 samples, 0.08%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (102 samples, 0.08%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (96 samples, 0.07%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (96 samples, 0.07%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (72 samples, 0.05%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (104 samples, 0.08%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (104 samples, 0.08%)core::slice::iter::Iter<T>::post_inc_start (32 samples, 0.02%)core::ptr::non_null::NonNull<T>::add (32 samples, 0.02%)__memcmp_evex_movbe (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (81 samples, 0.06%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (271 samples, 0.21%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (271 samples, 0.21%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (271 samples, 0.21%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (271 samples, 0.21%)<u8 as core::slice::cmp::SliceOrd>::compare (271 samples, 0.21%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (610 samples, 0.46%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (566 samples, 0.43%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (566 samples, 0.43%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Immut,K,V,Type>::keys (18 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (616 samples, 0.47%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::KV>::split (15 samples, 0.01%)alloc::collections::btree::map::entry::Entry<K,V,A>::or_insert (46 samples, 0.04%)alloc::collections::btree::map::entry::VacantEntry<K,V,A>::insert (45 samples, 0.03%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>::insert_recursing (40 samples, 0.03%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>::insert (27 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (29 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (20 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (120 samples, 0.09%)alloc::collections::btree::map::entry::VacantEntry<K,V,A>::insert (118 samples, 0.09%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Owned,K,V,alloc::collections::btree::node::marker::Leaf>::new_leaf (118 samples, 0.09%)alloc::collections::btree::node::LeafNode<K,V>::new (118 samples, 0.09%)alloc::boxed::Box<T,A>::new_uninit_in (118 samples, 0.09%)alloc::boxed::Box<T,A>::try_new_uninit_in (118 samples, 0.09%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (118 samples, 0.09%)alloc::alloc::Global::alloc_impl (118 samples, 0.09%)alloc::alloc::alloc (118 samples, 0.09%)__rdl_alloc (118 samples, 0.09%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (118 samples, 0.09%)__GI___libc_malloc (118 samples, 0.09%)_int_malloc (107 samples, 0.08%)_int_malloc (28 samples, 0.02%)__GI___libc_malloc (32 samples, 0.02%)__rdl_alloc (36 samples, 0.03%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (36 samples, 0.03%)alloc::sync::Arc<T>::new (42 samples, 0.03%)alloc::boxed::Box<T>::new (42 samples, 0.03%)alloc::alloc::exchange_malloc (39 samples, 0.03%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (39 samples, 0.03%)alloc::alloc::Global::alloc_impl (39 samples, 0.03%)alloc::alloc::alloc (39 samples, 0.03%)core::mem::drop (15 samples, 0.01%)core::ptr::drop_in_place<core::option::Option<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (15 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (15 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (15 samples, 0.01%)__GI___libc_free (39 samples, 0.03%)_int_free (37 samples, 0.03%)get_max_fast (16 samples, 0.01%)core::option::Option<T>::is_some_and (50 samples, 0.04%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (50 samples, 0.04%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (50 samples, 0.04%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (50 samples, 0.04%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (290 samples, 0.22%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (284 samples, 0.22%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (255 samples, 0.19%)std::sys::sync::rwlock::futex::RwLock::spin_read (16 samples, 0.01%)std::sys::sync::rwlock::futex::RwLock::spin_until (16 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (21 samples, 0.02%)std::sync::rwlock::RwLock<T>::read (21 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read (21 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read_contended (21 samples, 0.02%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (1,147 samples, 0.87%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (1,144 samples, 0.87%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents_mut (32 samples, 0.02%)std::sync::rwlock::RwLock<T>::write (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::write (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::write_contended (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_write (28 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_until (28 samples, 0.02%)torrust_tracker::core::Tracker::announce::{{closure}} (1,597 samples, 1.22%)<core::net::socket_addr::SocketAddrV4 as core::hash::Hash>::hash (14 samples, 0.01%)<core::net::ip_addr::Ipv4Addr as core::hash::Hash>::hash (14 samples, 0.01%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (29 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (24 samples, 0.02%)<core::time::Nanoseconds as core::hash::Hash>::hash (25 samples, 0.02%)core::hash::impls::<impl core::hash::Hash for u32>::hash (25 samples, 0.02%)core::hash::Hasher::write_u32 (25 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (25 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (25 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (36 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (37 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (37 samples, 0.03%)<core::time::Duration as core::hash::Hash>::hash (64 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for u64>::hash (39 samples, 0.03%)core::hash::Hasher::write_u64 (39 samples, 0.03%)<torrust_tracker_clock::time_extent::TimeExtent as core::hash::Hash>::hash (122 samples, 0.09%)core::hash::impls::<impl core::hash::Hash for u64>::hash (58 samples, 0.04%)core::hash::Hasher::write_u64 (58 samples, 0.04%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (58 samples, 0.04%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (58 samples, 0.04%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (57 samples, 0.04%)core::hash::sip::u8to64_le (23 samples, 0.02%)core::hash::Hasher::write_length_prefix (27 samples, 0.02%)core::hash::Hasher::write_usize (27 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (16 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (246 samples, 0.19%)core::array::<impl core::hash::Hash for [T: N]>::hash (93 samples, 0.07%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (93 samples, 0.07%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (66 samples, 0.05%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (62 samples, 0.05%)core::hash::sip::u8to64_le (17 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::check (285 samples, 0.22%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (36 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (36 samples, 0.03%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (24 samples, 0.02%)std::time::SystemTime::now (19 samples, 0.01%)std::sys::pal::unix::time::SystemTime::now (19 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (1,954 samples, 1.49%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (24 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (18 samples, 0.01%)<core::time::Nanoseconds as core::hash::Hash>::hash (20 samples, 0.02%)core::hash::impls::<impl core::hash::Hash for u32>::hash (20 samples, 0.02%)core::hash::Hasher::write_u32 (20 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (20 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (20 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (44 samples, 0.03%)<core::time::Duration as core::hash::Hash>::hash (65 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for u64>::hash (45 samples, 0.03%)core::hash::Hasher::write_u64 (45 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (45 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (45 samples, 0.03%)<torrust_tracker_clock::time_extent::TimeExtent as core::hash::Hash>::hash (105 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for u64>::hash (40 samples, 0.03%)core::hash::Hasher::write_u64 (40 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (40 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (40 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (39 samples, 0.03%)core::hash::Hasher::write_length_prefix (34 samples, 0.03%)core::hash::Hasher::write_usize (34 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (34 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (34 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (33 samples, 0.03%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (231 samples, 0.18%)core::array::<impl core::hash::Hash for [T: N]>::hash (100 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (100 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (66 samples, 0.05%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (61 samples, 0.05%)core::hash::sip::u8to64_le (16 samples, 0.01%)_int_free (16 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_connect::{{closure}} (270 samples, 0.21%)torrust_tracker::servers::udp::connection_cookie::make (268 samples, 0.20%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (36 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (35 samples, 0.03%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (31 samples, 0.02%)std::time::SystemTime::now (26 samples, 0.02%)std::sys::pal::unix::time::SystemTime::now (26 samples, 0.02%)torrust_tracker::core::ScrapeData::add_file (19 samples, 0.01%)std::collections::hash::map::HashMap<K,V,S>::insert (19 samples, 0.01%)hashbrown::map::HashMap<K,V,S,A>::insert (19 samples, 0.01%)hashbrown::raw::RawTable<T,A>::find_or_find_insert_slot (16 samples, 0.01%)hashbrown::raw::RawTable<T,A>::reserve (16 samples, 0.01%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (17 samples, 0.01%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (17 samples, 0.01%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (17 samples, 0.01%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (17 samples, 0.01%)<u8 as core::slice::cmp::SliceOrd>::compare (17 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (53 samples, 0.04%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (53 samples, 0.04%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (2,336 samples, 1.78%)t..torrust_tracker::servers::udp::handlers::handle_scrape::{{closure}} (101 samples, 0.08%)torrust_tracker::core::Tracker::scrape::{{closure}} (90 samples, 0.07%)torrust_tracker::core::Tracker::get_swarm_metadata (68 samples, 0.05%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (64 samples, 0.05%)alloc::raw_vec::finish_grow (19 samples, 0.01%)alloc::vec::Vec<T,A>::reserve (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::grow_amortized (21 samples, 0.02%)<alloc::string::String as core::fmt::Write>::write_str (23 samples, 0.02%)alloc::string::String::push_str (23 samples, 0.02%)alloc::vec::Vec<T,A>::extend_from_slice (23 samples, 0.02%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (23 samples, 0.02%)alloc::vec::Vec<T,A>::append_elements (23 samples, 0.02%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (85 samples, 0.06%)core::fmt::num::imp::fmt_u64 (78 samples, 0.06%)<alloc::string::String as core::fmt::Write>::write_str (15 samples, 0.01%)alloc::string::String::push_str (15 samples, 0.01%)alloc::vec::Vec<T,A>::extend_from_slice (15 samples, 0.01%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (15 samples, 0.01%)alloc::vec::Vec<T,A>::append_elements (15 samples, 0.01%)core::fmt::num::imp::<impl core::fmt::Display for i64>::fmt (37 samples, 0.03%)core::fmt::num::imp::fmt_u64 (36 samples, 0.03%)<T as alloc::string::ToString>::to_string (141 samples, 0.11%)core::option::Option<T>::expect (34 samples, 0.03%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (28 samples, 0.02%)alloc::alloc::dealloc (28 samples, 0.02%)__rdl_dealloc (28 samples, 0.02%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (28 samples, 0.02%)core::ptr::drop_in_place<alloc::string::String> (55 samples, 0.04%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (55 samples, 0.04%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (55 samples, 0.04%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (55 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::current_memory (20 samples, 0.02%)torrust_tracker::servers::udp::logging::map_action_name (16 samples, 0.01%)binascii::bin2hex (51 samples, 0.04%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (16 samples, 0.01%)core::fmt::write (25 samples, 0.02%)core::fmt::rt::Argument::fmt (15 samples, 0.01%)core::fmt::Formatter::write_fmt (87 samples, 0.07%)core::str::converts::from_utf8 (43 samples, 0.03%)core::str::validations::run_utf8_validation (37 samples, 0.03%)torrust_tracker_primitives::info_hash::InfoHash::to_hex_string (161 samples, 0.12%)<T as alloc::string::ToString>::to_string (161 samples, 0.12%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (156 samples, 0.12%)torrust_tracker::servers::udp::logging::log_request (479 samples, 0.36%)[[vdso]] (51 samples, 0.04%)alloc::raw_vec::finish_grow (56 samples, 0.04%)alloc::vec::Vec<T,A>::reserve (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::reserve (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::grow_amortized (64 samples, 0.05%)<alloc::string::String as core::fmt::Write>::write_str (65 samples, 0.05%)alloc::string::String::push_str (65 samples, 0.05%)alloc::vec::Vec<T,A>::extend_from_slice (65 samples, 0.05%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (65 samples, 0.05%)alloc::vec::Vec<T,A>::append_elements (65 samples, 0.05%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (114 samples, 0.09%)core::fmt::num::imp::fmt_u64 (110 samples, 0.08%)<T as alloc::string::ToString>::to_string (132 samples, 0.10%)core::option::Option<T>::expect (20 samples, 0.02%)core::ptr::drop_in_place<alloc::string::String> (22 samples, 0.02%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (22 samples, 0.02%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (22 samples, 0.02%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (22 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (8,883 samples, 6.77%)torrust_t..torrust_tracker::servers::udp::logging::log_response (238 samples, 0.18%)__GI___lll_lock_wait_private (14 samples, 0.01%)futex_wait (14 samples, 0.01%)__GI___lll_lock_wake_private (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (17 samples, 0.01%)_int_malloc (191 samples, 0.15%)__libc_calloc (238 samples, 0.18%)__memcpy_avx512_unaligned_erms (34 samples, 0.03%)alloc::vec::from_elem (316 samples, 0.24%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (316 samples, 0.24%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (316 samples, 0.24%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (316 samples, 0.24%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (312 samples, 0.24%)alloc::alloc::Global::alloc_impl (312 samples, 0.24%)alloc::alloc::alloc_zeroed (312 samples, 0.24%)__rdl_alloc_zeroed (312 samples, 0.24%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (312 samples, 0.24%)byteorder::ByteOrder::write_i32 (18 samples, 0.01%)<byteorder::BigEndian as byteorder::ByteOrder>::write_u32 (18 samples, 0.01%)core::num::<impl u32>::to_be_bytes (18 samples, 0.01%)core::num::<impl u32>::to_be (18 samples, 0.01%)core::num::<impl u32>::swap_bytes (18 samples, 0.01%)byteorder::io::WriteBytesExt::write_i32 (89 samples, 0.07%)std::io::Write::write_all (71 samples, 0.05%)<std::io::cursor::Cursor<alloc::vec::Vec<u8,A>> as std::io::Write>::write (71 samples, 0.05%)std::io::cursor::vec_write (71 samples, 0.05%)std::io::cursor::vec_write_unchecked (51 samples, 0.04%)core::ptr::mut_ptr::<impl *mut T>::copy_from (51 samples, 0.04%)core::intrinsics::copy (51 samples, 0.04%)aquatic_udp_protocol::response::Response::write (227 samples, 0.17%)byteorder::io::WriteBytesExt::write_i64 (28 samples, 0.02%)std::io::Write::write_all (21 samples, 0.02%)<std::io::cursor::Cursor<alloc::vec::Vec<u8,A>> as std::io::Write>::write (21 samples, 0.02%)std::io::cursor::vec_write (21 samples, 0.02%)std::io::cursor::vec_write_unchecked (21 samples, 0.02%)core::ptr::mut_ptr::<impl *mut T>::copy_from (21 samples, 0.02%)core::intrinsics::copy (21 samples, 0.02%)__GI___lll_lock_wake_private (17 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (14 samples, 0.01%)__GI___lll_lock_wait_private (16 samples, 0.01%)futex_wait (15 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (136 samples, 0.10%)__GI___libc_free (206 samples, 0.16%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (211 samples, 0.16%)alloc::alloc::dealloc (211 samples, 0.16%)__rdl_dealloc (211 samples, 0.16%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (211 samples, 0.16%)core::ptr::drop_in_place<std::io::cursor::Cursor<alloc::vec::Vec<u8>>> (224 samples, 0.17%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (224 samples, 0.17%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (224 samples, 0.17%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (224 samples, 0.17%)std::io::cursor::Cursor<T>::new (56 samples, 0.04%)tokio::io::ready::Ready::intersection (23 samples, 0.02%)tokio::io::ready::Ready::from_interest (23 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (83 samples, 0.06%)[unknown] (32,674 samples, 24.88%)[unknown][unknown] (32,402 samples, 24.68%)[unknown][unknown] (32,272 samples, 24.58%)[unknown][unknown] (32,215 samples, 24.54%)[unknown][unknown] (31,174 samples, 23.74%)[unknown][unknown] (30,794 samples, 23.45%)[unknown][unknown] (30,036 samples, 22.88%)[unknown][unknown] (28,639 samples, 21.81%)[unknown][unknown] (27,908 samples, 21.25%)[unknown][unknown] (26,013 samples, 19.81%)[unknown][unknown] (23,181 samples, 17.65%)[unknown][unknown] (19,559 samples, 14.90%)[unknown][unknown] (18,052 samples, 13.75%)[unknown][unknown] (15,794 samples, 12.03%)[unknown][unknown] (14,740 samples, 11.23%)[unknown][unknown] (12,486 samples, 9.51%)[unknown][unknown] (11,317 samples, 8.62%)[unknown][unknown] (10,725 samples, 8.17%)[unknown][unknown] (10,017 samples, 7.63%)[unknown][unknown] (9,713 samples, 7.40%)[unknown][unknown] (8,432 samples, 6.42%)[unknown][unknown] (8,062 samples, 6.14%)[unknown][unknown] (6,973 samples, 5.31%)[unknow..[unknown] (5,328 samples, 4.06%)[unk..[unknown] (4,352 samples, 3.31%)[un..[unknown] (3,786 samples, 2.88%)[u..[unknown] (3,659 samples, 2.79%)[u..[unknown] (3,276 samples, 2.50%)[u..[unknown] (2,417 samples, 1.84%)[..[unknown] (2,115 samples, 1.61%)[unknown] (1,610 samples, 1.23%)[unknown] (422 samples, 0.32%)[unknown] (84 samples, 0.06%)[unknown] (69 samples, 0.05%)__GI___pthread_disable_asynccancel (67 samples, 0.05%)__libc_sendto (32,896 samples, 25.05%)__libc_sendtotokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (32,981 samples, 25.12%)tokio::net::udp::UdpSocket::send_to_addr..mio::net::udp::UdpSocket::send_to (32,981 samples, 25.12%)mio::net::udp::UdpSocket::send_tomio::io_source::IoSource<T>::do_io (32,981 samples, 25.12%)mio::io_source::IoSource<T>::do_iomio::sys::unix::stateless_io_source::IoSourceState::do_io (32,981 samples, 25.12%)mio::sys::unix::stateless_io_source::IoS..mio::net::udp::UdpSocket::send_to::{{closure}} (32,981 samples, 25.12%)mio::net::udp::UdpSocket::send_to::{{clo..std::net::udp::UdpSocket::send_to (32,981 samples, 25.12%)std::net::udp::UdpSocket::send_tostd::sys_common::net::UdpSocket::send_to (32,981 samples, 25.12%)std::sys_common::net::UdpSocket::send_tostd::sys::pal::unix::cvt (85 samples, 0.06%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (44,349 samples, 33.78%)torrust_tracker::servers::udp::server::Udp::process_req..torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (43,412 samples, 33.06%)torrust_tracker::servers::udp::server::Udp::process_va..torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (34,320 samples, 26.14%)torrust_tracker::servers::udp::server::Udp..torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (33,360 samples, 25.41%)torrust_tracker::servers::udp::server::Ud..tokio::net::udp::UdpSocket::send_to::{{closure}} (33,227 samples, 25.31%)tokio::net::udp::UdpSocket::send_to::{{c..tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (33,142 samples, 25.24%)tokio::net::udp::UdpSocket::send_to_addr..tokio::runtime::io::registration::Registration::async_io::{{closure}} (33,115 samples, 25.22%)tokio::runtime::io::registration::Regist..tokio::runtime::io::registration::Registration::readiness::{{closure}} (28 samples, 0.02%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (18 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (15 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (14 samples, 0.01%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (15 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (15 samples, 0.01%)core::sync::atomic::atomic_add (15 samples, 0.01%)__GI___lll_lock_wait_private (16 samples, 0.01%)futex_wait (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (135 samples, 0.10%)__GI___libc_free (147 samples, 0.11%)syscall (22 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Core<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>> (15 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::dealloc (24 samples, 0.02%)core::mem::drop (24 samples, 0.02%)core::ptr::drop_in_place<alloc::boxed::Box<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (24 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>> (24 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::abort::AbortHandle> (262 samples, 0.20%)<tokio::runtime::task::abort::AbortHandle as core::ops::drop::Drop>::drop (262 samples, 0.20%)tokio::runtime::task::raw::RawTask::drop_abort_handle (256 samples, 0.19%)tokio::runtime::task::raw::drop_abort_handle (59 samples, 0.04%)tokio::runtime::task::harness::Harness<T,S>::drop_reference (50 samples, 0.04%)tokio::runtime::task::state::State::ref_dec (50 samples, 0.04%)tokio::runtime::task::raw::RawTask::drop_join_handle_slow (16 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::join::JoinHandle<()>> (47 samples, 0.04%)<tokio::runtime::task::join::JoinHandle<T> as core::ops::drop::Drop>::drop (47 samples, 0.04%)tokio::runtime::task::state::State::drop_join_handle_fast (19 samples, 0.01%)core::sync::atomic::AtomicUsize::compare_exchange_weak (19 samples, 0.01%)core::sync::atomic::atomic_compare_exchange_weak (19 samples, 0.01%)ringbuf::ring_buffer::base::RbBase::is_full (14 samples, 0.01%)<ringbuf::ring_buffer::shared::SharedRb<T,C> as ringbuf::ring_buffer::base::RbBase<T>>::head (14 samples, 0.01%)core::sync::atomic::AtomicUsize::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)ringbuf::consumer::Consumer<T,R>::advance (29 samples, 0.02%)ringbuf::ring_buffer::base::RbRead::advance_head (29 samples, 0.02%)ringbuf::ring_buffer::rb::Rb::pop (50 samples, 0.04%)ringbuf::consumer::Consumer<T,R>::pop (50 samples, 0.04%)ringbuf::producer::Producer<T,R>::advance (23 samples, 0.02%)ringbuf::ring_buffer::base::RbWrite::advance_tail (23 samples, 0.02%)core::num::nonzero::<impl core::ops::arith::Rem<core::num::nonzero::NonZero<usize>> for usize>::rem (19 samples, 0.01%)ringbuf::ring_buffer::rb::Rb::push_overwrite (107 samples, 0.08%)ringbuf::ring_buffer::rb::Rb::push (43 samples, 0.03%)ringbuf::producer::Producer<T,R>::push (43 samples, 0.03%)tokio::runtime::task::abort::AbortHandle::is_finished (84 samples, 0.06%)tokio::runtime::task::state::Snapshot::is_complete (84 samples, 0.06%)tokio::runtime::task::join::JoinHandle<T>::abort_handle (17 samples, 0.01%)tokio::runtime::task::raw::RawTask::ref_inc (17 samples, 0.01%)tokio::runtime::task::state::State::ref_inc (17 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (14 samples, 0.01%)core::sync::atomic::atomic_add (14 samples, 0.01%)__GI___lll_lock_wake_private (22 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)malloc_consolidate (95 samples, 0.07%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (76 samples, 0.06%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (31 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (26 samples, 0.02%)_int_malloc (282 samples, 0.21%)__GI___libc_malloc (323 samples, 0.25%)alloc::vec::Vec<T>::with_capacity (326 samples, 0.25%)alloc::vec::Vec<T,A>::with_capacity_in (326 samples, 0.25%)alloc::raw_vec::RawVec<T,A>::with_capacity_in (324 samples, 0.25%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (324 samples, 0.25%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (324 samples, 0.25%)alloc::alloc::Global::alloc_impl (324 samples, 0.25%)alloc::alloc::alloc (324 samples, 0.25%)__rdl_alloc (324 samples, 0.25%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (324 samples, 0.25%)tokio::io::ready::Ready::intersection (24 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (199 samples, 0.15%)tokio::util::bit::Pack::unpack (16 samples, 0.01%)tokio::util::bit::unpack (16 samples, 0.01%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (19 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (17 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (16 samples, 0.01%)tokio::net::udp::UdpSocket::readable::{{closure}} (222 samples, 0.17%)tokio::net::udp::UdpSocket::ready::{{closure}} (222 samples, 0.17%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (50 samples, 0.04%)std::io::error::repr_bitpacked::Repr::data (14 samples, 0.01%)std::io::error::repr_bitpacked::decode_repr (14 samples, 0.01%)std::io::error::Error::kind (16 samples, 0.01%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (14 samples, 0.01%)[unknown] (8,756 samples, 6.67%)[unknown][unknown] (8,685 samples, 6.61%)[unknown][unknown] (8,574 samples, 6.53%)[unknown][unknown] (8,415 samples, 6.41%)[unknown][unknown] (7,686 samples, 5.85%)[unknow..[unknown] (7,239 samples, 5.51%)[unknow..[unknown] (6,566 samples, 5.00%)[unkno..[unknown] (5,304 samples, 4.04%)[unk..[unknown] (4,008 samples, 3.05%)[un..[unknown] (3,571 samples, 2.72%)[u..[unknown] (2,375 samples, 1.81%)[..[unknown] (1,844 samples, 1.40%)[unknown] (1,030 samples, 0.78%)[unknown] (344 samples, 0.26%)[unknown] (113 samples, 0.09%)__libc_recvfrom (8,903 samples, 6.78%)__libc_re..__GI___pthread_disable_asynccancel (22 samples, 0.02%)std::sys::pal::unix::cvt (20 samples, 0.02%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}}::{{closure}} (9,005 samples, 6.86%)tokio::ne..mio::net::udp::UdpSocket::recv_from (8,964 samples, 6.83%)mio::net:..mio::io_source::IoSource<T>::do_io (8,964 samples, 6.83%)mio::io_s..mio::sys::unix::stateless_io_source::IoSourceState::do_io (8,964 samples, 6.83%)mio::sys:..mio::net::udp::UdpSocket::recv_from::{{closure}} (8,964 samples, 6.83%)mio::net:..std::net::udp::UdpSocket::recv_from (8,964 samples, 6.83%)std::net:..std::sys_common::net::UdpSocket::recv_from (8,964 samples, 6.83%)std::sys_..std::sys::pal::unix::net::Socket::recv_from (8,964 samples, 6.83%)std::sys:..std::sys::pal::unix::net::Socket::recv_from_with_flags (8,964 samples, 6.83%)std::sys:..std::sys_common::net::sockaddr_to_addr (23 samples, 0.02%)tokio::runtime::io::registration::Registration::clear_readiness (18 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::clear_readiness (18 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (32 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (9,967 samples, 7.59%)torrust_tr..tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (9,291 samples, 7.08%)tokio::ne..tokio::runtime::io::registration::Registration::async_io::{{closure}} (9,287 samples, 7.07%)tokio::ru..tokio::runtime::io::registration::Registration::readiness::{{closure}} (45 samples, 0.03%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (41 samples, 0.03%)__memcpy_avx512_unaligned_erms (424 samples, 0.32%)__memcpy_avx512_unaligned_erms (493 samples, 0.38%)__memcpy_avx512_unaligned_erms (298 samples, 0.23%)syscall (1,105 samples, 0.84%)[unknown] (1,095 samples, 0.83%)[unknown] (1,091 samples, 0.83%)[unknown] (1,049 samples, 0.80%)[unknown] (998 samples, 0.76%)[unknown] (907 samples, 0.69%)[unknown] (710 samples, 0.54%)[unknown] (635 samples, 0.48%)[unknown] (538 samples, 0.41%)[unknown] (358 samples, 0.27%)[unknown] (256 samples, 0.19%)[unknown] (153 samples, 0.12%)[unknown] (96 samples, 0.07%)[unknown] (81 samples, 0.06%)tokio::runtime::context::with_scheduler (36 samples, 0.03%)std::thread::local::LocalKey<T>::try_with (31 samples, 0.02%)tokio::runtime::context::with_scheduler::{{closure}} (27 samples, 0.02%)tokio::runtime::context::scoped::Scoped<T>::with (27 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (25 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (15 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (340 samples, 0.26%)core::sync::atomic::atomic_add (340 samples, 0.26%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (354 samples, 0.27%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (367 samples, 0.28%)[unknown] (95 samples, 0.07%)[unknown] (93 samples, 0.07%)[unknown] (92 samples, 0.07%)[unknown] (90 samples, 0.07%)[unknown] (82 samples, 0.06%)[unknown] (73 samples, 0.06%)[unknown] (63 samples, 0.05%)[unknown] (44 samples, 0.03%)[unknown] (40 samples, 0.03%)[unknown] (35 samples, 0.03%)[unknown] (30 samples, 0.02%)[unknown] (22 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (17 samples, 0.01%)tokio::runtime::driver::Handle::unpark (99 samples, 0.08%)tokio::runtime::driver::IoHandle::unpark (99 samples, 0.08%)tokio::runtime::io::driver::Handle::unpark (99 samples, 0.08%)mio::waker::Waker::wake (99 samples, 0.08%)mio::sys::unix::waker::fdbased::Waker::wake (99 samples, 0.08%)mio::sys::unix::waker::eventfd::WakerInternal::wake (99 samples, 0.08%)<&std::fs::File as std::io::Write>::write (99 samples, 0.08%)std::sys::pal::unix::fs::File::write (99 samples, 0.08%)std::sys::pal::unix::fd::FileDesc::write (99 samples, 0.08%)__GI___libc_write (99 samples, 0.08%)__GI___libc_write (99 samples, 0.08%)tokio::runtime::context::with_scheduler (1,615 samples, 1.23%)std::thread::local::LocalKey<T>::try_with (1,613 samples, 1.23%)tokio::runtime::context::with_scheduler::{{closure}} (1,612 samples, 1.23%)tokio::runtime::context::scoped::Scoped<T>::with (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (1,609 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (1,609 samples, 1.23%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (101 samples, 0.08%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (101 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_option_task_without_yield (1,647 samples, 1.25%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task (1,646 samples, 1.25%)tokio::runtime::scheduler::multi_thread::worker::with_current (1,646 samples, 1.25%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (23 samples, 0.02%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::push_front (18 samples, 0.01%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (104 samples, 0.08%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (60 samples, 0.05%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (57 samples, 0.04%)tokio::loom::std::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (49 samples, 0.04%)core::sync::atomic::AtomicU32::compare_exchange (38 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (38 samples, 0.03%)__memcpy_avx512_unaligned_erms (162 samples, 0.12%)__memcpy_avx512_unaligned_erms (34 samples, 0.03%)__GI___lll_lock_wake_private (127 samples, 0.10%)[unknown] (125 samples, 0.10%)[unknown] (124 samples, 0.09%)[unknown] (119 samples, 0.09%)[unknown] (110 samples, 0.08%)[unknown] (106 samples, 0.08%)[unknown] (87 samples, 0.07%)[unknown] (82 samples, 0.06%)[unknown] (51 samples, 0.04%)[unknown] (27 samples, 0.02%)[unknown] (19 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (77 samples, 0.06%)[unknown] (1,207 samples, 0.92%)[unknown] (1,146 samples, 0.87%)[unknown] (1,126 samples, 0.86%)[unknown] (1,091 samples, 0.83%)[unknown] (1,046 samples, 0.80%)[unknown] (962 samples, 0.73%)[unknown] (914 samples, 0.70%)[unknown] (848 samples, 0.65%)[unknown] (774 samples, 0.59%)[unknown] (580 samples, 0.44%)[unknown] (456 samples, 0.35%)[unknown] (305 samples, 0.23%)[unknown] (85 samples, 0.06%)__GI_mprotect (2,474 samples, 1.88%)_..[unknown] (2,457 samples, 1.87%)[..[unknown] (2,440 samples, 1.86%)[..[unknown] (2,436 samples, 1.86%)[..[unknown] (2,435 samples, 1.85%)[..[unknown] (2,360 samples, 1.80%)[..[unknown] (2,203 samples, 1.68%)[unknown] (1,995 samples, 1.52%)[unknown] (1,709 samples, 1.30%)[unknown] (1,524 samples, 1.16%)[unknown] (1,193 samples, 0.91%)[unknown] (865 samples, 0.66%)[unknown] (539 samples, 0.41%)[unknown] (259 samples, 0.20%)[unknown] (80 samples, 0.06%)[unknown] (29 samples, 0.02%)sysmalloc (3,786 samples, 2.88%)sy..grow_heap (2,509 samples, 1.91%)g.._int_malloc (4,038 samples, 3.08%)_in..unlink_chunk (31 samples, 0.02%)alloc::alloc::exchange_malloc (4,335 samples, 3.30%)all..<alloc::alloc::Global as core::alloc::Allocator>::allocate (4,329 samples, 3.30%)<al..alloc::alloc::Global::alloc_impl (4,329 samples, 3.30%)all..alloc::alloc::alloc (4,329 samples, 3.30%)all..__rdl_alloc (4,329 samples, 3.30%)__r..std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (4,329 samples, 3.30%)std..std::sys::pal::unix::alloc::aligned_malloc (4,329 samples, 3.30%)std..__posix_memalign (4,297 samples, 3.27%)__p..__posix_memalign (4,297 samples, 3.27%)__p.._mid_memalign (4,297 samples, 3.27%)_mi.._int_memalign (4,149 samples, 3.16%)_in..sysmalloc (18 samples, 0.01%)core::option::Option<T>::map (6,666 samples, 5.08%)core::..tokio::task::spawn::spawn_inner::{{closure}} (6,665 samples, 5.08%)tokio:..tokio::runtime::scheduler::Handle::spawn (6,665 samples, 5.08%)tokio:..tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (6,664 samples, 5.08%)tokio:..tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (6,661 samples, 5.07%)tokio:..tokio::runtime::task::list::OwnedTasks<S>::bind (4,692 samples, 3.57%)toki..tokio::runtime::task::new_task (4,579 samples, 3.49%)tok..tokio::runtime::task::raw::RawTask::new (4,579 samples, 3.49%)tok..tokio::runtime::task::core::Cell<T,S>::new (4,579 samples, 3.49%)tok..alloc::boxed::Box<T>::new (4,389 samples, 3.34%)all..tokio::runtime::context::current::with_current (7,636 samples, 5.82%)tokio::..std::thread::local::LocalKey<T>::try_with (7,635 samples, 5.81%)std::th..tokio::runtime::context::current::with_current::{{closure}} (7,188 samples, 5.47%)tokio::..tokio::task::spawn::spawn (7,670 samples, 5.84%)tokio::..tokio::task::spawn::spawn_inner (7,670 samples, 5.84%)tokio::..tokio::runtime::task::id::Id::next (24 samples, 0.02%)core::sync::atomic::AtomicU64::fetch_add (24 samples, 0.02%)core::sync::atomic::atomic_add (24 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (62,691 samples, 47.75%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_muttokio::runtime::task::core::Core<T,S>::poll::{{closure}} (62,691 samples, 47.75%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}}torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (18,228 samples, 13.88%)torrust_tracker::serv..torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (18,226 samples, 13.88%)torrust_tracker::serv..torrust_tracker::servers::udp::server::Udp::spawn_request_processor (7,679 samples, 5.85%)torrust..__memcpy_avx512_unaligned_erms (38 samples, 0.03%)__memcpy_avx512_unaligned_erms (407 samples, 0.31%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (411 samples, 0.31%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (411 samples, 0.31%)tokio::runtime::task::core::Core<T,S>::poll (63,150 samples, 48.10%)tokio::runtime::task::core::Core<T,S>::polltokio::runtime::task::core::Core<T,S>::drop_future_or_output (459 samples, 0.35%)tokio::runtime::task::core::Core<T,S>::set_stage (459 samples, 0.35%)__memcpy_avx512_unaligned_erms (16 samples, 0.01%)__memcpy_avx512_unaligned_erms (398 samples, 0.30%)__memcpy_avx512_unaligned_erms (325 samples, 0.25%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (330 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (330 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::set_stage (731 samples, 0.56%)tokio::runtime::task::harness::poll_future (63,908 samples, 48.67%)tokio::runtime::task::harness::poll_futurestd::panic::catch_unwind (63,908 samples, 48.67%)std::panic::catch_unwindstd::panicking::try (63,908 samples, 48.67%)std::panicking::trystd::panicking::try::do_call (63,908 samples, 48.67%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (63,908 samples, 48.67%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()..tokio::runtime::task::harness::poll_future::{{closure}} (63,908 samples, 48.67%)tokio::runtime::task::harness::poll_future::{{closure}}tokio::runtime::task::core::Core<T,S>::store_output (758 samples, 0.58%)tokio::runtime::coop::budget (65,027 samples, 49.53%)tokio::runtime::coop::budgettokio::runtime::coop::with_budget (65,027 samples, 49.53%)tokio::runtime::coop::with_budgettokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (65,009 samples, 49.51%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}}tokio::runtime::task::LocalNotified<S>::run (65,003 samples, 49.51%)tokio::runtime::task::LocalNotified<S>::runtokio::runtime::task::raw::RawTask::poll (65,003 samples, 49.51%)tokio::runtime::task::raw::RawTask::polltokio::runtime::task::raw::poll (64,538 samples, 49.15%)tokio::runtime::task::raw::polltokio::runtime::task::harness::Harness<T,S>::poll (64,493 samples, 49.12%)tokio::runtime::task::harness::Harness<T,S>::polltokio::runtime::task::harness::Harness<T,S>::poll_inner (63,919 samples, 48.68%)tokio::runtime::task::harness::Harness<T,S>::poll_innertokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (93 samples, 0.07%)syscall (2,486 samples, 1.89%)s..[unknown] (2,424 samples, 1.85%)[..[unknown] (2,416 samples, 1.84%)[..[unknown] (2,130 samples, 1.62%)[unknown] (2,013 samples, 1.53%)[unknown] (1,951 samples, 1.49%)[unknown] (1,589 samples, 1.21%)[unknown] (1,415 samples, 1.08%)[unknown] (1,217 samples, 0.93%)[unknown] (820 samples, 0.62%)[unknown] (564 samples, 0.43%)[unknown] (360 samples, 0.27%)[unknown] (244 samples, 0.19%)[unknown] (194 samples, 0.15%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (339 samples, 0.26%)core::sync::atomic::AtomicUsize::fetch_add (337 samples, 0.26%)core::sync::atomic::atomic_add (337 samples, 0.26%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (364 samples, 0.28%)[unknown] (154 samples, 0.12%)[unknown] (152 samples, 0.12%)[unknown] (143 samples, 0.11%)[unknown] (139 samples, 0.11%)[unknown] (131 samples, 0.10%)[unknown] (123 samples, 0.09%)[unknown] (110 samples, 0.08%)[unknown] (80 samples, 0.06%)[unknown] (74 samples, 0.06%)[unknown] (65 samples, 0.05%)[unknown] (64 samples, 0.05%)[unknown] (47 samples, 0.04%)[unknown] (44 samples, 0.03%)[unknown] (43 samples, 0.03%)[unknown] (40 samples, 0.03%)[unknown] (26 samples, 0.02%)[unknown] (20 samples, 0.02%)__GI___libc_write (158 samples, 0.12%)__GI___libc_write (158 samples, 0.12%)mio::sys::unix::waker::eventfd::WakerInternal::wake (159 samples, 0.12%)<&std::fs::File as std::io::Write>::write (159 samples, 0.12%)std::sys::pal::unix::fs::File::write (159 samples, 0.12%)std::sys::pal::unix::fd::FileDesc::write (159 samples, 0.12%)tokio::runtime::driver::Handle::unpark (168 samples, 0.13%)tokio::runtime::driver::IoHandle::unpark (168 samples, 0.13%)tokio::runtime::io::driver::Handle::unpark (168 samples, 0.13%)mio::waker::Waker::wake (165 samples, 0.13%)mio::sys::unix::waker::fdbased::Waker::wake (165 samples, 0.13%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (68,159 samples, 51.91%)tokio::runtime::scheduler::multi_thread::worker::Context::run_tasktokio::runtime::scheduler::multi_thread::worker::Core::transition_from_searching (3,024 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::transition_worker_from_searching (3,023 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (3,022 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (171 samples, 0.13%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (171 samples, 0.13%)core::option::Option<T>::or_else (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::tune_global_queue_interval (53 samples, 0.04%)tokio::runtime::scheduler::multi_thread::stats::Stats::tuned_global_queue_interval (53 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (107 samples, 0.08%)__GI___libc_free (17 samples, 0.01%)_int_free (17 samples, 0.01%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Dying,K,V>::deallocating_end (18 samples, 0.01%)alloc::collections::btree::navigate::<impl alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>>::deallocating_end (18 samples, 0.01%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,alloc::collections::btree::node::marker::LeafOrInternal>::deallocate_and_ascend (18 samples, 0.01%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (18 samples, 0.01%)alloc::alloc::dealloc (18 samples, 0.01%)__rdl_dealloc (18 samples, 0.01%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (18 samples, 0.01%)alloc::collections::btree::map::IntoIter<K,V,A>::dying_next (19 samples, 0.01%)tokio::runtime::task::Task<S>::shutdown (26 samples, 0.02%)tokio::runtime::task::raw::RawTask::shutdown (26 samples, 0.02%)tokio::runtime::task::raw::shutdown (26 samples, 0.02%)tokio::runtime::task::harness::Harness<T,S>::shutdown (26 samples, 0.02%)tokio::runtime::task::harness::cancel_task (26 samples, 0.02%)std::panic::catch_unwind (26 samples, 0.02%)std::panicking::try (26 samples, 0.02%)std::panicking::try::do_call (26 samples, 0.02%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (26 samples, 0.02%)core::ops::function::FnOnce::call_once (26 samples, 0.02%)tokio::runtime::task::harness::cancel_task::{{closure}} (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage (26 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (26 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::core::Tracker> (26 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)core::ptr::drop_in_place<std::sync::rwlock::RwLock<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)core::ptr::drop_in_place<core::cell::UnsafeCell<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)<alloc::collections::btree::map::BTreeMap<K,V,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)core::mem::drop (26 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::IntoIter<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)<alloc::collections::btree::map::IntoIter<K,V,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,NodeType>,alloc::collections::btree::node::marker::KV>::drop_key_val (24 samples, 0.02%)core::mem::maybe_uninit::MaybeUninit<T>::assume_init_drop (24 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (24 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (21 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>> (20 samples, 0.02%)core::ptr::drop_in_place<core::cell::UnsafeCell<torrust_tracker_torrent_repository::entry::Torrent>> (20 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker_torrent_repository::entry::Torrent> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::PeerId,alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (20 samples, 0.02%)<alloc::collections::btree::map::BTreeMap<K,V,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)core::mem::drop (20 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::IntoIter<torrust_tracker_primitives::PeerId,alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (20 samples, 0.02%)<alloc::collections::btree::map::IntoIter<K,V,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::pre_shutdown (33 samples, 0.03%)tokio::runtime::task::list::OwnedTasks<S>::close_and_shutdown_all (33 samples, 0.03%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (114 samples, 0.09%)alloc::sync::Arc<T,A>::inner (114 samples, 0.09%)core::ptr::non_null::NonNull<T>::as_ref (114 samples, 0.09%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (108 samples, 0.08%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (108 samples, 0.08%)core::cmp::impls::<impl core::cmp::PartialOrd for usize>::lt (106 samples, 0.08%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (49 samples, 0.04%)alloc::sync::Arc<T,A>::inner (49 samples, 0.04%)core::ptr::non_null::NonNull<T>::as_ref (49 samples, 0.04%)core::num::<impl u32>::wrapping_sub (132 samples, 0.10%)core::sync::atomic::AtomicU64::load (40 samples, 0.03%)core::sync::atomic::atomic_load (40 samples, 0.03%)tokio::loom::std::atomic_u32::AtomicU32::unsync_load (48 samples, 0.04%)core::sync::atomic::AtomicU32::load (48 samples, 0.04%)core::sync::atomic::atomic_load (48 samples, 0.04%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (65 samples, 0.05%)alloc::sync::Arc<T,A>::inner (65 samples, 0.05%)core::ptr::non_null::NonNull<T>::as_ref (65 samples, 0.05%)core::num::<impl u32>::wrapping_sub (50 samples, 0.04%)core::sync::atomic::AtomicU32::load (55 samples, 0.04%)core::sync::atomic::atomic_load (55 samples, 0.04%)core::sync::atomic::AtomicU64::load (80 samples, 0.06%)core::sync::atomic::atomic_load (80 samples, 0.06%)tokio::runtime::scheduler::multi_thread::queue::pack (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (666 samples, 0.51%)tokio::runtime::scheduler::multi_thread::queue::unpack (147 samples, 0.11%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (1,036 samples, 0.79%)tokio::runtime::scheduler::multi_thread::queue::unpack (46 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_searching (49 samples, 0.04%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_searching (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (2,414 samples, 1.84%)t..tokio::util::rand::FastRand::fastrand_n (24 samples, 0.02%)tokio::util::rand::FastRand::fastrand (24 samples, 0.02%)std::sys_common::backtrace::__rust_begin_short_backtrace (98,136 samples, 74.74%)std::sys_common::backtrace::__rust_begin_short_backtracetokio::runtime::blocking::pool::Spawner::spawn_thread::{{closure}} (98,136 samples, 74.74%)tokio::runtime::blocking::pool::Spawner::spawn_thread::{{closure}}tokio::runtime::blocking::pool::Inner::run (98,136 samples, 74.74%)tokio::runtime::blocking::pool::Inner::runtokio::runtime::blocking::pool::Task::run (98,042 samples, 74.67%)tokio::runtime::blocking::pool::Task::runtokio::runtime::task::UnownedTask<S>::run (98,042 samples, 74.67%)tokio::runtime::task::UnownedTask<S>::runtokio::runtime::task::raw::RawTask::poll (98,042 samples, 74.67%)tokio::runtime::task::raw::RawTask::polltokio::runtime::task::raw::poll (98,042 samples, 74.67%)tokio::runtime::task::raw::polltokio::runtime::task::harness::Harness<T,S>::poll (98,042 samples, 74.67%)tokio::runtime::task::harness::Harness<T,S>::polltokio::runtime::task::harness::Harness<T,S>::poll_inner (98,042 samples, 74.67%)tokio::runtime::task::harness::Harness<T,S>::poll_innertokio::runtime::task::harness::poll_future (98,042 samples, 74.67%)tokio::runtime::task::harness::poll_futurestd::panic::catch_unwind (98,042 samples, 74.67%)std::panic::catch_unwindstd::panicking::try (98,042 samples, 74.67%)std::panicking::trystd::panicking::try::do_call (98,042 samples, 74.67%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (98,042 samples, 74.67%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_oncetokio::runtime::task::harness::poll_future::{{closure}} (98,042 samples, 74.67%)tokio::runtime::task::harness::poll_future::{{closure}}tokio::runtime::task::core::Core<T,S>::poll (98,042 samples, 74.67%)tokio::runtime::task::core::Core<T,S>::polltokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (98,042 samples, 74.67%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_muttokio::runtime::task::core::Core<T,S>::poll::{{closure}} (98,042 samples, 74.67%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}}<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (98,042 samples, 74.67%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::polltokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}}tokio::runtime::scheduler::multi_thread::worker::run (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::runtokio::runtime::context::runtime::enter_runtime (98,042 samples, 74.67%)tokio::runtime::context::runtime::enter_runtimetokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}tokio::runtime::context::set_scheduler (98,042 samples, 74.67%)tokio::runtime::context::set_schedulerstd::thread::local::LocalKey<T>::with (98,042 samples, 74.67%)std::thread::local::LocalKey<T>::withstd::thread::local::LocalKey<T>::try_with (98,042 samples, 74.67%)std::thread::local::LocalKey<T>::try_withtokio::runtime::context::set_scheduler::{{closure}} (98,042 samples, 74.67%)tokio::runtime::context::set_scheduler::{{closure}}tokio::runtime::context::scoped::Scoped<T>::set (98,042 samples, 74.67%)tokio::runtime::context::scoped::Scoped<T>::settokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}}tokio::runtime::scheduler::multi_thread::worker::Context::run (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::Context::runstd::panic::catch_unwind (98,137 samples, 74.74%)std::panic::catch_unwindstd::panicking::try (98,137 samples, 74.74%)std::panicking::trystd::panicking::try::do_call (98,137 samples, 74.74%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (98,137 samples, 74.74%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_oncestd::thread::Builder::spawn_unchecked_::{{closure}}::{{closure}} (98,137 samples, 74.74%)std::thread::Builder::spawn_unchecked_::{{closure}}::{{closure}}<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once (98,139 samples, 74.74%)<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once (98,139 samples, 74.74%)<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_oncecore::ops::function::FnOnce::call_once{{vtable.shim}} (98,139 samples, 74.74%)core::ops::function::FnOnce::call_once{{vtable.shim}}std::thread::Builder::spawn_unchecked_::{{closure}} (98,139 samples, 74.74%)std::thread::Builder::spawn_unchecked_::{{closure}}clone3 (98,205 samples, 74.79%)clone3start_thread (98,205 samples, 74.79%)start_threadstd::sys::pal::unix::thread::Thread::new::thread_start (98,158 samples, 74.76%)std::sys::pal::unix::thread::Thread::new::thread_startcore::ptr::drop_in_place<std::sys::pal::unix::stack_overflow::Handler> (19 samples, 0.01%)<std::sys::pal::unix::stack_overflow::Handler as core::ops::drop::Drop>::drop (19 samples, 0.01%)std::sys::pal::unix::stack_overflow::imp::drop_handler (19 samples, 0.01%)__GI_munmap (19 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (17 samples, 0.01%)[unknown] (16 samples, 0.01%)core::fmt::Formatter::pad_integral (112 samples, 0.09%)core::fmt::Formatter::pad_integral::write_prefix (59 samples, 0.04%)core::fmt::Formatter::pad_integral (16 samples, 0.01%)core::fmt::write (20 samples, 0.02%)core::ptr::drop_in_place<aquatic_udp_protocol::response::Response> (19 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (51 samples, 0.04%)rand_chacha::guts::round (18 samples, 0.01%)rand_chacha::guts::refill_wide::impl_avx2 (26 samples, 0.02%)rand_chacha::guts::refill_wide::fn_impl (26 samples, 0.02%)rand_chacha::guts::refill_wide_impl (26 samples, 0.02%)rand_chacha::guts::refill_wide (14 samples, 0.01%)std_detect::detect::arch::x86::__is_feature_detected::avx2 (14 samples, 0.01%)std_detect::detect::check_for (14 samples, 0.01%)std_detect::detect::cache::test (14 samples, 0.01%)std_detect::detect::cache::Cache::test (14 samples, 0.01%)core::sync::atomic::AtomicUsize::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)core::cell::RefCell<T>::borrow_mut (81 samples, 0.06%)core::cell::RefCell<T>::try_borrow_mut (81 samples, 0.06%)core::cell::BorrowRefMut::new (81 samples, 0.06%)std::sys::pal::unix::time::Timespec::now (164 samples, 0.12%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (106 samples, 0.08%)tokio::runtime::coop::budget (105 samples, 0.08%)tokio::runtime::coop::with_budget (105 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (96 samples, 0.07%)std::sys::pal::unix::time::Timespec::sub_timespec (35 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::lock_contended (15 samples, 0.01%)syscall (90 samples, 0.07%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (21 samples, 0.02%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run (61 samples, 0.05%)tokio::runtime::context::runtime::enter_runtime (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (61 samples, 0.05%)tokio::runtime::context::set_scheduler (61 samples, 0.05%)std::thread::local::LocalKey<T>::with (61 samples, 0.05%)std::thread::local::LocalKey<T>::try_with (61 samples, 0.05%)tokio::runtime::context::set_scheduler::{{closure}} (61 samples, 0.05%)tokio::runtime::context::scoped::Scoped<T>::set (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Context::run (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (19 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (17 samples, 0.01%)tokio::runtime::context::CONTEXT::__getit (14 samples, 0.01%)core::cell::Cell<T>::get (14 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::TaskIdGuard> (22 samples, 0.02%)<tokio::runtime::task::core::TaskIdGuard as core::ops::drop::Drop>::drop (22 samples, 0.02%)tokio::runtime::context::set_current_task_id (22 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (22 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (112 samples, 0.09%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (111 samples, 0.08%)tokio::runtime::task::harness::poll_future (125 samples, 0.10%)std::panic::catch_unwind (125 samples, 0.10%)std::panicking::try (125 samples, 0.10%)std::panicking::try::do_call (125 samples, 0.10%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (125 samples, 0.10%)tokio::runtime::task::harness::poll_future::{{closure}} (125 samples, 0.10%)tokio::runtime::task::core::Core<T,S>::poll (125 samples, 0.10%)tokio::runtime::task::raw::poll (157 samples, 0.12%)tokio::runtime::task::harness::Harness<T,S>::poll (135 samples, 0.10%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (135 samples, 0.10%)tokio::runtime::time::Driver::park_internal (15 samples, 0.01%)torrust_tracker::bootstrap::logging::INIT (17 samples, 0.01%)__memcpy_avx512_unaligned_erms (397 samples, 0.30%)_int_free (24 samples, 0.02%)_int_malloc (132 samples, 0.10%)torrust_tracker::servers::udp::logging::log_request::__CALLSITE::META (570 samples, 0.43%)__GI___lll_lock_wait_private (22 samples, 0.02%)futex_wait (14 samples, 0.01%)__memcpy_avx512_unaligned_erms (299 samples, 0.23%)_int_free (16 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request::__CALLSITE (361 samples, 0.27%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (41 samples, 0.03%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (23 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (53 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (14 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (63 samples, 0.05%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (21 samples, 0.02%)__GI___libc_malloc (18 samples, 0.01%)alloc::vec::Vec<T>::with_capacity (116 samples, 0.09%)alloc::vec::Vec<T,A>::with_capacity_in (116 samples, 0.09%)alloc::raw_vec::RawVec<T,A>::with_capacity_in (116 samples, 0.09%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (116 samples, 0.09%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (116 samples, 0.09%)alloc::alloc::Global::alloc_impl (116 samples, 0.09%)alloc::alloc::alloc (116 samples, 0.09%)__rdl_alloc (116 samples, 0.09%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (116 samples, 0.09%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (53 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (53 samples, 0.04%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (53 samples, 0.04%)_int_malloc (21 samples, 0.02%)[unknown] (36 samples, 0.03%)[unknown] (16 samples, 0.01%)core::mem::zeroed (27 samples, 0.02%)core::mem::maybe_uninit::MaybeUninit<T>::zeroed (27 samples, 0.02%)core::ptr::mut_ptr::<impl *mut T>::write_bytes (27 samples, 0.02%)core::intrinsics::write_bytes (27 samples, 0.02%)[unknown] (27 samples, 0.02%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}}::{{closure}} (64 samples, 0.05%)mio::net::udp::UdpSocket::recv_from (49 samples, 0.04%)mio::io_source::IoSource<T>::do_io (49 samples, 0.04%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (49 samples, 0.04%)mio::net::udp::UdpSocket::recv_from::{{closure}} (49 samples, 0.04%)std::net::udp::UdpSocket::recv_from (49 samples, 0.04%)std::sys_common::net::UdpSocket::recv_from (49 samples, 0.04%)std::sys::pal::unix::net::Socket::recv_from (49 samples, 0.04%)std::sys::pal::unix::net::Socket::recv_from_with_flags (49 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (271 samples, 0.21%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (143 samples, 0.11%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (141 samples, 0.11%)tokio::runtime::io::registration::Registration::clear_readiness (15 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::clear_readiness (15 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (15 samples, 0.01%)torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (359 samples, 0.27%)torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (346 samples, 0.26%)torrust_tracker::servers::udp::server::Udp::spawn_request_processor (39 samples, 0.03%)tokio::task::spawn::spawn (39 samples, 0.03%)tokio::task::spawn::spawn_inner (39 samples, 0.03%)tokio::runtime::context::current::with_current (39 samples, 0.03%)std::thread::local::LocalKey<T>::try_with (39 samples, 0.03%)tokio::runtime::context::current::with_current::{{closure}} (39 samples, 0.03%)core::option::Option<T>::map (39 samples, 0.03%)tokio::task::spawn::spawn_inner::{{closure}} (39 samples, 0.03%)tokio::runtime::scheduler::Handle::spawn (39 samples, 0.03%)tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (39 samples, 0.03%)tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (39 samples, 0.03%)tokio::runtime::task::list::OwnedTasks<S>::bind (34 samples, 0.03%)all (131,301 samples, 100%)tokio-runtime-w (131,061 samples, 99.82%)tokio-runtime-w \ No newline at end of file diff --git a/docs/media/kcachegrind-screenshot.png b/docs/media/kcachegrind-screenshot.png new file mode 100644 index 000000000..a10eb5ad6 Binary files /dev/null and b/docs/media/kcachegrind-screenshot.png differ diff --git a/docs/media/packages/packages-dependencies-http-tracker.png b/docs/media/packages/packages-dependencies-http-tracker.png new file mode 100644 index 000000000..45dbd9839 Binary files /dev/null and b/docs/media/packages/packages-dependencies-http-tracker.png differ diff --git a/docs/media/packages/packages-dependencies-udp-tracker.png b/docs/media/packages/packages-dependencies-udp-tracker.png new file mode 100644 index 000000000..57987a31e Binary files /dev/null and b/docs/media/packages/packages-dependencies-udp-tracker.png differ diff --git a/docs/media/packages/torrust-tracker-layers-with-packages.png b/docs/media/packages/torrust-tracker-layers-with-packages.png new file mode 100644 index 000000000..9da465806 Binary files /dev/null and b/docs/media/packages/torrust-tracker-layers-with-packages.png differ diff --git a/docs/media/torrent-repository-implementations-benchmarking-report.png b/docs/media/torrent-repository-implementations-benchmarking-report.png new file mode 100644 index 000000000..ee87c6d42 Binary files /dev/null and b/docs/media/torrent-repository-implementations-benchmarking-report.png differ diff --git a/docs/media/torrust-tracker-components.png b/docs/media/torrust-tracker-components.png deleted file mode 100644 index 19fe3c0b8..000000000 Binary files a/docs/media/torrust-tracker-components.png and /dev/null differ diff --git a/docs/packages.md b/docs/packages.md new file mode 100644 index 000000000..118046a87 --- /dev/null +++ b/docs/packages.md @@ -0,0 +1,115 @@ +# Torrust Tracker Package Architecture + +- [Package Conventions](#package-conventions) +- [Package Catalog](#package-catalog) +- [Architectural Philosophy](#architectural-philosophy) +- [Protocol Implementation Details](#protocol-implementation-details) +- [Architectural Philosophy](#architectural-philosophy) + +```output +packages/ +├── axum-health-check-api-server +├── axum-http-tracker-server +├── axum-rest-tracker-api-server +├── axum-server +├── clock +├── configuration +├── http-protocol +├── http-tracker-core +├── located-error +├── primitives +├── rest-tracker-api-client +├── rest-tracker-api-core +├── server-lib +├── test-helpers +├── torrent-repository +├── tracker-client +├── tracker-core +├── udp-protocol +├── udp-tracker-core +└── udp-tracker-server +``` + +```output +console/ +└── tracker-client # Client for interacting with trackers +``` + +```output +contrib/ +└── bencode # Community-contributed Bencode utilities +``` + +## Package Conventions + +| Prefix | Responsibility | Dependencies | +|-----------------|-----------------------------------------|---------------------------| +| `axum-*` | HTTP server components using Axum | Axum framework | +| `*-server` | Server implementations | Corresponding *-core | +| `*-core` | Domain logic & business rules | Protocol implementations | +| `*-protocol` | BitTorrent protocol implementations | BitTorrent protocol | +| `udp-*` | UDP Protocol-specific implementations | Tracker core | +| `http-*` | HTTP Protocol-specific implementations | Tracker core | + +Key Architectural Principles: + +1. **Separation of Concerns**: Servers contain only network I/O logic. +2. **Protocol Compliance**: `*-protocol` packages strictly implement BEP specifications. +3. **Extensibility**: Core logic is framework-agnostic for easy protocol additions. + +## Package Catalog + +| Package | Description | Key Responsibilities | +|---------|-------------|----------------------| +| **axum-*** | | | +| `axum-server` | Base Axum HTTP server infrastructure | HTTP server lifecycle management | +| `axum-http-tracker-server` | BitTorrent HTTP tracker (BEP 3/23) | Handle announce/scrape requests | +| `axum-rest-tracker-api-server` | Management REST API | Tracker configuration & monitoring | +| `axum-health-check-api-server` | Health monitoring endpoint | System health reporting | +| **Core Components** | | | +| `http-tracker-core` | HTTP-specific implementation | Request validation, Response formatting | +| `udp-tracker-core` | UDP-specific implementation | Connectionless request handling | +| `tracker-core` | Central tracker logic | Peer management | +| **Protocols** | | | +| `http-protocol` | HTTP tracker protocol (BEP 3/23) | Announce/scrape request parsing | +| `udp-protocol` | UDP tracker protocol (BEP 15) | UDP message framing/parsing | +| **Domain** | | | +| `torrent-repository` | Torrent metadata storage | InfoHash management, Peer coordination | +| `configuration` | Runtime configuration | Config file parsing, Environment variables | +| `primitives` | Domain-specific types | InfoHash, PeerId, Byte handling | +| **Utilities** | | | +| `clock` | Time abstraction | Mockable time source for testing | +| `located-error` | Diagnostic errors | Error tracing with source locations | +| `test-helpers` | Testing utilities | Mock servers, Test data generation | +| **Client Tools** | | | +| `tracker-client` | CLI client | Tracker interaction/testing | +| `rest-tracker-api-client` | API client library | REST API integration | + +## Protocol Implementation Details + +### HTTP Tracker (BEP 3/23) + +- `http-protocol` implements: + - URL parameter parsing + - Response bencoding + - Error code mapping + - Compact peer formatting + +### UDP Tracker (BEP 15) + +- `udp-protocol` handles: + - Connection ID management + - Message framing (32-bit big-endian) + - Transaction ID tracking + - Error response codes + +## Architectural Philosophy + +1. **Testability**: Core packages have minimal dependencies for easy unit testing +2. **Observability**: Health checks and metrics built into server packages +3. **Modularity**: Protocol implementations decoupled from transport layers +4. **Extensibility**: New protocols can be added without modifying core logic + +![Torrust Tracker Architecture Diagram](./media/packages/torrust-tracker-layers-with-packages.png) + +> Diagram shows clean separation between network I/O (servers), protocol handling, and core tracker logic diff --git a/docs/profiling.md b/docs/profiling.md new file mode 100644 index 000000000..8038f9e77 --- /dev/null +++ b/docs/profiling.md @@ -0,0 +1,132 @@ +# Profiling + +## Using flamegraph + +### Requirements + +You need to install some dependencies. For Ubuntu you can run: + +```console +sudo apt-get install clang lld +``` + +You also need to uncomment these lines in the cargo [config.toml](./../.cargo/config.toml) file. + +```toml +[target.x86_64-unknown-linux-gnu] +linker = "/usr/bin/clang" +rustflags = ["-Clink-arg=-fuse-ld=lld", "-Clink-arg=-Wl,--no-rosegment"] +``` + +Follow the [flamegraph](https://github.com/flamegraph-rs/flamegraph) instructions for installation. + +Apart from running the tracker you will need to run some request if you want to profile services while they are processing requests. + +You can use the aquatic [UDP load test](https://github.com/greatest-ape/aquatic/tree/master/crates/udp_load_test) script. + +### Generate flamegraph + +To generate the graph you will need to: + +1. Build the tracker for profiling. +2. Run the aquatic UDP load test. +3. Run the tracker with flamegraph and profiling configuration. + +```console +cargo build --profile=release-debug --bin=profiling +./target/release/aquatic_udp_load_test -c "load-test-config.toml" +sudo TORRUST_TRACKER_CONFIG_TOML_PATH="./share/default/config/tracker.udp.benchmarking.toml" /home/USER/.cargo/bin/flamegraph -- ./target/release-debug/profiling 60 +``` + +__NOTICE__: You need to install the `aquatic_udp_load_test` program. + +The output should be like the following: + +```output +Loading configuration file: `./share/default/config/tracker.udp.benchmarking.toml` ... +Torrust successfully shutdown. +[ perf record: Woken up 23377 times to write data ] +Warning: +Processed 533730 events and lost 3 chunks! + +Check IO/CPU overload! + +[ perf record: Captured and wrote 5899.806 MB perf.data (373239 samples) ] +writing flamegraph to "flamegraph.svg" +``` + +![flamegraph](./media/flamegraph.svg) + +__NOTICE__: You need to provide the absolute path for the installed `flamegraph` app if you use sudo. Replace `/home/USER/.cargo/bin/flamegraph` with the location of your installed `flamegraph` app. You can run it without sudo but you can get a warning message like the following: + +```output +WARNING: Kernel address maps (/proc/{kallsyms,modules}) are restricted, +check /proc/sys/kernel/kptr_restrict and /proc/sys/kernel/perf_event_paranoid. + +Samples in kernel functions may not be resolved if a suitable vmlinux +file is not found in the buildid cache or in the vmlinux path. + +Samples in kernel modules won't be resolved at all. + +If some relocation was applied (e.g. kexec) symbols may be misresolved +even with a suitable vmlinux or kallsyms file. + +Couldn't record kernel reference relocation symbol +Symbol resolution may be skewed if relocation was used (e.g. kexec). +Check /proc/kallsyms permission or run as root. +Loading configuration file: `./share/default/config/tracker.udp.benchmarking.toml` ... +``` + +And some bars in the graph will have the `unknown` label. + +![flamegraph generated without sudo](./media/flamegraph_generated_without_sudo.svg) + +## Using valgrind and kcachegrind + +You need to: + +1. Build an run the tracker for profiling. +2. Make requests to the tracker while it's running. + +Build and the binary for profiling: + +```console +RUSTFLAGS='-g' cargo build --release --bin profiling \ + && export TORRUST_TRACKER_CONFIG_TOML_PATH="./share/default/config/tracker.udp.benchmarking.toml" \ + && valgrind \ + --tool=callgrind \ + --callgrind-out-file=callgrind.out \ + --collect-jumps=yes \ + --simulate-cache=yes \ + ./target/release/profiling 60 +``` + +> NOTICE: You should make requests to the services you want to profile. For example, using the [UDP load test](./benchmarking.md#run-udp-load-test). + +After running the tracker with ` **The `[semantic version]` is bumped according to releases, new features, and breaking changes.** +> +> *The `develop` branch uses the (semantic version) suffix `-develop`.* + +## Process + +**Note**: this guide assumes that the your git `torrust` remote is like this: + +```sh +git remote show torrust +``` + +```s +* remote torrust + Fetch URL: git@github.com:torrust/torrust-tracker.git + Push URL: git@github.com:torrust/torrust-tracker.git +... +``` + +### 1. The `develop` branch is ready for a release + +The `develop` branch should have the version `[semantic version]-develop` that is ready to be released. + +### 2. Stage `develop` HEAD for merging into the `main` branch + +```sh +git fetch --all +git push --force torrust develop:staging/main +``` + +### 3. Create Release Commit + +```sh +git stash +git switch staging/main +git reset --hard torrust/staging/main +# change `[semantic version]-develop` to `[semantic version]`. +git add -A +git commit -m "release: version [semantic version]" +git push torrust +``` + +### 4. Create and Merge Pull Request from `staging/main` into `main` branch + +Pull request title format: "Release Version `[semantic version]`". + +This pull request merges the new version into the `main` branch. + +### 5. Push new version from `main` HEAD to `releases/v[semantic version]` branch + +```sh +git fetch --all +git push torrust main:releases/v[semantic version] +``` + +> **Check that the deployment is successful!** + +### 6. Create Release Tag + +```sh +git switch releases/v[semantic version] +git tag --sign v[semantic version] +git push --tags torrust +``` + +Make sure the [deployment](https://github.com/torrust/torrust-tracker/actions/workflows/deployment.yaml) workflow was successfully executed and the new version for the following crates were published: + +- [torrust-tracker-contrib-bencode](https://crates.io/crates/torrust-tracker-contrib-bencode) +- [torrust-tracker-located-error](https://crates.io/crates/torrust-tracker-located-error) +- [torrust-tracker-primitives](https://crates.io/crates/torrust-tracker-primitives) +- [torrust-tracker-clock](https://crates.io/crates/torrust-tracker-clock) +- [torrust-tracker-configuration](https://crates.io/crates/torrust-tracker-configuration) +- [torrust-tracker-torrent-repository](https://crates.io/crates/torrust-tracker-torrent-repository) +- [torrust-tracker-test-helpers](https://crates.io/crates/torrust-tracker-test-helpers) +- [torrust-tracker](https://crates.io/crates/torrust-tracker) + +### 7. Create Release on Github from Tag + +This is for those who wish to download the source code. + +### 8. Stage `main` HEAD for merging into the `develop` branch + +Merge release back into the develop branch. + +```sh +git fetch --all +git push --force torrust main:staging/develop +``` + +### 9. Create Comment that bumps next development version + +```sh +git stash +git switch staging/develop +git reset --hard torrust/staging/develop +# change `[semantic version]` to `(next)[semantic version]-develop`. +git add -A +git commit -m "develop: bump to version (next)[semantic version]-develop" +git push torrust +``` + +### 10. Create and Merge Pull Request from `staging/develop` into `develop` branch + +Pull request title format: "Version `[semantic version]` was Released". + +This pull request merges the new release into the `develop` branch and bumps the version number. diff --git a/packages/axum-health-check-api-server/Cargo.toml b/packages/axum-health-check-api-server/Cargo.toml new file mode 100644 index 000000000..cf9d8d9a3 --- /dev/null +++ b/packages/axum-health-check-api-server/Cargo.toml @@ -0,0 +1,40 @@ +[package] +authors.workspace = true +description = "The Torrust Bittorrent HTTP tracker." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = [ "axum", "bittorrent", "healthcheck", "http", "server", "torrust", "tracker" ] +license.workspace = true +name = "torrust-axum-health-check-api-server" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +axum = { version = "0", features = [ "macros" ] } +axum-server = { version = "0", features = [ "tls-rustls-no-provider" ] } +futures = "0" +hyper = "1" +serde = { version = "1", features = [ "derive" ] } +serde_json = { version = "1", features = [ "preserve_order" ] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } +torrust-axum-server = { version = "3.0.0-develop", path = "../axum-server" } +torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +tower-http = { version = "0", features = [ "compression-full", "cors", "propagate-header", "request-id", "trace" ] } +tracing = "0" +url = "2.5.4" + +[dev-dependencies] +reqwest = { version = "0", features = [ "json" ] } +torrust-axum-health-check-api-server = { version = "3.0.0-develop", path = "../axum-health-check-api-server" } +torrust-axum-http-tracker-server = { version = "3.0.0-develop", path = "../axum-http-tracker-server" } +torrust-axum-rest-tracker-api-server = { version = "3.0.0-develop", path = "../axum-rest-tracker-api-server" } +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } +torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker-server" } +tracing-subscriber = { version = "0", features = [ "json" ] } diff --git a/packages/axum-health-check-api-server/LICENSE b/packages/axum-health-check-api-server/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/axum-health-check-api-server/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/axum-health-check-api-server/README.md b/packages/axum-health-check-api-server/README.md new file mode 100644 index 000000000..d4c6b4f0b --- /dev/null +++ b/packages/axum-health-check-api-server/README.md @@ -0,0 +1,49 @@ +# Torrust Axum HTTP Tracker + +The Torrust Tracker Health Check API. + +The Torrust tracker container starts a local HTTP server on port 1313 to check all services. + +It's used for the container health check. + +URL: + +Example response: + +```json +{ + "status": "Ok", + "message": "", + "details": [ + { + "binding": "0.0.0.0:6969", + "info": "checking the udp tracker health check at: 0.0.0.0:6969", + "result": { + "Ok": "Connected" + } + }, + { + "binding": "0.0.0.0:1212", + "info": "checking api health check at: http://0.0.0.0:1212/api/health_check", + "result": { + "Ok": "200 OK" + } + }, + { + "binding": "0.0.0.0:7070", + "info": "checking http tracker health check at: http://0.0.0.0:7070/health_check", + "result": { + "Ok": "200 OK" + } + } + ] +} +``` + +## Documentation + +[Crate documentation](https://docs.rs/torrust-axum-health-check-api-server). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/axum-health-check-api-server/src/environment.rs b/packages/axum-health-check-api-server/src/environment.rs new file mode 100644 index 000000000..c1fb0547a --- /dev/null +++ b/packages/axum-health-check-api-server/src/environment.rs @@ -0,0 +1,112 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use tokio::sync::oneshot::{self, Sender}; +use tokio::task::JoinHandle; +use torrust_server_lib::registar::Registar; +use torrust_server_lib::signals::{self, Halted as SignalHalted, Started as SignalStarted}; +use torrust_tracker_configuration::HealthCheckApi; + +use crate::{server, HEALTH_CHECK_API_LOG_TARGET}; + +pub type Started = Environment; + +#[derive(Debug)] +pub enum Error { + #[allow(dead_code)] + Error(String), +} + +pub struct Running { + pub binding: SocketAddr, + pub halt_task: Sender, + pub task: JoinHandle, +} + +pub struct Stopped { + pub bind_to: SocketAddr, +} + +pub struct Environment { + pub registar: Registar, + pub state: S, +} + +impl Environment { + #[must_use] + pub fn new(config: &Arc, registar: Registar) -> Self { + let bind_to = config.bind_address; + + Self { + registar, + state: Stopped { bind_to }, + } + } + + /// Start the test environment for the Health Check API. + /// It runs the API server. + /// + /// # Panics + /// + /// Will panic if it cannot start the service in a spawned task. + pub async fn start(self) -> Environment { + let (tx_start, rx_start) = oneshot::channel::(); + let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); + + let register = self.registar.entries(); + + tracing::debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Spawning task to launch the service ..."); + + let server = tokio::spawn(async move { + tracing::debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting the server in a spawned task ..."); + + server::start(self.state.bind_to, tx_start, rx_halt, register) + .await + .expect("it should start the health check service"); + + tracing::debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Server started. Sending the binding {} ...", self.state.bind_to); + + self.state.bind_to + }); + + tracing::debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Waiting for spawning task to send the binding ..."); + + let binding = rx_start.await.expect("it should send service binding").address; + + Environment { + registar: self.registar.clone(), + state: Running { + task: server, + halt_task: tx_halt, + binding, + }, + } + } +} + +impl Environment { + pub async fn new(config: &Arc, registar: Registar) -> Self { + Environment::::new(config, registar).start().await + } + + /// # Errors + /// + /// Will return an error if it cannot send the halt signal. + /// + /// # Panics + /// + /// Will panic if it cannot shutdown the service. + pub async fn stop(self) -> Result, Error> { + self.state + .halt_task + .send(SignalHalted::Normal) + .map_err(|e| Error::Error(e.to_string()))?; + + let bind_to = self.state.task.await.expect("it should shutdown the service"); + + Ok(Environment { + registar: self.registar.clone(), + state: Stopped { bind_to }, + }) + } +} diff --git a/packages/axum-health-check-api-server/src/handlers.rs b/packages/axum-health-check-api-server/src/handlers.rs new file mode 100644 index 000000000..a26c901d7 --- /dev/null +++ b/packages/axum-health-check-api-server/src/handlers.rs @@ -0,0 +1,54 @@ +use std::collections::VecDeque; + +use axum::extract::State; +use axum::Json; +use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistry}; +use tracing::{instrument, Level}; + +use super::resources::{CheckReport, Report}; +use super::responses; + +/// Endpoint for container health check. +/// +/// Creates a vector [`CheckReport`] from the input set of [`CheckJob`], and then builds a report from the results. +/// +#[instrument(skip(register), ret(level = Level::DEBUG))] +pub(crate) async fn health_check_handler(State(register): State) -> Json { + #[allow(unused_assignments)] + let mut checks: VecDeque = VecDeque::new(); + + { + let mutex = register.lock(); + + checks = mutex.await.values().map(ServiceRegistration::spawn_check).collect(); + } + + // if we do not have any checks, lets return a `none` result. + if checks.is_empty() { + return responses::none(); + } + + let jobs = checks.drain(..).map(|c| { + tokio::spawn(async move { + CheckReport { + service_binding: c.service_binding.url(), + binding: c.service_binding.bind_address(), + info: c.info.clone(), + service_type: c.service_type, + result: c.job.await.expect("it should be able to join into the checking function"), + } + }) + }); + + let results: Vec = futures::future::join_all(jobs) + .await + .drain(..) + .map(|r| r.expect("it should be able to connect to the job")) + .collect(); + + if results.iter().any(CheckReport::fail) { + responses::error("health check failed".to_string(), results) + } else { + responses::ok(results) + } +} diff --git a/packages/axum-health-check-api-server/src/lib.rs b/packages/axum-health-check-api-server/src/lib.rs new file mode 100644 index 000000000..6a3b4b34d --- /dev/null +++ b/packages/axum-health-check-api-server/src/lib.rs @@ -0,0 +1,7 @@ +pub mod environment; +pub mod handlers; +pub mod resources; +pub mod responses; +pub mod server; + +pub const HEALTH_CHECK_API_LOG_TARGET: &str = "HEALTH CHECK API"; diff --git a/packages/axum-health-check-api-server/src/resources.rs b/packages/axum-health-check-api-server/src/resources.rs new file mode 100644 index 000000000..44e64b24c --- /dev/null +++ b/packages/axum-health-check-api-server/src/resources.rs @@ -0,0 +1,67 @@ +use std::net::SocketAddr; + +use serde::{Deserialize, Serialize}; +use url::Url; + +#[derive(Copy, Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] +pub enum Status { + Ok, + Error, + None, +} + +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] +pub struct CheckReport { + pub service_binding: Url, + pub binding: SocketAddr, + pub service_type: String, + pub info: String, + pub result: Result, +} + +impl CheckReport { + #[must_use] + pub fn pass(&self) -> bool { + self.result.is_ok() + } + #[must_use] + pub fn fail(&self) -> bool { + self.result.is_err() + } +} + +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] +pub struct Report { + pub status: Status, + pub message: String, + pub details: Vec, +} + +impl Report { + #[must_use] + pub fn none() -> Report { + Self { + status: Status::None, + message: String::new(), + details: Vec::default(), + } + } + + #[must_use] + pub fn ok(details: Vec) -> Report { + Self { + status: Status::Ok, + message: String::new(), + details, + } + } + + #[must_use] + pub fn error(message: String, details: Vec) -> Report { + Self { + status: Status::Error, + message, + details, + } + } +} diff --git a/packages/axum-health-check-api-server/src/responses.rs b/packages/axum-health-check-api-server/src/responses.rs new file mode 100644 index 000000000..3796d8be4 --- /dev/null +++ b/packages/axum-health-check-api-server/src/responses.rs @@ -0,0 +1,15 @@ +use axum::Json; + +use super::resources::{CheckReport, Report}; + +pub fn ok(details: Vec) -> Json { + Json(Report::ok(details)) +} + +pub fn error(message: String, details: Vec) -> Json { + Json(Report::error(message, details)) +} + +pub fn none() -> Json { + Json(Report::none()) +} diff --git a/packages/axum-health-check-api-server/src/server.rs b/packages/axum-health-check-api-server/src/server.rs new file mode 100644 index 000000000..a371f146e --- /dev/null +++ b/packages/axum-health-check-api-server/src/server.rs @@ -0,0 +1,134 @@ +//! Logic to run the Health Check HTTP API server. +//! +//! This API is intended to be used by the container infrastructure to check if +//! the whole application is healthy. +use std::net::SocketAddr; +use std::time::Duration; + +use axum::http::HeaderName; +use axum::response::Response; +use axum::routing::get; +use axum::{Json, Router}; +use axum_server::Handle; +use futures::Future; +use hyper::Request; +use serde_json::json; +use tokio::sync::oneshot::{Receiver, Sender}; +use torrust_axum_server::signals::graceful_shutdown; +use torrust_server_lib::logging::Latency; +use torrust_server_lib::registar::ServiceRegistry; +use torrust_server_lib::signals::{Halted, Started}; +use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; +use tower_http::classify::ServerErrorsFailureClass; +use tower_http::compression::CompressionLayer; +use tower_http::propagate_header::PropagateHeaderLayer; +use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; +use tower_http::trace::{DefaultMakeSpan, TraceLayer}; +use tower_http::LatencyUnit; +use tracing::{instrument, Level, Span}; + +use crate::handlers::health_check_handler; +use crate::HEALTH_CHECK_API_LOG_TARGET; + +/// Starts Health Check API server. +/// +/// # Panics +/// +/// Will panic if binding to the socket address fails. +#[instrument(skip(bind_to, tx, rx_halt, register))] +pub fn start( + bind_to: SocketAddr, + tx: Sender, + rx_halt: Receiver, + register: ServiceRegistry, +) -> impl Future> { + let router = Router::new() + .route("/", get(|| async { Json(json!({})) })) + .route("/health_check", get(health_check_handler)) + .with_state(register) + .layer(CompressionLayer::new()) + .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) + .layer(PropagateHeaderLayer::new(HeaderName::from_static("x-request-id"))) + .layer( + TraceLayer::new_for_http() + .make_span_with(DefaultMakeSpan::new().level(Level::INFO)) + .on_request(|request: &Request, span: &Span| { + let method = request.method().to_string(); + let uri = request.uri().to_string(); + let request_id = request + .headers() + .get("x-request-id") + .map(|v| v.to_str().unwrap_or_default()) + .unwrap_or_default(); + + span.record("request_id", request_id); + + tracing::event!( + target: HEALTH_CHECK_API_LOG_TARGET, + tracing::Level::INFO, %method, %uri, %request_id, "request"); + }) + .on_response(|response: &Response, latency: Duration, span: &Span| { + let latency_ms = latency.as_millis(); + let status_code = response.status(); + let request_id = response + .headers() + .get("x-request-id") + .map(|v| v.to_str().unwrap_or_default()) + .unwrap_or_default(); + + span.record("request_id", request_id); + + if status_code.is_server_error() { + tracing::event!( + target: HEALTH_CHECK_API_LOG_TARGET, + tracing::Level::ERROR, %latency_ms, %status_code, %request_id, "response"); + } else { + tracing::event!( + target: HEALTH_CHECK_API_LOG_TARGET, + tracing::Level::INFO, %latency_ms, %status_code, %request_id, "response"); + } + }) + .on_failure( + |failure_classification: ServerErrorsFailureClass, latency: Duration, _span: &Span| { + let latency = Latency::new(LatencyUnit::Millis, latency); + + tracing::event!( + target: HEALTH_CHECK_API_LOG_TARGET, + tracing::Level::ERROR, %failure_classification, %latency, "response failed"); + }, + ), + ) + .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)); + + let socket = std::net::TcpListener::bind(bind_to).expect("Could not bind tcp_listener to address."); + socket + .set_nonblocking(true) + .expect("Failed to set socket to non-blocking mode"); + let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); + let protocol = Protocol::HTTP; // The health check API only supports HTTP directly now. Use a reverse proxy for HTTPS. + let service_binding = ServiceBinding::new(protocol.clone(), address).expect("Service binding creation failed"); + + let handle = Handle::new(); + + tracing::debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting service with graceful shutdown in a spawned task ..."); + + tokio::task::spawn(graceful_shutdown( + handle.clone(), + rx_halt, + format!("Shutting down http server on socket address: {address}"), + address, + )); + + let running = axum_server::from_tcp(socket) + .expect("Failed to create server from TCP socket") + .handle(handle) + .serve(router.into_make_service_with_connect_info::()); + + tx.send(Started { + service_binding, + address, + }) + .expect("the Health Check API server should not be dropped"); + + running +} diff --git a/packages/axum-health-check-api-server/tests/integration.rs b/packages/axum-health-check-api-server/tests/integration.rs new file mode 100644 index 000000000..13ca963a3 --- /dev/null +++ b/packages/axum-health-check-api-server/tests/integration.rs @@ -0,0 +1,19 @@ +//! Integration tests. +//! +//! ```text +//! cargo test --test integration +//! ``` +mod server; + +use torrust_tracker_clock::clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/packages/axum-health-check-api-server/tests/server/client.rs b/packages/axum-health-check-api-server/tests/server/client.rs new file mode 100644 index 000000000..3d8bdc7d6 --- /dev/null +++ b/packages/axum-health-check-api-server/tests/server/client.rs @@ -0,0 +1,5 @@ +use reqwest::Response; + +pub async fn get(path: &str) -> Response { + reqwest::Client::builder().build().unwrap().get(path).send().await.unwrap() +} diff --git a/packages/axum-health-check-api-server/tests/server/contract.rs b/packages/axum-health-check-api-server/tests/server/contract.rs new file mode 100644 index 000000000..af1c0cff9 --- /dev/null +++ b/packages/axum-health-check-api-server/tests/server/contract.rs @@ -0,0 +1,335 @@ +use torrust_axum_health_check_api_server::environment::Started; +use torrust_axum_health_check_api_server::resources::{Report, Status}; +use torrust_server_lib::registar::Registar; +use torrust_tracker_test_helpers::{configuration, logging}; + +use crate::server::client::get; + +#[tokio::test] +async fn health_check_endpoint_should_return_status_ok_when_there_is_no_services_registered() { + logging::setup(); + + let configuration = configuration::ephemeral_with_no_services(); + + let env = Started::new(&configuration.health_check_api.into(), Registar::default()).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report = response + .json::() + .await + .expect("it should be able to get the report as json"); + + assert_eq!(report.status, Status::None); + + env.stop().await.expect("it should stop the service"); +} + +mod api { + use std::sync::Arc; + + use torrust_axum_health_check_api_server::environment::Started; + use torrust_axum_health_check_api_server::resources::{Report, Status}; + use torrust_tracker_test_helpers::{configuration, logging}; + + use crate::server::client::get; + + #[tokio::test] + pub(crate) async fn it_should_return_good_health_for_api_service() { + logging::setup(); + + let configuration = Arc::new(configuration::ephemeral()); + + let service = torrust_axum_rest_tracker_api_server::environment::Started::new(&configuration).await; + + let registar = service.registar.clone(); + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Ok); + assert_eq!(report.message, String::new()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, service.bind_address()); + + assert_eq!(details.result, Ok("200 OK".to_string())); + + assert_eq!( + details.info, + format!( + "checking api health check at: http://{}/api/health_check", // DevSkim: ignore DS137138 + service.bind_address() + ) + ); + + env.stop().await.expect("it should stop the service"); + } + + service.stop().await; + } + + #[tokio::test] + pub(crate) async fn it_should_return_error_when_api_service_was_stopped_after_registration() { + logging::setup(); + + let configuration = Arc::new(configuration::ephemeral()); + + let service = torrust_axum_rest_tracker_api_server::environment::Started::new(&configuration).await; + + let binding = service.bind_address(); + + let registar = service.registar.clone(); + + service.server.stop().await.expect("it should stop udp server"); + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Error); + assert_eq!(report.message, "health check failed".to_string()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, binding); + assert!( + details.result.as_ref().is_err_and(|e| e.contains("error sending request")), + "Expected to contain, \"error sending request\", but have message \"{:?}\".", + details.result + ); + assert_eq!( + details.info, + format!("checking api health check at: http://{binding}/api/health_check") // DevSkim: ignore DS137138 + ); + + env.stop().await.expect("it should stop the service"); + } + } +} + +mod http { + use std::sync::Arc; + + use torrust_axum_health_check_api_server::environment::Started; + use torrust_axum_health_check_api_server::resources::{Report, Status}; + use torrust_tracker_test_helpers::{configuration, logging}; + + use crate::server::client::get; + + #[tokio::test] + pub(crate) async fn it_should_return_good_health_for_http_service() { + logging::setup(); + + let configuration = Arc::new(configuration::ephemeral()); + + let service = torrust_axum_http_tracker_server::environment::Started::new(&configuration).await; + + let registar = service.registar.clone(); + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Ok); + assert_eq!(report.message, String::new()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, *service.bind_address()); + assert_eq!(details.result, Ok("200 OK".to_string())); + + assert_eq!( + details.info, + format!( + "checking http tracker health check at: http://{}/health_check", // DevSkim: ignore DS137138 + service.bind_address() + ) + ); + + env.stop().await.expect("it should stop the service"); + } + + service.stop().await; + } + + #[tokio::test] + pub(crate) async fn it_should_return_error_when_http_service_was_stopped_after_registration() { + logging::setup(); + + let configuration = Arc::new(configuration::ephemeral()); + + let service = torrust_axum_http_tracker_server::environment::Started::new(&configuration).await; + + let binding = *service.bind_address(); + + let registar = service.registar.clone(); + + service.server.stop().await.expect("it should stop udp server"); + + // Give the OS a moment to fully release the TCP port after the server stops. + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Error); + assert_eq!(report.message, "health check failed".to_string()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, binding); + assert!( + details.result.as_ref().is_err_and(|e| e.contains("error sending request")), + "Expected to contain, \"error sending request\", but have message \"{:?}\".", + details.result + ); + assert_eq!( + details.info, + format!("checking http tracker health check at: http://{binding}/health_check") // DevSkim: ignore DS137138 + ); + + env.stop().await.expect("it should stop the service"); + } + } +} + +mod udp { + use std::sync::Arc; + + use torrust_axum_health_check_api_server::environment::Started; + use torrust_axum_health_check_api_server::resources::{Report, Status}; + use torrust_tracker_test_helpers::{configuration, logging}; + + use crate::server::client::get; + + #[tokio::test] + pub(crate) async fn it_should_return_good_health_for_udp_service() { + logging::setup(); + + let configuration = Arc::new(configuration::ephemeral()); + + let service = torrust_udp_tracker_server::environment::Started::new(&configuration).await; + + let registar = service.registar.clone(); + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Ok); + assert_eq!(report.message, String::new()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, service.bind_address()); + assert_eq!(details.result, Ok("Connected".to_string())); + + assert_eq!( + details.info, + format!("checking the udp tracker health check at: {}", service.bind_address()) + ); + + env.stop().await.expect("it should stop the service"); + } + + service.stop().await; + } + + #[tokio::test] + pub(crate) async fn it_should_return_error_when_udp_service_was_stopped_after_registration() { + logging::setup(); + + let configuration = Arc::new(configuration::ephemeral()); + + let service = torrust_udp_tracker_server::environment::Started::new(&configuration).await; + + let binding = service.bind_address(); + + let registar = service.registar.clone(); + + service.server.stop().await.expect("it should stop udp server"); + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Error); + assert_eq!(report.message, "health check failed".to_string()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, binding); + assert_eq!(details.result, Err("Timed Out".to_string())); + assert_eq!(details.info, format!("checking the udp tracker health check at: {binding}")); + + env.stop().await.expect("it should stop the service"); + } + } +} diff --git a/packages/axum-health-check-api-server/tests/server/mod.rs b/packages/axum-health-check-api-server/tests/server/mod.rs new file mode 100644 index 000000000..2676be6f9 --- /dev/null +++ b/packages/axum-health-check-api-server/tests/server/mod.rs @@ -0,0 +1,2 @@ +pub mod client; +pub mod contract; diff --git a/packages/axum-http-tracker-server/Cargo.toml b/packages/axum-http-tracker-server/Cargo.toml new file mode 100644 index 000000000..88d073527 --- /dev/null +++ b/packages/axum-http-tracker-server/Cargo.toml @@ -0,0 +1,53 @@ +[package] +authors.workspace = true +description = "The Torrust Bittorrent HTTP tracker." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = [ "axum", "bittorrent", "http", "server", "torrust", "tracker" ] +license.workspace = true +name = "torrust-axum-http-tracker-server" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +axum = { version = "0", features = [ "macros" ] } +axum-client-ip = "0" +axum-server = { version = "0", features = [ "tls-rustls-no-provider" ] } +bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "../http-tracker-core" } +bittorrent-http-tracker-protocol = { version = "3.0.0-develop", path = "../http-protocol" } +bittorrent-primitives = "0.1.0" +bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } +derive_more = { version = "2", features = [ "as_ref", "constructor", "from" ] } +futures = "0" +hyper = "1" +reqwest = { version = "0", features = [ "json" ] } +serde = { version = "1", features = [ "derive" ] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } +tokio-util = "0.7.15" +torrust-axum-server = { version = "3.0.0-develop", path = "../axum-server" } +torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } +tower = { version = "0", features = [ "timeout" ] } +tower-http = { version = "0", features = [ "compression-full", "cors", "propagate-header", "request-id", "trace" ] } +tracing = "0" + +[dev-dependencies] +local-ip-address = "0" +percent-encoding = "2" +rand = "0" +serde_bencode = "0" +serde_bytes = "0" +serde_repr = "0" +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } +uuid = { version = "1", features = [ "v4" ] } +zerocopy = "0.7" diff --git a/packages/axum-http-tracker-server/LICENSE b/packages/axum-http-tracker-server/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/axum-http-tracker-server/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/axum-http-tracker-server/README.md b/packages/axum-http-tracker-server/README.md new file mode 100644 index 000000000..b109a08c1 --- /dev/null +++ b/packages/axum-http-tracker-server/README.md @@ -0,0 +1,11 @@ +# Torrust Axum HTTP Tracker + +The Torrust Bittorrent HTTP tracker. + +## Documentation + +[Crate documentation](https://docs.rs/torrust-axum-http-tracker-server). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs new file mode 100644 index 000000000..616973a0f --- /dev/null +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -0,0 +1,179 @@ +use std::sync::Arc; + +use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; +use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::container::TrackerCoreContainer; +use futures::executor::block_on; +use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; +use torrust_axum_server::tsl::make_rust_tls; +use torrust_server_lib::registar::Registar; +use torrust_tracker_configuration::{logging, Configuration}; +use torrust_tracker_primitives::peer; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; + +use crate::server::{HttpServer, Launcher, Running, Stopped}; + +pub type Started = Environment; + +pub struct Environment { + pub container: Arc, + pub registar: Registar, + pub server: HttpServer, + pub event_listener_job: Option>, + pub cancellation_token: CancellationToken, +} + +impl Environment { + /// Add a torrent to the tracker + pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + self.container + .tracker_core_container + .in_memory_torrent_repository + .handle_announcement(info_hash, peer, None) + .await; + } +} + +impl Environment { + /// # Panics + /// + /// Will panic if it fails to make the TSL config from the configuration. + #[allow(dead_code)] + #[must_use] + pub fn new(configuration: &Arc) -> Self { + initialize_global_services(configuration); + + let container = Arc::new(EnvContainer::initialize(configuration)); + + let bind_to = container.http_tracker_core_container.http_tracker_config.bind_address; + + let tls = block_on(make_rust_tls( + &container.http_tracker_core_container.http_tracker_config.tsl_config, + )) + .map(|tls| tls.expect("tls config failed")); + + let server = HttpServer::new(Launcher::new(bind_to, tls)); + + Self { + container, + registar: Registar::default(), + server, + event_listener_job: None, + cancellation_token: CancellationToken::new(), + } + } + + /// Starts the test environment and return a running environment. + /// + /// # Panics + /// + /// Will panic if the server fails to start. + #[allow(dead_code)] + pub async fn start(self) -> Environment { + // Start the event listener + let event_listener_job = run_event_listener( + self.container.http_tracker_core_container.event_bus.receiver(), + self.cancellation_token.clone(), + &self.container.http_tracker_core_container.stats_repository, + ); + + // Start the server + let server = self + .server + .start(self.container.http_tracker_core_container.clone(), self.registar.give_form()) + .await + .expect("Failed to start the HTTP tracker server"); + + Environment { + container: self.container.clone(), + registar: self.registar.clone(), + server, + event_listener_job: Some(event_listener_job), + cancellation_token: self.cancellation_token, + } + } +} + +impl Environment { + pub async fn new(configuration: &Arc) -> Self { + Environment::::new(configuration).start().await + } + + /// Stops the test environment and return a stopped environment. + /// + /// # Panics + /// + /// Will panic if the server fails to stop. + pub async fn stop(self) -> Environment { + // Stop the event listener + if let Some(event_listener_job) = self.event_listener_job { + // todo: send a message to the event listener to stop and wait for + // it to finish + event_listener_job.abort(); + } + + // Stop the server + let server = self.server.stop().await.expect("Failed to stop the HTTP tracker server"); + + Environment { + container: self.container, + registar: Registar::default(), + server, + event_listener_job: None, + cancellation_token: self.cancellation_token, + } + } + + #[must_use] + pub fn bind_address(&self) -> &std::net::SocketAddr { + &self.server.state.binding + } +} + +pub struct EnvContainer { + pub tracker_core_container: Arc, + pub http_tracker_core_container: Arc, +} + +impl EnvContainer { + /// # Panics + /// + /// Will panic if the configuration is missing the HTTP tracker configuration. + #[must_use] + pub fn initialize(configuration: &Configuration) -> Self { + let core_config = Arc::new(configuration.core.clone()); + let http_tracker_config = configuration + .http_trackers + .clone() + .expect("missing HTTP tracker configuration"); + let http_tracker_config = Arc::new(http_tracker_config[0].clone()); + + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + configuration.core.tracker_usage_statistics.into(), + )); + + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + &core_config, + &swarm_coordination_registry_container, + )); + + let http_tracker_container = + HttpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, &http_tracker_config); + + Self { + tracker_core_container, + http_tracker_core_container: http_tracker_container, + } + } +} + +fn initialize_global_services(configuration: &Configuration) { + initialize_static(); + logging::setup(&configuration.logging); +} + +fn initialize_static() { + torrust_tracker_clock::initialize_static(); +} diff --git a/src/servers/http/mod.rs b/packages/axum-http-tracker-server/src/lib.rs similarity index 65% rename from src/servers/http/mod.rs rename to packages/axum-http-tracker-server/src/lib.rs index 067e88fdd..2bb6978b7 100644 --- a/src/servers/http/mod.rs +++ b/packages/axum-http-tracker-server/src/lib.rs @@ -39,59 +39,59 @@ //! **Query parameters** //! //! > **NOTICE**: you can click on the parameter name to see a full description -//! after extracting and parsing the parameter from the URL query component. +//! > after extracting and parsing the parameter from the URL query component. //! //! Parameter | Type | Description | Required | Default | Example //! ---|---|---|---|---|--- -//! [`info_hash`](crate::servers::http::v1::requests::announce::Announce::info_hash) | percent encoded of 20-byte array | The `Info Hash` of the torrent. | Yes | No | `%81%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00` +//! [`info_hash`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce::info_hash) | percent encoded of 20-byte array | The `Info Hash` of the torrent. | Yes | No | `%81%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00` //! `peer_addr` | string |The IP address of the peer. | No | No | `2.137.87.41` -//! [`downloaded`](crate::servers::http::v1::requests::announce::Announce::downloaded) | positive integer |The number of bytes downloaded by the peer. | No | `0` | `0` -//! [`uploaded`](crate::servers::http::v1::requests::announce::Announce::uploaded) | positive integer | The number of bytes uploaded by the peer. | No | `0` | `0` -//! [`peer_id`](crate::servers::http::v1::requests::announce::Announce::peer_id) | percent encoded of 20-byte array | The ID of the peer. | Yes | No | `-qB00000000000000001` -//! [`port`](crate::servers::http::v1::requests::announce::Announce::port) | positive integer | The port used by the peer. | Yes | No | `17548` -//! [`left`](crate::servers::http::v1::requests::announce::Announce::left) | positive integer | The number of bytes pending to download. | No | `0` | `0` -//! [`event`](crate::servers::http::v1::requests::announce::Announce::event) | positive integer | The event that triggered the `Announce` request: `started`, `completed`, `stopped` | No | `None` | `completed` -//! [`compact`](crate::servers::http::v1::requests::announce::Announce::compact) | `0` or `1` | Whether the tracker should return a compact peer list. | No | `None` | `0` +//! [`downloaded`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce::downloaded) | positive integer |The number of bytes downloaded by the peer. | No | `0` | `0` +//! [`uploaded`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce::uploaded) | positive integer | The number of bytes uploaded by the peer. | No | `0` | `0` +//! [`peer_id`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce::peer_id) | percent encoded of 20-byte array | The ID of the peer. | Yes | No | `-qB00000000000000001` +//! [`port`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce::port) | positive integer | The port used by the peer. | Yes | No | `17548` +//! [`left`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce::left) | positive integer | The number of bytes pending to download. | No | `0` | `0` +//! [`event`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce::event) | positive integer | The event that triggered the `Announce` request: `started`, `completed`, `stopped` | No | `None` | `completed` +//! [`compact`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce::compact) | `0` or `1` | Whether the tracker should return a compact peer list. | No | `None` | `0` //! `numwant` | positive integer | **Not implemented**. The maximum number of peers you want in the reply. | No | `50` | `50` //! -//! Refer to the [`Announce`](crate::servers::http::v1::requests::announce::Announce) +//! Refer to the [`Announce`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce) //! request for more information about the parameters. //! //! > **NOTICE**: the [BEP 03](https://www.bittorrent.org/beps/bep_0003.html) -//! defines only the `ip` and `event` parameters as optional. However, the -//! tracker assigns default values to the optional parameters if they are not -//! provided. +//! > defines only the `ip` and `event` parameters as optional. However, the +//! > tracker assigns default values to the optional parameters if they are not +//! > provided. //! //! > **NOTICE**: the `peer_addr` parameter is not part of the original -//! specification. But the peer IP was added in the -//! [UDP Tracker protocol](https://www.bittorrent.org/beps/bep_0015.html). It is -//! used to provide the peer's IP address to the tracker, but it is ignored by -//! the tracker. The tracker uses the IP address of the peer that sent the -//! request or the right-most-ip in the `X-Forwarded-For` header if the tracker -//! is behind a reverse proxy. +//! > specification. But the peer IP was added in the +//! > [UDP Tracker protocol](https://www.bittorrent.org/beps/bep_0015.html). It is +//! > used to provide the peer's IP address to the tracker, but it is ignored by +//! > the tracker. The tracker uses the IP address of the peer that sent the +//! > request or the right-most-ip in the `X-Forwarded-For` header if the tracker +//! > is behind a reverse proxy. //! //! > **NOTICE**: the maximum number of peers that the tracker can return is -//! `74`. Defined with a hardcoded const [`MAX_SCRAPE_TORRENTS`](crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS). -//! Refer to [issue 262](https://github.com/torrust/torrust-tracker/issues/262) -//! for more information about this limitation. +//! > `74`. Defined with a hardcoded const [`TORRENT_PEERS_LIMIT`](torrust_tracker_configuration::TORRENT_PEERS_LIMIT). +//! > Refer to [issue 262](https://github.com/torrust/torrust-tracker/issues/262) +//! > for more information about this limitation. //! //! > **NOTICE**: the `info_hash` parameter is NOT a `URL` encoded string param. -//! It is percent encode of the raw `info_hash` bytes (40 bytes). URL `GET` params -//! can contain any bytes, not only well-formed UTF-8. The `info_hash` is a -//! 20-byte SHA1. Check the [`percent_encoding`](crate::servers::http::percent_encoding) -//! module to know more about the encoding. +//! > It is percent encode of the raw `info_hash` bytes (40 bytes). URL `GET` params +//! > can contain any bytes, not only well-formed UTF-8. The `info_hash` is a +//! > 20-byte SHA1. Check the [`percent_encoding`] +//! > module to know more about the encoding. //! //! > **NOTICE**: the `peer_id` parameter is NOT a `URL` encoded string param. -//! It is percent encode of the raw peer ID bytes (20 bytes). URL `GET` params -//! can contain any bytes, not only well-formed UTF-8. The `info_hash` is a -//! 20-byte SHA1. Check the [`percent_encoding`](crate::servers::http::percent_encoding) -//! module to know more about the encoding. +//! > It is percent encode of the raw peer ID bytes (20 bytes). URL `GET` params +//! > can contain any bytes, not only well-formed UTF-8. The `info_hash` is a +//! > 20-byte SHA1. Check the [`percent_encoding`] +//! > module to know more about the encoding. //! //! > **NOTICE**: by default, the tracker returns the non-compact peer list when -//! no `compact` parameter is provided or is empty. The -//! [BEP 23](https://www.bittorrent.org/beps/bep_0023.html) suggests to do the -//! opposite. The tracker should return the compact peer list by default and -//! return the non-compact peer list if the `compact` parameter is `0`. +//! > no `compact` parameter is provided or is empty. The +//! > [BEP 23](https://www.bittorrent.org/beps/bep_0023.html) suggests to do the +//! > opposite. The tracker should return the compact peer list by default and +//! > return the non-compact peer list if the `compact` parameter is `0`. //! //! **Sample announce URL** //! @@ -152,7 +152,7 @@ //! 000000f0: 65 e //! ``` //! -//! Refer to the [`NonCompact`](crate::servers::http::v1::responses::announce::NonCompact) +//! Refer to the [`Normal`](bittorrent_http_tracker_protocol::v1::responses::announce::Normal), i.e. `Non-Compact` //! response for more information about the response. //! //! **Sample compact response** @@ -190,7 +190,7 @@ //! 0000070: 7065 pe //! ``` //! -//! Refer to the [`Compact`](crate::servers::http::v1::responses::announce::Compact) +//! Refer to the [`Compact`](bittorrent_http_tracker_protocol::v1::responses::announce::Compact) //! response for more information about the response. //! //! **Protocol** @@ -206,26 +206,26 @@ //! //! ### Scrape //! -//! The `scrape` request allows a peer to get [swarm metadata](crate::tracker::torrent::SwarmMetadata) +//! The `scrape` request allows a peer to get [swarm metadata](torrust_tracker_primitives::swarm_metadata::SwarmMetadata) //! for multiple torrents at the same time. //! -//! The response contains the [swarm metadata](crate::tracker::torrent::SwarmMetadata) +//! The response contains the [swarm metadata](torrust_tracker_primitives::swarm_metadata::SwarmMetadata) //! for that torrent: //! -//! - [complete](crate::tracker::torrent::SwarmMetadata::complete) -//! - [downloaded](crate::tracker::torrent::SwarmMetadata::downloaded) -//! - [incomplete](crate::tracker::torrent::SwarmMetadata::incomplete) +//! - [complete](torrust_tracker_primitives::swarm_metadata::SwarmMetadata::complete) +//! - [downloaded](torrust_tracker_primitives::swarm_metadata::SwarmMetadata::downloaded) +//! - [incomplete](torrust_tracker_primitives::swarm_metadata::SwarmMetadata::incomplete) //! //! **Query parameters** //! //! Parameter | Type | Description | Required | Default | Example //! ---|---|---|---|---|--- -//! [`info_hash`](crate::servers::http::v1::requests::scrape::Scrape::info_hashes) | percent encoded of 20-byte array | The `Info Hash` of the torrent. | Yes | No | `%81%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00` +//! [`info_hash`](bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape::info_hashes) | percent encoded of 20-byte array | The `Info Hash` of the torrent. | Yes | No | `%81%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00` //! //! > **NOTICE**: you can scrape multiple torrents at the same time by passing -//! multiple `info_hash` parameters. +//! > multiple `info_hash` parameters. //! -//! Refer to the [`Scrape`](crate::servers::http::v1::requests::scrape::Scrape) +//! Refer to the [`Scrape`](bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape) //! request for more information about the parameters. //! //! **Sample scrape URL** @@ -237,8 +237,8 @@ //! In order to scrape multiple torrents at the same time you can pass multiple //! `info_hash` parameters: `info_hash=%81%00%0...00%00%00&info_hash=%82%00%0...00%00%00` //! -//! > **NOTICE**: the maximum number of torrent you can scrape at the same time -//! is `74`. Defined with a hardcoded const [`MAX_SCRAPE_TORRENTS`](crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS). +//! > **NOTICE**: the maximum number of torrents you can scrape at the same time +//! > is `74`. Defined with a hardcoded const [`MAX_SCRAPE_TORRENTS`](torrust_udp_tracker_server::MAX_SCRAPE_TORRENTS). //! //! **Sample response** //! @@ -266,7 +266,7 @@ //! Where the `files` key contains a dictionary of dictionaries. The first //! dictionary key is the `info_hash` of the torrent (`iiiiiiiiiiiiiiiiiiii` in //! the example). The second level dictionary contains the -//! [swarm metadata](crate::tracker::torrent::SwarmMetadata) for that torrent. +//! [swarm metadata](torrust_tracker_primitives::swarm_metadata::SwarmMetadata) for that torrent. //! //! If you save the response as a file and you open it with a program that //! can handle binary data you would see: @@ -303,15 +303,35 @@ //! //! - [Bencode](https://en.wikipedia.org/wiki/Bencode). //! - [Bencode to Json Online converter](https://chocobo1.github.io/bencode_online). -use serde::{Deserialize, Serialize}; - -pub mod percent_encoding; +pub mod environment; pub mod server; pub mod v1; +use serde::{Deserialize, Serialize}; + +pub const HTTP_TRACKER_LOG_TARGET: &str = "HTTP TRACKER"; + /// The version of the HTTP tracker. #[derive(Serialize, Deserialize, Copy, Clone, PartialEq, Eq, Debug)] pub enum Version { /// The `v1` version of the HTTP tracker. V1, } + +#[cfg(test)] +pub(crate) mod tests { + + pub(crate) mod helpers { + use bittorrent_primitives::info_hash::InfoHash; + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } + } +} diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs new file mode 100644 index 000000000..69f9cb72e --- /dev/null +++ b/packages/axum-http-tracker-server/src/server.rs @@ -0,0 +1,377 @@ +//! Module to handle the HTTP server instances. +use std::net::SocketAddr; +use std::sync::Arc; + +use axum_server::tls_rustls::RustlsConfig; +use axum_server::Handle; +use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; +use derive_more::Constructor; +use futures::future::BoxFuture; +use tokio::sync::oneshot::{Receiver, Sender}; +use torrust_axum_server::custom_axum_server::{self, TimeoutAcceptor}; +use torrust_axum_server::signals::graceful_shutdown; +use torrust_server_lib::logging::STARTED_ON; +use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; +use torrust_server_lib::signals::{Halted, Started}; +use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; +use tracing::instrument; + +use super::v1::routes::router; +use crate::HTTP_TRACKER_LOG_TARGET; + +const TYPE_STRING: &str = "http_tracker"; +/// Error that can occur when starting or stopping the HTTP server. +/// +/// Some errors triggered while starting the server are: +/// +/// - The spawned server cannot send its `SocketAddr` back to the main thread. +/// - The launcher cannot receive the `SocketAddr` from the spawned server. +/// +/// Some errors triggered while stopping the server are: +/// +/// - The channel to send the shutdown signal to the server is closed. +/// - The task to shutdown the server on the spawned server failed to execute to +/// completion. +#[derive(Debug)] +pub enum Error { + Error(String), +} + +#[derive(Constructor, Debug)] +pub struct Launcher { + pub bind_to: SocketAddr, + pub tls: Option, +} + +impl Launcher { + #[instrument(skip(self, http_tracker_container, tx_start, rx_halt))] + fn start( + &self, + http_tracker_container: &Arc, + tx_start: Sender, + rx_halt: Receiver, + ) -> BoxFuture<'static, ()> { + let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address."); + socket + .set_nonblocking(true) + .expect("Failed to set socket to non-blocking mode"); + let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); + + let handle = Handle::new(); + + tokio::task::spawn(graceful_shutdown( + handle.clone(), + rx_halt, + format!("Shutting down HTTP server on socket address: {address}"), + address, + )); + + let tls = self.tls.clone(); + let protocol = if tls.is_some() { Protocol::HTTPS } else { Protocol::HTTP }; + let service_binding = ServiceBinding::new(protocol.clone(), address).expect("Service binding creation failed"); + + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{address}"); + + let app = router(http_tracker_container, &service_binding); + + let running = Box::pin(async { + match tls { + Some(tls) => custom_axum_server::from_tcp_rustls_with_timeouts(socket, tls) + .expect("Failed to create server from TCP socket with TLS") + .handle(handle) + // The TimeoutAcceptor is commented because TSL does not work with it. + // See: https://github.com/torrust/torrust-index/issues/204#issuecomment-2115529214 + //.acceptor(TimeoutAcceptor) + .serve(app.into_make_service_with_connect_info::()) + .await + .expect("Axum server crashed."), + None => custom_axum_server::from_tcp_with_timeouts(socket) + .expect("Failed to create server from TCP socket") + .handle(handle) + .acceptor(TimeoutAcceptor) + .serve(app.into_make_service_with_connect_info::()) + .await + .expect("Axum server crashed."), + } + }); + + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", address); + + tx_start + .send(Started { + service_binding, + address, + }) + .expect("the HTTP(s) Tracker service should not be dropped"); + + running + } +} + +/// A HTTP server instance controller with no HTTP instance running. +#[allow(clippy::module_name_repetitions)] +pub type StoppedHttpServer = HttpServer; + +/// A HTTP server instance controller with a running HTTP instance. +#[allow(clippy::module_name_repetitions)] +pub type RunningHttpServer = HttpServer; + +/// A HTTP server instance controller. +/// +/// It's responsible for: +/// +/// - Keeping the initial configuration of the server. +/// - Starting and stopping the server. +/// - Keeping the state of the server: `running` or `stopped`. +/// +/// It's an state machine. Configurations cannot be changed. This struct +/// represents concrete configuration and state. It allows to start and stop the +/// server but always keeping the same configuration. +/// +/// > **NOTICE**: if the configurations changes after running the server it will +/// > reset to the initial value after stopping the server. This struct is not +/// > intended to persist configurations between runs. +#[allow(clippy::module_name_repetitions)] +pub struct HttpServer { + /// The state of the server: `running` or `stopped`. + pub state: S, +} + +/// A stopped HTTP server state. +pub struct Stopped { + launcher: Launcher, +} + +/// A running HTTP server state. +pub struct Running { + /// The address where the server is bound. + pub binding: SocketAddr, + pub halt_task: tokio::sync::oneshot::Sender, + pub task: tokio::task::JoinHandle, +} + +impl HttpServer { + /// It creates a new `HttpServer` controller in `stopped` state. + #[must_use] + pub fn new(launcher: Launcher) -> Self { + Self { + state: Stopped { launcher }, + } + } + + /// It starts the server and returns a `HttpServer` controller in `running` + /// state. + /// + /// # Errors + /// + /// It would return an error if no `SocketAddr` is returned after launching the server. + /// + /// # Panics + /// + /// It would panic spawned HTTP server launcher cannot send the bound `SocketAddr` + /// back to the main thread. + pub async fn start( + self, + http_tracker_container: Arc, + form: ServiceRegistrationForm, + ) -> Result, Error> { + let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); + let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); + + let launcher = self.state.launcher; + + let task = tokio::spawn(async move { + let server = launcher.start(&http_tracker_container, tx_start, rx_halt); + + server.await; + + launcher + }); + + let started = rx_start.await.expect("it should be able to start the service"); + + let listen_url = started.service_binding; + let binding = started.address; + + form.send(ServiceRegistration::new(listen_url, check_fn)) + .expect("it should be able to send service registration"); + + Ok(HttpServer { + state: Running { + binding, + halt_task: tx_halt, + task, + }, + }) + } +} + +impl HttpServer { + /// It stops the server and returns a `HttpServer` controller in `stopped` + /// state. + /// + /// # Errors + /// + /// It would return an error if the channel for the task killer signal was closed. + pub async fn stop(self) -> Result, Error> { + self.state + .halt_task + .send(Halted::Normal) + .map_err(|_| Error::Error("Task killer channel was closed.".to_string()))?; + + let launcher = self.state.task.await.map_err(|e| Error::Error(e.to_string()))?; + + Ok(HttpServer { + state: Stopped { launcher }, + }) + } +} + +/// Checks the Health by connecting to the HTTP tracker endpoint. +/// +/// # Errors +/// +/// This function will return an error if unable to connect. +/// Or if the request returns an error. +#[must_use] +pub fn check_fn(service_binding: &ServiceBinding) -> ServiceHealthCheckJob { + let url = format!("http://{}/health_check", service_binding.bind_address()); // DevSkim: ignore DS137138 + + let info = format!("checking http tracker health check at: {url}"); + + let job = tokio::spawn(async move { + match reqwest::get(url).await { + Ok(response) => Ok(response.status().to_string()), + Err(err) => Err(err.to_string()), + } + }); + + ServiceHealthCheckJob::new(service_binding.clone(), info, TYPE_STRING.to_string(), job) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; + use bittorrent_http_tracker_core::event::bus::EventBus; + use bittorrent_http_tracker_core::event::sender::Broadcaster; + use bittorrent_http_tracker_core::services::announce::AnnounceService; + use bittorrent_http_tracker_core::services::scrape::ScrapeService; + use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; + use bittorrent_http_tracker_core::statistics::repository::Repository; + use bittorrent_tracker_core::container::TrackerCoreContainer; + use tokio_util::sync::CancellationToken; + use torrust_axum_server::tsl::make_rust_tls; + use torrust_server_lib::registar::Registar; + use torrust_tracker_configuration::{logging, Configuration}; + use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; + use torrust_tracker_test_helpers::configuration::ephemeral_public; + + use crate::server::{HttpServer, Launcher}; + + pub fn initialize_container(configuration: &Configuration) -> HttpTrackerCoreContainer { + let cancellation_token = CancellationToken::new(); + + let core_config = Arc::new(configuration.core.clone()); + + let http_trackers = configuration + .http_trackers + .clone() + .expect("missing HTTP trackers configuration"); + + let http_tracker_config = &http_trackers[0]; + + let http_tracker_config = Arc::new(http_tracker_config.clone()); + + // HTTP core stats + let http_core_broadcaster = Broadcaster::default(); + let http_stats_repository = Arc::new(Repository::new()); + let http_stats_event_bus = Arc::new(EventBus::new( + configuration.core.tracker_usage_statistics.into(), + http_core_broadcaster.clone(), + )); + + let http_stats_event_sender = http_stats_event_bus.sender(); + + if configuration.core.tracker_usage_statistics { + let _unused = run_event_listener(http_stats_event_bus.receiver(), cancellation_token, &http_stats_repository); + } + + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + configuration.core.tracker_usage_statistics.into(), + )); + + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + &core_config, + &swarm_coordination_registry_container, + )); + + let announce_service = Arc::new(AnnounceService::new( + tracker_core_container.core_config.clone(), + tracker_core_container.announce_handler.clone(), + tracker_core_container.authentication_service.clone(), + tracker_core_container.whitelist_authorization.clone(), + http_stats_event_sender.clone(), + )); + + let scrape_service = Arc::new(ScrapeService::new( + tracker_core_container.core_config.clone(), + tracker_core_container.scrape_handler.clone(), + tracker_core_container.authentication_service.clone(), + http_stats_event_sender.clone(), + )); + + HttpTrackerCoreContainer { + tracker_core_container, + http_tracker_config, + event_bus: http_stats_event_bus, + stats_event_sender: http_stats_event_sender, + stats_repository: http_stats_repository, + announce_service, + scrape_service, + } + } + + fn initialize_global_services(configuration: &Configuration) { + initialize_static(); + logging::setup(&configuration.logging); + } + + fn initialize_static() { + torrust_tracker_clock::initialize_static(); + } + + #[tokio::test] + async fn it_should_be_able_to_start_and_stop() { + let configuration = Arc::new(ephemeral_public()); + + let http_trackers = configuration + .http_trackers + .clone() + .expect("missing HTTP trackers configuration"); + + let http_tracker_config = &http_trackers[0]; + + initialize_global_services(&configuration); + + let http_tracker_container = Arc::new(initialize_container(&configuration)); + + let bind_to = http_tracker_config.bind_address; + + let tls = make_rust_tls(&http_tracker_config.tsl_config) + .await + .map(|tls| tls.expect("tls config failed")); + + let register = &Registar::default(); + let stopped = HttpServer::new(Launcher::new(bind_to, tls)); + + let started = stopped + .start(http_tracker_container, register.give_form()) + .await + .expect("it should start the server"); + let stopped = started.stop().await.expect("it should stop the server"); + + assert_eq!(stopped.state.launcher.bind_to, bind_to); + } +} diff --git a/src/servers/http/v1/extractors/announce_request.rs b/packages/axum-http-tracker-server/src/v1/extractors/announce_request.rs similarity index 58% rename from src/servers/http/v1/extractors/announce_request.rs rename to packages/axum-http-tracker-server/src/v1/extractors/announce_request.rs index 5d947ef91..57001a47e 100644 --- a/src/servers/http/v1/extractors/announce_request.rs +++ b/packages/axum-http-tracker-server/src/v1/extractors/announce_request.rs @@ -1,13 +1,13 @@ -//! Axum [`extractor`](axum::extract) for the [`Announce`](crate::servers::http::v1::requests::announce::Announce) +//! Axum [`extractor`](axum::extract) for the [`Announce`] //! request. //! -//! It parses the query parameters returning an [`Announce`](crate::servers::http::v1::requests::announce::Announce) +//! It parses the query parameters returning an [`Announce`] //! request. //! -//! Refer to [`Announce`](crate::servers::http::v1::requests::announce) for more +//! Refer to [`Announce`](bittorrent_http_tracker_protocol::v1::requests::announce) for more //! information about the returned structure. //! -//! It returns a bencoded [`Error`](crate::servers::http::v1::responses::error) +//! It returns a bencoded [`Error`](bittorrent_http_tracker_protocol::v1::responses::error) //! response (`500`) if the query parameters are missing or invalid. //! //! **Sample announce request** @@ -19,41 +19,44 @@ //! Missing query params for `announce` request: //! //! ```text -//! d14:failure reason149:Cannot parse query params for announce request: missing query params for announce request in src/servers/http/v1/extractors/announce_request.rs:54:23e +//! d14:failure reason149:Bad request. Cannot parse query params for announce request: missing query params for announce request in src/servers/http/v1/extractors/announce_request.rs:54:23e //! ``` //! //! Invalid query param (`info_hash`): //! //! ```text -//! d14:failure reason240:Cannot parse query params for announce request: invalid param value invalid for info_hash in not enough bytes for infohash: got 7 bytes, expected 20 src/shared/bit_torrent/info_hash.rs:240:27, src/servers/http/v1/requests/announce.rs:182:42e +//! d14:failure reason240:Bad request. Cannot parse query params for announce request: invalid param value invalid for info_hash in not enough bytes for infohash: got 7 bytes, expected 20 src/shared/bit_torrent/info_hash.rs:240:27, src/servers/http/v1/requests/announce.rs:182:42e //! ``` +use std::future::Future; use std::panic::Location; -use axum::async_trait; use axum::extract::FromRequestParts; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; +use bittorrent_http_tracker_protocol::v1::query::Query; +use bittorrent_http_tracker_protocol::v1::requests::announce::{Announce, ParseAnnounceQueryError}; +use bittorrent_http_tracker_protocol::v1::responses; +use futures::FutureExt; +use hyper::StatusCode; -use crate::servers::http::v1::query::Query; -use crate::servers::http::v1::requests::announce::{Announce, ParseAnnounceQueryError}; -use crate::servers::http::v1::responses; - -/// Extractor for the [`Announce`](crate::servers::http::v1::requests::announce::Announce) +/// Extractor for the [`Announce`] /// request. pub struct ExtractRequest(pub Announce); -#[async_trait] impl FromRequestParts for ExtractRequest where S: Send + Sync, { type Rejection = Response; - async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result { - match extract_announce_from(parts.uri.query()) { - Ok(announce_request) => Ok(ExtractRequest(announce_request)), - Err(error) => Err(error.into_response()), + fn from_request_parts(parts: &mut Parts, _state: &S) -> impl Future> + Send { + async { + match extract_announce_from(parts.uri.query()) { + Ok(announce_request) => Ok(ExtractRequest(announce_request)), + Err(error) => Err((StatusCode::OK, error.write()).into_response()), + } } + .boxed() } } @@ -83,11 +86,12 @@ fn extract_announce_from(maybe_raw_query: Option<&str>) -> Result **NOTICE**: the returned HTTP status code is always `200` for authentication errors. -//! Neither [The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -//! nor [The Private Torrents](https://www.bittorrent.org/beps/bep_0027.html) -//! specifications specify any HTTP status code for authentication errors. +//! > Neither [The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) +//! > nor [The Private Torrents](https://www.bittorrent.org/beps/bep_0027.html) +//! > specifications specify any HTTP status code for authentication errors. +use std::future::Future; use std::panic::Location; -use axum::async_trait; use axum::extract::rejection::PathRejection; use axum::extract::{FromRequestParts, Path}; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; +use bittorrent_http_tracker_protocol::v1::{auth, responses}; +use bittorrent_tracker_core::authentication::Key; +use hyper::StatusCode; use serde::Deserialize; -use crate::servers::http::v1::handlers::common::auth; -use crate::servers::http::v1::responses; -use crate::tracker::auth::Key; - -/// Extractor for the [`Key`](crate::tracker::auth::Key) struct. +/// Extractor for the [`Key`] struct. pub struct Extract(pub Key); #[derive(Deserialize)] @@ -68,20 +67,22 @@ impl KeyParam { } } -#[async_trait] impl FromRequestParts for Extract where - S: Send + Sync, + S: Send + Sync + 'static, { type Rejection = Response; - async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { - // Extract `key` from URL path with Axum `Path` extractor - let maybe_path_with_key = Path::::from_request_parts(parts, state).await; + #[allow(clippy::manual_async_fn)] + fn from_request_parts(parts: &mut Parts, state: &S) -> impl Future> + Send { + async move { + // Extract `key` from URL path with Axum `Path` extractor + let maybe_path_with_key = Path::::from_request_parts(parts, state).await; - match extract_key(maybe_path_with_key) { - Ok(key) => Ok(Extract(key)), - Err(error) => Err(error.into_response()), + match extract_key(maybe_path_with_key) { + Ok(key) => Ok(Extract(key)), + Err(error) => Err((StatusCode::OK, error.write()).into_response()), + } } } } @@ -114,11 +115,6 @@ fn custom_error(rejection: &PathRejection) -> responses::error::Error { location: Location::caller(), }) } - axum::extract::rejection::PathRejection::MissingPathParams(_) => { - responses::error::Error::from(auth::Error::MissingAuthKey { - location: Location::caller(), - }) - } _ => responses::error::Error::from(auth::Error::CannotExtractKeyParam { location: Location::caller(), }), @@ -128,8 +124,9 @@ fn custom_error(rejection: &PathRejection) -> responses::error::Error { #[cfg(test)] mod tests { + use bittorrent_http_tracker_protocol::v1::responses::error::Error; + use super::parse_key; - use crate::servers::http::v1::responses::error::Error; fn assert_error_response(error: &Error, error_message: &str) { assert!( @@ -144,6 +141,9 @@ mod tests { let response = parse_key(invalid_key).unwrap_err(); - assert_error_response(&response, "Authentication error: Invalid format for authentication key param"); + assert_error_response( + &response, + "Tracker authentication error: Invalid format for authentication key param", + ); } } diff --git a/src/servers/http/v1/extractors/client_ip_sources.rs b/packages/axum-http-tracker-server/src/v1/extractors/client_ip_sources.rs similarity index 62% rename from src/servers/http/v1/extractors/client_ip_sources.rs rename to packages/axum-http-tracker-server/src/v1/extractors/client_ip_sources.rs index f04300402..ed568e0b9 100644 --- a/src/servers/http/v1/extractors/client_ip_sources.rs +++ b/packages/axum-http-tracker-server/src/v1/extractors/client_ip_sources.rs @@ -16,7 +16,7 @@ //! the tracker will use the `X-Forwarded-For` header to get the client IP //! address. //! -//! See [`torrust_tracker_configuration::Configuration::on_reverse_proxy`]. +//! See [`torrust_tracker_configuration::Configuration::core.on_reverse_proxy`]. //! //! The tracker can also be configured to run without a reverse proxy. In this //! case, the tracker will use the IP address from the connection info. @@ -35,41 +35,42 @@ //! `right_most_x_forwarded_for` = 126.0.0.2 //! `connection_info_ip` = 126.0.0.3 //! ``` +use std::future::Future; use std::net::SocketAddr; -use axum::async_trait; use axum::extract::{ConnectInfo, FromRequestParts}; use axum::http::request::Parts; use axum::response::Response; use axum_client_ip::RightmostXForwardedFor; +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; -use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; - -/// Extractor for the [`ClientIpSources`](crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources) +/// Extractor for the [`ClientIpSources`] /// struct. pub struct Extract(pub ClientIpSources); -#[async_trait] impl FromRequestParts for Extract where S: Send + Sync, { type Rejection = Response; - async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { - let right_most_x_forwarded_for = match RightmostXForwardedFor::from_request_parts(parts, state).await { - Ok(right_most_x_forwarded_for) => Some(right_most_x_forwarded_for.0), - Err(_) => None, - }; + #[allow(clippy::manual_async_fn)] + fn from_request_parts(parts: &mut Parts, state: &S) -> impl Future> + Send { + async move { + let right_most_x_forwarded_for = match RightmostXForwardedFor::from_request_parts(parts, state).await { + Ok(right_most_x_forwarded_for) => Some(right_most_x_forwarded_for.0), + Err(_) => None, + }; - let connection_info_ip = match ConnectInfo::::from_request_parts(parts, state).await { - Ok(connection_info_socket_addr) => Some(connection_info_socket_addr.0.ip()), - Err(_) => None, - }; + let connection_info_ip = match ConnectInfo::::from_request_parts(parts, state).await { + Ok(connection_info_socket_addr) => Some(connection_info_socket_addr.0), + Err(_) => None, + }; - Ok(Extract(ClientIpSources { - right_most_x_forwarded_for, - connection_info_ip, - })) + Ok(Extract(ClientIpSources { + right_most_x_forwarded_for, + connection_info_socket_address: connection_info_ip, + })) + } } } diff --git a/src/servers/http/v1/extractors/mod.rs b/packages/axum-http-tracker-server/src/v1/extractors/mod.rs similarity index 100% rename from src/servers/http/v1/extractors/mod.rs rename to packages/axum-http-tracker-server/src/v1/extractors/mod.rs diff --git a/src/servers/http/v1/extractors/scrape_request.rs b/packages/axum-http-tracker-server/src/v1/extractors/scrape_request.rs similarity index 64% rename from src/servers/http/v1/extractors/scrape_request.rs rename to packages/axum-http-tracker-server/src/v1/extractors/scrape_request.rs index 63c4dba69..33a998ff2 100644 --- a/src/servers/http/v1/extractors/scrape_request.rs +++ b/packages/axum-http-tracker-server/src/v1/extractors/scrape_request.rs @@ -1,13 +1,13 @@ -//! Axum [`extractor`](axum::extract) for the [`Scrape`](crate::servers::http::v1::requests::scrape::Scrape) +//! Axum [`extractor`](axum::extract) for the [`Scrape`] //! request. //! -//! It parses the query parameters returning an [`Scrape`](crate::servers::http::v1::requests::scrape::Scrape) +//! It parses the query parameters returning an [`Scrape`] //! request. //! -//! Refer to [`Scrape`](crate::servers::http::v1::requests::scrape) for more +//! Refer to [`Scrape`](bittorrent_http_tracker_protocol::v1::requests::scrape) for more //! information about the returned structure. //! -//! It returns a bencoded [`Error`](crate::servers::http::v1::responses::error) +//! It returns a bencoded [`Error`](bittorrent_http_tracker_protocol::v1::responses::error) //! response (`500`) if the query parameters are missing or invalid. //! //! **Sample scrape request** @@ -19,41 +19,44 @@ //! Missing query params for scrape request: //! //! ```text -//! d14:failure reason143:Cannot parse query params for scrape request: missing query params for scrape request in src/servers/http/v1/extractors/scrape_request.rs:52:23e +//! d14:failure reason143:Bad request. Cannot parse query params for scrape request: missing query params for scrape request in src/servers/http/v1/extractors/scrape_request.rs:52:23e //! ``` //! //! Invalid query params for scrape request: //! //! ```text -//! d14:failure reason235:Cannot parse query params for scrape request: invalid param value invalid for info_hash in not enough bytes for infohash: got 7 bytes, expected 20 src/shared/bit_torrent/info_hash.rs:240:27, src/servers/http/v1/requests/scrape.rs:66:46e +//! d14:failure reason235:Bad request. Cannot parse query params for scrape request: invalid param value invalid for info_hash in not enough bytes for infohash: got 7 bytes, expected 20 src/shared/bit_torrent/info_hash.rs:240:27, src/servers/http/v1/requests/scrape.rs:66:46e //! ``` +use std::future::Future; use std::panic::Location; -use axum::async_trait; use axum::extract::FromRequestParts; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; +use bittorrent_http_tracker_protocol::v1::query::Query; +use bittorrent_http_tracker_protocol::v1::requests::scrape::{ParseScrapeQueryError, Scrape}; +use bittorrent_http_tracker_protocol::v1::responses; +use futures::FutureExt; +use hyper::StatusCode; -use crate::servers::http::v1::query::Query; -use crate::servers::http::v1::requests::scrape::{ParseScrapeQueryError, Scrape}; -use crate::servers::http::v1::responses; - -/// Extractor for the [`Scrape`](crate::servers::http::v1::requests::scrape::Scrape) +/// Extractor for the [`Scrape`] /// request. pub struct ExtractRequest(pub Scrape); -#[async_trait] impl FromRequestParts for ExtractRequest where S: Send + Sync, { type Rejection = Response; - async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result { - match extract_scrape_from(parts.uri.query()) { - Ok(scrape_request) => Ok(ExtractRequest(scrape_request)), - Err(error) => Err(error.into_response()), + fn from_request_parts(parts: &mut Parts, _state: &S) -> impl Future> + Send { + async { + match extract_scrape_from(parts.uri.query()) { + Ok(scrape_request) => Ok(ExtractRequest(scrape_request)), + Err(error) => Err((StatusCode::OK, error.write()).into_response()), + } } + .boxed() } } @@ -83,10 +86,11 @@ fn extract_scrape_from(maybe_raw_query: Option<&str>) -> Result TestInfoHash { TestInfoHash { bencoded: "%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0".to_owned(), - value: InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(), + value: InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(), // DevSkim: ignore DS173237 } } @@ -145,7 +149,7 @@ mod tests { assert_error_response( &response, - "Cannot parse query params for scrape request: missing query params for scrape request", + "Bad request. Cannot parse query params for scrape request: missing query params for scrape request", ); } @@ -154,13 +158,13 @@ mod tests { let invalid_query = "param1=value1=value2"; let response = extract_scrape_from(Some(invalid_query)).unwrap_err(); - assert_error_response(&response, "Cannot parse query params"); + assert_error_response(&response, "Bad request. Cannot parse query params"); } #[test] fn it_should_reject_a_request_with_a_query_that_cannot_be_parsed_into_a_scrape_request() { let response = extract_scrape_from(Some("param1=value1")).unwrap_err(); - assert_error_response(&response, "Cannot parse query params for scrape request"); + assert_error_response(&response, "Bad request. Cannot parse query params for scrape request"); } } diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs new file mode 100644 index 000000000..ce718cd30 --- /dev/null +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -0,0 +1,431 @@ +//! Axum [`handlers`](axum#handlers) for the `announce` requests. +//! +//! The handlers perform the authentication and authorization of the request, +//! and resolve the client IP address. +use std::sync::Arc; + +use axum::extract::State; +use axum::response::{IntoResponse, Response}; +use bittorrent_http_tracker_core::services::announce::{AnnounceService, HttpAnnounceError}; +use bittorrent_http_tracker_protocol::v1::requests::announce::{Announce, Compact}; +use bittorrent_http_tracker_protocol::v1::responses::{self}; +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; +use bittorrent_tracker_core::authentication::Key; +use hyper::StatusCode; +use torrust_tracker_primitives::core::AnnounceData; +use torrust_tracker_primitives::service_binding::ServiceBinding; + +use crate::v1::extractors::announce_request::ExtractRequest; +use crate::v1::extractors::authentication_key::Extract as ExtractKey; +use crate::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; + +/// It handles the `announce` request when the HTTP tracker does not require +/// authentication (no PATH `key` parameter required). +#[allow(clippy::unused_async)] +pub async fn handle_without_key( + State(state): State<(Arc, ServiceBinding)>, + ExtractRequest(announce_request): ExtractRequest, + ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, +) -> Response { + tracing::debug!("http announce request: {:#?}", announce_request); + + handle(&state.0, &announce_request, &client_ip_sources, &state.1, None).await +} + +/// It handles the `announce` request when the HTTP tracker requires +/// authentication (PATH `key` parameter required). +#[allow(clippy::unused_async)] +pub async fn handle_with_key( + State(state): State<(Arc, ServiceBinding)>, + ExtractRequest(announce_request): ExtractRequest, + ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, + ExtractKey(key): ExtractKey, +) -> Response { + tracing::debug!("http announce request: {:#?}", announce_request); + + handle(&state.0, &announce_request, &client_ip_sources, &state.1, Some(key)).await +} + +/// It handles the `announce` request. +/// +/// Internal implementation that handles both the `authenticated` and +/// `unauthenticated` modes. +async fn handle( + announce_service: &Arc, + announce_request: &Announce, + client_ip_sources: &ClientIpSources, + server_service_binding: &ServiceBinding, + maybe_key: Option, +) -> Response { + let announce_data = match handle_announce( + announce_service, + announce_request, + client_ip_sources, + server_service_binding, + maybe_key, + ) + .await + { + Ok(announce_data) => announce_data, + Err(error) => { + let error_response = responses::error::Error { + failure_reason: error.to_string(), + }; + return (StatusCode::OK, error_response.write()).into_response(); + } + }; + build_response(announce_request, announce_data) +} + +async fn handle_announce( + announce_service: &Arc, + announce_request: &Announce, + client_ip_sources: &ClientIpSources, + server_service_binding: &ServiceBinding, + maybe_key: Option, +) -> Result { + announce_service + .handle_announce(announce_request, client_ip_sources, server_service_binding, maybe_key) + .await +} + +fn build_response(announce_request: &Announce, announce_data: AnnounceData) -> Response { + if announce_request.compact.as_ref().is_some_and(|f| *f == Compact::Accepted) { + let response: responses::Announce = announce_data.into(); + let bytes: Vec = response.data.into(); + (StatusCode::OK, bytes).into_response() + } else { + let response: responses::Announce = announce_data.into(); + let bytes: Vec = response.data.into(); + (StatusCode::OK, bytes).into_response() + } +} + +#[cfg(test)] +mod tests { + + use std::sync::Arc; + + use aquatic_udp_protocol::PeerId; + use bittorrent_http_tracker_core::event::bus::EventBus; + use bittorrent_http_tracker_core::event::sender::Broadcaster; + use bittorrent_http_tracker_core::services::announce::AnnounceService; + use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; + use bittorrent_http_tracker_core::statistics::repository::Repository; + use bittorrent_http_tracker_protocol::v1::requests::announce::Announce; + use bittorrent_http_tracker_protocol::v1::responses; + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; + use bittorrent_tracker_core::authentication::service::AuthenticationService; + use bittorrent_tracker_core::databases::setup::initialize_database; + use bittorrent_tracker_core::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; + use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use tokio_util::sync::CancellationToken; + use torrust_tracker_configuration::Configuration; + use torrust_tracker_test_helpers::configuration; + + use crate::tests::helpers::sample_info_hash; + + struct CoreHttpTrackerServices { + pub announce_service: Arc, + } + + fn initialize_private_tracker() -> CoreHttpTrackerServices { + initialize_core_tracker_services(&configuration::ephemeral_private()) + } + + fn initialize_listed_tracker() -> CoreHttpTrackerServices { + initialize_core_tracker_services(&configuration::ephemeral_listed()) + } + + fn initialize_tracker_on_reverse_proxy() -> CoreHttpTrackerServices { + initialize_core_tracker_services(&configuration::ephemeral_with_reverse_proxy()) + } + + fn initialize_tracker_not_on_reverse_proxy() -> CoreHttpTrackerServices { + initialize_core_tracker_services(&configuration::ephemeral_without_reverse_proxy()) + } + + fn initialize_core_tracker_services(config: &Configuration) -> CoreHttpTrackerServices { + let cancellation_token = CancellationToken::new(); + + // Initialize the core tracker services with the provided configuration. + let core_config = Arc::new(config.core.clone()); + let database = initialize_database(&config.core); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(AuthenticationService::new(&config.core, &in_memory_key_repository)); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_downloads_metric_repository, + )); + + // HTTP core stats + let http_core_broadcaster = Broadcaster::default(); + let http_stats_repository = Arc::new(Repository::new()); + let http_stats_event_bus = Arc::new(EventBus::new( + config.core.tracker_usage_statistics.into(), + http_core_broadcaster.clone(), + )); + + let http_stats_event_sender = http_stats_event_bus.sender(); + + if config.core.tracker_usage_statistics { + let _unused = run_event_listener(http_stats_event_bus.receiver(), cancellation_token, &http_stats_repository); + } + + let announce_service = Arc::new(AnnounceService::new( + core_config.clone(), + announce_handler.clone(), + authentication_service.clone(), + whitelist_authorization.clone(), + http_stats_event_sender.clone(), + )); + + CoreHttpTrackerServices { announce_service } + } + + fn sample_announce_request() -> Announce { + Announce { + info_hash: sample_info_hash(), + peer_id: PeerId(*b"-qB00000000000000001"), + port: 17548, + downloaded: None, + uploaded: None, + left: None, + event: None, + compact: None, + numwant: None, + } + } + + fn sample_client_ip_sources() -> ClientIpSources { + ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_socket_address: None, + } + } + + fn assert_error_response(error: &responses::error::Error, error_message: &str) { + assert!( + error.failure_reason.contains(error_message), + "Error response does not contain message: '{error_message}'. Error: {error:?}" + ); + } + + mod with_tracker_in_private_mode { + + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::str::FromStr; + + use bittorrent_http_tracker_protocol::v1::responses; + use bittorrent_tracker_core::authentication; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use super::{initialize_private_tracker, sample_announce_request, sample_client_ip_sources}; + use crate::v1::handlers::announce::handle_announce; + use crate::v1::handlers::announce::tests::assert_error_response; + + #[tokio::test] + async fn it_should_fail_when_the_authentication_key_is_missing() { + let http_core_tracker_services = initialize_private_tracker(); + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let maybe_key = None; + + let response = handle_announce( + &http_core_tracker_services.announce_service, + &sample_announce_request(), + &sample_client_ip_sources(), + &server_service_binding, + maybe_key, + ) + .await + .unwrap_err(); + + let error_response = responses::error::Error { + failure_reason: response.to_string(), + }; + + assert_error_response( + &error_response, + "Tracker core error: Tracker core authentication error: Missing authentication key", + ); + } + + #[tokio::test] + async fn it_should_fail_when_the_authentication_key_is_invalid() { + let http_core_tracker_services = initialize_private_tracker(); + + let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let maybe_key = Some(unregistered_key); + + let response = handle_announce( + &http_core_tracker_services.announce_service, + &sample_announce_request(), + &sample_client_ip_sources(), + &server_service_binding, + maybe_key, + ) + .await + .unwrap_err(); + + let error_response = responses::error::Error { + failure_reason: response.to_string(), + }; + + assert_error_response( + &error_response, + "Tracker core error: Tracker core authentication error: Failed to read key: YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ", + ); + } + } + + mod with_tracker_in_listed_mode { + + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use bittorrent_http_tracker_protocol::v1::responses; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use super::{initialize_listed_tracker, sample_announce_request, sample_client_ip_sources}; + use crate::v1::handlers::announce::handle_announce; + use crate::v1::handlers::announce::tests::assert_error_response; + + #[tokio::test] + async fn it_should_fail_when_the_announced_torrent_is_not_whitelisted() { + let http_core_tracker_services = initialize_listed_tracker(); + + let announce_request = sample_announce_request(); + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let response = handle_announce( + &http_core_tracker_services.announce_service, + &announce_request, + &sample_client_ip_sources(), + &server_service_binding, + None, + ) + .await + .unwrap_err(); + + let error_response = responses::error::Error { + failure_reason: response.to_string(), + }; + + assert_error_response( + &error_response, + &format!( + "Tracker core error: Tracker core whitelist error: The torrent: {}, is not whitelisted", + announce_request.info_hash + ), + ); + } + } + + mod with_tracker_on_reverse_proxy { + + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use bittorrent_http_tracker_protocol::v1::responses; + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use super::{initialize_tracker_on_reverse_proxy, sample_announce_request}; + use crate::v1::handlers::announce::handle_announce; + use crate::v1::handlers::announce::tests::assert_error_response; + + #[tokio::test] + async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { + let http_core_tracker_services = initialize_tracker_on_reverse_proxy(); + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_socket_address: None, + }; + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let response = handle_announce( + &http_core_tracker_services.announce_service, + &sample_announce_request(), + &client_ip_sources, + &server_service_binding, + None, + ) + .await + .unwrap_err(); + + let error_response = responses::error::Error { + failure_reason: response.to_string(), + }; + + assert_error_response( + &error_response, + "Error resolving peer IP: missing or invalid the right most X-Forwarded-For IP", + ); + } + } + + mod with_tracker_not_on_reverse_proxy { + + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use bittorrent_http_tracker_protocol::v1::responses; + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use super::{initialize_tracker_not_on_reverse_proxy, sample_announce_request}; + use crate::v1::handlers::announce::handle_announce; + use crate::v1::handlers::announce::tests::assert_error_response; + + #[tokio::test] + async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { + let http_core_tracker_services = initialize_tracker_not_on_reverse_proxy(); + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_socket_address: None, + }; + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let response = handle_announce( + &http_core_tracker_services.announce_service, + &sample_announce_request(), + &client_ip_sources, + &server_service_binding, + None, + ) + .await + .unwrap_err(); + + let error_response = responses::error::Error { + failure_reason: response.to_string(), + }; + + assert_error_response( + &error_response, + "Error resolving peer IP: cannot get the client IP from the connection info", + ); + } + } +} diff --git a/packages/axum-http-tracker-server/src/v1/handlers/health_check.rs b/packages/axum-http-tracker-server/src/v1/handlers/health_check.rs new file mode 100644 index 000000000..b15af6255 --- /dev/null +++ b/packages/axum-http-tracker-server/src/v1/handlers/health_check.rs @@ -0,0 +1,18 @@ +use axum::Json; +use serde::{Deserialize, Serialize}; + +#[allow(clippy::unused_async)] +pub async fn handler() -> Json { + Json(Report { status: Status::Ok }) +} + +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] +pub enum Status { + Ok, + Error, +} + +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] +pub struct Report { + pub status: Status, +} diff --git a/packages/axum-http-tracker-server/src/v1/handlers/mod.rs b/packages/axum-http-tracker-server/src/v1/handlers/mod.rs new file mode 100644 index 000000000..785213696 --- /dev/null +++ b/packages/axum-http-tracker-server/src/v1/handlers/mod.rs @@ -0,0 +1,4 @@ +//! Axum [`handlers`](axum#handlers) for the HTTP server. +pub mod announce; +pub mod health_check; +pub mod scrape; diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs new file mode 100644 index 000000000..bdd4378f3 --- /dev/null +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -0,0 +1,392 @@ +//! Axum [`handlers`](axum#handlers) for the `announce` requests. +//! +//! The handlers perform the authentication and authorization of the request, +//! and resolve the client IP address. +use std::sync::Arc; + +use axum::extract::State; +use axum::response::{IntoResponse, Response}; +use bittorrent_http_tracker_core::services::scrape::ScrapeService; +use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; +use bittorrent_http_tracker_protocol::v1::responses; +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; +use bittorrent_tracker_core::authentication::Key; +use hyper::StatusCode; +use torrust_tracker_primitives::core::ScrapeData; +use torrust_tracker_primitives::service_binding::ServiceBinding; + +use crate::v1::extractors::authentication_key::Extract as ExtractKey; +use crate::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; +use crate::v1::extractors::scrape_request::ExtractRequest; + +/// It handles the `scrape` request when the HTTP tracker is configured +/// to run in `public` mode. +#[allow(clippy::unused_async)] +pub async fn handle_without_key( + State(state): State<(Arc, ServiceBinding)>, + ExtractRequest(scrape_request): ExtractRequest, + ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, +) -> Response { + tracing::debug!("http scrape request: {:#?}", &scrape_request); + + handle(&state.0, &scrape_request, &client_ip_sources, &state.1, None).await +} + +/// It handles the `scrape` request when the HTTP tracker is configured +/// to run in `private` or `private_listed` mode. +/// +/// In this case, the authentication `key` parameter is required. +#[allow(clippy::unused_async)] +pub async fn handle_with_key( + State(state): State<(Arc, ServiceBinding)>, + ExtractRequest(scrape_request): ExtractRequest, + ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, + ExtractKey(key): ExtractKey, +) -> Response { + tracing::debug!("http scrape request: {:#?}", &scrape_request); + + handle(&state.0, &scrape_request, &client_ip_sources, &state.1, Some(key)).await +} + +async fn handle( + scrape_service: &Arc, + scrape_request: &Scrape, + client_ip_sources: &ClientIpSources, + server_service_binding: &ServiceBinding, + maybe_key: Option, +) -> Response { + let scrape_data = match scrape_service + .handle_scrape(scrape_request, client_ip_sources, server_service_binding, maybe_key) + .await + { + Ok(scrape_data) => scrape_data, + Err(error) => { + let error_response = responses::error::Error { + failure_reason: error.to_string(), + }; + return (StatusCode::OK, error_response.write()).into_response(); + } + }; + + build_response(scrape_data) +} + +fn build_response(scrape_data: ScrapeData) -> Response { + let response = responses::scrape::Bencoded::from(scrape_data); + + (StatusCode::OK, response.body()).into_response() +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::str::FromStr; + use std::sync::Arc; + + use bittorrent_http_tracker_core::event::bus::EventBus; + use bittorrent_http_tracker_core::event::sender::Broadcaster; + use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; + use bittorrent_http_tracker_core::statistics::repository::Repository; + use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; + use bittorrent_http_tracker_protocol::v1::responses; + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use bittorrent_primitives::info_hash::InfoHash; + use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; + use bittorrent_tracker_core::authentication::service::AuthenticationService; + use bittorrent_tracker_core::scrape_handler::ScrapeHandler; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; + use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use tokio_util::sync::CancellationToken; + use torrust_tracker_configuration::{Configuration, Core}; + use torrust_tracker_test_helpers::configuration; + + struct CoreTrackerServices { + pub core_config: Arc, + pub scrape_handler: Arc, + pub authentication_service: Arc, + } + + struct CoreHttpTrackerServices { + pub http_stats_event_sender: bittorrent_http_tracker_core::event::sender::Sender, + } + + fn initialize_private_tracker() -> (CoreTrackerServices, CoreHttpTrackerServices) { + initialize_core_tracker_services(&configuration::ephemeral_private()) + } + + fn initialize_listed_tracker() -> (CoreTrackerServices, CoreHttpTrackerServices) { + initialize_core_tracker_services(&configuration::ephemeral_listed()) + } + + fn initialize_tracker_on_reverse_proxy() -> (CoreTrackerServices, CoreHttpTrackerServices) { + initialize_core_tracker_services(&configuration::ephemeral_with_reverse_proxy()) + } + + fn initialize_tracker_not_on_reverse_proxy() -> (CoreTrackerServices, CoreHttpTrackerServices) { + initialize_core_tracker_services(&configuration::ephemeral_without_reverse_proxy()) + } + + fn initialize_core_tracker_services(config: &Configuration) -> (CoreTrackerServices, CoreHttpTrackerServices) { + let cancellation_token = CancellationToken::new(); + + let core_config = Arc::new(config.core.clone()); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(AuthenticationService::new(&config.core, &in_memory_key_repository)); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + // HTTP core stats + let http_core_broadcaster = Broadcaster::default(); + let http_stats_repository = Arc::new(Repository::new()); + let http_stats_event_bus = Arc::new(EventBus::new( + config.core.tracker_usage_statistics.into(), + http_core_broadcaster.clone(), + )); + + let http_stats_event_sender = http_stats_event_bus.sender(); + + if config.core.tracker_usage_statistics { + let _unused = run_event_listener(http_stats_event_bus.receiver(), cancellation_token, &http_stats_repository); + } + + ( + CoreTrackerServices { + core_config, + scrape_handler, + authentication_service, + }, + CoreHttpTrackerServices { http_stats_event_sender }, + ) + } + + fn sample_scrape_request() -> Scrape { + Scrape { + info_hashes: vec!["3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap()], // DevSkim: ignore DS173237 + } + } + + fn sample_client_ip_sources() -> ClientIpSources { + ClientIpSources { + right_most_x_forwarded_for: Some(IpAddr::from_str("203.0.113.195").unwrap()), + connection_info_socket_address: Some(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 8080)), + } + } + + fn assert_error_response(error: &responses::error::Error, error_message: &str) { + assert!( + error.failure_reason.contains(error_message), + "Error response does not contain message: '{error_message}'. Error: {error:?}" + ); + } + + mod with_tracker_in_private_mode { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::str::FromStr; + + use bittorrent_http_tracker_core::services::scrape::ScrapeService; + use bittorrent_tracker_core::authentication; + use torrust_tracker_primitives::core::ScrapeData; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use super::{initialize_private_tracker, sample_client_ip_sources, sample_scrape_request}; + + #[tokio::test] + async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_missing() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let (core_tracker_services, core_http_tracker_services) = initialize_private_tracker(); + + let scrape_request = sample_scrape_request(); + let maybe_key = None; + + let scrape_service = ScrapeService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.scrape_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let scrape_data = scrape_service + .handle_scrape( + &scrape_request, + &sample_client_ip_sources(), + &server_service_binding, + maybe_key, + ) + .await + .unwrap(); + + let expected_scrape_data = ScrapeData::zeroed(&scrape_request.info_hashes); + + assert_eq!(scrape_data, expected_scrape_data); + } + + #[tokio::test] + async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_invalid() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let (core_tracker_services, core_http_tracker_services) = initialize_private_tracker(); + + let scrape_request = sample_scrape_request(); + let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + let maybe_key = Some(unregistered_key); + + let scrape_service = ScrapeService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.scrape_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let scrape_data = scrape_service + .handle_scrape( + &scrape_request, + &sample_client_ip_sources(), + &server_service_binding, + maybe_key, + ) + .await + .unwrap(); + + let expected_scrape_data = ScrapeData::zeroed(&scrape_request.info_hashes); + + assert_eq!(scrape_data, expected_scrape_data); + } + } + + mod with_tracker_in_listed_mode { + + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use bittorrent_http_tracker_core::services::scrape::ScrapeService; + use torrust_tracker_primitives::core::ScrapeData; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use super::{initialize_listed_tracker, sample_client_ip_sources, sample_scrape_request}; + + #[tokio::test] + async fn it_should_return_zeroed_swarm_metadata_when_the_torrent_is_not_whitelisted() { + let (core_tracker_services, core_http_tracker_services) = initialize_listed_tracker(); + + let scrape_request = sample_scrape_request(); + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let scrape_service = ScrapeService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.scrape_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let scrape_data = scrape_service + .handle_scrape(&scrape_request, &sample_client_ip_sources(), &server_service_binding, None) + .await + .unwrap(); + + let expected_scrape_data = ScrapeData::zeroed(&scrape_request.info_hashes); + + assert_eq!(scrape_data, expected_scrape_data); + } + } + + mod with_tracker_on_reverse_proxy { + + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use bittorrent_http_tracker_core::services::scrape::ScrapeService; + use bittorrent_http_tracker_protocol::v1::responses; + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use super::{initialize_tracker_on_reverse_proxy, sample_scrape_request}; + use crate::v1::handlers::scrape::tests::assert_error_response; + + #[tokio::test] + async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { + let (core_tracker_services, core_http_tracker_services) = initialize_tracker_on_reverse_proxy(); + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_socket_address: None, + }; + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let scrape_service = ScrapeService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.scrape_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let response = scrape_service + .handle_scrape(&sample_scrape_request(), &client_ip_sources, &server_service_binding, None) + .await + .unwrap_err(); + + let error_response = responses::error::Error { + failure_reason: response.to_string(), + }; + + assert_error_response( + &error_response, + "Error resolving peer IP: missing or invalid the right most X-Forwarded-For IP", + ); + } + } + + mod with_tracker_not_on_reverse_proxy { + + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use bittorrent_http_tracker_core::services::scrape::ScrapeService; + use bittorrent_http_tracker_protocol::v1::responses; + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use super::{initialize_tracker_not_on_reverse_proxy, sample_scrape_request}; + use crate::v1::handlers::scrape::tests::assert_error_response; + + #[tokio::test] + async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { + let (core_tracker_services, core_http_tracker_services) = initialize_tracker_not_on_reverse_proxy(); + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_socket_address: None, + }; + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let scrape_service = ScrapeService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.scrape_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let response = scrape_service + .handle_scrape(&sample_scrape_request(), &client_ip_sources, &server_service_binding, None) + .await + .unwrap_err(); + + let error_response = responses::error::Error { + failure_reason: response.to_string(), + }; + + assert_error_response( + &error_response, + "Error resolving peer IP: cannot get the client IP from the connection info", + ); + } + } +} diff --git a/packages/axum-http-tracker-server/src/v1/mod.rs b/packages/axum-http-tracker-server/src/v1/mod.rs new file mode 100644 index 000000000..7b1b15138 --- /dev/null +++ b/packages/axum-http-tracker-server/src/v1/mod.rs @@ -0,0 +1,4 @@ +//! HTTP server implementation for the `v1` API. +pub mod extractors; +pub mod handlers; +pub mod routes; diff --git a/packages/axum-http-tracker-server/src/v1/routes.rs b/packages/axum-http-tracker-server/src/v1/routes.rs new file mode 100644 index 000000000..df395cd9a --- /dev/null +++ b/packages/axum-http-tracker-server/src/v1/routes.rs @@ -0,0 +1,128 @@ +//! HTTP server routes for version `v1`. +use std::sync::Arc; +use std::time::Duration; + +use axum::error_handling::HandleErrorLayer; +use axum::http::HeaderName; +use axum::response::Response; +use axum::routing::get; +use axum::{BoxError, Router}; +use axum_client_ip::SecureClientIpSource; +use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; +use hyper::{Request, StatusCode}; +use torrust_server_lib::logging::Latency; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; +use torrust_tracker_primitives::service_binding::ServiceBinding; +use tower::timeout::TimeoutLayer; +use tower::ServiceBuilder; +use tower_http::classify::ServerErrorsFailureClass; +use tower_http::compression::CompressionLayer; +use tower_http::propagate_header::PropagateHeaderLayer; +use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; +use tower_http::trace::{DefaultMakeSpan, TraceLayer}; +use tower_http::LatencyUnit; +use tracing::{instrument, Level, Span}; + +use super::handlers::{announce, health_check, scrape}; +use crate::HTTP_TRACKER_LOG_TARGET; + +/// It adds the routes to the router. +/// +/// > **NOTICE**: it's added a layer to get the client IP from the connection +/// > info. The tracker could use the connection info to get the client IP. +#[instrument(skip(http_tracker_container, server_service_binding))] +pub fn router(http_tracker_container: &Arc, server_service_binding: &ServiceBinding) -> Router { + let server_socket_addr = server_service_binding.bind_address(); + + Router::new() + // Health check + .route("/health_check", get(health_check::handler)) + // Announce request + .route( + "/announce", + get(announce::handle_without_key).with_state(( + http_tracker_container.announce_service.clone(), + server_service_binding.clone(), + )), + ) + .route( + "/announce/{key}", + get(announce::handle_with_key).with_state(( + http_tracker_container.announce_service.clone(), + server_service_binding.clone(), + )), + ) + // Scrape request + .route( + "/scrape", + get(scrape::handle_without_key) + .with_state((http_tracker_container.scrape_service.clone(), server_service_binding.clone())), + ) + .route( + "/scrape/{key}", + get(scrape::handle_with_key) + .with_state((http_tracker_container.scrape_service.clone(), server_service_binding.clone())), + ) + // Add extension to get the client IP from the connection info + .layer(SecureClientIpSource::ConnectInfo.into_extension()) + .layer(CompressionLayer::new()) + .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) + .layer(PropagateHeaderLayer::new(HeaderName::from_static("x-request-id"))) + .layer( + TraceLayer::new_for_http() + .make_span_with(DefaultMakeSpan::new().level(Level::INFO)) + .on_request(move |request: &Request, span: &Span| { + let method = request.method().to_string(); + let uri = request.uri().to_string(); + let request_id = request + .headers() + .get("x-request-id") + .map(|v| v.to_str().unwrap_or_default()) + .unwrap_or_default(); + + span.record("request_id", request_id); + + tracing::event!( + target: HTTP_TRACKER_LOG_TARGET, + tracing::Level::INFO, %server_socket_addr, %method, %uri, %request_id, "request"); + }) + .on_response(move |response: &Response, latency: Duration, span: &Span| { + let latency_ms = latency.as_millis(); + let status_code = response.status(); + let request_id = response + .headers() + .get("x-request-id") + .map(|v| v.to_str().unwrap_or_default()) + .unwrap_or_default(); + + span.record("request_id", request_id); + + if status_code.is_server_error() { + tracing::event!( + target: HTTP_TRACKER_LOG_TARGET, + tracing::Level::ERROR, %server_socket_addr, %latency_ms, %status_code, %request_id, "response"); + } else { + tracing::event!( + target: HTTP_TRACKER_LOG_TARGET, + tracing::Level::INFO, %server_socket_addr, %latency_ms, %status_code, %request_id, "response"); + } + }) + .on_failure( + |failure_classification: ServerErrorsFailureClass, latency: Duration, _span: &Span| { + let latency = Latency::new(LatencyUnit::Millis, latency); + + tracing::event!( + target: HTTP_TRACKER_LOG_TARGET, + tracing::Level::ERROR, %failure_classification, %latency, "response failed"); + }, + ), + ) + .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) + .layer( + ServiceBuilder::new() + // this middleware goes above `TimeoutLayer` because it will receive + // errors returned by `TimeoutLayer` + .layer(HandleErrorLayer::new(|_: BoxError| async { StatusCode::REQUEST_TIMEOUT })) + .layer(TimeoutLayer::new(DEFAULT_TIMEOUT)), + ) +} diff --git a/packages/axum-http-tracker-server/tests/common/fixtures.rs b/packages/axum-http-tracker-server/tests/common/fixtures.rs new file mode 100644 index 000000000..2b4a42b58 --- /dev/null +++ b/packages/axum-http-tracker-server/tests/common/fixtures.rs @@ -0,0 +1,22 @@ +use bittorrent_primitives::info_hash::InfoHash; +use rand::prelude::*; + +pub fn invalid_info_hashes() -> Vec { + [ + "0".to_string(), + "-1".to_string(), + "1.1".to_string(), + "INVALID INFOHASH".to_string(), + "9c38422213e30bff212b30c360d26f9a0213642".to_string(), // 39-char length instead of 40. DevSkim: ignore DS173237 + "9c38422213e30bff212b30c360d26f9a0213642&".to_string(), // Invalid char + ] + .to_vec() +} + +/// Returns a random info hash. +pub fn random_info_hash() -> InfoHash { + let mut rng = rand::rng(); + let random_bytes: [u8; 20] = rng.random(); + + InfoHash::from_bytes(&random_bytes) +} diff --git a/tests/common/http.rs b/packages/axum-http-tracker-server/tests/common/http.rs similarity index 100% rename from tests/common/http.rs rename to packages/axum-http-tracker-server/tests/common/http.rs diff --git a/tests/common/mod.rs b/packages/axum-http-tracker-server/tests/common/mod.rs similarity index 55% rename from tests/common/mod.rs rename to packages/axum-http-tracker-server/tests/common/mod.rs index 51a8a5b03..810620359 100644 --- a/tests/common/mod.rs +++ b/packages/axum-http-tracker-server/tests/common/mod.rs @@ -1,4 +1,2 @@ -pub mod app; pub mod fixtures; pub mod http; -pub mod udp; diff --git a/packages/axum-http-tracker-server/tests/integration.rs b/packages/axum-http-tracker-server/tests/integration.rs new file mode 100644 index 000000000..70b3aeb89 --- /dev/null +++ b/packages/axum-http-tracker-server/tests/integration.rs @@ -0,0 +1,20 @@ +//! Integration tests. +//! +//! ```text +//! cargo test --test integration +//! ``` +mod common; +mod server; + +use torrust_tracker_clock::clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/tests/servers/http/asserts.rs b/packages/axum-http-tracker-server/tests/server/asserts.rs similarity index 89% rename from tests/servers/http/asserts.rs rename to packages/axum-http-tracker-server/tests/server/asserts.rs index 3a2e67bf0..a82014e16 100644 --- a/tests/servers/http/asserts.rs +++ b/packages/axum-http-tracker-server/tests/server/asserts.rs @@ -4,7 +4,7 @@ use reqwest::Response; use super::responses::announce::{Announce, Compact, DeserializedCompact}; use super::responses::scrape; -use crate::servers::http::responses::error::Error; +use crate::server::responses::error::Error; pub fn assert_bencoded_error(response_text: &String, expected_failure_reason: &str, location: &'static Location<'static>) { let error_failure_reason = serde_bencode::from_str::(response_text) @@ -22,6 +22,7 @@ pub fn assert_bencoded_error(response_text: &String, expected_failure_reason: &s ); } +#[allow(dead_code)] pub async fn assert_empty_announce_response(response: Response) { assert_eq!(response.status(), 200); let announce_response: Announce = serde_bencode::from_str(&response.text().await.unwrap()).unwrap(); @@ -133,7 +134,7 @@ pub async fn assert_cannot_parse_query_params_error_response(response: Response, assert_bencoded_error( &response.text().await.unwrap(), - &format!("Cannot parse query params{failure}"), + &format!("Bad request. Cannot parse query params{failure}"), Location::caller(), ); } @@ -141,5 +142,19 @@ pub async fn assert_cannot_parse_query_params_error_response(response: Response, pub async fn assert_authentication_error_response(response: Response) { assert_eq!(response.status(), 200); - assert_bencoded_error(&response.text().await.unwrap(), "Authentication error", Location::caller()); + assert_bencoded_error( + &response.text().await.unwrap(), + "Tracker authentication error", + Location::caller(), + ); +} + +pub async fn assert_tracker_core_authentication_error_response(response: Response) { + assert_eq!(response.status(), 200); + + assert_bencoded_error( + &response.text().await.unwrap(), + "Tracker core error: Tracker core authentication error", + Location::caller(), + ); } diff --git a/tests/servers/http/client.rs b/packages/axum-http-tracker-server/tests/server/client.rs similarity index 84% rename from tests/servers/http/client.rs rename to packages/axum-http-tracker-server/tests/server/client.rs index f5cdca398..ca9703858 100644 --- a/tests/servers/http/client.rs +++ b/packages/axum-http-tracker-server/tests/server/client.rs @@ -1,7 +1,7 @@ use std::net::IpAddr; +use bittorrent_tracker_core::authentication::Key; use reqwest::{Client as ReqwestClient, Response}; -use torrust_tracker::tracker::auth::Key; use super::requests::announce::{self, Query}; use super::requests::scrape; @@ -9,7 +9,7 @@ use super::requests::scrape; /// HTTP Tracker Client pub struct Client { server_addr: std::net::SocketAddr, - reqwest_client: ReqwestClient, + reqwest: ReqwestClient, key: Option, } @@ -25,7 +25,7 @@ impl Client { pub fn new(server_addr: std::net::SocketAddr) -> Self { Self { server_addr, - reqwest_client: reqwest::Client::builder().build().unwrap(), + reqwest: reqwest::Client::builder().build().unwrap(), key: None, } } @@ -34,7 +34,7 @@ impl Client { pub fn bind(server_addr: std::net::SocketAddr, local_address: IpAddr) -> Self { Self { server_addr, - reqwest_client: reqwest::Client::builder().local_address(local_address).build().unwrap(), + reqwest: reqwest::Client::builder().local_address(local_address).build().unwrap(), key: None, } } @@ -42,7 +42,7 @@ impl Client { pub fn authenticated(server_addr: std::net::SocketAddr, key: Key) -> Self { Self { server_addr, - reqwest_client: reqwest::Client::builder().build().unwrap(), + reqwest: reqwest::Client::builder().build().unwrap(), key: Some(key), } } @@ -60,12 +60,16 @@ impl Client { .await } + pub async fn health_check(&self) -> Response { + self.get(&self.build_path("health_check")).await + } + pub async fn get(&self, path: &str) -> Response { - self.reqwest_client.get(self.build_url(path)).send().await.unwrap() + self.reqwest.get(self.build_url(path)).send().await.unwrap() } pub async fn get_with_header(&self, path: &str, key: &str, value: &str) -> Response { - self.reqwest_client + self.reqwest .get(self.build_url(path)) .header(key, value) .send() diff --git a/tests/servers/http/mod.rs b/packages/axum-http-tracker-server/tests/server/mod.rs similarity index 95% rename from tests/servers/http/mod.rs rename to packages/axum-http-tracker-server/tests/server/mod.rs index cb2885df0..31b48b2f0 100644 --- a/tests/servers/http/mod.rs +++ b/packages/axum-http-tracker-server/tests/server/mod.rs @@ -2,7 +2,6 @@ pub mod asserts; pub mod client; pub mod requests; pub mod responses; -pub mod test_environment; pub mod v1; use percent_encoding::NON_ALPHANUMERIC; diff --git a/tests/servers/http/requests/announce.rs b/packages/axum-http-tracker-server/tests/server/requests/announce.rs similarity index 87% rename from tests/servers/http/requests/announce.rs rename to packages/axum-http-tracker-server/tests/server/requests/announce.rs index 20c5ddaa7..5a670b618 100644 --- a/tests/servers/http/requests/announce.rs +++ b/packages/axum-http-tracker-server/tests/server/requests/announce.rs @@ -2,11 +2,11 @@ use std::fmt; use std::net::{IpAddr, Ipv4Addr}; use std::str::FromStr; +use aquatic_udp_protocol::PeerId; +use bittorrent_primitives::info_hash::InfoHash; use serde_repr::Serialize_repr; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -use torrust_tracker::tracker::peer::Id; -use crate::servers::http::{percent_encode_byte_array, ByteArray20}; +use crate::server::{percent_encode_byte_array, ByteArray20}; pub struct Query { pub info_hash: ByteArray20, @@ -18,10 +18,11 @@ pub struct Query { pub left: BaseTenASCII, pub event: Option, pub compact: Option, + pub numwant: Option, } impl fmt::Display for Query { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.build()) } } @@ -57,7 +58,7 @@ pub enum Event { } impl fmt::Display for Event { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { //Event::Started => write!(f, "started"), //Event::Stopped => write!(f, "stopped"), @@ -74,7 +75,7 @@ pub enum Compact { } impl fmt::Display for Compact { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Compact::Accepted => write!(f, "1"), Compact::NotAccepted => write!(f, "0"), @@ -93,11 +94,12 @@ impl QueryBuilder { peer_addr: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 88)), downloaded: 0, uploaded: 0, - peer_id: Id(*b"-qB00000000000000001").0, + peer_id: PeerId(*b"-qB00000000000000001").0, port: 17548, left: 0, event: Some(Event::Completed), compact: Some(Compact::NotAccepted), + numwant: None, }; Self { announce_query: default_announce_query, @@ -109,7 +111,7 @@ impl QueryBuilder { self } - pub fn with_peer_id(mut self, peer_id: &Id) -> Self { + pub fn with_peer_id(mut self, peer_id: &PeerId) -> Self { self.announce_query.peer_id = peer_id.0; self } @@ -124,6 +126,11 @@ impl QueryBuilder { self } + pub fn with_port(mut self, port: u16) -> Self { + self.announce_query.port = port; + self + } + pub fn without_compact(mut self) -> Self { self.announce_query.compact = None; self @@ -149,7 +156,9 @@ impl QueryBuilder { /// left=0 /// event=completed /// compact=0 +/// numwant=50 /// ``` +#[derive(Debug)] pub struct QueryParams { pub info_hash: Option, pub peer_addr: Option, @@ -160,10 +169,11 @@ pub struct QueryParams { pub left: Option, pub event: Option, pub compact: Option, + pub numwant: Option, } impl std::fmt::Display for QueryParams { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut params = vec![]; if let Some(info_hash) = &self.info_hash { @@ -193,6 +203,9 @@ impl std::fmt::Display for QueryParams { if let Some(compact) = &self.compact { params.push(("compact", compact)); } + if let Some(numwant) = &self.numwant { + params.push(("numwant", numwant)); + } let query = params .iter() @@ -208,6 +221,7 @@ impl QueryParams { pub fn from(announce_query: &Query) -> Self { let event = announce_query.event.as_ref().map(std::string::ToString::to_string); let compact = announce_query.compact.as_ref().map(std::string::ToString::to_string); + let numwant = announce_query.numwant.map(|numwant| numwant.to_string()); Self { info_hash: Some(percent_encode_byte_array(&announce_query.info_hash)), @@ -219,6 +233,7 @@ impl QueryParams { left: Some(announce_query.left.to_string()), event, compact, + numwant, } } @@ -241,6 +256,7 @@ impl QueryParams { self.left = None; self.event = None; self.compact = None; + self.numwant = None; } pub fn set(&mut self, param_name: &str, param_value: &str) { @@ -254,6 +270,7 @@ impl QueryParams { "left" => self.left = Some(param_value.to_string()), "event" => self.event = Some(param_value.to_string()), "compact" => self.compact = Some(param_value.to_string()), + "numwant" => self.numwant = Some(param_value.to_string()), &_ => panic!("Invalid param name for announce query"), } } diff --git a/tests/servers/http/requests/mod.rs b/packages/axum-http-tracker-server/tests/server/requests/mod.rs similarity index 100% rename from tests/servers/http/requests/mod.rs rename to packages/axum-http-tracker-server/tests/server/requests/mod.rs diff --git a/tests/servers/http/requests/scrape.rs b/packages/axum-http-tracker-server/tests/server/requests/scrape.rs similarity index 91% rename from tests/servers/http/requests/scrape.rs rename to packages/axum-http-tracker-server/tests/server/requests/scrape.rs index 9e4257d6c..afd8cfbe3 100644 --- a/tests/servers/http/requests/scrape.rs +++ b/packages/axum-http-tracker-server/tests/server/requests/scrape.rs @@ -1,16 +1,16 @@ use std::fmt; use std::str::FromStr; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; +use bittorrent_primitives::info_hash::InfoHash; -use crate::servers::http::{percent_encode_byte_array, ByteArray20}; +use crate::server::{percent_encode_byte_array, ByteArray20}; pub struct Query { pub info_hash: Vec, } impl fmt::Display for Query { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.build()) } } @@ -93,7 +93,7 @@ impl QueryParams { } impl std::fmt::Display for QueryParams { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let query = self .info_hash .iter() diff --git a/tests/servers/http/responses/announce.rs b/packages/axum-http-tracker-server/tests/server/responses/announce.rs similarity index 92% rename from tests/servers/http/responses/announce.rs rename to packages/axum-http-tracker-server/tests/server/responses/announce.rs index 8a07ebd5e..554e5ab40 100644 --- a/tests/servers/http/responses/announce.rs +++ b/packages/axum-http-tracker-server/tests/server/responses/announce.rs @@ -1,7 +1,8 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use serde::{self, Deserialize, Serialize}; -use torrust_tracker::tracker::peer::Peer; +use serde::{Deserialize, Serialize}; +use torrust_tracker_primitives::peer; +use zerocopy::AsBytes as _; #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Announce { @@ -22,10 +23,10 @@ pub struct DictionaryPeer { pub port: u16, } -impl From for DictionaryPeer { - fn from(peer: Peer) -> Self { +impl From for DictionaryPeer { + fn from(peer: peer::Peer) -> Self { DictionaryPeer { - peer_id: peer.peer_id.to_bytes().to_vec(), + peer_id: peer.peer_id.as_bytes().to_vec(), ip: peer.peer_addr.ip().to_string(), port: peer.peer_addr.port(), } diff --git a/tests/servers/http/responses/error.rs b/packages/axum-http-tracker-server/tests/server/responses/error.rs similarity index 77% rename from tests/servers/http/responses/error.rs rename to packages/axum-http-tracker-server/tests/server/responses/error.rs index 12c53a0cf..00befdb54 100644 --- a/tests/servers/http/responses/error.rs +++ b/packages/axum-http-tracker-server/tests/server/responses/error.rs @@ -1,4 +1,4 @@ -use serde::{self, Deserialize, Serialize}; +use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Error { diff --git a/tests/servers/http/responses/mod.rs b/packages/axum-http-tracker-server/tests/server/responses/mod.rs similarity index 100% rename from tests/servers/http/responses/mod.rs rename to packages/axum-http-tracker-server/tests/server/responses/mod.rs diff --git a/tests/servers/http/responses/scrape.rs b/packages/axum-http-tracker-server/tests/server/responses/scrape.rs similarity index 96% rename from tests/servers/http/responses/scrape.rs rename to packages/axum-http-tracker-server/tests/server/responses/scrape.rs index 221ff0a38..5de15c731 100644 --- a/tests/servers/http/responses/scrape.rs +++ b/packages/axum-http-tracker-server/tests/server/responses/scrape.rs @@ -1,10 +1,10 @@ use std::collections::HashMap; use std::str; -use serde::{self, Deserialize, Serialize}; +use serde::{Deserialize, Serialize}; use serde_bencode::value::Value; -use crate::servers::http::{ByteArray20, InfoHash}; +use crate::server::{ByteArray20, InfoHash}; #[derive(Debug, PartialEq, Default)] pub struct Response { @@ -73,9 +73,13 @@ impl ResponseBuilder { #[derive(Debug)] pub enum BencodeParseError { + #[allow(dead_code)] InvalidValueExpectedDict { value: Value }, + #[allow(dead_code)] InvalidValueExpectedInt { value: Value }, + #[allow(dead_code)] InvalidFileField { value: Value }, + #[allow(dead_code)] MissingFileField { field_name: String }, } diff --git a/tests/servers/http/v1/contract.rs b/packages/axum-http-tracker-server/tests/server/v1/contract.rs similarity index 51% rename from tests/servers/http/v1/contract.rs rename to packages/axum-http-tracker-server/tests/server/v1/contract.rs index b508dfc39..85792f922 100644 --- a/tests/servers/http/v1/contract.rs +++ b/packages/axum-http-tracker-server/tests/server/v1/contract.rs @@ -1,56 +1,79 @@ -use torrust_tracker_test_helpers::configuration; - -use crate::servers::http::test_environment::running_test_environment; - -pub type V1 = torrust_tracker::servers::http::v1::launcher::Launcher; +use torrust_axum_http_tracker_server::environment::Started; +use torrust_tracker_test_helpers::{configuration, logging}; #[tokio::test] -async fn test_environment_should_be_started_and_stopped() { - let test_env = running_test_environment::(configuration::ephemeral()).await; +async fn environment_should_be_started_and_stopped() { + logging::setup(); - test_env.stop().await; + let env = Started::new(&configuration::ephemeral().into()).await; + + env.stop().await; } mod for_all_config_modes { + use torrust_axum_http_tracker_server::environment::Started; + use torrust_axum_http_tracker_server::v1::handlers::health_check::{Report, Status}; + use torrust_tracker_test_helpers::{configuration, logging}; + + use crate::server::client::Client; + + #[tokio::test] + async fn health_check_endpoint_should_return_ok_if_the_http_tracker_is_running() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral_with_reverse_proxy().into()).await; + + let response = Client::new(*env.bind_address()).health_check().await; + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + assert_eq!(response.json::().await.unwrap(), Report { status: Status::Ok }); + + env.stop().await; + } + mod and_running_on_reverse_proxy { - use torrust_tracker_test_helpers::configuration; + use torrust_axum_http_tracker_server::environment::Started; + use torrust_tracker_test_helpers::{configuration, logging}; - use crate::servers::http::asserts::assert_could_not_find_remote_address_on_x_forwarded_for_header_error_response; - use crate::servers::http::client::Client; - use crate::servers::http::requests::announce::QueryBuilder; - use crate::servers::http::test_environment::running_test_environment; - use crate::servers::http::v1::contract::V1; + use crate::server::asserts::assert_could_not_find_remote_address_on_x_forwarded_for_header_error_response; + use crate::server::client::Client; + use crate::server::requests::announce::QueryBuilder; #[tokio::test] async fn should_fail_when_the_http_request_does_not_include_the_xff_http_request_header() { + logging::setup(); + // If the tracker is running behind a reverse proxy, the peer IP is the // right most IP in the `X-Forwarded-For` HTTP header, which is the IP of the proxy's client. - let test_env = running_test_environment::(configuration::ephemeral_with_reverse_proxy()).await; + let env = Started::new(&configuration::ephemeral_with_reverse_proxy().into()).await; let params = QueryBuilder::default().query().params(); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_could_not_find_remote_address_on_x_forwarded_for_header_error_response(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_xff_http_request_header_contains_an_invalid_ip() { - let test_env = running_test_environment::(configuration::ephemeral_with_reverse_proxy()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral_with_reverse_proxy().into()).await; let params = QueryBuilder::default().query().params(); - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .get_with_header(&format!("announce?{params}"), "X-Forwarded-For", "INVALID IP") .await; assert_could_not_find_remote_address_on_x_forwarded_for_header_error_response(response).await; - test_env.stop().await; + env.stop().await; } } @@ -67,72 +90,89 @@ mod for_all_config_modes { // Vuze (bittorrent client) docs: // https://wiki.vuze.com/w/Announce - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV6}; use std::str::FromStr; + use aquatic_udp_protocol::PeerId; + use bittorrent_primitives::info_hash::InfoHash; use local_ip_address::local_ip; - use reqwest::Response; - use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; - use torrust_tracker::tracker::peer; - use torrust_tracker_test_helpers::configuration; - - use crate::common::fixtures::{invalid_info_hashes, PeerBuilder}; - use crate::servers::http::asserts::{ + use reqwest::{Response, StatusCode}; + use tokio::net::TcpListener; + use torrust_axum_http_tracker_server::environment::Started; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_test_helpers::{configuration, logging}; + + use crate::common::fixtures::invalid_info_hashes; + use crate::server::asserts::{ assert_announce_response, assert_bad_announce_request_error_response, assert_cannot_parse_query_param_error_response, - assert_cannot_parse_query_params_error_response, assert_compact_announce_response, assert_empty_announce_response, - assert_is_announce_response, assert_missing_query_params_for_announce_request_error_response, + assert_cannot_parse_query_params_error_response, assert_compact_announce_response, assert_is_announce_response, + assert_missing_query_params_for_announce_request_error_response, }; - use crate::servers::http::client::Client; - use crate::servers::http::requests::announce::{Compact, QueryBuilder}; - use crate::servers::http::responses; - use crate::servers::http::responses::announce::{Announce, CompactPeer, CompactPeerList, DictionaryPeer}; - use crate::servers::http::test_environment::running_test_environment; - use crate::servers::http::v1::contract::V1; + use crate::server::client::Client; + use crate::server::requests::announce::{Compact, QueryBuilder}; + use crate::server::responses; + use crate::server::responses::announce::{Announce, CompactPeer, CompactPeerList, DictionaryPeer}; + + #[tokio::test] + async fn it_should_start_and_stop() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral_public().into()).await; + env.stop().await; + } #[tokio::test] async fn should_respond_if_only_the_mandatory_fields_are_provided() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); params.remove_optional_params(); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_is_announce_response(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_url_query_component_is_empty() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; - let response = Client::new(*test_env.bind_address()).get("announce").await; + let response = Client::new(*env.bind_address()).get("announce").await; assert_missing_query_params_for_announce_request_error_response(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_url_query_parameters_are_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_query_param = "a=b=c"; - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .get(&format!("announce?{invalid_query_param}")) .await; assert_cannot_parse_query_param_error_response(response, "invalid param a=b=c").await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_a_mandatory_field_is_missing() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; // Without `info_hash` param @@ -140,7 +180,7 @@ mod for_all_config_modes { params.info_hash = None; - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "missing param info_hash").await; @@ -150,7 +190,7 @@ mod for_all_config_modes { params.peer_id = None; - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "missing param peer_id").await; @@ -160,53 +200,59 @@ mod for_all_config_modes { params.port = None; - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "missing param port").await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_info_hash_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); for invalid_value in &invalid_info_hashes() { params.set("info_hash", invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_cannot_parse_query_params_error_response(response, "").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_not_fail_when_the_peer_address_param_is_invalid() { + logging::setup(); + // AnnounceQuery does not even contain the `peer_addr` // The peer IP is obtained in two ways: // 1. If tracker is NOT running `on_reverse_proxy` from the remote client IP. // 2. If tracker is running `on_reverse_proxy` from `X-Forwarded-For` request HTTP header. - let test_env = running_test_environment::(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); params.peer_addr = Some("INVALID-IP-ADDRESS".to_string()); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_is_announce_response(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_downloaded_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -215,17 +261,19 @@ mod for_all_config_modes { for invalid_value in invalid_values { params.set("downloaded", invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "invalid param value").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_uploaded_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -234,17 +282,19 @@ mod for_all_config_modes { for invalid_value in invalid_values { params.set("uploaded", invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "invalid param value").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_peer_id_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -260,17 +310,19 @@ mod for_all_config_modes { for invalid_value in invalid_values { params.set("peer_id", invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "invalid param value").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_port_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -279,17 +331,19 @@ mod for_all_config_modes { for invalid_value in invalid_values { params.set("port", invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "invalid param value").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_left_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -298,17 +352,19 @@ mod for_all_config_modes { for invalid_value in invalid_values { params.set("left", invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "invalid param value").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_event_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -325,17 +381,19 @@ mod for_all_config_modes { for invalid_value in invalid_values { params.set("event", invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "invalid param value").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_compact_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -344,114 +402,145 @@ mod for_all_config_modes { for invalid_value in invalid_values { params.set("compact", invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "invalid param value").await; } - test_env.stop().await; + env.stop().await; + } + + #[tokio::test] + async fn should_fail_when_the_numwant_param_is_invalid() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let mut params = QueryBuilder::default().query().params(); + + let invalid_values = ["-1", "1.1", "a"]; + + for invalid_value in invalid_values { + params.set("numwant", invalid_value); + + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; + + assert_bad_announce_request_error_response(response, "invalid param value").await; + } + + env.stop().await; } #[tokio::test] async fn should_return_no_peers_if_the_announced_peer_is_the_first_one() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral_public().into()).await; - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .announce( &QueryBuilder::default() - .with_info_hash(&InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap()) + .with_info_hash(&InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap()) // DevSkim: ignore DS173237 .query(), ) .await; + let announce_policy = env.container.tracker_core_container.core_config.announce_policy; + assert_announce_response( response, &Announce { complete: 1, // the peer for this test incomplete: 0, - interval: test_env.tracker.config.announce_interval, - min_interval: test_env.tracker.config.min_announce_interval, + interval: announce_policy.interval, + min_interval: announce_policy.interval_min, peers: vec![], }, ) .await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_return_the_list_of_previously_announced_peers() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + logging::setup(); - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let env = Started::new(&configuration::ephemeral_public().into()).await; + + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 // Peer 1 - let previously_announced_peer = PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .build(); + let previously_announced_peer = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000001")).build(); // Add the Peer 1 - test_env.add_torrent_peer(&info_hash, &previously_announced_peer).await; + env.add_torrent_peer(&info_hash, &previously_announced_peer).await; // Announce the new Peer 2. This new peer is non included on the response peer list - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .announce( &QueryBuilder::default() .with_info_hash(&info_hash) - .with_peer_id(&peer::Id(*b"-qB00000000000000002")) + .with_peer_id(&PeerId(*b"-qB00000000000000002")) .query(), ) .await; + let announce_policy = env.container.tracker_core_container.core_config.announce_policy; + // It should only contain the previously announced peer assert_announce_response( response, &Announce { complete: 2, incomplete: 0, - interval: test_env.tracker.config.announce_interval, - min_interval: test_env.tracker.config.min_announce_interval, + interval: announce_policy.interval, + min_interval: announce_policy.interval_min, peers: vec![DictionaryPeer::from(previously_announced_peer)], }, ) .await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_return_the_list_of_previously_announced_peers_including_peers_using_ipv4_and_ipv6() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + logging::setup(); - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let env = Started::new(&configuration::ephemeral_public().into()).await; + + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 // Announce a peer using IPV4 let peer_using_ipv4 = PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), 8080)) .build(); - test_env.add_torrent_peer(&info_hash, &peer_using_ipv4).await; + env.add_torrent_peer(&info_hash, &peer_using_ipv4).await; // Announce a peer using IPV6 let peer_using_ipv6 = PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000002")) + .with_peer_id(&PeerId(*b"-qB00000000000000002")) .with_peer_addr(&SocketAddr::new( IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), 8080, )) .build(); - test_env.add_torrent_peer(&info_hash, &peer_using_ipv6).await; + env.add_torrent_peer(&info_hash, &peer_using_ipv6).await; // Announce the new Peer. - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .announce( &QueryBuilder::default() .with_info_hash(&info_hash) - .with_peer_id(&peer::Id(*b"-qB00000000000000003")) + .with_peer_id(&PeerId(*b"-qB00000000000000003")) .query(), ) .await; + let announce_policy = env.container.tracker_core_container.core_config.announce_policy; + // The newly announced peer is not included on the response peer list, // but all the previously announced peers should be included regardless the IP version they are using. assert_announce_response( @@ -459,63 +548,91 @@ mod for_all_config_modes { &Announce { complete: 3, incomplete: 0, - interval: test_env.tracker.config.announce_interval, - min_interval: test_env.tracker.config.min_announce_interval, + interval: announce_policy.interval, + min_interval: announce_policy.interval_min, peers: vec![DictionaryPeer::from(peer_using_ipv4), DictionaryPeer::from(peer_using_ipv6)], }, ) .await; - test_env.stop().await; + env.stop().await; } #[tokio::test] - async fn should_consider_two_peers_to_be_the_same_when_they_have_the_same_peer_id_even_if_the_ip_is_different() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + async fn should_consider_two_peers_to_be_the_same_when_they_have_the_same_socket_address_even_if_the_peer_id_is_different( + ) { + logging::setup(); - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - let peer = PeerBuilder::default().build(); + let env = Started::new(&configuration::ephemeral_public().into()).await; - // Add a peer - test_env.add_torrent_peer(&info_hash, &peer).await; + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 + let peer = PeerBuilder::default().build(); - let announce_query = QueryBuilder::default() + let announce_query_1 = QueryBuilder::default() .with_info_hash(&info_hash) .with_peer_id(&peer.peer_id) + .with_peer_addr(&peer.peer_addr.ip()) + .with_port(peer.peer_addr.port()) .query(); - assert_ne!(peer.peer_addr.ip(), announce_query.peer_addr); + let announce_query_2 = QueryBuilder::default() + .with_info_hash(&info_hash) + .with_peer_id(&PeerId(*b"-qB00000000000000002")) // Different peer ID + .with_peer_addr(&peer.peer_addr.ip()) + .with_port(peer.peer_addr.port()) + .query(); + + // Same peer socket address + assert_eq!(announce_query_1.peer_addr, announce_query_2.peer_addr); + assert_eq!(announce_query_1.port, announce_query_2.port); + + // Different peer ID + assert_ne!(announce_query_1.peer_id, announce_query_2.peer_id); - let response = Client::new(*test_env.bind_address()).announce(&announce_query).await; + let _response = Client::new(*env.bind_address()).announce(&announce_query_1).await; + let response = Client::new(*env.bind_address()).announce(&announce_query_2).await; - assert_empty_announce_response(response).await; + let announce_policy = env.container.tracker_core_container.core_config.announce_policy; + + // The response should contain only the first peer. + assert_announce_response( + response, + &Announce { + complete: 1, + incomplete: 0, + interval: announce_policy.interval, + min_interval: announce_policy.interval_min, + peers: vec![], + }, + ) + .await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_return_the_compact_response() { + logging::setup(); + // Tracker Returns Compact Peer Lists // https://www.bittorrent.org/beps/bep_0023.html - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 // Peer 1 - let previously_announced_peer = PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .build(); + let previously_announced_peer = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000001")).build(); // Add the Peer 1 - test_env.add_torrent_peer(&info_hash, &previously_announced_peer).await; + env.add_torrent_peer(&info_hash, &previously_announced_peer).await; // Announce the new Peer 2 accepting compact responses - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .announce( &QueryBuilder::default() .with_info_hash(&info_hash) - .with_peer_id(&peer::Id(*b"-qB00000000000000002")) + .with_peer_id(&PeerId(*b"-qB00000000000000002")) .with_compact(Compact::Accepted) .query(), ) @@ -531,34 +648,34 @@ mod for_all_config_modes { assert_compact_announce_response(response, &expected_response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_not_return_the_compact_response_by_default() { + logging::setup(); + // code-review: the HTTP tracker does not return the compact response by default if the "compact" // param is not provided in the announce URL. The BEP 23 suggest to do so. - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 // Peer 1 - let previously_announced_peer = PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .build(); + let previously_announced_peer = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000001")).build(); // Add the Peer 1 - test_env.add_torrent_peer(&info_hash, &previously_announced_peer).await; + env.add_torrent_peer(&info_hash, &previously_announced_peer).await; // Announce the new Peer 2 without passing the "compact" param // By default it should respond with the compact peer list // https://www.bittorrent.org/beps/bep_0023.html - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .announce( &QueryBuilder::default() .with_info_hash(&info_hash) - .with_peer_id(&peer::Id(*b"-qB00000000000000002")) + .with_peer_id(&PeerId(*b"-qB00000000000000002")) .without_compact() .query(), ) @@ -566,7 +683,7 @@ mod for_all_config_modes { assert!(!is_a_compact_announce_response(response).await); - test_env.stop().await; + env.stop().await; } async fn is_a_compact_announce_response(response: Response) -> bool { @@ -576,247 +693,248 @@ mod for_all_config_modes { } #[tokio::test] - async fn should_increase_the_number_of_tcp4_connections_handled_in_statistics() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; - - Client::new(*test_env.bind_address()) - .announce(&QueryBuilder::default().query()) - .await; - - let stats = test_env.tracker.get_stats().await; - - assert_eq!(stats.tcp4_connections_handled, 1); - - drop(stats); + async fn should_increase_the_number_of_tcp4_announce_requests_handled_in_statistics() { + logging::setup(); - test_env.stop().await; - } + let env = Started::new(&configuration::ephemeral_public().into()).await; - #[tokio::test] - async fn should_increase_the_number_of_tcp6_connections_handled_in_statistics() { - let test_env = running_test_environment::(configuration::ephemeral_ipv6()).await; - - Client::bind(*test_env.bind_address(), IpAddr::from_str("::1").unwrap()) + Client::new(*env.bind_address()) .announce(&QueryBuilder::default().query()) .await; - let stats = test_env.tracker.get_stats().await; + let stats = env.container.http_tracker_core_container.stats_repository.get_stats().await; - assert_eq!(stats.tcp6_connections_handled, 1); + assert_eq!(stats.tcp4_announces_handled(), 1); drop(stats); - test_env.stop().await; + env.stop().await; } #[tokio::test] - async fn should_not_increase_the_number_of_tcp6_connections_handled_if_the_client_is_not_using_an_ipv6_ip() { - // The tracker ignores the peer address in the request param. It uses the client remote ip address. - - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; - - Client::new(*test_env.bind_address()) - .announce( - &QueryBuilder::default() - .with_peer_addr(&IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1))) - .query(), - ) - .await; - - let stats = test_env.tracker.get_stats().await; - - assert_eq!(stats.tcp6_connections_handled, 0); - - drop(stats); - - test_env.stop().await; - } - - #[tokio::test] - async fn should_increase_the_number_of_tcp4_announce_requests_handled_in_statistics() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; - - Client::new(*test_env.bind_address()) - .announce(&QueryBuilder::default().query()) - .await; - - let stats = test_env.tracker.get_stats().await; - - assert_eq!(stats.tcp4_announces_handled, 1); - - drop(stats); + async fn should_increase_the_number_of_tcp6_announce_requests_handled_in_statistics() { + logging::setup(); - test_env.stop().await; - } + if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) + .await + .is_err() + { + return; // we cannot bind to a ipv6 socket, so we will skip this test + } - #[tokio::test] - async fn should_increase_the_number_of_tcp6_announce_requests_handled_in_statistics() { - let test_env = running_test_environment::(configuration::ephemeral_ipv6()).await; + let env = Started::new(&configuration::ephemeral_ipv6().into()).await; - Client::bind(*test_env.bind_address(), IpAddr::from_str("::1").unwrap()) + Client::bind(*env.bind_address(), IpAddr::from_str("::1").unwrap()) .announce(&QueryBuilder::default().query()) .await; - let stats = test_env.tracker.get_stats().await; + let stats = env.container.http_tracker_core_container.stats_repository.get_stats().await; - assert_eq!(stats.tcp6_announces_handled, 1); + assert_eq!(stats.tcp6_announces_handled(), 1); drop(stats); - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_not_increase_the_number_of_tcp6_announce_requests_handled_if_the_client_is_not_using_an_ipv6_ip() { + logging::setup(); + // The tracker ignores the peer address in the request param. It uses the client remote ip address. - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; - Client::new(*test_env.bind_address()) + Client::new(*env.bind_address()) .announce( &QueryBuilder::default() - .with_peer_addr(&IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1))) + .with_peer_addr(&IpAddr::V6(Ipv6Addr::LOCALHOST)) .query(), ) .await; - let stats = test_env.tracker.get_stats().await; + let stats = env.container.http_tracker_core_container.stats_repository.get_stats().await; - assert_eq!(stats.tcp6_announces_handled, 0); + assert_eq!(stats.tcp6_announces_handled(), 0); drop(stats); - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_assign_to_the_peer_ip_the_remote_client_ip_instead_of_the_peer_address_in_the_request_param() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + logging::setup(); - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - let client_ip = local_ip().unwrap(); + let env = Started::new(&configuration::ephemeral_public().into()).await; - let client = Client::bind(*test_env.bind_address(), client_ip); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 + let client_ip = local_ip().unwrap(); let announce_query = QueryBuilder::default() .with_info_hash(&info_hash) .with_peer_addr(&IpAddr::from_str("2.2.2.2").unwrap()) .query(); - client.announce(&announce_query).await; + { + let client = Client::bind(*env.bind_address(), client_ip); + let status = client.announce(&announce_query).await.status(); - let peers = test_env.tracker.get_all_torrent_peers(&info_hash).await; + assert_eq!(status, StatusCode::OK); + } + + let peers = env + .container + .tracker_core_container + .in_memory_torrent_repository + .get_torrent_peers(&info_hash) + .await; let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), client_ip); assert_ne!(peer_addr.ip(), IpAddr::from_str("2.2.2.2").unwrap()); - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn when_the_client_ip_is_a_loopback_ipv4_it_should_assign_to_the_peer_ip_the_external_ip_in_the_tracker_configuration( ) { + logging::setup(); + /* We assume that both the client and tracker share the same public IP. client <-> tracker <-> Internet 127.0.0.1 external_ip = "2.137.87.41" */ + let env = + Started::new(&configuration::ephemeral_with_external_ip(IpAddr::from_str("2.137.87.41").unwrap()).into()).await; - let test_env = running_test_environment::(configuration::ephemeral_with_external_ip( - IpAddr::from_str("2.137.87.41").unwrap(), - )) - .await; - - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 let loopback_ip = IpAddr::from_str("127.0.0.1").unwrap(); let client_ip = loopback_ip; - let client = Client::bind(*test_env.bind_address(), client_ip); - let announce_query = QueryBuilder::default() .with_info_hash(&info_hash) .with_peer_addr(&IpAddr::from_str("2.2.2.2").unwrap()) .query(); - client.announce(&announce_query).await; + { + let client = Client::bind(*env.bind_address(), client_ip); + let status = client.announce(&announce_query).await.status(); - let peers = test_env.tracker.get_all_torrent_peers(&info_hash).await; + assert_eq!(status, StatusCode::OK); + } + + let peers = env + .container + .tracker_core_container + .in_memory_torrent_repository + .get_torrent_peers(&info_hash) + .await; let peer_addr = peers[0].peer_addr; - assert_eq!(peer_addr.ip(), test_env.tracker.config.get_ext_ip().unwrap()); + assert_eq!( + peer_addr.ip(), + env.container.tracker_core_container.core_config.net.external_ip.unwrap() + ); assert_ne!(peer_addr.ip(), IpAddr::from_str("2.2.2.2").unwrap()); - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn when_the_client_ip_is_a_loopback_ipv6_it_should_assign_to_the_peer_ip_the_external_ip_in_the_tracker_configuration( ) { + logging::setup(); + /* We assume that both the client and tracker share the same public IP. client <-> tracker <-> Internet ::1 external_ip = "2345:0425:2CA1:0000:0000:0567:5673:23b5" */ - let test_env = running_test_environment::(configuration::ephemeral_with_external_ip( - IpAddr::from_str("2345:0425:2CA1:0000:0000:0567:5673:23b5").unwrap(), - )) + let env = Started::new( + &configuration::ephemeral_with_external_ip(IpAddr::from_str("2345:0425:2CA1:0000:0000:0567:5673:23b5").unwrap()) + .into(), + ) .await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 let loopback_ip = IpAddr::from_str("127.0.0.1").unwrap(); let client_ip = loopback_ip; - let client = Client::bind(*test_env.bind_address(), client_ip); - let announce_query = QueryBuilder::default() .with_info_hash(&info_hash) .with_peer_addr(&IpAddr::from_str("2.2.2.2").unwrap()) .query(); - client.announce(&announce_query).await; + { + let client = Client::bind(*env.bind_address(), client_ip); + let status = client.announce(&announce_query).await.status(); - let peers = test_env.tracker.get_all_torrent_peers(&info_hash).await; + assert_eq!(status, StatusCode::OK); + } + + let peers = env + .container + .tracker_core_container + .in_memory_torrent_repository + .get_torrent_peers(&info_hash) + .await; let peer_addr = peers[0].peer_addr; - assert_eq!(peer_addr.ip(), test_env.tracker.config.get_ext_ip().unwrap()); + assert_eq!( + peer_addr.ip(), + env.container.tracker_core_container.core_config.net.external_ip.unwrap() + ); assert_ne!(peer_addr.ip(), IpAddr::from_str("2.2.2.2").unwrap()); - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn when_the_tracker_is_behind_a_reverse_proxy_it_should_assign_to_the_peer_ip_the_ip_in_the_x_forwarded_for_http_header( ) { + logging::setup(); + /* client <-> http proxy <-> tracker <-> Internet ip: header: config: peer addr: 145.254.214.256 X-Forwarded-For = 145.254.214.256 on_reverse_proxy = true 145.254.214.256 */ - let test_env = running_test_environment::(configuration::ephemeral_with_reverse_proxy()).await; + let env = Started::new(&configuration::ephemeral_with_reverse_proxy().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - - let client = Client::new(*test_env.bind_address()); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 let announce_query = QueryBuilder::default().with_info_hash(&info_hash).query(); - client - .announce_with_header( - &announce_query, - "X-Forwarded-For", - "203.0.113.195,2001:db8:85a3:8d3:1319:8a2e:370:7348,150.172.238.178", - ) - .await; + { + let client = Client::new(*env.bind_address()); + let status = client + .announce_with_header( + &announce_query, + "X-Forwarded-For", + "203.0.113.195,2001:db8:85a3:8d3:1319:8a2e:370:7348,150.172.238.178", + ) + .await + .status(); + + assert_eq!(status, StatusCode::OK); + } - let peers = test_env.tracker.get_all_torrent_peers(&info_hash).await; + let peers = env + .container + .tracker_core_container + .in_memory_torrent_repository + .get_torrent_peers(&info_hash) + .await; let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), IpAddr::from_str("150.172.238.178").unwrap()); - test_env.stop().await; + env.stop().await; } } @@ -830,70 +948,76 @@ mod for_all_config_modes { // Vuze (bittorrent client) docs: // https://wiki.vuze.com/w/Scrape - use std::net::IpAddr; + use std::net::{IpAddr, Ipv6Addr, SocketAddrV6}; use std::str::FromStr; - use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; - use torrust_tracker::tracker::peer; - use torrust_tracker_test_helpers::configuration; + use aquatic_udp_protocol::PeerId; + use bittorrent_primitives::info_hash::InfoHash; + use tokio::net::TcpListener; + use torrust_axum_http_tracker_server::environment::Started; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_test_helpers::{configuration, logging}; - use crate::common::fixtures::{invalid_info_hashes, PeerBuilder}; - use crate::servers::http::asserts::{ + use crate::common::fixtures::invalid_info_hashes; + use crate::server::asserts::{ assert_cannot_parse_query_params_error_response, assert_missing_query_params_for_scrape_request_error_response, assert_scrape_response, }; - use crate::servers::http::client::Client; - use crate::servers::http::requests; - use crate::servers::http::requests::scrape::QueryBuilder; - use crate::servers::http::responses::scrape::{self, File, ResponseBuilder}; - use crate::servers::http::test_environment::running_test_environment; - use crate::servers::http::v1::contract::V1; - - //#[tokio::test] + use crate::server::client::Client; + use crate::server::requests; + use crate::server::requests::scrape::QueryBuilder; + use crate::server::responses::scrape::{self, File, ResponseBuilder}; + + #[tokio::test] #[allow(dead_code)] async fn should_fail_when_the_request_is_empty() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; - let response = Client::new(*test_env.bind_address()).get("scrape").await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral_public().into()).await; + let response = Client::new(*env.bind_address()).get("scrape").await; assert_missing_query_params_for_scrape_request_error_response(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_info_hash_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral_public().into()).await; let mut params = QueryBuilder::default().query().params(); for invalid_value in &invalid_info_hashes() { params.set_one_info_hash_param(invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_cannot_parse_query_params_error_response(response, "").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_return_the_file_with_the_incomplete_peer_when_there_is_one_peer_with_bytes_pending_to_download() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + logging::setup(); - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let env = Started::new(&configuration::ephemeral_public().into()).await; - test_env - .add_torrent_peer( - &info_hash, - &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) - .build(), - ) - .await; + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 - let response = Client::new(*test_env.bind_address()) + env.add_torrent_peer( + &info_hash, + &PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000001")) + .with_bytes_left_to_download(1) + .build(), + ) + .await; + + let response = Client::new(*env.bind_address()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -914,26 +1038,27 @@ mod for_all_config_modes { assert_scrape_response(response, &expected_scrape_response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_return_the_file_with_the_complete_peer_when_there_is_one_peer_with_no_bytes_pending_to_download() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + logging::setup(); - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let env = Started::new(&configuration::ephemeral_public().into()).await; - test_env - .add_torrent_peer( - &info_hash, - &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .with_no_bytes_pending_to_download() - .build(), - ) - .await; + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 + + env.add_torrent_peer( + &info_hash, + &PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000001")) + .with_no_bytes_left_to_download() + .build(), + ) + .await; - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -954,16 +1079,18 @@ mod for_all_config_modes { assert_scrape_response(response, &expected_scrape_response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_return_a_file_with_zeroed_values_when_there_are_no_peers() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + logging::setup(); - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let env = Started::new(&configuration::ephemeral_public().into()).await; - let response = Client::new(*test_env.bind_address()) + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 + + let response = Client::new(*env.bind_address()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -973,17 +1100,19 @@ mod for_all_config_modes { assert_scrape_response(response, &scrape::Response::with_one_file(info_hash.bytes(), File::zeroed())).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_accept_multiple_infohashes() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral_public().into()).await; - let info_hash1 = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - let info_hash2 = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(); + let info_hash1 = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 + let info_hash2 = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(); // DevSkim: ignore DS173237 - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .scrape( &requests::scrape::QueryBuilder::default() .add_info_hash(&info_hash1) @@ -999,16 +1128,18 @@ mod for_all_config_modes { assert_scrape_response(response, &expected_scrape_response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_increase_the_number_ot_tcp4_scrape_requests_handled_in_statistics() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + logging::setup(); - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let env = Started::new(&configuration::ephemeral_public().into()).await; - Client::new(*test_env.bind_address()) + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 + + Client::new(*env.bind_address()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -1016,22 +1147,31 @@ mod for_all_config_modes { ) .await; - let stats = test_env.tracker.get_stats().await; + let stats = env.container.http_tracker_core_container.stats_repository.get_stats().await; - assert_eq!(stats.tcp4_scrapes_handled, 1); + assert_eq!(stats.tcp4_scrapes_handled(), 1); drop(stats); - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_increase_the_number_ot_tcp6_scrape_requests_handled_in_statistics() { - let test_env = running_test_environment::(configuration::ephemeral_ipv6()).await; + logging::setup(); - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) + .await + .is_err() + { + return; // we cannot bind to a ipv6 socket, so we will skip this test + } - Client::bind(*test_env.bind_address(), IpAddr::from_str("::1").unwrap()) + let env = Started::new(&configuration::ephemeral_ipv6().into()).await; + + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 + + Client::bind(*env.bind_address(), IpAddr::from_str("::1").unwrap()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -1039,13 +1179,13 @@ mod for_all_config_modes { ) .await; - let stats = test_env.tracker.get_stats().await; + let stats = env.container.http_tracker_core_container.stats_repository.get_stats().await; - assert_eq!(stats.tcp6_scrapes_handled, 1); + assert_eq!(stats.tcp6_scrapes_handled(), 1); drop(stats); - test_env.stop().await; + env.stop().await; } } } @@ -1055,84 +1195,103 @@ mod configured_as_whitelisted { mod and_receiving_an_announce_request { use std::str::FromStr; - use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; - use torrust_tracker_test_helpers::configuration; + use bittorrent_primitives::info_hash::InfoHash; + use torrust_axum_http_tracker_server::environment::Started; + use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; + use torrust_tracker_test_helpers::{configuration, logging}; + use uuid::Uuid; - use crate::servers::http::asserts::{assert_is_announce_response, assert_torrent_not_in_whitelist_error_response}; - use crate::servers::http::client::Client; - use crate::servers::http::requests::announce::QueryBuilder; - use crate::servers::http::test_environment::running_test_environment; - use crate::servers::http::v1::contract::V1; + use crate::common::fixtures::random_info_hash; + use crate::server::asserts::{assert_is_announce_response, assert_torrent_not_in_whitelist_error_response}; + use crate::server::client::Client; + use crate::server::requests::announce::QueryBuilder; #[tokio::test] async fn should_fail_if_the_torrent_is_not_in_the_whitelist() { - let test_env = running_test_environment::(configuration::ephemeral_mode_whitelisted()).await; + logging::setup(); - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let env = Started::new(&configuration::ephemeral_listed().into()).await; - let response = Client::new(*test_env.bind_address()) - .announce(&QueryBuilder::default().with_info_hash(&info_hash).query()) + let request_id = Uuid::new_v4(); + let info_hash = random_info_hash(); + + let response = Client::new(*env.bind_address()) + .announce_with_header( + &QueryBuilder::default().with_info_hash(&info_hash).query(), + "x-request-id", + &request_id.to_string(), + ) .await; assert_torrent_not_in_whitelist_error_response(response).await; - test_env.stop().await; + assert!( + logs_contains_a_line_with(&["ERROR", &format!("{info_hash}"), "is not whitelisted"]), + "Expected logs to contain: ERROR ... {info_hash} is not whitelisted" + ); + + env.stop().await; } #[tokio::test] async fn should_allow_announcing_a_whitelisted_torrent() { - let test_env = running_test_environment::(configuration::ephemeral_mode_whitelisted()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral_listed().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 - test_env - .tracker + env.container + .tracker_core_container + .whitelist_manager .add_torrent_to_whitelist(&info_hash) .await .expect("should add the torrent to the whitelist"); - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .announce(&QueryBuilder::default().with_info_hash(&info_hash).query()) .await; assert_is_announce_response(response).await; - test_env.stop().await; + env.stop().await; } } mod receiving_an_scrape_request { use std::str::FromStr; - use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; - use torrust_tracker::tracker::peer; - use torrust_tracker_test_helpers::configuration; + use aquatic_udp_protocol::PeerId; + use bittorrent_primitives::info_hash::InfoHash; + use torrust_axum_http_tracker_server::environment::Started; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; + use torrust_tracker_test_helpers::{configuration, logging}; - use crate::common::fixtures::PeerBuilder; - use crate::servers::http::asserts::assert_scrape_response; - use crate::servers::http::client::Client; - use crate::servers::http::requests; - use crate::servers::http::responses::scrape::{File, ResponseBuilder}; - use crate::servers::http::test_environment::running_test_environment; - use crate::servers::http::v1::contract::V1; + use crate::common::fixtures::random_info_hash; + use crate::server::asserts::assert_scrape_response; + use crate::server::client::Client; + use crate::server::requests; + use crate::server::responses::scrape::{File, ResponseBuilder}; #[tokio::test] async fn should_return_the_zeroed_file_when_the_requested_file_is_not_whitelisted() { - let test_env = running_test_environment::(configuration::ephemeral_mode_whitelisted()).await; + logging::setup(); - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let env = Started::new(&configuration::ephemeral_listed().into()).await; - test_env - .add_torrent_peer( - &info_hash, - &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) - .build(), - ) - .await; + let info_hash = random_info_hash(); + + env.add_torrent_peer( + &info_hash, + &PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000001")) + .with_bytes_left_to_download(1) + .build(), + ) + .await; - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -1144,32 +1303,39 @@ mod configured_as_whitelisted { assert_scrape_response(response, &expected_scrape_response).await; - test_env.stop().await; + assert!( + logs_contains_a_line_with(&["ERROR", &format!("{info_hash}"), "is not whitelisted"]), + "Expected logs to contain: ERROR ... {info_hash} is not whitelisted" + ); + + env.stop().await; } #[tokio::test] async fn should_return_the_file_stats_when_the_requested_file_is_whitelisted() { - let test_env = running_test_environment::(configuration::ephemeral_mode_whitelisted()).await; + logging::setup(); - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let env = Started::new(&configuration::ephemeral_listed().into()).await; - test_env - .add_torrent_peer( - &info_hash, - &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) - .build(), - ) - .await; + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 + + env.add_torrent_peer( + &info_hash, + &PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000001")) + .with_bytes_left_to_download(1) + .build(), + ) + .await; - test_env - .tracker + env.container + .tracker_core_container + .whitelist_manager .add_torrent_to_whitelist(&info_hash) .await .expect("should add the torrent to the whitelist"); - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -1190,7 +1356,7 @@ mod configured_as_whitelisted { assert_scrape_response(response, &expected_scrape_response).await; - test_env.stop().await; + env.stop().await; } } } @@ -1201,53 +1367,66 @@ mod configured_as_private { use std::str::FromStr; use std::time::Duration; - use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; - use torrust_tracker::tracker::auth::Key; - use torrust_tracker_test_helpers::configuration; + use bittorrent_primitives::info_hash::InfoHash; + use bittorrent_tracker_core::authentication::Key; + use torrust_axum_http_tracker_server::environment::Started; + use torrust_tracker_test_helpers::{configuration, logging}; - use crate::servers::http::asserts::{assert_authentication_error_response, assert_is_announce_response}; - use crate::servers::http::client::Client; - use crate::servers::http::requests::announce::QueryBuilder; - use crate::servers::http::test_environment::running_test_environment; - use crate::servers::http::v1::contract::V1; + use crate::server::asserts::{ + assert_authentication_error_response, assert_is_announce_response, assert_tracker_core_authentication_error_response, + }; + use crate::server::client::Client; + use crate::server::requests::announce::QueryBuilder; #[tokio::test] async fn should_respond_to_authenticated_peers() { - let test_env = running_test_environment::(configuration::ephemeral_mode_private()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral_private().into()).await; - let expiring_key = test_env.tracker.generate_auth_key(Duration::from_secs(60)).await.unwrap(); + let expiring_key = env + .container + .tracker_core_container + .keys_handler + .generate_expiring_peer_key(Some(Duration::from_secs(60))) + .await + .unwrap(); - let response = Client::authenticated(*test_env.bind_address(), expiring_key.key()) + let response = Client::authenticated(*env.bind_address(), expiring_key.key()) .announce(&QueryBuilder::default().query()) .await; assert_is_announce_response(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_if_the_peer_has_not_provided_the_authentication_key() { - let test_env = running_test_environment::(configuration::ephemeral_mode_private()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral_private().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .announce(&QueryBuilder::default().with_info_hash(&info_hash).query()) .await; - assert_authentication_error_response(response).await; + assert_tracker_core_authentication_error_response(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_if_the_key_query_param_cannot_be_parsed() { - let test_env = running_test_environment::(configuration::ephemeral_mode_private()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral_private().into()).await; let invalid_key = "INVALID_KEY"; - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .get(&format!( "announce/{invalid_key}?info_hash=%81%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00&peer_addr=2.137.87.41&downloaded=0&uploaded=0&peer_id=-qB00000000000000001&port=17548&left=0&event=completed&compact=0" )) @@ -1258,18 +1437,20 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_peer_cannot_be_authenticated_with_the_provided_key() { - let test_env = running_test_environment::(configuration::ephemeral_mode_private()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral_private().into()).await; // The tracker does not have this key let unregistered_key = Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); - let response = Client::authenticated(*test_env.bind_address(), unregistered_key) + let response = Client::authenticated(*env.bind_address(), unregistered_key) .announce(&QueryBuilder::default().query()) .await; - assert_authentication_error_response(response).await; + assert_tracker_core_authentication_error_response(response).await; - test_env.stop().await; + env.stop().await; } } @@ -1278,26 +1459,27 @@ mod configured_as_private { use std::str::FromStr; use std::time::Duration; - use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; - use torrust_tracker::tracker::auth::Key; - use torrust_tracker::tracker::peer; - use torrust_tracker_test_helpers::configuration; + use aquatic_udp_protocol::PeerId; + use bittorrent_primitives::info_hash::InfoHash; + use bittorrent_tracker_core::authentication::Key; + use torrust_axum_http_tracker_server::environment::Started; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_test_helpers::{configuration, logging}; - use crate::common::fixtures::PeerBuilder; - use crate::servers::http::asserts::{assert_authentication_error_response, assert_scrape_response}; - use crate::servers::http::client::Client; - use crate::servers::http::requests; - use crate::servers::http::responses::scrape::{File, ResponseBuilder}; - use crate::servers::http::test_environment::running_test_environment; - use crate::servers::http::v1::contract::V1; + use crate::server::asserts::{assert_authentication_error_response, assert_scrape_response}; + use crate::server::client::Client; + use crate::server::requests; + use crate::server::responses::scrape::{File, ResponseBuilder}; #[tokio::test] async fn should_fail_if_the_key_query_param_cannot_be_parsed() { - let test_env = running_test_environment::(configuration::ephemeral_mode_private()).await; + logging::setup(); + + let env = Started::new(&configuration::ephemeral_private().into()).await; let invalid_key = "INVALID_KEY"; - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .get(&format!( "scrape/{invalid_key}?info_hash=%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0" )) @@ -1308,21 +1490,22 @@ mod configured_as_private { #[tokio::test] async fn should_return_the_zeroed_file_when_the_client_is_not_authenticated() { - let test_env = running_test_environment::(configuration::ephemeral_mode_private()).await; + logging::setup(); - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let env = Started::new(&configuration::ephemeral_private().into()).await; - test_env - .add_torrent_peer( - &info_hash, - &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) - .build(), - ) - .await; + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 - let response = Client::new(*test_env.bind_address()) + env.add_torrent_peer( + &info_hash, + &PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000001")) + .with_bytes_left_to_download(1) + .build(), + ) + .await; + + let response = Client::new(*env.bind_address()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -1334,28 +1517,35 @@ mod configured_as_private { assert_scrape_response(response, &expected_scrape_response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_return_the_real_file_stats_when_the_client_is_authenticated() { - let test_env = running_test_environment::(configuration::ephemeral_mode_private()).await; + logging::setup(); - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let env = Started::new(&configuration::ephemeral_private().into()).await; - test_env - .add_torrent_peer( - &info_hash, - &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) - .build(), - ) - .await; + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 + + env.add_torrent_peer( + &info_hash, + &PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000001")) + .with_bytes_left_to_download(1) + .build(), + ) + .await; - let expiring_key = test_env.tracker.generate_auth_key(Duration::from_secs(60)).await.unwrap(); + let expiring_key = env + .container + .tracker_core_container + .keys_handler + .generate_expiring_peer_key(Some(Duration::from_secs(60))) + .await + .unwrap(); - let response = Client::authenticated(*test_env.bind_address(), expiring_key.key()) + let response = Client::authenticated(*env.bind_address(), expiring_key.key()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -1376,31 +1566,32 @@ mod configured_as_private { assert_scrape_response(response, &expected_scrape_response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_return_the_zeroed_file_when_the_authentication_key_provided_by_the_client_is_invalid() { + logging::setup(); + // There is not authentication error // code-review: should this really be this way? - let test_env = running_test_environment::(configuration::ephemeral_mode_private()).await; + let env = Started::new(&configuration::ephemeral_private().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 - test_env - .add_torrent_peer( - &info_hash, - &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) - .build(), - ) - .await; + env.add_torrent_peer( + &info_hash, + &PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000001")) + .with_bytes_left_to_download(1) + .build(), + ) + .await; let false_key: Key = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ".parse().unwrap(); - let response = Client::authenticated(*test_env.bind_address(), false_key) + let response = Client::authenticated(*env.bind_address(), false_key) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -1412,7 +1603,7 @@ mod configured_as_private { assert_scrape_response(response, &expected_scrape_response).await; - test_env.stop().await; + env.stop().await; } } } diff --git a/tests/servers/http/v1/mod.rs b/packages/axum-http-tracker-server/tests/server/v1/mod.rs similarity index 100% rename from tests/servers/http/v1/mod.rs rename to packages/axum-http-tracker-server/tests/server/v1/mod.rs diff --git a/packages/axum-rest-tracker-api-server/Cargo.toml b/packages/axum-rest-tracker-api-server/Cargo.toml new file mode 100644 index 000000000..7353e66e8 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/Cargo.toml @@ -0,0 +1,55 @@ +[package] +authors.workspace = true +description = "The Torrust Tracker API." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = [ "axum", "bittorrent", "http", "server", "torrust", "tracker" ] +license.workspace = true +name = "torrust-axum-rest-tracker-api-server" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +axum = { version = "0", features = [ "macros" ] } +axum-extra = { version = "0", features = [ "query" ] } +axum-server = { version = "0", features = [ "tls-rustls-no-provider" ] } +bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "../http-tracker-core" } +bittorrent-primitives = "0.1.0" +bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } +bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "../udp-tracker-core" } +derive_more = { version = "2", features = [ "as_ref", "constructor", "from" ] } +futures = "0" +hyper = "1" +reqwest = { version = "0", features = [ "json" ] } +serde = { version = "1", features = [ "derive" ] } +serde_json = { version = "1", features = [ "preserve_order" ] } +serde_with = { version = "3", features = [ "json" ] } +thiserror = "2" +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } +torrust-axum-server = { version = "3.0.0-develop", path = "../axum-server" } +torrust-rest-tracker-api-client = { version = "3.0.0-develop", path = "../rest-tracker-api-client" } +torrust-rest-tracker-api-core = { version = "3.0.0-develop", path = "../rest-tracker-api-core" } +torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } +torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker-server" } +tower = { version = "0", features = [ "timeout" ] } +tower-http = { version = "0", features = [ "compression-full", "cors", "propagate-header", "request-id", "trace" ] } +tracing = "0" +url = "2" + +[dev-dependencies] +local-ip-address = "0" +mockall = "0" +torrust-rest-tracker-api-client = { version = "3.0.0-develop", path = "../rest-tracker-api-client" } +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } +url = { version = "2", features = [ "serde" ] } +uuid = { version = "1", features = [ "v4" ] } diff --git a/packages/axum-rest-tracker-api-server/LICENSE b/packages/axum-rest-tracker-api-server/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/axum-rest-tracker-api-server/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/axum-rest-tracker-api-server/README.md b/packages/axum-rest-tracker-api-server/README.md new file mode 100644 index 000000000..6a0415828 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/README.md @@ -0,0 +1,11 @@ +# Torrust Tracker API + +The Torrust Tracker Rest API. + +## Documentation + +[Crate documentation](https://docs.rs/torrust-axum-tracker-api-server). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/axum-rest-tracker-api-server/src/environment.rs b/packages/axum-rest-tracker-api-server/src/environment.rs new file mode 100644 index 000000000..cddb45277 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/environment.rs @@ -0,0 +1,217 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::container::TrackerCoreContainer; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; +use futures::executor::block_on; +use torrust_axum_server::tsl::make_rust_tls; +use torrust_rest_tracker_api_client::connection_info::{ConnectionInfo, Origin}; +use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; +use torrust_server_lib::registar::Registar; +use torrust_tracker_configuration::{logging, Configuration}; +use torrust_tracker_primitives::peer; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; +use torrust_udp_tracker_server::container::UdpTrackerServerContainer; + +use crate::server::{ApiServer, Launcher, Running, Stopped}; + +pub type Started = Environment; + +pub struct Environment +where + S: std::fmt::Debug + std::fmt::Display, +{ + pub container: Arc, + pub registar: Registar, + pub server: ApiServer, +} + +impl Environment +where + S: std::fmt::Debug + std::fmt::Display, +{ + /// Add a torrent to the tracker + pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + self.container + .tracker_core_container + .in_memory_torrent_repository + .handle_announcement(info_hash, peer, None) + .await; + } +} + +impl Environment { + /// # Panics + /// + /// Will panic if it cannot make the TSL configuration from the provided + /// configuration. + #[must_use] + pub fn new(configuration: &Arc) -> Self { + initialize_global_services(configuration); + + let container = Arc::new(EnvContainer::initialize(configuration)); + + let bind_to = container.tracker_http_api_core_container.http_api_config.bind_address; + + let tls = block_on(make_rust_tls( + &container.tracker_http_api_core_container.http_api_config.tsl_config, + )) + .map(|tls| tls.expect("tls config failed")); + + let server = ApiServer::new(Launcher::new(bind_to, tls)); + + Self { + container, + registar: Registar::default(), + server, + } + } + + /// # Panics + /// + /// Will panic if the server cannot be started. + pub async fn start(self) -> Environment { + let access_tokens = Arc::new( + self.container + .tracker_http_api_core_container + .http_api_config + .access_tokens + .clone(), + ); + + Environment { + container: self.container.clone(), + registar: self.registar.clone(), + server: self + .server + .start( + self.container.tracker_http_api_core_container.clone(), + self.registar.give_form(), + access_tokens, + ) + .await + .unwrap(), + } + } +} + +impl Environment { + pub async fn new(configuration: &Arc) -> Self { + Environment::::new(configuration).start().await + } + + /// # Panics + /// + /// Will panic if the server cannot be stopped. + pub async fn stop(self) -> Environment { + Environment { + container: self.container, + registar: Registar::default(), + server: self.server.stop().await.unwrap(), + } + } + + /// # Panics + /// + /// Will panic if it cannot build the origin for the connection info from the + /// server local socket address. + #[must_use] + pub fn get_connection_info(&self) -> ConnectionInfo { + let origin = Origin::new(&format!("http://{}/", self.server.state.local_addr)).unwrap(); // DevSkim: ignore DS137138 + + ConnectionInfo { + origin, + api_token: self + .container + .tracker_http_api_core_container + .http_api_config + .access_tokens + .get("admin") + .cloned(), + } + } + + #[must_use] + pub fn bind_address(&self) -> SocketAddr { + self.server.state.local_addr + } +} + +pub struct EnvContainer { + pub tracker_core_container: Arc, + pub tracker_http_api_core_container: Arc, +} + +impl EnvContainer { + /// # Panics + /// + /// Will panic if: + /// + /// - The configuration does not contain a HTTP tracker configuration. + /// - The configuration does not contain a UDP tracker configuration. + /// - The configuration does not contain a HTTP API configuration. + #[must_use] + pub fn initialize(configuration: &Configuration) -> Self { + let core_config = Arc::new(configuration.core.clone()); + + let http_tracker_config = configuration + .http_trackers + .clone() + .expect("missing HTTP tracker configuration"); + let http_tracker_config = Arc::new(http_tracker_config[0].clone()); + + let udp_tracker_configurations = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); + let udp_tracker_config = Arc::new(udp_tracker_configurations[0].clone()); + + let http_api_config = Arc::new( + configuration + .http_api + .clone() + .expect("missing HTTP API configuration") + .clone(), + ); + + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + core_config.tracker_usage_statistics.into(), + )); + + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + &core_config, + &swarm_coordination_registry_container, + )); + + let http_tracker_core_container = + HttpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, &http_tracker_config); + + let udp_tracker_core_container = + UdpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, &udp_tracker_config); + + let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); + + let tracker_http_api_core_container = TrackerHttpApiCoreContainer::initialize_from( + &swarm_coordination_registry_container, + &tracker_core_container, + &http_tracker_core_container, + &udp_tracker_core_container, + &udp_tracker_server_container, + &http_api_config, + ); + + Self { + tracker_core_container, + tracker_http_api_core_container, + } + } +} + +fn initialize_global_services(configuration: &Configuration) { + initialize_static(); + logging::setup(&configuration.logging); +} + +fn initialize_static() { + torrust_tracker_clock::initialize_static(); + bittorrent_udp_tracker_core::initialize_static(); +} diff --git a/src/servers/apis/mod.rs b/packages/axum-rest-tracker-api-server/src/lib.rs similarity index 66% rename from src/servers/apis/mod.rs rename to packages/axum-rest-tracker-api-server/src/lib.rs index eb278bf3c..0ed026654 100644 --- a/src/servers/apis/mod.rs +++ b/packages/axum-rest-tracker-api-server/src/lib.rs @@ -1,9 +1,9 @@ //! The tracker REST API with all its versions. //! //! > **NOTICE**: This API should not be exposed directly to the internet, it is -//! intended for internal use only. +//! > intended for internal use only. //! -//! Endpoints for the latest API: [v1](crate::servers::apis::v1). +//! Endpoints for the latest API: [v1]. //! //! All endpoints require an authorization token which must be set in the //! configuration before running the tracker. The default configuration uses @@ -25,11 +25,11 @@ //! //! ```toml //! [http_api] -//! enabled = true //! bind_address = "0.0.0.0:1212" -//! ssl_enabled = false -//! ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -//! ssl_key_path = "./storage/ssl_certificates/localhost.key" +//! +//! [http_api.tsl_config] +//! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" +//! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" //! //! [http_api.access_tokens] //! admin = "MyAccessToken" @@ -41,8 +41,8 @@ //! When you run the tracker with enabled API, you will see the following message: //! //! ```text -//! Loading configuration from config file ./config.toml -//! 023-03-28T12:19:24.963054069+01:00 [torrust_tracker::bootstrap::logging][INFO] logging initialized. +//! Loading configuration from config file ./tracker.toml +//! 023-03-28T12:19:24.963054069+01:00 [torrust_tracker::bootstrap::logging][INFO] Logging initialized //! ... //! 023-03-28T12:19:24.964138723+01:00 [torrust_tracker::bootstrap::jobs::tracker_apis][INFO] Starting Torrust APIs server on: http://0.0.0.0:1212 //! ``` @@ -60,7 +60,7 @@ //! ``` //! //! The response will be a JSON object. For example, the [tracker statistics -//! endpoint](crate::servers::apis::v1::context::stats#get-tracker-statistics): +//! endpoint](crate::v1::context::stats#get-tracker-statistics): //! //! ```json //! { @@ -101,51 +101,49 @@ //! //! Refer to [`torrust-tracker-configuration`](torrust_tracker_configuration) //! for more information about the API configuration and to the -//! [`auth`](crate::servers::apis::v1::middlewares::auth) middleware for more +//! [`auth`](crate::v1::middlewares::auth) middleware for more //! information about the authentication process. //! //! # Setup SSL (optional) //! -//! The API server supports SSL. You can enable it by setting the -//! [`ssl_enabled`](torrust_tracker_configuration::HttpApi::ssl_enabled) option -//! to `true` in the configuration file -//! ([`http_api`](torrust_tracker_configuration::HttpApi) section). +//! The API server supports SSL. You can enable it by adding the `tsl_config` +//! section to the configuration. //! //! ```toml //! [http_api] -//! enabled = true //! bind_address = "0.0.0.0:1212" -//! ssl_enabled = true -//! ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -//! ssl_key_path = "./storage/ssl_certificates/localhost.key" +//! +//! [http_api.tsl_config] +//! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" +//! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" //! //! [http_api.access_tokens] //! admin = "MyAccessToken" //! ``` //! //! > **NOTICE**: If you are using a reverse proxy like NGINX, you can skip this -//! step and use NGINX for the SSL instead. See -//! [other alternatives to Nginx/certbot](https://github.com/torrust/torrust-tracker/discussions/131) +//! > step and use NGINX for the SSL instead. See +//! > [other alternatives to Nginx/certbot](https://github.com/torrust/torrust-tracker/discussions/131) //! //! > **NOTICE**: You can generate a self-signed certificate for localhost using -//! OpenSSL. See [Let's Encrypt](https://letsencrypt.org/docs/certificates-for-localhost/). -//! That's particularly useful for testing purposes. Once you have the certificate -//! you need to set the [`ssl_cert_path`](torrust_tracker_configuration::HttpApi::ssl_cert_path) -//! and [`ssl_key_path`](torrust_tracker_configuration::HttpApi::ssl_key_path) -//! options in the configuration file with the paths to the certificate -//! (`localhost.crt`) and key (`localhost.key`) files. +//! > OpenSSL. See [Let's Encrypt](https://letsencrypt.org/docs/certificates-for-localhost/). +//! > That's particularly useful for testing purposes. Once you have the certificate +//! > you need to set the [`ssl_cert_path`](torrust_tracker_configuration::HttpApi::tsl_config.ssl_cert_path) +//! > and [`ssl_key_path`](torrust_tracker_configuration::HttpApi::tsl_config.ssl_key_path) +//! > options in the configuration file with the paths to the certificate +//! > (`localhost.crt`) and key (`localhost.key`) files. //! //! # Versioning //! //! The API is versioned and each version has its own module. //! The API server runs all the API versions on the same server using -//! the same port. Currently there is only one API version: [v1](crate::servers::apis::v1) +//! the same port. Currently there is only one API version: [v1] //! but a version [`v2`](https://github.com/torrust/torrust-tracker/issues/144) //! is planned. //! //! # Endpoints //! -//! Refer to the [v1](crate::servers::apis::v1) module for the list of available +//! Refer to the [v1] module for the list of available //! API endpoints. //! //! # Documentation @@ -153,13 +151,28 @@ //! If you want to contribute to this documentation you can [open a new pull request](https://github.com/torrust/torrust-tracker/pulls). //! //! > **NOTICE**: we are using [curl](https://curl.se/) in the API examples. -//! And you have to use quotes around the URL in order to avoid unexpected -//! errors. For example: `curl "http://127.0.0.1:1212/api/v1/stats?token=MyAccessToken"`. +//! > And you have to use quotes around the URL in order to avoid unexpected +//! > errors. For example: `curl "http://127.0.0.1:1212/api/v1/stats?token=MyAccessToken"`. +pub mod environment; pub mod routes; pub mod server; pub mod v1; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; +use torrust_tracker_clock::clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; + +pub const API_LOG_TARGET: &str = "API"; /// The info hash URL path parameter. /// @@ -172,3 +185,10 @@ use serde::Deserialize; /// in order to provide a more specific error message. #[derive(Deserialize)] pub struct InfoHashParam(pub String); + +/// The version of the HTTP Api. +#[derive(Serialize, Deserialize, Copy, Clone, PartialEq, Eq, Debug)] +pub enum Version { + /// The `v1` version of the HTTP Api. + V1, +} diff --git a/packages/axum-rest-tracker-api-server/src/routes.rs b/packages/axum-rest-tracker-api-server/src/routes.rs new file mode 100644 index 000000000..78b7818d9 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/routes.rs @@ -0,0 +1,114 @@ +//! API routes. +//! +//! It loads all the API routes for all API versions and adds the authentication +//! middleware to them. +//! +//! All the API routes have the `/api` prefix and the version number as the +//! first path segment. For example: `/api/v1/torrents`. +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +use axum::error_handling::HandleErrorLayer; +use axum::http::HeaderName; +use axum::response::Response; +use axum::routing::get; +use axum::{middleware, BoxError, Router}; +use hyper::{Request, StatusCode}; +use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; +use torrust_server_lib::logging::Latency; +use torrust_tracker_configuration::{AccessTokens, DEFAULT_TIMEOUT}; +use tower::timeout::TimeoutLayer; +use tower::ServiceBuilder; +use tower_http::classify::ServerErrorsFailureClass; +use tower_http::compression::CompressionLayer; +use tower_http::propagate_header::PropagateHeaderLayer; +use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; +use tower_http::trace::{DefaultMakeSpan, TraceLayer}; +use tower_http::LatencyUnit; +use tracing::{instrument, Level, Span}; + +use super::v1; +use super::v1::context::health_check::handlers::health_check_handler; +use super::v1::middlewares::auth::State; +use crate::API_LOG_TARGET; + +/// Add all API routes to the router. +#[instrument(skip(http_api_container, access_tokens))] +pub fn router( + http_api_container: &Arc, + access_tokens: Arc, + server_socket_addr: SocketAddr, +) -> Router { + let router = Router::new(); + + let api_url_prefix = "/api"; + + let router = v1::routes::add(api_url_prefix, router, http_api_container); + + let state = State { access_tokens }; + + router + .layer(middleware::from_fn_with_state(state, v1::middlewares::auth::auth)) + .route(&format!("{api_url_prefix}/health_check"), get(health_check_handler)) + .layer(CompressionLayer::new()) + .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) + .layer(PropagateHeaderLayer::new(HeaderName::from_static("x-request-id"))) + .layer( + TraceLayer::new_for_http() + .make_span_with(DefaultMakeSpan::new().level(Level::INFO)) + .on_request(|request: &Request, span: &Span| { + let method = request.method().to_string(); + let uri = request.uri().to_string(); + let request_id = request + .headers() + .get("x-request-id") + .map(|v| v.to_str().unwrap_or_default()) + .unwrap_or_default(); + + span.record("request_id", request_id); + + tracing::event!( + target: API_LOG_TARGET, + tracing::Level::INFO, %method, %uri, %request_id, "request"); + }) + .on_response(move |response: &Response, latency: Duration, span: &Span| { + let latency_ms = latency.as_millis(); + let status_code = response.status(); + let request_id = response + .headers() + .get("x-request-id") + .map(|v| v.to_str().unwrap_or_default()) + .unwrap_or_default(); + + span.record("request_id", request_id); + + if status_code.is_server_error() { + tracing::event!( + target: API_LOG_TARGET, + tracing::Level::ERROR, %latency_ms, %status_code, %server_socket_addr, %request_id, "response"); + } else { + tracing::event!( + target: API_LOG_TARGET, + tracing::Level::INFO, %latency_ms, %status_code, %server_socket_addr, %request_id, "response"); + } + }) + .on_failure( + move |failure_classification: ServerErrorsFailureClass, latency: Duration, _span: &Span| { + let latency = Latency::new(LatencyUnit::Millis, latency); + + tracing::event!( + target: API_LOG_TARGET, + tracing::Level::ERROR, %failure_classification, %latency, %server_socket_addr, "response failed"); + }, + ), + ) + .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) + .layer( + ServiceBuilder::new() + // this middleware goes above `TimeoutLayer` because it will receive + // errors returned by `TimeoutLayer` + .layer(HandleErrorLayer::new(|_: BoxError| async { StatusCode::REQUEST_TIMEOUT })) + .layer(TimeoutLayer::new(DEFAULT_TIMEOUT)), + ) +} diff --git a/packages/axum-rest-tracker-api-server/src/server.rs b/packages/axum-rest-tracker-api-server/src/server.rs new file mode 100644 index 000000000..9eef6b71a --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/server.rs @@ -0,0 +1,363 @@ +//! Logic to run the HTTP API server. +//! +//! It contains two main structs: `ApiServer` and `Launcher`, +//! and two main functions: `start` and `start_tls`. +//! +//! The `ApiServer` struct is responsible for: +//! - Starting and stopping the server. +//! - Storing the configuration. +//! +//! `ApiServer` relies on a launcher to start the actual server. +/// +/// 1. `ApiServer::start` -> spawns new asynchronous task. +/// 2. `Launcher::start` -> starts the server on the spawned task. +/// +/// The `Launcher` struct is responsible for: +/// +/// - Knowing how to start the server with graceful shutdown. +/// +/// For the time being the `ApiServer` and `Launcher` are only used in tests +/// where we need to start and stop the server multiple times. In production +/// code and the main application uses the `start` and `start_tls` functions +/// to start the servers directly since we do not need to control the server +/// when it's running. In the future we might need to control the server, +/// for example, to restart it to apply new configuration changes, to remotely +/// shutdown the server, etc. +use std::net::SocketAddr; +use std::sync::Arc; + +use axum_server::tls_rustls::RustlsConfig; +use axum_server::Handle; +use derive_more::derive::Display; +use derive_more::Constructor; +use futures::future::BoxFuture; +use thiserror::Error; +use tokio::sync::oneshot::{Receiver, Sender}; +use torrust_axum_server::custom_axum_server::{self, TimeoutAcceptor}; +use torrust_axum_server::signals::graceful_shutdown; +use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; +use torrust_server_lib::logging::STARTED_ON; +use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; +use torrust_server_lib::signals::{Halted, Started}; +use torrust_tracker_configuration::AccessTokens; +use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; +use tracing::{instrument, Level}; + +use super::routes::router; +use crate::API_LOG_TARGET; + +const TYPE_STRING: &str = "tracker_rest_api"; + +/// Errors that can occur when starting or stopping the API server. +#[derive(Debug, Error)] +pub enum Error { + #[error("Error when starting or stopping the API server")] + FailedToStartOrStop(String), +} + +/// An alias for the `ApiServer` struct with the `Stopped` state. +#[allow(clippy::module_name_repetitions)] +pub type StoppedApiServer = ApiServer; + +/// An alias for the `ApiServer` struct with the `Running` state. +#[allow(clippy::module_name_repetitions)] +pub type RunningApiServer = ApiServer; + +/// A struct responsible for starting and stopping an API server with a +/// specific configuration and keeping track of the started server. +/// +/// It's a state machine that can be in one of two +/// states: `Stopped` or `Running`. +#[allow(clippy::module_name_repetitions)] +#[derive(Debug, Display)] +pub struct ApiServer +where + S: std::fmt::Debug + std::fmt::Display, +{ + pub state: S, +} + +/// The `Stopped` state of the `ApiServer` struct. +#[derive(Debug, Display)] +#[display("Stopped: {launcher}")] +pub struct Stopped { + launcher: Launcher, +} + +/// The `Running` state of the `ApiServer` struct. +#[derive(Debug, Display)] +#[display("Running (with local address): {local_addr}")] +pub struct Running { + pub local_addr: SocketAddr, + pub halt_task: tokio::sync::oneshot::Sender, + pub task: tokio::task::JoinHandle, +} + +impl Running { + #[must_use] + pub fn new( + local_addr: SocketAddr, + halt_task: tokio::sync::oneshot::Sender, + task: tokio::task::JoinHandle, + ) -> Self { + Self { + local_addr, + halt_task, + task, + } + } +} + +impl ApiServer { + #[must_use] + pub fn new(launcher: Launcher) -> Self { + Self { + state: Stopped { launcher }, + } + } + + /// Starts the API server with the given configuration. + /// + /// # Errors + /// + /// It would return an error if no `SocketAddr` is returned after launching the server. + /// + /// # Panics + /// + /// It would panic if the bound socket address cannot be sent back to this starter. + #[instrument(skip(self, http_api_container, form, access_tokens), err, ret(Display, level = Level::INFO))] + pub async fn start( + self, + http_api_container: Arc, + form: ServiceRegistrationForm, + access_tokens: Arc, + ) -> Result, Error> { + let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); + let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); + + let launcher = self.state.launcher; + + let task = tokio::spawn(async move { + tracing::debug!(target: API_LOG_TARGET, "Starting with launcher in spawned task ..."); + + let _task = launcher.start(&http_api_container, access_tokens, tx_start, rx_halt).await; + + tracing::debug!(target: API_LOG_TARGET, "Started with launcher in spawned task"); + + launcher + }); + + let api_server = match rx_start.await { + Ok(started) => { + form.send(ServiceRegistration::new(started.service_binding, check_fn)) + .expect("it should be able to send service registration"); + + ApiServer { + state: Running::new(started.address, tx_halt, task), + } + } + Err(err) => { + let msg = format!("Unable to start API server: {err}"); + tracing::error!("{}", msg); + panic!("{}", msg); + } + }; + + Ok(api_server) + } +} + +impl ApiServer { + /// Stops the API server. + /// + /// # Errors + /// + /// It would return an error if the channel for the task killer signal was closed. + #[instrument(skip(self), err, ret(Display, level = Level::INFO))] + pub async fn stop(self) -> Result, Error> { + self.state + .halt_task + .send(Halted::Normal) + .map_err(|_| Error::FailedToStartOrStop("Task killer channel was closed.".to_string()))?; + + let launcher = self.state.task.await.map_err(|e| Error::FailedToStartOrStop(e.to_string()))?; + + Ok(ApiServer { + state: Stopped { launcher }, + }) + } +} + +/// Checks the Health by connecting to the API service endpoint. +/// +/// # Errors +/// +/// This function will return an error if unable to connect. +/// Or if there request returns an error code. +#[must_use] +#[instrument(skip())] +pub fn check_fn(service_binding: &ServiceBinding) -> ServiceHealthCheckJob { + let url = format!("http://{}/api/health_check", service_binding.bind_address()); // DevSkim: ignore DS137138 + + let info = format!("checking api health check at: {url}"); + + let job = tokio::spawn(async move { + match reqwest::get(url).await { + Ok(response) => Ok(response.status().to_string()), + Err(err) => Err(err.to_string()), + } + }); + ServiceHealthCheckJob::new(service_binding.clone(), info, TYPE_STRING.to_string(), job) +} + +/// A struct responsible for starting the API server. +#[derive(Constructor, Debug)] +pub struct Launcher { + bind_to: SocketAddr, + tls: Option, +} + +impl std::fmt::Display for Launcher { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if self.tls.is_some() { + write!(f, "(with socket): {}, using TLS", self.bind_to) + } else { + write!(f, "(with socket): {}, without TLS", self.bind_to) + } + } +} + +impl Launcher { + /// Starts the API server with graceful shutdown. + /// + /// If TLS is enabled in the configuration, it will start the server with + /// TLS. See [`torrust-tracker-configuration`](torrust_tracker_configuration) + /// for more information about configuration. + /// + /// # Panics + /// + /// Will panic if unable to bind to the socket, or unable to get the address of the bound socket. + /// Will also panic if unable to send message regarding the bound socket address. + #[instrument(skip(self, http_api_container, access_tokens, tx_start, rx_halt))] + pub fn start( + &self, + http_api_container: &Arc, + access_tokens: Arc, + tx_start: Sender, + rx_halt: Receiver, + ) -> BoxFuture<'static, ()> { + let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address."); + socket + .set_nonblocking(true) + .expect("Failed to set socket to non-blocking mode"); + let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); + + let router = router(http_api_container, access_tokens, address); + + let handle = Handle::new(); + + tokio::task::spawn(graceful_shutdown( + handle.clone(), + rx_halt, + format!("Shutting down tracker API server on socket address: {address}"), + address, + )); + + let tls = self.tls.clone(); + let protocol = if tls.is_some() { Protocol::HTTPS } else { Protocol::HTTP }; + let service_binding = ServiceBinding::new(protocol.clone(), address).expect("Service binding creation failed"); + + tracing::info!(target: API_LOG_TARGET, "Starting on: {protocol}://{address}"); + + let running = Box::pin(async { + match tls { + Some(tls) => custom_axum_server::from_tcp_rustls_with_timeouts(socket, tls) + .expect("Failed to create server from TCP socket with TLS") + .handle(handle) + // The TimeoutAcceptor is commented because TSL does not work with it. + // See: https://github.com/torrust/torrust-index/issues/204#issuecomment-2115529214 + //.acceptor(TimeoutAcceptor) + .serve(router.into_make_service_with_connect_info::()) + .await + .expect("Axum server for tracker API crashed."), + None => custom_axum_server::from_tcp_with_timeouts(socket) + .expect("Failed to create server from TCP socket") + .handle(handle) + .acceptor(TimeoutAcceptor) + .serve(router.into_make_service_with_connect_info::()) + .await + .expect("Axum server for tracker API crashed."), + } + }); + + tracing::info!(target: API_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", address); + + tx_start + .send(Started { + service_binding, + address, + }) + .expect("the HTTP(s) Tracker API service should not be dropped"); + + running + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use torrust_axum_server::tsl::make_rust_tls; + use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; + use torrust_server_lib::registar::Registar; + use torrust_tracker_configuration::{logging, Configuration}; + use torrust_tracker_test_helpers::configuration::ephemeral_public; + + use crate::server::{ApiServer, Launcher}; + + fn initialize_global_services(configuration: &Configuration) { + initialize_static(); + logging::setup(&configuration.logging); + } + + fn initialize_static() { + torrust_tracker_clock::initialize_static(); + bittorrent_udp_tracker_core::initialize_static(); + } + + #[tokio::test] + async fn it_should_be_able_to_start_and_stop() { + let cfg = Arc::new(ephemeral_public()); + let core_config = Arc::new(cfg.core.clone()); + let http_tracker_config = cfg.http_trackers.clone().expect("missing HTTP tracker configuration"); + let http_tracker_config = Arc::new(http_tracker_config[0].clone()); + let udp_tracker_configurations = cfg.udp_trackers.clone().expect("missing UDP tracker configuration"); + let udp_tracker_config = Arc::new(udp_tracker_configurations[0].clone()); + let http_api_config = Arc::new(cfg.http_api.clone().expect("missing HTTP API configuration").clone()); + + initialize_global_services(&cfg); + + let bind_to = http_api_config.bind_address; + + let tls = make_rust_tls(&http_api_config.tsl_config) + .await + .map(|tls| tls.expect("tls config failed")); + + let access_tokens = Arc::new(http_api_config.access_tokens.clone()); + + let stopped = ApiServer::new(Launcher::new(bind_to, tls)); + + let register = &Registar::default(); + + let http_api_container = + TrackerHttpApiCoreContainer::initialize(&core_config, &http_tracker_config, &udp_tracker_config, &http_api_config); + + let started = stopped + .start(http_api_container, register.give_form(), access_tokens) + .await + .expect("it should start the server"); + let stopped = started.stop().await.expect("it should stop the server"); + + assert_eq!(stopped.state.launcher.bind_to, bind_to); + } +} diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/forms.rs b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/forms.rs new file mode 100644 index 000000000..5dfea6e80 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/forms.rs @@ -0,0 +1,22 @@ +use serde::{Deserialize, Serialize}; +use serde_with::{serde_as, DefaultOnNull}; + +/// This type contains the info needed to add a new tracker key. +/// +/// You can upload a pre-generated key or let the app to generate a new one. +/// You can also set an expiration date or leave it empty (`None`) if you want +/// to create permanent key that does not expire. +#[serde_as] +#[derive(Serialize, Deserialize, Debug)] +pub struct AddKeyForm { + /// The pre-generated key. Use `None` (null in json) to generate a random key. + #[serde_as(deserialize_as = "DefaultOnNull")] + #[serde(rename = "key")] + pub opt_key: Option, + + /// How long the key will be valid in seconds. Use `None` (null in json) for + /// permanent keys. + #[serde_as(deserialize_as = "DefaultOnNull")] + #[serde(rename = "seconds_valid")] + pub opt_seconds_valid: Option, +} diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/handlers.rs new file mode 100644 index 000000000..10530287c --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/handlers.rs @@ -0,0 +1,141 @@ +//! API handlers for the [`auth_key`](crate::v1::context::auth_key) API context. +use std::str::FromStr; +use std::sync::Arc; +use std::time::Duration; + +use axum::extract::{self, Path, State}; +use axum::response::Response; +use bittorrent_tracker_core::authentication::handler::{AddKeyRequest, KeysHandler}; +use bittorrent_tracker_core::authentication::Key; +use serde::Deserialize; + +use super::forms::AddKeyForm; +use super::responses::{ + auth_key_response, failed_to_delete_key_response, failed_to_generate_key_response, failed_to_reload_keys_response, + invalid_auth_key_duration_response, invalid_auth_key_response, +}; +use crate::v1::context::auth_key::resources::AuthKey; +use crate::v1::responses::{invalid_auth_key_param_response, ok_response}; + +/// It handles the request to add a new authentication key. +/// +/// It returns these types of responses: +/// +/// - `200` with a json [`AuthKey`] +/// resource. If the key was generated successfully. +/// - `400` with an error if the key couldn't been added because of an invalid +/// request. +/// - `500` with serialized error in debug format. If the key couldn't be +/// generated. +/// +/// Refer to the [API endpoint documentation](crate::v1::context::auth_key#generate-a-new-authentication-key) +/// for more information about this endpoint. +pub async fn add_auth_key_handler( + State(keys_handler): State>, + extract::Json(add_key_form): extract::Json, +) -> Response { + match keys_handler + .add_peer_key(AddKeyRequest { + opt_key: add_key_form.opt_key.clone(), + opt_seconds_valid: add_key_form.opt_seconds_valid, + }) + .await + { + Ok(auth_key) => auth_key_response(&AuthKey::from(auth_key)), + Err(err) => match err { + bittorrent_tracker_core::error::PeerKeyError::DurationOverflow { seconds_valid } => { + invalid_auth_key_duration_response(seconds_valid) + } + bittorrent_tracker_core::error::PeerKeyError::InvalidKey { key, source } => invalid_auth_key_response(&key, source), + bittorrent_tracker_core::error::PeerKeyError::DatabaseError { source } => failed_to_generate_key_response(source), + }, + } +} + +/// It handles the request to generate a new authentication key. +/// +/// It returns two types of responses: +/// +/// - `200` with an json [`AuthKey`] +/// resource. If the key was generated successfully. +/// - `500` with serialized error in debug format. If the key couldn't be +/// generated. +/// +/// Refer to the [API endpoint documentation](crate::v1::context::auth_key#generate-a-new-authentication-key) +/// for more information about this endpoint. +/// +/// This endpoint has been deprecated. Use [`add_auth_key_handler`]. +pub async fn generate_auth_key_handler( + State(keys_handler): State>, + Path(seconds_valid_or_key): Path, +) -> Response { + let seconds_valid = seconds_valid_or_key; + match keys_handler + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) + .await + { + Ok(auth_key) => auth_key_response(&AuthKey::from(auth_key)), + Err(e) => failed_to_generate_key_response(e), + } +} + +/// A container for the `key` parameter extracted from the URL PATH. +/// +/// It does not perform any validation, it just stores the value. +/// +/// In the current API version, the `key` parameter can be either a valid key +/// like `xqD6NWH9TcKrOCwDmqcdH5hF5RrbL0A6` or the number of seconds the +/// key will be valid, for example two minutes `120`. +/// +/// For example, the `key` is used in the following requests: +/// +/// - `POST /api/v1/key/120`. It will generate a new key valid for two minutes. +/// - `DELETE /api/v1/key/xqD6NWH9TcKrOCwDmqcdH5hF5RrbL0A6`. It will delete the +/// key `xqD6NWH9TcKrOCwDmqcdH5hF5RrbL0A6`. +/// +/// > **NOTICE**: this may change in the future, in the [API v2](https://github.com/torrust/torrust-tracker/issues/144). +#[derive(Deserialize)] +pub struct KeyParam(String); + +/// It handles the request to delete an authentication key. +/// +/// It returns two types of responses: +/// +/// - `200` with an json [`ActionStatus::Ok`](crate::v1::responses::ActionStatus::Ok) +/// response. If the key was deleted successfully. +/// - `500` with serialized error in debug format. If the key couldn't be +/// deleted. +/// +/// Refer to the [API endpoint documentation](crate::v1::context::auth_key#delete-an-authentication-key) +/// for more information about this endpoint. +pub async fn delete_auth_key_handler( + State(keys_handler): State>, + Path(seconds_valid_or_key): Path, +) -> Response { + match Key::from_str(&seconds_valid_or_key.0) { + Err(_) => invalid_auth_key_param_response(&seconds_valid_or_key.0), + Ok(key) => match keys_handler.remove_peer_key(&key).await { + Ok(()) => ok_response(), + Err(e) => failed_to_delete_key_response(e), + }, + } +} + +/// It handles the request to reload the authentication keys from the database +/// into memory. +/// +/// It returns two types of responses: +/// +/// - `200` with an json [`ActionStatus::Ok`](crate::v1::responses::ActionStatus::Ok) +/// response. If the keys were successfully reloaded. +/// - `500` with serialized error in debug format. If the they couldn't be +/// reloaded. +/// +/// Refer to the [API endpoint documentation](crate::v1::context::auth_key#reload-authentication-keys) +/// for more information about this endpoint. +pub async fn reload_keys_handler(State(keys_handler): State>) -> Response { + match keys_handler.load_peer_keys_from_database().await { + Ok(()) => ok_response(), + Err(e) => failed_to_reload_keys_response(e), + } +} diff --git a/src/servers/apis/v1/context/auth_key/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/mod.rs similarity index 67% rename from src/servers/apis/v1/context/auth_key/mod.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/auth_key/mod.rs index 11bc8a43f..0a3937ef2 100644 --- a/src/servers/apis/v1/context/auth_key/mod.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/mod.rs @@ -3,8 +3,8 @@ //! Authentication keys are used to authenticate HTTP tracker `announce` and //! `scrape` requests. //! -//! When the tracker is running in `private` or `private_listed` mode, the -//! authentication keys are required to announce and scrape torrents. +//! When the tracker is running in `private` mode, the authentication keys are +//! required to announce and scrape torrents. //! //! A sample `announce` request **without** authentication key: //! @@ -22,22 +22,29 @@ //! //! # Generate a new authentication key //! -//! `POST /key/:seconds_valid` +//! `POST /keys` //! -//! It generates a new authentication key. +//! It generates a new authentication key or upload a pre-generated key. //! -//! > **NOTICE**: keys expire after a certain amount of time. -//! -//! **Path parameters** +//! **POST parameters** //! //! Name | Type | Description | Required | Example //! ---|---|---|---|--- -//! `seconds_valid` | positive integer | The number of seconds the key will be valid. | Yes | `3600` +//! `key` | 32-char string (0-9, a-z, A-Z) or `null` | The optional pre-generated key. | Yes | `Xc1L4PbQJSFGlrgSRZl8wxSFAuMa21z7` or `null` +//! `seconds_valid` | positive integer or `null` | The number of seconds the key will be valid. | Yes | `3600` or `null` +//! +//! > **NOTICE**: the `key` and `seconds_valid` fields are optional. If `key` is not provided the tracker +//! > will generated a random one. If `seconds_valid` field is not provided the key will be permanent. You can use the `null` value. //! //! **Example request** //! //! ```bash -//! curl -X POST "http://127.0.0.1:1212/api/v1/key/120?token=MyAccessToken" +//! curl -X POST http://localhost:1212/api/v1/keys?token=MyAccessToken \ +//! -H "Content-Type: application/json" \ +//! -d '{ +//! "key": "xqD6NWH9TcKrOCwDmqcdH5hF5RrbL0A6", +//! "seconds_valid": 7200 +//! }' //! ``` //! //! **Example response** `200` @@ -51,13 +58,13 @@ //! ``` //! //! > **NOTICE**: `valid_until` and `expiry_time` represent the same time. -//! `valid_until` is the number of seconds since the Unix epoch -//! ([timestamp](https://en.wikipedia.org/wiki/Timestamp)), while `expiry_time` -//! is the human-readable time ([ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html)). +//! > `valid_until` is the number of seconds since the Unix epoch +//! > ([timestamp](https://en.wikipedia.org/wiki/Timestamp)), while `expiry_time` +//! > is the human-readable time ([ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html)). //! //! **Resource** //! -//! Refer to the API [`AuthKey`](crate::servers::apis::v1::context::auth_key::resources::AuthKey) +//! Refer to the API [`AuthKey`](crate::v1::context::auth_key::resources::AuthKey) //! resource for more information about the response attributes. //! //! # Delete an authentication key @@ -96,8 +103,8 @@ //! ``` //! //! > **NOTICE**: a `500` status code will be returned and the body is not a -//! valid JSON. It's a text body containing the serialized-to-display error -//! message. +//! > valid JSON. It's a text body containing the serialized-to-display error +//! > message. //! //! # Reload authentication keys //! @@ -119,6 +126,7 @@ //! "status": "ok" //! } //! ``` +pub mod forms; pub mod handlers; pub mod resources; pub mod responses; diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/resources.rs b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/resources.rs new file mode 100644 index 000000000..357f1c365 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/resources.rs @@ -0,0 +1,129 @@ +//! API resources for the [`auth_key`](crate::v1::context::auth_key) API context. + +use bittorrent_tracker_core::authentication::{self, Key}; +use serde::{Deserialize, Serialize}; +use torrust_tracker_clock::conv::convert_from_iso_8601_to_timestamp; + +/// A resource that represents an authentication key. +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] +pub struct AuthKey { + /// The authentication key. + pub key: String, + /// The timestamp when the key will expire. + #[deprecated(since = "3.0.0", note = "please use `expiry_time` instead")] + pub valid_until: Option, // todo: remove when the torrust-index-backend starts using the `expiry_time` attribute. + /// The ISO 8601 timestamp when the key will expire. + pub expiry_time: Option, +} + +impl From for authentication::PeerKey { + fn from(auth_key_resource: AuthKey) -> Self { + authentication::PeerKey { + key: auth_key_resource.key.parse::().unwrap(), + valid_until: auth_key_resource + .expiry_time + .map(|expiry_time| convert_from_iso_8601_to_timestamp(&expiry_time)), + } + } +} + +#[allow(deprecated)] +impl From for AuthKey { + fn from(auth_key: authentication::PeerKey) -> Self { + match (auth_key.valid_until, auth_key.expiry_time()) { + (Some(valid_until), Some(expiry_time)) => AuthKey { + key: auth_key.key.to_string(), + valid_until: Some(valid_until.as_secs()), + expiry_time: Some(expiry_time.to_string()), + }, + _ => AuthKey { + key: auth_key.key.to_string(), + valid_until: None, + expiry_time: None, + }, + } + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use bittorrent_tracker_core::authentication::{self, Key}; + use torrust_tracker_clock::clock::stopped::Stopped as _; + use torrust_tracker_clock::clock::{self, Time}; + + use super::AuthKey; + use crate::CurrentClock; + + struct TestTime { + pub timestamp: u64, + pub iso_8601_v1: String, + pub iso_8601_v2: String, + } + + fn one_hour_after_unix_epoch() -> TestTime { + let timestamp = 60_u64; + let iso_8601_v1 = "1970-01-01T00:01:00.000Z".to_string(); + let iso_8601_v2 = "1970-01-01 00:01:00 UTC".to_string(); + TestTime { + timestamp, + iso_8601_v1, + iso_8601_v2, + } + } + + #[test] + #[allow(deprecated)] + fn it_should_be_convertible_into_an_auth_key() { + clock::Stopped::local_set_to_unix_epoch(); + + let auth_key_resource = AuthKey { + key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".to_string(), // cspell:disable-line + valid_until: Some(one_hour_after_unix_epoch().timestamp), + expiry_time: Some(one_hour_after_unix_epoch().iso_8601_v1), + }; + + assert_eq!( + authentication::PeerKey::from(auth_key_resource), + authentication::PeerKey { + key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".parse::().unwrap(), // cspell:disable-line + valid_until: Some(CurrentClock::now_add(&Duration::new(one_hour_after_unix_epoch().timestamp, 0)).unwrap()) + } + ); + } + + #[test] + #[allow(deprecated)] + fn it_should_be_convertible_from_an_auth_key() { + clock::Stopped::local_set_to_unix_epoch(); + + let auth_key = authentication::PeerKey { + key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".parse::().unwrap(), // cspell:disable-line + valid_until: Some(CurrentClock::now_add(&Duration::new(one_hour_after_unix_epoch().timestamp, 0)).unwrap()), + }; + + assert_eq!( + AuthKey::from(auth_key), + AuthKey { + key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".to_string(), // cspell:disable-line + valid_until: Some(one_hour_after_unix_epoch().timestamp), + expiry_time: Some(one_hour_after_unix_epoch().iso_8601_v2), + } + ); + } + + #[test] + #[allow(deprecated)] + fn it_should_be_convertible_into_json() { + assert_eq!( + serde_json::to_string(&AuthKey { + key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".to_string(), // cspell:disable-line + valid_until: Some(one_hour_after_unix_epoch().timestamp), + expiry_time: Some(one_hour_after_unix_epoch().iso_8601_v1), + }) + .unwrap(), + "{\"key\":\"IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM\",\"valid_until\":60,\"expiry_time\":\"1970-01-01T00:01:00.000Z\"}" // cspell:disable-line + ); + } +} diff --git a/src/servers/apis/v1/context/auth_key/responses.rs b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/responses.rs similarity index 60% rename from src/servers/apis/v1/context/auth_key/responses.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/auth_key/responses.rs index 51be162c5..8a0503703 100644 --- a/src/servers/apis/v1/context/auth_key/responses.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/responses.rs @@ -1,11 +1,11 @@ -//! API responses for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context. +//! API responses for the [`auth_key`](crate::v1::context::auth_key) API context. use std::error::Error; use axum::http::{header, StatusCode}; use axum::response::{IntoResponse, Response}; -use crate::servers::apis::v1::context::auth_key::resources::AuthKey; -use crate::servers::apis::v1::responses::unhandled_rejection_response; +use crate::v1::context::auth_key::resources::AuthKey; +use crate::v1::responses::{bad_request_response, unhandled_rejection_response}; /// `200` response that contains the `AuthKey` resource as json. /// @@ -22,12 +22,20 @@ pub fn auth_key_response(auth_key: &AuthKey) -> Response { .into_response() } +// Error responses + /// `500` error response when a new authentication key cannot be generated. #[must_use] pub fn failed_to_generate_key_response(e: E) -> Response { unhandled_rejection_response(format!("failed to generate key: {e}")) } +/// `500` error response when the provide key cannot be added. +#[must_use] +pub fn failed_to_add_key_response(e: E) -> Response { + unhandled_rejection_response(format!("failed to add key: {e}")) +} + /// `500` error response when an authentication key cannot be deleted. #[must_use] pub fn failed_to_delete_key_response(e: E) -> Response { @@ -40,3 +48,13 @@ pub fn failed_to_delete_key_response(e: E) -> Response { pub fn failed_to_reload_keys_response(e: E) -> Response { unhandled_rejection_response(format!("failed to reload keys: {e}")) } + +#[must_use] +pub fn invalid_auth_key_response(auth_key: &str, e: E) -> Response { + bad_request_response(&format!("Invalid URL: invalid auth key: string \"{auth_key}\", {e}")) +} + +#[must_use] +pub fn invalid_auth_key_duration_response(duration: u64) -> Response { + bad_request_response(&format!("Invalid URL: invalid auth key duration: \"{duration}\"")) +} diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/routes.rs new file mode 100644 index 000000000..64a0c1f11 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/routes.rs @@ -0,0 +1,45 @@ +//! API routes for the [`auth_key`](crate::v1::context::auth_key) +//! API context. +//! +//! - `POST /key/:seconds_valid` +//! - `DELETE /key/:key` +//! - `GET /keys/reload` +//! +//! Refer to the [API endpoint documentation](crate::v1::context::auth_key). +use std::sync::Arc; + +use axum::routing::{get, post}; +use axum::Router; +use bittorrent_tracker_core::authentication::handler::KeysHandler; + +use super::handlers::{add_auth_key_handler, delete_auth_key_handler, generate_auth_key_handler, reload_keys_handler}; + +/// It adds the routes to the router for the [`auth_key`](crate::v1::context::auth_key) API context. +pub fn add(prefix: &str, router: Router, keys_handler: &Arc) -> Router { + // Keys + router + .route( + // code-review: Axum does not allow two routes with the same path but different path variable name. + // In the new major API version, `seconds_valid` should be a POST form field so that we will have two paths: + // + // POST /keys + // DELETE /keys/:key + // + // The POST /key/:seconds_valid has been deprecated and it will removed in the future. + // Use POST /keys + &format!("{prefix}/key/{{seconds_valid_or_key}}"), + post(generate_auth_key_handler) + .with_state(keys_handler.clone()) + .delete(delete_auth_key_handler) + .with_state(keys_handler.clone()), + ) + // Keys command + .route( + &format!("{prefix}/keys/reload"), + get(reload_keys_handler).with_state(keys_handler.clone()), + ) + .route( + &format!("{prefix}/keys"), + post(add_auth_key_handler).with_state(keys_handler.clone()), + ) +} diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/health_check/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/health_check/handlers.rs new file mode 100644 index 000000000..dfcad1f56 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/v1/context/health_check/handlers.rs @@ -0,0 +1,11 @@ +//! API handlers for the [`stats`](crate::v1::context::health_check) +//! API context. + +use axum::Json; + +use super::resources::{Report, Status}; + +/// Endpoint for container health check. +pub async fn health_check_handler() -> Json { + Json(Report { status: Status::Ok }) +} diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/health_check/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/context/health_check/mod.rs new file mode 100644 index 000000000..6b1a1475f --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/v1/context/health_check/mod.rs @@ -0,0 +1,34 @@ +//! API health check endpoint. +//! +//! It is used to check is the service is running. Especially for containers. +//! +//! # Endpoints +//! +//! - [Health Check](#health-check) +//! +//! # Health Check +//! +//! `GET /api/health_check` +//! +//! Returns the API status. +//! +//! **Example request** +//! +//! ```bash +//! curl "http://127.0.0.1:1212/api/health_check" +//! ``` +//! +//! **Example response** `200` +//! +//! ```json +//! { +//! "status": "Ok", +//! } +//! ``` +//! +//! **Resource** +//! +//! Refer to the API [`Stats`](crate::context::health_check::resources::Report) +//! resource for more information about the response attributes. +pub mod handlers; +pub mod resources; diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/health_check/resources.rs b/packages/axum-rest-tracker-api-server/src/v1/context/health_check/resources.rs new file mode 100644 index 000000000..5ea5871f8 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/v1/context/health_check/resources.rs @@ -0,0 +1,14 @@ +//! API resources for the [`stats`](crate::v1::context::health_check) +//! API context. +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] +pub enum Status { + Ok, + Error, +} + +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] +pub struct Report { + pub status: Status, +} diff --git a/src/servers/apis/v1/context/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/context/mod.rs similarity index 91% rename from src/servers/apis/v1/context/mod.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/mod.rs index 5e268a429..be67cd96a 100644 --- a/src/servers/apis/v1/context/mod.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/mod.rs @@ -3,6 +3,7 @@ //! Each context is a module that contains the API endpoints related to a //! specific resource group. pub mod auth_key; +pub mod health_check; pub mod stats; pub mod torrent; pub mod whitelist; diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs new file mode 100644 index 000000000..1b1f670a0 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs @@ -0,0 +1,98 @@ +//! API handlers for the [`stats`](crate::v1::context::stats) +//! API context. +use std::sync::Arc; + +use axum::extract::State; +use axum::response::Response; +use axum_extra::extract::Query; +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use bittorrent_udp_tracker_core::services::banning::BanService; +use serde::Deserialize; +use tokio::sync::RwLock; +use torrust_rest_tracker_api_core::statistics::services::{get_labeled_metrics, get_metrics}; + +use super::responses::{labeled_metrics_response, labeled_stats_response, metrics_response, stats_response}; + +#[derive(Deserialize, Debug, Default)] +#[serde(rename_all = "lowercase")] +pub enum Format { + #[default] + Json, + Prometheus, +} + +#[derive(Deserialize, Debug)] +pub struct QueryParams { + /// The [`Format`] of the stats. + #[serde(default)] + pub format: Option, +} + +/// It handles the request to get the tracker global metrics. +/// +/// By default it returns a `200` response with the stats in JSON format. +/// +/// You can add the GET parameter `format=prometheus` to get the stats in +/// Prometheus Text Exposition Format. +/// +/// Refer to the [API endpoint documentation](crate::v1::context::stats#get-tracker-statistics) +/// for more information about this endpoint. +#[allow(clippy::type_complexity)] +pub async fn get_stats_handler( + State(state): State<( + Arc, + Arc, + Arc, + Arc, + )>, + params: Query, +) -> Response { + let metrics = get_metrics(state.0.clone(), state.1.clone(), state.2.clone(), state.3.clone()).await; + + match params.0.format { + Some(format) => match format { + Format::Json => stats_response(metrics), + Format::Prometheus => metrics_response(&metrics), + }, + None => stats_response(metrics), + } +} + +/// It handles the request to get the tracker extendable metrics. +/// +/// By default it returns a `200` response with the stats in JSON format. +/// +/// You can add the GET parameter `format=prometheus` to get the stats in +/// Prometheus Text Exposition Format. +#[allow(clippy::type_complexity)] +pub async fn get_metrics_handler( + State(state): State<( + Arc, + Arc>, + Arc, + Arc, + Arc, + Arc, + Arc, + )>, + params: Query, +) -> Response { + let metrics = get_labeled_metrics( + state.0.clone(), + state.1.clone(), + state.2.clone(), + state.3.clone(), + state.4.clone(), + state.5.clone(), + state.6.clone(), + ) + .await; + + match params.0.format { + Some(format) => match format { + Format::Json => labeled_stats_response(metrics), + Format::Prometheus => labeled_metrics_response(&metrics), + }, + None => labeled_stats_response(metrics), + } +} diff --git a/src/servers/apis/v1/context/stats/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/mod.rs similarity index 93% rename from src/servers/apis/v1/context/stats/mod.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/stats/mod.rs index 80f37f73f..5c6b0a39c 100644 --- a/src/servers/apis/v1/context/stats/mod.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/mod.rs @@ -44,7 +44,7 @@ //! //! **Resource** //! -//! Refer to the API [`Stats`](crate::servers::apis::v1::context::stats::resources::Stats) +//! Refer to the API [`Stats`](crate::v1::context::stats::resources::Stats) //! resource for more information about the response attributes. pub mod handlers; pub mod resources; diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs new file mode 100644 index 000000000..ece50383b --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs @@ -0,0 +1,221 @@ +//! API resources for the [`stats`](crate::v1::context::stats) +//! API context. +use serde::{Deserialize, Serialize}; +use torrust_rest_tracker_api_core::statistics::services::{TrackerLabeledMetrics, TrackerMetrics}; +use torrust_tracker_metrics::metric_collection::MetricCollection; + +/// It contains all the statistics generated by the tracker. +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] +pub struct Stats { + // Torrent metrics + /// Total number of torrents. + pub torrents: u64, + /// Total number of seeders for all torrents. + pub seeders: u64, + /// Total number of peers that have ever completed downloading for all torrents. + pub completed: u64, + /// Total number of leechers for all torrents. + pub leechers: u64, + + // Protocol metrics + /// Total number of TCP (HTTP tracker) connections from IPv4 peers. + /// Since the HTTP tracker spec does not require a handshake, this metric + /// increases for every HTTP request. + pub tcp4_connections_handled: u64, + /// Total number of TCP (HTTP tracker) `announce` requests from IPv4 peers. + pub tcp4_announces_handled: u64, + /// Total number of TCP (HTTP tracker) `scrape` requests from IPv4 peers. + pub tcp4_scrapes_handled: u64, + + /// Total number of TCP (HTTP tracker) connections from IPv6 peers. + pub tcp6_connections_handled: u64, + /// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers. + pub tcp6_announces_handled: u64, + /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. + pub tcp6_scrapes_handled: u64, + + // UDP + /// Total number of UDP (UDP tracker) requests aborted. + pub udp_requests_aborted: u64, + /// Total number of UDP (UDP tracker) requests banned. + pub udp_requests_banned: u64, + /// Total number of IPs banned for UDP (UDP tracker) requests. + pub udp_banned_ips_total: u64, + /// Average rounded time spent processing UDP connect requests. + pub udp_avg_connect_processing_time_ns: u64, + /// Average rounded time spent processing UDP announce requests. + pub udp_avg_announce_processing_time_ns: u64, + /// Average rounded time spent processing UDP scrape requests. + pub udp_avg_scrape_processing_time_ns: u64, + + // UDPv4 + /// Total number of UDP (UDP tracker) requests from IPv4 peers. + pub udp4_requests: u64, + /// Total number of UDP (UDP tracker) connections from IPv4 peers. + pub udp4_connections_handled: u64, + /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. + pub udp4_announces_handled: u64, + /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. + pub udp4_scrapes_handled: u64, + /// Total number of UDP (UDP tracker) responses from IPv4 peers. + pub udp4_responses: u64, + /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. + pub udp4_errors_handled: u64, + + // UDPv6 + /// Total number of UDP (UDP tracker) requests from IPv6 peers. + pub udp6_requests: u64, + /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. + pub udp6_connections_handled: u64, + /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. + pub udp6_announces_handled: u64, + /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. + pub udp6_scrapes_handled: u64, + /// Total number of UDP (UDP tracker) responses from IPv6 peers. + pub udp6_responses: u64, + /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. + pub udp6_errors_handled: u64, +} + +impl From for Stats { + #[allow(deprecated)] + fn from(metrics: TrackerMetrics) -> Self { + Self { + torrents: metrics.torrents_metrics.total_torrents, + seeders: metrics.torrents_metrics.total_complete, + completed: metrics.torrents_metrics.total_downloaded, + leechers: metrics.torrents_metrics.total_incomplete, + // TCP + tcp4_connections_handled: metrics.protocol_metrics.tcp4_connections_handled, + tcp4_announces_handled: metrics.protocol_metrics.tcp4_announces_handled, + tcp4_scrapes_handled: metrics.protocol_metrics.tcp4_scrapes_handled, + tcp6_connections_handled: metrics.protocol_metrics.tcp6_connections_handled, + tcp6_announces_handled: metrics.protocol_metrics.tcp6_announces_handled, + tcp6_scrapes_handled: metrics.protocol_metrics.tcp6_scrapes_handled, + // UDP + udp_requests_aborted: metrics.protocol_metrics.udp_requests_aborted, + udp_requests_banned: metrics.protocol_metrics.udp_requests_banned, + udp_banned_ips_total: metrics.protocol_metrics.udp_banned_ips_total, + udp_avg_connect_processing_time_ns: metrics.protocol_metrics.udp_avg_connect_processing_time_ns, + udp_avg_announce_processing_time_ns: metrics.protocol_metrics.udp_avg_announce_processing_time_ns, + udp_avg_scrape_processing_time_ns: metrics.protocol_metrics.udp_avg_scrape_processing_time_ns, + // UDPv4 + udp4_requests: metrics.protocol_metrics.udp4_requests, + udp4_connections_handled: metrics.protocol_metrics.udp4_connections_handled, + udp4_announces_handled: metrics.protocol_metrics.udp4_announces_handled, + udp4_scrapes_handled: metrics.protocol_metrics.udp4_scrapes_handled, + udp4_responses: metrics.protocol_metrics.udp4_responses, + udp4_errors_handled: metrics.protocol_metrics.udp4_errors_handled, + // UDPv6 + udp6_requests: metrics.protocol_metrics.udp6_requests, + udp6_connections_handled: metrics.protocol_metrics.udp6_connections_handled, + udp6_announces_handled: metrics.protocol_metrics.udp6_announces_handled, + udp6_scrapes_handled: metrics.protocol_metrics.udp6_scrapes_handled, + udp6_responses: metrics.protocol_metrics.udp6_responses, + udp6_errors_handled: metrics.protocol_metrics.udp6_errors_handled, + } + } +} + +/// It contains all the statistics generated by the tracker. +#[derive(Serialize, Debug, PartialEq)] +pub struct LabeledStats { + metrics: MetricCollection, +} + +impl From for LabeledStats { + #[allow(deprecated)] + fn from(metrics: TrackerLabeledMetrics) -> Self { + Self { + metrics: metrics.metrics, + } + } +} + +#[cfg(test)] +mod tests { + use torrust_rest_tracker_api_core::statistics::metrics::{ProtocolMetrics, TorrentsMetrics}; + use torrust_rest_tracker_api_core::statistics::services::TrackerMetrics; + + use super::Stats; + + #[test] + #[allow(deprecated)] + fn stats_resource_should_be_converted_from_tracker_metrics() { + assert_eq!( + Stats::from(TrackerMetrics { + torrents_metrics: TorrentsMetrics { + total_complete: 1, + total_downloaded: 2, + total_incomplete: 3, + total_torrents: 4 + }, + protocol_metrics: ProtocolMetrics { + // TCP + tcp4_connections_handled: 5, + tcp4_announces_handled: 6, + tcp4_scrapes_handled: 7, + tcp6_connections_handled: 8, + tcp6_announces_handled: 9, + tcp6_scrapes_handled: 10, + // UDP + udp_requests_aborted: 11, + udp_requests_banned: 12, + udp_banned_ips_total: 13, + udp_avg_connect_processing_time_ns: 14, + udp_avg_announce_processing_time_ns: 15, + udp_avg_scrape_processing_time_ns: 16, + // UDPv4 + udp4_requests: 17, + udp4_connections_handled: 18, + udp4_announces_handled: 19, + udp4_scrapes_handled: 20, + udp4_responses: 21, + udp4_errors_handled: 22, + // UDPv6 + udp6_requests: 23, + udp6_connections_handled: 24, + udp6_announces_handled: 25, + udp6_scrapes_handled: 26, + udp6_responses: 27, + udp6_errors_handled: 28 + } + }), + Stats { + torrents: 4, + seeders: 1, + completed: 2, + leechers: 3, + // TCPv4 + tcp4_connections_handled: 5, + tcp4_announces_handled: 6, + tcp4_scrapes_handled: 7, + // TCPv6 + tcp6_connections_handled: 8, + tcp6_announces_handled: 9, + tcp6_scrapes_handled: 10, + // UDP + udp_requests_aborted: 11, + udp_requests_banned: 12, + udp_banned_ips_total: 13, + udp_avg_connect_processing_time_ns: 14, + udp_avg_announce_processing_time_ns: 15, + udp_avg_scrape_processing_time_ns: 16, + // UDPv4 + udp4_requests: 17, + udp4_connections_handled: 18, + udp4_announces_handled: 19, + udp4_scrapes_handled: 20, + udp4_responses: 21, + udp4_errors_handled: 22, + // UDPv6 + udp6_requests: 23, + udp6_connections_handled: 24, + udp6_announces_handled: 25, + udp6_scrapes_handled: 26, + udp6_responses: 27, + udp6_errors_handled: 28 + } + ); + } +} diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs new file mode 100644 index 000000000..e79f7e562 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs @@ -0,0 +1,140 @@ +//! API responses for the [`stats`](crate::v1::context::stats) +//! API context. +use axum::response::{IntoResponse, Json, Response}; +use torrust_rest_tracker_api_core::statistics::services::{TrackerLabeledMetrics, TrackerMetrics}; +use torrust_tracker_metrics::prometheus::PrometheusSerializable; + +use super::resources::{LabeledStats, Stats}; + +/// `200` response that contains the [`LabeledStats`] resource as json. +#[must_use] +pub fn labeled_stats_response(tracker_metrics: TrackerLabeledMetrics) -> Response { + Json(LabeledStats::from(tracker_metrics)).into_response() +} + +#[must_use] +pub fn labeled_metrics_response(tracker_metrics: &TrackerLabeledMetrics) -> Response { + tracker_metrics.metrics.to_prometheus().into_response() +} + +/// `200` response that contains the [`Stats`] resource as json. +#[must_use] +pub fn stats_response(tracker_metrics: TrackerMetrics) -> Response { + Json(Stats::from(tracker_metrics)).into_response() +} + +/// `200` response that contains the [`Stats`] resource in Prometheus Text Exposition Format . +#[allow(deprecated)] +#[must_use] +pub fn metrics_response(tracker_metrics: &TrackerMetrics) -> Response { + let mut lines = vec![]; + + lines.push(format!("torrents {}", tracker_metrics.torrents_metrics.total_torrents)); + lines.push(format!("seeders {}", tracker_metrics.torrents_metrics.total_complete)); + lines.push(format!("completed {}", tracker_metrics.torrents_metrics.total_downloaded)); + lines.push(format!("leechers {}", tracker_metrics.torrents_metrics.total_incomplete)); + + // TCP + + // TCPv4 + + lines.push(format!( + "tcp4_connections_handled {}", + tracker_metrics.protocol_metrics.tcp4_connections_handled + )); + lines.push(format!( + "tcp4_announces_handled {}", + tracker_metrics.protocol_metrics.tcp4_announces_handled + )); + lines.push(format!( + "tcp4_scrapes_handled {}", + tracker_metrics.protocol_metrics.tcp4_scrapes_handled + )); + + // TCPv6 + + lines.push(format!( + "tcp6_connections_handled {}", + tracker_metrics.protocol_metrics.tcp6_connections_handled + )); + lines.push(format!( + "tcp6_announces_handled {}", + tracker_metrics.protocol_metrics.tcp6_announces_handled + )); + lines.push(format!( + "tcp6_scrapes_handled {}", + tracker_metrics.protocol_metrics.tcp6_scrapes_handled + )); + + // UDP + + lines.push(format!( + "udp_requests_aborted {}", + tracker_metrics.protocol_metrics.udp_requests_aborted + )); + lines.push(format!( + "udp_requests_banned {}", + tracker_metrics.protocol_metrics.udp_requests_banned + )); + lines.push(format!( + "udp_banned_ips_total {}", + tracker_metrics.protocol_metrics.udp_banned_ips_total + )); + lines.push(format!( + "udp_avg_connect_processing_time_ns {}", + tracker_metrics.protocol_metrics.udp_avg_connect_processing_time_ns + )); + lines.push(format!( + "udp_avg_announce_processing_time_ns {}", + tracker_metrics.protocol_metrics.udp_avg_announce_processing_time_ns + )); + lines.push(format!( + "udp_avg_scrape_processing_time_ns {}", + tracker_metrics.protocol_metrics.udp_avg_scrape_processing_time_ns + )); + + // UDPv4 + + lines.push(format!("udp4_requests {}", tracker_metrics.protocol_metrics.udp4_requests)); + lines.push(format!( + "udp4_connections_handled {}", + tracker_metrics.protocol_metrics.udp4_connections_handled + )); + lines.push(format!( + "udp4_announces_handled {}", + tracker_metrics.protocol_metrics.udp4_announces_handled + )); + lines.push(format!( + "udp4_scrapes_handled {}", + tracker_metrics.protocol_metrics.udp4_scrapes_handled + )); + lines.push(format!("udp4_responses {}", tracker_metrics.protocol_metrics.udp4_responses)); + lines.push(format!( + "udp4_errors_handled {}", + tracker_metrics.protocol_metrics.udp4_errors_handled + )); + + // UDPv6 + + lines.push(format!("udp6_requests {}", tracker_metrics.protocol_metrics.udp6_requests)); + lines.push(format!( + "udp6_connections_handled {}", + tracker_metrics.protocol_metrics.udp6_connections_handled + )); + lines.push(format!( + "udp6_announces_handled {}", + tracker_metrics.protocol_metrics.udp6_announces_handled + )); + lines.push(format!( + "udp6_scrapes_handled {}", + tracker_metrics.protocol_metrics.udp6_scrapes_handled + )); + lines.push(format!("udp6_responses {}", tracker_metrics.protocol_metrics.udp6_responses)); + lines.push(format!( + "udp6_errors_handled {}", + tracker_metrics.protocol_metrics.udp6_errors_handled + )); + + // Return the plain text response + lines.join("\n").into_response() +} diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs new file mode 100644 index 000000000..2bf3776fd --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs @@ -0,0 +1,42 @@ +//! API routes for the [`stats`](crate::v1::context::stats) API context. +//! +//! - `GET /stats` +//! +//! Refer to the [API endpoint documentation](crate::v1::context::stats). +use std::sync::Arc; + +use axum::routing::get; +use axum::Router; +use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; + +use super::handlers::{get_metrics_handler, get_stats_handler}; + +/// It adds the routes to the router for the [`stats`](crate::v1::context::stats) API context. +pub fn add(prefix: &str, router: Router, http_api_container: &Arc) -> Router { + router + .route( + &format!("{prefix}/stats"), + get(get_stats_handler).with_state(( + http_api_container.tracker_core_container.in_memory_torrent_repository.clone(), + http_api_container.tracker_core_container.stats_repository.clone(), + http_api_container.http_stats_repository.clone(), + http_api_container.udp_server_stats_repository.clone(), + )), + ) + .route( + &format!("{prefix}/metrics"), + get(get_metrics_handler).with_state(( + http_api_container.tracker_core_container.in_memory_torrent_repository.clone(), + http_api_container.ban_service.clone(), + // Stats + http_api_container + .swarm_coordination_registry_container + .stats_repository + .clone(), + http_api_container.tracker_core_container.stats_repository.clone(), + http_api_container.http_stats_repository.clone(), + http_api_container.udp_core_stats_repository.clone(), + http_api_container.udp_server_stats_repository.clone(), + )), + ) +} diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/torrent/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/handlers.rs new file mode 100644 index 000000000..eecbd9ac3 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/handlers.rs @@ -0,0 +1,143 @@ +//! API handlers for the [`torrent`](crate::v1::context::torrent) +//! API context. +use std::fmt; +use std::str::FromStr; +use std::sync::Arc; + +use axum::extract::{Path, State}; +use axum::response::{IntoResponse, Response}; +use axum_extra::extract::Query; +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use bittorrent_tracker_core::torrent::services::{get_torrent_info, get_torrents, get_torrents_page}; +use serde::{de, Deserialize, Deserializer}; +use thiserror::Error; +use torrust_tracker_primitives::pagination::Pagination; + +use super::responses::{torrent_info_response, torrent_list_response, torrent_not_known_response}; +use crate::v1::responses::invalid_info_hash_param_response; +use crate::InfoHashParam; + +/// It handles the request to get the torrent data. +/// +/// It returns: +/// +/// - `200` response with a json [`Torrent`](crate::v1::context::torrent::resources::torrent::Torrent). +/// - `500` with serialized error in debug format if the torrent is not known. +/// +/// Refer to the [API endpoint documentation](crate::v1::context::torrent#get-a-torrent) +/// for more information about this endpoint. +pub async fn get_torrent_handler( + State(in_memory_torrent_repository): State>, + Path(info_hash): Path, +) -> Response { + match InfoHash::from_str(&info_hash.0) { + Err(_) => invalid_info_hash_param_response(&info_hash.0), + Ok(info_hash) => match get_torrent_info(&in_memory_torrent_repository, &info_hash).await { + Some(info) => torrent_info_response(info).into_response(), + None => torrent_not_known_response(), + }, + } +} + +/// A container for the URL query parameters. +/// +/// Pagination: `offset` and `limit`. +/// Array of infohashes: `info_hash`. +/// +/// You can either get all torrents with pagination or get a list of torrents +/// providing a list of infohashes. For example: +/// +/// First page of torrents: +/// +/// +/// +/// +/// Only two torrents: +/// +/// +/// +/// +/// NOTICE: Pagination is ignored if array of infohashes is provided. +#[derive(Deserialize, Debug)] +pub struct QueryParams { + /// The offset of the first page to return. Starts at 0. + #[serde(default, deserialize_with = "empty_string_as_none")] + pub offset: Option, + /// The maximum number of items to return per page. + #[serde(default, deserialize_with = "empty_string_as_none")] + pub limit: Option, + /// A list of infohashes to retrieve. + #[serde(default, rename = "info_hash")] + pub info_hashes: Vec, +} + +/// It handles the request to get a list of torrents. +/// +/// It returns a `200` response with a json array with [`crate::v1::context::torrent::resources::torrent::ListItem`] resources. +/// +/// Refer to the [API endpoint documentation](crate::v1::context::torrent#list-torrents) +/// for more information about this endpoint. +pub async fn get_torrents_handler( + State(in_memory_torrent_repository): State>, + pagination: Query, +) -> Response { + tracing::debug!("pagination: {:?}", pagination); + + if pagination.0.info_hashes.is_empty() { + torrent_list_response( + &get_torrents_page( + &in_memory_torrent_repository, + Some(&Pagination::new_with_options(pagination.0.offset, pagination.0.limit)), + ) + .await, + ) + .into_response() + } else { + match parse_info_hashes(pagination.0.info_hashes) { + Ok(info_hashes) => { + torrent_list_response(&get_torrents(&in_memory_torrent_repository, &info_hashes).await).into_response() + } + Err(err) => match err { + QueryParamError::InvalidInfoHash { info_hash } => invalid_info_hash_param_response(&info_hash), + }, + } + } +} + +#[derive(Error, Debug)] +pub enum QueryParamError { + #[error("invalid infohash {info_hash}")] + InvalidInfoHash { info_hash: String }, +} + +fn parse_info_hashes(info_hashes_str: Vec) -> Result, QueryParamError> { + let mut info_hashes: Vec = Vec::new(); + + for info_hash_str in info_hashes_str { + match InfoHash::from_str(&info_hash_str) { + Ok(info_hash) => info_hashes.push(info_hash), + Err(_err) => { + return Err(QueryParamError::InvalidInfoHash { + info_hash: info_hash_str, + }) + } + } + } + + Ok(info_hashes) +} + +/// Serde deserialization decorator to map empty Strings to None, +fn empty_string_as_none<'de, D, T>(de: D) -> Result, D::Error> +where + D: Deserializer<'de>, + T: FromStr, + T::Err: fmt::Display, +{ + let opt = Option::::deserialize(de)?; + match opt.as_deref() { + None | Some("") => Ok(None), + Some(s) => FromStr::from_str(s).map_err(de::Error::custom).map(Some), + } +} diff --git a/src/servers/apis/v1/context/torrent/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/mod.rs similarity index 92% rename from src/servers/apis/v1/context/torrent/mod.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/torrent/mod.rs index 1658e1748..1a62fef25 100644 --- a/src/servers/apis/v1/context/torrent/mod.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/mod.rs @@ -62,7 +62,7 @@ //! //! **Resource** //! -//! Refer to the API [`Torrent`](crate::servers::apis::v1::context::torrent::resources::torrent::Torrent) +//! Refer to the API [`Torrent`](crate::v1::context::torrent::resources::torrent::Torrent) //! resource for more information about the response attributes. //! //! # List torrents @@ -102,7 +102,7 @@ //! //! **Resource** //! -//! Refer to the API [`ListItem`](crate::servers::apis::v1::context::torrent::resources::torrent::ListItem) +//! Refer to the API [`ListItem`](crate::v1::context::torrent::resources::torrent::ListItem) //! resource for more information about the attributes for a single item in the //! response. //! diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/mod.rs new file mode 100644 index 000000000..8e31036d3 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/mod.rs @@ -0,0 +1,4 @@ +//! API resources for the [`torrent`](crate::v1::context::torrent) +//! API context. +pub mod peer; +pub mod torrent; diff --git a/src/servers/apis/v1/context/torrent/resources/peer.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/peer.rs similarity index 51% rename from src/servers/apis/v1/context/torrent/resources/peer.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/peer.rs index 539637b35..dd4a6cc26 100644 --- a/src/servers/apis/v1/context/torrent/resources/peer.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/peer.rs @@ -1,12 +1,13 @@ //! `Peer` and Peer `Id` API resources. +use aquatic_udp_protocol::PeerId; +use derive_more::From; use serde::{Deserialize, Serialize}; - -use crate::tracker; +use torrust_tracker_primitives::peer; /// `Peer` API resource. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub struct Peer { - /// The peer's ID. See [`Id`](crate::servers::apis::v1::context::torrent::resources::peer::Id). + /// The peer's ID. See [`Id`]. pub peer_id: Id, /// The peer's socket address. For example: `192.168.1.88:17548`. pub peer_addr: String, @@ -22,7 +23,7 @@ pub struct Peer { /// The peer's left bytes (pending to download). pub left: i64, /// The peer's event: `started`, `stopped`, `completed`. - /// See [`AnnounceEventDef`](crate::shared::bit_torrent::common::AnnounceEventDef). + /// See [`AnnounceEvent`](aquatic_udp_protocol::AnnounceEvent). pub event: String, } @@ -35,27 +36,42 @@ pub struct Id { pub client: Option, } -impl From for Id { - fn from(peer_id: tracker::peer::Id) -> Self { +impl From for Id { + fn from(peer_id: PeerId) -> Self { + let peer_id = peer::Id::from(peer_id); Id { id: peer_id.to_hex_string(), - client: peer_id.get_client_name().map(std::string::ToString::to_string), + client: peer_id.get_client_name(), } } } -impl From for Peer { - #[allow(deprecated)] - fn from(peer: tracker::peer::Peer) -> Self { +impl From for Peer { + fn from(value: peer::Peer) -> Self { + #[allow(deprecated)] Peer { - peer_id: Id::from(peer.peer_id), - peer_addr: peer.peer_addr.to_string(), - updated: peer.updated.as_millis(), - updated_milliseconds_ago: peer.updated.as_millis(), - uploaded: peer.uploaded.0, - downloaded: peer.downloaded.0, - left: peer.left.0, - event: format!("{:?}", peer.event), + peer_id: Id::from(value.peer_id), + peer_addr: value.peer_addr.to_string(), + updated: value.updated.as_millis(), + updated_milliseconds_ago: value.updated.as_millis(), + uploaded: value.uploaded.0.get(), + downloaded: value.downloaded.0.get(), + left: value.left.0.get(), + event: format!("{:?}", value.event), + } + } +} + +#[derive(From, PartialEq, Default)] +pub struct Vector(pub Vec); + +impl FromIterator for Vector { + fn from_iter>(iter: T) -> Self { + let mut peers = Vector::default(); + + for i in iter { + peers.0.push(i.into()); } + peers } } diff --git a/src/servers/apis/v1/context/torrent/resources/torrent.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/torrent.rs similarity index 71% rename from src/servers/apis/v1/context/torrent/resources/torrent.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/torrent.rs index c9dbd1c02..1753b60b9 100644 --- a/src/servers/apis/v1/context/torrent/resources/torrent.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/torrent.rs @@ -2,13 +2,11 @@ //! //! - `Torrent` is the full torrent resource. //! - `ListItem` is a list item resource on a torrent list. `ListItem` does -//! include a `peers` field but it is always `None` in the struct and `null` in -//! the JSON response. +//! include a `peers` field but it is always `None` in the struct and `null` in +//! the JSON response. +use bittorrent_tracker_core::torrent::services::{BasicInfo, Info}; use serde::{Deserialize, Serialize}; -use super::peer; -use crate::tracker::services::torrent::{BasicInfo, Info}; - /// `Torrent` API resource. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub struct Torrent { @@ -23,7 +21,7 @@ pub struct Torrent { /// The torrent's leechers counter. Active peers that are downloading the /// torrent. pub leechers: u64, - /// The torrent's peers. See [`Peer`](crate::servers::apis::v1::context::torrent::resources::peer::Peer). + /// The torrent's peers. See [`Peer`](crate::v1::context::torrent::resources::peer::Peer). #[serde(skip_serializing_if = "Option::is_none")] pub peers: Option>, } @@ -44,9 +42,6 @@ pub struct ListItem { /// The torrent's leechers counter. Active peers that are downloading the /// torrent. pub leechers: u64, - /// The torrent's peers. It's always `None` in the struct and `null` in the - /// JSON response. - pub peers: Option>, // todo: this is always None. Remove field from endpoint? } impl ListItem { @@ -59,8 +54,8 @@ impl ListItem { } } -/// Maps an array of the domain type [`BasicInfo`](crate::tracker::services::torrent::BasicInfo) -/// to the API resource type [`ListItem`](crate::servers::apis::v1::context::torrent::resources::torrent::ListItem). +/// Maps an array of the domain type [`BasicInfo`] +/// to the API resource type [`ListItem`]. #[must_use] pub fn to_resource(basic_info_vec: &[BasicInfo]) -> Vec { basic_info_vec @@ -71,14 +66,16 @@ pub fn to_resource(basic_info_vec: &[BasicInfo]) -> Vec { impl From for Torrent { fn from(info: Info) -> Self { + let peers: Option = info.peers.map(|peers| peers.into_iter().collect()); + + let peers: Option> = peers.map(|peers| peers.0); + Self { info_hash: info.info_hash.to_string(), seeders: info.seeders, completed: info.completed, leechers: info.leechers, - peers: info - .peers - .map(|peers| peers.iter().map(|peer| peer::Peer::from(*peer)).collect()), + peers, } } } @@ -90,7 +87,6 @@ impl From for ListItem { seeders: basic_info.seeders, completed: basic_info.completed, leechers: basic_info.leechers, - peers: None, } } } @@ -100,24 +96,23 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::str::FromStr; - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use bittorrent_primitives::info_hash::InfoHash; + use bittorrent_tracker_core::torrent::services::{BasicInfo, Info}; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use super::Torrent; - use crate::servers::apis::v1::context::torrent::resources::peer::Peer; - use crate::servers::apis::v1::context::torrent::resources::torrent::ListItem; - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::shared::clock::DurationSinceUnixEpoch; - use crate::tracker::peer; - use crate::tracker::services::torrent::{BasicInfo, Info}; + use crate::v1::context::torrent::resources::peer::Peer; + use crate::v1::context::torrent::resources::torrent::ListItem; fn sample_peer() -> peer::Peer { peer::Peer { - peer_id: peer::Id(*b"-qB00000000000000000"), + peer_id: PeerId(*b"-qB00000000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), event: AnnounceEvent::Started, } } @@ -126,14 +121,14 @@ mod tests { fn torrent_resource_should_be_converted_from_torrent_info() { assert_eq!( Torrent::from(Info { - info_hash: InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(), + info_hash: InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(), // DevSkim: ignore DS173237 seeders: 1, completed: 2, leechers: 3, peers: Some(vec![sample_peer()]), }), Torrent { - info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), + info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), // DevSkim: ignore DS173237 seeders: 1, completed: 2, leechers: 3, @@ -146,17 +141,16 @@ mod tests { fn torrent_resource_list_item_should_be_converted_from_the_basic_torrent_info() { assert_eq!( ListItem::from(BasicInfo { - info_hash: InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(), + info_hash: InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(), // DevSkim: ignore DS173237 seeders: 1, completed: 2, leechers: 3, }), ListItem { - info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), + info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), // DevSkim: ignore DS173237 seeders: 1, completed: 2, leechers: 3, - peers: None, } ); } diff --git a/src/servers/apis/v1/context/torrent/responses.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/responses.rs similarity index 68% rename from src/servers/apis/v1/context/torrent/responses.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/torrent/responses.rs index d3be092eb..e498c6c59 100644 --- a/src/servers/apis/v1/context/torrent/responses.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/responses.rs @@ -1,20 +1,20 @@ -//! API responses for the [`torrent`](crate::servers::apis::v1::context::torrent) +//! API responses for the [`torrent`](crate::v1::context::torrent) //! API context. use axum::response::{IntoResponse, Json, Response}; +use bittorrent_tracker_core::torrent::services::{BasicInfo, Info}; use serde_json::json; use super::resources::torrent::{ListItem, Torrent}; -use crate::tracker::services::torrent::{BasicInfo, Info}; /// `200` response that contains an array of -/// [`ListItem`](crate::servers::apis::v1::context::torrent::resources::torrent::ListItem) +/// [`ListItem`] /// resources as json. pub fn torrent_list_response(basic_infos: &[BasicInfo]) -> Json> { Json(ListItem::new_vec(basic_infos)) } /// `200` response that contains a -/// [`Torrent`](crate::servers::apis::v1::context::torrent::resources::torrent::Torrent) +/// [`Torrent`] /// resources as json. pub fn torrent_info_response(info: Info) -> Json { Json(Torrent::from(info)) diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/torrent/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/routes.rs new file mode 100644 index 000000000..678fe7783 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/routes.rs @@ -0,0 +1,27 @@ +//! API routes for the [`torrent`](crate::v1::context::torrent) API context. +//! +//! - `GET /torrent/:info_hash` +//! - `GET /torrents` +//! +//! Refer to the [API endpoint documentation](crate::v1::context::torrent). +use std::sync::Arc; + +use axum::routing::get; +use axum::Router; +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + +use super::handlers::{get_torrent_handler, get_torrents_handler}; + +/// It adds the routes to the router for the [`torrent`](crate::v1::context::torrent) API context. +pub fn add(prefix: &str, router: Router, in_memory_torrent_repository: &Arc) -> Router { + // Torrents + router + .route( + &format!("{prefix}/torrent/{{info_hash}}"), + get(get_torrent_handler).with_state(in_memory_torrent_repository.clone()), + ) + .route( + &format!("{prefix}/torrents"), + get(get_torrents_handler).with_state(in_memory_torrent_repository.clone()), + ) +} diff --git a/src/servers/apis/v1/context/whitelist/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/handlers.rs similarity index 50% rename from src/servers/apis/v1/context/whitelist/handlers.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/whitelist/handlers.rs index 8e8c20b50..bafa8aaff 100644 --- a/src/servers/apis/v1/context/whitelist/handlers.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/handlers.rs @@ -1,36 +1,36 @@ -//! API handlers for the [`whitelist`](crate::servers::apis::v1::context::whitelist) +//! API handlers for the [`whitelist`](crate::v1::context::whitelist) //! API context. use std::str::FromStr; use std::sync::Arc; use axum::extract::{Path, State}; use axum::response::Response; +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use super::responses::{ failed_to_reload_whitelist_response, failed_to_remove_torrent_from_whitelist_response, failed_to_whitelist_torrent_response, }; -use crate::servers::apis::v1::responses::{invalid_info_hash_param_response, ok_response}; -use crate::servers::apis::InfoHashParam; -use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::Tracker; +use crate::v1::responses::{invalid_info_hash_param_response, ok_response}; +use crate::InfoHashParam; /// It handles the request to add a torrent to the whitelist. /// /// It returns: /// -/// - `200` response with a [`ActionStatus::Ok`](crate::servers::apis::v1::responses::ActionStatus::Ok) in json. +/// - `200` response with a [`ActionStatus::Ok`](crate::v1::responses::ActionStatus::Ok) in json. /// - `500` with serialized error in debug format if the torrent couldn't be whitelisted. /// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::whitelist#add-a-torrent-to-the-whitelist) +/// Refer to the [API endpoint documentation](crate::v1::context::whitelist#add-a-torrent-to-the-whitelist) /// for more information about this endpoint. pub async fn add_torrent_to_whitelist_handler( - State(tracker): State>, + State(whitelist_manager): State>, Path(info_hash): Path, ) -> Response { match InfoHash::from_str(&info_hash.0) { Err(_) => invalid_info_hash_param_response(&info_hash.0), - Ok(info_hash) => match tracker.add_torrent_to_whitelist(&info_hash).await { - Ok(_) => ok_response(), + Ok(info_hash) => match whitelist_manager.add_torrent_to_whitelist(&info_hash).await { + Ok(()) => ok_response(), Err(e) => failed_to_whitelist_torrent_response(e), }, } @@ -40,20 +40,20 @@ pub async fn add_torrent_to_whitelist_handler( /// /// It returns: /// -/// - `200` response with a [`ActionStatus::Ok`](crate::servers::apis::v1::responses::ActionStatus::Ok) in json. +/// - `200` response with a [`ActionStatus::Ok`](crate::v1::responses::ActionStatus::Ok) in json. /// - `500` with serialized error in debug format if the torrent couldn't be -/// removed from the whitelisted. +/// removed from the whitelisted. /// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::whitelist#remove-a-torrent-from-the-whitelist) +/// Refer to the [API endpoint documentation](crate::v1::context::whitelist#remove-a-torrent-from-the-whitelist) /// for more information about this endpoint. pub async fn remove_torrent_from_whitelist_handler( - State(tracker): State>, + State(whitelist_manager): State>, Path(info_hash): Path, ) -> Response { match InfoHash::from_str(&info_hash.0) { Err(_) => invalid_info_hash_param_response(&info_hash.0), - Ok(info_hash) => match tracker.remove_torrent_from_whitelist(&info_hash).await { - Ok(_) => ok_response(), + Ok(info_hash) => match whitelist_manager.remove_torrent_from_whitelist(&info_hash).await { + Ok(()) => ok_response(), Err(e) => failed_to_remove_torrent_from_whitelist_response(e), }, } @@ -63,15 +63,15 @@ pub async fn remove_torrent_from_whitelist_handler( /// /// It returns: /// -/// - `200` response with a [`ActionStatus::Ok`](crate::servers::apis::v1::responses::ActionStatus::Ok) in json. +/// - `200` response with a [`ActionStatus::Ok`](crate::v1::responses::ActionStatus::Ok) in json. /// - `500` with serialized error in debug format if the torrent whitelist -/// couldn't be reloaded from the database. +/// couldn't be reloaded from the database. /// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::whitelist#reload-the-whitelist) +/// Refer to the [API endpoint documentation](crate::v1::context::whitelist#reload-the-whitelist) /// for more information about this endpoint. -pub async fn reload_whitelist_handler(State(tracker): State>) -> Response { - match tracker.load_whitelist_from_database().await { - Ok(_) => ok_response(), +pub async fn reload_whitelist_handler(State(whitelist_manager): State>) -> Response { + match whitelist_manager.load_whitelist_from_database().await { + Ok(()) => ok_response(), Err(e) => failed_to_reload_whitelist_response(e), } } diff --git a/src/servers/apis/v1/context/whitelist/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/mod.rs similarity index 90% rename from src/servers/apis/v1/context/whitelist/mod.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/whitelist/mod.rs index 2bb35ef65..79da43fdc 100644 --- a/src/servers/apis/v1/context/whitelist/mod.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/mod.rs @@ -11,12 +11,12 @@ //! torrents in the whitelist. The whitelist can be updated using the API. //! //! > **NOTICE**: the whitelist is only used when the tracker is configured to -//! in `listed` or `private_listed` modes. Refer to the -//! [configuration crate documentation](https://docs.rs/torrust-tracker-configuration) -//! to know how to enable the those modes. +//! > in `listed` or `private_listed` modes. Refer to the +//! > [configuration crate documentation](https://docs.rs/torrust-tracker-configuration) +//! > to know how to enable the those modes. //! //! > **NOTICE**: if the tracker is not running in `listed` or `private_listed` -//! modes the requests to the whitelist API will be ignored. +//! > modes the requests to the whitelist API will be ignored. //! //! # Endpoints //! diff --git a/src/servers/apis/v1/context/whitelist/responses.rs b/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/responses.rs similarity index 84% rename from src/servers/apis/v1/context/whitelist/responses.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/whitelist/responses.rs index ce901c2f0..1e4d66f7f 100644 --- a/src/servers/apis/v1/context/whitelist/responses.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/responses.rs @@ -1,10 +1,10 @@ -//! API responses for the [`whitelist`](crate::servers::apis::v1::context::whitelist) +//! API responses for the [`whitelist`](crate::v1::context::whitelist) //! API context. use std::error::Error; use axum::response::Response; -use crate::servers::apis::v1::responses::unhandled_rejection_response; +use crate::v1::responses::unhandled_rejection_response; /// `500` error response when a torrent cannot be removed from the whitelist. #[must_use] diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/routes.rs new file mode 100644 index 000000000..c99b008b3 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/routes.rs @@ -0,0 +1,35 @@ +//! API routes for the [`whitelist`](crate::v1::context::whitelist) API context. +//! +//! - `POST /whitelist/:info_hash` +//! - `DELETE /whitelist/:info_hash` +//! - `GET /whitelist/reload` +//! +//! Refer to the [API endpoint documentation](crate::v1::context::torrent). +use std::sync::Arc; + +use axum::routing::{delete, get, post}; +use axum::Router; +use bittorrent_tracker_core::whitelist::manager::WhitelistManager; + +use super::handlers::{add_torrent_to_whitelist_handler, reload_whitelist_handler, remove_torrent_from_whitelist_handler}; + +/// It adds the routes to the router for the [`whitelist`](crate::v1::context::whitelist) API context. +pub fn add(prefix: &str, router: Router, whitelist_manager: &Arc) -> Router { + let prefix = format!("{prefix}/whitelist"); + + router + // Whitelisted torrents + .route( + &format!("{prefix}/{{info_hash}}"), + post(add_torrent_to_whitelist_handler).with_state(whitelist_manager.clone()), + ) + .route( + &format!("{prefix}/{{info_hash}}"), + delete(remove_torrent_from_whitelist_handler).with_state(whitelist_manager.clone()), + ) + // Whitelist commands + .route( + &format!("{prefix}/reload"), + get(reload_whitelist_handler).with_state(whitelist_manager.clone()), + ) +} diff --git a/packages/axum-rest-tracker-api-server/src/v1/middlewares/auth.rs b/packages/axum-rest-tracker-api-server/src/v1/middlewares/auth.rs new file mode 100644 index 000000000..9b5ec2320 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/v1/middlewares/auth.rs @@ -0,0 +1,170 @@ +//! Authentication middleware for the API. +//! +//! It uses a "token" to authenticate the user. The token must be one of the +//! `access_tokens` in the tracker [HTTP API configuration](torrust_tracker_configuration::HttpApi). +//! +//! There are two ways to provide the token: +//! +//! 1. As a `Bearer` token in the `Authorization` header. +//! 2. As a `token` GET param in the URL. +//! +//! Using the `Authorization` header: +//! +//! ```console +//! curl -H "Authorization: Bearer MyAccessToken" http://:/api/v1/ +//! ``` +//! +//! Using the `token` GET param: +//! +//! `http://:/api/v1/?token=`. +//! +//! > **NOTICE**: the token can be at any position in the URL, not just at the +//! > beginning or at the end. +//! +//! The token must be one of the `access_tokens` in the tracker +//! [HTTP API configuration](torrust_tracker_configuration::HttpApi). +//! +//! The configuration file `tracker.toml` contains a list of tokens: +//! +//! ```toml +//! [http_api.access_tokens] +//! admin = "MyAccessToken" +//! ``` +//! +//! All the tokes have the same permissions, so it is not possible to have +//! different permissions for different tokens. The label is only used to +//! identify the token. +//! +//! NOTICE: The token is not encrypted, so it is recommended to use HTTPS to +//! protect the token from being intercepted. +//! +//! NOTICE: If both the `Authorization` header and the `token` GET param are +//! provided, the `Authorization` header will be used. +use std::sync::Arc; + +use axum::extract::{self}; +use axum::http::Request; +use axum::middleware::Next; +use axum::response::{IntoResponse, Response}; +use serde::Deserialize; +use torrust_tracker_configuration::AccessTokens; + +use crate::v1::responses::unhandled_rejection_response; + +pub const AUTH_BEARER_TOKEN_HEADER_PREFIX: &str = "Bearer"; + +/// Container for the `token` extracted from the query params. +#[derive(Deserialize, Debug)] +pub struct QueryParams { + pub token: Option, +} + +#[derive(Clone, Debug)] +pub struct State { + pub access_tokens: Arc, +} + +/// Middleware for authentication. +/// +/// The token must be one of the tokens in the tracker [HTTP API configuration](torrust_tracker_configuration::HttpApi). +pub async fn auth( + extract::State(state): extract::State, + extract::Query(params): extract::Query, + request: Request, + next: Next, +) -> Response { + let token_from_header = match extract_bearer_token_from_header(&request) { + Ok(token) => token, + Err(err) => return err.into_response(), + }; + + let token_from_get_param = params.token.clone(); + + let provided_tokens = (token_from_header, token_from_get_param); + + let token = match provided_tokens { + (Some(token_from_header), Some(_token_from_get_param)) => token_from_header, + (Some(token_from_header), None) => token_from_header, + (None, Some(token_from_get_param)) => token_from_get_param, + (None, None) => return AuthError::Unauthorized.into_response(), + }; + + if !authenticate(&token, &state.access_tokens) { + return AuthError::TokenNotValid.into_response(); + } + + next.run(request).await +} + +fn extract_bearer_token_from_header(request: &Request) -> Result, AuthError> { + let headers = request.headers(); + + let header_value = headers + .get(axum::http::header::AUTHORIZATION) + .and_then(|header_value| header_value.to_str().ok()); + + match header_value { + None => Ok(None), + Some(header_value) => { + if header_value == AUTH_BEARER_TOKEN_HEADER_PREFIX { + // Empty token + return Ok(Some(String::new())); + } + + if !header_value.starts_with(&format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} ").to_string()) { + // Invalid token type. Missing "Bearer" prefix. + return Err(AuthError::UnknownTokenProvided); + } + + Ok(header_value + .strip_prefix(&format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} ").to_string()) + .map(std::string::ToString::to_string)) + } + } +} + +enum AuthError { + /// Missing token for authentication. + Unauthorized, + + /// Token was provided but it is not valid. + TokenNotValid, + + /// Token was provided but it is not in a format that the server can't understands. + UnknownTokenProvided, +} + +impl IntoResponse for AuthError { + fn into_response(self) -> Response { + match self { + AuthError::Unauthorized => unauthorized_response(), + AuthError::TokenNotValid => token_not_valid_response(), + AuthError::UnknownTokenProvided => unknown_auth_data_provided_response(), + } + } +} + +fn authenticate(token: &str, tokens: &AccessTokens) -> bool { + tokens.values().any(|t| t == token) +} + +/// `500` error response returned when the token is missing. +#[must_use] +pub fn unauthorized_response() -> Response { + unhandled_rejection_response("unauthorized".to_string()) +} + +/// `500` error response when the provided token is not valid. +#[must_use] +pub fn token_not_valid_response() -> Response { + unhandled_rejection_response("token not valid".to_string()) +} + +/// `500` error response when the provided token type is not valid. +/// +/// The client has provided authentication information that the server does not +/// understand. +#[must_use] +pub fn unknown_auth_data_provided_response() -> Response { + unhandled_rejection_response("unknown token provided".to_string()) +} diff --git a/src/servers/apis/v1/middlewares/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/middlewares/mod.rs similarity index 100% rename from src/servers/apis/v1/middlewares/mod.rs rename to packages/axum-rest-tracker-api-server/src/v1/middlewares/mod.rs diff --git a/src/servers/apis/v1/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/mod.rs similarity index 54% rename from src/servers/apis/v1/mod.rs rename to packages/axum-rest-tracker-api-server/src/v1/mod.rs index 213ee9335..7910d7d4d 100644 --- a/src/servers/apis/v1/mod.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/mod.rs @@ -4,17 +4,17 @@ //! //! Context | Description | Version //! ---|---|--- -//! `Stats` | Tracker statistics | [`v1`](crate::servers::apis::v1::context::stats) -//! `Torrents` | Torrents | [`v1`](crate::servers::apis::v1::context::torrent) -//! `Whitelist` | Torrents whitelist | [`v1`](crate::servers::apis::v1::context::whitelist) -//! `Authentication keys` | Authentication keys | [`v1`](crate::servers::apis::v1::context::auth_key) +//! `Stats` | Tracker statistics | [`v1`](crate::v1::context::stats) +//! `Torrents` | Torrents | [`v1`](crate::v1::context::torrent) +//! `Whitelist` | Torrents whitelist | [`v1`](crate::v1::context::whitelist) +//! `Authentication keys` | Authentication keys | [`v1`](crate::v1::context::auth_key) //! //! > **NOTICE**: //! - The authentication keys are only used by the HTTP tracker. //! - The whitelist is only used when the tracker is running in `listed` or -//! `private_listed` mode. +//! `private_listed` mode. //! -//! Refer to the [authentication middleware](crate::servers::apis::v1::middlewares::auth) +//! Refer to the [authentication middleware](crate::v1::middlewares::auth) //! for more information about the authentication process. pub mod context; pub mod middlewares; diff --git a/src/servers/apis/v1/responses.rs b/packages/axum-rest-tracker-api-server/src/v1/responses.rs similarity index 97% rename from src/servers/apis/v1/responses.rs rename to packages/axum-rest-tracker-api-server/src/v1/responses.rs index ecaf90098..d2c52ac40 100644 --- a/src/servers/apis/v1/responses.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/responses.rs @@ -61,7 +61,8 @@ pub fn invalid_auth_key_param_response(invalid_key: &str) -> Response { bad_request_response(&format!("Invalid auth key id param \"{invalid_key}\"")) } -fn bad_request_response(body: &str) -> Response { +#[must_use] +pub fn bad_request_response(body: &str) -> Response { ( StatusCode::BAD_REQUEST, [(header::CONTENT_TYPE, "text/plain; charset=utf-8")], diff --git a/packages/axum-rest-tracker-api-server/src/v1/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/routes.rs new file mode 100644 index 000000000..f7057a852 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/src/v1/routes.rs @@ -0,0 +1,30 @@ +//! Route initialization for the v1 API. +use std::sync::Arc; + +use axum::Router; +use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; + +use super::context::{auth_key, stats, torrent, whitelist}; + +/// Add the routes for the v1 API. +pub fn add(prefix: &str, router: Router, http_api_container: &Arc) -> Router { + let v1_prefix = format!("{prefix}/v1"); + + let router = auth_key::routes::add( + &v1_prefix, + router, + &http_api_container.tracker_core_container.keys_handler.clone(), + ); + let router = stats::routes::add(&v1_prefix, router, http_api_container); + let router = whitelist::routes::add( + &v1_prefix, + router, + &http_api_container.tracker_core_container.whitelist_manager, + ); + + torrent::routes::add( + &v1_prefix, + router, + &http_api_container.tracker_core_container.in_memory_torrent_repository.clone(), + ) +} diff --git a/packages/axum-rest-tracker-api-server/tests/common/fixtures.rs b/packages/axum-rest-tracker-api-server/tests/common/fixtures.rs new file mode 100644 index 000000000..4589ea2ce --- /dev/null +++ b/packages/axum-rest-tracker-api-server/tests/common/fixtures.rs @@ -0,0 +1,11 @@ +pub fn invalid_info_hashes() -> Vec { + [ + "0".to_string(), + "-1".to_string(), + "1.1".to_string(), + "INVALID INFOHASH".to_string(), + "9c38422213e30bff212b30c360d26f9a0213642".to_string(), // 39-char length instead of 40. DevSkim: ignore DS173237 + "9c38422213e30bff212b30c360d26f9a0213642&".to_string(), // Invalid char + ] + .to_vec() +} diff --git a/packages/axum-rest-tracker-api-server/tests/common/mod.rs b/packages/axum-rest-tracker-api-server/tests/common/mod.rs new file mode 100644 index 000000000..d066349cc --- /dev/null +++ b/packages/axum-rest-tracker-api-server/tests/common/mod.rs @@ -0,0 +1 @@ +pub mod fixtures; diff --git a/packages/axum-rest-tracker-api-server/tests/integration.rs b/packages/axum-rest-tracker-api-server/tests/integration.rs new file mode 100644 index 000000000..878ac203d --- /dev/null +++ b/packages/axum-rest-tracker-api-server/tests/integration.rs @@ -0,0 +1,20 @@ +//! Integration tests. +//! +//! ```text +//! cargo test --test integration +//! ``` + +use torrust_tracker_clock::clock; +mod common; +mod server; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/packages/axum-rest-tracker-api-server/tests/server/connection_info.rs b/packages/axum-rest-tracker-api-server/tests/server/connection_info.rs new file mode 100644 index 000000000..6459c9a2f --- /dev/null +++ b/packages/axum-rest-tracker-api-server/tests/server/connection_info.rs @@ -0,0 +1,9 @@ +use torrust_rest_tracker_api_client::connection_info::{ConnectionInfo, Origin}; + +pub fn connection_with_invalid_token(origin: Origin) -> ConnectionInfo { + ConnectionInfo::authenticated(origin, "invalid token") +} + +pub fn connection_with_no_token(origin: Origin) -> ConnectionInfo { + ConnectionInfo::anonymous(origin) +} diff --git a/packages/axum-rest-tracker-api-server/tests/server/mod.rs b/packages/axum-rest-tracker-api-server/tests/server/mod.rs new file mode 100644 index 000000000..9dea49a4c --- /dev/null +++ b/packages/axum-rest-tracker-api-server/tests/server/mod.rs @@ -0,0 +1,19 @@ +pub mod connection_info; +pub mod v1; + +use std::sync::Arc; + +use bittorrent_tracker_core::databases::Database; + +/// It forces a database error by dropping all tables. That makes all queries +/// fail. +/// +/// code-review: +/// +/// Alternatively we could: +/// +/// - Inject a database mock in the future. +/// - Inject directly the database reference passed to the Tracker type. +pub fn force_database_error(tracker: &Arc>) { + tracker.drop_database_tables().unwrap(); +} diff --git a/tests/servers/api/v1/asserts.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/asserts.rs similarity index 76% rename from tests/servers/api/v1/asserts.rs rename to packages/axum-rest-tracker-api-server/tests/server/v1/asserts.rs index 955293db1..abd60cf94 100644 --- a/tests/servers/api/v1/asserts.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/asserts.rs @@ -1,9 +1,9 @@ // code-review: should we use macros to return the exact line where the assert fails? use reqwest::Response; -use torrust_tracker::servers::apis::v1::context::auth_key::resources::AuthKey; -use torrust_tracker::servers::apis::v1::context::stats::resources::Stats; -use torrust_tracker::servers::apis::v1::context::torrent::resources::torrent::{ListItem, Torrent}; +use torrust_axum_rest_tracker_api_server::v1::context::auth_key::resources::AuthKey; +use torrust_axum_rest_tracker_api_server::v1::context::stats::resources::Stats; +use torrust_axum_rest_tracker_api_server::v1::context::torrent::resources::torrent::{ListItem, Torrent}; // Resource responses @@ -61,6 +61,18 @@ pub async fn assert_bad_request(response: Response, body: &str) { assert_eq!(response.text().await.unwrap(), body); } +pub async fn assert_bad_request_with_text(response: Response, text: &str) { + assert_eq!(response.status(), 400); + assert_eq!(response.headers().get("content-type").unwrap(), "text/plain; charset=utf-8"); + assert!(response.text().await.unwrap().contains(text)); +} + +pub async fn assert_unprocessable_content(response: Response, text: &str) { + assert_eq!(response.status(), 422); + assert_eq!(response.headers().get("content-type").unwrap(), "text/plain; charset=utf-8"); + assert!(response.text().await.unwrap().contains(text)); +} + pub async fn assert_not_found(response: Response) { assert_eq!(response.status(), 404); // todo: missing header in the response @@ -82,14 +94,30 @@ pub async fn assert_invalid_infohash_param(response: Response, invalid_infohash: .await; } -pub async fn assert_invalid_auth_key_param(response: Response, invalid_auth_key: &str) { +pub async fn assert_invalid_auth_key_get_param(response: Response, invalid_auth_key: &str) { assert_bad_request(response, &format!("Invalid auth key id param \"{}\"", &invalid_auth_key)).await; } +pub async fn assert_invalid_auth_key_post_param(response: Response, invalid_auth_key: &str) { + assert_bad_request_with_text( + response, + &format!("Invalid URL: invalid auth key: string \"{}\"", &invalid_auth_key), + ) + .await; +} + +pub async fn assert_unprocessable_auth_key_duration_param(response: Response, _invalid_value: &str) { + assert_unprocessable_content( + response, + "Failed to deserialize the JSON body into the target type: seconds_valid: invalid type", + ) + .await; +} + pub async fn assert_invalid_key_duration_param(response: Response, invalid_key_duration: &str) { assert_bad_request( response, - &format!("Invalid URL: Cannot parse `\"{invalid_key_duration}\"` to a `u64`"), + &format!("Invalid URL: Cannot parse `{invalid_key_duration}` to a `u64`"), ) .await; } diff --git a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs new file mode 100644 index 000000000..be291a50c --- /dev/null +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs @@ -0,0 +1,294 @@ +mod given_that_the_token_is_only_provided_in_the_authentication_header { + use hyper::header; + use torrust_axum_rest_tracker_api_server::environment::Started; + use torrust_rest_tracker_api_client::common::http::Query; + use torrust_rest_tracker_api_client::connection_info::ConnectionInfo; + use torrust_rest_tracker_api_client::v1::client::{ + headers_with_auth_token, headers_with_request_id, Client, AUTH_BEARER_TOKEN_HEADER_PREFIX, + }; + use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; + use torrust_tracker_test_helpers::{configuration, logging}; + use uuid::Uuid; + + use crate::server::v1::asserts::assert_token_not_valid; + + #[tokio::test] + async fn it_should_authenticate_requests_when_the_token_is_provided_in_the_authentication_header() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let token = env.get_connection_info().api_token.unwrap(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_request_with_query("stats", Query::default(), Some(headers_with_auth_token(&token))) + .await; + + assert_eq!(response.status(), 200); + + env.stop().await; + } + + #[tokio::test] + async fn it_should_not_authenticate_requests_when_the_token_is_empty() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let request_id = Uuid::new_v4(); + + let mut headers = headers_with_request_id(request_id); + + // Send the header with an empty token + headers.insert( + header::AUTHORIZATION, + format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} ") + .parse() + .expect("the auth token is not a valid header value"), + ); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_request_with_query("stats", Query::default(), Some(headers)) + .await; + + assert_token_not_valid(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; + } + + #[tokio::test] + async fn it_should_not_authenticate_requests_when_the_token_is_invalid() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let request_id = Uuid::new_v4(); + + let mut headers = headers_with_request_id(request_id); + + // Send the header with an empty token + headers.insert( + header::AUTHORIZATION, + "Bearer INVALID TOKEN" + .parse() + .expect("the auth token is not a valid header value"), + ); + + let connection_info = ConnectionInfo::anonymous(env.get_connection_info().origin); + + let response = Client::new(connection_info) + .unwrap() + .get_request_with_query("stats", Query::default(), Some(headers)) + .await; + + assert_token_not_valid(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; + } +} +mod given_that_the_token_is_only_provided_in_the_query_param { + + use torrust_axum_rest_tracker_api_server::environment::Started; + use torrust_rest_tracker_api_client::common::http::{Query, QueryParam}; + use torrust_rest_tracker_api_client::connection_info::ConnectionInfo; + use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client, TOKEN_PARAM_NAME}; + use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; + use torrust_tracker_test_helpers::{configuration, logging}; + use uuid::Uuid; + + use crate::server::v1::asserts::assert_token_not_valid; + + #[tokio::test] + async fn it_should_authenticate_requests_when_the_token_is_provided_as_a_query_param() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let token = env.get_connection_info().api_token.unwrap(); + + let connection_info = ConnectionInfo::anonymous(env.get_connection_info().origin); + + let response = Client::new(connection_info) + .unwrap() + .get_request_with_query( + "stats", + Query::params([QueryParam::new(TOKEN_PARAM_NAME, &token)].to_vec()), + None, + ) + .await; + + assert_eq!(response.status(), 200); + + env.stop().await; + } + + #[tokio::test] + async fn it_should_not_authenticate_requests_when_the_token_is_empty() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let request_id = Uuid::new_v4(); + + let connection_info = ConnectionInfo::anonymous(env.get_connection_info().origin); + + let response = Client::new(connection_info) + .unwrap() + .get_request_with_query( + "stats", + Query::params([QueryParam::new(TOKEN_PARAM_NAME, "")].to_vec()), + Some(headers_with_request_id(request_id)), + ) + .await; + + assert_token_not_valid(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; + } + + #[tokio::test] + async fn it_should_not_authenticate_requests_when_the_token_is_invalid() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let request_id = Uuid::new_v4(); + + let connection_info = ConnectionInfo::anonymous(env.get_connection_info().origin); + + let response = Client::new(connection_info) + .unwrap() + .get_request_with_query( + "stats", + Query::params([QueryParam::new(TOKEN_PARAM_NAME, "INVALID TOKEN")].to_vec()), + Some(headers_with_request_id(request_id)), + ) + .await; + + assert_token_not_valid(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; + } + + #[tokio::test] + async fn it_should_allow_the_token_query_param_to_be_at_any_position_in_the_url_query() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let token = env.get_connection_info().api_token.unwrap(); + + let connection_info = ConnectionInfo::anonymous(env.get_connection_info().origin); + + // At the beginning of the query component + let response = Client::new(connection_info) + .unwrap() + .get_request(&format!("torrents?token={token}&limit=1")) + .await; + + assert_eq!(response.status(), 200); + + // At the end of the query component + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_request(&format!("torrents?limit=1&token={token}")) + .await; + + assert_eq!(response.status(), 200); + + env.stop().await; + } +} + +mod given_that_not_token_is_provided { + + use torrust_axum_rest_tracker_api_server::environment::Started; + use torrust_rest_tracker_api_client::common::http::Query; + use torrust_rest_tracker_api_client::connection_info::ConnectionInfo; + use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client}; + use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; + use torrust_tracker_test_helpers::{configuration, logging}; + use uuid::Uuid; + + use crate::server::v1::asserts::assert_unauthorized; + + #[tokio::test] + async fn it_should_not_authenticate_requests_when_the_token_is_missing() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let request_id = Uuid::new_v4(); + + let connection_info = ConnectionInfo::anonymous(env.get_connection_info().origin); + + let response = Client::new(connection_info) + .unwrap() + .get_request_with_query("stats", Query::default(), Some(headers_with_request_id(request_id))) + .await; + + assert_unauthorized(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; + } +} + +mod given_that_token_is_provided_via_get_param_and_authentication_header { + use torrust_axum_rest_tracker_api_server::environment::Started; + use torrust_rest_tracker_api_client::common::http::{Query, QueryParam}; + use torrust_rest_tracker_api_client::v1::client::{headers_with_auth_token, Client, TOKEN_PARAM_NAME}; + use torrust_tracker_test_helpers::{configuration, logging}; + + #[tokio::test] + async fn it_should_authenticate_requests_using_the_token_provided_in_the_authentication_header() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let authorized_token = env.get_connection_info().api_token.unwrap(); + + let non_authorized_token = "NonAuthorizedToken"; + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_request_with_query( + "stats", + Query::params([QueryParam::new(TOKEN_PARAM_NAME, non_authorized_token)].to_vec()), + Some(headers_with_auth_token(&authorized_token)), + ) + .await; + + // The token provided in the query param should be ignored and the token + // in the authentication header should be used. + assert_eq!(response.status(), 200); + + env.stop().await; + } +} diff --git a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/auth_key.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/auth_key.rs new file mode 100644 index 000000000..3781f4f60 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/auth_key.rs @@ -0,0 +1,619 @@ +use std::time::Duration; + +use bittorrent_tracker_core::authentication::Key; +use serde::Serialize; +use torrust_axum_rest_tracker_api_server::environment::Started; +use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, AddKeyForm, Client}; +use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; +use torrust_tracker_test_helpers::{configuration, logging}; +use uuid::Uuid; + +use crate::server::connection_info::{connection_with_invalid_token, connection_with_no_token}; +use crate::server::force_database_error; +use crate::server::v1::asserts::{ + assert_auth_key_utf8, assert_failed_to_delete_key, assert_failed_to_generate_key, assert_failed_to_reload_keys, + assert_invalid_auth_key_get_param, assert_invalid_auth_key_post_param, assert_ok, assert_token_not_valid, + assert_unauthorized, assert_unprocessable_auth_key_duration_param, +}; + +#[tokio::test] +async fn should_allow_generating_a_new_random_auth_key() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .add_auth_key( + AddKeyForm { + opt_key: None, + seconds_valid: Some(60), + }, + Some(headers_with_request_id(request_id)), + ) + .await; + + let auth_key_resource = assert_auth_key_utf8(response).await; + + assert!(env + .container + .tracker_core_container + .authentication_service + .authenticate(&auth_key_resource.key.parse::().unwrap()) + .await + .is_ok()); + + env.stop().await; +} + +#[tokio::test] +async fn should_allow_uploading_a_preexisting_auth_key() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .add_auth_key( + AddKeyForm { + opt_key: Some("Xc1L4PbQJSFGlrgSRZl8wxSFAuMa21z5".to_string()), + seconds_valid: Some(60), + }, + Some(headers_with_request_id(request_id)), + ) + .await; + + let auth_key_resource = assert_auth_key_utf8(response).await; + + assert!(env + .container + .tracker_core_container + .authentication_service + .authenticate(&auth_key_resource.key.parse::().unwrap()) + .await + .is_ok()); + + env.stop().await; +} + +#[tokio::test] +async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let request_id = Uuid::new_v4(); + + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() + .add_auth_key( + AddKeyForm { + opt_key: None, + seconds_valid: Some(60), + }, + Some(headers_with_request_id(request_id)), + ) + .await; + + assert_token_not_valid(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + let request_id = Uuid::new_v4(); + + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() + .add_auth_key( + AddKeyForm { + opt_key: None, + seconds_valid: Some(60), + }, + Some(headers_with_request_id(request_id)), + ) + .await; + + assert_unauthorized(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; +} + +#[tokio::test] +async fn should_fail_when_the_auth_key_cannot_be_generated() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + force_database_error(&env.container.tracker_core_container.database); + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .add_auth_key( + AddKeyForm { + opt_key: None, + seconds_valid: Some(60), + }, + Some(headers_with_request_id(request_id)), + ) + .await; + + assert_failed_to_generate_key(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; +} + +#[tokio::test] +async fn should_allow_deleting_an_auth_key() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let seconds_valid = 60; + let auth_key = env + .container + .tracker_core_container + .keys_handler + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) + .await + .unwrap(); + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .delete_auth_key(&auth_key.key.to_string(), Some(headers_with_request_id(request_id))) + .await; + + assert_ok(response).await; + + env.stop().await; +} + +#[tokio::test] +async fn should_fail_generating_a_new_auth_key_when_the_provided_key_is_invalid() { + #[derive(Serialize, Debug)] + pub struct InvalidAddKeyForm { + #[serde(rename = "key")] + pub opt_key: Option, + pub seconds_valid: u64, + } + + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let invalid_keys = [ + // "", it returns 404 + // " ", it returns 404 + "-1", // Not a string + "invalid", // Invalid string + "GQEs2ZNcCm9cwEV9dBpcPB5OwNFWFiR", // Not a 32-char string + "%QEs2ZNcCm9cwEV9dBpcPB5OwNFWFiRd", // Invalid char. + ]; + + for invalid_key in invalid_keys { + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .post_form( + "keys", + &InvalidAddKeyForm { + opt_key: Some(invalid_key.to_string()), + seconds_valid: 60, + }, + Some(headers_with_request_id(request_id)), + ) + .await; + + assert_invalid_auth_key_post_param(response, invalid_key).await; + } + + env.stop().await; +} + +#[tokio::test] +async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid() { + #[derive(Serialize, Debug)] + pub struct InvalidAddKeyForm { + #[serde(rename = "key")] + pub opt_key: Option, + pub seconds_valid: String, + } + + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let invalid_key_durations = [ + // "", it returns 404 + // " ", it returns 404 + "-1", "text", + ]; + + for invalid_key_duration in invalid_key_durations { + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .post_form( + "keys", + &InvalidAddKeyForm { + opt_key: None, + seconds_valid: invalid_key_duration.to_string(), + }, + Some(headers_with_request_id(request_id)), + ) + .await; + + assert_unprocessable_auth_key_duration_param(response, invalid_key_duration).await; + } + + env.stop().await; +} + +#[tokio::test] +async fn should_fail_deleting_an_auth_key_when_the_key_id_is_invalid() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let invalid_auth_keys = [ + // "", it returns a 404 + // " ", it returns a 404 + "0", + "-1", + "INVALID AUTH KEY ID", + "IrweYtVuQPGbG9Jzx1DihcPmJGGpVy8", // 32 char key cspell:disable-line + "IrweYtVuQPGbG9Jzx1DihcPmJGGpVy8zs", // 34 char key cspell:disable-line + ]; + + for invalid_auth_key in &invalid_auth_keys { + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .delete_auth_key(invalid_auth_key, Some(headers_with_request_id(request_id))) + .await; + + assert_invalid_auth_key_get_param(response, invalid_auth_key).await; + } + + env.stop().await; +} + +#[tokio::test] +async fn should_fail_when_the_auth_key_cannot_be_deleted() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let seconds_valid = 60; + let auth_key = env + .container + .tracker_core_container + .keys_handler + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) + .await + .unwrap(); + + force_database_error(&env.container.tracker_core_container.database); + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .delete_auth_key(&auth_key.key.to_string(), Some(headers_with_request_id(request_id))) + .await; + + assert_failed_to_delete_key(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; +} + +#[tokio::test] +async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let seconds_valid = 60; + + // Generate new auth key + let auth_key = env + .container + .tracker_core_container + .keys_handler + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) + .await + .unwrap(); + + let request_id = Uuid::new_v4(); + + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() + .delete_auth_key(&auth_key.key.to_string(), Some(headers_with_request_id(request_id))) + .await; + + assert_token_not_valid(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + // Generate new auth key + let auth_key = env + .container + .tracker_core_container + .keys_handler + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) + .await + .unwrap(); + + let request_id = Uuid::new_v4(); + + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() + .delete_auth_key(&auth_key.key.to_string(), Some(headers_with_request_id(request_id))) + .await; + + assert_unauthorized(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; +} + +#[tokio::test] +async fn should_allow_reloading_keys() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let seconds_valid = 60; + env.container + .tracker_core_container + .keys_handler + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) + .await + .unwrap(); + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .reload_keys(Some(headers_with_request_id(request_id))) + .await; + + assert_ok(response).await; + + env.stop().await; +} + +#[tokio::test] +async fn should_fail_when_keys_cannot_be_reloaded() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let request_id = Uuid::new_v4(); + let seconds_valid = 60; + + env.container + .tracker_core_container + .keys_handler + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) + .await + .unwrap(); + + force_database_error(&env.container.tracker_core_container.database); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .reload_keys(Some(headers_with_request_id(request_id))) + .await; + + assert_failed_to_reload_keys(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; +} + +#[tokio::test] +async fn should_not_allow_reloading_keys_for_unauthenticated_users() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let seconds_valid = 60; + env.container + .tracker_core_container + .keys_handler + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) + .await + .unwrap(); + + let request_id = Uuid::new_v4(); + + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() + .reload_keys(Some(headers_with_request_id(request_id))) + .await; + + assert_token_not_valid(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + let request_id = Uuid::new_v4(); + + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() + .reload_keys(Some(headers_with_request_id(request_id))) + .await; + + assert_unauthorized(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; +} + +mod deprecated_generate_key_endpoint { + + use bittorrent_tracker_core::authentication::Key; + use torrust_axum_rest_tracker_api_server::environment::Started; + use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client}; + use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; + use torrust_tracker_test_helpers::{configuration, logging}; + use uuid::Uuid; + + use crate::server::connection_info::{connection_with_invalid_token, connection_with_no_token}; + use crate::server::force_database_error; + use crate::server::v1::asserts::{ + assert_auth_key_utf8, assert_failed_to_generate_key, assert_invalid_key_duration_param, assert_token_not_valid, + assert_unauthorized, + }; + + #[tokio::test] + async fn should_allow_generating_a_new_auth_key() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let seconds_valid = 60; + + let response = Client::new(env.get_connection_info()) + .unwrap() + .generate_auth_key(seconds_valid, None) + .await; + + let auth_key_resource = assert_auth_key_utf8(response).await; + + assert!(env + .container + .tracker_core_container + .authentication_service + .authenticate(&auth_key_resource.key.parse::().unwrap()) + .await + .is_ok()); + + env.stop().await; + } + + #[tokio::test] + async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let request_id = Uuid::new_v4(); + let seconds_valid = 60; + + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() + .generate_auth_key(seconds_valid, Some(headers_with_request_id(request_id))) + .await; + + assert_token_not_valid(response).await; + + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() + .generate_auth_key(seconds_valid, None) + .await; + + assert_unauthorized(response).await; + + env.stop().await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + } + + #[tokio::test] + async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let invalid_key_durations = [ + // "", it returns 404 + // " ", it returns 404 + "-1", "text", + ]; + + for invalid_key_duration in invalid_key_durations { + let response = Client::new(env.get_connection_info()) + .unwrap() + .post_empty(&format!("key/{invalid_key_duration}"), None) + .await; + + assert_invalid_key_duration_param(response, invalid_key_duration).await; + } + + env.stop().await; + } + + #[tokio::test] + async fn should_fail_when_the_auth_key_cannot_be_generated() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + force_database_error(&env.container.tracker_core_container.database); + + let request_id = Uuid::new_v4(); + let seconds_valid = 60; + let response = Client::new(env.get_connection_info()) + .unwrap() + .generate_auth_key(seconds_valid, Some(headers_with_request_id(request_id))) + .await; + + assert_failed_to_generate_key(response).await; + + env.stop().await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + } +} diff --git a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/health_check.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/health_check.rs new file mode 100644 index 000000000..3a08c6d51 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/health_check.rs @@ -0,0 +1,22 @@ +use torrust_axum_rest_tracker_api_server::environment::Started; +use torrust_axum_rest_tracker_api_server::v1::context::health_check::resources::{Report, Status}; +use torrust_rest_tracker_api_client::v1::client::get; +use torrust_tracker_test_helpers::{configuration, logging}; +use url::Url; + +#[tokio::test] +async fn health_check_endpoint_should_return_status_ok_if_api_is_running() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let url = Url::parse(&format!("{}api/health_check", env.get_connection_info().origin)).unwrap(); + + let response = get(url, None, None).await; + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + assert_eq!(response.json::().await.unwrap(), Report { status: Status::Ok }); + + env.stop().await; +} diff --git a/tests/servers/api/v1/contract/context/mod.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/mod.rs similarity index 75% rename from tests/servers/api/v1/contract/context/mod.rs rename to packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/mod.rs index 6d3fb7566..032e13b0b 100644 --- a/tests/servers/api/v1/contract/context/mod.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/mod.rs @@ -1,4 +1,5 @@ pub mod auth_key; +pub mod health_check; pub mod stats; pub mod torrent; pub mod whitelist; diff --git a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/stats.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/stats.rs new file mode 100644 index 000000000..7cae0abbf --- /dev/null +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/stats.rs @@ -0,0 +1,111 @@ +use std::str::FromStr; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_axum_rest_tracker_api_server::environment::Started; +use torrust_axum_rest_tracker_api_server::v1::context::stats::resources::Stats; +use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client}; +use torrust_tracker_primitives::peer::fixture::PeerBuilder; +use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; +use torrust_tracker_test_helpers::{configuration, logging}; +use uuid::Uuid; + +use crate::server::connection_info::{connection_with_invalid_token, connection_with_no_token}; +use crate::server::v1::asserts::{assert_stats, assert_token_not_valid, assert_unauthorized}; + +#[tokio::test] +async fn should_allow_getting_tracker_statistics() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + env.add_torrent_peer( + &InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(), // DevSkim: ignore DS173237 + &PeerBuilder::default().into(), + ) + .await; + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_tracker_statistics(Some(headers_with_request_id(request_id))) + .await; + + assert_stats( + response, + Stats { + torrents: 1, + seeders: 1, + completed: 0, + leechers: 0, + // TCP + tcp4_connections_handled: 0, + tcp4_announces_handled: 0, + tcp4_scrapes_handled: 0, + tcp6_connections_handled: 0, + tcp6_announces_handled: 0, + tcp6_scrapes_handled: 0, + // UDP + udp_requests_aborted: 0, + udp_requests_banned: 0, + udp_banned_ips_total: 0, + udp_avg_connect_processing_time_ns: 0, + udp_avg_announce_processing_time_ns: 0, + udp_avg_scrape_processing_time_ns: 0, + // UDPv4 + udp4_requests: 0, + udp4_connections_handled: 0, + udp4_announces_handled: 0, + udp4_scrapes_handled: 0, + udp4_responses: 0, + udp4_errors_handled: 0, + // UDPv6 + udp6_requests: 0, + udp6_connections_handled: 0, + udp6_announces_handled: 0, + udp6_scrapes_handled: 0, + udp6_responses: 0, + udp6_errors_handled: 0, + }, + ) + .await; + + env.stop().await; +} + +#[tokio::test] +async fn should_not_allow_getting_tracker_statistics_for_unauthenticated_users() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let request_id = Uuid::new_v4(); + + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() + .get_tracker_statistics(Some(headers_with_request_id(request_id))) + .await; + + assert_token_not_valid(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + let request_id = Uuid::new_v4(); + + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() + .get_tracker_statistics(Some(headers_with_request_id(request_id))) + .await; + + assert_unauthorized(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; +} diff --git a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/torrent.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/torrent.rs new file mode 100644 index 000000000..ae9819785 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/torrent.rs @@ -0,0 +1,423 @@ +use std::str::FromStr; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_axum_rest_tracker_api_server::environment::Started; +use torrust_axum_rest_tracker_api_server::v1::context::torrent::resources::peer::Peer; +use torrust_axum_rest_tracker_api_server::v1::context::torrent::resources::torrent::{self, Torrent}; +use torrust_rest_tracker_api_client::common::http::{Query, QueryParam}; +use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client}; +use torrust_tracker_primitives::peer::fixture::PeerBuilder; +use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; +use torrust_tracker_test_helpers::{configuration, logging}; +use uuid::Uuid; + +use crate::server::connection_info::{connection_with_invalid_token, connection_with_no_token}; +use crate::server::v1::asserts::{ + assert_bad_request, assert_invalid_infohash_param, assert_not_found, assert_token_not_valid, assert_torrent_info, + assert_torrent_list, assert_torrent_not_known, assert_unauthorized, +}; +use crate::server::v1::contract::fixtures::{invalid_infohashes_returning_bad_request, invalid_infohashes_returning_not_found}; + +#[tokio::test] +async fn should_allow_getting_all_torrents() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 + + env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()).await; + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_torrents(Query::empty(), Some(headers_with_request_id(request_id))) + .await; + + assert_torrent_list( + response, + vec![torrent::ListItem { + info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), // DevSkim: ignore DS173237 + seeders: 1, + completed: 0, + leechers: 0, + }], + ) + .await; + + env.stop().await; +} + +#[tokio::test] +async fn should_allow_limiting_the_torrents_in_the_result() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + // torrents are ordered alphabetically by infohashes + let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 + let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); // DevSkim: ignore DS173237 + + env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()).await; + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_torrents( + Query::params([QueryParam::new("limit", "1")].to_vec()), + Some(headers_with_request_id(request_id)), + ) + .await; + + assert_torrent_list( + response, + vec![torrent::ListItem { + info_hash: "0b3aea4adc213ce32295be85d3883a63bca25446".to_string(), // DevSkim: ignore DS173237 + seeders: 1, + completed: 0, + leechers: 0, + }], + ) + .await; + + env.stop().await; +} + +#[tokio::test] +async fn should_allow_the_torrents_result_pagination() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + // torrents are ordered alphabetically by infohashes + let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 + let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); // DevSkim: ignore DS173237 + + env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()).await; + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_torrents( + Query::params([QueryParam::new("offset", "1")].to_vec()), + Some(headers_with_request_id(request_id)), + ) + .await; + + assert_torrent_list( + response, + vec![torrent::ListItem { + info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), // DevSkim: ignore DS173237 + seeders: 1, + completed: 0, + leechers: 0, + }], + ) + .await; + + env.stop().await; +} + +#[tokio::test] +async fn should_allow_getting_a_list_of_torrents_providing_infohashes() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 + let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); // DevSkim: ignore DS173237 + + env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()).await; + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_torrents( + Query::params( + [ + QueryParam::new("info_hash", "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d"), // DevSkim: ignore DS173237 + QueryParam::new("info_hash", "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d"), // DevSkim: ignore DS173237 + ] + .to_vec(), + ), + Some(headers_with_request_id(request_id)), + ) + .await; + + assert_torrent_list( + response, + vec![ + torrent::ListItem { + info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), // DevSkim: ignore DS173237 + seeders: 1, + completed: 0, + leechers: 0, + }, + torrent::ListItem { + info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), // DevSkim: ignore DS173237 + seeders: 1, + completed: 0, + leechers: 0, + }, + ], + ) + .await; + + env.stop().await; +} + +#[tokio::test] +async fn should_fail_getting_torrents_when_the_offset_query_parameter_cannot_be_parsed() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let invalid_offsets = [" ", "-1", "1.1", "INVALID OFFSET"]; + + for invalid_offset in &invalid_offsets { + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_torrents( + Query::params([QueryParam::new("offset", invalid_offset)].to_vec()), + Some(headers_with_request_id(request_id)), + ) + .await; + + assert_bad_request( + response, + "Failed to deserialize query string: offset: invalid digit found in string", + ) + .await; + } + + env.stop().await; +} + +#[tokio::test] +async fn should_fail_getting_torrents_when_the_limit_query_parameter_cannot_be_parsed() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let invalid_limits = [" ", "-1", "1.1", "INVALID LIMIT"]; + + for invalid_limit in &invalid_limits { + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_torrents( + Query::params([QueryParam::new("limit", invalid_limit)].to_vec()), + Some(headers_with_request_id(request_id)), + ) + .await; + + assert_bad_request( + response, + "Failed to deserialize query string: limit: invalid digit found in string", + ) + .await; + } + + env.stop().await; +} + +#[tokio::test] +async fn should_fail_getting_torrents_when_the_info_hash_parameter_is_invalid() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let invalid_info_hashes = [" ", "-1", "1.1", "INVALID INFO_HASH"]; + + for invalid_info_hash in &invalid_info_hashes { + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_torrents( + Query::params([QueryParam::new("info_hash", invalid_info_hash)].to_vec()), + Some(headers_with_request_id(request_id)), + ) + .await; + + assert_bad_request( + response, + &format!("Invalid URL: invalid infohash param: string \"{invalid_info_hash}\", expected a 40 character long string"), + ) + .await; + } + + env.stop().await; +} + +#[tokio::test] +async fn should_not_allow_getting_torrents_for_unauthenticated_users() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let request_id = Uuid::new_v4(); + + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() + .get_torrents(Query::empty(), Some(headers_with_request_id(request_id))) + .await; + + assert_token_not_valid(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + let request_id = Uuid::new_v4(); + + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() + .get_torrents(Query::default(), Some(headers_with_request_id(request_id))) + .await; + + assert_unauthorized(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; +} + +#[tokio::test] +async fn should_allow_getting_a_torrent_info() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 + + let peer = PeerBuilder::default().into(); + + env.add_torrent_peer(&info_hash, &peer).await; + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_torrent(&info_hash.to_string(), Some(headers_with_request_id(request_id))) + .await; + + assert_torrent_info( + response, + Torrent { + info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), // DevSkim: ignore DS173237 + seeders: 1, + completed: 0, + leechers: 0, + peers: Some(vec![Peer::from(peer)]), + }, + ) + .await; + + env.stop().await; +} + +#[tokio::test] +async fn should_fail_while_getting_a_torrent_info_when_the_torrent_does_not_exist() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let request_id = Uuid::new_v4(); + let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_torrent(&info_hash.to_string(), Some(headers_with_request_id(request_id))) + .await; + + assert_torrent_not_known(response).await; + + env.stop().await; +} + +#[tokio::test] +async fn should_fail_getting_a_torrent_info_when_the_provided_infohash_is_invalid() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + for invalid_infohash in &invalid_infohashes_returning_bad_request() { + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_torrent(invalid_infohash, Some(headers_with_request_id(request_id))) + .await; + + assert_invalid_infohash_param(response, invalid_infohash).await; + } + + for invalid_infohash in &invalid_infohashes_returning_not_found() { + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_torrent(invalid_infohash, Some(headers_with_request_id(request_id))) + .await; + + assert_not_found(response).await; + } + + env.stop().await; +} + +#[tokio::test] +async fn should_not_allow_getting_a_torrent_info_for_unauthenticated_users() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 + + env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()).await; + + let request_id = Uuid::new_v4(); + + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() + .get_torrent(&info_hash.to_string(), Some(headers_with_request_id(request_id))) + .await; + + assert_token_not_valid(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + let request_id = Uuid::new_v4(); + + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() + .get_torrent(&info_hash.to_string(), Some(headers_with_request_id(request_id))) + .await; + + assert_unauthorized(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; +} diff --git a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/whitelist.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/whitelist.rs new file mode 100644 index 000000000..61fc233d0 --- /dev/null +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/whitelist.rs @@ -0,0 +1,412 @@ +use std::str::FromStr; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_axum_rest_tracker_api_server::environment::Started; +use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client}; +use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; +use torrust_tracker_test_helpers::{configuration, logging}; +use uuid::Uuid; + +use crate::server::connection_info::{connection_with_invalid_token, connection_with_no_token}; +use crate::server::force_database_error; +use crate::server::v1::asserts::{ + assert_failed_to_reload_whitelist, assert_failed_to_remove_torrent_from_whitelist, assert_failed_to_whitelist_torrent, + assert_invalid_infohash_param, assert_not_found, assert_ok, assert_token_not_valid, assert_unauthorized, +}; +use crate::server::v1::contract::fixtures::{invalid_infohashes_returning_bad_request, invalid_infohashes_returning_not_found}; + +#[tokio::test] +async fn should_allow_whitelisting_a_torrent() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let request_id = Uuid::new_v4(); + let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 + + let response = Client::new(env.get_connection_info()) + .unwrap() + .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) + .await; + + assert_ok(response).await; + assert!( + env.container + .tracker_core_container + .in_memory_whitelist + .contains(&InfoHash::from_str(&info_hash).unwrap()) + .await + ); + + env.stop().await; +} + +#[tokio::test] +async fn should_allow_whitelisting_a_torrent_that_has_been_already_whitelisted() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 + + let api_client = Client::new(env.get_connection_info()).unwrap(); + + let request_id = Uuid::new_v4(); + + let response = api_client + .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) + .await; + assert_ok(response).await; + + let request_id = Uuid::new_v4(); + + let response = api_client + .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) + .await; + assert_ok(response).await; + + env.stop().await; +} + +#[tokio::test] +async fn should_not_allow_whitelisting_a_torrent_for_unauthenticated_users() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 + + let request_id = Uuid::new_v4(); + + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() + .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) + .await; + + assert_token_not_valid(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + let request_id = Uuid::new_v4(); + + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() + .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) + .await; + + assert_unauthorized(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; +} + +#[tokio::test] +async fn should_fail_when_the_torrent_cannot_be_whitelisted() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 + + force_database_error(&env.container.tracker_core_container.database); + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) + .await; + + assert_failed_to_whitelist_torrent(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; +} + +#[tokio::test] +async fn should_fail_whitelisting_a_torrent_when_the_provided_infohash_is_invalid() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let request_id = Uuid::new_v4(); + + for invalid_infohash in &invalid_infohashes_returning_bad_request() { + let response = Client::new(env.get_connection_info()) + .unwrap() + .whitelist_a_torrent(invalid_infohash, Some(headers_with_request_id(request_id))) + .await; + + assert_invalid_infohash_param(response, invalid_infohash).await; + } + + let request_id = Uuid::new_v4(); + + for invalid_infohash in &invalid_infohashes_returning_not_found() { + let response = Client::new(env.get_connection_info()) + .unwrap() + .whitelist_a_torrent(invalid_infohash, Some(headers_with_request_id(request_id))) + .await; + + assert_not_found(response).await; + } + + env.stop().await; +} + +#[tokio::test] +async fn should_allow_removing_a_torrent_from_the_whitelist() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 + let info_hash = InfoHash::from_str(&hash).unwrap(); + + env.container + .tracker_core_container + .whitelist_manager + .add_torrent_to_whitelist(&info_hash) + .await + .unwrap(); + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .remove_torrent_from_whitelist(&hash, Some(headers_with_request_id(request_id))) + .await; + + assert_ok(response).await; + assert!( + !env.container + .tracker_core_container + .in_memory_whitelist + .contains(&info_hash) + .await + ); + + env.stop().await; +} + +#[tokio::test] +async fn should_not_fail_trying_to_remove_a_non_whitelisted_torrent_from_the_whitelist() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let non_whitelisted_torrent_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .remove_torrent_from_whitelist(&non_whitelisted_torrent_hash, Some(headers_with_request_id(request_id))) + .await; + + assert_ok(response).await; + + env.stop().await; +} + +#[tokio::test] +async fn should_fail_removing_a_torrent_from_the_whitelist_when_the_provided_infohash_is_invalid() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + for invalid_infohash in &invalid_infohashes_returning_bad_request() { + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .remove_torrent_from_whitelist(invalid_infohash, Some(headers_with_request_id(request_id))) + .await; + + assert_invalid_infohash_param(response, invalid_infohash).await; + } + + for invalid_infohash in &invalid_infohashes_returning_not_found() { + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .remove_torrent_from_whitelist(invalid_infohash, Some(headers_with_request_id(request_id))) + .await; + + assert_not_found(response).await; + } + + env.stop().await; +} + +#[tokio::test] +async fn should_fail_when_the_torrent_cannot_be_removed_from_the_whitelist() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 + let info_hash = InfoHash::from_str(&hash).unwrap(); + env.container + .tracker_core_container + .whitelist_manager + .add_torrent_to_whitelist(&info_hash) + .await + .unwrap(); + + force_database_error(&env.container.tracker_core_container.database); + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .remove_torrent_from_whitelist(&hash, Some(headers_with_request_id(request_id))) + .await; + + assert_failed_to_remove_torrent_from_whitelist(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; +} + +#[tokio::test] +async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthenticated_users() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 + let info_hash = InfoHash::from_str(&hash).unwrap(); + + env.container + .tracker_core_container + .whitelist_manager + .add_torrent_to_whitelist(&info_hash) + .await + .unwrap(); + + let request_id = Uuid::new_v4(); + + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() + .remove_torrent_from_whitelist(&hash, Some(headers_with_request_id(request_id))) + .await; + + assert_token_not_valid(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.container + .tracker_core_container + .whitelist_manager + .add_torrent_to_whitelist(&info_hash) + .await + .unwrap(); + + let request_id = Uuid::new_v4(); + + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() + .remove_torrent_from_whitelist(&hash, Some(headers_with_request_id(request_id))) + .await; + + assert_unauthorized(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; +} + +#[tokio::test] +async fn should_allow_reload_the_whitelist_from_the_database() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 + let info_hash = InfoHash::from_str(&hash).unwrap(); + + env.container + .tracker_core_container + .whitelist_manager + .add_torrent_to_whitelist(&info_hash) + .await + .unwrap(); + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .reload_whitelist(Some(headers_with_request_id(request_id))) + .await; + + assert_ok(response).await; + /* todo: this assert fails because the whitelist has not been reloaded yet. + We could add a new endpoint GET /api/whitelist/:info_hash to check if a torrent + is whitelisted and use that endpoint to check if the torrent is still there after reloading. + assert!( + !(env + .tracker + .is_info_hash_whitelisted(&InfoHash::from_str(&info_hash).unwrap()) + .await) + ); + */ + + env.stop().await; +} + +#[tokio::test] +async fn should_fail_when_the_whitelist_cannot_be_reloaded_from_the_database() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 + let info_hash = InfoHash::from_str(&hash).unwrap(); + env.container + .tracker_core_container + .whitelist_manager + .add_torrent_to_whitelist(&info_hash) + .await + .unwrap(); + + force_database_error(&env.container.tracker_core_container.database); + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .reload_whitelist(Some(headers_with_request_id(request_id))) + .await; + + assert_failed_to_reload_whitelist(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; +} diff --git a/tests/servers/api/v1/contract/fixtures.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/fixtures.rs similarity index 100% rename from tests/servers/api/v1/contract/fixtures.rs rename to packages/axum-rest-tracker-api-server/tests/server/v1/contract/fixtures.rs diff --git a/tests/servers/api/v1/contract/mod.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/mod.rs similarity index 71% rename from tests/servers/api/v1/contract/mod.rs rename to packages/axum-rest-tracker-api-server/tests/server/v1/contract/mod.rs index 38b4a2b37..2a3f78afd 100644 --- a/tests/servers/api/v1/contract/mod.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/mod.rs @@ -1,4 +1,3 @@ pub mod authentication; -pub mod configuration; pub mod context; pub mod fixtures; diff --git a/tests/servers/api/v1/mod.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/mod.rs similarity index 68% rename from tests/servers/api/v1/mod.rs rename to packages/axum-rest-tracker-api-server/tests/server/v1/mod.rs index 37298b377..e2db6b4ce 100644 --- a/tests/servers/api/v1/mod.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/mod.rs @@ -1,3 +1,2 @@ pub mod asserts; -pub mod client; pub mod contract; diff --git a/packages/axum-server/Cargo.toml b/packages/axum-server/Cargo.toml new file mode 100644 index 000000000..45eddd3b0 --- /dev/null +++ b/packages/axum-server/Cargo.toml @@ -0,0 +1,32 @@ +[package] +authors.workspace = true +description = "A wrapper for the Axum server for Torrust HTTP servers to add timeouts." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = [ "axum", "server", "torrust", "wrapper" ] +license.workspace = true +name = "torrust-axum-server" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +axum-server = { version = "0", features = [ "tls-rustls-no-provider" ] } +camino = { version = "1", features = [ "serde", "serde1" ] } +futures-util = "0" +http-body = "1" +hyper = "1" +hyper-util = { version = "0", features = [ "http1", "http2", "tokio" ] } +pin-project-lite = "0" +thiserror = "2" +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } +torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } +tower = { version = "0", features = [ "timeout" ] } +tracing = "0" + +[dev-dependencies] diff --git a/packages/axum-server/LICENSE b/packages/axum-server/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/axum-server/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/axum-server/README.md b/packages/axum-server/README.md new file mode 100644 index 000000000..d2f396915 --- /dev/null +++ b/packages/axum-server/README.md @@ -0,0 +1,11 @@ +# Torrust Axum Server + +A wrapper for the Axum server for Torrust HTTP servers to add timeouts. + +## Documentation + +[Crate documentation](https://docs.rs/torrust-axum-server). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/axum-server/src/custom_axum_server.rs b/packages/axum-server/src/custom_axum_server.rs new file mode 100644 index 000000000..0328198ec --- /dev/null +++ b/packages/axum-server/src/custom_axum_server.rs @@ -0,0 +1,286 @@ +//! Wrapper for Axum server to add timeouts. +//! +//! Copyright (c) Eray Karatay ([@programatik29](https://github.com/programatik29)). +//! +//! See: . +//! +//! If a client opens a HTTP connection and it does not send any requests, the +//! connection is closed after a timeout. You can test it with: +//! +//! ```text +//! telnet 127.0.0.1 1212 +//! Trying 127.0.0.1... +//! Connected to 127.0.0.1. +//! Escape character is '^]'. +//! Connection closed by foreign host. +//! ``` +//! +//! If you want to know more about Axum and timeouts see . +use std::future::Ready; +use std::io::ErrorKind; +use std::net::{SocketAddr, TcpListener}; +use std::pin::Pin; +use std::task::{Context, Poll}; +use std::time::Duration; + +use axum_server::accept::Accept; +use axum_server::tls_rustls::{RustlsAcceptor, RustlsConfig}; +use axum_server::Server; +use futures_util::{ready, Future}; +use http_body::{Body, Frame}; +use hyper::Response; +use hyper_util::rt::TokioTimer; +use pin_project_lite::pin_project; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; +use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; +use tokio::time::{Instant, Sleep}; +use tower::Service; + +type RustlsServerResult = Result, std::io::Error>; +type ServerResult = Result, std::io::Error>; + +const HTTP1_HEADER_READ_TIMEOUT: Duration = Duration::from_secs(5); +const HTTP2_KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(5); +const HTTP2_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(5); + +/// Creates an Axum server from a TCP listener with configured timeouts. +/// +/// # Errors +/// +/// Returns an error if the server cannot be created from the TCP socket. +pub fn from_tcp_with_timeouts(socket: TcpListener) -> ServerResult { + axum_server::from_tcp(socket).map(add_timeouts) +} + +/// Creates an Axum server from a TCP listener with TLS and configured timeouts. +/// +/// # Errors +/// +/// Returns an error if the server cannot be created from the TCP socket or if TLS configuration fails. +pub fn from_tcp_rustls_with_timeouts(socket: TcpListener, tls: RustlsConfig) -> RustlsServerResult { + axum_server::from_tcp_rustls(socket, tls).map(add_timeouts) +} + +fn add_timeouts(mut server: Server) -> Server { + server.http_builder().http1().timer(TokioTimer::new()); + server.http_builder().http2().timer(TokioTimer::new()); + + server.http_builder().http1().header_read_timeout(HTTP1_HEADER_READ_TIMEOUT); + server + .http_builder() + .http2() + .keep_alive_timeout(HTTP2_KEEP_ALIVE_TIMEOUT) + .keep_alive_interval(HTTP2_KEEP_ALIVE_INTERVAL); + + server +} + +#[derive(Clone)] +pub struct TimeoutAcceptor; + +impl Accept for TimeoutAcceptor { + type Stream = TimeoutStream; + type Service = TimeoutService; + type Future = Ready>; + + fn accept(&self, stream: I, service: S) -> Self::Future { + let (tx, rx) = mpsc::unbounded_channel(); + + let stream = TimeoutStream::new(stream, HTTP1_HEADER_READ_TIMEOUT, rx); + let service = TimeoutService::new(service, tx); + + std::future::ready(Ok((stream, service))) + } +} + +#[derive(Clone)] +pub struct TimeoutService { + inner: S, + sender: UnboundedSender, +} + +impl TimeoutService { + fn new(inner: S, sender: UnboundedSender) -> Self { + Self { inner, sender } + } +} + +impl Service for TimeoutService +where + S: Service>, +{ + type Response = Response>; + type Error = S::Error; + type Future = TimeoutServiceFuture; + + fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.inner.poll_ready(cx) + } + + fn call(&mut self, req: Request) -> Self::Future { + // send timer wait signal + let _ = self.sender.send(TimerSignal::Wait); + + TimeoutServiceFuture::new(self.inner.call(req), self.sender.clone()) + } +} + +pin_project! { + pub struct TimeoutServiceFuture { + #[pin] + inner: F, + sender: Option>, + } +} + +impl TimeoutServiceFuture { + fn new(inner: F, sender: UnboundedSender) -> Self { + Self { + inner, + sender: Some(sender), + } + } +} + +impl Future for TimeoutServiceFuture +where + F: Future, E>>, +{ + type Output = Result>, E>; + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let this = self.project(); + this.inner.poll(cx).map(|result| { + result.map(|response| { + response.map(|body| TimeoutBody::new(body, this.sender.take().expect("future polled after ready"))) + }) + }) + } +} + +enum TimerSignal { + Wait, + Reset, +} + +pin_project! { + pub struct TimeoutBody { + #[pin] + inner: B, + sender: UnboundedSender, + } +} + +impl TimeoutBody { + fn new(inner: B, sender: UnboundedSender) -> Self { + Self { inner, sender } + } +} + +impl Body for TimeoutBody { + type Data = B::Data; + type Error = B::Error; + + fn poll_frame(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll, Self::Error>>> { + let this = self.project(); + let option = ready!(this.inner.poll_frame(cx)); + + if option.is_none() { + let _ = this.sender.send(TimerSignal::Reset); + } + + Poll::Ready(option) + } + + fn is_end_stream(&self) -> bool { + let is_end_stream = self.inner.is_end_stream(); + + if is_end_stream { + let _ = self.sender.send(TimerSignal::Reset); + } + + is_end_stream + } + + fn size_hint(&self) -> http_body::SizeHint { + self.inner.size_hint() + } +} + +pub struct TimeoutStream { + inner: IO, + // hyper requires unpin + sleep: Pin>, + duration: Duration, + waiting: bool, + receiver: UnboundedReceiver, + finished: bool, +} + +impl TimeoutStream { + fn new(inner: IO, duration: Duration, receiver: UnboundedReceiver) -> Self { + Self { + inner, + sleep: Box::pin(tokio::time::sleep(duration)), + duration, + waiting: false, + receiver, + finished: false, + } + } +} + +impl AsyncRead for TimeoutStream { + fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll> { + if !self.finished { + match Pin::new(&mut self.receiver).poll_recv(cx) { + // reset the timer + Poll::Ready(Some(TimerSignal::Reset)) => { + self.waiting = false; + + let deadline = Instant::now() + self.duration; + self.sleep.as_mut().reset(deadline); + } + // enter waiting mode (for response body last chunk) + Poll::Ready(Some(TimerSignal::Wait)) => self.waiting = true, + Poll::Ready(None) => self.finished = true, + Poll::Pending => (), + } + } + + if !self.waiting { + // return error if timer is elapsed + if let Poll::Ready(()) = self.sleep.as_mut().poll(cx) { + return Poll::Ready(Err(std::io::Error::new(ErrorKind::TimedOut, "request header read timed out"))); + } + } + + Pin::new(&mut self.inner).poll_read(cx, buf) + } +} + +impl AsyncWrite for TimeoutStream { + fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { + Pin::new(&mut self.inner).poll_write(cx, buf) + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_flush(cx) + } + + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_shutdown(cx) + } + + fn poll_write_vectored( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[std::io::IoSlice<'_>], + ) -> Poll> { + Pin::new(&mut self.inner).poll_write_vectored(cx, bufs) + } + + fn is_write_vectored(&self) -> bool { + self.inner.is_write_vectored() + } +} diff --git a/packages/axum-server/src/lib.rs b/packages/axum-server/src/lib.rs new file mode 100644 index 000000000..88bf25f19 --- /dev/null +++ b/packages/axum-server/src/lib.rs @@ -0,0 +1,3 @@ +pub mod custom_axum_server; +pub mod signals; +pub mod tsl; diff --git a/packages/axum-server/src/signals.rs b/packages/axum-server/src/signals.rs new file mode 100644 index 000000000..360879e32 --- /dev/null +++ b/packages/axum-server/src/signals.rs @@ -0,0 +1,49 @@ +use std::net::SocketAddr; +use std::time::Duration; + +use tokio::time::{sleep, Instant}; +use torrust_server_lib::signals::{shutdown_signal_with_message, Halted}; +use tracing::instrument; + +#[instrument(skip(handle, rx_halt, message))] +pub async fn graceful_shutdown( + handle: axum_server::Handle, + rx_halt: tokio::sync::oneshot::Receiver, + message: String, + address: SocketAddr, +) { + shutdown_signal_with_message(rx_halt, message.clone()).await; + + let grace_period = Duration::from_secs(90); + let max_wait = Duration::from_secs(95); + let start = Instant::now(); + + handle.graceful_shutdown(Some(grace_period)); + + tracing::info!("!! {} in {} seconds !!", message, grace_period.as_secs()); + + loop { + if handle.connection_count() == 0 { + tracing::info!("All connections closed, shutting down server in address {}", address); + break; + } + + if start.elapsed() >= max_wait { + tracing::warn!( + "Shutdown timeout of {} seconds reached. Forcing shutdown in address {} with {} active connections.", + max_wait.as_secs(), + address, + handle.connection_count() + ); + break; + } + + tracing::info!( + "Remaining alive connections: {} ({}s elapsed)", + handle.connection_count(), + start.elapsed().as_secs() + ); + + sleep(Duration::from_secs(1)).await; + } +} diff --git a/packages/axum-server/src/tsl.rs b/packages/axum-server/src/tsl.rs new file mode 100644 index 000000000..5d68b5b4c --- /dev/null +++ b/packages/axum-server/src/tsl.rs @@ -0,0 +1,85 @@ +use std::panic::Location; +use std::sync::Arc; + +use axum_server::tls_rustls::RustlsConfig; +use thiserror::Error; +use torrust_tracker_configuration::TslConfig; +use torrust_tracker_located_error::{DynError, LocatedError}; +use tracing::instrument; + +/// Error returned by the Bootstrap Process. +#[derive(Error, Debug)] +pub enum Error { + /// Enabled tls but missing config. + #[error("tls config missing")] + MissingTlsConfig { location: &'static Location<'static> }, + + /// Unable to parse tls Config. + #[error("bad tls config: {source}")] + BadTlsConfig { + source: LocatedError<'static, dyn std::error::Error + Send + Sync>, + }, +} + +#[instrument(skip(opt_tsl_config))] +pub async fn make_rust_tls(opt_tsl_config: &Option) -> Option> { + match opt_tsl_config { + Some(tsl_config) => { + let cert = tsl_config.ssl_cert_path.clone(); + let key = tsl_config.ssl_key_path.clone(); + + if !cert.exists() || !key.exists() { + return Some(Err(Error::MissingTlsConfig { + location: Location::caller(), + })); + } + + tracing::info!("Using https: cert path: {cert}."); + tracing::info!("Using https: key path: {key}."); + + Some( + RustlsConfig::from_pem_file(cert, key) + .await + .map_err(|err| Error::BadTlsConfig { + source: (Arc::new(err) as DynError).into(), + }), + ) + } + None => None, + } +} + +#[cfg(test)] +mod tests { + + use camino::Utf8PathBuf; + use torrust_tracker_configuration::TslConfig; + + use super::{make_rust_tls, Error}; + + #[tokio::test] + async fn it_should_error_on_bad_tls_config() { + let err = make_rust_tls(&Some(TslConfig { + ssl_cert_path: Utf8PathBuf::from("bad cert path"), + ssl_key_path: Utf8PathBuf::from("bad key path"), + })) + .await + .expect("tls_was_enabled") + .expect_err("bad_cert_and_key_files"); + + assert!(matches!(err, Error::MissingTlsConfig { location: _ })); + } + + #[tokio::test] + async fn it_should_error_on_missing_cert_or_key_paths() { + let err = make_rust_tls(&Some(TslConfig { + ssl_cert_path: Utf8PathBuf::from(""), + ssl_key_path: Utf8PathBuf::from(""), + })) + .await + .expect("tls_was_enabled") + .expect_err("missing_config"); + + assert!(matches!(err, Error::MissingTlsConfig { location: _ })); + } +} diff --git a/packages/clock/Cargo.toml b/packages/clock/Cargo.toml new file mode 100644 index 000000000..c0cafff0a --- /dev/null +++ b/packages/clock/Cargo.toml @@ -0,0 +1,25 @@ +[package] +description = "A library to a clock for the torrust tracker." +keywords = [ "clock", "library", "torrents" ] +name = "torrust-tracker-clock" +readme = "README.md" + +authors.workspace = true +categories.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +chrono = { version = "0", default-features = false, features = [ "clock" ] } +lazy_static = "1" +tracing = "0" + +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } + +[dev-dependencies] diff --git a/packages/clock/README.md b/packages/clock/README.md new file mode 100644 index 000000000..bfdd7808f --- /dev/null +++ b/packages/clock/README.md @@ -0,0 +1,11 @@ +# Torrust Tracker Clock + +A library to provide a working and mockable clock for the [Torrust Tracker](https://github.com/torrust/torrust-tracker). + +## Documentation + +[Crate documentation](https://docs.rs/torrust-tracker-torrent-clock). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/clock/src/clock/mod.rs b/packages/clock/src/clock/mod.rs new file mode 100644 index 000000000..50afbc9db --- /dev/null +++ b/packages/clock/src/clock/mod.rs @@ -0,0 +1,72 @@ +use std::time::Duration; + +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use self::stopped::StoppedClock; +use self::working::WorkingClock; + +pub mod stopped; +pub mod working; + +/// A generic structure that represents a clock. +/// +/// It can be either the working clock (production) or the stopped clock +/// (testing). It implements the `Time` trait, which gives you the current time. +#[derive(Debug)] +pub struct Clock { + clock: std::marker::PhantomData, +} + +/// The working clock. It returns the current time. +pub type Working = Clock; +/// The stopped clock. It returns always the same fixed time. +pub type Stopped = Clock; + +/// Trait for types that can be used as a timestamp clock. +pub trait Time: Sized { + fn now() -> DurationSinceUnixEpoch; + + fn dbg_clock_type() -> String; + + #[must_use] + fn now_add(add_time: &Duration) -> Option { + Self::now().checked_add(*add_time) + } + #[must_use] + fn now_sub(sub_time: &Duration) -> Option { + Self::now().checked_sub(*sub_time) + } +} + +#[cfg(test)] +mod tests { + use std::any::TypeId; + use std::time::Duration; + + use crate::clock::{self, Stopped, Time, Working}; + use crate::CurrentClock; + + #[test] + fn it_should_be_the_stopped_clock_as_default_when_testing() { + // We are testing, so we should default to the fixed time. + assert_eq!(TypeId::of::(), TypeId::of::()); + assert_eq!(Stopped::now(), CurrentClock::now()); + } + + #[test] + fn it_should_have_different_times() { + assert_ne!(TypeId::of::(), TypeId::of::()); + assert_ne!(Stopped::now(), Working::now()); + } + + #[test] + fn it_should_use_stopped_time_for_testing() { + assert_eq!(CurrentClock::dbg_clock_type(), "Stopped".to_owned()); + + let time = CurrentClock::now(); + std::thread::sleep(Duration::from_millis(50)); + let time_2 = CurrentClock::now(); + + assert_eq!(time, time_2); + } +} diff --git a/packages/clock/src/clock/stopped/mod.rs b/packages/clock/src/clock/stopped/mod.rs new file mode 100644 index 000000000..5d0b2ec4e --- /dev/null +++ b/packages/clock/src/clock/stopped/mod.rs @@ -0,0 +1,209 @@ +/// Trait for types that can be used as a timestamp clock stopped +/// at a given time. +#[allow(clippy::module_name_repetitions)] +pub struct StoppedClock {} + +#[allow(clippy::module_name_repetitions)] +pub trait Stopped: clock::Time { + /// It sets the clock to a given time. + fn local_set(unix_time: &DurationSinceUnixEpoch); + + /// It sets the clock to the Unix Epoch. + fn local_set_to_unix_epoch() { + Self::local_set(&DurationSinceUnixEpoch::ZERO); + } + + /// It sets the clock to the time the application started. + fn local_set_to_app_start_time(); + + /// It sets the clock to the current system time. + fn local_set_to_system_time_now(); + + /// It adds a `Duration` to the clock. + /// + /// # Errors + /// + /// Will return `IntErrorKind` if `duration` would overflow the internal `Duration`. + fn local_add(duration: &Duration) -> Result<(), IntErrorKind>; + + /// It subtracts a `Duration` from the clock. + /// # Errors + /// + /// Will return `IntErrorKind` if `duration` would underflow the internal `Duration`. + fn local_sub(duration: &Duration) -> Result<(), IntErrorKind>; + + /// It resets the clock to default fixed time that is application start time (or the unix epoch when testing). + fn local_reset(); +} + +use std::num::IntErrorKind; +use std::time::Duration; + +use super::{DurationSinceUnixEpoch, Time}; +use crate::clock; + +impl Time for clock::Stopped { + fn now() -> DurationSinceUnixEpoch { + detail::FIXED_TIME.with(|time| { + return *time.borrow(); + }) + } + + fn dbg_clock_type() -> String { + "Stopped".to_owned() + } +} + +impl Stopped for clock::Stopped { + fn local_set(unix_time: &DurationSinceUnixEpoch) { + detail::FIXED_TIME.with(|time| { + *time.borrow_mut() = *unix_time; + }); + } + + fn local_set_to_app_start_time() { + Self::local_set(&detail::get_app_start_time()); + } + + fn local_set_to_system_time_now() { + Self::local_set(&detail::get_app_start_time()); + } + + fn local_add(duration: &Duration) -> Result<(), IntErrorKind> { + detail::FIXED_TIME.with(|time| { + let time_borrowed = *time.borrow(); + *time.borrow_mut() = match time_borrowed.checked_add(*duration) { + Some(time) => time, + None => { + return Err(IntErrorKind::PosOverflow); + } + }; + Ok(()) + }) + } + + fn local_sub(duration: &Duration) -> Result<(), IntErrorKind> { + detail::FIXED_TIME.with(|time| { + let time_borrowed = *time.borrow(); + *time.borrow_mut() = match time_borrowed.checked_sub(*duration) { + Some(time) => time, + None => { + return Err(IntErrorKind::NegOverflow); + } + }; + Ok(()) + }) + } + + fn local_reset() { + Self::local_set(&detail::get_default_fixed_time()); + } +} + +#[cfg(test)] +mod tests { + use std::thread; + use std::time::Duration; + + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::clock::stopped::Stopped as _; + use crate::clock::{Stopped, Time, Working}; + + #[test] + fn it_should_default_to_zero_when_testing() { + assert_eq!(Stopped::now(), DurationSinceUnixEpoch::ZERO); + } + + #[test] + fn it_should_possible_to_set_the_time() { + // Check we start with ZERO. + assert_eq!(Stopped::now(), Duration::ZERO); + + // Set to Current Time and Check + let timestamp = Working::now(); + Stopped::local_set(×tamp); + assert_eq!(Stopped::now(), timestamp); + + // Elapse the Current Time and Check + Stopped::local_add(×tamp).unwrap(); + assert_eq!(Stopped::now(), timestamp + timestamp); + + // Reset to ZERO and Check + Stopped::local_reset(); + assert_eq!(Stopped::now(), Duration::ZERO); + } + + #[test] + fn it_should_default_to_zero_on_thread_exit() { + assert_eq!(Stopped::now(), Duration::ZERO); + let after5 = Working::now_add(&Duration::from_secs(5)).unwrap(); + Stopped::local_set(&after5); + assert_eq!(Stopped::now(), after5); + + let t = thread::spawn(move || { + // each thread starts out with the initial value of ZERO + assert_eq!(Stopped::now(), Duration::ZERO); + + // and gets set to the current time. + let timestamp = Working::now(); + Stopped::local_set(×tamp); + assert_eq!(Stopped::now(), timestamp); + }); + + // wait for the thread to complete and bail out on panic + t.join().unwrap(); + + // we retain our original value of current time + 5sec despite the child thread + assert_eq!(Stopped::now(), after5); + + // Reset to ZERO and Check + Stopped::local_reset(); + assert_eq!(Stopped::now(), Duration::ZERO); + } +} + +mod detail { + use std::cell::RefCell; + use std::time::SystemTime; + + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::static_time; + + thread_local!(pub static FIXED_TIME: RefCell = RefCell::new(get_default_fixed_time())); + + pub fn get_app_start_time() -> DurationSinceUnixEpoch { + (*static_time::TIME_AT_APP_START) + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap() + } + + #[cfg(not(test))] + pub fn get_default_fixed_time() -> DurationSinceUnixEpoch { + get_app_start_time() + } + + #[cfg(test)] + pub fn get_default_fixed_time() -> DurationSinceUnixEpoch { + DurationSinceUnixEpoch::ZERO + } + + #[cfg(test)] + mod tests { + use std::time::Duration; + + use crate::clock::stopped::detail::{get_app_start_time, get_default_fixed_time}; + + #[test] + fn it_should_get_the_zero_start_time_when_testing() { + assert_eq!(get_default_fixed_time(), Duration::ZERO); + } + + #[test] + fn it_should_get_app_start_time() { + const TIME_AT_WRITING_THIS_TEST: Duration = Duration::new(1_662_983_731, 22312); + assert!(get_app_start_time() > TIME_AT_WRITING_THIS_TEST); + } + } +} diff --git a/packages/clock/src/clock/working/mod.rs b/packages/clock/src/clock/working/mod.rs new file mode 100644 index 000000000..6d0b4dcf7 --- /dev/null +++ b/packages/clock/src/clock/working/mod.rs @@ -0,0 +1,18 @@ +use std::time::SystemTime; + +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::clock; + +#[allow(clippy::module_name_repetitions)] +pub struct WorkingClock; + +impl clock::Time for clock::Working { + fn now() -> DurationSinceUnixEpoch { + SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap() + } + + fn dbg_clock_type() -> String { + "Working".to_owned() + } +} diff --git a/packages/clock/src/conv/mod.rs b/packages/clock/src/conv/mod.rs new file mode 100644 index 000000000..0ac278171 --- /dev/null +++ b/packages/clock/src/conv/mod.rs @@ -0,0 +1,82 @@ +use std::str::FromStr; + +use chrono::{DateTime, Utc}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +/// It converts a string in ISO 8601 format to a timestamp. +/// +/// For example, the string `1970-01-01T00:00:00.000Z` which is the Unix Epoch +/// will be converted to a timestamp of 0: `DurationSinceUnixEpoch::ZERO`. +/// +/// # Panics +/// +/// Will panic if the input time cannot be converted to `DateTime::`, internally using the `i64` type. +/// (this will naturally happen in 292.5 billion years) +#[must_use] +pub fn convert_from_iso_8601_to_timestamp(iso_8601: &str) -> DurationSinceUnixEpoch { + convert_from_datetime_utc_to_timestamp(&DateTime::::from_str(iso_8601).unwrap()) +} + +/// It converts a `DateTime::` to a timestamp. +/// For example, the `DateTime::` of the Unix Epoch will be converted to a +/// timestamp of 0: `DurationSinceUnixEpoch::ZERO`. +/// +/// # Panics +/// +/// Will panic if the input time overflows the `u64` type. +/// (this will naturally happen in 584.9 billion years) +#[must_use] +pub fn convert_from_datetime_utc_to_timestamp(datetime_utc: &DateTime) -> DurationSinceUnixEpoch { + DurationSinceUnixEpoch::from_secs(u64::try_from(datetime_utc.timestamp()).expect("Overflow of u64 seconds, very future!")) +} + +/// It converts a timestamp to a `DateTime::`. +/// For example, the timestamp of 0: `DurationSinceUnixEpoch::ZERO` will be +/// converted to the `DateTime::` of the Unix Epoch. +/// +/// # Panics +/// +/// Will panic if the input time overflows the `u64` seconds overflows the `i64` type. +/// (this will naturally happen in 292.5 billion years) +#[must_use] +pub fn convert_from_timestamp_to_datetime_utc(duration: DurationSinceUnixEpoch) -> DateTime { + DateTime::from_timestamp( + i64::try_from(duration.as_secs()).expect("Overflow of i64 seconds, very future!"), + duration.subsec_nanos(), + ) + .unwrap() +} + +#[cfg(test)] +mod tests { + use chrono::DateTime; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::conv::{ + convert_from_datetime_utc_to_timestamp, convert_from_iso_8601_to_timestamp, convert_from_timestamp_to_datetime_utc, + }; + + #[test] + fn should_be_converted_to_datetime_utc() { + let timestamp = DurationSinceUnixEpoch::ZERO; + assert_eq!( + convert_from_timestamp_to_datetime_utc(timestamp), + DateTime::from_timestamp(0, 0).unwrap() + ); + } + + #[test] + fn should_be_converted_from_datetime_utc() { + let datetime = DateTime::from_timestamp(0, 0).unwrap(); + assert_eq!( + convert_from_datetime_utc_to_timestamp(&datetime), + DurationSinceUnixEpoch::ZERO + ); + } + + #[test] + fn should_be_converted_from_datetime_utc_in_iso_8601() { + let iso_8601 = "1970-01-01T00:00:00.000Z".to_string(); + assert_eq!(convert_from_iso_8601_to_timestamp(&iso_8601), DurationSinceUnixEpoch::ZERO); + } +} diff --git a/packages/clock/src/lib.rs b/packages/clock/src/lib.rs new file mode 100644 index 000000000..ff0527714 --- /dev/null +++ b/packages/clock/src/lib.rs @@ -0,0 +1,56 @@ +//! Time related functions and types. +//! +//! It's usually a good idea to control where the time comes from +//! in an application so that it can be mocked for testing and it can be +//! controlled in production so we get the intended behavior without +//! relying on the specific time zone for the underlying system. +//! +//! Clocks use the type `DurationSinceUnixEpoch` which is a +//! `std::time::Duration` since the Unix Epoch (timestamp). +//! +//! ```text +//! Local time: lun 2023-03-27 16:12:00 WEST +//! Universal time: lun 2023-03-27 15:12:00 UTC +//! Time zone: Atlantic/Canary (WEST, +0100) +//! Timestamp: 1679929914 +//! Duration: 1679929914.10167426 +//! ``` +//! +//! > **NOTICE**: internally the `Duration` is stores it's main unit as seconds in a `u64` and it will +//! > overflow in 584.9 billion years. +//! +//! > **NOTICE**: the timestamp does not depend on the time zone. That gives you +//! > the ability to use the clock regardless of the underlying system time zone +//! > configuration. See [Unix time Wikipedia entry](https://en.wikipedia.org/wiki/Unix_time). +pub mod clock; +pub mod conv; +pub mod static_time; + +#[macro_use] +extern crate lazy_static; + +use tracing::instrument; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; + +/// It initializes the application static values. +/// +/// These values are accessible throughout the entire application: +/// +/// - The time when the application started. +/// - An ephemeral instance random seed. This seed is used for encryption and +/// it's changed when the main application process is restarted. +#[instrument(skip())] +pub fn initialize_static() { + // Set the time of Torrust app starting + lazy_static::initialize(&static_time::TIME_AT_APP_START); +} diff --git a/src/shared/clock/static_time.rs b/packages/clock/src/static_time/mod.rs similarity index 100% rename from src/shared/clock/static_time.rs rename to packages/clock/src/static_time/mod.rs diff --git a/packages/clock/tests/clock/mod.rs b/packages/clock/tests/clock/mod.rs new file mode 100644 index 000000000..5d94bb83d --- /dev/null +++ b/packages/clock/tests/clock/mod.rs @@ -0,0 +1,16 @@ +use std::time::Duration; + +use torrust_tracker_clock::clock::Time; + +use crate::CurrentClock; + +#[test] +fn it_should_use_stopped_time_for_testing() { + assert_eq!(CurrentClock::dbg_clock_type(), "Stopped".to_owned()); + + let time = CurrentClock::now(); + std::thread::sleep(Duration::from_millis(50)); + let time_2 = CurrentClock::now(); + + assert_eq!(time, time_2); +} diff --git a/packages/clock/tests/integration.rs b/packages/clock/tests/integration.rs new file mode 100644 index 000000000..fa500227a --- /dev/null +++ b/packages/clock/tests/integration.rs @@ -0,0 +1,19 @@ +//! Integration tests. +//! +//! ```text +//! cargo test --test integration +//! ``` + +//mod common; +mod clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = torrust_tracker_clock::clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = torrust_tracker_clock::clock::Stopped; diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 6f9e5cbc5..1155ba417 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -1,20 +1,32 @@ [package] -name = "torrust-tracker-configuration" description = "A library to provide configuration to the Torrust Tracker." -license = "AGPL-3.0" -version.workspace = true +keywords = [ "config", "library", "settings" ] +name = "torrust-tracker-configuration" +readme = "README.md" + authors.workspace = true +documentation.workspace = true edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true [dependencies] -serde = { version = "1.0", features = ["derive"] } -serde_with = "2.0" -config = "0.13" -toml = "0.7" -log = { version = "0.4", features = ["release_max_level_info"] } -thiserror = "1.0" -torrust-tracker-primitives = { version = "3.0.0-alpha.2", path = "../primitives" } -torrust-tracker-located-error = { version = "3.0.0-alpha.2", path = "../located-error" } +camino = { version = "1", features = [ "serde", "serde1" ] } +derive_more = { version = "2", features = [ "constructor", "display" ] } +figment = { version = "0", features = [ "env", "test", "toml" ] } +serde = { version = "1", features = [ "derive" ] } +serde_json = { version = "1", features = [ "preserve_order" ] } +serde_with = "3" +thiserror = "2" +toml = "0" +torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } +tracing = "0" +tracing-subscriber = { version = "0", features = [ "json" ] } +url = "2" [dev-dependencies] -uuid = { version = "1", features = ["v4"] } +uuid = { version = "1", features = [ "v4" ] } diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index e48355757..d12020b8c 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -3,696 +3,342 @@ //! This module contains the configuration data structures for the //! Torrust Tracker, which is a `BitTorrent` tracker server. //! -//! The configuration is loaded from a [TOML](https://toml.io/en/) file -//! `config.toml` in the project root folder or from an environment variable -//! with the same content as the file. -//! -//! When you run the tracker without a configuration file, a new one will be -//! created with the default values, but the tracker immediately exits. You can -//! then edit the configuration file and run the tracker again. -//! -//! Configuration can not only be loaded from a file, but also from environment -//! variable `TORRUST_TRACKER_CONFIG`. This is useful when running the tracker -//! in a Docker container or environments where you do not have a persistent -//! storage or you cannot inject a configuration file. Refer to -//! [`Torrust Tracker documentation`](https://docs.rs/torrust-tracker) for more -//! information about how to pass configuration to the tracker. -//! -//! # Table of contents -//! -//! - [Sections](#sections) -//! - [Port binding](#port-binding) -//! - [TSL support](#tsl-support) -//! - [Generating self-signed certificates](#generating-self-signed-certificates) -//! - [Default configuration](#default-configuration) -//! -//! ## Sections -//! -//! Each section in the toml structure is mapped to a data structure. For -//! example, the `[http_api]` section (configuration for the tracker HTTP API) -//! is mapped to the [`HttpApi`](HttpApi) structure. -//! -//! > **NOTICE**: some sections are arrays of structures. For example, the -//! > `[[udp_trackers]]` section is an array of [`UdpTracker`](UdpTracker) since -//! > you can have multiple running UDP trackers bound to different ports. -//! -//! Please refer to the documentation of each structure for more information -//! about each section. -//! -//! - [`Core configuration`](crate::Configuration) -//! - [`HTTP API configuration`](crate::HttpApi) -//! - [`HTTP Tracker configuration`](crate::HttpTracker) -//! - [`UDP Tracker configuration`](crate::UdpTracker) -//! -//! ## Port binding -//! -//! For the API, HTTP and UDP trackers you can bind to a random port by using -//! port `0`. For example, if you want to bind to a random port on all -//! interfaces, use `0.0.0.0:0`. The OS will choose a random port but the -//! tracker will not print the port it is listening to when it starts. It just -//! says `Starting Torrust HTTP tracker server on: http://0.0.0.0:0`. It shows -//! the port used in the configuration file, and not the port the -//! tracker is actually listening to. This is a planned feature, see issue -//! [186](https://github.com/torrust/torrust-tracker/issues/186) for more -//! information. -//! -//! ## TSL support -//! -//! For the API and HTTP tracker you can enable TSL by setting `ssl_enabled` to -//! `true` and setting the paths to the certificate and key files. -//! -//! Typically, you will have a directory structure like this: -//! -//! ```text -//! storage/ -//! ├── database -//! │ └── data.db -//! └── ssl_certificates -//! ├── localhost.crt -//! └── localhost.key -//! ``` -//! -//! where you can store all the persistent data. -//! -//! Alternatively, you could setup a reverse proxy like Nginx or Apache to -//! handle the SSL/TLS part and forward the requests to the tracker. If you do -//! that, you should set [`on_reverse_proxy`](crate::Configuration::on_reverse_proxy) -//! to `true` in the configuration file. It's out of scope for this -//! documentation to explain in detail how to setup a reverse proxy, but the -//! configuration file should be something like this: -//! -//! For [NGINX](https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/): -//! -//! ```text -//! # HTTPS only (with SSL - force redirect to HTTPS) -//! -//! server { -//! listen 80; -//! server_name tracker.torrust.com; -//! -//! return 301 https://$host$request_uri; -//! } -//! -//! server { -//! listen 443; -//! server_name tracker.torrust.com; -//! -//! ssl_certificate CERT_PATH -//! ssl_certificate_key CERT_KEY_PATH; -//! -//! location / { -//! proxy_set_header X-Forwarded-For $remote_addr; -//! proxy_pass http://127.0.0.1:6969; -//! } -//! } -//! ``` -//! -//! For [Apache](https://httpd.apache.org/docs/2.4/howto/reverse_proxy.html): -//! -//! ```text -//! # HTTPS only (with SSL - force redirect to HTTPS) -//! -//! -//! ServerAdmin webmaster@tracker.torrust.com -//! ServerName tracker.torrust.com -//! -//! -//! RewriteEngine on -//! RewriteCond %{HTTPS} off -//! RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] -//! -//! -//! -//! -//! -//! ServerAdmin webmaster@tracker.torrust.com -//! ServerName tracker.torrust.com -//! -//! -//! Order allow,deny -//! Allow from all -//! -//! -//! ProxyPreserveHost On -//! ProxyRequests Off -//! AllowEncodedSlashes NoDecode -//! -//! ProxyPass / http://localhost:3000/ -//! ProxyPassReverse / http://localhost:3000/ -//! ProxyPassReverse / http://tracker.torrust.com/ -//! -//! RequestHeader set X-Forwarded-Proto "https" -//! RequestHeader set X-Forwarded-Port "443" -//! -//! ErrorLog ${APACHE_LOG_DIR}/tracker.torrust.com-error.log -//! CustomLog ${APACHE_LOG_DIR}/tracker.torrust.com-access.log combined -//! -//! SSLCertificateFile CERT_PATH -//! SSLCertificateKeyFile CERT_KEY_PATH -//! -//! -//! ``` -//! -//! ## Generating self-signed certificates -//! -//! For testing purposes, you can use self-signed certificates. -//! -//! Refer to [Let's Encrypt - Certificates for localhost](https://letsencrypt.org/docs/certificates-for-localhost/) -//! for more information. -//! -//! Running the following command will generate a certificate (`localhost.crt`) -//! and key (`localhost.key`) file in your current directory: -//! -//! ```s -//! openssl req -x509 -out localhost.crt -keyout localhost.key \ -//! -newkey rsa:2048 -nodes -sha256 \ -//! -subj '/CN=localhost' -extensions EXT -config <( \ -//! printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth") -//! ``` -//! -//! You can then use the generated files in the configuration file: -//! -//! ```s -//! [[http_trackers]] -//! enabled = true -//! ... -//! ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -//! ssl_key_path = "./storage/ssl_certificates/localhost.key" -//! -//! [http_api] -//! enabled = true -//! ... -//! ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -//! ssl_key_path = "./storage/ssl_certificates/localhost.key" -//! ``` -//! -//! ## Default configuration -//! -//! The default configuration is: -//! -//! ```toml -//! log_level = "info" -//! mode = "public" -//! db_driver = "Sqlite3" -//! db_path = "./storage/database/data.db" -//! announce_interval = 120 -//! min_announce_interval = 120 -//! max_peer_timeout = 900 -//! on_reverse_proxy = false -//! external_ip = "0.0.0.0" -//! tracker_usage_statistics = true -//! persistent_torrent_completed_stat = false -//! inactive_peer_cleanup_interval = 600 -//! remove_peerless_torrents = true -//! -//! [[udp_trackers]] -//! enabled = false -//! bind_address = "0.0.0.0:6969" -//! -//! [[http_trackers]] -//! enabled = false -//! bind_address = "0.0.0.0:7070" -//! ssl_enabled = false -//! ssl_cert_path = "" -//! ssl_key_path = "" -//! -//! [http_api] -//! enabled = true -//! bind_address = "127.0.0.1:1212" -//! ssl_enabled = false -//! ssl_cert_path = "" -//! ssl_key_path = "" -//! -//! [http_api.access_tokens] -//! admin = "MyAccessToken" -//!``` -use std::collections::{HashMap, HashSet}; -use std::net::IpAddr; -use std::panic::Location; -use std::path::Path; -use std::str::FromStr; +//! The current version for configuration is [`v2_0_0`]. +pub mod logging; +pub mod v2_0_0; +pub mod validator; + +use std::collections::HashMap; +use std::env; use std::sync::Arc; -use std::{env, fs}; +use std::time::Duration; -use config::{Config, ConfigError, File, FileFormat}; -use log::warn; +use camino::Utf8PathBuf; +use derive_more::{Constructor, Display}; use serde::{Deserialize, Serialize}; -use serde_with::{serde_as, NoneAsEmptyString}; +use serde_with::serde_as; use thiserror::Error; -use torrust_tracker_located_error::{Located, LocatedError}; -use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; - -/// Configuration for each UDP tracker. -#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] -pub struct UdpTracker { - /// Weather the UDP tracker is enabled or not. - pub enabled: bool, - /// The address the tracker will bind to. - /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to - /// listen to all interfaces, use `0.0.0.0`. If you want the operating - /// system to choose a random port, use port `0`. - pub bind_address: String, +use torrust_tracker_located_error::{DynError, LocatedError}; + +/// The maximum number of returned peers for a torrent. +pub const TORRENT_PEERS_LIMIT: usize = 74; + +/// Default timeout for sending and receiving packets. And waiting for sockets +/// to be readable and writable. +pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(5); + +// Environment variables + +/// The whole `tracker.toml` file content. It has priority over the config file. +/// Even if the file is not on the default path. +const ENV_VAR_CONFIG_TOML: &str = "TORRUST_TRACKER_CONFIG_TOML"; + +/// The `tracker.toml` file location. +pub const ENV_VAR_CONFIG_TOML_PATH: &str = "TORRUST_TRACKER_CONFIG_TOML_PATH"; + +pub type Configuration = v2_0_0::Configuration; +pub type Core = v2_0_0::core::Core; +pub type Logging = v2_0_0::logging::Logging; +pub type HealthCheckApi = v2_0_0::health_check_api::HealthCheckApi; +pub type HttpApi = v2_0_0::tracker_api::HttpApi; +pub type HttpTracker = v2_0_0::http_tracker::HttpTracker; +pub type UdpTracker = v2_0_0::udp_tracker::UdpTracker; +pub type Database = v2_0_0::database::Database; +pub type Driver = v2_0_0::database::Driver; +pub type Threshold = v2_0_0::logging::Threshold; + +pub type AccessTokens = HashMap; + +pub const LATEST_VERSION: &str = "2.0.0"; + +/// Info about the configuration specification. +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Display, Clone)] +#[display("Metadata(app: {app}, purpose: {purpose}, schema_version: {schema_version})")] +pub struct Metadata { + /// The application this configuration is valid for. + #[serde(default = "Metadata::default_app")] + app: App, + + /// The purpose of this parsed file. + #[serde(default = "Metadata::default_purpose")] + purpose: Purpose, + + /// The schema version for the configuration. + #[serde(default = "Metadata::default_schema_version")] + #[serde(flatten)] + schema_version: Version, } -/// Configuration for each HTTP tracker. -#[serde_as] -#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] -pub struct HttpTracker { - /// Weather the HTTP tracker is enabled or not. - pub enabled: bool, - /// The address the tracker will bind to. - /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to - /// listen to all interfaces, use `0.0.0.0`. If you want the operating - /// system to choose a random port, use port `0`. - pub bind_address: String, - /// Weather the HTTP tracker will use SSL or not. - pub ssl_enabled: bool, - /// Path to the SSL certificate file. Only used if `ssl_enabled` is `true`. - #[serde_as(as = "NoneAsEmptyString")] - pub ssl_cert_path: Option, - /// Path to the SSL key file. Only used if `ssl_enabled` is `true`. - #[serde_as(as = "NoneAsEmptyString")] - pub ssl_key_path: Option, +impl Default for Metadata { + fn default() -> Self { + Self { + app: Self::default_app(), + purpose: Self::default_purpose(), + schema_version: Self::default_schema_version(), + } + } } -/// Configuration for the HTTP API. -#[serde_as] -#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] -pub struct HttpApi { - /// Weather the HTTP API is enabled or not. - pub enabled: bool, - /// The address the tracker will bind to. - /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to - /// listen to all interfaces, use `0.0.0.0`. If you want the operating - /// system to choose a random port, use port `0`. - pub bind_address: String, - /// Weather the HTTP API will use SSL or not. - pub ssl_enabled: bool, - /// Path to the SSL certificate file. Only used if `ssl_enabled` is `true`. - #[serde_as(as = "NoneAsEmptyString")] - pub ssl_cert_path: Option, - /// Path to the SSL key file. Only used if `ssl_enabled` is `true`. - #[serde_as(as = "NoneAsEmptyString")] - pub ssl_key_path: Option, - /// Access tokens for the HTTP API. The key is a label identifying the - /// token and the value is the token itself. The token is used to - /// authenticate the user. All tokens are valid for all endpoints and have - /// the all permissions. - pub access_tokens: HashMap, +impl Metadata { + fn default_app() -> App { + App::TorrustTracker + } + + fn default_purpose() -> Purpose { + Purpose::Configuration + } + + fn default_schema_version() -> Version { + Version::latest() + } +} + +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Display, Clone)] +#[serde(rename_all = "kebab-case")] +pub enum App { + TorrustTracker, +} + +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Display, Clone)] +#[serde(rename_all = "lowercase")] +pub enum Purpose { + Configuration, } -impl HttpApi { - /// Checks if the given token is one of the token in the configuration. - #[must_use] - pub fn contains_token(&self, token: &str) -> bool { - let tokens: HashMap = self.access_tokens.clone(); - let tokens: HashSet = tokens.into_values().collect(); - tokens.contains(token) +/// The configuration version. +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Display, Clone)] +#[serde(rename_all = "lowercase")] +pub struct Version { + #[serde(default = "Version::default_semver")] + schema_version: String, +} + +impl Default for Version { + fn default() -> Self { + Self { + schema_version: Self::default_semver(), + } } } -/// Core configuration for the tracker. -#[allow(clippy::struct_excessive_bools)] -#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)] -pub struct Configuration { - /// Logging level. Possible values are: `Off`, `Error`, `Warn`, `Info`, - /// `Debug` and `Trace`. Default is `Info`. - pub log_level: Option, - /// Tracker mode. See [`TrackerMode`](torrust_tracker_primitives::TrackerMode) for more information. - pub mode: TrackerMode, - - // Database configuration - /// Database driver. Possible values are: `Sqlite3`, and `MySQL`. - pub db_driver: DatabaseDriver, - /// Database connection string. The format depends on the database driver. - /// For `Sqlite3`, the format is `path/to/database.db`, for example: - /// `./storage/database/data.db`. - /// For `Mysql`, the format is `mysql://db_user:db_user_password:port/db_name`, for - /// example: `root:password@localhost:3306/torrust`. - pub db_path: String, +impl Version { + fn new(semver: &str) -> Self { + Self { + schema_version: semver.to_owned(), + } + } - /// Interval in seconds that the client should wait between sending regular - /// announce requests to the tracker. - /// - /// It's a **recommended** wait time between announcements. - /// - /// This is the standard amount of time that clients should wait between - /// sending consecutive announcements to the tracker. This value is set by - /// the tracker and is typically provided in the tracker's response to a - /// client's initial request. It serves as a guideline for clients to know - /// how often they should contact the tracker for updates on the peer list, - /// while ensuring that the tracker is not overwhelmed with requests. - pub announce_interval: u32, - /// Minimum announce interval. Clients must not reannounce more frequently - /// than this. - /// - /// It establishes the shortest allowed wait time. - /// - /// This is an optional parameter in the protocol that the tracker may - /// provide in its response. It sets a lower limit on the frequency at which - /// clients are allowed to send announcements. Clients should respect this - /// value to prevent sending too many requests in a short period, which - /// could lead to excessive load on the tracker or even getting banned by - /// the tracker for not adhering to the rules. - pub min_announce_interval: u32, - /// Weather the tracker is behind a reverse proxy or not. - /// If the tracker is behind a reverse proxy, the `X-Forwarded-For` header - /// sent from the proxy will be used to get the client's IP address. - pub on_reverse_proxy: bool, - /// The external IP address of the tracker. If the client is using a - /// loopback IP address, this IP address will be used instead. If the peer - /// is using a loopback IP address, the tracker assumes that the peer is - /// in the same network as the tracker and will use the tracker's IP - /// address instead. - pub external_ip: Option, - /// Weather the tracker should collect statistics about tracker usage. - /// If enabled, the tracker will collect statistics like the number of - /// connections handled, the number of announce requests handled, etc. - /// Refer to the [`Tracker`](https://docs.rs/torrust-tracker) for more - /// information about the collected metrics. - pub tracker_usage_statistics: bool, - /// If enabled the tracker will persist the number of completed downloads. - /// That's how many times a torrent has been downloaded completely. - pub persistent_torrent_completed_stat: bool, + fn latest() -> Self { + Self { + schema_version: LATEST_VERSION.to_string(), + } + } + fn default_semver() -> String { + LATEST_VERSION.to_string() + } +} + +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Constructor)] +pub struct TrackerPolicy { // Cleanup job configuration /// Maximum time in seconds that a peer can be inactive before being /// considered an inactive peer. If a peer is inactive for more than this /// time, it will be removed from the torrent peer list. + #[serde(default = "TrackerPolicy::default_max_peer_timeout")] pub max_peer_timeout: u32, - /// Interval in seconds that the cleanup job will run to remove inactive - /// peers from the torrent peer list. - pub inactive_peer_cleanup_interval: u64, + + /// If enabled the tracker will persist the number of completed downloads. + /// That's how many times a torrent has been downloaded completely. + #[serde(default = "TrackerPolicy::default_persistent_torrent_completed_stat")] + pub persistent_torrent_completed_stat: bool, + /// If enabled, the tracker will remove torrents that have no peers. - /// THe clean up torrent job runs every `inactive_peer_cleanup_interval` + /// The clean up torrent job runs every `inactive_peer_cleanup_interval` /// seconds and it removes inactive peers. Eventually, the peer list of a /// torrent could be empty and the torrent will be removed if this option is /// enabled. + #[serde(default = "TrackerPolicy::default_remove_peerless_torrents")] pub remove_peerless_torrents: bool, - - // Server jobs configuration - /// The list of UDP trackers the tracker is running. Each UDP tracker - /// represents a UDP server that the tracker is running and it has its own - /// configuration. - pub udp_trackers: Vec, - /// The list of HTTP trackers the tracker is running. Each HTTP tracker - /// represents a HTTP server that the tracker is running and it has its own - /// configuration. - pub http_trackers: Vec, - /// The HTTP API configuration. - pub http_api: HttpApi, -} - -/// Errors that can occur when loading the configuration. -#[derive(Error, Debug)] -pub enum Error { - /// Unable to load the configuration from the environment variable. - /// This error only occurs if there is no configuration file and the - /// `TORRUST_TRACKER_CONFIG` environment variable is not set. - #[error("Unable to load from Environmental Variable: {source}")] - UnableToLoadFromEnvironmentVariable { - source: LocatedError<'static, dyn std::error::Error + Send + Sync>, - }, - - /// If you run the tracker without providing the configuration (via the - /// `TORRUST_TRACKER_CONFIG` environment variable or configuration file), - /// the tracker will create a default configuration file but it will not - /// load it. It will return this error instead and you have to restart the - /// it. - #[error("Default configuration created at: `{path}`, please review and reload tracker, {location}")] - CreatedNewConfigHalt { - location: &'static Location<'static>, - path: String, - }, - - /// Unable to load the configuration from the configuration file. - #[error("Failed processing the configuration: {source}")] - ConfigError { source: LocatedError<'static, ConfigError> }, } -impl From for Error { - #[track_caller] - fn from(err: ConfigError) -> Self { - Self::ConfigError { - source: Located(err).into(), +impl Default for TrackerPolicy { + fn default() -> Self { + Self { + max_peer_timeout: Self::default_max_peer_timeout(), + persistent_torrent_completed_stat: Self::default_persistent_torrent_completed_stat(), + remove_peerless_torrents: Self::default_remove_peerless_torrents(), } } } -impl Default for Configuration { - fn default() -> Self { - let mut configuration = Configuration { - log_level: Option::from(String::from("info")), - mode: TrackerMode::Public, - db_driver: DatabaseDriver::Sqlite3, - db_path: String::from("./storage/database/data.db"), - announce_interval: 120, - min_announce_interval: 120, - max_peer_timeout: 900, - on_reverse_proxy: false, - external_ip: Some(String::from("0.0.0.0")), - tracker_usage_statistics: true, - persistent_torrent_completed_stat: false, - inactive_peer_cleanup_interval: 600, - remove_peerless_torrents: true, - udp_trackers: Vec::new(), - http_trackers: Vec::new(), - http_api: HttpApi { - enabled: true, - bind_address: String::from("127.0.0.1:1212"), - ssl_enabled: false, - ssl_cert_path: None, - ssl_key_path: None, - access_tokens: [(String::from("admin"), String::from("MyAccessToken"))] - .iter() - .cloned() - .collect(), - }, - }; - configuration.udp_trackers.push(UdpTracker { - enabled: false, - bind_address: String::from("0.0.0.0:6969"), - }); - configuration.http_trackers.push(HttpTracker { - enabled: false, - bind_address: String::from("0.0.0.0:7070"), - ssl_enabled: false, - ssl_cert_path: None, - ssl_key_path: None, - }); - configuration +impl TrackerPolicy { + fn default_max_peer_timeout() -> u32 { + 900 } -} -impl Configuration { - /// Returns the tracker public IP address id defined in the configuration, - /// and `None` otherwise. - #[must_use] - pub fn get_ext_ip(&self) -> Option { - match &self.external_ip { - None => None, - Some(external_ip) => match IpAddr::from_str(external_ip) { - Ok(external_ip) => Some(external_ip), - Err(_) => None, - }, - } + fn default_persistent_torrent_completed_stat() -> bool { + false } - /// Loads the configuration from the configuration file. + fn default_remove_peerless_torrents() -> bool { + true + } +} + +/// Information required for loading config +#[derive(Debug, Default, Clone)] +pub struct Info { + config_toml: Option, + config_toml_path: String, +} + +impl Info { + /// Build Configuration Info /// /// # Errors /// - /// Will return `Err` if `path` does not exist or has a bad configuration. - pub fn load_from_file(path: &str) -> Result { - let config_builder = Config::builder(); - - #[allow(unused_assignments)] - let mut config = Config::default(); - - if Path::new(path).exists() { - config = config_builder.add_source(File::with_name(path)).build()?; + /// Will return `Err` if unable to obtain a configuration. + /// + #[allow(clippy::needless_pass_by_value)] + pub fn new(default_config_toml_path: String) -> Result { + let env_var_config_toml = ENV_VAR_CONFIG_TOML.to_string(); + let env_var_config_toml_path = ENV_VAR_CONFIG_TOML_PATH.to_string(); + + let config_toml = if let Ok(config_toml) = env::var(env_var_config_toml) { + println!("Loading extra configuration from environment variable:\n {config_toml}"); + Some(config_toml) } else { - warn!("No config file found."); - warn!("Creating config file.."); - let config = Configuration::default(); - config.save_to_file(path)?; - return Err(Error::CreatedNewConfigHalt { - location: Location::caller(), - path: path.to_string(), - }); - } + None + }; - let torrust_config: Configuration = config.try_deserialize()?; + let config_toml_path = if let Ok(config_toml_path) = env::var(env_var_config_toml_path) { + println!("Loading extra configuration from file: `{config_toml_path}` ..."); + config_toml_path + } else { + println!("Loading extra configuration from default configuration file: `{default_config_toml_path}` ..."); + default_config_toml_path + }; - Ok(torrust_config) + Ok(Self { + config_toml, + config_toml_path, + }) } +} - /// Loads the configuration from the environment variable. The whole - /// configuration must be in the environment variable. It contains the same - /// configuration as the configuration file with the same format. +/// Announce policy +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Copy, Constructor)] +pub struct AnnouncePolicy { + /// Interval in seconds that the client should wait between sending regular + /// announce requests to the tracker. /// - /// # Errors + /// It's a **recommended** wait time between announcements. /// - /// Will return `Err` if the environment variable does not exist or has a bad configuration. - pub fn load_from_env_var(config_env_var_name: &str) -> Result { - match env::var(config_env_var_name) { - Ok(config_toml) => { - let config_builder = Config::builder() - .add_source(File::from_str(&config_toml, FileFormat::Toml)) - .build()?; - let config = config_builder.try_deserialize()?; - Ok(config) - } - Err(e) => Err(Error::UnableToLoadFromEnvironmentVariable { - source: (Arc::new(e) as Arc).into(), - }), - } - } + /// This is the standard amount of time that clients should wait between + /// sending consecutive announcements to the tracker. This value is set by + /// the tracker and is typically provided in the tracker's response to a + /// client's initial request. It serves as a guideline for clients to know + /// how often they should contact the tracker for updates on the peer list, + /// while ensuring that the tracker is not overwhelmed with requests. + #[serde(default = "AnnouncePolicy::default_interval")] + pub interval: u32, - /// Saves the configuration to the configuration file. + /// Minimum announce interval. Clients must not reannounce more frequently + /// than this. /// - /// # Errors + /// It establishes the shortest allowed wait time. /// - /// Will return `Err` if `filename` does not exist or the user does not have - /// permission to read it. Will also return `Err` if the configuration is - /// not valid or cannot be encoded to TOML. - pub fn save_to_file(&self, path: &str) -> Result<(), Error> { - fs::write(path, self.to_toml()).expect("Could not write to file!"); - Ok(()) - } - - /// Encodes the configuration to TOML. - fn to_toml(&self) -> String { - toml::to_string(self).expect("Could not encode TOML value") - } + /// This is an optional parameter in the protocol that the tracker may + /// provide in its response. It sets a lower limit on the frequency at which + /// clients are allowed to send announcements. Clients should respect this + /// value to prevent sending too many requests in a short period, which + /// could lead to excessive load on the tracker or even getting banned by + /// the tracker for not adhering to the rules. + #[serde(default = "AnnouncePolicy::default_interval_min")] + pub interval_min: u32, } -#[cfg(test)] -mod tests { - use crate::Configuration; - - #[cfg(test)] - fn default_config_toml() -> String { - let config = r#"log_level = "info" - mode = "public" - db_driver = "Sqlite3" - db_path = "./storage/database/data.db" - announce_interval = 120 - min_announce_interval = 120 - on_reverse_proxy = false - external_ip = "0.0.0.0" - tracker_usage_statistics = true - persistent_torrent_completed_stat = false - max_peer_timeout = 900 - inactive_peer_cleanup_interval = 600 - remove_peerless_torrents = true - - [[udp_trackers]] - enabled = false - bind_address = "0.0.0.0:6969" - - [[http_trackers]] - enabled = false - bind_address = "0.0.0.0:7070" - ssl_enabled = false - ssl_cert_path = "" - ssl_key_path = "" - - [http_api] - enabled = true - bind_address = "127.0.0.1:1212" - ssl_enabled = false - ssl_cert_path = "" - ssl_key_path = "" - - [http_api.access_tokens] - admin = "MyAccessToken" - "# - .lines() - .map(str::trim_start) - .collect::>() - .join("\n"); - config +impl Default for AnnouncePolicy { + fn default() -> Self { + Self { + interval: Self::default_interval(), + interval_min: Self::default_interval_min(), + } } +} - #[test] - fn configuration_should_have_default_values() { - let configuration = Configuration::default(); - - let toml = toml::to_string(&configuration).expect("Could not encode TOML value"); - - assert_eq!(toml, default_config_toml()); +impl AnnouncePolicy { + fn default_interval() -> u32 { + 120 } - #[test] - fn configuration_should_contain_the_external_ip() { - let configuration = Configuration::default(); - - assert_eq!(configuration.external_ip, Some(String::from("0.0.0.0"))); + fn default_interval_min() -> u32 { + 120 } +} - #[test] - fn configuration_should_be_saved_in_a_toml_config_file() { - use std::{env, fs}; - - use uuid::Uuid; - - // Build temp config file path - let temp_directory = env::temp_dir(); - let temp_file = temp_directory.join(format!("test_config_{}.toml", Uuid::new_v4())); - - // Convert to argument type for Configuration::save_to_file - let config_file_path = temp_file; - let path = config_file_path.to_string_lossy().to_string(); - - let default_configuration = Configuration::default(); - - default_configuration - .save_to_file(&path) - .expect("Could not save configuration to file"); - - let contents = fs::read_to_string(&path).expect("Something went wrong reading the file"); - - assert_eq!(contents, default_config_toml()); - } +/// Errors that can occur when loading the configuration. +#[derive(Error, Debug)] +pub enum Error { + /// Unable to load the configuration from the environment variable. + /// This error only occurs if there is no configuration file and the + /// `TORRUST_TRACKER_CONFIG_TOML` environment variable is not set. + #[error("Unable to load from Environmental Variable: {source}")] + UnableToLoadFromEnvironmentVariable { + source: LocatedError<'static, dyn std::error::Error + Send + Sync>, + }, - #[cfg(test)] - fn create_temp_config_file_with_default_config() -> String { - use std::env; - use std::fs::File; - use std::io::Write; + #[error("Unable to load from Config File: {source}")] + UnableToLoadFromConfigFile { + source: LocatedError<'static, dyn std::error::Error + Send + Sync>, + }, - use uuid::Uuid; + /// Unable to load the configuration from the configuration file. + #[error("Failed processing the configuration: {source}")] + ConfigError { + source: LocatedError<'static, dyn std::error::Error + Send + Sync>, + }, - // Build temp config file path - let temp_directory = env::temp_dir(); - let temp_file = temp_directory.join(format!("test_config_{}.toml", Uuid::new_v4())); + #[error("The error for errors that can never happen.")] + Infallible, - // Convert to argument type for Configuration::load_from_file - let config_file_path = temp_file.clone(); - let path = config_file_path.to_string_lossy().to_string(); + #[error("Unsupported configuration version: {version}")] + UnsupportedVersion { version: Version }, - // Write file contents - let mut file = File::create(temp_file).unwrap(); - writeln!(&mut file, "{}", default_config_toml()).unwrap(); + #[error("Missing mandatory configuration option. Option path: {path}")] + MissingMandatoryOption { path: String }, +} - path +impl From for Error { + #[track_caller] + fn from(err: figment::Error) -> Self { + Self::ConfigError { + source: (Arc::new(err) as DynError).into(), + } } +} - #[test] - fn configuration_should_be_loaded_from_a_toml_config_file() { - let config_file_path = create_temp_config_file_with_default_config(); - - let configuration = Configuration::load_from_file(&config_file_path).expect("Could not load configuration from file"); +#[serde_as] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Default)] +pub struct TslConfig { + /// Path to the SSL certificate file. + #[serde(default = "TslConfig::default_ssl_cert_path")] + pub ssl_cert_path: Utf8PathBuf, + + /// Path to the SSL key file. + #[serde(default = "TslConfig::default_ssl_key_path")] + pub ssl_key_path: Utf8PathBuf, +} - assert_eq!(configuration, Configuration::default()); +impl TslConfig { + #[allow(clippy::unnecessary_wraps)] + fn default_ssl_cert_path() -> Utf8PathBuf { + Utf8PathBuf::new() } - #[test] - fn http_api_configuration_should_check_if_it_contains_a_token() { - let configuration = Configuration::default(); - - assert!(configuration.http_api.contains_token("MyAccessToken")); - assert!(!configuration.http_api.contains_token("NonExistingToken")); + #[allow(clippy::unnecessary_wraps)] + fn default_ssl_key_path() -> Utf8PathBuf { + Utf8PathBuf::new() } } diff --git a/packages/configuration/src/logging.rs b/packages/configuration/src/logging.rs new file mode 100644 index 000000000..b8db27b8c --- /dev/null +++ b/packages/configuration/src/logging.rs @@ -0,0 +1,85 @@ +//! Setup for the application logging. +//! +//! It redirects the log info to the standard output with the log threshold +//! defined in the configuration. +//! +//! - `Off` +//! - `Error` +//! - `Warn` +//! - `Info` +//! - `Debug` +//! - `Trace` +//! +//! Refer to the [configuration crate documentation](https://docs.rs/torrust-tracker-configuration) to know how to change log settings. +use std::sync::Once; + +use tracing::level_filters::LevelFilter; + +use crate::{Logging, Threshold}; + +static INIT: Once = Once::new(); + +/// It redirects the log info to the standard output with the log threshold +/// defined in the configuration. +pub fn setup(cfg: &Logging) { + let tracing_level = map_to_tracing_level_filter(&cfg.threshold); + + if tracing_level == LevelFilter::OFF { + return; + } + + INIT.call_once(|| { + tracing_init(tracing_level, &TraceStyle::Default); + }); +} + +fn map_to_tracing_level_filter(threshold: &Threshold) -> LevelFilter { + match threshold { + Threshold::Off => LevelFilter::OFF, + Threshold::Error => LevelFilter::ERROR, + Threshold::Warn => LevelFilter::WARN, + Threshold::Info => LevelFilter::INFO, + Threshold::Debug => LevelFilter::DEBUG, + Threshold::Trace => LevelFilter::TRACE, + } +} + +fn tracing_init(filter: LevelFilter, style: &TraceStyle) { + let builder = tracing_subscriber::fmt() + .with_max_level(filter) + .with_ansi(true) + .with_test_writer(); + + let () = match style { + TraceStyle::Default => builder.init(), + TraceStyle::Pretty(display_filename) => builder.pretty().with_file(*display_filename).init(), + TraceStyle::Compact => builder.compact().init(), + TraceStyle::Json => builder.json().init(), + }; + + tracing::info!("Logging initialized"); +} + +#[derive(Debug)] +pub enum TraceStyle { + Default, + Pretty(bool), + Compact, + Json, +} + +impl std::fmt::Display for TraceStyle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let style = match self { + TraceStyle::Default => "Default Style", + TraceStyle::Pretty(path) => match path { + true => "Pretty Style with File Paths", + false => "Pretty Style without File Paths", + }, + TraceStyle::Compact => "Compact Style", + TraceStyle::Json => "Json Format", + }; + + f.write_str(style) + } +} diff --git a/packages/configuration/src/v2_0_0/core.rs b/packages/configuration/src/v2_0_0/core.rs new file mode 100644 index 000000000..32dac8b3c --- /dev/null +++ b/packages/configuration/src/v2_0_0/core.rs @@ -0,0 +1,145 @@ +use derive_more::{Constructor, Display}; +use serde::{Deserialize, Serialize}; + +use super::network::Network; +use crate::v2_0_0::database::Database; +use crate::validator::{SemanticValidationError, Validator}; +use crate::{AnnouncePolicy, TrackerPolicy}; + +#[allow(clippy::struct_excessive_bools)] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] +pub struct Core { + /// Announce policy configuration. + #[serde(default = "Core::default_announce_policy")] + pub announce_policy: AnnouncePolicy, + + /// Database configuration. + #[serde(default = "Core::default_database")] + pub database: Database, + + /// Interval in seconds that the cleanup job will run to remove inactive + /// peers from the torrent peer list. + #[serde(default = "Core::default_inactive_peer_cleanup_interval")] + pub inactive_peer_cleanup_interval: u64, + + /// When `true` only approved torrents can be announced in the tracker. + #[serde(default = "Core::default_listed")] + pub listed: bool, + + /// Network configuration. + #[serde(default = "Core::default_network")] + pub net: Network, + + /// When `true` clients require a key to connect and use the tracker. + #[serde(default = "Core::default_private")] + pub private: bool, + + /// Configuration specific when the tracker is running in private mode. + #[serde(default = "Core::default_private_mode")] + pub private_mode: Option, + + /// Tracker policy configuration. + #[serde(default = "Core::default_tracker_policy")] + pub tracker_policy: TrackerPolicy, + + /// Weather the tracker should collect statistics about tracker usage. + /// If enabled, the tracker will collect statistics like the number of + /// connections handled, the number of announce requests handled, etc. + /// Refer to the [`Tracker`](https://docs.rs/torrust-tracker) for more + /// information about the collected metrics. + #[serde(default = "Core::default_tracker_usage_statistics")] + pub tracker_usage_statistics: bool, +} + +impl Default for Core { + fn default() -> Self { + Self { + announce_policy: Self::default_announce_policy(), + database: Self::default_database(), + inactive_peer_cleanup_interval: Self::default_inactive_peer_cleanup_interval(), + listed: Self::default_listed(), + net: Self::default_network(), + private: Self::default_private(), + private_mode: Self::default_private_mode(), + tracker_policy: Self::default_tracker_policy(), + tracker_usage_statistics: Self::default_tracker_usage_statistics(), + } + } +} + +impl Core { + fn default_announce_policy() -> AnnouncePolicy { + AnnouncePolicy::default() + } + + fn default_database() -> Database { + Database::default() + } + + fn default_inactive_peer_cleanup_interval() -> u64 { + 600 + } + + fn default_listed() -> bool { + false + } + + fn default_network() -> Network { + Network::default() + } + + fn default_private() -> bool { + false + } + + fn default_private_mode() -> Option { + if Self::default_private() { + Some(PrivateMode::default()) + } else { + None + } + } + + fn default_tracker_policy() -> TrackerPolicy { + TrackerPolicy::default() + } + + fn default_tracker_usage_statistics() -> bool { + true + } +} + +/// Configuration specific when the tracker is running in private mode. +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Copy, Constructor, Display)] +pub struct PrivateMode { + /// A flag to disable expiration date for peer keys. + /// + /// When true, if the keys is not permanent the expiration date will be + /// ignored. The key will be accepted even if it has expired. + #[serde(default = "PrivateMode::default_check_keys_expiration")] + pub check_keys_expiration: bool, +} + +impl Default for PrivateMode { + fn default() -> Self { + Self { + check_keys_expiration: Self::default_check_keys_expiration(), + } + } +} + +impl PrivateMode { + fn default_check_keys_expiration() -> bool { + true + } +} + +impl Validator for Core { + fn validate(&self) -> Result<(), SemanticValidationError> { + if self.private_mode.is_some() && !self.private { + return Err(SemanticValidationError::UselessPrivateModeSection); + } + + Ok(()) + } +} diff --git a/packages/configuration/src/v2_0_0/database.rs b/packages/configuration/src/v2_0_0/database.rs new file mode 100644 index 000000000..c2b24d809 --- /dev/null +++ b/packages/configuration/src/v2_0_0/database.rs @@ -0,0 +1,84 @@ +use serde::{Deserialize, Serialize}; +use url::Url; + +#[allow(clippy::struct_excessive_bools)] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] +pub struct Database { + // Database configuration + /// Database driver. Possible values are: `sqlite3`, and `mysql`. + #[serde(default = "Database::default_driver")] + pub driver: Driver, + + /// Database connection string. The format depends on the database driver. + /// For `sqlite3`, the format is `path/to/database.db`, for example: + /// `./storage/tracker/lib/database/sqlite3.db`. + /// For `Mysql`, the format is `mysql://db_user:db_user_password:port/db_name`, for + /// example: `mysql://root:password@localhost:3306/torrust`. + #[serde(default = "Database::default_path")] + pub path: String, +} + +impl Default for Database { + fn default() -> Self { + Self { + driver: Self::default_driver(), + path: Self::default_path(), + } + } +} + +impl Database { + fn default_driver() -> Driver { + Driver::Sqlite3 + } + + fn default_path() -> String { + String::from("./storage/tracker/lib/database/sqlite3.db") + } + + /// Masks secrets in the configuration. + /// + /// # Panics + /// + /// Will panic if the database path for `MySQL` is not a valid URL. + pub fn mask_secrets(&mut self) { + match self.driver { + Driver::Sqlite3 => { + // Nothing to mask + } + Driver::MySQL => { + let mut url = Url::parse(&self.path).expect("path for MySQL driver should be a valid URL"); + url.set_password(Some("***")).expect("url password should be changed"); + self.path = url.to_string(); + } + } + } +} + +/// The database management system used by the tracker. +#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Clone)] +#[serde(rename_all = "lowercase")] +pub enum Driver { + /// The `Sqlite3` database driver. + Sqlite3, + /// The `MySQL` database driver. + MySQL, +} + +#[cfg(test)] +mod tests { + + use super::{Database, Driver}; + + #[test] + fn it_should_allow_masking_the_mysql_user_password() { + let mut database = Database { + driver: Driver::MySQL, + path: "mysql://root:password@localhost:3306/torrust".to_string(), + }; + + database.mask_secrets(); + + assert_eq!(database.path, "mysql://root:***@localhost:3306/torrust".to_string()); + } +} diff --git a/packages/configuration/src/v2_0_0/health_check_api.rs b/packages/configuration/src/v2_0_0/health_check_api.rs new file mode 100644 index 000000000..368f26c42 --- /dev/null +++ b/packages/configuration/src/v2_0_0/health_check_api.rs @@ -0,0 +1,30 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + +use serde::{Deserialize, Serialize}; +use serde_with::serde_as; + +/// Configuration for the Health Check API. +#[serde_as] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] +pub struct HealthCheckApi { + /// The address the API will bind to. + /// The format is `ip:port`, for example `127.0.0.1:1313`. If you want to + /// listen to all interfaces, use `0.0.0.0`. If you want the operating + /// system to choose a random port, use port `0`. + #[serde(default = "HealthCheckApi::default_bind_address")] + pub bind_address: SocketAddr, +} + +impl Default for HealthCheckApi { + fn default() -> Self { + Self { + bind_address: Self::default_bind_address(), + } + } +} + +impl HealthCheckApi { + fn default_bind_address() -> SocketAddr { + SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1313) + } +} diff --git a/packages/configuration/src/v2_0_0/http_tracker.rs b/packages/configuration/src/v2_0_0/http_tracker.rs new file mode 100644 index 000000000..ae00257d8 --- /dev/null +++ b/packages/configuration/src/v2_0_0/http_tracker.rs @@ -0,0 +1,50 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + +use serde::{Deserialize, Serialize}; +use serde_with::serde_as; + +use crate::TslConfig; + +/// Configuration for each HTTP tracker. +#[serde_as] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] +pub struct HttpTracker { + /// The address the tracker will bind to. + /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to + /// listen to all interfaces, use `0.0.0.0`. If you want the operating + /// system to choose a random port, use port `0`. + #[serde(default = "HttpTracker::default_bind_address")] + pub bind_address: SocketAddr, + + /// TSL config. + #[serde(default = "HttpTracker::default_tsl_config")] + pub tsl_config: Option, + + /// Weather the tracker should collect statistics about tracker usage. + #[serde(default = "HttpTracker::default_tracker_usage_statistics")] + pub tracker_usage_statistics: bool, +} + +impl Default for HttpTracker { + fn default() -> Self { + Self { + bind_address: Self::default_bind_address(), + tsl_config: Self::default_tsl_config(), + tracker_usage_statistics: Self::default_tracker_usage_statistics(), + } + } +} + +impl HttpTracker { + fn default_bind_address() -> SocketAddr { + SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 7070) + } + + fn default_tsl_config() -> Option { + None + } + + fn default_tracker_usage_statistics() -> bool { + false + } +} diff --git a/packages/configuration/src/v2_0_0/logging.rs b/packages/configuration/src/v2_0_0/logging.rs new file mode 100644 index 000000000..e7dbe146c --- /dev/null +++ b/packages/configuration/src/v2_0_0/logging.rs @@ -0,0 +1,41 @@ +use serde::{Deserialize, Serialize}; + +#[allow(clippy::struct_excessive_bools)] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] +pub struct Logging { + /// Logging level. Possible values are: `Off`, `Error`, `Warn`, `Info`, + /// `Debug` and `Trace`. Default is `Info`. + #[serde(default = "Logging::default_threshold")] + pub threshold: Threshold, +} + +impl Default for Logging { + fn default() -> Self { + Self { + threshold: Self::default_threshold(), + } + } +} + +impl Logging { + fn default_threshold() -> Threshold { + Threshold::Info + } +} + +#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Clone)] +#[serde(rename_all = "lowercase")] +pub enum Threshold { + /// A threshold lower than all security levels. + Off, + /// Corresponds to the `Error` security level. + Error, + /// Corresponds to the `Warn` security level. + Warn, + /// Corresponds to the `Info` security level. + Info, + /// Corresponds to the `Debug` security level. + Debug, + /// Corresponds to the `Trace` security level. + Trace, +} diff --git a/packages/configuration/src/v2_0_0/mod.rs b/packages/configuration/src/v2_0_0/mod.rs new file mode 100644 index 000000000..b3fbc881e --- /dev/null +++ b/packages/configuration/src/v2_0_0/mod.rs @@ -0,0 +1,674 @@ +//! Version `1` for [Torrust Tracker](https://docs.rs/torrust-tracker) +//! configuration data structures. +//! +//! This module contains the configuration data structures for the +//! Torrust Tracker, which is a `BitTorrent` tracker server. +//! +//! The configuration is loaded from a [TOML](https://toml.io/en/) file +//! `tracker.toml` in the project root folder or from an environment variable +//! with the same content as the file. +//! +//! Configuration can not only be loaded from a file, but also from an +//! environment variable `TORRUST_TRACKER_CONFIG_TOML`. This is useful when running +//! the tracker in a Docker container or environments where you do not have a +//! persistent storage or you cannot inject a configuration file. Refer to +//! [`Torrust Tracker documentation`](https://docs.rs/torrust-tracker) for more +//! information about how to pass configuration to the tracker. +//! +//! When you run the tracker without providing the configuration via a file or +//! env var, the default configuration is used. +//! +//! # Table of contents +//! +//! - [Sections](#sections) +//! - [Port binding](#port-binding) +//! - [TSL support](#tsl-support) +//! - [Generating self-signed certificates](#generating-self-signed-certificates) +//! - [Default configuration](#default-configuration) +//! +//! ## Sections +//! +//! Each section in the toml structure is mapped to a data structure. For +//! example, the `[http_api]` section (configuration for the tracker HTTP API) +//! is mapped to the [`HttpApi`] structure. +//! +//! > **NOTICE**: some sections are arrays of structures. For example, the +//! > `[[udp_trackers]]` section is an array of [`UdpTracker`] since +//! > you can have multiple running UDP trackers bound to different ports. +//! +//! Please refer to the documentation of each structure for more information +//! about each section. +//! +//! - [`Core configuration`](crate::v2_0_0::Configuration) +//! - [`HTTP API configuration`](crate::v2_0_0::tracker_api::HttpApi) +//! - [`HTTP Tracker configuration`](crate::v2_0_0::http_tracker::HttpTracker) +//! - [`UDP Tracker configuration`](crate::v2_0_0::udp_tracker::UdpTracker) +//! - [`Health Check API configuration`](crate::v2_0_0::health_check_api::HealthCheckApi) +//! +//! ## Port binding +//! +//! For the API, HTTP and UDP trackers you can bind to a random port by using +//! port `0`. For example, if you want to bind to a random port on all +//! interfaces, use `0.0.0.0:0`. The OS will choose a random free port. +//! +//! ## TSL support +//! +//! For the API and HTTP tracker you can enable TSL by setting `ssl_enabled` to +//! `true` and setting the paths to the certificate and key files. +//! +//! Typically, you will have a `storage` directory like the following: +//! +//! ```text +//! storage/ +//! ├── config.toml +//! └── tracker +//! ├── etc +//! │ └── tracker.toml +//! ├── lib +//! │ ├── database +//! │ │ ├── sqlite3.db +//! │ │ └── sqlite.db +//! │ └── tls +//! │ ├── localhost.crt +//! │ └── localhost.key +//! └── log +//! ``` +//! +//! where the application stores all the persistent data. +//! +//! Alternatively, you could setup a reverse proxy like Nginx or Apache to +//! handle the SSL/TLS part and forward the requests to the tracker. If you do +//! that, you should set [`on_reverse_proxy`](crate::v2_0_0::network::Network::on_reverse_proxy) +//! to `true` in the configuration file. It's out of scope for this +//! documentation to explain in detail how to setup a reverse proxy, but the +//! configuration file should be something like this: +//! +//! For [NGINX](https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/): +//! +//! ```text +//! # HTTPS only (with SSL - force redirect to HTTPS) +//! +//! server { +//! listen 80; +//! server_name tracker.torrust.com; +//! +//! return 301 https://$host$request_uri; +//! } +//! +//! server { +//! listen 443; +//! server_name tracker.torrust.com; +//! +//! ssl_certificate CERT_PATH +//! ssl_certificate_key CERT_KEY_PATH; +//! +//! location / { +//! proxy_set_header X-Forwarded-For $remote_addr; +//! proxy_pass http://127.0.0.1:6969; +//! } +//! } +//! ``` +//! +//! For [Apache](https://httpd.apache.org/docs/2.4/howto/reverse_proxy.html): +//! +//! ```text +//! # HTTPS only (with SSL - force redirect to HTTPS) +//! +//! +//! ServerAdmin webmaster@tracker.torrust.com +//! ServerName tracker.torrust.com +//! +//! +//! RewriteEngine on +//! RewriteCond %{HTTPS} off +//! RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] +//! +//! +//! +//! +//! +//! ServerAdmin webmaster@tracker.torrust.com +//! ServerName tracker.torrust.com +//! +//! +//! Order allow,deny +//! Allow from all +//! +//! +//! ProxyPreserveHost On +//! ProxyRequests Off +//! AllowEncodedSlashes NoDecode +//! +//! ProxyPass / http://localhost:3000/ +//! ProxyPassReverse / http://localhost:3000/ +//! ProxyPassReverse / http://tracker.torrust.com/ +//! +//! RequestHeader set X-Forwarded-Proto "https" +//! RequestHeader set X-Forwarded-Port "443" +//! +//! ErrorLog ${APACHE_LOG_DIR}/tracker.torrust.com-error.log +//! CustomLog ${APACHE_LOG_DIR}/tracker.torrust.com-access.log combined +//! +//! SSLCertificateFile CERT_PATH +//! SSLCertificateKeyFile CERT_KEY_PATH +//! +//! +//! ``` +//! +//! ## Generating self-signed certificates +//! +//! For testing purposes, you can use self-signed certificates. +//! +//! Refer to [Let's Encrypt - Certificates for localhost](https://letsencrypt.org/docs/certificates-for-localhost/) +//! for more information. +//! +//! Running the following command will generate a certificate (`localhost.crt`) +//! and key (`localhost.key`) file in your current directory: +//! +//! ```s +//! openssl req -x509 -out localhost.crt -keyout localhost.key \ +//! -newkey rsa:2048 -nodes -sha256 \ +//! -subj '/CN=localhost' -extensions EXT -config <( \ +//! printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth") +//! ``` +//! +//! You can then use the generated files in the configuration file: +//! +//! ```s +//! [[http_trackers]] +//! ... +//! +//! [http_trackers.tsl_config] +//! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" +//! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" +//! +//! [http_api] +//! ... +//! +//! [http_api.tsl_config] +//! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" +//! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" +//! ``` +//! +//! ## Default configuration +//! +//! The default configuration is: +//! +//! ```toml +//! [logging] +//! threshold = "info" +//! +//! [core] +//! inactive_peer_cleanup_interval = 600 +//! listed = false +//! private = false +//! tracker_usage_statistics = true +//! +//! [core.announce_policy] +//! interval = 120 +//! interval_min = 120 +//! +//! [core.database] +//! driver = "sqlite3" +//! path = "./storage/tracker/lib/database/sqlite3.db" +//! +//! [core.net] +//! external_ip = "0.0.0.0" +//! on_reverse_proxy = false +//! +//! [core.tracker_policy] +//! max_peer_timeout = 900 +//! persistent_torrent_completed_stat = false +//! remove_peerless_torrents = true +//! +//! [http_api] +//! bind_address = "127.0.0.1:1212" +//! +//! [http_api.access_tokens] +//! admin = "MyAccessToken" +//! [health_check_api] +//! bind_address = "127.0.0.1:1313" +//!``` +pub mod core; +pub mod database; +pub mod health_check_api; +pub mod http_tracker; +pub mod logging; +pub mod network; +pub mod tracker_api; +pub mod udp_tracker; + +use std::fs; +use std::net::IpAddr; + +use figment::providers::{Env, Format, Serialized, Toml}; +use figment::Figment; +use logging::Logging; +use serde::{Deserialize, Serialize}; + +use self::core::Core; +use self::health_check_api::HealthCheckApi; +use self::http_tracker::HttpTracker; +use self::tracker_api::HttpApi; +use self::udp_tracker::UdpTracker; +use crate::validator::{SemanticValidationError, Validator}; +use crate::{Error, Info, Metadata, Version}; + +/// This configuration version +const VERSION_2_0_0: &str = "2.0.0"; + +/// Prefix for env vars that overwrite configuration options. +const CONFIG_OVERRIDE_PREFIX: &str = "TORRUST_TRACKER_CONFIG_OVERRIDE_"; + +/// Path separator in env var names for nested values in configuration. +const CONFIG_OVERRIDE_SEPARATOR: &str = "__"; + +/// Core configuration for the tracker. +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Default, Clone)] +pub struct Configuration { + /// Configuration metadata. + pub metadata: Metadata, + + /// Logging configuration + pub logging: Logging, + + /// Core configuration. + pub core: Core, + + /// The list of UDP trackers the tracker is running. Each UDP tracker + /// represents a UDP server that the tracker is running and it has its own + /// configuration. + pub udp_trackers: Option>, + + /// The list of HTTP trackers the tracker is running. Each HTTP tracker + /// represents a HTTP server that the tracker is running and it has its own + /// configuration. + pub http_trackers: Option>, + + /// The HTTP API configuration. + pub http_api: Option, + + /// The Health Check API configuration. + pub health_check_api: HealthCheckApi, +} + +impl Configuration { + /// Returns the tracker public IP address id defined in the configuration, + /// and `None` otherwise. + #[must_use] + pub fn get_ext_ip(&self) -> Option { + self.core.net.external_ip.as_ref().map(|external_ip| *external_ip) + } + + /// Saves the default configuration at the given path. + /// + /// # Errors + /// + /// Will return `Err` if `path` is not a valid path or the configuration + /// file cannot be created. + pub fn create_default_configuration_file(path: &str) -> Result { + let config = Configuration::default(); + config.save_to_file(path)?; + Ok(config) + } + + /// Loads the configuration from the `Info` struct. The whole + /// configuration in toml format is included in the `info.tracker_toml` + /// string. + /// + /// Configuration provided via env var has priority over config file path. + /// + /// # Errors + /// + /// Will return `Err` if the environment variable does not exist or has a bad configuration. + pub fn load(info: &Info) -> Result { + // Load configuration provided by the user, prioritizing env vars + let figment = if let Some(config_toml) = &info.config_toml { + Figment::from(Toml::string(config_toml)).merge(Env::prefixed(CONFIG_OVERRIDE_PREFIX).split(CONFIG_OVERRIDE_SEPARATOR)) + } else { + Figment::from(Toml::file(&info.config_toml_path)) + .merge(Env::prefixed(CONFIG_OVERRIDE_PREFIX).split(CONFIG_OVERRIDE_SEPARATOR)) + }; + + // Make sure user has provided the mandatory options. + Self::check_mandatory_options(&figment)?; + + // Fill missing options with default values. + let figment = figment.join(Serialized::defaults(Configuration::default())); + + // Build final configuration. + let config: Configuration = figment.extract()?; + + // Make sure the provided schema version matches this version. + if config.metadata.schema_version != Version::new(VERSION_2_0_0) { + return Err(Error::UnsupportedVersion { + version: config.metadata.schema_version, + }); + } + + Ok(config) + } + + /// Some configuration options are mandatory. The tracker will panic if + /// the user doesn't provide an explicit value for them from one of the + /// configuration sources: TOML or ENV VARS. + /// + /// # Errors + /// + /// Will return an error if a mandatory configuration option is only + /// obtained by default value (code), meaning the user hasn't overridden it. + fn check_mandatory_options(figment: &Figment) -> Result<(), Error> { + let mandatory_options = ["metadata.schema_version", "logging.threshold", "core.private", "core.listed"]; + + for mandatory_option in mandatory_options { + figment + .find_value(mandatory_option) + .map_err(|_err| Error::MissingMandatoryOption { + path: mandatory_option.to_owned(), + })?; + } + + Ok(()) + } + + /// Saves the configuration to the configuration file. + /// + /// # Errors + /// + /// Will return `Err` if `filename` does not exist or the user does not have + /// permission to read it. Will also return `Err` if the configuration is + /// not valid or cannot be encoded to TOML. + /// + /// # Panics + /// + /// Will panic if the configuration cannot be written into the file. + pub fn save_to_file(&self, path: &str) -> Result<(), Error> { + fs::write(path, self.to_toml()).expect("Could not write to file!"); + Ok(()) + } + + /// Encodes the configuration to TOML. + /// + /// # Panics + /// + /// Will panic if it can't be converted to TOML. + #[must_use] + fn to_toml(&self) -> String { + // code-review: do we need to use Figment also to serialize into toml? + toml::to_string(self).expect("Could not encode TOML value") + } + + /// Encodes the configuration to JSON. + /// + /// # Panics + /// + /// Will panic if it can't be converted to JSON. + #[must_use] + pub fn to_json(&self) -> String { + // code-review: do we need to use Figment also to serialize into json? + serde_json::to_string_pretty(self).expect("Could not encode JSON value") + } + + /// Masks secrets in the configuration. + #[must_use] + pub fn mask_secrets(mut self) -> Self { + self.core.database.mask_secrets(); + + if let Some(ref mut api) = self.http_api { + api.mask_secrets(); + } + + self + } +} + +impl Validator for Configuration { + fn validate(&self) -> Result<(), SemanticValidationError> { + self.core.validate() + } +} + +#[cfg(test)] +mod tests { + + use std::net::{IpAddr, Ipv4Addr}; + + use crate::v2_0_0::Configuration; + use crate::Info; + + #[cfg(test)] + fn default_config_toml() -> String { + let config = r#"[metadata] + app = "torrust-tracker" + purpose = "configuration" + schema_version = "2.0.0" + + [logging] + threshold = "info" + + [core] + inactive_peer_cleanup_interval = 600 + listed = false + private = false + tracker_usage_statistics = true + + [core.announce_policy] + interval = 120 + interval_min = 120 + + [core.database] + driver = "sqlite3" + path = "./storage/tracker/lib/database/sqlite3.db" + + [core.net] + external_ip = "0.0.0.0" + on_reverse_proxy = false + + [core.tracker_policy] + max_peer_timeout = 900 + persistent_torrent_completed_stat = false + remove_peerless_torrents = true + + [health_check_api] + bind_address = "127.0.0.1:1313" + "# + .lines() + .map(str::trim_start) + .collect::>() + .join("\n"); + config + } + + #[test] + fn configuration_should_have_default_values() { + let configuration = Configuration::default(); + + let toml = toml::to_string(&configuration).expect("Could not encode TOML value"); + + assert_eq!(toml, default_config_toml()); + } + + #[test] + fn configuration_should_contain_the_external_ip() { + let configuration = Configuration::default(); + + assert_eq!(configuration.core.net.external_ip, Some(IpAddr::V4(Ipv4Addr::UNSPECIFIED))); + } + + #[test] + fn configuration_should_be_saved_in_a_toml_config_file() { + use std::{env, fs}; + + use uuid::Uuid; + + // Build temp config file path + let temp_directory = env::temp_dir(); + let temp_file = temp_directory.join(format!("test_config_{}.toml", Uuid::new_v4())); + + // Convert to argument type for Configuration::save_to_file + let config_file_path = temp_file; + let path = config_file_path.to_string_lossy().to_string(); + + let default_configuration = Configuration::default(); + + default_configuration + .save_to_file(&path) + .expect("Could not save configuration to file"); + + let contents = fs::read_to_string(&path).expect("Something went wrong reading the file"); + + assert_eq!(contents, default_config_toml()); + } + + #[test] + #[allow(clippy::result_large_err)] + fn configuration_should_use_the_default_values_when_only_the_mandatory_options_are_provided_by_the_user_via_toml_file() { + figment::Jail::expect_with(|jail| { + jail.create_file( + "tracker.toml", + r#" + [metadata] + schema_version = "2.0.0" + + [logging] + threshold = "info" + + [core] + listed = false + private = false + "#, + )?; + + let info = Info { + config_toml: None, + config_toml_path: "tracker.toml".to_string(), + }; + + let configuration = Configuration::load(&info).expect("Could not load configuration from file"); + + assert_eq!(configuration, Configuration::default()); + + Ok(()) + }); + } + + #[test] + #[allow(clippy::result_large_err)] + fn configuration_should_use_the_default_values_when_only_the_mandatory_options_are_provided_by_the_user_via_toml_content() { + figment::Jail::expect_with(|_jail| { + let config_toml = r#" + [metadata] + schema_version = "2.0.0" + + [logging] + threshold = "info" + + [core] + listed = false + private = false + "# + .to_string(); + + let info = Info { + config_toml: Some(config_toml), + config_toml_path: String::new(), + }; + + let configuration = Configuration::load(&info).expect("Could not load configuration from file"); + + assert_eq!(configuration, Configuration::default()); + + Ok(()) + }); + } + + #[test] + #[allow(clippy::result_large_err)] + fn default_configuration_could_be_overwritten_from_a_single_env_var_with_toml_contents() { + figment::Jail::expect_with(|_jail| { + let config_toml = r#" + [metadata] + schema_version = "2.0.0" + + [logging] + threshold = "info" + + [core] + listed = false + private = false + + [core.database] + path = "OVERWRITTEN DEFAULT DB PATH" + "# + .to_string(); + + let info = Info { + config_toml: Some(config_toml), + config_toml_path: String::new(), + }; + + let configuration = Configuration::load(&info).expect("Could not load configuration from file"); + + assert_eq!(configuration.core.database.path, "OVERWRITTEN DEFAULT DB PATH".to_string()); + + Ok(()) + }); + } + + #[test] + #[allow(clippy::result_large_err)] + fn default_configuration_could_be_overwritten_from_a_toml_config_file() { + figment::Jail::expect_with(|jail| { + jail.create_file( + "tracker.toml", + r#" + [metadata] + schema_version = "2.0.0" + + [logging] + threshold = "info" + + [core] + listed = false + private = false + + [core.database] + path = "OVERWRITTEN DEFAULT DB PATH" + "#, + )?; + + let info = Info { + config_toml: None, + config_toml_path: "tracker.toml".to_string(), + }; + + let configuration = Configuration::load(&info).expect("Could not load configuration from file"); + + assert_eq!(configuration.core.database.path, "OVERWRITTEN DEFAULT DB PATH".to_string()); + + Ok(()) + }); + } + + #[allow(clippy::result_large_err)] + #[test] + fn configuration_should_allow_to_overwrite_the_default_tracker_api_token_for_admin_with_an_env_var() { + figment::Jail::expect_with(|jail| { + jail.set_env("TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN", "NewToken"); + + let info = Info { + config_toml: Some(default_config_toml()), + config_toml_path: String::new(), + }; + + let configuration = Configuration::load(&info).expect("Could not load configuration from file"); + + assert_eq!( + configuration.http_api.unwrap().access_tokens.get("admin"), + Some("NewToken".to_owned()).as_ref() + ); + + Ok(()) + }); + } +} diff --git a/packages/configuration/src/v2_0_0/network.rs b/packages/configuration/src/v2_0_0/network.rs new file mode 100644 index 000000000..7a4668727 --- /dev/null +++ b/packages/configuration/src/v2_0_0/network.rs @@ -0,0 +1,41 @@ +use std::net::{IpAddr, Ipv4Addr}; + +use serde::{Deserialize, Serialize}; + +#[allow(clippy::struct_excessive_bools)] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] +pub struct Network { + /// The external IP address of the tracker. If the client is using a + /// loopback IP address, this IP address will be used instead. If the peer + /// is using a loopback IP address, the tracker assumes that the peer is + /// in the same network as the tracker and will use the tracker's IP + /// address instead. + #[serde(default = "Network::default_external_ip")] + pub external_ip: Option, + + /// Weather the tracker is behind a reverse proxy or not. + /// If the tracker is behind a reverse proxy, the `X-Forwarded-For` header + /// sent from the proxy will be used to get the client's IP address. + #[serde(default = "Network::default_on_reverse_proxy")] + pub on_reverse_proxy: bool, +} + +impl Default for Network { + fn default() -> Self { + Self { + external_ip: Self::default_external_ip(), + on_reverse_proxy: Self::default_on_reverse_proxy(), + } + } +} + +impl Network { + #[allow(clippy::unnecessary_wraps)] + fn default_external_ip() -> Option { + Some(IpAddr::V4(Ipv4Addr::UNSPECIFIED)) + } + + fn default_on_reverse_proxy() -> bool { + false + } +} diff --git a/packages/configuration/src/v2_0_0/tracker_api.rs b/packages/configuration/src/v2_0_0/tracker_api.rs new file mode 100644 index 000000000..9433c8c8c --- /dev/null +++ b/packages/configuration/src/v2_0_0/tracker_api.rs @@ -0,0 +1,88 @@ +use std::collections::HashMap; +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + +use serde::{Deserialize, Serialize}; +use serde_with::serde_as; + +use crate::TslConfig; + +pub type AccessTokens = HashMap; + +/// Configuration for the HTTP API. +#[serde_as] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] +pub struct HttpApi { + /// The address the tracker will bind to. + /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to + /// listen to all interfaces, use `0.0.0.0`. If you want the operating + /// system to choose a random port, use port `0`. + #[serde(default = "HttpApi::default_bind_address")] + pub bind_address: SocketAddr, + + /// TSL config. Only used if `ssl_enabled` is true. + #[serde(default = "HttpApi::default_tsl_config")] + pub tsl_config: Option, + + /// Access tokens for the HTTP API. The key is a label identifying the + /// token and the value is the token itself. The token is used to + /// authenticate the user. All tokens are valid for all endpoints and have + /// all permissions. + #[serde(default = "HttpApi::default_access_tokens")] + pub access_tokens: AccessTokens, +} + +impl Default for HttpApi { + fn default() -> Self { + Self { + bind_address: Self::default_bind_address(), + tsl_config: Self::default_tsl_config(), + access_tokens: Self::default_access_tokens(), + } + } +} + +impl HttpApi { + fn default_bind_address() -> SocketAddr { + SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1212) + } + + #[allow(clippy::unnecessary_wraps)] + fn default_tsl_config() -> Option { + None + } + + fn default_access_tokens() -> AccessTokens { + [].iter().cloned().collect() + } + + pub fn add_token(&mut self, key: &str, token: &str) { + self.access_tokens.insert(key.to_string(), token.to_string()); + } + + pub fn mask_secrets(&mut self) { + for token in self.access_tokens.values_mut() { + *token = "***".to_string(); + } + } +} + +#[cfg(test)] +mod tests { + use crate::v2_0_0::tracker_api::HttpApi; + + #[test] + fn default_http_api_configuration_should_not_contains_any_token() { + let configuration = HttpApi::default(); + + assert_eq!(configuration.access_tokens.values().len(), 0); + } + + #[test] + fn http_api_configuration_should_allow_adding_tokens() { + let mut configuration = HttpApi::default(); + + configuration.add_token("admin", "MyAccessToken"); + + assert!(configuration.access_tokens.values().any(|t| t == "MyAccessToken")); + } +} diff --git a/packages/configuration/src/v2_0_0/udp_tracker.rs b/packages/configuration/src/v2_0_0/udp_tracker.rs new file mode 100644 index 000000000..133018e86 --- /dev/null +++ b/packages/configuration/src/v2_0_0/udp_tracker.rs @@ -0,0 +1,46 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] +pub struct UdpTracker { + /// The address the tracker will bind to. + /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to + /// listen to all interfaces, use `0.0.0.0`. If you want the operating + /// system to choose a random port, use port `0`. + #[serde(default = "UdpTracker::default_bind_address")] + pub bind_address: SocketAddr, + + /// The lifetime of the server-generated connection cookie, that is passed + /// the client as the `ConnectionId`. + #[serde(default = "UdpTracker::default_cookie_lifetime")] + pub cookie_lifetime: Duration, + + /// Weather the tracker should collect statistics about tracker usage. + #[serde(default = "UdpTracker::default_tracker_usage_statistics")] + pub tracker_usage_statistics: bool, +} +impl Default for UdpTracker { + fn default() -> Self { + Self { + bind_address: Self::default_bind_address(), + cookie_lifetime: Self::default_cookie_lifetime(), + tracker_usage_statistics: Self::default_tracker_usage_statistics(), + } + } +} + +impl UdpTracker { + fn default_bind_address() -> SocketAddr { + SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 6969) + } + + fn default_cookie_lifetime() -> Duration { + Duration::from_secs(120) + } + + fn default_tracker_usage_statistics() -> bool { + false + } +} diff --git a/packages/configuration/src/validator.rs b/packages/configuration/src/validator.rs new file mode 100644 index 000000000..4555b88dd --- /dev/null +++ b/packages/configuration/src/validator.rs @@ -0,0 +1,19 @@ +//! Trait to validate semantic errors. +//! +//! Errors could involve more than one configuration option. Some configuration +//! combinations can be incompatible. +use thiserror::Error; + +/// Errors that can occur validating the configuration. +#[derive(Error, Debug)] +pub enum SemanticValidationError { + #[error("Private mode section in configuration can only be included when the tracker is running in private mode.")] + UselessPrivateModeSection, +} + +pub trait Validator { + /// # Errors + /// + /// Will return an error if the configuration is invalid. + fn validate(&self) -> Result<(), SemanticValidationError>; +} diff --git a/packages/events/.gitignore b/packages/events/.gitignore new file mode 100644 index 000000000..0b1372e5c --- /dev/null +++ b/packages/events/.gitignore @@ -0,0 +1 @@ +./.coverage diff --git a/packages/events/Cargo.toml b/packages/events/Cargo.toml new file mode 100644 index 000000000..165ecca68 --- /dev/null +++ b/packages/events/Cargo.toml @@ -0,0 +1,22 @@ +[package] +description = "A library with functionality to handle events in Torrust tracker packages." +keywords = [ "events", "library", "rust", "torrust", "tracker" ] +name = "torrust-tracker-events" +readme = "README.md" + +authors.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +futures = "0" +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync", "time" ] } + +[dev-dependencies] +mockall = "0" diff --git a/packages/events/LICENSE b/packages/events/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/events/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/events/README.md b/packages/events/README.md new file mode 100644 index 000000000..42a5a2f61 --- /dev/null +++ b/packages/events/README.md @@ -0,0 +1,11 @@ +# Torrust Tracker Events + +A library with functionality to handle events in [Torrust Tracker](https://github.com/torrust/torrust-tracker) packages. + +## Documentation + +[Crate documentation](https://docs.rs/torrust-tracker-events). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/events/src/broadcaster.rs b/packages/events/src/broadcaster.rs new file mode 100644 index 000000000..79c83df8a --- /dev/null +++ b/packages/events/src/broadcaster.rs @@ -0,0 +1,117 @@ +use futures::future::BoxFuture; +use futures::FutureExt; +use tokio::sync::broadcast::{self}; + +use crate::receiver::{Receiver, RecvError}; +use crate::sender::{SendError, Sender}; + +const CHANNEL_CAPACITY: usize = 65536; + +/// An event sender and receiver implementation using a broadcast channel. +#[derive(Clone, Debug)] +pub struct Broadcaster { + pub(crate) sender: broadcast::Sender, +} + +impl Default for Broadcaster { + fn default() -> Self { + let (sender, _receiver) = broadcast::channel(CHANNEL_CAPACITY); + Self { sender } + } +} + +impl Broadcaster { + #[must_use] + pub fn subscribe(&self) -> broadcast::Receiver { + self.sender.subscribe() + } +} + +impl Sender for Broadcaster { + type Event = Event; + + fn send(&self, event: Event) -> BoxFuture<'_, Option>>> { + async move { Some(self.sender.send(event).map_err(std::convert::Into::into)) }.boxed() + } +} + +impl Receiver for broadcast::Receiver { + type Event = Event; + + fn recv(&mut self) -> BoxFuture<'_, Result> { + async move { self.recv().await.map_err(std::convert::Into::into) }.boxed() + } +} + +impl From> for SendError { + fn from(err: broadcast::error::SendError) -> Self { + SendError(err.0) + } +} + +impl From for RecvError { + fn from(err: broadcast::error::RecvError) -> Self { + match err { + broadcast::error::RecvError::Lagged(amt) => RecvError::Lagged(amt), + broadcast::error::RecvError::Closed => RecvError::Closed, + } + } +} + +#[cfg(test)] +mod tests { + use tokio::time::{timeout, Duration}; + + use super::*; + + #[tokio::test] + async fn it_should_allow_sending_an_event_and_received_it() { + let broadcaster = Broadcaster::::default(); + + let mut receiver = broadcaster.subscribe(); + + let event = "test"; + + let _unused = broadcaster.send(event.to_owned()).await.unwrap().unwrap(); + + let received_event = receiver.recv().await.unwrap(); + + assert_eq!(received_event, event); + } + + #[tokio::test] + async fn it_should_return_the_number_of_receivers_when_and_event_is_sent() { + let broadcaster = Broadcaster::::default(); + let mut _receiver = broadcaster.subscribe(); + + let number_of_receivers = broadcaster.send("test".into()).await; + + assert!(matches!(number_of_receivers, Some(Ok(1)))); + } + + #[tokio::test] + async fn it_should_fail_when_trying_tos_send_with_no_subscribers() { + let event = String::from("test"); + + let broadcaster = Broadcaster::::default(); + + let result: Result> = broadcaster.send(event).await.unwrap(); + + assert!(matches!(result, Err(SendError::(_event)))); + } + + #[tokio::test] + async fn it_should_allow_subscribing_multiple_receivers() { + let broadcaster = Broadcaster::::default(); + let mut r1 = broadcaster.subscribe(); + let mut r2 = broadcaster.subscribe(); + + let _ = broadcaster.send(1).await; + + let val1 = timeout(Duration::from_secs(1), r1.recv()).await.unwrap().unwrap(); + let val2 = timeout(Duration::from_secs(1), r2.recv()).await.unwrap().unwrap(); + + assert_eq!(val1, 1); + assert_eq!(val2, 1); + } +} diff --git a/packages/events/src/bus.rs b/packages/events/src/bus.rs new file mode 100644 index 000000000..b42fb4fc5 --- /dev/null +++ b/packages/events/src/bus.rs @@ -0,0 +1,125 @@ +use std::sync::Arc; + +use crate::broadcaster::Broadcaster; +use crate::{receiver, sender}; + +#[derive(Clone, Debug)] +pub enum SenderStatus { + Enabled, + Disabled, +} + +impl From for SenderStatus { + fn from(enabled: bool) -> Self { + if enabled { + Self::Enabled + } else { + Self::Disabled + } + } +} + +impl From for bool { + fn from(sender_status: SenderStatus) -> Self { + match sender_status { + SenderStatus::Enabled => true, + SenderStatus::Disabled => false, + } + } +} + +#[derive(Clone, Debug)] +pub struct EventBus { + pub sender_status: SenderStatus, + pub broadcaster: Broadcaster, +} + +impl Default for EventBus { + fn default() -> Self { + let sender_status = SenderStatus::Enabled; + let broadcaster = Broadcaster::::default(); + + Self::new(sender_status, broadcaster) + } +} + +impl EventBus { + #[must_use] + pub fn new(sender_status: SenderStatus, broadcaster: Broadcaster) -> Self { + Self { + sender_status, + broadcaster, + } + } + + #[must_use] + pub fn sender(&self) -> Option>> { + match self.sender_status { + SenderStatus::Enabled => Some(Arc::new(self.broadcaster.clone())), + SenderStatus::Disabled => None, + } + } + + #[must_use] + pub fn receiver(&self) -> Box> { + Box::new(self.broadcaster.subscribe()) + } +} + +#[cfg(test)] +mod tests { + use tokio::time::{timeout, Duration}; + + use super::*; + + #[tokio::test] + async fn it_should_provide_an_event_sender_when_enabled() { + let bus = EventBus::::new(SenderStatus::Enabled, Broadcaster::default()); + + assert!(bus.sender().is_some()); + } + + #[tokio::test] + async fn it_should_not_provide_event_sender_when_disabled() { + let bus = EventBus::::new(SenderStatus::Disabled, Broadcaster::default()); + + assert!(bus.sender().is_none()); + } + + #[tokio::test] + async fn it_should_enabled_by_default() { + let bus = EventBus::::default(); + + assert!(bus.sender().is_some()); + } + + #[tokio::test] + async fn it_should_allow_sending_events_that_are_received_by_receivers() { + let bus = EventBus::::default(); + let sender = bus.sender().unwrap(); + let mut receiver = bus.receiver(); + + let event = "hello".to_string(); + + let _unused = sender.send(event.clone()).await.unwrap().unwrap(); + + let result = timeout(Duration::from_secs(1), receiver.recv()).await; + + assert_eq!(result.unwrap().unwrap(), event); + } + + #[tokio::test] + async fn it_should_send_a_closed_events_to_receivers_when_sender_is_dropped() { + let bus = EventBus::::default(); + + let mut receiver = bus.receiver(); + + let future = receiver.recv(); + + drop(bus); // explicitly drop sender + + let result = timeout(Duration::from_secs(1), future).await; + + assert!(matches!(result.unwrap(), Err(crate::receiver::RecvError::Closed))); + } +} diff --git a/packages/events/src/lib.rs b/packages/events/src/lib.rs new file mode 100644 index 000000000..d933b304c --- /dev/null +++ b/packages/events/src/lib.rs @@ -0,0 +1,7 @@ +pub mod broadcaster; +pub mod bus; +pub mod receiver; +pub mod sender; + +/// Target for tracing crate logs. +pub const EVENTS_TARGET: &str = "EVENTS"; diff --git a/packages/events/src/receiver.rs b/packages/events/src/receiver.rs new file mode 100644 index 000000000..15adb816a --- /dev/null +++ b/packages/events/src/receiver.rs @@ -0,0 +1,38 @@ +use std::fmt; + +use futures::future::BoxFuture; +#[cfg(test)] +use mockall::{automock, predicate::str}; + +/// A trait for receiving events. +#[cfg_attr(test, automock(type Event=();))] +pub trait Receiver: Sync + Send { + type Event: Send + Clone; + + fn recv(&mut self) -> BoxFuture<'_, Result>; +} + +/// An error returned from the [`recv`] function on a [`Receiver`]. +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum RecvError { + /// There are no more active senders implying no further messages will ever + /// be sent. + Closed, + + /// The receiver lagged too far behind. Attempting to receive again will + /// return the oldest message still retained by the channel. + /// + /// Includes the number of skipped messages. + Lagged(u64), +} + +impl fmt::Display for RecvError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + RecvError::Closed => write!(f, "channel closed"), + RecvError::Lagged(amt) => write!(f, "channel lagged by {amt}"), + } + } +} + +impl std::error::Error for RecvError {} diff --git a/packages/events/src/sender.rs b/packages/events/src/sender.rs new file mode 100644 index 000000000..3dccade4c --- /dev/null +++ b/packages/events/src/sender.rs @@ -0,0 +1,39 @@ +use std::fmt; +use std::fmt::Debug; + +use futures::future::BoxFuture; +#[cfg(test)] +use mockall::{automock, predicate::str}; + +/// A trait for sending events. +#[cfg_attr(test, automock(type Event=();))] +pub trait Sender: Sync + Send { + type Event: Send + Clone; + + /// Sends an event to all active receivers. + /// + /// Returns a future that resolves to an `Option>>`: + /// + /// - `Some(Ok(n))` — the event was successfully sent to `n` receivers. + /// - `Some(Err(e))` — an error occurred while sending the event. + /// - `None` — the sender is inactive or disconnected, and the event was not sent. + /// + /// The `Option` allows implementations to express cases where sending is not possible + /// (e.g., when the sender is disabled or there are no active receivers). + /// + /// The `usize` typically represents the number of receivers the message was delivered to, + /// but its semantics may vary depending on the concrete implementation. + fn send(&self, event: Self::Event) -> BoxFuture<'_, Option>>>; +} + +/// Error returned by the [`send`] function on a [`Sender`]. +#[derive(Debug)] +pub struct SendError(pub Event); + +impl fmt::Display for SendError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "channel closed") + } +} + +impl std::error::Error for SendError {} diff --git a/packages/events/src/shutdown.rs b/packages/events/src/shutdown.rs new file mode 100644 index 000000000..e69de29bb diff --git a/packages/http-protocol/Cargo.toml b/packages/http-protocol/Cargo.toml new file mode 100644 index 000000000..78a037b18 --- /dev/null +++ b/packages/http-protocol/Cargo.toml @@ -0,0 +1,31 @@ +[package] +description = "A library with the primitive types and functions for the BitTorrent HTTP tracker protocol." +keywords = [ "api", "library", "primitives" ] +name = "bittorrent-http-tracker-protocol" +readme = "README.md" + +authors.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +bittorrent-primitives = "0.1.0" +bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } +derive_more = { version = "2", features = [ "as_ref", "constructor", "from" ] } +multimap = "0" +percent-encoding = "2" +serde = { version = "1", features = [ "derive" ] } +serde_bencode = "0" +thiserror = "2" +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-develop", path = "../../contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } diff --git a/packages/http-protocol/LICENSE b/packages/http-protocol/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/http-protocol/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/http-protocol/README.md b/packages/http-protocol/README.md new file mode 100644 index 000000000..5f0a31a78 --- /dev/null +++ b/packages/http-protocol/README.md @@ -0,0 +1,11 @@ +# BitTorrent HTTP Tracker Protocol + +A library with the primitive types and functions used by BitTorrent HTTP trackers. + +## Documentation + +[Crate documentation](https://docs.rs/bittorrent-http-tracker-protocol). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/http-protocol/src/lib.rs b/packages/http-protocol/src/lib.rs new file mode 100644 index 000000000..326a5b182 --- /dev/null +++ b/packages/http-protocol/src/lib.rs @@ -0,0 +1,16 @@ +//! Primitive types and function for `BitTorrent` HTTP trackers. +pub mod percent_encoding; +pub mod v1; + +use torrust_tracker_clock::clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/src/servers/http/percent_encoding.rs b/packages/http-protocol/src/percent_encoding.rs similarity index 74% rename from src/servers/http/percent_encoding.rs rename to packages/http-protocol/src/percent_encoding.rs index c8f0f7f12..e58bf94be 100644 --- a/src/servers/http/percent_encoding.rs +++ b/packages/http-protocol/src/percent_encoding.rs @@ -15,20 +15,21 @@ //! - //! - //! - -use crate::shared::bit_torrent::info_hash::{ConversionError, InfoHash}; -use crate::tracker::peer::{self, IdConversionError}; +use aquatic_udp_protocol::PeerId; +use bittorrent_primitives::info_hash::{self, InfoHash}; +use torrust_tracker_primitives::peer; /// Percent decodes a percent encoded infohash. Internally an -/// [`InfoHash`](crate::shared::bit_torrent::info_hash::InfoHash) is a 20-byte array. +/// [`InfoHash`] is a 20-byte array. /// /// For example, given the infohash `3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0`, /// it's percent encoded representation is `%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0`. /// /// ```rust /// use std::str::FromStr; -/// use torrust_tracker::servers::http::percent_encoding::percent_decode_info_hash; -/// use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -/// use torrust_tracker::tracker::peer; +/// use bittorrent_http_tracker_protocol::percent_encoding::percent_decode_info_hash; +/// use bittorrent_primitives::info_hash::InfoHash; +/// use torrust_tracker_primitives::peer; /// /// let encoded_infohash = "%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0"; /// @@ -43,13 +44,13 @@ use crate::tracker::peer::{self, IdConversionError}; /// # Errors /// /// Will return `Err` if the decoded bytes do not represent a valid -/// [`InfoHash`](crate::shared::bit_torrent::info_hash::InfoHash). -pub fn percent_decode_info_hash(raw_info_hash: &str) -> Result { +/// [`InfoHash`]. +pub fn percent_decode_info_hash(raw_info_hash: &str) -> Result { let bytes = percent_encoding::percent_decode_str(raw_info_hash).collect::>(); InfoHash::try_from(bytes) } -/// Percent decodes a percent encoded peer id. Internally a peer [`Id`](crate::tracker::peer::Id) +/// Percent decodes a percent encoded peer id. Internally a peer [`Id`](PeerId) /// is a 20-byte array. /// /// For example, given the peer id `*b"-qB00000000000000000"`, @@ -57,32 +58,34 @@ pub fn percent_decode_info_hash(raw_info_hash: &str) -> Result Result { +/// Will return `Err` if if the decoded bytes do not represent a valid [`PeerId`]. +pub fn percent_decode_peer_id(raw_peer_id: &str) -> Result { let bytes = percent_encoding::percent_decode_str(raw_peer_id).collect::>(); - peer::Id::try_from(bytes) + Ok(*peer::Id::try_from(bytes)?) } #[cfg(test)] mod tests { use std::str::FromStr; - use crate::servers::http::percent_encoding::{percent_decode_info_hash, percent_decode_peer_id}; - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::tracker::peer; + use aquatic_udp_protocol::PeerId; + use bittorrent_primitives::info_hash::InfoHash; + + use crate::percent_encoding::{percent_decode_info_hash, percent_decode_peer_id}; #[test] fn it_should_decode_a_percent_encoded_info_hash() { @@ -111,7 +114,7 @@ mod tests { let peer_id = percent_decode_peer_id(encoded_peer_id).unwrap(); - assert_eq!(peer_id, peer::Id(*b"-qB00000000000000000")); + assert_eq!(peer_id, PeerId(*b"-qB00000000000000000")); } #[test] diff --git a/packages/http-protocol/src/v1/auth.rs b/packages/http-protocol/src/v1/auth.rs new file mode 100644 index 000000000..ad2e59e53 --- /dev/null +++ b/packages/http-protocol/src/v1/auth.rs @@ -0,0 +1,17 @@ +use std::panic::Location; + +use thiserror::Error; + +/// Authentication error. +/// +/// When the tracker is private, the authentication key is required in the URL +/// path. These are the possible errors that can occur when extracting the key +/// from the URL path. +#[derive(Debug, Error)] +pub enum Error { + #[error("Invalid format for authentication key param. Error in {location}")] + InvalidKeyFormat { location: &'static Location<'static> }, + + #[error("Cannot extract authentication key param from URL path. Error in {location}")] + CannotExtractKeyParam { location: &'static Location<'static> }, +} diff --git a/packages/http-protocol/src/v1/mod.rs b/packages/http-protocol/src/v1/mod.rs new file mode 100644 index 000000000..6de653e66 --- /dev/null +++ b/packages/http-protocol/src/v1/mod.rs @@ -0,0 +1,5 @@ +pub mod auth; +pub mod query; +pub mod requests; +pub mod responses; +pub mod services; diff --git a/src/servers/http/v1/query.rs b/packages/http-protocol/src/v1/query.rs similarity index 90% rename from src/servers/http/v1/query.rs rename to packages/http-protocol/src/v1/query.rs index 6bbdc63e9..9f53ef54f 100644 --- a/src/servers/http/v1/query.rs +++ b/packages/http-protocol/src/v1/query.rs @@ -31,7 +31,7 @@ impl Query { /// input `name` exists. For example: /// /// ```rust - /// use torrust_tracker::servers::http::v1::query::Query; + /// use bittorrent_http_tracker_protocol::v1::query::Query; /// /// let raw_query = "param1=value1¶m2=value2"; /// @@ -44,7 +44,7 @@ impl Query { /// It returns only the first param value even if it has multiple values: /// /// ```rust - /// use torrust_tracker::servers::http::v1::query::Query; + /// use bittorrent_http_tracker_protocol::v1::query::Query; /// /// let raw_query = "param1=value1¶m1=value2"; /// @@ -60,7 +60,7 @@ impl Query { /// Returns all the param values as a vector. /// /// ```rust - /// use torrust_tracker::servers::http::v1::query::Query; + /// use bittorrent_http_tracker_protocol::v1::query::Query; /// /// let query = "param1=value1¶m1=value2".parse::().unwrap(); /// @@ -73,7 +73,7 @@ impl Query { /// Returns all the param values as a vector even if it has only one value. /// /// ```rust - /// use torrust_tracker::servers::http::v1::query::Query; + /// use bittorrent_http_tracker_protocol::v1::query::Query; /// /// let query = "param1=value1".parse::().unwrap(); /// @@ -86,14 +86,14 @@ impl Query { self.params.get_vec(name).map(|pairs| { let mut param_values = vec![]; for pair in pairs { - param_values.push(pair.value.to_string()); + param_values.push(pair.value.clone()); } param_values }) } } -/// This error can be returned when parsing a [`Query`](crate::servers::http::v1::query::Query) +/// This error can be returned when parsing a [`Query`] /// from a string. #[derive(Error, Debug)] pub enum ParseQueryError { @@ -137,7 +137,7 @@ impl From> for Query { } impl std::fmt::Display for Query { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let query = self .params .iter_all() @@ -185,7 +185,7 @@ impl FromStr for NameValuePair { } impl std::fmt::Display for NameValuePair { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}={}", self.name, self.value) } } @@ -208,7 +208,7 @@ impl FieldValuePairSet { } impl std::fmt::Display for FieldValuePairSet { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let query = self .pairs .iter() @@ -224,7 +224,7 @@ impl std::fmt::Display for FieldValuePairSet { mod tests { mod url_query { - use crate::servers::http::v1::query::Query; + use crate::v1::query::Query; #[test] fn should_parse_the_query_params_from_an_url_query_string() { @@ -249,6 +249,13 @@ mod tests { assert_eq!(query.get_param("param2"), Some("value2".to_string())); } + #[test] + fn should_ignore_duplicate_param_values_when_asked_to_return_only_one_value() { + let query = Query::from(vec![("param1", "value1"), ("param1", "value2")]); + + assert_eq!(query.get_param("param1"), Some("value1".to_string())); + } + #[test] fn should_fail_parsing_an_invalid_query_string() { let invalid_raw_query = "name=value=value"; @@ -277,7 +284,7 @@ mod tests { } mod should_allow_more_than_one_value_for_the_same_param { - use crate::servers::http::v1::query::Query; + use crate::v1::query::Query; #[test] fn instantiated_from_a_vector() { @@ -299,7 +306,7 @@ mod tests { } mod should_be_displayed { - use crate::servers::http::v1::query::Query; + use crate::v1::query::Query; #[test] fn with_one_param() { @@ -320,7 +327,7 @@ mod tests { } mod param_name_value_pair { - use crate::servers::http::v1::query::NameValuePair; + use crate::v1::query::NameValuePair; #[test] fn should_parse_a_single_query_param() { diff --git a/src/servers/http/v1/requests/announce.rs b/packages/http-protocol/src/v1/requests/announce.rs similarity index 72% rename from src/servers/http/v1/requests/announce.rs rename to packages/http-protocol/src/v1/requests/announce.rs index 1cf632eb5..a04738749 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/packages/http-protocol/src/v1/requests/announce.rs @@ -2,21 +2,21 @@ //! //! Data structures and logic for parsing the `announce` request. use std::fmt; +use std::net::{IpAddr, SocketAddr}; use std::panic::Location; use std::str::FromStr; +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +use bittorrent_primitives::info_hash::{self, InfoHash}; use thiserror::Error; +use torrust_tracker_clock::clock::Time; use torrust_tracker_located_error::{Located, LocatedError}; +use torrust_tracker_primitives::peer; -use crate::servers::http::percent_encoding::{percent_decode_info_hash, percent_decode_peer_id}; -use crate::servers::http::v1::query::{ParseQueryError, Query}; -use crate::servers::http::v1::responses; -use crate::shared::bit_torrent::info_hash::{ConversionError, InfoHash}; -use crate::tracker::peer::{self, IdConversionError}; - -/// The number of bytes `downloaded`, `uploaded` or `left`. It's used in the -/// `Announce` request for parameters that represent a number of bytes. -pub type NumberOfBytes = i64; +use crate::percent_encoding::{percent_decode_info_hash, percent_decode_peer_id}; +use crate::v1::query::{ParseQueryError, Query}; +use crate::v1::responses; +use crate::CurrentClock; // Query param names const INFO_HASH: &str = "info_hash"; @@ -27,43 +27,47 @@ const UPLOADED: &str = "uploaded"; const LEFT: &str = "left"; const EVENT: &str = "event"; const COMPACT: &str = "compact"; +const NUMWANT: &str = "numwant"; /// The `Announce` request. Fields use the domain types after parsing the /// query params of the request. /// /// ```rust -/// use torrust_tracker::servers::http::v1::requests::announce::{Announce, Compact, Event}; -/// use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -/// use torrust_tracker::tracker::peer; +/// use aquatic_udp_protocol::{NumberOfBytes, PeerId}; +/// use bittorrent_http_tracker_protocol::v1::requests::announce::{Announce, Compact, Event}; +/// use bittorrent_primitives::info_hash::InfoHash; /// /// let request = Announce { /// // Mandatory params /// info_hash: "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), -/// peer_id: "-qB00000000000000001".parse::().unwrap(), +/// peer_id: PeerId(*b"-qB00000000000000001"), /// port: 17548, /// // Optional params -/// downloaded: Some(1), -/// uploaded: Some(2), -/// left: Some(3), +/// downloaded: Some(NumberOfBytes::new(1)), +/// uploaded: Some(NumberOfBytes::new(1)), +/// left: Some(NumberOfBytes::new(1)), /// event: Some(Event::Started), -/// compact: Some(Compact::NotAccepted) +/// compact: Some(Compact::NotAccepted), +/// numwant: Some(50) /// }; /// ``` /// /// > **NOTICE**: The [BEP 03. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -/// specifies that only the peer `IP` and `event`are optional. However, the -/// tracker defines default values for some of the mandatory params. +/// > specifies that only the peer `IP` and `event`are optional. However, the +/// > tracker defines default values for some of the mandatory params. /// /// > **NOTICE**: The struct does not contain the `IP` of the peer. It's not -/// mandatory and it's not used by the tracker. The `IP` is obtained from the -/// request itself. +/// > mandatory and it's not used by the tracker. The `IP` is obtained from the +/// > request itself. #[derive(Debug, PartialEq)] pub struct Announce { // Mandatory params /// The `InfoHash` of the torrent. pub info_hash: InfoHash, - /// The `peer::Id` of the peer. - pub peer_id: peer::Id, + + /// The `PeerId` of the peer. + pub peer_id: PeerId, + /// The port of the peer. pub port: u16, @@ -83,6 +87,10 @@ pub struct Announce { /// Whether the response should be in compact mode or not. pub compact: Option, + + /// Number of peers that the client would receive from the tracker. The + /// value is permitted to be zero. + pub numwant: Option, } /// Errors that can occur when parsing the `Announce` request. @@ -119,14 +127,14 @@ pub enum ParseAnnounceQueryError { InvalidInfoHashParam { param_name: String, param_value: String, - source: LocatedError<'static, ConversionError>, + source: LocatedError<'static, info_hash::ConversionError>, }, /// The `peer_id` is invalid. #[error("invalid param value {param_value} for {param_name} in {source}")] InvalidPeerIdParam { param_name: String, param_value: String, - source: LocatedError<'static, IdConversionError>, + source: LocatedError<'static, peer::IdConversionError>, }, } @@ -137,15 +145,21 @@ pub enum ParseAnnounceQueryError { /// /// Refer to [BEP 03. The `BitTorrent Protocol` Specification](https://www.bittorrent.org/beps/bep_0003.html) /// for more information. -#[derive(PartialEq, Debug)] +#[derive(PartialEq, Debug, Clone)] pub enum Event { /// Event sent when a download first begins. Started, + /// Event sent when the downloader cease downloading. Stopped, + /// Event sent when the download is complete. - /// No `completed` is sent if the file was complete when started + /// No `completed` is sent if the file was complete when started. Completed, + + /// It is the same as not being present. If not present, this is one of the + /// announcements done at regular intervals. + Empty, } impl FromStr for Event { @@ -156,6 +170,7 @@ impl FromStr for Event { "started" => Ok(Self::Started), "stopped" => Ok(Self::Stopped), "completed" => Ok(Self::Completed), + "empty" => Ok(Self::Empty), _ => Err(ParseAnnounceQueryError::InvalidParam { param_name: EVENT.to_owned(), param_value: raw_param.to_owned(), @@ -166,11 +181,34 @@ impl FromStr for Event { } impl fmt::Display for Event { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Event::Started => write!(f, "started"), Event::Stopped => write!(f, "stopped"), Event::Completed => write!(f, "completed"), + Event::Empty => write!(f, "empty"), + } + } +} + +impl From for Event { + fn from(event: aquatic_udp_protocol::request::AnnounceEvent) -> Self { + match event { + AnnounceEvent::Started => Self::Started, + AnnounceEvent::Stopped => Self::Stopped, + AnnounceEvent::Completed => Self::Completed, + AnnounceEvent::None => Self::Empty, + } + } +} + +impl From for aquatic_udp_protocol::request::AnnounceEvent { + fn from(event: Event) -> Self { + match event { + Event::Started => Self::Started, + Event::Stopped => Self::Stopped, + Event::Completed => Self::Completed, + Event::Empty => Self::None, } } } @@ -180,8 +218,8 @@ impl fmt::Display for Event { /// Depending on the value of this param, the tracker will return a different /// response: /// -/// - [`NonCompact`](crate::servers::http::v1::responses::announce::NonCompact) response. -/// - [`Compact`](crate::servers::http::v1::responses::announce::Compact) response. +/// - [`Normal`](crate::v1::responses::announce::Normal), i.e. a `non-compact` response. +/// - [`Compact`](crate::v1::responses::announce::Compact) response. /// /// Refer to [BEP 23. Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) #[derive(PartialEq, Debug)] @@ -194,7 +232,7 @@ pub enum Compact { } impl fmt::Display for Compact { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Compact::Accepted => write!(f, "1"), Compact::NotAccepted => write!(f, "0"), @@ -221,7 +259,7 @@ impl FromStr for Compact { impl From for responses::error::Error { fn from(err: ParseQueryError) -> Self { responses::error::Error { - failure_reason: format!("Cannot parse query params: {err}"), + failure_reason: format!("Bad request. Cannot parse query params: {err}"), } } } @@ -229,7 +267,7 @@ impl From for responses::error::Error { impl From for responses::error::Error { fn from(err: ParseAnnounceQueryError) -> Self { responses::error::Error { - failure_reason: format!("Cannot parse query params for announce request: {err}"), + failure_reason: format!("Bad request. Cannot parse query params for announce request: {err}"), } } } @@ -247,6 +285,7 @@ impl TryFrom for Announce { left: extract_left(&query)?, event: extract_event(&query)?, compact: extract_compact(&query)?, + numwant: extract_numwant(&query)?, }) } } @@ -264,16 +303,14 @@ fn extract_info_hash(query: &Query) -> Result })?, ) } - None => { - return Err(ParseAnnounceQueryError::MissingParam { - location: Location::caller(), - param_name: INFO_HASH.to_owned(), - }) - } + None => Err(ParseAnnounceQueryError::MissingParam { + location: Location::caller(), + param_name: INFO_HASH.to_owned(), + }), } } -fn extract_peer_id(query: &Query) -> Result { +fn extract_peer_id(query: &Query) -> Result { match query.get_param(PEER_ID) { Some(raw_param) => Ok( percent_decode_peer_id(&raw_param).map_err(|err| ParseAnnounceQueryError::InvalidPeerIdParam { @@ -282,12 +319,10 @@ fn extract_peer_id(query: &Query) -> Result { source: Located(err).into(), })?, ), - None => { - return Err(ParseAnnounceQueryError::MissingParam { - location: Location::caller(), - param_name: PEER_ID.to_owned(), - }) - } + None => Err(ParseAnnounceQueryError::MissingParam { + location: Location::caller(), + param_name: PEER_ID.to_owned(), + }), } } @@ -298,12 +333,10 @@ fn extract_port(query: &Query) -> Result { param_value: raw_param.clone(), location: Location::caller(), })?), - None => { - return Err(ParseAnnounceQueryError::MissingParam { - location: Location::caller(), - param_name: PORT.to_owned(), - }) - } + None => Err(ParseAnnounceQueryError::MissingParam { + location: Location::caller(), + param_name: PORT.to_owned(), + }), } } @@ -330,13 +363,16 @@ fn extract_number_of_bytes_from_param(param_name: &str, query: &Query) -> Result location: Location::caller(), })?; - Ok(Some(i64::try_from(number_of_bytes).map_err(|_e| { - ParseAnnounceQueryError::NumberOfBytesOverflow { + let number_of_bytes = + i64::try_from(number_of_bytes).map_err(|_e| ParseAnnounceQueryError::NumberOfBytesOverflow { param_name: param_name.to_owned(), param_value: raw_param.clone(), location: Location::caller(), - } - })?)) + })?; + + let number_of_bytes = NumberOfBytes::new(number_of_bytes); + + Ok(Some(number_of_bytes)) } None => Ok(None), } @@ -356,17 +392,51 @@ fn extract_compact(query: &Query) -> Result, ParseAnnounceQueryE } } +fn extract_numwant(query: &Query) -> Result, ParseAnnounceQueryError> { + match query.get_param(NUMWANT) { + Some(raw_param) => match u32::from_str(&raw_param) { + Ok(numwant) => Ok(Some(numwant)), + Err(_) => Err(ParseAnnounceQueryError::InvalidParam { + param_name: NUMWANT.to_owned(), + param_value: raw_param.clone(), + location: Location::caller(), + }), + }, + None => Ok(None), + } +} + +/// It builds a `Peer` from the announce request. +/// +/// It ignores the peer address in the announce request params. +#[must_use] +pub fn peer_from_request(announce_request: &Announce, peer_ip: &IpAddr) -> peer::Peer { + peer::Peer { + peer_id: announce_request.peer_id, + peer_addr: SocketAddr::new(*peer_ip, announce_request.port), + updated: CurrentClock::now(), + uploaded: announce_request.uploaded.unwrap_or(NumberOfBytes::new(0)), + downloaded: announce_request.downloaded.unwrap_or(NumberOfBytes::new(0)), + left: announce_request.left.unwrap_or(NumberOfBytes::new(0)), + event: match &announce_request.event { + Some(event) => event.clone().into(), + None => AnnounceEvent::None, + }, + } +} + #[cfg(test)] mod tests { mod announce_request { - use crate::servers::http::v1::query::Query; - use crate::servers::http::v1::requests::announce::{ - Announce, Compact, Event, COMPACT, DOWNLOADED, EVENT, INFO_HASH, LEFT, PEER_ID, PORT, UPLOADED, + use aquatic_udp_protocol::{NumberOfBytes, PeerId}; + use bittorrent_primitives::info_hash::InfoHash; + + use crate::v1::query::Query; + use crate::v1::requests::announce::{ + Announce, Compact, Event, COMPACT, DOWNLOADED, EVENT, INFO_HASH, LEFT, NUMWANT, PEER_ID, PORT, UPLOADED, }; - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::tracker::peer; #[test] fn should_be_instantiated_from_the_url_query_with_only_the_mandatory_params() { @@ -384,14 +454,15 @@ mod tests { assert_eq!( announce_request, Announce { - info_hash: "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), - peer_id: "-qB00000000000000001".parse::().unwrap(), + info_hash: "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), // DevSkim: ignore DS173237 + peer_id: PeerId(*b"-qB00000000000000001"), port: 17548, downloaded: None, uploaded: None, left: None, event: None, compact: None, + numwant: None, } ); } @@ -407,6 +478,7 @@ mod tests { (LEFT, "3"), (EVENT, "started"), (COMPACT, "0"), + (NUMWANT, "50"), ]) .to_string(); @@ -417,23 +489,24 @@ mod tests { assert_eq!( announce_request, Announce { - info_hash: "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), - peer_id: "-qB00000000000000001".parse::().unwrap(), + info_hash: "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), // DevSkim: ignore DS173237 + peer_id: PeerId(*b"-qB00000000000000001"), port: 17548, - downloaded: Some(1), - uploaded: Some(2), - left: Some(3), + downloaded: Some(NumberOfBytes::new(1)), + uploaded: Some(NumberOfBytes::new(2)), + left: Some(NumberOfBytes::new(3)), event: Some(Event::Started), compact: Some(Compact::NotAccepted), + numwant: Some(50), } ); } mod when_it_is_instantiated_from_the_url_query_params { - use crate::servers::http::v1::query::Query; - use crate::servers::http::v1::requests::announce::{ - Announce, COMPACT, DOWNLOADED, EVENT, INFO_HASH, LEFT, PEER_ID, PORT, UPLOADED, + use crate::v1::query::Query; + use crate::v1::requests::announce::{ + Announce, COMPACT, DOWNLOADED, EVENT, INFO_HASH, LEFT, NUMWANT, PEER_ID, PORT, UPLOADED, }; #[test] @@ -552,6 +625,19 @@ mod tests { assert!(Announce::try_from(raw_query.parse::().unwrap()).is_err()); } + + #[test] + fn it_should_fail_if_the_numwant_param_is_invalid() { + let raw_query = Query::from(vec![ + (INFO_HASH, "%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0"), + (PEER_ID, "-qB00000000000000001"), + (PORT, "17548"), + (NUMWANT, "-1"), + ]) + .to_string(); + + assert!(Announce::try_from(raw_query.parse::().unwrap()).is_err()); + } } } } diff --git a/packages/http-protocol/src/v1/requests/mod.rs b/packages/http-protocol/src/v1/requests/mod.rs new file mode 100644 index 000000000..d19bd78d3 --- /dev/null +++ b/packages/http-protocol/src/v1/requests/mod.rs @@ -0,0 +1,3 @@ +//! HTTP requests for the HTTP tracker. +pub mod announce; +pub mod scrape; diff --git a/src/servers/http/v1/requests/scrape.rs b/packages/http-protocol/src/v1/requests/scrape.rs similarity index 78% rename from src/servers/http/v1/requests/scrape.rs rename to packages/http-protocol/src/v1/requests/scrape.rs index 227ea74ae..ae8e41cc2 100644 --- a/src/servers/http/v1/requests/scrape.rs +++ b/packages/http-protocol/src/v1/requests/scrape.rs @@ -3,15 +3,13 @@ //! Data structures and logic for parsing the `scrape` request. use std::panic::Location; +use bittorrent_primitives::info_hash::{self, InfoHash}; use thiserror::Error; use torrust_tracker_located_error::{Located, LocatedError}; -use crate::servers::http::percent_encoding::percent_decode_info_hash; -use crate::servers::http::v1::query::Query; -use crate::servers::http::v1::responses; -use crate::shared::bit_torrent::info_hash::{ConversionError, InfoHash}; - -pub type NumberOfBytes = i64; +use crate::percent_encoding::percent_decode_info_hash; +use crate::v1::query::Query; +use crate::v1::responses; // Query param names const INFO_HASH: &str = "info_hash"; @@ -34,14 +32,14 @@ pub enum ParseScrapeQueryError { InvalidInfoHashParam { param_name: String, param_value: String, - source: LocatedError<'static, ConversionError>, + source: LocatedError<'static, info_hash::ConversionError>, }, } impl From for responses::error::Error { fn from(err: ParseScrapeQueryError) -> Self { responses::error::Error { - failure_reason: format!("Cannot parse query params for scrape request: {err}"), + failure_reason: format!("Bad request. Cannot parse query params for scrape request: {err}"), } } } @@ -74,12 +72,10 @@ fn extract_info_hashes(query: &Query) -> Result, ParseScrapeQueryE Ok(info_hashes) } - None => { - return Err(ParseScrapeQueryError::MissingParam { - location: Location::caller(), - param_name: INFO_HASH.to_owned(), - }) - } + None => Err(ParseScrapeQueryError::MissingParam { + location: Location::caller(), + param_name: INFO_HASH.to_owned(), + }), } } @@ -88,9 +84,10 @@ mod tests { mod scrape_request { - use crate::servers::http::v1::query::Query; - use crate::servers::http::v1::requests::scrape::{Scrape, INFO_HASH}; - use crate::shared::bit_torrent::info_hash::InfoHash; + use bittorrent_primitives::info_hash::InfoHash; + + use crate::v1::query::Query; + use crate::v1::requests::scrape::{Scrape, INFO_HASH}; #[test] fn should_be_instantiated_from_the_url_query_with_only_one_infohash() { @@ -110,8 +107,8 @@ mod tests { mod when_it_is_instantiated_from_the_url_query_params { - use crate::servers::http::v1::query::Query; - use crate::servers::http::v1::requests::scrape::{Scrape, INFO_HASH}; + use crate::v1::query::Query; + use crate::v1::requests::scrape::{Scrape, INFO_HASH}; #[test] fn it_should_fail_if_the_query_does_not_include_the_info_hash_param() { diff --git a/packages/http-protocol/src/v1/responses/announce.rs b/packages/http-protocol/src/v1/responses/announce.rs new file mode 100644 index 000000000..7175b019a --- /dev/null +++ b/packages/http-protocol/src/v1/responses/announce.rs @@ -0,0 +1,351 @@ +//! `Announce` response for the HTTP tracker [`announce`](crate::v1::requests::announce::Announce) request. +//! +//! Data structures and logic to build the `announce` response. +use std::io::Write; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + +use derive_more::{AsRef, Constructor, From}; +use torrust_tracker_contrib_bencode::{ben_bytes, ben_int, ben_list, ben_map, BMutAccess, BencodeMut}; +use torrust_tracker_primitives::core::AnnounceData; +use torrust_tracker_primitives::peer; + +/// An [`Announce`] response, that can be anything that is convertible from [`AnnounceData`]. +/// +/// The [`Announce`] can built from any data that implements: [`From`] and [`Into>`]. +/// +/// The two standard forms of an announce response are: [`Normal`] and [`Compact`]. +/// +/// +/// _"To reduce the size of tracker responses and to reduce memory and +/// computational requirements in trackers, trackers may return peers as a +/// packed string rather than as a bencoded list."_ +/// +/// Refer to the official BEPs for more information: +/// +/// - [BEP 03: The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) +/// - [BEP 23: Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) +/// - [BEP 07: IPv6 Tracker Extension](https://www.bittorrent.org/beps/bep_0007.html) + +#[derive(Debug, AsRef, PartialEq, Constructor)] +pub struct Announce +where + E: From + Into>, +{ + pub data: E, +} + +/// Build any [`Announce`] from an [`AnnounceData`]. +impl + Into>> From for Announce { + fn from(data: AnnounceData) -> Self { + Self::new(data.into()) + } +} + +/// Format of the [`Normal`] (Non-Compact) Encoding +pub struct Normal { + complete: i64, + incomplete: i64, + interval: i64, + min_interval: i64, + peers: Vec, +} + +impl From for Normal { + fn from(data: AnnounceData) -> Self { + Self { + complete: data.stats.complete.into(), + incomplete: data.stats.incomplete.into(), + interval: data.policy.interval.into(), + min_interval: data.policy.interval_min.into(), + peers: data.peers.iter().map(AsRef::as_ref).copied().collect(), + } + } +} + +#[allow(clippy::from_over_into)] +impl Into> for Normal { + fn into(self) -> Vec { + let mut peers_list = ben_list!(); + let peers_list_mut = peers_list.list_mut().unwrap(); + for peer in &self.peers { + peers_list_mut.push(peer.into()); + } + + (ben_map! { + "complete" => ben_int!(self.complete), + "incomplete" => ben_int!(self.incomplete), + "interval" => ben_int!(self.interval), + "min interval" => ben_int!(self.min_interval), + "peers" => peers_list.clone() + }) + .encode() + } +} + +/// Format of the [`Compact`] Encoding +pub struct Compact { + complete: i64, + incomplete: i64, + interval: i64, + min_interval: i64, + peers: Vec, + peers6: Vec, +} + +impl From for Compact { + fn from(data: AnnounceData) -> Self { + let compact_peers: Vec = data.peers.iter().map(AsRef::as_ref).copied().collect(); + + let (peers, peers6): (Vec>, Vec>) = + compact_peers.into_iter().collect(); + + let peers_encoded: CompactPeersEncoded = peers.into_iter().collect(); + let peers_encoded_6: CompactPeersEncoded = peers6.into_iter().collect(); + + Self { + complete: data.stats.complete.into(), + incomplete: data.stats.incomplete.into(), + interval: data.policy.interval.into(), + min_interval: data.policy.interval_min.into(), + peers: peers_encoded.0, + peers6: peers_encoded_6.0, + } + } +} + +#[allow(clippy::from_over_into)] +impl Into> for Compact { + fn into(self) -> Vec { + (ben_map! { + "complete" => ben_int!(self.complete), + "incomplete" => ben_int!(self.incomplete), + "interval" => ben_int!(self.interval), + "min interval" => ben_int!(self.min_interval), + "peers" => ben_bytes!(self.peers), + "peers6" => ben_bytes!(self.peers6) + }) + .encode() + } +} + +/// A [`NormalPeer`], for the [`Normal`] form. +/// +/// ```rust +/// use std::net::{IpAddr, Ipv4Addr}; +/// use bittorrent_http_tracker_protocol::v1::responses::announce::{Normal, NormalPeer}; +/// +/// let peer = NormalPeer { +/// peer_id: *b"-qB00000000000000001", +/// ip: IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), // 105.105.105.105 +/// port: 0x7070, // 28784 +/// }; +/// +/// ``` +#[derive(Debug, PartialEq)] +pub struct NormalPeer { + /// The peer's ID. + pub peer_id: [u8; 20], + /// The peer's IP address. + pub ip: IpAddr, + /// The peer's port number. + pub port: u16, +} + +impl peer::Encoding for NormalPeer {} + +impl From for NormalPeer { + fn from(peer: peer::Peer) -> Self { + NormalPeer { + peer_id: peer.peer_id.0, + ip: peer.peer_addr.ip(), + port: peer.peer_addr.port(), + } + } +} + +impl From<&NormalPeer> for BencodeMut<'_> { + fn from(value: &NormalPeer) -> Self { + ben_map! { + "peer id" => ben_bytes!(value.peer_id.clone().to_vec()), + "ip" => ben_bytes!(value.ip.to_string()), + "port" => ben_int!(i64::from(value.port)) + } + } +} + +/// A [`CompactPeer`], for the [`Compact`] form. +/// +/// _"To reduce the size of tracker responses and to reduce memory and +/// computational requirements in trackers, trackers may return peers as a +/// packed string rather than as a bencoded list."_ +/// +/// A part from reducing the size of the response, this format does not contain +/// the peer's ID. +/// +/// ```rust +/// use std::net::{IpAddr, Ipv4Addr}; +/// use bittorrent_http_tracker_protocol::v1::responses::announce::{Compact, CompactPeer, CompactPeerData}; +/// +/// let peer = CompactPeer::V4(CompactPeerData { +/// ip: Ipv4Addr::new(0x69, 0x69, 0x69, 0x69), // 105.105.105.105 +/// port: 0x7070, // 28784 +/// }); +/// +/// ``` +/// +/// Refer to [BEP 23: Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) +/// for more information. +#[derive(Clone, Debug, PartialEq)] +pub enum CompactPeer { + /// The peer's IP address. + V4(CompactPeerData), + /// The peer's port number. + V6(CompactPeerData), +} + +impl peer::Encoding for CompactPeer {} + +impl From for CompactPeer { + fn from(peer: peer::Peer) -> Self { + match (peer.peer_addr.ip(), peer.peer_addr.port()) { + (IpAddr::V4(ip), port) => Self::V4(CompactPeerData { ip, port }), + (IpAddr::V6(ip), port) => Self::V6(CompactPeerData { ip, port }), + } + } +} + +/// The [`CompactPeerData`], that made with either a [`Ipv4Addr`], or [`Ipv6Addr`] along with a `port`. +/// +#[derive(Clone, Debug, PartialEq)] +pub struct CompactPeerData { + /// The peer's IP address. + pub ip: V, + /// The peer's port number. + pub port: u16, +} + +impl FromIterator for (Vec>, Vec>) { + fn from_iter>(iter: T) -> Self { + let mut peers_v4: Vec> = vec![]; + let mut peers_v6: Vec> = vec![]; + + for peer in iter { + match peer { + CompactPeer::V4(peer) => peers_v4.push(peer), + CompactPeer::V6(peer6) => peers_v6.push(peer6), + } + } + + (peers_v4, peers_v6) + } +} + +#[derive(From, PartialEq)] +struct CompactPeersEncoded(Vec); + +impl FromIterator> for CompactPeersEncoded { + fn from_iter>>(iter: T) -> Self { + let mut bytes: Vec = vec![]; + + for peer in iter { + bytes + .write_all(&u32::from(peer.ip).to_be_bytes()) + .expect("it should write peer ip"); + bytes.write_all(&peer.port.to_be_bytes()).expect("it should write peer port"); + } + + bytes.into() + } +} + +impl FromIterator> for CompactPeersEncoded { + fn from_iter>>(iter: T) -> Self { + let mut bytes: Vec = Vec::new(); + + for peer in iter { + bytes + .write_all(&u128::from(peer.ip).to_be_bytes()) + .expect("it should write peer ip"); + bytes.write_all(&peer.port.to_be_bytes()).expect("it should write peer port"); + } + bytes.into() + } +} + +#[cfg(test)] +mod tests { + + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::PeerId; + use torrust_tracker_configuration::AnnouncePolicy; + use torrust_tracker_primitives::core::AnnounceData; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + + use crate::v1::responses::announce::{Announce, Compact, Normal}; + + // Some ascii values used in tests: + // + // +-----------------+ + // | Dec | Hex | Chr | + // +-----------------+ + // | 105 | 69 | i | + // | 112 | 70 | p | + // +-----------------+ + // + // IP addresses and port numbers used in tests are chosen so that their bencoded representation + // is also a valid string which makes asserts more readable. + + fn setup_announce_data() -> AnnounceData { + let policy = AnnouncePolicy::new(111, 222); + + let peer_ipv4 = PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000001")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), 0x7070)) + .build(); + + let peer_ipv6 = PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000002")) + .with_peer_addr(&SocketAddr::new( + IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + 0x7070, + )) + .build(); + + let peers = vec![Arc::new(peer_ipv4), Arc::new(peer_ipv6)]; + let stats = SwarmMetadata::new(333, 333, 444); + + AnnounceData::new(peers, stats, policy) + } + + #[test] + fn non_compact_announce_response_can_be_bencoded() { + let response: Announce = setup_announce_data().into(); + let bytes = response.data.into(); + + // cspell:disable-next-line + let expected_bytes = b"d8:completei333e10:incompletei444e8:intervali111e12:min intervali222e5:peersld2:ip15:105.105.105.1057:peer id20:-qB000000000000000014:porti28784eed2:ip39:6969:6969:6969:6969:6969:6969:6969:69697:peer id20:-qB000000000000000024:porti28784eeee"; + + assert_eq!( + String::from_utf8(bytes).unwrap(), + String::from_utf8(expected_bytes.to_vec()).unwrap() + ); + } + + #[test] + fn compact_announce_response_can_be_bencoded() { + let response: Announce = setup_announce_data().into(); + let bytes = response.data.into(); + + let expected_bytes = + // cspell:disable-next-line + b"d8:completei333e10:incompletei444e8:intervali111e12:min intervali222e5:peers6:iiiipp6:peers618:iiiiiiiiiiiiiiiippe"; + + assert_eq!( + String::from_utf8(bytes).unwrap(), + String::from_utf8(expected_bytes.to_vec()).unwrap() + ); + } +} diff --git a/packages/http-protocol/src/v1/responses/error.rs b/packages/http-protocol/src/v1/responses/error.rs new file mode 100644 index 000000000..2e7a36d0a --- /dev/null +++ b/packages/http-protocol/src/v1/responses/error.rs @@ -0,0 +1,131 @@ +//! `Error` response for the HTTP tracker. +//! +//! Data structures and logic to build the error responses. +//! +//! From the [BEP 03. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html): +//! +//! _"Tracker responses are bencoded dictionaries. If a tracker response has a +//! key failure reason, then that maps to a human readable string which explains +//! why the query failed, and no other keys are required."_ +//! +//! > **NOTICE**: error responses are bencoded and always have a `200 OK` status +//! > code. The official `BitTorrent` specification does not specify the status +//! > code. +use serde::Serialize; + +use crate::v1::auth; +use crate::v1::services::peer_ip_resolver::PeerIpResolutionError; + +/// `Error` response for the HTTP tracker. +#[derive(Serialize, Debug, PartialEq)] +pub struct Error { + /// Human readable string which explains why the request failed. + #[serde(rename = "failure reason")] + pub failure_reason: String, +} + +impl Error { + /// Returns the bencoded representation of the `Error` struct. + /// + /// ```rust + /// use bittorrent_http_tracker_protocol::v1::responses::error::Error; + /// + /// let err = Error { + /// failure_reason: "error message".to_owned(), + /// }; + /// + /// // cspell:disable-next-line + /// assert_eq!(err.write(), "d14:failure reason13:error messagee"); + /// ``` + /// + /// # Panics + /// + /// It would panic if the `Error` struct contained an inappropriate field + /// type. + #[must_use] + pub fn write(&self) -> String { + serde_bencode::to_string(&self).unwrap() + } +} + +impl From for Error { + fn from(err: auth::Error) -> Self { + Self { + failure_reason: format!("Tracker authentication error: {err}"), + } + } +} + +impl From for Error { + fn from(err: PeerIpResolutionError) -> Self { + Self { + failure_reason: format!("Error resolving peer IP: {err}"), + } + } +} + +impl From for Error { + fn from(err: bittorrent_tracker_core::error::AnnounceError) -> Self { + Error { + failure_reason: format!("Tracker announce error: {err}"), + } + } +} + +impl From for Error { + fn from(err: bittorrent_tracker_core::error::ScrapeError) -> Self { + Error { + failure_reason: format!("Tracker scrape error: {err}"), + } + } +} + +impl From for Error { + fn from(err: bittorrent_tracker_core::error::WhitelistError) -> Self { + Error { + failure_reason: format!("Tracker whitelist error: {err}"), + } + } +} + +impl From for Error { + fn from(err: bittorrent_tracker_core::authentication::Error) -> Self { + Error { + failure_reason: format!("Tracker authentication error: {err}"), + } + } +} + +#[cfg(test)] +mod tests { + use std::panic::Location; + + use super::Error; + use crate::v1::responses; + use crate::v1::services::peer_ip_resolver::PeerIpResolutionError; + + #[test] + fn http_tracker_errors_can_be_bencoded() { + let err = Error { + failure_reason: "error message".to_owned(), + }; + + assert_eq!(err.write(), "d14:failure reason13:error messagee"); // cspell:disable-line + } + + fn assert_error_response(error: &responses::error::Error, error_message: &str) { + assert!( + error.failure_reason.contains(error_message), + "Error response does not contain message: '{error_message}'. Error: {error:?}" + ); + } + + #[test] + fn it_should_map_a_peer_ip_resolution_error_into_an_error_response() { + let response = responses::error::Error::from(PeerIpResolutionError::MissingRightMostXForwardedForIp { + location: Location::caller(), + }); + + assert_error_response(&response, "Error resolving peer IP"); + } +} diff --git a/packages/http-protocol/src/v1/responses/mod.rs b/packages/http-protocol/src/v1/responses/mod.rs new file mode 100644 index 000000000..e704d8908 --- /dev/null +++ b/packages/http-protocol/src/v1/responses/mod.rs @@ -0,0 +1,6 @@ +//! HTTP responses for the HTTP tracker. +pub mod announce; +pub mod error; +pub mod scrape; + +pub use announce::{Announce, Compact, Normal}; diff --git a/src/servers/http/v1/responses/scrape.rs b/packages/http-protocol/src/v1/responses/scrape.rs similarity index 76% rename from src/servers/http/v1/responses/scrape.rs rename to packages/http-protocol/src/v1/responses/scrape.rs index 6610f9dc4..022735abc 100644 --- a/src/servers/http/v1/responses/scrape.rs +++ b/packages/http-protocol/src/v1/responses/scrape.rs @@ -1,23 +1,20 @@ -//! `Scrape` response for the HTTP tracker [`scrape`](crate::servers::http::v1::requests::scrape::Scrape) request. +//! `Scrape` response for the HTTP tracker [`scrape`](crate::v1::requests::scrape::Scrape) request. //! //! Data structures and logic to build the `scrape` response. use std::borrow::Cow; -use axum::http::StatusCode; -use axum::response::{IntoResponse, Response}; -use bip_bencode::{ben_int, ben_map, BMutAccess}; - -use crate::tracker::ScrapeData; +use torrust_tracker_contrib_bencode::{ben_int, ben_map, BMutAccess}; +use torrust_tracker_primitives::core::ScrapeData; /// The `Scrape` response for the HTTP tracker. /// /// ```rust -/// use torrust_tracker::servers::http::v1::responses::scrape::Bencoded; -/// use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -/// use torrust_tracker::tracker::torrent::SwarmMetadata; -/// use torrust_tracker::tracker::ScrapeData; +/// use bittorrent_http_tracker_protocol::v1::responses::scrape::Bencoded; +/// use bittorrent_primitives::info_hash::InfoHash; +/// use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +/// use torrust_tracker_primitives::core::ScrapeData; /// -/// let info_hash = InfoHash([0x69; 20]); +/// let info_hash = InfoHash::from_bytes(&[0x69; 20]); /// let mut scrape_data = ScrapeData::empty(); /// scrape_data.add_file( /// &info_hash, @@ -82,23 +79,18 @@ impl From for Bencoded { } } -impl IntoResponse for Bencoded { - fn into_response(self) -> Response { - (StatusCode::OK, self.body()).into_response() - } -} - #[cfg(test)] mod tests { mod scrape_response { - use crate::servers::http::v1::responses::scrape::Bencoded; - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::tracker::torrent::SwarmMetadata; - use crate::tracker::ScrapeData; + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::core::ScrapeData; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + + use crate::v1::responses::scrape::Bencoded; fn sample_scrape_data() -> ScrapeData { - let info_hash = InfoHash([0x69; 20]); + let info_hash = InfoHash::from_bytes(&[0x69; 20]); let mut scrape_data = ScrapeData::empty(); scrape_data.add_file( &info_hash, diff --git a/packages/http-protocol/src/v1/services/mod.rs b/packages/http-protocol/src/v1/services/mod.rs new file mode 100644 index 000000000..de800f630 --- /dev/null +++ b/packages/http-protocol/src/v1/services/mod.rs @@ -0,0 +1 @@ +pub mod peer_ip_resolver; diff --git a/packages/http-protocol/src/v1/services/peer_ip_resolver.rs b/packages/http-protocol/src/v1/services/peer_ip_resolver.rs new file mode 100644 index 000000000..ceaa7e11c --- /dev/null +++ b/packages/http-protocol/src/v1/services/peer_ip_resolver.rs @@ -0,0 +1,262 @@ +//! This service resolves the remote client address. +//! +//! The peer IP is used to identify the peer in the tracker. It's the peer IP +//! that is used in the `announce` responses (peer list). And it's also used to +//! send statistics events. +//! +//! Given this request chain: +//! +//! ```text +//! client <-> http proxy 1 <-> http proxy 2 <-> server +//! ip: 126.0.0.1 ip: 126.0.0.2 ip: 126.0.0.3 ip: 126.0.0.4 +//! X-Forwarded-For: 126.0.0.1 X-Forwarded-For: 126.0.0.1,126.0.0.2 +//! ``` +//! +//! This `ClientIpSources` contains two options for the peer IP: +//! +//! ```text +//! right_most_x_forwarded_for = 126.0.0.2 +//! connection_info_ip = 126.0.0.3 +//! ``` +//! +//! Which one to use depends on the `ReverseProxyMode`. +use std::net::{IpAddr, SocketAddr}; +use std::panic::Location; + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +/// Resolves the client's real address considering proxy headers. Port is also +/// included when available. +/// +/// # Errors +/// +/// This function returns an error if the IP address cannot be resolved. +pub fn resolve_remote_client_addr( + reverse_proxy_mode: &ReverseProxyMode, + client_ip_sources: &ClientIpSources, +) -> Result { + let ip = match reverse_proxy_mode { + ReverseProxyMode::Enabled => ResolvedIp::FromXForwardedFor(client_ip_sources.try_client_ip_from_proxy_header()?), + ReverseProxyMode::Disabled => ResolvedIp::FromSocketAddr(client_ip_sources.try_client_ip_from_connection_info()?), + }; + + let port = client_ip_sources.client_port_from_connection_info(); + + Ok(RemoteClientAddr::new(ip, port)) +} + +/// This struct indicates whether the tracker is running on reverse proxy mode. +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, Copy)] +pub enum ReverseProxyMode { + Enabled, + Disabled, +} + +impl From for bool { + fn from(reverse_proxy_mode: ReverseProxyMode) -> Self { + match reverse_proxy_mode { + ReverseProxyMode::Enabled => true, + ReverseProxyMode::Disabled => false, + } + } +} + +impl From for ReverseProxyMode { + fn from(reverse_proxy_mode: bool) -> Self { + if reverse_proxy_mode { + ReverseProxyMode::Enabled + } else { + ReverseProxyMode::Disabled + } + } +} +/// This struct contains the sources from which the peer IP can be obtained. +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)] +pub struct ClientIpSources { + /// The right most IP from the `X-Forwarded-For` HTTP header. + pub right_most_x_forwarded_for: Option, + + /// The client's socket address from the connection info. + pub connection_info_socket_address: Option, +} + +impl ClientIpSources { + fn try_client_ip_from_connection_info(&self) -> Result { + if let Some(socket_addr) = self.connection_info_socket_address { + Ok(socket_addr.ip()) + } else { + Err(PeerIpResolutionError::MissingClientIp { + location: Location::caller(), + }) + } + } + + fn try_client_ip_from_proxy_header(&self) -> Result { + if let Some(ip) = self.right_most_x_forwarded_for { + Ok(ip) + } else { + Err(PeerIpResolutionError::MissingRightMostXForwardedForIp { + location: Location::caller(), + }) + } + } + + fn client_port_from_connection_info(&self) -> Option { + if self.connection_info_socket_address.is_some() { + self.connection_info_socket_address.map(|socket_addr| socket_addr.port()) + } else { + None + } + } +} + +/// The error that can occur when resolving the peer IP. +#[derive(Error, Debug, Clone)] +pub enum PeerIpResolutionError { + /// The peer IP cannot be obtained because the tracker is configured as a + /// reverse proxy but the `X-Forwarded-For` HTTP header is missing or + /// invalid. + #[error( + "missing or invalid the right most X-Forwarded-For IP (mandatory on reverse proxy tracker configuration) in {location}" + )] + MissingRightMostXForwardedForIp { location: &'static Location<'static> }, + + /// The peer IP cannot be obtained because the tracker is not configured as + /// a reverse proxy but the connection info was not provided to the Axum + /// framework via a route extension. + #[error("cannot get the client IP from the connection info in {location}")] + MissingClientIp { location: &'static Location<'static> }, +} + +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, Copy)] +pub struct RemoteClientAddr { + ip: ResolvedIp, + port: Option, +} + +impl RemoteClientAddr { + #[must_use] + pub fn new(ip: ResolvedIp, port: Option) -> Self { + Self { ip, port } + } + + #[must_use] + pub fn ip(&self) -> IpAddr { + match self.ip { + ResolvedIp::FromSocketAddr(ip) | ResolvedIp::FromXForwardedFor(ip) => ip, + } + } + + #[must_use] + pub fn port(&self) -> Option { + self.port + } +} + +/// This enum indicates the source of the resolved IP address. +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, Copy)] +pub enum ResolvedIp { + FromXForwardedFor(IpAddr), + FromSocketAddr(IpAddr), +} + +#[cfg(test)] +mod tests { + use super::resolve_remote_client_addr; + + mod working_without_reverse_proxy { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::str::FromStr; + + use super::resolve_remote_client_addr; + use crate::v1::services::peer_ip_resolver::{ + ClientIpSources, PeerIpResolutionError, RemoteClientAddr, ResolvedIp, ReverseProxyMode, + }; + + #[test] + fn it_should_get_the_remote_client_address_from_the_connection_info() { + let reverse_proxy_mode = ReverseProxyMode::Disabled; + + let ip = resolve_remote_client_addr( + &reverse_proxy_mode, + &ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_socket_address: Some(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080)), + }, + ) + .unwrap(); + + assert_eq!( + ip, + RemoteClientAddr::new( + ResolvedIp::FromSocketAddr(IpAddr::from_str("203.0.113.195").unwrap()), + Some(8080) + ) + ); + } + + #[test] + fn it_should_return_an_error_if_it_cannot_get_the_remote_client_ip_from_the_connection_info() { + let reverse_proxy_mode = ReverseProxyMode::Disabled; + + let error = resolve_remote_client_addr( + &reverse_proxy_mode, + &ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_socket_address: None, + }, + ) + .unwrap_err(); + + assert!(matches!(error, PeerIpResolutionError::MissingClientIp { .. })); + } + } + + mod working_on_reverse_proxy_mode { + use std::net::IpAddr; + use std::str::FromStr; + + use crate::v1::services::peer_ip_resolver::{ + resolve_remote_client_addr, ClientIpSources, PeerIpResolutionError, RemoteClientAddr, ResolvedIp, ReverseProxyMode, + }; + + #[test] + fn it_should_get_the_remote_client_ip_from_the_right_most_ip_in_the_x_forwarded_for_header() { + let reverse_proxy_mode = ReverseProxyMode::Enabled; + + let ip = resolve_remote_client_addr( + &reverse_proxy_mode, + &ClientIpSources { + right_most_x_forwarded_for: Some(IpAddr::from_str("203.0.113.195").unwrap()), + connection_info_socket_address: None, + }, + ) + .unwrap(); + + assert_eq!( + ip, + RemoteClientAddr::new( + ResolvedIp::FromXForwardedFor(IpAddr::from_str("203.0.113.195").unwrap()), + None + ) + ); + } + + #[test] + fn it_should_return_an_error_if_it_cannot_get_the_right_most_ip_from_the_x_forwarded_for_header() { + let reverse_proxy_mode = ReverseProxyMode::Enabled; + + let error = resolve_remote_client_addr( + &reverse_proxy_mode, + &ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_socket_address: None, + }, + ) + .unwrap_err(); + + assert!(matches!(error, PeerIpResolutionError::MissingRightMostXForwardedForIp { .. })); + } + } +} diff --git a/packages/http-tracker-core/Cargo.toml b/packages/http-tracker-core/Cargo.toml new file mode 100644 index 000000000..c419052f9 --- /dev/null +++ b/packages/http-tracker-core/Cargo.toml @@ -0,0 +1,43 @@ +[package] +authors.workspace = true +description = "A library with the core functionality needed to implement a BitTorrent HTTP tracker." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = [ "api", "bittorrent", "core", "library", "tracker" ] +license.workspace = true +name = "bittorrent-http-tracker-core" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +bittorrent-http-tracker-protocol = { version = "3.0.0-develop", path = "../http-protocol" } +bittorrent-primitives = "0.1.0" +bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } +criterion = { version = "0.5.1", features = [ "async_tokio" ] } +futures = "0" +serde = "1.0.219" +thiserror = "2" +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } +tokio-util = "0.7.15" +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } +torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } +tracing = "0" + +[dev-dependencies] +formatjson = "0.3.1" +mockall = "0" +serde_json = "1.0.140" +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } + +[[bench]] +harness = false +name = "http_tracker_core_benchmark" diff --git a/packages/http-tracker-core/LICENSE b/packages/http-tracker-core/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/http-tracker-core/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/http-tracker-core/README.md b/packages/http-tracker-core/README.md new file mode 100644 index 000000000..0dd915c24 --- /dev/null +++ b/packages/http-tracker-core/README.md @@ -0,0 +1,15 @@ +# BitTorrent HTTP Tracker Core library + +A library with the core functionality needed to implement a BitTorrent HTTP tracker. + +You usually don’t need to use this library directly. Instead, you should use the [Torrust Tracker](https://github.com/torrust/torrust-tracker). If you want to build your own tracker, you can use this library as the core functionality. + +> **Disclaimer**: This library is actively under development. We’re currently extracting and refining common types from the[Torrust Tracker](https://github.com/torrust/torrust-tracker) to make them available to the BitTorrent community in Rust. While these types are functional, they are not yet ready for use in production or third-party projects. + +## Documentation + +[Crate documentation](https://docs.rs/bittorrent-http-tracker-core). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/http-tracker-core/benches/helpers/mod.rs b/packages/http-tracker-core/benches/helpers/mod.rs new file mode 100644 index 000000000..4a91f2224 --- /dev/null +++ b/packages/http-tracker-core/benches/helpers/mod.rs @@ -0,0 +1,2 @@ +pub mod sync; +pub mod util; diff --git a/packages/http-tracker-core/benches/helpers/sync.rs b/packages/http-tracker-core/benches/helpers/sync.rs new file mode 100644 index 000000000..dbf0dac83 --- /dev/null +++ b/packages/http-tracker-core/benches/helpers/sync.rs @@ -0,0 +1,38 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::time::{Duration, Instant}; + +use bittorrent_http_tracker_core::services::announce::AnnounceService; +use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + +use crate::helpers::util::{initialize_core_tracker_services, sample_announce_request_for_peer, sample_peer}; + +#[must_use] +pub async fn return_announce_data_once(samples: u64) -> Duration { + let (core_tracker_services, core_http_tracker_services) = initialize_core_tracker_services(); + + let peer = sample_peer(); + + let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); + + let announce_service = AnnounceService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.announce_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_tracker_services.whitelist_authorization.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let start = Instant::now(); + + for _ in 0..samples { + let _announce_data = announce_service + .handle_announce(&announce_request, &client_ip_sources, &server_service_binding, None) + .await + .unwrap(); + } + + start.elapsed() +} diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs new file mode 100644 index 000000000..028d7c535 --- /dev/null +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -0,0 +1,135 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::sync::Arc; + +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +use bittorrent_http_tracker_core::event::bus::EventBus; +use bittorrent_http_tracker_core::event::sender::Broadcaster; +use bittorrent_http_tracker_core::event::Event; +use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; +use bittorrent_http_tracker_core::statistics::repository::Repository; +use bittorrent_http_tracker_protocol::v1::requests::announce::Announce; +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::announce_handler::AnnounceHandler; +use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; +use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::databases::setup::initialize_database; +use bittorrent_tracker_core::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; +use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; +use futures::future::BoxFuture; +use mockall::mock; +use tokio_util::sync::CancellationToken; +use torrust_tracker_configuration::{Configuration, Core}; +use torrust_tracker_events::sender::SendError; +use torrust_tracker_primitives::peer::Peer; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; +use torrust_tracker_test_helpers::configuration; + +pub struct CoreTrackerServices { + pub core_config: Arc, + pub announce_handler: Arc, + pub authentication_service: Arc, + pub whitelist_authorization: Arc, +} + +pub struct CoreHttpTrackerServices { + pub http_stats_event_sender: bittorrent_http_tracker_core::event::sender::Sender, +} + +pub fn initialize_core_tracker_services() -> (CoreTrackerServices, CoreHttpTrackerServices) { + initialize_core_tracker_services_with_config(&configuration::ephemeral_public()) +} + +pub fn initialize_core_tracker_services_with_config(config: &Configuration) -> (CoreTrackerServices, CoreHttpTrackerServices) { + let cancellation_token = CancellationToken::new(); + + let core_config = Arc::new(config.core.clone()); + let database = initialize_database(&config.core); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(AuthenticationService::new(&core_config, &in_memory_key_repository)); + + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_downloads_metric_repository, + )); + + // HTTP core stats + let http_core_broadcaster = Broadcaster::default(); + let http_stats_repository = Arc::new(Repository::new()); + let http_stats_event_bus = Arc::new(EventBus::new( + config.core.tracker_usage_statistics.into(), + http_core_broadcaster.clone(), + )); + + let http_stats_event_sender = http_stats_event_bus.sender(); + + if config.core.tracker_usage_statistics { + let _unused = run_event_listener(http_stats_event_bus.receiver(), cancellation_token, &http_stats_repository); + } + + ( + CoreTrackerServices { + core_config, + announce_handler, + authentication_service, + whitelist_authorization, + }, + CoreHttpTrackerServices { http_stats_event_sender }, + ) +} + +pub fn sample_peer() -> peer::Peer { + peer::Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), + event: AnnounceEvent::Started, + } +} + +pub fn sample_announce_request_for_peer(peer: Peer) -> (Announce, ClientIpSources) { + let announce_request = Announce { + info_hash: sample_info_hash(), + peer_id: peer.peer_id, + port: peer.peer_addr.port(), + uploaded: Some(peer.uploaded), + downloaded: Some(peer.downloaded), + left: Some(peer.left), + event: Some(peer.event.into()), + compact: None, + numwant: None, + }; + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_socket_address: Some(SocketAddr::new(peer.peer_addr.ip(), 8080)), + }; + + (announce_request, client_ip_sources) +} +#[must_use] +pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") +} + +mock! { + HttpStatsEventSender {} + impl torrust_tracker_events::sender::Sender for HttpStatsEventSender { + type Event = Event; + + fn send(&self, event: Event) -> BoxFuture<'static,Option > > > ; + } +} diff --git a/packages/http-tracker-core/benches/http_tracker_core_benchmark.rs b/packages/http-tracker-core/benches/http_tracker_core_benchmark.rs new file mode 100644 index 000000000..c193c5124 --- /dev/null +++ b/packages/http-tracker-core/benches/http_tracker_core_benchmark.rs @@ -0,0 +1,23 @@ +mod helpers; + +use std::time::Duration; + +use criterion::{criterion_group, criterion_main, Criterion}; + +use crate::helpers::sync; + +fn announce_once(c: &mut Criterion) { + let _rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); + + let mut group = c.benchmark_group("http_tracker_handle_announce_once"); + + group.warm_up_time(Duration::from_millis(500)); + group.measurement_time(Duration::from_secs(1)); + + group.bench_function("handle_announce_data", |b| { + b.iter(|| sync::return_announce_data_once(100)); + }); +} + +criterion_group!(benches, announce_once); +criterion_main!(benches); diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs new file mode 100644 index 000000000..ed0aaf8b0 --- /dev/null +++ b/packages/http-tracker-core/src/container.rs @@ -0,0 +1,114 @@ +use std::sync::Arc; + +use bittorrent_tracker_core::container::TrackerCoreContainer; +use torrust_tracker_configuration::{Core, HttpTracker}; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; + +use crate::event::bus::EventBus; +use crate::event::sender::Broadcaster; +use crate::services::announce::AnnounceService; +use crate::services::scrape::ScrapeService; +use crate::statistics::repository::Repository; +use crate::{event, services, statistics}; + +pub struct HttpTrackerCoreContainer { + pub http_tracker_config: Arc, + + pub tracker_core_container: Arc, + + // `HttpTrackerCoreServices` + pub event_bus: Arc, + pub stats_event_sender: event::sender::Sender, + pub stats_repository: Arc, + pub announce_service: Arc, + pub scrape_service: Arc, +} + +impl HttpTrackerCoreContainer { + #[must_use] + pub fn initialize(core_config: &Arc, http_tracker_config: &Arc) -> Arc { + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + core_config.tracker_usage_statistics.into(), + )); + + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + core_config, + &swarm_coordination_registry_container, + )); + + Self::initialize_from_tracker_core(&tracker_core_container, http_tracker_config) + } + + #[must_use] + pub fn initialize_from_tracker_core( + tracker_core_container: &Arc, + http_tracker_config: &Arc, + ) -> Arc { + let http_tracker_core_services = HttpTrackerCoreServices::initialize_from(tracker_core_container); + + Self::initialize_from_services(tracker_core_container, &http_tracker_core_services, http_tracker_config) + } + + #[must_use] + pub fn initialize_from_services( + tracker_core_container: &Arc, + http_tracker_core_services: &Arc, + http_tracker_config: &Arc, + ) -> Arc { + Arc::new(Self { + tracker_core_container: tracker_core_container.clone(), + http_tracker_config: http_tracker_config.clone(), + event_bus: http_tracker_core_services.event_bus.clone(), + stats_event_sender: http_tracker_core_services.stats_event_sender.clone(), + stats_repository: http_tracker_core_services.stats_repository.clone(), + announce_service: http_tracker_core_services.announce_service.clone(), + scrape_service: http_tracker_core_services.scrape_service.clone(), + }) + } +} + +pub struct HttpTrackerCoreServices { + pub event_bus: Arc, + pub stats_event_sender: event::sender::Sender, + pub stats_repository: Arc, + pub announce_service: Arc, + pub scrape_service: Arc, +} + +impl HttpTrackerCoreServices { + #[must_use] + pub fn initialize_from(tracker_core_container: &Arc) -> Arc { + // HTTP core stats + let http_core_broadcaster = Broadcaster::default(); + let http_stats_repository = Arc::new(Repository::new()); + let http_stats_event_bus = Arc::new(EventBus::new( + tracker_core_container.core_config.tracker_usage_statistics.into(), + http_core_broadcaster.clone(), + )); + + let http_stats_event_sender = http_stats_event_bus.sender(); + + let http_announce_service = Arc::new(AnnounceService::new( + tracker_core_container.core_config.clone(), + tracker_core_container.announce_handler.clone(), + tracker_core_container.authentication_service.clone(), + tracker_core_container.whitelist_authorization.clone(), + http_stats_event_sender.clone(), + )); + + let http_scrape_service = Arc::new(ScrapeService::new( + tracker_core_container.core_config.clone(), + tracker_core_container.scrape_handler.clone(), + tracker_core_container.authentication_service.clone(), + http_stats_event_sender.clone(), + )); + + Arc::new(Self { + event_bus: http_stats_event_bus, + stats_event_sender: http_stats_event_sender, + stats_repository: http_stats_repository, + announce_service: http_announce_service, + scrape_service: http_scrape_service, + }) + } +} diff --git a/packages/http-tracker-core/src/event.rs b/packages/http-tracker-core/src/event.rs new file mode 100644 index 000000000..2a4734bfd --- /dev/null +++ b/packages/http-tracker-core/src/event.rs @@ -0,0 +1,206 @@ +use std::net::{IpAddr, SocketAddr}; + +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::RemoteClientAddr; +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_metrics::label::{LabelSet, LabelValue}; +use torrust_tracker_metrics::label_name; +use torrust_tracker_primitives::peer::PeerAnnouncement; +use torrust_tracker_primitives::service_binding::ServiceBinding; + +/// A HTTP core event. +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum Event { + TcpAnnounce { + connection: ConnectionContext, + info_hash: InfoHash, + announcement: PeerAnnouncement, + }, + TcpScrape { + connection: ConnectionContext, + }, +} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub struct ConnectionContext { + client: ClientConnectionContext, + server: ServerConnectionContext, +} + +impl ConnectionContext { + #[must_use] + pub fn new(remote_client_addr: RemoteClientAddr, server_service_binding: ServiceBinding) -> Self { + Self { + client: ClientConnectionContext { remote_client_addr }, + server: ServerConnectionContext { + service_binding: server_service_binding, + }, + } + } + + #[must_use] + pub fn client_ip_addr(&self) -> IpAddr { + self.client.ip_addr() + } + + #[must_use] + pub fn client_port(&self) -> Option { + self.client.port() + } + + #[must_use] + pub fn server_socket_addr(&self) -> SocketAddr { + self.server.service_binding.bind_address() + } +} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub struct ClientConnectionContext { + remote_client_addr: RemoteClientAddr, +} + +impl ClientConnectionContext { + #[must_use] + pub fn ip_addr(&self) -> IpAddr { + self.remote_client_addr.ip() + } + + #[must_use] + pub fn port(&self) -> Option { + self.remote_client_addr.port() + } +} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub struct ServerConnectionContext { + service_binding: ServiceBinding, +} + +impl From for LabelSet { + fn from(connection_context: ConnectionContext) -> Self { + LabelSet::from([ + ( + label_name!("server_binding_protocol"), + LabelValue::new(&connection_context.server.service_binding.protocol().to_string()), + ), + ( + label_name!("server_binding_ip"), + LabelValue::new(&connection_context.server.service_binding.bind_address().ip().to_string()), + ), + ( + label_name!("server_binding_address_ip_type"), + LabelValue::new(&connection_context.server.service_binding.bind_address_ip_type().to_string()), + ), + ( + label_name!("server_binding_address_ip_family"), + LabelValue::new(&connection_context.server.service_binding.bind_address_ip_family().to_string()), + ), + ( + label_name!("server_binding_port"), + LabelValue::new(&connection_context.server.service_binding.bind_address().port().to_string()), + ), + ]) + } +} + +pub mod sender { + use std::sync::Arc; + + use super::Event; + + pub type Sender = Option>>; + pub type Broadcaster = torrust_tracker_events::broadcaster::Broadcaster; +} + +pub mod receiver { + use super::Event; + + pub type Receiver = Box>; +} + +pub mod bus { + use crate::event::Event; + + pub type EventBus = torrust_tracker_events::bus::EventBus; +} + +#[cfg(test)] +pub mod test { + + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{RemoteClientAddr, ResolvedIp}; + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::service_binding::Protocol; + + use super::Event; + use crate::tests::sample_info_hash; + + #[must_use] + pub fn announce_events_match(event: &Event, expected_event: &Event) -> bool { + match (event, expected_event) { + ( + Event::TcpAnnounce { + connection, + info_hash, + announcement, + }, + Event::TcpAnnounce { + connection: expected_connection, + info_hash: expected_info_hash, + announcement: expected_announcement, + }, + ) => { + *connection == *expected_connection + && *info_hash == *expected_info_hash + && announcement.peer_id == expected_announcement.peer_id + && announcement.peer_addr == expected_announcement.peer_addr + // Events can't be compared due to the `updated` field. + // The `announcement.uploaded` contains the current time + // when the test is executed. + // todo: mock time + //&& announcement.updated == expected_announcement.updated + && announcement.uploaded == expected_announcement.uploaded + && announcement.downloaded == expected_announcement.downloaded + && announcement.left == expected_announcement.left + && announcement.event == expected_announcement.event + } + _ => false, + } + } + + #[test] + fn events_should_be_comparable() { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use torrust_tracker_primitives::service_binding::ServiceBinding; + + use crate::event::{ConnectionContext, Event}; + + let remote_client_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); + let info_hash = sample_info_hash(); + + let event1 = Event::TcpAnnounce { + connection: ConnectionContext::new( + RemoteClientAddr::new(ResolvedIp::FromSocketAddr(remote_client_ip), Some(8080)), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(), + ), + info_hash, + announcement: Peer::default(), + }; + + let event2 = Event::TcpAnnounce { + connection: ConnectionContext::new( + RemoteClientAddr::new( + ResolvedIp::FromSocketAddr(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2))), + Some(8080), + ), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(), + ), + info_hash, + announcement: Peer::default(), + }; + + let event1_clone = event1.clone(); + + assert!(event1 == event1_clone); + assert!(event1 != event2); + } +} diff --git a/packages/http-tracker-core/src/lib.rs b/packages/http-tracker-core/src/lib.rs new file mode 100644 index 000000000..1692a68fa --- /dev/null +++ b/packages/http-tracker-core/src/lib.rs @@ -0,0 +1,63 @@ +pub mod container; +pub mod event; +pub mod services; +pub mod statistics; + +use torrust_tracker_clock::clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; + +pub const HTTP_TRACKER_LOG_TARGET: &str = "HTTP TRACKER"; + +#[cfg(test)] +pub(crate) mod tests { + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } + + pub fn sample_peer_using_ipv4() -> peer::Peer { + sample_peer() + } + + pub fn sample_peer_using_ipv6() -> peer::Peer { + let mut peer = sample_peer(); + peer.peer_addr = SocketAddr::new( + IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + 8080, + ); + peer + } + + pub fn sample_peer() -> peer::Peer { + peer::Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), + event: AnnounceEvent::Started, + } + } +} diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs new file mode 100644 index 000000000..766f08c12 --- /dev/null +++ b/packages/http-tracker-core/src/services/announce.rs @@ -0,0 +1,557 @@ +//! The `announce` service. +//! +//! The service is responsible for handling the `announce` requests. +//! +//! It delegates the `announce` logic to the [`AnnounceHandler`] and it returns +//! the [`AnnounceData`]. +//! +//! It also sends an [`http_tracker_core::event::Event`] +//! because events are specific for the HTTP tracker. +use std::panic::Location; +use std::sync::Arc; + +use bittorrent_http_tracker_protocol::v1::requests::announce::{peer_from_request, Announce}; +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{ + resolve_remote_client_addr, ClientIpSources, PeerIpResolutionError, RemoteClientAddr, +}; +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; +use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::authentication::{self, Key}; +use bittorrent_tracker_core::error::{AnnounceError, TrackerCoreError, WhitelistError}; +use bittorrent_tracker_core::whitelist; +use torrust_tracker_configuration::Core; +use torrust_tracker_primitives::core::AnnounceData; +use torrust_tracker_primitives::peer::PeerAnnouncement; +use torrust_tracker_primitives::service_binding::ServiceBinding; + +use crate::event; +use crate::event::Event; + +/// The HTTP tracker `announce` service. +/// +/// The service sends an statistics event that increments: +/// +/// - The number of TCP `announce` requests handled by the HTTP tracker. +/// - The number of TCP `scrape` requests handled by the HTTP tracker. +pub struct AnnounceService { + core_config: Arc, + announce_handler: Arc, + authentication_service: Arc, + whitelist_authorization: Arc, + opt_http_stats_event_sender: event::sender::Sender, +} + +impl AnnounceService { + #[must_use] + pub fn new( + core_config: Arc, + announce_handler: Arc, + authentication_service: Arc, + whitelist_authorization: Arc, + opt_http_stats_event_sender: event::sender::Sender, + ) -> Self { + Self { + core_config, + announce_handler, + authentication_service, + whitelist_authorization, + opt_http_stats_event_sender, + } + } + + /// Handles an announce request. + /// + /// # Errors + /// + /// This function will return an error if: + /// + /// - The tracker is running in `listed` mode and the torrent is not whitelisted. + /// - There is an error when resolving the client IP address. + pub async fn handle_announce( + &self, + announce_request: &Announce, + client_ip_sources: &ClientIpSources, + server_service_binding: &ServiceBinding, + maybe_key: Option, + ) -> Result { + self.authenticate(maybe_key).await?; + + self.authorize(announce_request.info_hash).await?; + + let remote_client_addr = resolve_remote_client_addr(&self.core_config.net.on_reverse_proxy.into(), client_ip_sources)?; + + let mut peer = peer_from_request(announce_request, &remote_client_addr.ip()); + + let peers_wanted = Self::peers_wanted(announce_request); + + let announce_data = self + .announce_handler + .handle_announcement( + &announce_request.info_hash, + &mut peer, + &remote_client_addr.ip(), + &peers_wanted, + ) + .await?; + + self.send_event( + announce_request.info_hash, + remote_client_addr, + server_service_binding.clone(), + peer, + ) + .await; + + Ok(announce_data) + } + + async fn authenticate(&self, maybe_key: Option) -> Result<(), authentication::key::Error> { + if self.core_config.private { + let key = maybe_key.ok_or(authentication::key::Error::MissingAuthKey { + location: Location::caller(), + })?; + + self.authentication_service.authenticate(&key).await?; + } + + Ok(()) + } + + async fn authorize(&self, info_hash: InfoHash) -> Result<(), WhitelistError> { + self.whitelist_authorization.authorize(&info_hash).await + } + + /// Determines how many peers the client wants in the response + fn peers_wanted(announce_request: &Announce) -> PeersWanted { + match announce_request.numwant { + Some(numwant) => PeersWanted::only(numwant), + None => PeersWanted::AsManyAsPossible, + } + } + + async fn send_event( + &self, + info_hash: InfoHash, + remote_client_addr: RemoteClientAddr, + server_service_binding: ServiceBinding, + announcement: PeerAnnouncement, + ) { + if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { + let event = Event::TcpAnnounce { + connection: event::ConnectionContext::new(remote_client_addr, server_service_binding), + info_hash, + announcement, + }; + + tracing::debug!("Sending TcpAnnounce event: {:?}", event); + + http_stats_event_sender.send(event).await; + } + } +} + +/// Errors related to announce requests. +#[derive(thiserror::Error, Debug, Clone)] +pub enum HttpAnnounceError { + #[error("Error resolving peer IP: {source}")] + PeerIpResolutionError { source: PeerIpResolutionError }, + + #[error("Tracker core error: {source}")] + TrackerCoreError { source: TrackerCoreError }, +} + +impl From for HttpAnnounceError { + fn from(peer_ip_resolution_error: PeerIpResolutionError) -> Self { + Self::PeerIpResolutionError { + source: peer_ip_resolution_error, + } + } +} + +impl From for HttpAnnounceError { + fn from(tracker_core_error: TrackerCoreError) -> Self { + Self::TrackerCoreError { + source: tracker_core_error, + } + } +} + +impl From for HttpAnnounceError { + fn from(announce_error: AnnounceError) -> Self { + Self::TrackerCoreError { + source: announce_error.into(), + } + } +} + +impl From for HttpAnnounceError { + fn from(whitelist_error: WhitelistError) -> Self { + Self::TrackerCoreError { + source: whitelist_error.into(), + } + } +} + +impl From for HttpAnnounceError { + fn from(whitelist_error: authentication::key::Error) -> Self { + Self::TrackerCoreError { + source: whitelist_error.into(), + } + } +} + +#[cfg(test)] +mod tests { + use std::net::SocketAddr; + use std::sync::Arc; + + use bittorrent_http_tracker_protocol::v1::requests::announce::Announce; + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; + use bittorrent_tracker_core::authentication::service::AuthenticationService; + use bittorrent_tracker_core::databases::setup::initialize_database; + use bittorrent_tracker_core::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; + use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use tokio_util::sync::CancellationToken; + use torrust_tracker_configuration::{Configuration, Core}; + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_test_helpers::configuration; + + struct CoreTrackerServices { + pub core_config: Arc, + pub announce_handler: Arc, + pub authentication_service: Arc, + pub whitelist_authorization: Arc, + } + + struct CoreHttpTrackerServices { + pub http_stats_event_sender: crate::event::sender::Sender, + } + + fn initialize_core_tracker_services() -> (CoreTrackerServices, CoreHttpTrackerServices) { + initialize_core_tracker_services_with_config(&configuration::ephemeral_public()) + } + + fn initialize_core_tracker_services_with_config(config: &Configuration) -> (CoreTrackerServices, CoreHttpTrackerServices) { + let cancellation_token = CancellationToken::new(); + + let core_config = Arc::new(config.core.clone()); + let database = initialize_database(&config.core); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(AuthenticationService::new(&core_config, &in_memory_key_repository)); + + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_downloads_metric_repository, + )); + + // HTTP core stats + let http_core_broadcaster = Broadcaster::default(); + let http_stats_repository = Arc::new(Repository::new()); + let http_stats_event_bus = Arc::new(EventBus::new( + config.core.tracker_usage_statistics.into(), + http_core_broadcaster.clone(), + )); + + let http_stats_event_sender = http_stats_event_bus.sender(); + + if config.core.tracker_usage_statistics { + let _unused = run_event_listener(http_stats_event_bus.receiver(), cancellation_token, &http_stats_repository); + } + + ( + CoreTrackerServices { + core_config, + announce_handler, + authentication_service, + whitelist_authorization, + }, + CoreHttpTrackerServices { http_stats_event_sender }, + ) + } + + fn sample_announce_request_for_peer(peer: Peer) -> (Announce, ClientIpSources) { + let announce_request = Announce { + info_hash: sample_info_hash(), + peer_id: peer.peer_id, + port: peer.peer_addr.port(), + uploaded: Some(peer.uploaded), + downloaded: Some(peer.downloaded), + left: Some(peer.left), + event: Some(peer.event.into()), + compact: None, + numwant: None, + }; + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_socket_address: Some(SocketAddr::new(peer.peer_addr.ip(), 8080)), + }; + + (announce_request, client_ip_sources) + } + + use futures::future::BoxFuture; + use mockall::mock; + use torrust_tracker_events::sender::SendError; + + use crate::event::bus::EventBus; + use crate::event::sender::Broadcaster; + use crate::event::Event; + use crate::statistics::event::listener::run_event_listener; + use crate::statistics::repository::Repository; + use crate::tests::sample_info_hash; + + mock! { + HttpStatsEventSender {} + impl torrust_tracker_events::sender::Sender for HttpStatsEventSender { + type Event = Event; + + fn send(&self, event: Event) -> BoxFuture<'static,Option > > > ; + } + } + + mod with_tracker_in_any_mode { + use std::future; + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::sync::Arc; + + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{RemoteClientAddr, ResolvedIp}; + use mockall::predicate::{self}; + use torrust_tracker_configuration::Configuration; + use torrust_tracker_primitives::core::AnnounceData; + use torrust_tracker_primitives::peer; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + use torrust_tracker_test_helpers::configuration; + + use crate::event::test::announce_events_match; + use crate::event::{ConnectionContext, Event}; + use crate::services::announce::tests::{ + initialize_core_tracker_services, initialize_core_tracker_services_with_config, sample_announce_request_for_peer, + MockHttpStatsEventSender, + }; + use crate::services::announce::AnnounceService; + use crate::tests::{sample_info_hash, sample_peer, sample_peer_using_ipv4, sample_peer_using_ipv6}; + + #[tokio::test] + async fn it_should_return_the_announce_data() { + let (core_tracker_services, core_http_tracker_services) = initialize_core_tracker_services(); + + let peer = sample_peer(); + + let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let announce_service = AnnounceService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.announce_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_tracker_services.whitelist_authorization.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let announce_data = announce_service + .handle_announce(&announce_request, &client_ip_sources, &server_service_binding, None) + .await + .unwrap(); + + let expected_announce_data = AnnounceData { + peers: vec![], + stats: SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0, + }, + policy: core_tracker_services.core_config.announce_policy, + }; + + assert_eq!(announce_data, expected_announce_data); + } + + #[tokio::test] + async fn it_should_send_the_tcp_4_announce_event_when_the_peer_uses_ipv4() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + let peer = sample_peer_using_ipv4(); + let remote_client_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); + + let server_service_binding_clone = server_service_binding.clone(); + + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); + http_stats_event_sender_mock + .expect_send() + .with(predicate::function(move |event| { + let mut announcement = peer; + announcement.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); + + let expected_event = Event::TcpAnnounce { + connection: ConnectionContext::new( + RemoteClientAddr::new(ResolvedIp::FromSocketAddr(remote_client_ip), Some(8080)), + server_service_binding.clone(), + ), + info_hash: sample_info_hash(), + announcement, + }; + + announce_events_match(event, &expected_event) + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let http_stats_event_sender: crate::event::sender::Sender = Some(Arc::new(http_stats_event_sender_mock)); + + let (core_tracker_services, mut core_http_tracker_services) = initialize_core_tracker_services(); + + core_http_tracker_services.http_stats_event_sender = http_stats_event_sender; + + let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); + + let announce_service = AnnounceService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.announce_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_tracker_services.whitelist_authorization.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let _announce_data = announce_service + .handle_announce(&announce_request, &client_ip_sources, &server_service_binding_clone, None) + .await + .unwrap(); + } + + fn tracker_with_an_ipv6_external_ip() -> Configuration { + let mut configuration = configuration::ephemeral(); + configuration.core.net.external_ip = Some(IpAddr::V6(Ipv6Addr::new( + 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, + ))); + configuration + } + + fn peer_with_the_ipv4_loopback_ip() -> peer::Peer { + let loopback_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); + let mut peer = sample_peer(); + peer.peer_addr = SocketAddr::new(loopback_ip, 8080); + peer + } + + #[tokio::test] + async fn it_should_send_the_tcp_4_announce_event_when_the_peer_uses_ipv4_even_if_the_tracker_changes_the_peer_ip_to_ipv6() + { + // Tracker changes the peer IP to the tracker external IP when the peer is using the loopback IP. + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + let peer = peer_with_the_ipv4_loopback_ip(); + let remote_client_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); + + let server_service_binding_clone = server_service_binding.clone(); + + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); + http_stats_event_sender_mock + .expect_send() + .with(predicate::function(move |event| { + let mut peer_announcement = peer; + peer_announcement.peer_addr = SocketAddr::new( + IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + 8080, + ); + + let expected_event = Event::TcpAnnounce { + connection: ConnectionContext::new( + RemoteClientAddr::new(ResolvedIp::FromSocketAddr(remote_client_ip), Some(8080)), + server_service_binding.clone(), + ), + info_hash: sample_info_hash(), + announcement: peer_announcement, + }; + + announce_events_match(event, &expected_event) + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + + let http_stats_event_sender: crate::event::sender::Sender = Some(Arc::new(http_stats_event_sender_mock)); + + let (core_tracker_services, mut core_http_tracker_services) = + initialize_core_tracker_services_with_config(&tracker_with_an_ipv6_external_ip()); + + core_http_tracker_services.http_stats_event_sender = http_stats_event_sender; + + let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); + + let announce_service = AnnounceService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.announce_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_tracker_services.whitelist_authorization.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let _announce_data = announce_service + .handle_announce(&announce_request, &client_ip_sources, &server_service_binding_clone, None) + .await + .unwrap(); + } + + #[tokio::test] + async fn it_should_send_the_tcp_6_announce_event_when_the_peer_uses_ipv6_even_if_the_tracker_changes_the_peer_ip_to_ipv4() + { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + let peer = sample_peer_using_ipv6(); + let remote_client_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); + + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); + http_stats_event_sender_mock + .expect_send() + .with(predicate::function(move |event| { + let expected_event = Event::TcpAnnounce { + connection: ConnectionContext::new( + RemoteClientAddr::new(ResolvedIp::FromSocketAddr(remote_client_ip), Some(8080)), + server_service_binding.clone(), + ), + info_hash: sample_info_hash(), + announcement: peer, + }; + announce_events_match(event, &expected_event) + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let http_stats_event_sender: crate::event::sender::Sender = Some(Arc::new(http_stats_event_sender_mock)); + + let (core_tracker_services, mut core_http_tracker_services) = initialize_core_tracker_services(); + core_http_tracker_services.http_stats_event_sender = http_stats_event_sender; + + let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); + + let announce_service = AnnounceService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.announce_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_tracker_services.whitelist_authorization.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let _announce_data = announce_service + .handle_announce(&announce_request, &client_ip_sources, &server_service_binding, None) + .await + .unwrap(); + } + } +} diff --git a/src/servers/http/v1/services/mod.rs b/packages/http-tracker-core/src/services/mod.rs similarity index 92% rename from src/servers/http/v1/services/mod.rs rename to packages/http-tracker-core/src/services/mod.rs index 2e6285d1a..ce99c6856 100644 --- a/src/servers/http/v1/services/mod.rs +++ b/packages/http-tracker-core/src/services/mod.rs @@ -6,5 +6,4 @@ //! //! Refer to [`torrust_tracker`](crate) documentation. pub mod announce; -pub mod peer_ip_resolver; pub mod scrape; diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs new file mode 100644 index 000000000..4587bc90a --- /dev/null +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -0,0 +1,620 @@ +//! The `scrape` service. +//! +//! The service is responsible for handling the `scrape` requests. +//! +//! It delegates the `scrape` logic to the [`ScrapeHandler`] and it returns the +//! [`ScrapeData`]. +//! +//! It also sends an [`http_tracker_core::statistics::event::Event`] +//! because events are specific for the HTTP tracker. +use std::sync::Arc; + +use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{ + resolve_remote_client_addr, ClientIpSources, PeerIpResolutionError, RemoteClientAddr, +}; +use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::authentication::{self, Key}; +use bittorrent_tracker_core::error::{ScrapeError, TrackerCoreError, WhitelistError}; +use bittorrent_tracker_core::scrape_handler::ScrapeHandler; +use torrust_tracker_configuration::Core; +use torrust_tracker_primitives::core::ScrapeData; +use torrust_tracker_primitives::service_binding::ServiceBinding; + +use crate::event::{ConnectionContext, Event}; + +/// The HTTP tracker `scrape` service. +/// +/// The service sends an statistics event that increments: +/// +/// - The number of TCP `announce` requests handled by the HTTP tracker. +/// - The number of TCP `scrape` requests handled by the HTTP tracker. +/// +/// # Errors +/// +/// This function will return an error if: +/// +/// - There is an error when resolving the client IP address. +pub struct ScrapeService { + core_config: Arc, + scrape_handler: Arc, + authentication_service: Arc, + opt_http_stats_event_sender: crate::event::sender::Sender, +} + +impl ScrapeService { + #[must_use] + pub fn new( + core_config: Arc, + scrape_handler: Arc, + authentication_service: Arc, + opt_http_stats_event_sender: crate::event::sender::Sender, + ) -> Self { + Self { + core_config, + scrape_handler, + authentication_service, + opt_http_stats_event_sender, + } + } + + /// Handles a scrape request. + /// + /// When the peer is not authenticated and the tracker is running in `private` + /// mode, the tracker returns empty stats for all the torrents. + /// + /// # Errors + /// + /// This function will return an error if: + /// + /// - There is an error when resolving the client IP address. + pub async fn handle_scrape( + &self, + scrape_request: &Scrape, + client_ip_sources: &ClientIpSources, + server_service_binding: &ServiceBinding, + maybe_key: Option, + ) -> Result { + let scrape_data = if self.authentication_is_required() && !self.is_authenticated(maybe_key).await { + ScrapeData::zeroed(&scrape_request.info_hashes) + } else { + self.scrape_handler.handle_scrape(&scrape_request.info_hashes).await? + }; + + let remote_client_addr = resolve_remote_client_addr(&self.core_config.net.on_reverse_proxy.into(), client_ip_sources)?; + + self.send_event(remote_client_addr, server_service_binding.clone()).await; + + Ok(scrape_data) + } + + fn authentication_is_required(&self) -> bool { + self.core_config.private + } + + async fn is_authenticated(&self, maybe_key: Option) -> bool { + if let Some(key) = maybe_key { + return self.authentication_service.authenticate(&key).await.is_ok(); + } + + false + } + + async fn send_event(&self, remote_client_addr: RemoteClientAddr, server_service_binding: ServiceBinding) { + if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { + let event = Event::TcpScrape { + connection: ConnectionContext::new(remote_client_addr, server_service_binding), + }; + + tracing::debug!("Sending TcpScrape event: {:?}", event); + + http_stats_event_sender.send(event).await; + } + } +} + +/// Errors related to announce requests. +#[derive(thiserror::Error, Debug, Clone)] +pub enum HttpScrapeError { + #[error("Error resolving peer IP: {source}")] + PeerIpResolutionError { source: PeerIpResolutionError }, + + #[error("Tracker core error: {source}")] + TrackerCoreError { source: TrackerCoreError }, +} + +impl From for HttpScrapeError { + fn from(peer_ip_resolution_error: PeerIpResolutionError) -> Self { + Self::PeerIpResolutionError { + source: peer_ip_resolution_error, + } + } +} + +impl From for HttpScrapeError { + fn from(tracker_core_error: TrackerCoreError) -> Self { + Self::TrackerCoreError { + source: tracker_core_error, + } + } +} + +impl From for HttpScrapeError { + fn from(announce_error: ScrapeError) -> Self { + Self::TrackerCoreError { + source: announce_error.into(), + } + } +} + +impl From for HttpScrapeError { + fn from(whitelist_error: WhitelistError) -> Self { + Self::TrackerCoreError { + source: whitelist_error.into(), + } + } +} + +impl From for HttpScrapeError { + fn from(whitelist_error: authentication::key::Error) -> Self { + Self::TrackerCoreError { + source: whitelist_error.into(), + } + } +} + +#[cfg(test)] +mod tests { + + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use bittorrent_primitives::info_hash::InfoHash; + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; + use bittorrent_tracker_core::authentication::service::AuthenticationService; + use bittorrent_tracker_core::databases::setup::initialize_database; + use bittorrent_tracker_core::scrape_handler::ScrapeHandler; + use bittorrent_tracker_core::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; + use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use futures::future::BoxFuture; + use mockall::mock; + use torrust_tracker_configuration::Configuration; + use torrust_tracker_events::sender::SendError; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + + use crate::event::Event; + use crate::tests::sample_info_hash; + + struct Container { + announce_handler: Arc, + scrape_handler: Arc, + authentication_service: Arc, + } + + fn initialize_services_with_configuration(config: &Configuration) -> Container { + let database = initialize_database(&config.core); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(AuthenticationService::new(&config.core, &in_memory_key_repository)); + + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_downloads_metric_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + Container { + announce_handler, + scrape_handler, + authentication_service, + } + } + + fn sample_info_hashes() -> Vec { + vec![sample_info_hash()] + } + + fn sample_peer() -> peer::Peer { + peer::Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), + event: AnnounceEvent::Started, + } + } + + mock! { + HttpStatsEventSender {} + impl torrust_tracker_events::sender::Sender for HttpStatsEventSender { + type Event = Event; + + fn send(&self, event: Event) -> BoxFuture<'static,Option > > > ; + } + } + + mod with_real_data { + + use std::future; + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::sync::Arc; + + use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{ClientIpSources, RemoteClientAddr, ResolvedIp}; + use bittorrent_tracker_core::announce_handler::PeersWanted; + use mockall::predicate::eq; + use torrust_tracker_events::bus::SenderStatus; + use torrust_tracker_primitives::core::ScrapeData; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + use torrust_tracker_test_helpers::configuration; + + use crate::event::bus::EventBus; + use crate::event::sender::Broadcaster; + use crate::event::{ConnectionContext, Event}; + use crate::services::scrape::tests::{ + initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, + }; + use crate::services::scrape::ScrapeService; + use crate::tests::sample_info_hash; + + #[tokio::test] + async fn it_should_return_the_scrape_data_for_a_torrent() { + let configuration = configuration::ephemeral_public(); + let core_config = Arc::new(configuration.core.clone()); + + // HTTP core stats + let http_core_broadcaster = Broadcaster::default(); + let http_stats_event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, http_core_broadcaster.clone())); + + let http_stats_event_sender = http_stats_event_bus.sender(); + + let container = initialize_services_with_configuration(&configuration); + + let info_hash = sample_info_hash(); + let info_hashes = vec![info_hash]; + + // Announce a new peer to force scrape data to contain non zeroed data + let mut peer = sample_peer(); + let original_peer_ip = peer.ip(); + container + .announce_handler + .handle_announcement(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::AsManyAsPossible) + .await + .unwrap(); + + let scrape_request = Scrape { + info_hashes: info_hashes.clone(), + }; + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_socket_address: Some(SocketAddr::new(original_peer_ip, 8080)), + }; + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let scrape_service = Arc::new(ScrapeService::new( + core_config.clone(), + container.scrape_handler.clone(), + container.authentication_service.clone(), + http_stats_event_sender.clone(), + )); + + let scrape_data = scrape_service + .handle_scrape(&scrape_request, &client_ip_sources, &server_service_binding, None) + .await + .unwrap(); + + let mut expected_scrape_data = ScrapeData::empty(); + expected_scrape_data.add_file( + &info_hash, + SwarmMetadata { + complete: 1, + downloaded: 0, + incomplete: 0, + }, + ); + + assert_eq!(scrape_data, expected_scrape_data); + } + + #[tokio::test] + async fn it_should_send_the_tcp_4_scrape_event_when_the_peer_uses_ipv4() { + let config = configuration::ephemeral(); + + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); + http_stats_event_sender_mock + .expect_send() + .with(eq(Event::TcpScrape { + connection: ConnectionContext::new( + RemoteClientAddr::new( + ResolvedIp::FromSocketAddr(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1))), + Some(8080), + ), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(), + ), + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let http_stats_event_sender: crate::event::sender::Sender = Some(Arc::new(http_stats_event_sender_mock)); + + let container = initialize_services_with_configuration(&config); + + let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); + + let scrape_request = Scrape { + info_hashes: sample_info_hashes(), + }; + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_socket_address: Some(SocketAddr::new(peer_ip, 8080)), + }; + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let scrape_service = Arc::new(ScrapeService::new( + Arc::new(config.core), + container.scrape_handler.clone(), + container.authentication_service.clone(), + http_stats_event_sender.clone(), + )); + + scrape_service + .handle_scrape(&scrape_request, &client_ip_sources, &server_service_binding, None) + .await + .unwrap(); + } + + #[tokio::test] + async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let config = configuration::ephemeral(); + + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); + http_stats_event_sender_mock + .expect_send() + .with(eq(Event::TcpScrape { + connection: ConnectionContext::new( + RemoteClientAddr::new( + ResolvedIp::FromSocketAddr(IpAddr::V6(Ipv6Addr::new( + 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, + ))), + Some(8080), + ), + server_service_binding, + ), + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let http_stats_event_sender: crate::event::sender::Sender = Some(Arc::new(http_stats_event_sender_mock)); + + let container = initialize_services_with_configuration(&config); + + let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); + + let scrape_request = Scrape { + info_hashes: sample_info_hashes(), + }; + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_socket_address: Some(SocketAddr::new(peer_ip, 8080)), + }; + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let scrape_service = Arc::new(ScrapeService::new( + Arc::new(config.core), + container.scrape_handler.clone(), + container.authentication_service.clone(), + http_stats_event_sender.clone(), + )); + + scrape_service + .handle_scrape(&scrape_request, &client_ip_sources, &server_service_binding, None) + .await + .unwrap(); + } + } + + mod with_zeroed_data { + + use std::future; + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::sync::Arc; + + use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{ClientIpSources, RemoteClientAddr, ResolvedIp}; + use bittorrent_tracker_core::announce_handler::PeersWanted; + use mockall::predicate::eq; + use torrust_tracker_events::bus::SenderStatus; + use torrust_tracker_primitives::core::ScrapeData; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + use torrust_tracker_test_helpers::configuration; + + use crate::event::bus::EventBus; + use crate::event::sender::Broadcaster; + use crate::event::{ConnectionContext, Event}; + use crate::services::scrape::tests::{ + initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, + }; + use crate::services::scrape::ScrapeService; + use crate::tests::sample_info_hash; + + #[tokio::test] + async fn it_should_return_the_zeroed_scrape_data_when_the_tracker_is_running_in_private_mode_and_the_peer_is_not_authenticated( + ) { + let config = configuration::ephemeral_private(); + + let container = initialize_services_with_configuration(&config); + + // HTTP core stats + let http_core_broadcaster = Broadcaster::default(); + let http_stats_event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, http_core_broadcaster.clone())); + + let http_stats_event_sender = http_stats_event_bus.sender(); + + let info_hash = sample_info_hash(); + let info_hashes = vec![info_hash]; + + // Announce a new peer to force scrape data to contain non zeroed data + let mut peer = sample_peer(); + let original_peer_ip = peer.ip(); + container + .announce_handler + .handle_announcement(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::AsManyAsPossible) + .await + .unwrap(); + + let scrape_request = Scrape { + info_hashes: sample_info_hashes(), + }; + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_socket_address: Some(SocketAddr::new(original_peer_ip, 8080)), + }; + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let scrape_service = Arc::new(ScrapeService::new( + Arc::new(config.core), + container.scrape_handler.clone(), + container.authentication_service.clone(), + http_stats_event_sender.clone(), + )); + + let scrape_data = scrape_service + .handle_scrape(&scrape_request, &client_ip_sources, &server_service_binding, None) + .await + .unwrap(); + + let expected_scrape_data = ScrapeData::zeroed(&info_hashes); + + assert_eq!(scrape_data, expected_scrape_data); + } + + #[tokio::test] + async fn it_should_send_the_tcp_4_scrape_event_when_the_peer_uses_ipv4() { + let config = configuration::ephemeral(); + + let container = initialize_services_with_configuration(&config); + + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); + http_stats_event_sender_mock + .expect_send() + .with(eq(Event::TcpScrape { + connection: ConnectionContext::new( + RemoteClientAddr::new( + ResolvedIp::FromSocketAddr(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1))), + Some(8080), + ), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(), + ), + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let http_stats_event_sender: crate::event::sender::Sender = Some(Arc::new(http_stats_event_sender_mock)); + + let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); + + let scrape_request = Scrape { + info_hashes: sample_info_hashes(), + }; + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_socket_address: Some(SocketAddr::new(peer_ip, 8080)), + }; + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let scrape_service = Arc::new(ScrapeService::new( + Arc::new(config.core), + container.scrape_handler.clone(), + container.authentication_service.clone(), + http_stats_event_sender.clone(), + )); + + scrape_service + .handle_scrape(&scrape_request, &client_ip_sources, &server_service_binding, None) + .await + .unwrap(); + } + + #[tokio::test] + async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let config = configuration::ephemeral(); + + let container = initialize_services_with_configuration(&config); + + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); + http_stats_event_sender_mock + .expect_send() + .with(eq(Event::TcpScrape { + connection: ConnectionContext::new( + RemoteClientAddr::new( + ResolvedIp::FromSocketAddr(IpAddr::V6(Ipv6Addr::new( + 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, + ))), + Some(8080), + ), + server_service_binding, + ), + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let http_stats_event_sender: crate::event::sender::Sender = Some(Arc::new(http_stats_event_sender_mock)); + + let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); + + let scrape_request = Scrape { + info_hashes: sample_info_hashes(), + }; + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_socket_address: Some(SocketAddr::new(peer_ip, 8080)), + }; + + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + + let scrape_service = Arc::new(ScrapeService::new( + Arc::new(config.core), + container.scrape_handler.clone(), + container.authentication_service.clone(), + http_stats_event_sender.clone(), + )); + + scrape_service + .handle_scrape(&scrape_request, &client_ip_sources, &server_service_binding, None) + .await + .unwrap(); + } + } +} diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs new file mode 100644 index 000000000..37c7a26b5 --- /dev/null +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -0,0 +1,166 @@ +use std::sync::Arc; + +use torrust_tracker_metrics::label::{LabelSet, LabelValue}; +use torrust_tracker_metrics::{label_name, metric_name}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::Event; +use crate::statistics::repository::Repository; +use crate::statistics::HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; + +pub async fn handle_event(event: Event, stats_repository: &Arc, now: DurationSinceUnixEpoch) { + match event { + Event::TcpAnnounce { connection, .. } => { + let mut label_set = LabelSet::from(connection); + label_set.upsert(label_name!("request_kind"), LabelValue::new("announce")); + + match stats_repository + .increase_counter(&metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) + .await + { + Ok(()) => { + tracing::debug!( + "Successfully increased the counter for HTTP announce requests received: {}", + label_set + ); + } + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; + } + Event::TcpScrape { connection } => { + let mut label_set = LabelSet::from(connection); + label_set.upsert(label_name!("request_kind"), LabelValue::new("scrape")); + + match stats_repository + .increase_counter(&metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) + .await + { + Ok(()) => { + tracing::debug!( + "Successfully increased the counter for HTTP scrape requests received: {}", + label_set + ); + } + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; + } + } + + tracing::debug!("stats: {:?}", stats_repository.get_stats().await); +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::sync::Arc; + + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{RemoteClientAddr, ResolvedIp}; + use torrust_tracker_clock::clock::Time; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event}; + use crate::statistics::event::handler::handle_event; + use crate::statistics::repository::Repository; + use crate::tests::{sample_info_hash, sample_peer_using_ipv4, sample_peer_using_ipv6}; + use crate::CurrentClock; + + #[tokio::test] + async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() { + let stats_repository = Arc::new(Repository::new()); + let peer = sample_peer_using_ipv4(); + let remote_client_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)); + + handle_event( + Event::TcpAnnounce { + connection: ConnectionContext::new( + RemoteClientAddr::new(ResolvedIp::FromSocketAddr(remote_client_ip), Some(8080)), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(), + ), + info_hash: sample_info_hash(), + announcement: peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp4_announces_handled(), 1); + } + + #[tokio::test] + async fn should_increase_the_tcp4_scrapes_counter_when_it_receives_a_tcp4_scrape_event() { + let stats_repository = Arc::new(Repository::new()); + + handle_event( + Event::TcpScrape { + connection: ConnectionContext::new( + RemoteClientAddr::new( + ResolvedIp::FromSocketAddr(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2))), + Some(8080), + ), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(), + ), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp4_scrapes_handled(), 1); + } + + #[tokio::test] + async fn should_increase_the_tcp6_announces_counter_when_it_receives_a_tcp6_announce_event() { + let stats_repository = Arc::new(Repository::new()); + let peer = sample_peer_using_ipv6(); + let remote_client_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); + + handle_event( + Event::TcpAnnounce { + connection: ConnectionContext::new( + RemoteClientAddr::new(ResolvedIp::FromSocketAddr(remote_client_ip), Some(8080)), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 7070)).unwrap(), + ), + info_hash: sample_info_hash(), + announcement: peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp6_announces_handled(), 1); + } + + #[tokio::test] + async fn should_increase_the_tcp6_scrapes_counter_when_it_receives_a_tcp6_scrape_event() { + let stats_repository = Arc::new(Repository::new()); + + handle_event( + Event::TcpScrape { + connection: ConnectionContext::new( + RemoteClientAddr::new( + ResolvedIp::FromSocketAddr(IpAddr::V6(Ipv6Addr::new( + 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, + ))), + Some(8080), + ), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 7070)).unwrap(), + ), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp6_scrapes_handled(), 1); + } +} diff --git a/packages/http-tracker-core/src/statistics/event/listener.rs b/packages/http-tracker-core/src/statistics/event/listener.rs new file mode 100644 index 000000000..ff2937a59 --- /dev/null +++ b/packages/http-tracker-core/src/statistics/event/listener.rs @@ -0,0 +1,58 @@ +use std::sync::Arc; + +use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_events::receiver::RecvError; + +use super::handler::handle_event; +use crate::event::receiver::Receiver; +use crate::statistics::repository::Repository; +use crate::{CurrentClock, HTTP_TRACKER_LOG_TARGET}; + +#[must_use] +pub fn run_event_listener( + receiver: Receiver, + cancellation_token: CancellationToken, + repository: &Arc, +) -> JoinHandle<()> { + let stats_repository = repository.clone(); + + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting HTTP tracker core event listener"); + + tokio::spawn(async move { + dispatch_events(receiver, cancellation_token, stats_repository).await; + + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "HTTP tracker core event listener finished"); + }) +} + +async fn dispatch_events(mut receiver: Receiver, cancellation_token: CancellationToken, stats_repository: Arc) { + loop { + tokio::select! { + biased; + + () = cancellation_token.cancelled() => { + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Received cancellation request, shutting down HTTP tracker core event listener."); + break; + } + + result = receiver.recv() => { + match result { + Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, + Err(e) => { + match e { + RecvError::Closed => { + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Http tracker core statistics receiver closed."); + break; + } + RecvError::Lagged(n) => { + tracing::warn!(target: HTTP_TRACKER_LOG_TARGET, "Http tracker core statistics receiver lagged by {} events.", n); + } + } + } + } + } + } + } +} diff --git a/packages/http-tracker-core/src/statistics/event/mod.rs b/packages/http-tracker-core/src/statistics/event/mod.rs new file mode 100644 index 000000000..dae683398 --- /dev/null +++ b/packages/http-tracker-core/src/statistics/event/mod.rs @@ -0,0 +1,2 @@ +pub mod handler; +pub mod listener; diff --git a/packages/http-tracker-core/src/statistics/metrics.rs b/packages/http-tracker-core/src/statistics/metrics.rs new file mode 100644 index 000000000..00d09b803 --- /dev/null +++ b/packages/http-tracker-core/src/statistics/metrics.rs @@ -0,0 +1,97 @@ +use serde::Serialize; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::aggregate::sum::Sum; +use torrust_tracker_metrics::metric_collection::{Error, MetricCollection}; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::statistics::HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; + +/// Metrics collected by the tracker. +#[derive(Debug, Clone, PartialEq, Default, Serialize)] +pub struct Metrics { + /// A collection of metrics. + pub metric_collection: MetricCollection, +} + +impl Metrics { + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn increase_counter( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.increment_counter(metric_name, labels, now) + } + + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn set_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.set_gauge(metric_name, labels, value, now) + } +} + +impl Metrics { + /// Total number of TCP (HTTP tracker) `announce` requests from IPv4 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn tcp4_announces_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "announce")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of TCP (HTTP tracker) `scrape` requests from IPv4 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn tcp4_scrapes_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn tcp6_announces_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn tcp6_scrapes_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "scrape")].into(), + ) + .unwrap_or_default() as u64 + } +} diff --git a/packages/http-tracker-core/src/statistics/mod.rs b/packages/http-tracker-core/src/statistics/mod.rs new file mode 100644 index 000000000..3ae355471 --- /dev/null +++ b/packages/http-tracker-core/src/statistics/mod.rs @@ -0,0 +1,23 @@ +pub mod event; +pub mod metrics; +pub mod repository; + +use metrics::Metrics; +use torrust_tracker_metrics::metric::description::MetricDescription; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_metrics::unit::Unit; + +pub const HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL: &str = "http_tracker_core_requests_received_total"; + +#[must_use] +pub fn describe_metrics() -> Metrics { + let mut metrics = Metrics::default(); + + metrics.metric_collection.describe_counter( + &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("Total number of HTTP requests received")), + ); + + metrics +} diff --git a/packages/http-tracker-core/src/statistics/repository.rs b/packages/http-tracker-core/src/statistics/repository.rs new file mode 100644 index 000000000..ea027f5c6 --- /dev/null +++ b/packages/http-tracker-core/src/statistics/repository.rs @@ -0,0 +1,54 @@ +use std::sync::Arc; + +use tokio::sync::{RwLock, RwLockReadGuard}; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::Error; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::describe_metrics; +use super::metrics::Metrics; + +/// A repository for the tracker metrics. +#[derive(Clone)] +pub struct Repository { + pub stats: Arc>, +} + +impl Default for Repository { + fn default() -> Self { + Self::new() + } +} + +impl Repository { + #[must_use] + pub fn new() -> Self { + let stats = Arc::new(RwLock::new(describe_metrics())); + + Self { stats } + } + + pub async fn get_stats(&self) -> RwLockReadGuard<'_, Metrics> { + self.stats.read().await + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increase the counter. + pub async fn increase_counter( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.increase_counter(metric_name, labels, now); + + drop(stats_lock); + + result + } +} diff --git a/packages/located-error/Cargo.toml b/packages/located-error/Cargo.toml index acd13def3..232a6113f 100644 --- a/packages/located-error/Cargo.toml +++ b/packages/located-error/Cargo.toml @@ -1,14 +1,21 @@ [package] -name = "torrust-tracker-located-error" description = "A library to provide error decorator with the location and the source of the original error." -license = "AGPL-3.0" -version.workspace = true +keywords = [ "errors", "helper", "library" ] +name = "torrust-tracker-located-error" +readme = "README.md" + authors.workspace = true +documentation.workspace = true edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true [dependencies] -log = { version = "0.4", features = ["release_max_level_info"] } +tracing = "0" [dev-dependencies] -thiserror = "1.0" - +thiserror = "2" diff --git a/packages/located-error/src/lib.rs b/packages/located-error/src/lib.rs index 67c432528..09bfbd185 100644 --- a/packages/located-error/src/lib.rs +++ b/packages/located-error/src/lib.rs @@ -23,7 +23,7 @@ //! let b: LocatedError = Located(e).into(); //! let l = get_caller_location(); //! -//! assert!(b.to_string().contains("Test, src/lib.rs")); +//! assert!(b.to_string().contains("src/lib.rs")); //! ``` //! //! # Credits @@ -33,6 +33,8 @@ use std::error::Error; use std::panic::Location; use std::sync::Arc; +pub type DynError = Arc; + /// A generic wrapper around an error. /// /// Where `E` is the inner error (source error). @@ -48,7 +50,7 @@ where location: Box>, } -impl<'a, E> std::fmt::Display for LocatedError<'a, E> +impl std::fmt::Display for LocatedError<'_, E> where E: Error + ?Sized + Send + Sync, { @@ -57,7 +59,7 @@ where } } -impl<'a, E> Error for LocatedError<'a, E> +impl Error for LocatedError<'_, E> where E: Error + ?Sized + Send + Sync + 'static, { @@ -66,7 +68,7 @@ where } } -impl<'a, E> Clone for LocatedError<'a, E> +impl Clone for LocatedError<'_, E> where E: Error + ?Sized + Send + Sync, { @@ -90,13 +92,13 @@ where source: Arc::new(self.0), location: Box::new(*std::panic::Location::caller()), }; - log::debug!("{e}"); + tracing::debug!("{e}"); e } } #[allow(clippy::from_over_into)] -impl<'a> Into> for Arc { +impl<'a> Into> for DynError { #[track_caller] fn into(self) -> LocatedError<'a, dyn std::error::Error + Send + Sync> { LocatedError { @@ -128,7 +130,7 @@ mod tests { fn error_should_include_location() { let e = TestError::Test; - let b: LocatedError = Located(e).into(); + let b: LocatedError<'_, TestError> = Located(e).into(); let l = get_caller_location(); assert_eq!(b.location.file(), l.file()); diff --git a/packages/metrics/.gitignore b/packages/metrics/.gitignore new file mode 100644 index 000000000..6350e9868 --- /dev/null +++ b/packages/metrics/.gitignore @@ -0,0 +1 @@ +.coverage diff --git a/packages/metrics/Cargo.toml b/packages/metrics/Cargo.toml new file mode 100644 index 000000000..b6d327d70 --- /dev/null +++ b/packages/metrics/Cargo.toml @@ -0,0 +1,30 @@ +[package] +description = "A library with the primitive types shared by the Torrust tracker packages." +keywords = [ "api", "library", "metrics" ] +name = "torrust-tracker-metrics" +readme = "README.md" + +authors.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +chrono = { version = "0", default-features = false, features = [ "clock" ] } +derive_more = { version = "2", features = [ "constructor" ] } +serde = { version = "1", features = [ "derive" ] } +serde_json = "1.0.140" +thiserror = "2" +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +tracing = "0.1.41" + +[dev-dependencies] +approx = "0.5.1" +formatjson = "0.3.1" +pretty_assertions = "1.4.1" +rstest = "0.25.0" diff --git a/packages/metrics/LICENSE b/packages/metrics/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/metrics/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/metrics/README.md b/packages/metrics/README.md new file mode 100644 index 000000000..3d1d94c5f --- /dev/null +++ b/packages/metrics/README.md @@ -0,0 +1,210 @@ +# Torrust Tracker Metrics + +A comprehensive metrics library providing type-safe metric collection, aggregation, and Prometheus export functionality for the [Torrust Tracker](https://github.com/torrust/torrust-tracker) ecosystem. + +## Overview + +This library offers a robust metrics system designed specifically for tracking and monitoring BitTorrent tracker performance. It provides type-safe metric collection with support for labels, time-series data, and multiple export formats including Prometheus. + +## Key Features + +- **Type-Safe Metrics**: Strongly typed `Counter` and `Gauge` metrics with compile-time guarantees +- **Label Support**: Rich labeling system for multi-dimensional metrics +- **Time-Series Data**: Built-in support for timestamped samples +- **Prometheus Export**: Native Prometheus format serialization +- **Aggregation Functions**: Sum operations with mathematically appropriate return types +- **JSON Serialization**: Full serde support for all metric types +- **Memory Efficient**: Optimized data structures for high-performance scenarios + +## Quick Start + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +torrust-tracker-metrics = "3.0.0" +``` + +### Basic Usage + +```rust +use torrust_tracker_metrics::{ + metric_collection::MetricCollection, + label::{LabelSet, LabelValue}, + metric_name, label_name, +}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +// Create a metric collection +let mut metrics = MetricCollection::default(); + +// Define labels +let labels: LabelSet = [ + (label_name!("server"), LabelValue::new("tracker-01")), + (label_name!("protocol"), LabelValue::new("http")), +].into(); + +// Record metrics +let time = DurationSinceUnixEpoch::from_secs(1234567890); +metrics.increment_counter( + &metric_name!("requests_total"), + &labels, + time, +)?; + +metrics.set_gauge( + &metric_name!("active_connections"), + &labels, + 42.0, + time, +)?; + +// Export to Prometheus format +let prometheus_output = metrics.to_prometheus(); +println!("{}", prometheus_output); +``` + +### Metric Aggregation + +```rust +use torrust_tracker_metrics::metric_collection::aggregate::{Sum, Avg}; + +// Sum all counter values matching specific labels +let total_requests = metrics.sum( + &metric_name!("requests_total"), + &[("server", "tracker-01")].into(), +); + +println!("Total requests: {:?}", total_requests); + +// Calculate average of gauge values matching specific labels +let avg_response_time = metrics.avg( + &metric_name!("response_time_seconds"), + &[("endpoint", "/announce")].into(), +); + +println!("Average response time: {:?}", avg_response_time); +``` + +## Architecture + +### Core Components + +- **`Counter`**: Monotonically increasing integer values (u64) +- **`Gauge`**: Arbitrary floating-point values that can increase or decrease (f64) +- **`Metric`**: Generic metric container with metadata (name, description, unit) +- **`MetricCollection`**: Type-safe collection managing both counters and gauges +- **`LabelSet`**: Key-value pairs for metric dimensionality +- **`Sample`**: Timestamped metric values with associated labels + +### Type System + +The library uses Rust's type system to ensure metric safety: + +```rust +// Counter operations return u64 +let counter_sum: Option = counter_collection.sum(&name, &labels); + +// Gauge operations return f64 +let gauge_sum: Option = gauge_collection.sum(&name, &labels); + +// Mixed collections convert to f64 for compatibility +let mixed_sum: Option = metric_collection.sum(&name, &labels); +``` + +### Module Structure + +```output +src/ +├── counter.rs # Counter metric type +├── gauge.rs # Gauge metric type +├── metric/ # Generic metric container +│ ├── mod.rs +│ ├── name.rs # Metric naming +│ ├── description.rs # Metric descriptions +│ └── aggregate/ # Metric-level aggregations +├── metric_collection/ # Collection management +│ ├── mod.rs +│ └── aggregate/ # Collection-level aggregations +├── label/ # Label system +│ ├── name.rs # Label names +│ ├── value.rs # Label values +│ └── set.rs # Label collections +├── sample.rs # Timestamped values +├── sample_collection.rs # Sample management +├── prometheus.rs # Prometheus export +└── unit.rs # Measurement units +``` + +## Documentation + +- [Crate documentation](https://docs.rs/torrust-tracker-metrics) +- [API Reference](https://docs.rs/torrust-tracker-metrics/latest/torrust_tracker_metrics/) + +## Development + +### Code Coverage + +Run basic coverage report: + +```console +cargo llvm-cov --package torrust-tracker-metrics +``` + +Generate LCOV report (for IDE integration): + +```console +mkdir -p ./.coverage +cargo llvm-cov --package torrust-tracker-metrics --lcov --output-path=./.coverage/lcov.info +``` + +Generate detailed HTML coverage report: + +Generate detailed HTML coverage report: + +```console +mkdir -p ./.coverage +cargo llvm-cov --package torrust-tracker-metrics --html --output-dir ./.coverage +``` + +Open the coverage report in your browser: + +```console +open ./.coverage/index.html # macOS +xdg-open ./.coverage/index.html # Linux +``` + +## Performance Considerations + +- **Memory Usage**: Metrics are stored in-memory with efficient HashMap-based collections +- **Label Cardinality**: Be mindful of label combinations as they create separate time series +- **Aggregation**: Sum operations are optimized for both single-type and mixed collections + +## Compatibility + +This library is designed to be compatible with the standard Rust [metrics](https://crates.io/crates/metrics) crate ecosystem where possible. + +## Contributing + +We welcome contributions! Please see the main [Torrust Tracker repository](https://github.com/torrust/torrust-tracker) for contribution guidelines. + +### Reporting Issues + +- [Bug Reports](https://github.com/torrust/torrust-tracker/issues/new?template=bug_report.md) +- [Feature Requests](https://github.com/torrust/torrust-tracker/issues/new?template=feature_request.md) + +## Acknowledgements + +This library draws inspiration from the Rust [metrics](https://crates.io/crates/metrics) crate, incorporating compatible APIs and naming conventions where possible. We may consider migrating to the standard metrics crate in future versions while maintaining our specialized functionality. + +Special thanks to the Rust metrics ecosystem contributors for establishing excellent patterns for metrics collection and export. + +## License + +This project is licensed under the [GNU AFFERO GENERAL PUBLIC LICENSE v3.0](./LICENSE). + +## Related Projects + +- [Torrust Tracker](https://github.com/torrust/torrust-tracker) - The main BitTorrent tracker +- [metrics](https://crates.io/crates/metrics) - Standard Rust metrics facade +- [prometheus](https://crates.io/crates/prometheus) - Prometheus client library diff --git a/packages/metrics/cSpell.json b/packages/metrics/cSpell.json new file mode 100644 index 000000000..8f5002833 --- /dev/null +++ b/packages/metrics/cSpell.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://raw.githubusercontent.com/streetsidesoftware/cspell/main/cspell.schema.json", + "version": "0.2", + "dictionaryDefinitions": [ + { + "name": "project-words", + "path": "../../project-words.txt", + "addWords": true + } + ], + "dictionaries": ["project-words"], + "enableFiletypes": [ + "dockerfile", + "shellscript", + "toml" + ], + "ignorePaths": [ + "target", + "/project-words.txt" + ] +} diff --git a/packages/metrics/src/counter.rs b/packages/metrics/src/counter.rs new file mode 100644 index 000000000..0e2002181 --- /dev/null +++ b/packages/metrics/src/counter.rs @@ -0,0 +1,266 @@ +use derive_more::Display; +use serde::{Deserialize, Serialize}; + +use super::prometheus::PrometheusSerializable; + +#[derive(Debug, Display, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Counter(u64); + +impl Counter { + #[must_use] + pub fn new(value: u64) -> Self { + Self(value) + } + + #[must_use] + pub fn value(&self) -> u64 { + self.0 + } + + #[must_use] + pub fn primitive(&self) -> u64 { + self.value() + } + + pub fn increment(&mut self, value: u64) { + self.0 += value; + } + + pub fn absolute(&mut self, value: u64) { + self.0 = value; + } +} + +impl From for Counter { + fn from(value: u32) -> Self { + Self(u64::from(value)) + } +} + +impl From for Counter { + fn from(value: u64) -> Self { + Self(value) + } +} + +impl From for Counter { + fn from(value: i32) -> Self { + #[allow(clippy::cast_sign_loss)] + Self(value as u64) + } +} + +impl From for u64 { + fn from(counter: Counter) -> Self { + counter.value() + } +} + +impl PrometheusSerializable for Counter { + fn to_prometheus(&self) -> String { + format!("{}", self.value()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_should_be_created_from_integer_values() { + let counter = Counter::new(0); + assert_eq!(counter.value(), 0); + } + + #[test] + fn it_could_be_converted_from_u64() { + let counter: Counter = 42.into(); + assert_eq!(counter.value(), 42); + } + + #[test] + fn it_could_be_converted_into_u64() { + let counter = Counter::new(42); + let value: u64 = counter.into(); + assert_eq!(value, 42); + } + + #[test] + fn it_could_be_incremented() { + let mut counter = Counter::new(0); + counter.increment(1); + assert_eq!(counter.value(), 1); + + counter.increment(2); + assert_eq!(counter.value(), 3); + } + + #[test] + fn it_could_set_to_an_absolute_value() { + let mut counter = Counter::new(0); + counter.absolute(1); + assert_eq!(counter.value(), 1); + } + + #[test] + fn it_serializes_to_prometheus() { + let counter = Counter::new(42); + assert_eq!(counter.to_prometheus(), "42"); + } + + #[test] + fn it_could_be_converted_from_u32() { + let counter: Counter = 42u32.into(); + assert_eq!(counter.value(), 42); + } + + #[test] + fn it_could_be_converted_from_i32() { + let counter: Counter = 42i32.into(); + assert_eq!(counter.value(), 42); + } + + #[test] + fn it_should_return_primitive_value() { + let counter = Counter::new(123); + assert_eq!(counter.primitive(), 123); + } + + #[test] + fn it_should_handle_zero_value() { + let counter = Counter::new(0); + assert_eq!(counter.value(), 0); + assert_eq!(counter.primitive(), 0); + } + + #[test] + fn it_should_handle_large_values() { + let counter = Counter::new(u64::MAX); + assert_eq!(counter.value(), u64::MAX); + } + + #[test] + fn it_should_handle_u32_max_conversion() { + let counter: Counter = u32::MAX.into(); + assert_eq!(counter.value(), u64::from(u32::MAX)); + } + + #[test] + fn it_should_handle_i32_max_conversion() { + let counter: Counter = i32::MAX.into(); + assert_eq!(counter.value(), i32::MAX as u64); + } + + #[test] + fn it_should_handle_negative_i32_conversion() { + let counter: Counter = (-42i32).into(); + #[allow(clippy::cast_sign_loss)] + let expected = (-42i32) as u64; + assert_eq!(counter.value(), expected); + } + + #[test] + fn it_should_handle_i32_min_conversion() { + let counter: Counter = i32::MIN.into(); + #[allow(clippy::cast_sign_loss)] + let expected = i32::MIN as u64; + assert_eq!(counter.value(), expected); + } + + #[test] + fn it_should_handle_large_increments() { + let mut counter = Counter::new(100); + counter.increment(1000); + assert_eq!(counter.value(), 1100); + + counter.increment(u64::MAX - 1100); + assert_eq!(counter.value(), u64::MAX); + } + + #[test] + fn it_should_support_multiple_absolute_operations() { + let mut counter = Counter::new(0); + + counter.absolute(100); + assert_eq!(counter.value(), 100); + + counter.absolute(50); + assert_eq!(counter.value(), 50); + + counter.absolute(0); + assert_eq!(counter.value(), 0); + } + + #[test] + fn it_should_be_displayable() { + let counter = Counter::new(42); + assert_eq!(counter.to_string(), "42"); + + let counter = Counter::new(0); + assert_eq!(counter.to_string(), "0"); + } + + #[test] + fn it_should_be_debuggable() { + let counter = Counter::new(42); + let debug_string = format!("{counter:?}"); + assert_eq!(debug_string, "Counter(42)"); + } + + #[test] + fn it_should_be_cloneable() { + let counter = Counter::new(42); + let cloned_counter = counter.clone(); + assert_eq!(counter, cloned_counter); + assert_eq!(counter.value(), cloned_counter.value()); + } + + #[test] + fn it_should_support_equality_comparison() { + let counter1 = Counter::new(42); + let counter2 = Counter::new(42); + let counter3 = Counter::new(43); + + assert_eq!(counter1, counter2); + assert_ne!(counter1, counter3); + } + + #[test] + fn it_should_have_default_value() { + let counter = Counter::default(); + assert_eq!(counter.value(), 0); + } + + #[test] + fn it_should_handle_conversion_roundtrip() { + let original_value = 12345u64; + let counter = Counter::from(original_value); + let converted_back: u64 = counter.into(); + assert_eq!(original_value, converted_back); + } + + #[test] + fn it_should_handle_u32_conversion_roundtrip() { + let original_value = 12345u32; + let counter = Counter::from(original_value); + assert_eq!(counter.value(), u64::from(original_value)); + } + + #[test] + fn it_should_handle_i32_conversion_roundtrip() { + let original_value = 12345i32; + let counter = Counter::from(original_value); + #[allow(clippy::cast_sign_loss)] + let expected = original_value as u64; + assert_eq!(counter.value(), expected); + } + + #[test] + fn it_should_serialize_large_values_to_prometheus() { + let counter = Counter::new(u64::MAX); + assert_eq!(counter.to_prometheus(), u64::MAX.to_string()); + + let counter = Counter::new(0); + assert_eq!(counter.to_prometheus(), "0"); + } +} diff --git a/packages/metrics/src/gauge.rs b/packages/metrics/src/gauge.rs new file mode 100644 index 000000000..d0883715b --- /dev/null +++ b/packages/metrics/src/gauge.rs @@ -0,0 +1,240 @@ +use derive_more::Display; +use serde::{Deserialize, Serialize}; + +use super::prometheus::PrometheusSerializable; + +#[derive(Debug, Display, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Gauge(f64); + +impl Gauge { + #[must_use] + pub fn new(value: f64) -> Self { + Self(value) + } + + #[must_use] + pub fn value(&self) -> f64 { + self.0 + } + + #[must_use] + pub fn primitive(&self) -> f64 { + self.value() + } + + pub fn set(&mut self, value: f64) { + self.0 = value; + } + + pub fn increment(&mut self, value: f64) { + self.0 += value; + } + + pub fn decrement(&mut self, value: f64) { + self.0 -= value; + } +} + +impl From for Gauge { + fn from(value: f32) -> Self { + Self(f64::from(value)) + } +} + +impl From for Gauge { + fn from(value: f64) -> Self { + Self(value) + } +} + +impl From for f64 { + fn from(counter: Gauge) -> Self { + counter.value() + } +} + +impl PrometheusSerializable for Gauge { + fn to_prometheus(&self) -> String { + format!("{}", self.value()) + } +} + +#[cfg(test)] +mod tests { + use approx::assert_relative_eq; + + use super::*; + + #[test] + fn it_should_be_created_from_integer_values() { + let gauge = Gauge::new(0.0); + assert_relative_eq!(gauge.value(), 0.0); + } + + #[test] + fn it_could_be_converted_from_u64() { + let gauge: Gauge = 42.0.into(); + assert_relative_eq!(gauge.value(), 42.0); + } + + #[test] + fn it_could_be_converted_into_i64() { + let gauge = Gauge::new(42.0); + let value: f64 = gauge.into(); + assert_relative_eq!(value, 42.0); + } + + #[test] + fn it_could_be_set() { + let mut gauge = Gauge::new(0.0); + gauge.set(1.0); + assert_relative_eq!(gauge.value(), 1.0); + } + + #[test] + fn it_could_be_incremented() { + let mut gauge = Gauge::new(0.0); + gauge.increment(1.0); + assert_relative_eq!(gauge.value(), 1.0); + } + + #[test] + fn it_could_be_decremented() { + let mut gauge = Gauge::new(1.0); + gauge.decrement(1.0); + assert_relative_eq!(gauge.value(), 0.0); + } + + #[test] + fn it_serializes_to_prometheus() { + let counter = Gauge::new(42.0); + assert_eq!(counter.to_prometheus(), "42"); + + let counter = Gauge::new(42.1); + assert_eq!(counter.to_prometheus(), "42.1"); + } + + #[test] + fn it_could_be_converted_from_f32() { + let gauge: Gauge = 42.5f32.into(); + assert_relative_eq!(gauge.value(), 42.5); + } + + #[test] + fn it_should_return_primitive_value() { + let gauge = Gauge::new(123.456); + assert_relative_eq!(gauge.primitive(), 123.456); + } + + #[test] + fn it_should_handle_zero_value() { + let gauge = Gauge::new(0.0); + assert_relative_eq!(gauge.value(), 0.0); + assert_relative_eq!(gauge.primitive(), 0.0); + } + + #[test] + fn it_should_handle_negative_values() { + let gauge = Gauge::new(-42.5); + assert_relative_eq!(gauge.value(), -42.5); + } + + #[test] + fn it_should_handle_large_values() { + let gauge = Gauge::new(f64::MAX); + assert_relative_eq!(gauge.value(), f64::MAX); + } + + #[test] + fn it_should_handle_infinity() { + let gauge = Gauge::new(f64::INFINITY); + assert_relative_eq!(gauge.value(), f64::INFINITY); + } + + #[test] + fn it_should_handle_nan() { + let gauge = Gauge::new(f64::NAN); + assert!(gauge.value().is_nan()); + } + + #[test] + fn it_should_be_displayable() { + let gauge = Gauge::new(42.5); + assert_eq!(gauge.to_string(), "42.5"); + + let gauge = Gauge::new(0.0); + assert_eq!(gauge.to_string(), "0"); + } + + #[test] + fn it_should_be_debuggable() { + let gauge = Gauge::new(42.5); + let debug_string = format!("{gauge:?}"); + assert_eq!(debug_string, "Gauge(42.5)"); + } + + #[test] + fn it_should_be_cloneable() { + let gauge = Gauge::new(42.5); + let cloned_gauge = gauge.clone(); + assert_eq!(gauge, cloned_gauge); + assert_relative_eq!(gauge.value(), cloned_gauge.value()); + } + + #[test] + fn it_should_support_equality_comparison() { + let gauge1 = Gauge::new(42.5); + let gauge2 = Gauge::new(42.5); + let gauge3 = Gauge::new(43.0); + + assert_eq!(gauge1, gauge2); + assert_ne!(gauge1, gauge3); + } + + #[test] + fn it_should_have_default_value() { + let gauge = Gauge::default(); + assert_relative_eq!(gauge.value(), 0.0); + } + + #[test] + fn it_should_handle_conversion_roundtrip() { + let original_value = 12345.678; + let gauge = Gauge::from(original_value); + let converted_back: f64 = gauge.into(); + assert_relative_eq!(original_value, converted_back); + } + + #[test] + fn it_should_handle_f32_conversion_roundtrip() { + let original_value = 12345.5f32; + let gauge = Gauge::from(original_value); + assert_relative_eq!(gauge.value(), f64::from(original_value)); + } + + #[test] + fn it_should_handle_multiple_operations() { + let mut gauge = Gauge::new(100.0); + + gauge.increment(50.0); + assert_relative_eq!(gauge.value(), 150.0); + + gauge.decrement(25.0); + assert_relative_eq!(gauge.value(), 125.0); + + gauge.set(200.0); + assert_relative_eq!(gauge.value(), 200.0); + } + + #[test] + fn it_should_serialize_special_values_to_prometheus() { + let gauge = Gauge::new(f64::INFINITY); + assert_eq!(gauge.to_prometheus(), "inf"); + + let gauge = Gauge::new(f64::NEG_INFINITY); + assert_eq!(gauge.to_prometheus(), "-inf"); + + let gauge = Gauge::new(f64::NAN); + assert_eq!(gauge.to_prometheus(), "NaN"); + } +} diff --git a/packages/metrics/src/label/mod.rs b/packages/metrics/src/label/mod.rs new file mode 100644 index 000000000..880fdbbb1 --- /dev/null +++ b/packages/metrics/src/label/mod.rs @@ -0,0 +1,9 @@ +pub mod name; +mod pair; +mod set; +pub mod value; + +pub type LabelName = name::LabelName; +pub type LabelValue = value::LabelValue; +pub type LabelPair = pair::LabelPair; +pub type LabelSet = set::LabelSet; diff --git a/packages/metrics/src/label/name.rs b/packages/metrics/src/label/name.rs new file mode 100644 index 000000000..194aeb2b3 --- /dev/null +++ b/packages/metrics/src/label/name.rs @@ -0,0 +1,126 @@ +use derive_more::Display; +use serde::{Deserialize, Serialize}; + +use crate::prometheus::PrometheusSerializable; + +#[derive(Debug, Display, Clone, Eq, PartialEq, Default, Deserialize, Serialize, Hash, Ord, PartialOrd)] +pub struct LabelName(String); + +impl LabelName { + /// Creates a new `LabelName` instance. + /// + /// # Panics + /// + /// Panics if the provided name is empty. + #[must_use] + pub fn new(name: &str) -> Self { + assert!(!name.is_empty(), "Label name cannot be empty."); + Self(name.to_owned()) + } +} + +impl PrometheusSerializable for LabelName { + /// In Prometheus: + /// + /// - Labels may contain ASCII letters, numbers, as well as underscores. + /// They must match the regex [a-zA-Z_][a-zA-Z0-9_]*. + /// - Label names beginning with __ (two "_") are reserved for internal + /// use. + /// - Label values may contain any Unicode characters. + /// - Labels with an empty label value are considered equivalent to + /// labels that do not exist. + /// + /// The label name is changed: + /// + /// - If a label name starts with, or contains, an invalid character: + /// replace character with underscore. + /// - If th label name starts with two underscores: + /// add additional underscore (three underscores total) + fn to_prometheus(&self) -> String { + // Replace invalid characters with underscore + let processed: String = self + .0 + .chars() + .enumerate() + .map(|(i, c)| { + if i == 0 { + if c.is_ascii_alphabetic() || c == '_' { + c + } else { + '_' + } + } else if c.is_ascii_alphanumeric() || c == '_' { + c + } else { + '_' + } + }) + .collect(); + + // If the label name starts with two underscores, add an additional + if processed.starts_with("__") && !processed.starts_with("___") { + format!("_{processed}") + } else { + processed + } + } +} + +#[macro_export] +macro_rules! label_name { + ("") => { + compile_error!("Label name cannot be empty"); + }; + ($name:literal) => { + $crate::label::name::LabelName::new($name) + }; + ($name:ident) => { + $crate::label::name::LabelName::new($name) + }; +} +#[cfg(test)] +mod tests { + mod serialization_of_label_name_to_prometheus { + use rstest::rstest; + + use crate::label::LabelName; + use crate::prometheus::PrometheusSerializable; + + #[rstest] + #[case("1 valid name", "valid_name", "valid_name")] + #[case("2 leading underscore", "_leading_underscore", "_leading_underscore")] + #[case("3 leading lowercase", "v123", "v123")] + #[case("4 leading uppercase", "V123", "V123")] + fn valid_names_in_prometheus(#[case] case: &str, #[case] input: &str, #[case] output: &str) { + assert_eq!(label_name!(input).to_prometheus(), output, "{case} failed: {input:?}"); + } + + #[rstest] + #[case("1 invalid start 1", "9invalid_start", "_invalid_start")] + #[case("2 invalid start 2", "@test", "_test")] + #[case("3 invalid dash", "invalid-char", "invalid_char")] + #[case("4 invalid spaces", "spaces are bad", "spaces_are_bad")] + #[case("5 invalid special chars", "a!b@c#d$e%f^g&h*i(j)", "a_b_c_d_e_f_g_h_i_j_")] + #[case("6 invalid colon", "my:metric/version", "my_metric_version")] + #[case("7 all invalid characters", "!@#$%^&*()", "__________")] + #[case("8 non_ascii_characters", "ñaca©", "_aca_")] + fn names_that_need_changes_in_prometheus(#[case] case: &str, #[case] input: &str, #[case] output: &str) { + assert_eq!(label_name!(input).to_prometheus(), output, "{case} failed: {input:?}"); + } + + #[rstest] + #[case("1 double underscore start", "__private", "___private")] + #[case("2 double underscore only", "__", "___")] + #[case("3 processed to double underscore", "^^name", "___name")] + #[case("4 processed to double underscore after first char", "0__name", "___name")] + fn names_starting_with_double_underscore(#[case] case: &str, #[case] input: &str, #[case] output: &str) { + assert_eq!(label_name!(input).to_prometheus(), output, "{case} failed: {input:?}"); + } + + #[test] + #[should_panic(expected = "Label name cannot be empty.")] + fn empty_name() { + let _name = LabelName::new(""); + } + } +} diff --git a/packages/metrics/src/label/pair.rs b/packages/metrics/src/label/pair.rs new file mode 100644 index 000000000..858902451 --- /dev/null +++ b/packages/metrics/src/label/pair.rs @@ -0,0 +1,29 @@ +use super::{LabelName, LabelValue}; +use crate::prometheus::PrometheusSerializable; + +pub type LabelPair = (LabelName, LabelValue); + +// Generic implementation for any tuple (A, B) where A and B implement PrometheusSerializable +impl PrometheusSerializable for (A, B) { + fn to_prometheus(&self) -> String { + format!("{}=\"{}\"", self.0.to_prometheus(), self.1.to_prometheus()) + } +} + +#[cfg(test)] +mod tests { + mod serialization_of_label_pair_to_prometheus { + use crate::label::LabelValue; + use crate::label_name; + use crate::prometheus::PrometheusSerializable; + + #[test] + fn test_label_pair_serialization_to_prometheus() { + let label_pair = (label_name!("label_name"), LabelValue::new("value")); + assert_eq!(label_pair.to_prometheus(), r#"label_name="value""#); + + let label_pair = (&label_name!("label_name"), &LabelValue::new("value")); + assert_eq!(label_pair.to_prometheus(), r#"label_name="value""#); + } + } +} diff --git a/packages/metrics/src/label/set.rs b/packages/metrics/src/label/set.rs new file mode 100644 index 000000000..46256e4d5 --- /dev/null +++ b/packages/metrics/src/label/set.rs @@ -0,0 +1,584 @@ +use std::collections::btree_map::Iter; +use std::collections::BTreeMap; +use std::fmt::Display; + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +use super::{LabelName, LabelPair, LabelValue}; +use crate::prometheus::PrometheusSerializable; + +#[derive(Debug, Clone, Eq, PartialEq, Default, Ord, PartialOrd, Hash)] +pub struct LabelSet { + items: BTreeMap, +} + +impl LabelSet { + #[must_use] + pub fn empty() -> Self { + Self { items: BTreeMap::new() } + } + + /// Insert a new label pair or update the value of an existing label. + pub fn upsert(&mut self, name: LabelName, value: LabelValue) { + self.items.insert(name, value); + } + + pub fn is_empty(&self) -> bool { + self.items.is_empty() + } + + pub fn contains_pair(&self, name: &LabelName, value: &LabelValue) -> bool { + match self.items.get(name) { + Some(existing_value) => existing_value == value, + None => false, + } + } + + pub fn matches(&self, criteria: &LabelSet) -> bool { + criteria.iter().all(|(name, value)| self.contains_pair(name, value)) + } + + pub fn iter(&self) -> Iter<'_, LabelName, LabelValue> { + self.items.iter() + } +} + +impl Display for LabelSet { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let items = self + .items + .iter() + .map(|(name, value)| format!("{name}=\"{value}\"")) + .collect::>() + .join(","); + + write!(f, "{{{items}}}") + } +} + +impl From> for LabelSet { + fn from(values: BTreeMap) -> Self { + Self { items: values } + } +} + +impl From> for LabelSet { + fn from(vec: Vec<(&str, &str)>) -> Self { + let mut items = BTreeMap::new(); + + for (name, value) in vec { + items.insert(LabelName::new(name), LabelValue::new(value)); + } + + Self { items } + } +} + +impl From> for LabelSet { + fn from(vec: Vec<(String, String)>) -> Self { + let mut items = BTreeMap::new(); + + for (name, value) in vec { + items.insert(LabelName::new(&name), LabelValue::new(&value)); + } + + Self { items } + } +} + +impl From> for LabelSet { + fn from(vec: Vec) -> Self { + let mut items = BTreeMap::new(); + + for (name, value) in vec { + items.insert(name, value); + } + + Self { items } + } +} + +impl From> for LabelSet { + fn from(vec: Vec) -> Self { + let mut items = BTreeMap::new(); + + for serialized_label in vec { + items.insert(serialized_label.name, serialized_label.value); + } + + Self { items } + } +} + +impl From<[LabelPair; N]> for LabelSet { + fn from(arr: [LabelPair; N]) -> Self { + let values = BTreeMap::from(arr); + Self { items: values } + } +} + +impl From<[(String, String); N]> for LabelSet { + fn from(arr: [(String, String); N]) -> Self { + let values = arr + .iter() + .map(|(name, value)| (LabelName::new(name), LabelValue::new(value))) + .collect::>(); + Self { items: values } + } +} + +impl From<[(&str, &str); N]> for LabelSet { + fn from(arr: [(&str, &str); N]) -> Self { + let values = arr + .iter() + .map(|(name, value)| (LabelName::new(name), LabelValue::new(value))) + .collect::>(); + Self { items: values } + } +} + +impl From for LabelSet { + fn from(label_pair: LabelPair) -> Self { + let mut set = BTreeMap::new(); + + set.insert(label_pair.0, label_pair.1); + + Self { items: set } + } +} + +#[derive(Debug, Clone, Eq, PartialEq, Default, Deserialize, Serialize)] +struct SerializedLabel { + name: LabelName, + value: LabelValue, +} + +impl Serialize for LabelSet { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.items + .iter() + .map(|(name, value)| SerializedLabel { + name: name.clone(), + value: value.clone(), + }) + .collect::>() + .serialize(serializer) + } +} + +impl<'de> Deserialize<'de> for LabelSet { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let serialized_labels = Vec::::deserialize(deserializer)?; + + Ok(LabelSet::from(serialized_labels)) + } +} + +impl PrometheusSerializable for LabelSet { + fn to_prometheus(&self) -> String { + if self.is_empty() { + return String::new(); + } + + let items = self.items.iter().fold(String::new(), |mut output, label_pair| { + if !output.is_empty() { + output.push(','); + } + + output.push_str(&label_pair.to_prometheus()); + + output + }); + + format!("{{{items}}}") + } +} + +#[cfg(test)] +mod tests { + + use std::collections::BTreeMap; + use std::hash::{DefaultHasher, Hash}; + + use pretty_assertions::assert_eq; + + use super::{LabelName, LabelValue}; + use crate::label::LabelSet; + use crate::label_name; + use crate::prometheus::PrometheusSerializable; + + fn sample_vec_of_label_pairs() -> Vec<(LabelName, LabelValue)> { + sample_array_of_label_pairs().into() + } + + fn sample_array_of_label_pairs() -> [(LabelName, LabelValue); 3] { + [ + (label_name!("server_service_binding_protocol"), LabelValue::new("http")), + (label_name!("server_service_binding_ip"), LabelValue::new("0.0.0.0")), + (label_name!("server_service_binding_port"), LabelValue::new("7070")), + ] + } + + #[test] + fn it_should_allow_inserting_a_new_label_pair() { + let mut label_set = LabelSet::default(); + + label_set.upsert(label_name!("label_name"), LabelValue::new("value")); + + assert_eq!( + label_set.items.get(&label_name!("label_name")).unwrap(), + &LabelValue::new("value") + ); + } + + #[test] + fn it_should_allow_updating_a_label_value() { + let mut label_set = LabelSet::default(); + + label_set.upsert(label_name!("label_name"), LabelValue::new("old value")); + label_set.upsert(label_name!("label_name"), LabelValue::new("new value")); + + assert_eq!( + label_set.items.get(&label_name!("label_name")).unwrap(), + &LabelValue::new("new value") + ); + } + + #[test] + fn it_should_allow_serializing_to_json_as_an_array_of_label_objects() { + let label_set = LabelSet::from((label_name!("label_name"), LabelValue::new("label value"))); + + let json = serde_json::to_string(&label_set).unwrap(); + + assert_eq!( + formatjson::format_json(&json).unwrap(), + formatjson::format_json( + r#" + [ + { + "name": "label_name", + "value": "label value" + } + ] + "# + ) + .unwrap() + ); + } + + #[test] + fn it_should_allow_deserializing_from_json_as_an_array_of_label_objects() { + let json = formatjson::format_json( + r#" + [ + { + "name": "label_name", + "value": "label value" + } + ] + "#, + ) + .unwrap(); + + let label_set: LabelSet = serde_json::from_str(&json).unwrap(); + + assert_eq!( + label_set, + LabelSet::from((label_name!("label_name"), LabelValue::new("label value"))) + ); + } + + #[test] + fn it_should_allow_serializing_to_prometheus_format() { + let label_set = LabelSet::from((label_name!("label_name"), LabelValue::new("label value"))); + assert_eq!(label_set.to_prometheus(), r#"{label_name="label value"}"#); + } + + #[test] + fn it_should_handle_prometheus_format_with_special_characters() { + let label_set: LabelSet = vec![("label_with_underscores", "value_with_underscores")].into(); + assert_eq!( + label_set.to_prometheus(), + r#"{label_with_underscores="value_with_underscores"}"# + ); + } + + #[test] + fn it_should_alphabetically_order_labels_in_prometheus_format() { + let label_set = LabelSet::from([ + (label_name!("b_label_name"), LabelValue::new("b label value")), + (label_name!("a_label_name"), LabelValue::new("a label value")), + ]); + + assert_eq!( + label_set.to_prometheus(), + r#"{a_label_name="a label value",b_label_name="b label value"}"# + ); + } + + #[test] + fn it_should_allow_displaying() { + let label_set = LabelSet::from((label_name!("label_name"), LabelValue::new("label value"))); + + assert_eq!(label_set.to_string(), r#"{label_name="label value"}"#); + } + + #[test] + fn it_should_allow_instantiation_from_an_array_of_label_pairs() { + let label_set: LabelSet = sample_array_of_label_pairs().into(); + + assert_eq!( + label_set, + LabelSet { + items: BTreeMap::from(sample_array_of_label_pairs()) + } + ); + } + + #[test] + fn it_should_allow_instantiation_from_a_vec_of_label_pairs() { + let label_set: LabelSet = sample_vec_of_label_pairs().into(); + + assert_eq!( + label_set, + LabelSet { + items: BTreeMap::from(sample_array_of_label_pairs()) + } + ); + } + + #[test] + fn it_should_allow_instantiation_from_a_b_tree_map() { + let label_set: LabelSet = BTreeMap::from(sample_array_of_label_pairs()).into(); + + assert_eq!( + label_set, + LabelSet { + items: BTreeMap::from(sample_array_of_label_pairs()) + } + ); + } + + #[test] + fn it_should_allow_instantiation_from_a_label_pair() { + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + assert_eq!( + label_set, + LabelSet { + items: BTreeMap::from([(label_name!("label_name"), LabelValue::new("value"))]) + } + ); + } + + #[test] + fn it_should_allow_instantiation_from_vec_of_str_tuples() { + let label_set: LabelSet = vec![("foo", "bar"), ("baz", "qux")].into(); + + let mut expected = BTreeMap::new(); + expected.insert(LabelName::new("foo"), LabelValue::new("bar")); + expected.insert(LabelName::new("baz"), LabelValue::new("qux")); + + assert_eq!(label_set, LabelSet { items: expected }); + } + + #[test] + fn it_should_allow_instantiation_from_vec_of_string_tuples() { + let label_set: LabelSet = vec![("foo".to_string(), "bar".to_string()), ("baz".to_string(), "qux".to_string())].into(); + + let mut expected = BTreeMap::new(); + expected.insert(LabelName::new("foo"), LabelValue::new("bar")); + expected.insert(LabelName::new("baz"), LabelValue::new("qux")); + + assert_eq!(label_set, LabelSet { items: expected }); + } + + #[test] + fn it_should_allow_instantiation_from_vec_of_serialized_label() { + use super::SerializedLabel; + let label_set: LabelSet = vec![ + SerializedLabel { + name: LabelName::new("foo"), + value: LabelValue::new("bar"), + }, + SerializedLabel { + name: LabelName::new("baz"), + value: LabelValue::new("qux"), + }, + ] + .into(); + + let mut expected = BTreeMap::new(); + expected.insert(LabelName::new("foo"), LabelValue::new("bar")); + expected.insert(LabelName::new("baz"), LabelValue::new("qux")); + + assert_eq!(label_set, LabelSet { items: expected }); + } + + #[test] + fn it_should_allow_instantiation_from_array_of_string_tuples() { + let arr: [(String, String); 2] = [("foo".to_string(), "bar".to_string()), ("baz".to_string(), "qux".to_string())]; + let label_set: LabelSet = arr.into(); + + let mut expected = BTreeMap::new(); + + expected.insert(LabelName::new("foo"), LabelValue::new("bar")); + expected.insert(LabelName::new("baz"), LabelValue::new("qux")); + + assert_eq!(label_set, LabelSet { items: expected }); + } + + #[test] + fn it_should_allow_instantiation_from_array_of_str_tuples() { + let arr: [(&str, &str); 2] = [("foo", "bar"), ("baz", "qux")]; + let label_set: LabelSet = arr.into(); + + let mut expected = BTreeMap::new(); + + expected.insert(LabelName::new("foo"), LabelValue::new("bar")); + expected.insert(LabelName::new("baz"), LabelValue::new("qux")); + + assert_eq!(label_set, LabelSet { items: expected }); + } + + #[test] + fn it_should_be_comparable() { + let a: LabelSet = (label_name!("x"), LabelValue::new("1")).into(); + let b: LabelSet = (label_name!("x"), LabelValue::new("1")).into(); + let c: LabelSet = (label_name!("y"), LabelValue::new("2")).into(); + + assert_eq!(a, b); + assert_ne!(a, c); + } + + #[test] + fn it_should_be_allow_ordering() { + let a: LabelSet = (label_name!("x"), LabelValue::new("1")).into(); + let b: LabelSet = (label_name!("y"), LabelValue::new("2")).into(); + + assert!(a < b); + } + + #[test] + fn it_should_be_hashable() { + let a: LabelSet = (label_name!("x"), LabelValue::new("1")).into(); + + let mut hasher = DefaultHasher::new(); + + a.hash(&mut hasher); + } + + #[test] + fn it_should_implement_clone() { + let a: LabelSet = (label_name!("x"), LabelValue::new("1")).into(); + let _unused = a.clone(); + } + + #[test] + fn it_should_check_if_empty() { + let empty_set = LabelSet::empty(); + assert!(empty_set.is_empty()); + } + + #[test] + fn it_should_check_if_non_empty() { + let non_empty_set: LabelSet = (label_name!("label"), LabelValue::new("value")).into(); + assert!(!non_empty_set.is_empty()); + } + + #[test] + fn it_should_create_an_empty_label_set() { + let empty_set = LabelSet::empty(); + assert!(empty_set.is_empty()); + } + + #[test] + fn it_should_check_if_contains_specific_label_pair() { + let label_set: LabelSet = vec![("service", "tracker"), ("protocol", "http")].into(); + + // Test existing pair + assert!(label_set.contains_pair(&LabelName::new("service"), &LabelValue::new("tracker"))); + assert!(label_set.contains_pair(&LabelName::new("protocol"), &LabelValue::new("http"))); + + // Test non-existing name + assert!(!label_set.contains_pair(&LabelName::new("missing"), &LabelValue::new("value"))); + + // Test existing name with wrong value + assert!(!label_set.contains_pair(&LabelName::new("service"), &LabelValue::new("wrong"))); + } + + #[test] + fn it_should_match_against_criteria() { + let label_set: LabelSet = vec![("service", "tracker"), ("protocol", "http"), ("version", "v1")].into(); + + // Empty criteria should match any label set + assert!(label_set.matches(&LabelSet::empty())); + + // Single matching criterion + let single_criteria: LabelSet = vec![("service", "tracker")].into(); + assert!(label_set.matches(&single_criteria)); + + // Multiple matching criteria + let multiple_criteria: LabelSet = vec![("service", "tracker"), ("protocol", "http")].into(); + assert!(label_set.matches(&multiple_criteria)); + + // Non-matching criterion + let non_matching: LabelSet = vec![("service", "wrong")].into(); + assert!(!label_set.matches(&non_matching)); + + // Partially matching criteria (one matches, one doesn't) + let partial_matching: LabelSet = vec![("service", "tracker"), ("missing", "value")].into(); + assert!(!label_set.matches(&partial_matching)); + + // Criteria with label not in original set + let missing_label: LabelSet = vec![("missing_label", "value")].into(); + assert!(!label_set.matches(&missing_label)); + } + + #[test] + fn it_should_allow_iteration_over_label_pairs() { + let label_set: LabelSet = vec![("service", "tracker"), ("protocol", "http")].into(); + + let mut count = 0; + + for (name, value) in label_set.iter() { + count += 1; + // Verify we can access name and value + assert!(!name.to_string().is_empty()); + assert!(!value.to_string().is_empty()); + } + + assert_eq!(count, 2); + } + + #[test] + fn it_should_display_empty_label_set() { + let empty_set = LabelSet::empty(); + assert_eq!(empty_set.to_string(), "{}"); + } + + #[test] + fn it_should_serialize_empty_label_set_to_prometheus_format() { + let empty_set = LabelSet::empty(); + assert_eq!(empty_set.to_prometheus(), ""); + } + + #[test] + fn it_should_maintain_order_in_iteration() { + let label_set: LabelSet = vec![("z_label", "z_value"), ("a_label", "a_value"), ("m_label", "m_value")].into(); + + let mut labels: Vec = vec![]; + for (name, _) in label_set.iter() { + labels.push(name.to_string()); + } + + // Should be in alphabetical order + assert_eq!(labels, vec!["a_label", "m_label", "z_label"]); + } +} diff --git a/packages/metrics/src/label/value.rs b/packages/metrics/src/label/value.rs new file mode 100644 index 000000000..4f25844a8 --- /dev/null +++ b/packages/metrics/src/label/value.rs @@ -0,0 +1,103 @@ +use derive_more::Display; +use serde::{Deserialize, Serialize}; + +use crate::prometheus::PrometheusSerializable; + +#[derive(Debug, Display, Clone, Eq, PartialEq, Default, Deserialize, Serialize, Hash, Ord, PartialOrd)] +pub struct LabelValue(String); + +impl LabelValue { + #[must_use] + pub fn new(value: &str) -> Self { + Self(value.to_owned()) + } + + /// Empty label values are ignored in Prometheus. + #[must_use] + pub fn ignore() -> Self { + Self(String::default()) + } +} + +impl PrometheusSerializable for LabelValue { + fn to_prometheus(&self) -> String { + self.0.clone() + } +} + +impl From for LabelValue { + fn from(value: String) -> Self { + Self(value) + } +} + +#[cfg(test)] +mod tests { + use std::collections::hash_map::DefaultHasher; + use std::hash::Hash; + + use crate::label::value::LabelValue; + use crate::prometheus::PrometheusSerializable; + + #[test] + fn it_serializes_to_prometheus() { + let label_value = LabelValue::new("value"); + assert_eq!(label_value.to_prometheus(), "value"); + } + + #[test] + fn it_could_be_initialized_from_str() { + let lv = LabelValue::new("abc"); + assert_eq!(lv.0, "abc"); + } + + #[test] + fn it_should_allow_to_create_an_ignored_label_value() { + let lv = LabelValue::ignore(); + assert_eq!(lv.0, ""); + } + + #[test] + fn it_should_be_converted_from_string() { + let s = String::from("foo"); + let lv: LabelValue = s.clone().into(); + assert_eq!(lv.0, s); + } + + #[test] + fn it_should_be_comparable() { + let a = LabelValue::new("x"); + let b = LabelValue::new("x"); + let c = LabelValue::new("y"); + + assert_eq!(a, b); + assert_ne!(a, c); + } + + #[test] + fn it_should_be_allow_ordering() { + let a = LabelValue::new("x"); + let b = LabelValue::new("y"); + + assert!(a < b); + } + + #[test] + fn it_should_be_hashable() { + let a = LabelValue::new("x"); + let mut hasher = DefaultHasher::new(); + a.hash(&mut hasher); + } + + #[test] + fn it_should_implement_clone() { + let a = LabelValue::new("x"); + let _unused = a.clone(); + } + + #[test] + fn it_should_implement_display() { + let a = LabelValue::new("x"); + assert_eq!(format!("{a}"), "x"); + } +} diff --git a/packages/metrics/src/lib.rs b/packages/metrics/src/lib.rs new file mode 100644 index 000000000..997cd3c8c --- /dev/null +++ b/packages/metrics/src/lib.rs @@ -0,0 +1,30 @@ +pub mod counter; +pub mod gauge; +pub mod label; +pub mod metric; +pub mod metric_collection; +pub mod prometheus; +pub mod sample; +pub mod sample_collection; +pub mod unit; + +pub const METRICS_TARGET: &str = "METRICS"; + +#[cfg(test)] +mod tests { + /// It removes leading and trailing whitespace from each line. + pub fn format_prometheus_output(output: &str) -> String { + output + .lines() + .map(str::trim_start) + .map(str::trim_end) + .collect::>() + .join("\n") + } + + pub fn sort_lines(s: &str) -> String { + let mut lines: Vec<&str> = s.split('\n').collect(); + lines.sort_unstable(); + lines.join("\n") + } +} diff --git a/packages/metrics/src/metric/aggregate/avg.rs b/packages/metrics/src/metric/aggregate/avg.rs new file mode 100644 index 000000000..95628450b --- /dev/null +++ b/packages/metrics/src/metric/aggregate/avg.rs @@ -0,0 +1,294 @@ +use crate::counter::Counter; +use crate::gauge::Gauge; +use crate::label::LabelSet; +use crate::metric::aggregate::sum::Sum; +use crate::metric::Metric; + +pub trait Avg { + type Output; + fn avg(&self, label_set_criteria: &LabelSet) -> Self::Output; +} + +impl Avg for Metric { + type Output = f64; + + fn avg(&self, label_set_criteria: &LabelSet) -> Self::Output { + let matching_samples = self.collect_matching_samples(label_set_criteria); + + if matching_samples.is_empty() { + return 0.0; + } + + let sum = self.sum(label_set_criteria); + + #[allow(clippy::cast_precision_loss)] + (sum as f64 / matching_samples.len() as f64) + } +} + +impl Avg for Metric { + type Output = f64; + + fn avg(&self, label_set_criteria: &LabelSet) -> Self::Output { + let matching_samples = self.collect_matching_samples(label_set_criteria); + + if matching_samples.is_empty() { + return 0.0; + } + + let sum = self.sum(label_set_criteria); + + #[allow(clippy::cast_precision_loss)] + (sum / matching_samples.len() as f64) + } +} + +#[cfg(test)] +mod tests { + + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::counter::Counter; + use crate::gauge::Gauge; + use crate::label::LabelSet; + use crate::metric::aggregate::avg::Avg; + use crate::metric::{Metric, MetricName}; + use crate::metric_name; + use crate::sample::Sample; + use crate::sample_collection::SampleCollection; + + struct MetricBuilder { + sample_time: DurationSinceUnixEpoch, + name: MetricName, + samples: Vec>, + } + + impl Default for MetricBuilder { + fn default() -> Self { + Self { + sample_time: DurationSinceUnixEpoch::from_secs(1_743_552_000), + name: metric_name!("test_metric"), + samples: vec![], + } + } + } + + impl MetricBuilder { + fn with_sample(mut self, value: T, label_set: &LabelSet) -> Self { + let sample = Sample::new(value, self.sample_time, label_set.clone()); + self.samples.push(sample); + self + } + + fn build(self) -> Metric { + Metric::new( + self.name, + None, + None, + SampleCollection::new(self.samples).expect("invalid samples"), + ) + } + } + + fn counter_cases() -> Vec<(Metric, LabelSet, f64)> { + // (metric, label set criteria, expected_average_value) + vec![ + // Metric with one sample without label set + ( + MetricBuilder::default().with_sample(1.into(), &LabelSet::empty()).build(), + LabelSet::empty(), + 1.0, + ), + // Metric with one sample with a label set + ( + MetricBuilder::default() + .with_sample(1.into(), &[("l1", "l1_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 1.0, + ), + // Metric with two samples, different label sets, average all + ( + MetricBuilder::default() + .with_sample(1.into(), &[("l1", "l1_value")].into()) + .with_sample(3.into(), &[("l2", "l2_value")].into()) + .build(), + LabelSet::empty(), + 2.0, // (1 + 3) / 2 = 2.0 + ), + // Metric with two samples, different label sets, average one + ( + MetricBuilder::default() + .with_sample(1.into(), &[("l1", "l1_value")].into()) + .with_sample(2.into(), &[("l2", "l2_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 1.0, + ), + // Metric with three samples, same label key, different label values, average by key + ( + MetricBuilder::default() + .with_sample(2.into(), &[("l1", "l1_value"), ("la", "la_value")].into()) + .with_sample(4.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) + .with_sample(6.into(), &[("l1", "l1_value"), ("lc", "lc_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 4.0, // (2 + 4 + 6) / 3 = 4.0 + ), + // Metric with two samples, different label values, average by subkey + ( + MetricBuilder::default() + .with_sample(5.into(), &[("l1", "l1_value"), ("la", "la_value")].into()) + .with_sample(7.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) + .build(), + [("la", "la_value")].into(), + 5.0, + ), + // Edge: Metric with no samples at all + (MetricBuilder::default().build(), LabelSet::empty(), 0.0), + // Edge: Metric with samples but no matching labels + ( + MetricBuilder::default() + .with_sample(5.into(), &[("foo", "bar")].into()) + .build(), + [("not", "present")].into(), + 0.0, + ), + // Edge: Metric with zero value + ( + MetricBuilder::default() + .with_sample(0.into(), &[("l3", "l3_value")].into()) + .build(), + [("l3", "l3_value")].into(), + 0.0, + ), + // Edge: Metric with a very large value + ( + MetricBuilder::default() + .with_sample((u64::MAX / 2).into(), &[("edge", "large1")].into()) + .with_sample((u64::MAX / 2).into(), &[("edge", "large2")].into()) + .build(), + LabelSet::empty(), + #[allow(clippy::cast_precision_loss)] + (u64::MAX as f64 / 2.0), // Average of (max/2) and (max/2) + ), + ] + } + + fn gauge_cases() -> Vec<(Metric, LabelSet, f64)> { + // (metric, label set criteria, expected_average_value) + vec![ + // Metric with one sample without label set + ( + MetricBuilder::default().with_sample(1.0.into(), &LabelSet::empty()).build(), + LabelSet::empty(), + 1.0, + ), + // Metric with one sample with a label set + ( + MetricBuilder::default() + .with_sample(1.0.into(), &[("l1", "l1_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 1.0, + ), + // Metric with two samples, different label sets, average all + ( + MetricBuilder::default() + .with_sample(1.0.into(), &[("l1", "l1_value")].into()) + .with_sample(3.0.into(), &[("l2", "l2_value")].into()) + .build(), + LabelSet::empty(), + 2.0, // (1.0 + 3.0) / 2 = 2.0 + ), + // Metric with two samples, different label sets, average one + ( + MetricBuilder::default() + .with_sample(1.0.into(), &[("l1", "l1_value")].into()) + .with_sample(2.0.into(), &[("l2", "l2_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 1.0, + ), + // Metric with three samples, same label key, different label values, average by key + ( + MetricBuilder::default() + .with_sample(2.0.into(), &[("l1", "l1_value"), ("la", "la_value")].into()) + .with_sample(4.0.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) + .with_sample(6.0.into(), &[("l1", "l1_value"), ("lc", "lc_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 4.0, // (2.0 + 4.0 + 6.0) / 3 = 4.0 + ), + // Metric with two samples, different label values, average by subkey + ( + MetricBuilder::default() + .with_sample(5.0.into(), &[("l1", "l1_value"), ("la", "la_value")].into()) + .with_sample(7.0.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) + .build(), + [("la", "la_value")].into(), + 5.0, + ), + // Edge: Metric with no samples at all + (MetricBuilder::default().build(), LabelSet::empty(), 0.0), + // Edge: Metric with samples but no matching labels + ( + MetricBuilder::default() + .with_sample(5.0.into(), &[("foo", "bar")].into()) + .build(), + [("not", "present")].into(), + 0.0, + ), + // Edge: Metric with zero value + ( + MetricBuilder::default() + .with_sample(0.0.into(), &[("l3", "l3_value")].into()) + .build(), + [("l3", "l3_value")].into(), + 0.0, + ), + // Edge: Metric with negative values + ( + MetricBuilder::default() + .with_sample((-2.0).into(), &[("l4", "l4_value")].into()) + .with_sample(4.0.into(), &[("l5", "l5_value")].into()) + .build(), + LabelSet::empty(), + 1.0, // (-2.0 + 4.0) / 2 = 1.0 + ), + // Edge: Metric with decimal values + ( + MetricBuilder::default() + .with_sample(1.5.into(), &[("l6", "l6_value")].into()) + .with_sample(2.5.into(), &[("l7", "l7_value")].into()) + .build(), + LabelSet::empty(), + 2.0, // (1.5 + 2.5) / 2 = 2.0 + ), + ] + } + + #[test] + fn test_counter_cases() { + for (idx, (metric, criteria, expected_value)) in counter_cases().iter().enumerate() { + let avg = metric.avg(criteria); + + assert!( + (avg - expected_value).abs() <= f64::EPSILON, + "at case {idx}, expected avg to be {expected_value}, got {avg}" + ); + } + } + + #[test] + fn test_gauge_cases() { + for (idx, (metric, criteria, expected_value)) in gauge_cases().iter().enumerate() { + let avg = metric.avg(criteria); + + assert!( + (avg - expected_value).abs() <= f64::EPSILON, + "at case {idx}, expected avg to be {expected_value}, got {avg}" + ); + } + } +} diff --git a/packages/metrics/src/metric/aggregate/mod.rs b/packages/metrics/src/metric/aggregate/mod.rs new file mode 100644 index 000000000..1224a1f52 --- /dev/null +++ b/packages/metrics/src/metric/aggregate/mod.rs @@ -0,0 +1,2 @@ +pub mod avg; +pub mod sum; diff --git a/packages/metrics/src/metric/aggregate/sum.rs b/packages/metrics/src/metric/aggregate/sum.rs new file mode 100644 index 000000000..30c2819b7 --- /dev/null +++ b/packages/metrics/src/metric/aggregate/sum.rs @@ -0,0 +1,278 @@ +use crate::counter::Counter; +use crate::gauge::Gauge; +use crate::label::LabelSet; +use crate::metric::Metric; + +pub trait Sum { + type Output; + fn sum(&self, label_set_criteria: &LabelSet) -> Self::Output; +} + +impl Sum for Metric { + type Output = u64; + + fn sum(&self, label_set_criteria: &LabelSet) -> Self::Output { + self.sample_collection + .iter() + .filter(|(label_set, _measurement)| label_set.matches(label_set_criteria)) + .map(|(_label_set, measurement)| measurement.value().primitive()) + .sum() + } +} + +impl Sum for Metric { + type Output = f64; + + fn sum(&self, label_set_criteria: &LabelSet) -> Self::Output { + self.sample_collection + .iter() + .filter(|(label_set, _measurement)| label_set.matches(label_set_criteria)) + .map(|(_label_set, measurement)| measurement.value().primitive()) + .sum() + } +} + +#[cfg(test)] +mod tests { + + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::counter::Counter; + use crate::gauge::Gauge; + use crate::label::LabelSet; + use crate::metric::aggregate::sum::Sum; + use crate::metric::{Metric, MetricName}; + use crate::metric_name; + use crate::sample::Sample; + use crate::sample_collection::SampleCollection; + + struct MetricBuilder { + sample_time: DurationSinceUnixEpoch, + name: MetricName, + samples: Vec>, + } + + impl Default for MetricBuilder { + fn default() -> Self { + Self { + sample_time: DurationSinceUnixEpoch::from_secs(1_743_552_000), + name: metric_name!("test_metric"), + samples: vec![], + } + } + } + + impl MetricBuilder { + fn with_sample(mut self, value: T, label_set: &LabelSet) -> Self { + let sample = Sample::new(value, self.sample_time, label_set.clone()); + self.samples.push(sample); + self + } + + fn build(self) -> Metric { + Metric::new( + self.name, + None, + None, + SampleCollection::new(self.samples).expect("invalid samples"), + ) + } + } + + fn counter_cases() -> Vec<(Metric, LabelSet, u64)> { + // (metric, label set criteria, expected_aggregate_value) + vec![ + // Metric with one sample without label set + ( + MetricBuilder::default().with_sample(1.into(), &LabelSet::empty()).build(), + LabelSet::empty(), + 1, + ), + // Metric with one sample with a label set + ( + MetricBuilder::default() + .with_sample(1.into(), &[("l1", "l1_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 1, + ), + // Metric with two samples, different label sets, sum all + ( + MetricBuilder::default() + .with_sample(1.into(), &[("l1", "l1_value")].into()) + .with_sample(2.into(), &[("l2", "l2_value")].into()) + .build(), + LabelSet::empty(), + 3, + ), + // Metric with two samples, different label sets, sum one + ( + MetricBuilder::default() + .with_sample(1.into(), &[("l1", "l1_value")].into()) + .with_sample(2.into(), &[("l2", "l2_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 1, + ), + // Metric with two samples, same label key, different label values, sum by key + ( + MetricBuilder::default() + .with_sample(1.into(), &[("l1", "l1_value"), ("la", "la_value")].into()) + .with_sample(2.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 3, + ), + // Metric with two samples, different label values, sum by subkey + ( + MetricBuilder::default() + .with_sample(1.into(), &[("l1", "l1_value"), ("la", "la_value")].into()) + .with_sample(2.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) + .build(), + [("la", "la_value")].into(), + 1, + ), + // Edge: Metric with no samples at all + (MetricBuilder::default().build(), LabelSet::empty(), 0), + // Edge: Metric with samples but no matching labels + ( + MetricBuilder::default() + .with_sample(5.into(), &[("foo", "bar")].into()) + .build(), + [("not", "present")].into(), + 0, + ), + // Edge: Metric with zero value + ( + MetricBuilder::default() + .with_sample(0.into(), &[("l3", "l3_value")].into()) + .build(), + [("l3", "l3_value")].into(), + 0, + ), + // Edge: Metric with a very large value + ( + MetricBuilder::default() + .with_sample(u64::MAX.into(), &LabelSet::empty()) + .build(), + LabelSet::empty(), + u64::MAX, + ), + ] + } + + fn gauge_cases() -> Vec<(Metric, LabelSet, f64)> { + // (metric, label set criteria, expected_aggregate_value) + vec![ + // Metric with one sample without label set + ( + MetricBuilder::default().with_sample(1.0.into(), &LabelSet::empty()).build(), + LabelSet::empty(), + 1.0, + ), + // Metric with one sample with a label set + ( + MetricBuilder::default() + .with_sample(1.0.into(), &[("l1", "l1_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 1.0, + ), + // Metric with two samples, different label sets, sum all + ( + MetricBuilder::default() + .with_sample(1.0.into(), &[("l1", "l1_value")].into()) + .with_sample(2.0.into(), &[("l2", "l2_value")].into()) + .build(), + LabelSet::empty(), + 3.0, + ), + // Metric with two samples, different label sets, sum one + ( + MetricBuilder::default() + .with_sample(1.0.into(), &[("l1", "l1_value")].into()) + .with_sample(2.0.into(), &[("l2", "l2_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 1.0, + ), + // Metric with two samples, same label key, different label values, sum by key + ( + MetricBuilder::default() + .with_sample(1.0.into(), &[("l1", "l1_value"), ("la", "la_value")].into()) + .with_sample(2.0.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 3.0, + ), + // Metric with two samples, different label values, sum by subkey + ( + MetricBuilder::default() + .with_sample(1.0.into(), &[("l1", "l1_value"), ("la", "la_value")].into()) + .with_sample(2.0.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) + .build(), + [("la", "la_value")].into(), + 1.0, + ), + // Edge: Metric with no samples at all + (MetricBuilder::default().build(), LabelSet::empty(), 0.0), + // Edge: Metric with samples but no matching labels + ( + MetricBuilder::default() + .with_sample(5.0.into(), &[("foo", "bar")].into()) + .build(), + [("not", "present")].into(), + 0.0, + ), + // Edge: Metric with zero value + ( + MetricBuilder::default() + .with_sample(0.0.into(), &[("l3", "l3_value")].into()) + .build(), + [("l3", "l3_value")].into(), + 0.0, + ), + // Edge: Metric with negative values + ( + MetricBuilder::default() + .with_sample((-2.0).into(), &[("l4", "l4_value")].into()) + .with_sample(3.0.into(), &[("l5", "l5_value")].into()) + .build(), + LabelSet::empty(), + 1.0, + ), + // Edge: Metric with a very large value + ( + MetricBuilder::default() + .with_sample(f64::MAX.into(), &LabelSet::empty()) + .build(), + LabelSet::empty(), + f64::MAX, + ), + ] + } + + #[test] + fn test_counter_cases() { + for (idx, (metric, criteria, expected_value)) in counter_cases().iter().enumerate() { + let sum = metric.sum(criteria); + + assert_eq!( + sum, *expected_value, + "at case {idx}, expected sum to be {expected_value}, got {sum}" + ); + } + } + + #[test] + fn test_gauge_cases() { + for (idx, (metric, criteria, expected_value)) in gauge_cases().iter().enumerate() { + let sum = metric.sum(criteria); + + assert!( + (sum - expected_value).abs() <= f64::EPSILON, + "at case {idx}, expected sum to be {expected_value}, got {sum}" + ); + } + } +} diff --git a/packages/metrics/src/metric/description.rs b/packages/metrics/src/metric/description.rs new file mode 100644 index 000000000..6a0ca3432 --- /dev/null +++ b/packages/metrics/src/metric/description.rs @@ -0,0 +1,42 @@ +use derive_more::Display; +use serde::{Deserialize, Serialize}; + +use crate::prometheus::PrometheusSerializable; + +#[derive(Debug, Display, Clone, Eq, PartialEq, Default, Deserialize, Serialize, Hash, Ord, PartialOrd)] +pub struct MetricDescription(String); + +impl MetricDescription { + #[must_use] + pub fn new(name: &str) -> Self { + Self(name.to_owned()) + } +} + +impl PrometheusSerializable for MetricDescription { + fn to_prometheus(&self) -> String { + self.0.clone() + } +} +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_should_be_created_from_a_string_reference() { + let metric = MetricDescription::new("Metric description"); + assert_eq!(metric.0, "Metric description"); + } + + #[test] + fn it_serializes_to_prometheus() { + let label_value = MetricDescription::new("name"); + assert_eq!(label_value.to_prometheus(), "name"); + } + + #[test] + fn it_should_be_displayed() { + let metric = MetricDescription::new("Metric description"); + assert_eq!(metric.to_string(), "Metric description"); + } +} diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs new file mode 100644 index 000000000..6bc1a6075 --- /dev/null +++ b/packages/metrics/src/metric/mod.rs @@ -0,0 +1,365 @@ +pub mod aggregate; +pub mod description; +pub mod name; + +use serde::{Deserialize, Serialize}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::counter::Counter; +use super::label::LabelSet; +use super::prometheus::PrometheusSerializable; +use super::sample_collection::SampleCollection; +use crate::gauge::Gauge; +use crate::metric::description::MetricDescription; +use crate::sample::Measurement; +use crate::unit::Unit; + +pub type MetricName = name::MetricName; + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Metric { + name: MetricName, + + #[serde(rename = "unit")] + opt_unit: Option, + + #[serde(rename = "description")] + opt_description: Option, + + #[serde(rename = "samples")] + sample_collection: SampleCollection, +} + +impl Metric { + #[must_use] + pub fn new( + name: MetricName, + opt_unit: Option, + opt_description: Option, + samples: SampleCollection, + ) -> Self { + Self { + name, + opt_unit, + opt_description, + sample_collection: samples, + } + } + + /// # Panics + /// + /// This function will panic if the empty sample collection cannot be created. + #[must_use] + pub fn new_empty_with_name(name: MetricName) -> Self { + Self { + name, + opt_unit: None, + opt_description: None, + sample_collection: SampleCollection::new(vec![]).expect("Empty sample collection creation should not fail"), + } + } + + #[must_use] + pub fn name(&self) -> &MetricName { + &self.name + } + + #[must_use] + pub fn get_sample_data(&self, label_set: &LabelSet) -> Option<&Measurement> { + self.sample_collection.get(label_set) + } + + #[must_use] + pub fn number_of_samples(&self) -> usize { + self.sample_collection.len() + } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.sample_collection.is_empty() + } + + #[must_use] + pub fn collect_matching_samples( + &self, + label_set_criteria: &LabelSet, + ) -> Vec<(&crate::label::LabelSet, &crate::sample::Measurement)> { + self.sample_collection + .iter() + .filter(|(label_set, _measurement)| label_set.matches(label_set_criteria)) + .collect() + } +} + +impl Metric { + pub fn increment(&mut self, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + self.sample_collection.increment(label_set, time); + } + + pub fn absolute(&mut self, label_set: &LabelSet, value: u64, time: DurationSinceUnixEpoch) { + self.sample_collection.absolute(label_set, value, time); + } +} + +impl Metric { + pub fn set(&mut self, label_set: &LabelSet, value: f64, time: DurationSinceUnixEpoch) { + self.sample_collection.set(label_set, value, time); + } + + pub fn increment(&mut self, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + self.sample_collection.increment(label_set, time); + } + + pub fn decrement(&mut self, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + self.sample_collection.decrement(label_set, time); + } +} + +enum PrometheusType { + Counter, + Gauge, +} + +impl PrometheusSerializable for PrometheusType { + fn to_prometheus(&self) -> String { + match self { + PrometheusType::Counter => "counter".to_string(), + PrometheusType::Gauge => "gauge".to_string(), + } + } +} + +impl Metric { + #[must_use] + fn prometheus_help_line(&self) -> String { + if let Some(description) = &self.opt_description { + format!("# HELP {} {}", self.name.to_prometheus(), description.to_prometheus()) + } else { + String::new() + } + } + + #[must_use] + fn prometheus_type_line(&self, prometheus_type: &PrometheusType) -> String { + format!("# TYPE {} {}", self.name.to_prometheus(), prometheus_type.to_prometheus()) + } + + #[must_use] + fn prometheus_sample_line(&self, label_set: &LabelSet, measurement: &Measurement) -> String { + format!( + "{}{} {}", + self.name.to_prometheus(), + label_set.to_prometheus(), + measurement.to_prometheus() + ) + } + + #[must_use] + fn prometheus_samples(&self) -> String { + self.sample_collection + .iter() + .map(|(label_set, measurement)| self.prometheus_sample_line(label_set, measurement)) + .collect::>() + .join("\n") + } + + fn to_prometheus(&self, prometheus_type: &PrometheusType) -> String { + let help_line = self.prometheus_help_line(); + let type_line = self.prometheus_type_line(prometheus_type); + let samples = self.prometheus_samples(); + + format!("{help_line}\n{type_line}\n{samples}") + } +} + +impl PrometheusSerializable for Metric { + fn to_prometheus(&self) -> String { + self.to_prometheus(&PrometheusType::Counter) + } +} + +impl PrometheusSerializable for Metric { + fn to_prometheus(&self) -> String { + self.to_prometheus(&PrometheusType::Gauge) + } +} + +#[cfg(test)] +mod tests { + mod for_generic_metrics { + use super::super::*; + use crate::gauge::Gauge; + use crate::label::LabelValue; + use crate::sample::Sample; + use crate::{label_name, metric_name}; + + #[test] + fn it_should_be_empty_when_it_does_not_have_any_sample() { + let name = metric_name!("test_metric"); + + let samples = SampleCollection::::default(); + + let metric = Metric::::new(name.clone(), None, None, samples); + + assert!(metric.is_empty()); + } + + fn counter_metric_with_one_sample() -> Metric { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + + let name = metric_name!("test_metric"); + + let label_set: LabelSet = [(label_name!("server_binding_protocol"), LabelValue::new("http"))].into(); + + let samples = SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set.clone())]).unwrap(); + + Metric::::new(name.clone(), None, None, samples) + } + + #[test] + fn it_should_return_the_number_of_samples() { + assert_eq!(counter_metric_with_one_sample().number_of_samples(), 1); + } + + #[test] + fn it_should_return_zero_number_of_samples_for_an_empty_metric() { + let name = metric_name!("test_metric"); + + let samples = SampleCollection::::default(); + + let metric = Metric::::new(name.clone(), None, None, samples); + + assert_eq!(metric.number_of_samples(), 0); + } + } + + mod for_counter_metrics { + use super::super::*; + use crate::counter::Counter; + use crate::label::LabelValue; + use crate::sample::Sample; + use crate::{label_name, metric_name}; + + #[test] + fn it_should_be_created_from_its_name_and_a_collection_of_samples() { + let name = metric_name!("test_metric"); + + let samples = SampleCollection::::default(); + + let _metric = Metric::::new(name, None, None, samples); + } + + #[test] + fn it_should_allow_incrementing_a_sample() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let name = metric_name!("test_metric"); + let label_set: LabelSet = [(label_name!("server_binding_protocol"), LabelValue::new("http"))].into(); + let samples = SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]).unwrap(); + let mut metric = Metric::::new(name.clone(), None, None, samples); + + metric.increment(&label_set, time); + + assert_eq!(metric.get_sample_data(&label_set).unwrap().value().value(), 1); + } + + #[test] + fn it_should_allow_setting_to_an_absolute_value() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let name = metric_name!("test_metric"); + let label_set: LabelSet = [(label_name!("server_binding_protocol"), LabelValue::new("http"))].into(); + let samples = SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]).unwrap(); + let mut metric = Metric::::new(name.clone(), None, None, samples); + + metric.absolute(&label_set, 1, time); + + assert_eq!(metric.get_sample_data(&label_set).unwrap().value().value(), 1); + } + } + + mod for_gauge_metrics { + use approx::assert_relative_eq; + + use super::super::*; + use crate::gauge::Gauge; + use crate::label::LabelValue; + use crate::sample::Sample; + use crate::{label_name, metric_name}; + + #[test] + fn it_should_be_created_from_its_name_and_a_collection_of_samples() { + let name = metric_name!("test_metric"); + + let samples = SampleCollection::::default(); + + let _metric = Metric::::new(name, None, None, samples); + } + + #[test] + fn it_should_allow_incrementing_a_sample() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let name = metric_name!("test_metric"); + let label_set: LabelSet = [(label_name!("server_binding_protocol"), LabelValue::new("http"))].into(); + let samples = SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]).unwrap(); + let mut metric = Metric::::new(name.clone(), None, None, samples); + + metric.increment(&label_set, time); + + assert_relative_eq!(metric.get_sample_data(&label_set).unwrap().value().value(), 1.0); + } + + #[test] + fn it_should_allow_decrement_a_sample() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let name = metric_name!("test_metric"); + let label_set: LabelSet = [(label_name!("server_binding_protocol"), LabelValue::new("http"))].into(); + let samples = SampleCollection::new(vec![Sample::new(Gauge::new(1.0), time, label_set.clone())]).unwrap(); + let mut metric = Metric::::new(name.clone(), None, None, samples); + + metric.decrement(&label_set, time); + + assert_relative_eq!(metric.get_sample_data(&label_set).unwrap().value().value(), 0.0); + } + + #[test] + fn it_should_allow_setting_a_sample() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let name = metric_name!("test_metric"); + let label_set: LabelSet = [(label_name!("server_binding_protocol"), LabelValue::new("http"))].into(); + let samples = SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]).unwrap(); + let mut metric = Metric::::new(name.clone(), None, None, samples); + + metric.set(&label_set, 1.0, time); + + assert_relative_eq!(metric.get_sample_data(&label_set).unwrap().value().value(), 1.0); + } + } + + mod for_prometheus_serialization { + use super::super::*; + use crate::counter::Counter; + use crate::metric_name; + + #[test] + fn it_should_return_empty_string_for_prometheus_help_line_when_description_is_none() { + let name = metric_name!("test_metric"); + let samples = SampleCollection::::default(); + let metric = Metric::::new(name, None, None, samples); + + let help_line = metric.prometheus_help_line(); + + assert_eq!(help_line, String::new()); + } + + #[test] + fn it_should_return_formatted_help_line_for_prometheus_when_description_is_some() { + let name = metric_name!("test_metric"); + let description = MetricDescription::new("This is a test metric description"); + let samples = SampleCollection::::default(); + let metric = Metric::::new(name, None, Some(description), samples); + + let help_line = metric.prometheus_help_line(); + + assert_eq!(help_line, "# HELP test_metric This is a test metric description"); + } + } +} diff --git a/packages/metrics/src/metric/name.rs b/packages/metrics/src/metric/name.rs new file mode 100644 index 000000000..09c8c9e6d --- /dev/null +++ b/packages/metrics/src/metric/name.rs @@ -0,0 +1,97 @@ +use derive_more::Display; +use serde::{Deserialize, Serialize}; + +use crate::prometheus::PrometheusSerializable; + +#[derive(Debug, Display, Clone, Eq, PartialEq, Default, Deserialize, Serialize, Hash, Ord, PartialOrd)] +pub struct MetricName(String); + +impl MetricName { + /// Creates a new `MetricName` instance. + /// + /// # Panics + /// + /// Panics if the provided name is empty. + #[must_use] + pub fn new(name: &str) -> Self { + assert!(!name.is_empty(), "Metric name cannot be empty."); + Self(name.to_owned()) + } +} + +impl PrometheusSerializable for MetricName { + fn to_prometheus(&self) -> String { + // Metric names may contain ASCII letters, digits, underscores, and + // colons. It must match the regex [a-zA-Z_:][a-zA-Z0-9_:]*. + // If the metric name starts with, or contains, an invalid character: + // replace character with underscore. + + self.0 + .chars() + .enumerate() + .map(|(i, c)| { + if i == 0 { + if c.is_ascii_alphabetic() || c == '_' || c == ':' { + c + } else { + '_' + } + } else if c.is_ascii_alphanumeric() || c == '_' || c == ':' { + c + } else { + '_' + } + }) + .collect() + } +} + +#[macro_export] +macro_rules! metric_name { + ("") => { + compile_error!("Metric name cannot be empty"); + }; + ($name:literal) => { + $crate::metric::name::MetricName::new($name) + }; + ($name:ident) => { + $crate::metric::name::MetricName::new($name) + }; +} + +#[cfg(test)] +mod tests { + + mod serialization_of_metric_name_to_prometheus { + + use crate::metric::name::MetricName; + use crate::prometheus::PrometheusSerializable; + + #[test] + fn valid_names_in_prometheus() { + assert_eq!(metric_name!("valid_name").to_prometheus(), "valid_name"); + assert_eq!(metric_name!("_leading_underscore").to_prometheus(), "_leading_underscore"); + assert_eq!(metric_name!(":leading_colon").to_prometheus(), ":leading_colon"); + assert_eq!(metric_name!("v123").to_prometheus(), "v123"); // leading lowercase + assert_eq!(metric_name!("V123").to_prometheus(), "V123"); // leading lowercase + } + + #[test] + fn names_that_need_changes_in_prometheus() { + assert_eq!(metric_name!("9invalid_start").to_prometheus(), "_invalid_start"); + assert_eq!(metric_name!("@test").to_prometheus(), "_test"); + assert_eq!(metric_name!("invalid-char").to_prometheus(), "invalid_char"); + assert_eq!(metric_name!("spaces are bad").to_prometheus(), "spaces_are_bad"); + assert_eq!(metric_name!("a!b@c#d$e%f^g&h*i(j)").to_prometheus(), "a_b_c_d_e_f_g_h_i_j_"); + assert_eq!(metric_name!("my:metric/version").to_prometheus(), "my:metric_version"); + assert_eq!(metric_name!("!@#$%^&*()").to_prometheus(), "__________"); + assert_eq!(metric_name!("ñaca©").to_prometheus(), "_aca_"); + } + + #[test] + #[should_panic(expected = "Metric name cannot be empty.")] + fn empty_name() { + let _name = MetricName::new(""); + } + } +} diff --git a/packages/metrics/src/metric_collection/aggregate/avg.rs b/packages/metrics/src/metric_collection/aggregate/avg.rs new file mode 100644 index 000000000..0aef4e325 --- /dev/null +++ b/packages/metrics/src/metric_collection/aggregate/avg.rs @@ -0,0 +1,212 @@ +use crate::counter::Counter; +use crate::gauge::Gauge; +use crate::label::LabelSet; +use crate::metric::aggregate::avg::Avg as MetricAvgTrait; +use crate::metric::MetricName; +use crate::metric_collection::{MetricCollection, MetricKindCollection}; + +pub trait Avg { + fn avg(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option; +} + +impl Avg for MetricCollection { + fn avg(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { + if let Some(value) = self.counters.avg(metric_name, label_set_criteria) { + return Some(value); + } + + if let Some(value) = self.gauges.avg(metric_name, label_set_criteria) { + return Some(value); + } + + None + } +} + +impl Avg for MetricKindCollection { + fn avg(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { + self.metrics.get(metric_name).map(|metric| metric.avg(label_set_criteria)) + } +} + +impl Avg for MetricKindCollection { + fn avg(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { + self.metrics.get(metric_name).map(|metric| metric.avg(label_set_criteria)) + } +} + +#[cfg(test)] +mod tests { + + mod it_should_allow_averaging_all_metric_samples_containing_some_given_labels { + + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::label::LabelValue; + use crate::label_name; + use crate::metric_collection::aggregate::avg::Avg; + + #[test] + fn type_counter_with_two_samples() { + use crate::label::LabelSet; + use crate::metric_collection::MetricCollection; + use crate::metric_name; + + let metric_name = metric_name!("test_counter"); + + let mut collection = MetricCollection::default(); + + collection + .increment_counter( + &metric_name!("test_counter"), + &(label_name!("label_1"), LabelValue::new("value_1")).into(), + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + collection + .increment_counter( + &metric_name!("test_counter"), + &(label_name!("label_2"), LabelValue::new("value_2")).into(), + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + // Two samples with value 1 each, average should be 1.0 + assert_eq!(collection.avg(&metric_name, &LabelSet::empty()), Some(1.0)); + assert_eq!( + collection.avg(&metric_name, &(label_name!("label_1"), LabelValue::new("value_1")).into()), + Some(1.0) + ); + } + + #[test] + fn type_counter_with_different_values() { + use crate::label::LabelSet; + use crate::metric_collection::MetricCollection; + use crate::metric_name; + + let metric_name = metric_name!("test_counter"); + + let mut collection = MetricCollection::default(); + + // First increment: value goes from 0 to 1 + collection + .increment_counter( + &metric_name!("test_counter"), + &(label_name!("label_1"), LabelValue::new("value_1")).into(), + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + // Second increment on the same label: value goes from 1 to 2 + collection + .increment_counter( + &metric_name!("test_counter"), + &(label_name!("label_1"), LabelValue::new("value_1")).into(), + DurationSinceUnixEpoch::from_secs(2), + ) + .unwrap(); + + // Create another counter with a different value + collection + .set_counter( + &metric_name!("test_counter"), + &(label_name!("label_2"), LabelValue::new("value_2")).into(), + 4, + DurationSinceUnixEpoch::from_secs(3), + ) + .unwrap(); + + // Average of 2 and 4 should be 3.0 + assert_eq!(collection.avg(&metric_name, &LabelSet::empty()), Some(3.0)); + assert_eq!( + collection.avg(&metric_name, &(label_name!("label_1"), LabelValue::new("value_1")).into()), + Some(2.0) + ); + assert_eq!( + collection.avg(&metric_name, &(label_name!("label_2"), LabelValue::new("value_2")).into()), + Some(4.0) + ); + } + + #[test] + fn type_gauge_with_two_samples() { + use crate::label::LabelSet; + use crate::metric_collection::MetricCollection; + use crate::metric_name; + + let metric_name = metric_name!("test_gauge"); + + let mut collection = MetricCollection::default(); + + collection + .set_gauge( + &metric_name!("test_gauge"), + &(label_name!("label_1"), LabelValue::new("value_1")).into(), + 2.0, + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + collection + .set_gauge( + &metric_name!("test_gauge"), + &(label_name!("label_2"), LabelValue::new("value_2")).into(), + 4.0, + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + // Average of 2.0 and 4.0 should be 3.0 + assert_eq!(collection.avg(&metric_name, &LabelSet::empty()), Some(3.0)); + assert_eq!( + collection.avg(&metric_name, &(label_name!("label_1"), LabelValue::new("value_1")).into()), + Some(2.0) + ); + } + + #[test] + fn type_gauge_with_negative_values() { + use crate::label::LabelSet; + use crate::metric_collection::MetricCollection; + use crate::metric_name; + + let metric_name = metric_name!("test_gauge"); + + let mut collection = MetricCollection::default(); + + collection + .set_gauge( + &metric_name!("test_gauge"), + &(label_name!("label_1"), LabelValue::new("value_1")).into(), + -2.0, + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + collection + .set_gauge( + &metric_name!("test_gauge"), + &(label_name!("label_2"), LabelValue::new("value_2")).into(), + 6.0, + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + // Average of -2.0 and 6.0 should be 2.0 + assert_eq!(collection.avg(&metric_name, &LabelSet::empty()), Some(2.0)); + } + + #[test] + fn nonexistent_metric() { + use crate::label::LabelSet; + use crate::metric_collection::MetricCollection; + use crate::metric_name; + + let collection = MetricCollection::default(); + + assert_eq!(collection.avg(&metric_name!("nonexistent"), &LabelSet::empty()), None); + } + } +} diff --git a/packages/metrics/src/metric_collection/aggregate/mod.rs b/packages/metrics/src/metric_collection/aggregate/mod.rs new file mode 100644 index 000000000..1224a1f52 --- /dev/null +++ b/packages/metrics/src/metric_collection/aggregate/mod.rs @@ -0,0 +1,2 @@ +pub mod avg; +pub mod sum; diff --git a/packages/metrics/src/metric_collection/aggregate/sum.rs b/packages/metrics/src/metric_collection/aggregate/sum.rs new file mode 100644 index 000000000..3285fa8f1 --- /dev/null +++ b/packages/metrics/src/metric_collection/aggregate/sum.rs @@ -0,0 +1,118 @@ +use crate::counter::Counter; +use crate::gauge::Gauge; +use crate::label::LabelSet; +use crate::metric::aggregate::sum::Sum as MetricSumTrait; +use crate::metric::MetricName; +use crate::metric_collection::{MetricCollection, MetricKindCollection}; + +pub trait Sum { + fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option; +} + +impl Sum for MetricCollection { + fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { + if let Some(value) = self.counters.sum(metric_name, label_set_criteria) { + return Some(value); + } + + if let Some(value) = self.gauges.sum(metric_name, label_set_criteria) { + return Some(value); + } + + None + } +} + +impl Sum for MetricKindCollection { + fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { + #[allow(clippy::cast_precision_loss)] + self.metrics + .get(metric_name) + .map(|metric| metric.sum(label_set_criteria) as f64) + } +} + +impl Sum for MetricKindCollection { + fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { + self.metrics.get(metric_name).map(|metric| metric.sum(label_set_criteria)) + } +} + +#[cfg(test)] +mod tests { + + mod it_should_allow_summing_all_metric_samples_containing_some_given_labels { + + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::label::LabelValue; + use crate::label_name; + use crate::metric_collection::aggregate::sum::Sum; + + #[test] + fn type_counter_with_two_samples() { + use crate::label::LabelSet; + use crate::metric_collection::MetricCollection; + use crate::metric_name; + + let metric_name = metric_name!("test_counter"); + + let mut collection = MetricCollection::default(); + + collection + .increment_counter( + &metric_name!("test_counter"), + &(label_name!("label_1"), LabelValue::new("value_1")).into(), + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + collection + .increment_counter( + &metric_name!("test_counter"), + &(label_name!("label_2"), LabelValue::new("value_2")).into(), + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + assert_eq!(collection.sum(&metric_name, &LabelSet::empty()), Some(2.0)); + assert_eq!( + collection.sum(&metric_name, &(label_name!("label_1"), LabelValue::new("value_1")).into()), + Some(1.0) + ); + } + + #[test] + fn type_gauge_with_two_samples() { + use crate::label::LabelSet; + use crate::metric_collection::MetricCollection; + use crate::metric_name; + + let metric_name = metric_name!("test_gauge"); + + let mut collection = MetricCollection::default(); + + collection + .increment_gauge( + &metric_name!("test_gauge"), + &(label_name!("label_1"), LabelValue::new("value_1")).into(), + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + collection + .increment_gauge( + &metric_name!("test_gauge"), + &(label_name!("label_2"), LabelValue::new("value_2")).into(), + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + assert_eq!(collection.sum(&metric_name, &LabelSet::empty()), Some(2.0)); + assert_eq!( + collection.sum(&metric_name, &(label_name!("label_1"), LabelValue::new("value_1")).into()), + Some(1.0) + ); + } + } +} diff --git a/packages/metrics/src/metric_collection/mod.rs b/packages/metrics/src/metric_collection/mod.rs new file mode 100644 index 000000000..e183236aa --- /dev/null +++ b/packages/metrics/src/metric_collection/mod.rs @@ -0,0 +1,1196 @@ +pub mod aggregate; + +use std::collections::{HashMap, HashSet}; + +use serde::ser::{SerializeSeq, Serializer}; +use serde::{Deserialize, Deserializer, Serialize}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::counter::Counter; +use super::gauge::Gauge; +use super::label::LabelSet; +use super::metric::{Metric, MetricName}; +use super::prometheus::PrometheusSerializable; +use crate::metric::description::MetricDescription; +use crate::sample_collection::SampleCollection; +use crate::unit::Unit; +use crate::METRICS_TARGET; + +// code-review: serialize in a deterministic order? For example: +// - First the counter metrics ordered by name. +// - Then the gauge metrics ordered by name. + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct MetricCollection { + counters: MetricKindCollection, + gauges: MetricKindCollection, +} + +impl MetricCollection { + /// # Errors + /// + /// Returns an error if there are duplicate metric names across counters and + /// gauges. + pub fn new(counters: MetricKindCollection, gauges: MetricKindCollection) -> Result { + // Check for name collisions across metric types + let counter_names: HashSet<_> = counters.names().collect(); + let gauge_names: HashSet<_> = gauges.names().collect(); + + if !counter_names.is_disjoint(&gauge_names) { + return Err(Error::MetricNameCollisionInConstructor { + counter_names: counter_names.iter().map(std::string::ToString::to_string).collect(), + gauge_names: gauge_names.iter().map(std::string::ToString::to_string).collect(), + }); + } + + Ok(Self { counters, gauges }) + } + + /// Merges another `MetricCollection` into this one. + /// + /// # Errors + /// + /// Returns an error if a metric name already exists in the current collection. + pub fn merge(&mut self, other: &Self) -> Result<(), Error> { + self.check_cross_type_collision(other)?; + self.counters.merge(&other.counters)?; + self.gauges.merge(&other.gauges)?; + Ok(()) + } + + /// Returns a set of all metric names in this collection. + fn collect_names(&self) -> HashSet { + self.counters.names().chain(self.gauges.names()).cloned().collect() + } + + /// Checks for name collisions between this collection and another one. + fn check_cross_type_collision(&self, other: &Self) -> Result<(), Error> { + let self_names: HashSet<_> = self.collect_names(); + let other_names: HashSet<_> = other.collect_names(); + + let cross_type_collisions = self_names.intersection(&other_names).next(); + + if let Some(name) = cross_type_collisions { + return Err(Error::MetricNameCollisionInMerge { + metric_name: (*name).clone(), + }); + } + + Ok(()) + } + + // Counter-specific methods + + pub fn describe_counter(&mut self, name: &MetricName, opt_unit: Option, opt_description: Option) { + tracing::info!(target: METRICS_TARGET, type = "counter", name = name.to_string(), unit = ?opt_unit, description = ?opt_description); + + let metric = Metric::::new(name.clone(), opt_unit, opt_description, SampleCollection::default()); + + self.counters.insert(metric); + } + + #[must_use] + pub fn contains_counter(&self, name: &MetricName) -> bool { + self.counters.metrics.contains_key(name) + } + + #[must_use] + pub fn get_counter_value(&self, name: &MetricName, label_set: &LabelSet) -> Option { + self.counters.get_value(name, label_set) + } + + /// Increases the counter for the given metric name and labels. + /// + /// # Errors + /// + /// Return an error if a metrics of a different type with the same name + /// already exists. + pub fn increment_counter( + &mut self, + name: &MetricName, + label_set: &LabelSet, + time: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + if self.gauges.metrics.contains_key(name) { + return Err(Error::MetricNameCollisionAdding { + metric_name: name.clone(), + }); + } + + self.counters.increment(name, label_set, time); + + Ok(()) + } + + /// Sets the counter for the given metric name and labels. + /// + /// # Errors + /// + /// Return an error if a metrics of a different type with the same name + /// already exists. + pub fn set_counter( + &mut self, + name: &MetricName, + label_set: &LabelSet, + value: u64, + time: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + if self.gauges.metrics.contains_key(name) { + return Err(Error::MetricNameCollisionAdding { + metric_name: name.clone(), + }); + } + + self.counters.absolute(name, label_set, value, time); + + Ok(()) + } + + // Gauge-specific methods + + pub fn describe_gauge(&mut self, name: &MetricName, opt_unit: Option, opt_description: Option) { + tracing::info!(target: METRICS_TARGET, type = "gauge", name = name.to_string(), unit = ?opt_unit, description = ?opt_description); + + let metric = Metric::::new(name.clone(), opt_unit, opt_description, SampleCollection::default()); + + self.gauges.insert(metric); + } + + #[must_use] + pub fn contains_gauge(&self, name: &MetricName) -> bool { + self.gauges.metrics.contains_key(name) + } + + #[must_use] + pub fn get_gauge_value(&self, name: &MetricName, label_set: &LabelSet) -> Option { + self.gauges.get_value(name, label_set) + } + + /// # Errors + /// + /// Return an error if a metrics of a different type with the same name + /// already exists. + pub fn set_gauge( + &mut self, + name: &MetricName, + label_set: &LabelSet, + value: f64, + time: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + if self.counters.metrics.contains_key(name) { + return Err(Error::MetricNameCollisionAdding { + metric_name: name.clone(), + }); + } + + self.gauges.set(name, label_set, value, time); + + Ok(()) + } + + /// # Errors + /// + /// Return an error if a metrics of a different type with the same name + /// already exists. + pub fn increment_gauge( + &mut self, + name: &MetricName, + label_set: &LabelSet, + time: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + if self.counters.metrics.contains_key(name) { + return Err(Error::MetricNameCollisionAdding { + metric_name: name.clone(), + }); + } + + self.gauges.increment(name, label_set, time); + + Ok(()) + } + + /// # Errors + /// + /// Return an error if a metrics of a different type with the same name + /// already exists. + pub fn decrement_gauge( + &mut self, + name: &MetricName, + label_set: &LabelSet, + time: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + if self.counters.metrics.contains_key(name) { + return Err(Error::MetricNameCollisionAdding { + metric_name: name.clone(), + }); + } + + self.gauges.decrement(name, label_set, time); + + Ok(()) + } +} + +#[derive(thiserror::Error, Debug, Clone)] +pub enum Error { + #[error("Metric names must be unique across all metrics types.")] + MetricNameCollisionInConstructor { + counter_names: Vec, + gauge_names: Vec, + }, + + #[error("Found duplicate metric name in list. Metric names must be unique across all metrics types.")] + DuplicateMetricNameInList { metric_name: MetricName }, + + #[error("Cannot merge metric '{metric_name}': it already exists in the current collection")] + MetricNameCollisionInMerge { metric_name: MetricName }, + + #[error("Cannot create metric with name '{metric_name}': another metric with this name already exists")] + MetricNameCollisionAdding { metric_name: MetricName }, +} + +/// Implements serialization for `MetricCollection`. +impl Serialize for MetricCollection { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + #[derive(Serialize)] + #[serde(tag = "type", rename_all = "lowercase")] + enum SerializableMetric<'a> { + Counter(&'a Metric), + Gauge(&'a Metric), + } + + let mut seq = serializer.serialize_seq(Some(self.counters.metrics.len() + self.gauges.metrics.len()))?; + + for metric in self.counters.metrics.values() { + seq.serialize_element(&SerializableMetric::Counter(metric))?; + } + + for metric in self.gauges.metrics.values() { + seq.serialize_element(&SerializableMetric::Gauge(metric))?; + } + + seq.end() + } +} + +impl<'de> Deserialize<'de> for MetricCollection { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + #[derive(Deserialize)] + #[serde(tag = "type", rename_all = "lowercase")] + enum MetricPayload { + Counter(Metric), + Gauge(Metric), + } + + let payload = Vec::::deserialize(deserializer)?; + + let mut counters = Vec::new(); + let mut gauges = Vec::new(); + + for metric in payload { + match metric { + MetricPayload::Counter(counter) => counters.push(counter), + MetricPayload::Gauge(gauge) => gauges.push(gauge), + } + } + + let counters = MetricKindCollection::new(counters).map_err(serde::de::Error::custom)?; + let gauges = MetricKindCollection::new(gauges).map_err(serde::de::Error::custom)?; + + let metric_collection = MetricCollection::new(counters, gauges).map_err(serde::de::Error::custom)?; + + Ok(metric_collection) + } +} + +impl PrometheusSerializable for MetricCollection { + fn to_prometheus(&self) -> String { + self.counters + .metrics + .values() + .filter(|metric| !metric.is_empty()) + .map(Metric::::to_prometheus) + .chain( + self.gauges + .metrics + .values() + .filter(|metric| !metric.is_empty()) + .map(Metric::::to_prometheus), + ) + .collect::>() + .join("\n\n") + } +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct MetricKindCollection { + metrics: HashMap>, +} + +impl MetricKindCollection { + /// Creates a new `MetricKindCollection` from a vector of metrics + /// + /// # Errors + /// + /// Returns an error if duplicate metric names are passed. + pub fn new(metrics: Vec>) -> Result { + let mut map = HashMap::with_capacity(metrics.len()); + + for metric in metrics { + let metric_name = metric.name().clone(); + + if let Some(_old_metric) = map.insert(metric.name().clone(), metric) { + return Err(Error::DuplicateMetricNameInList { metric_name }); + } + } + + Ok(Self { metrics: map }) + } + + /// Returns an iterator over all metric names in this collection. + pub fn names(&self) -> impl Iterator { + self.metrics.keys() + } + + pub fn insert_if_absent(&mut self, metric: Metric) { + if !self.metrics.contains_key(metric.name()) { + self.insert(metric); + } + } + + pub fn insert(&mut self, metric: Metric) { + self.metrics.insert(metric.name().clone(), metric); + } +} + +impl MetricKindCollection { + /// Merges another `MetricKindCollection` into this one. + /// + /// # Errors + /// + /// Returns an error if a metric name already exists in the current collection. + pub fn merge(&mut self, other: &Self) -> Result<(), Error> { + self.check_for_name_collision(other)?; + + for (metric_name, metric) in &other.metrics { + self.metrics.insert(metric_name.clone(), metric.clone()); + } + + Ok(()) + } + + fn check_for_name_collision(&self, other: &Self) -> Result<(), Error> { + for metric_name in other.metrics.keys() { + if self.metrics.contains_key(metric_name) { + return Err(Error::MetricNameCollisionInMerge { + metric_name: metric_name.clone(), + }); + } + } + + Ok(()) + } +} + +impl MetricKindCollection { + /// Increments the counter for the given metric name and labels. + /// + /// If the metric name does not exist, it will be created. + /// + /// # Panics + /// + /// Panics if the metric does not exist. + pub fn increment(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + let metric = Metric::::new_empty_with_name(name.clone()); + + self.insert_if_absent(metric); + + let metric = self.metrics.get_mut(name).expect("Counter metric should exist"); + + metric.increment(label_set, time); + } + + /// Sets the counter to an absolute value for the given metric name and labels. + /// + /// If the metric name does not exist, it will be created. + /// + /// # Panics + /// + /// Panics if the metric does not exist. + pub fn absolute(&mut self, name: &MetricName, label_set: &LabelSet, value: u64, time: DurationSinceUnixEpoch) { + let metric = Metric::::new_empty_with_name(name.clone()); + + self.insert_if_absent(metric); + + let metric = self.metrics.get_mut(name).expect("Counter metric should exist"); + + metric.absolute(label_set, value, time); + } + + #[must_use] + pub fn get_value(&self, name: &MetricName, label_set: &LabelSet) -> Option { + self.metrics + .get(name) + .and_then(|metric| metric.get_sample_data(label_set)) + .map(|sample| sample.value().clone()) + } +} + +impl MetricKindCollection { + /// Sets the gauge for the given metric name and labels. + /// + /// If the metric name does not exist, it will be created. + /// + /// # Panics + /// + /// Panics if the metric does not exist and it could not be created. + pub fn set(&mut self, name: &MetricName, label_set: &LabelSet, value: f64, time: DurationSinceUnixEpoch) { + let metric = Metric::::new_empty_with_name(name.clone()); + + self.insert_if_absent(metric); + + let metric = self.metrics.get_mut(name).expect("Gauge metric should exist"); + + metric.set(label_set, value, time); + } + + /// Increments the gauge for the given metric name and labels. + /// + /// If the metric name does not exist, it will be created. + /// + /// # Panics + /// + /// Panics if the metric does not exist and it could not be created. + pub fn increment(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + let metric = Metric::::new_empty_with_name(name.clone()); + + self.insert_if_absent(metric); + + let metric = self.metrics.get_mut(name).expect("Gauge metric should exist"); + + metric.increment(label_set, time); + } + + /// Decrements the gauge for the given metric name and labels. + /// + /// If the metric name does not exist, it will be created. + /// + /// # Panics + /// + /// Panics if the metric does not exist and it could not be created. + pub fn decrement(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + let metric = Metric::::new_empty_with_name(name.clone()); + + self.insert_if_absent(metric); + + let metric = self.metrics.get_mut(name).expect("Gauge metric should exist"); + + metric.decrement(label_set, time); + } + + #[must_use] + pub fn get_value(&self, name: &MetricName, label_set: &LabelSet) -> Option { + self.metrics + .get(name) + .and_then(|metric| metric.get_sample_data(label_set)) + .map(|sample| sample.value().clone()) + } +} + +#[cfg(test)] +mod tests { + + use pretty_assertions::assert_eq; + + use super::*; + use crate::label::LabelValue; + use crate::sample::Sample; + use crate::sample_collection::SampleCollection; + use crate::tests::{format_prometheus_output, sort_lines}; + use crate::{label_name, metric_name}; + + /// Fixture for testing serialization and deserialization of `MetricCollection`. + /// + /// It contains a default `MetricCollection` object, its JSON representation, + /// and its Prometheus format representation. + struct MetricCollectionFixture { + pub object: MetricCollection, + pub json: String, + pub prometheus: String, + } + + impl Default for MetricCollectionFixture { + fn default() -> Self { + Self { + object: Self::object(), + json: Self::json(), + prometheus: Self::prometheus(), + } + } + } + + impl MetricCollectionFixture { + fn deconstruct(&self) -> (MetricCollection, String, String) { + (self.object.clone(), self.json.clone(), self.prometheus.clone()) + } + + fn object() -> MetricCollection { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + + let label_set_1: LabelSet = [ + (label_name!("server_binding_protocol"), LabelValue::new("http")), + (label_name!("server_binding_ip"), LabelValue::new("0.0.0.0")), + (label_name!("server_binding_port"), LabelValue::new("7070")), + ] + .into(); + + MetricCollection::new( + MetricKindCollection::new(vec![Metric::new( + metric_name!("http_tracker_core_announce_requests_received_total"), + None, + Some(MetricDescription::new("The number of announce requests received.")), + SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set_1.clone())]).unwrap(), + )]) + .unwrap(), + MetricKindCollection::new(vec![Metric::new( + metric_name!("udp_tracker_server_performance_avg_announce_processing_time_ns"), + None, + Some(MetricDescription::new("The average announce processing time in nanoseconds.")), + SampleCollection::new(vec![Sample::new(Gauge::new(1.0), time, label_set_1.clone())]).unwrap(), + )]) + .unwrap(), + ) + .unwrap() + } + + fn json() -> String { + r#" + [ + { + "type":"counter", + "name":"http_tracker_core_announce_requests_received_total", + "unit": null, + "description": "The number of announce requests received.", + "samples":[ + { + "value":1, + "recorded_at":"2025-04-02T00:00:00+00:00", + "labels":[ + { + "name":"server_binding_ip", + "value":"0.0.0.0" + }, + { + "name":"server_binding_port", + "value":"7070" + }, + { + "name":"server_binding_protocol", + "value":"http" + } + ] + } + ] + }, + { + "type":"gauge", + "name":"udp_tracker_server_performance_avg_announce_processing_time_ns", + "unit": null, + "description": "The average announce processing time in nanoseconds.", + "samples":[ + { + "value":1.0, + "recorded_at":"2025-04-02T00:00:00+00:00", + "labels":[ + { + "name":"server_binding_ip", + "value":"0.0.0.0" + }, + { + "name":"server_binding_port", + "value":"7070" + }, + { + "name":"server_binding_protocol", + "value":"http" + } + ] + } + ] + } + ] + "# + .to_owned() + } + + fn prometheus() -> String { + format_prometheus_output( + r#"# HELP http_tracker_core_announce_requests_received_total The number of announce requests received. +# TYPE http_tracker_core_announce_requests_received_total counter +http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 + +# HELP udp_tracker_server_performance_avg_announce_processing_time_ns The average announce processing time in nanoseconds. +# TYPE udp_tracker_server_performance_avg_announce_processing_time_ns gauge +udp_tracker_server_performance_avg_announce_processing_time_ns{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 +"#, + ) + } + } + + #[test] + fn it_should_not_allow_duplicate_names_across_types() { + let counters = MetricKindCollection::new(vec![Metric::new( + metric_name!("test_metric"), + None, + None, + SampleCollection::default(), + )]) + .unwrap(); + let gauges = MetricKindCollection::new(vec![Metric::new( + metric_name!("test_metric"), + None, + None, + SampleCollection::default(), + )]) + .unwrap(); + + assert!(MetricCollection::new(counters, gauges).is_err()); + } + + #[test] + fn it_should_not_allow_creating_a_gauge_with_the_same_name_as_a_counter() { + let mut collection = MetricCollection::default(); + let label_set = LabelSet::default(); + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + + // First create a counter + collection + .increment_counter(&metric_name!("test_metric"), &label_set, time) + .unwrap(); + + // Then try to create a gauge with the same name + let result = collection.set_gauge(&metric_name!("test_metric"), &label_set, 1.0, time); + + assert!(result.is_err()); + } + + #[test] + fn it_should_not_allow_creating_a_counter_with_the_same_name_as_a_gauge() { + let mut collection = MetricCollection::default(); + let label_set = LabelSet::default(); + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + + // First set the gauge + collection + .set_gauge(&metric_name!("test_metric"), &label_set, 1.0, time) + .unwrap(); + + // Then try to create a counter with the same name + let result = collection.increment_counter(&metric_name!("test_metric"), &label_set, time); + + assert!(result.is_err()); + } + + #[test] + fn it_should_allow_serializing_to_json() { + // todo: this test does work with metric with multiple samples because + // samples are not serialized in the same order as they are created. + let (metric_collection, expected_json, _expected_prometheus) = MetricCollectionFixture::default().deconstruct(); + + let json = serde_json::to_string_pretty(&metric_collection).unwrap(); + + assert_eq!( + serde_json::from_str::(&json).unwrap(), + serde_json::from_str::(&expected_json).unwrap() + ); + } + + #[test] + fn it_should_allow_deserializing_from_json() { + let (expected_metric_collection, metric_collection_json, _expected_prometheus) = + MetricCollectionFixture::default().deconstruct(); + + let metric_collection: MetricCollection = serde_json::from_str(&metric_collection_json).unwrap(); + + assert_eq!(metric_collection, expected_metric_collection); + } + + #[test] + fn it_should_allow_serializing_to_prometheus_format() { + let (metric_collection, _expected_json, expected_prometheus) = MetricCollectionFixture::default().deconstruct(); + + let prometheus_output = metric_collection.to_prometheus(); + + assert_eq!(prometheus_output, expected_prometheus); + } + + #[test] + fn it_should_allow_serializing_to_prometheus_format_with_multiple_samples_per_metric() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + + let label_set_1: LabelSet = [ + (label_name!("server_binding_protocol"), LabelValue::new("http")), + (label_name!("server_binding_ip"), LabelValue::new("0.0.0.0")), + (label_name!("server_binding_port"), LabelValue::new("7070")), + ] + .into(); + + let label_set_2: LabelSet = [ + (label_name!("server_binding_protocol"), LabelValue::new("http")), + (label_name!("server_binding_ip"), LabelValue::new("0.0.0.0")), + (label_name!("server_binding_port"), LabelValue::new("7171")), + ] + .into(); + + let metric_collection = MetricCollection::new( + MetricKindCollection::new(vec![Metric::new( + metric_name!("http_tracker_core_announce_requests_received_total"), + None, + Some(MetricDescription::new("The number of announce requests received.")), + SampleCollection::new(vec![ + Sample::new(Counter::new(1), time, label_set_1.clone()), + Sample::new(Counter::new(2), time, label_set_2.clone()), + ]) + .unwrap(), + )]) + .unwrap(), + MetricKindCollection::default(), + ) + .unwrap(); + + let prometheus_output = metric_collection.to_prometheus(); + + let expected_prometheus_output = format_prometheus_output( + r#"# HELP http_tracker_core_announce_requests_received_total The number of announce requests received. +# TYPE http_tracker_core_announce_requests_received_total counter +http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 +http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7171",server_binding_protocol="http"} 2 +"#, + ); + + // code-review: samples are not serialized in the same order as they are created. + // Should we use a deterministic order? + + assert_eq!(sort_lines(&prometheus_output), sort_lines(&expected_prometheus_output)); + } + + #[test] + fn it_should_exclude_metrics_without_samples_from_prometheus_format() { + let mut counters = MetricKindCollection::default(); + let mut gauges = MetricKindCollection::default(); + + let counter = Metric::::new_empty_with_name(metric_name!("test_counter")); + counters.insert_if_absent(counter); + + let gauge = Metric::::new_empty_with_name(metric_name!("test_gauge")); + gauges.insert_if_absent(gauge); + + let metric_collection = MetricCollection::new(counters, gauges).unwrap(); + + let prometheus_output = metric_collection.to_prometheus(); + + assert_eq!(prometheus_output, ""); + } + + #[test] + fn it_should_allow_merging_metric_collections() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection1 = MetricCollection::default(); + collection1 + .increment_counter(&metric_name!("test_counter"), &label_set, time) + .unwrap(); + + let mut collection2 = MetricCollection::default(); + collection2 + .set_gauge(&metric_name!("test_gauge"), &label_set, 1.0, time) + .unwrap(); + + collection1.merge(&collection2).unwrap(); + + assert!(collection1.contains_counter(&metric_name!("test_counter"))); + assert!(collection1.contains_gauge(&metric_name!("test_gauge"))); + } + + #[test] + fn it_should_not_allow_merging_metric_collections_with_name_collisions_for_the_same_metric_types() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection1 = MetricCollection::default(); + collection1 + .increment_counter(&metric_name!("test_metric"), &label_set, time) + .unwrap(); + + let mut collection2 = MetricCollection::default(); + collection2 + .increment_counter(&metric_name!("test_metric"), &label_set, time) + .unwrap(); + let result = collection1.merge(&collection2); + + assert!(result.is_err()); + } + + #[test] + fn it_should_not_allow_merging_metric_collections_with_name_collisions_for_different_metric_types() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection1 = MetricCollection::default(); + collection1 + .increment_counter(&metric_name!("test_metric"), &label_set, time) + .unwrap(); + + let mut collection2 = MetricCollection::default(); + collection2 + .set_gauge(&metric_name!("test_metric"), &label_set, 1.0, time) + .unwrap(); + + let result = collection1.merge(&collection2); + + assert!(result.is_err()); + } + + fn collection_with_one_counter(metric_name: &MetricName, label_set: &LabelSet, counter: Counter) -> MetricCollection { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + + MetricCollection::new( + MetricKindCollection::new(vec![Metric::new( + metric_name.clone(), + None, + None, + SampleCollection::new(vec![Sample::new(counter, time, label_set.clone())]).unwrap(), + )]) + .unwrap(), + MetricKindCollection::default(), + ) + .unwrap() + } + + fn collection_with_one_gauge(metric_name: &MetricName, label_set: &LabelSet, gauge: Gauge) -> MetricCollection { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + + MetricCollection::new( + MetricKindCollection::default(), + MetricKindCollection::new(vec![Metric::new( + metric_name.clone(), + None, + None, + SampleCollection::new(vec![Sample::new(gauge, time, label_set.clone())]).unwrap(), + )]) + .unwrap(), + ) + .unwrap() + } + + mod for_counters { + + use pretty_assertions::assert_eq; + + use super::*; + use crate::label::LabelValue; + use crate::sample::Sample; + use crate::sample_collection::SampleCollection; + + #[test] + fn it_should_allow_setting_to_an_absolute_value() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let metric_name = metric_name!("test_counter"); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection = collection_with_one_counter(&metric_name, &label_set, Counter::new(0)); + + collection + .set_counter(&metric_name!("test_counter"), &label_set, 1, time) + .unwrap(); + + assert_eq!( + collection.get_counter_value(&metric_name!("test_counter"), &label_set), + Some(Counter::new(1)) + ); + } + + #[test] + fn it_should_fail_setting_to_an_absolute_value_if_a_gauge_with_the_same_name_exists() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let metric_name = metric_name!("test_counter"); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection = collection_with_one_gauge(&metric_name, &label_set, Gauge::new(0.0)); + + let result = collection.set_counter(&metric_name!("test_counter"), &label_set, 1, time); + + assert!( + result.is_err() + && matches!(result, Err(Error::MetricNameCollisionAdding { metric_name }) if metric_name == metric_name!("test_counter")) + ); + } + + #[test] + fn it_should_increase_a_preexistent_counter() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let metric_name = metric_name!("test_counter"); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection = collection_with_one_counter(&metric_name, &label_set, Counter::new(0)); + + collection + .increment_counter(&metric_name!("test_counter"), &label_set, time) + .unwrap(); + + assert_eq!( + collection.get_counter_value(&metric_name!("test_counter"), &label_set), + Some(Counter::new(1)) + ); + } + + #[test] + fn it_should_automatically_create_a_counter_when_increasing_if_it_does_not_exist() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut metric_collection = + MetricCollection::new(MetricKindCollection::default(), MetricKindCollection::default()).unwrap(); + + metric_collection + .increment_counter(&metric_name!("test_counter"), &label_set, time) + .unwrap(); + metric_collection + .increment_counter(&metric_name!("test_counter"), &label_set, time) + .unwrap(); + + assert_eq!( + metric_collection.get_counter_value(&metric_name!("test_counter"), &label_set), + Some(Counter::new(2)) + ); + } + + #[test] + fn it_should_allow_describing_a_counter_before_using_it() { + let mut metric_collection = + MetricCollection::new(MetricKindCollection::default(), MetricKindCollection::default()).unwrap(); + + metric_collection.describe_counter(&metric_name!("test_counter"), None, None); + + assert!(metric_collection.contains_counter(&metric_name!("test_counter"))); + } + + #[test] + fn it_should_not_allow_duplicate_metric_names_when_instantiating() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let result = MetricKindCollection::new(vec![ + Metric::new( + metric_name!("test_counter"), + None, + None, + SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]).unwrap(), + ), + Metric::new( + metric_name!("test_counter"), + None, + None, + SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]).unwrap(), + ), + ]); + + assert!(result.is_err()); + } + } + + mod for_gauges { + + use pretty_assertions::assert_eq; + + use super::*; + use crate::label::LabelValue; + use crate::sample::Sample; + use crate::sample_collection::SampleCollection; + + #[test] + fn it_should_set_a_preexistent_gauge() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let metric_name = metric_name!("test_gauge"); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection = collection_with_one_gauge(&metric_name, &label_set, Gauge::new(0.0)); + + collection + .set_gauge(&metric_name!("test_gauge"), &label_set, 1.0, time) + .unwrap(); + + assert_eq!( + collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), + Some(Gauge::new(1.0)) + ); + } + + #[test] + fn it_should_allow_incrementing_a_gauge() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let metric_name = metric_name!("test_gauge"); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection = collection_with_one_gauge(&metric_name, &label_set, Gauge::new(0.0)); + + collection + .increment_gauge(&metric_name!("test_gauge"), &label_set, time) + .unwrap(); + + assert_eq!( + collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), + Some(Gauge::new(1.0)) + ); + } + + #[test] + fn it_should_fail_incrementing_a_gauge_if_it_exists_a_counter_with_the_same_name() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let metric_name = metric_name!("test_gauge"); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection = collection_with_one_counter(&metric_name, &label_set, Counter::new(0)); + + let result = collection.increment_gauge(&metric_name!("test_gauge"), &label_set, time); + + assert!( + result.is_err() + && matches!(result, Err(Error::MetricNameCollisionAdding { metric_name }) if metric_name == metric_name!("test_gauge")) + ); + } + + #[test] + fn it_should_allow_decrementing_a_gauge() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let metric_name = metric_name!("test_gauge"); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection = collection_with_one_gauge(&metric_name, &label_set, Gauge::new(1.0)); + + collection + .decrement_gauge(&metric_name!("test_gauge"), &label_set, time) + .unwrap(); + + assert_eq!( + collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), + Some(Gauge::new(0.0)) + ); + } + + #[test] + fn it_should_fail_decrementing_a_gauge_if_it_exists_a_counter_with_the_same_name() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let metric_name = metric_name!("test_gauge"); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection = collection_with_one_counter(&metric_name, &label_set, Counter::new(0)); + + let result = collection.decrement_gauge(&metric_name!("test_gauge"), &label_set, time); + + assert!( + result.is_err() + && matches!(result, Err(Error::MetricNameCollisionAdding { metric_name }) if metric_name == metric_name!("test_gauge")) + ); + } + + #[test] + fn it_should_automatically_create_a_gauge_when_setting_if_it_does_not_exist() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut metric_collection = + MetricCollection::new(MetricKindCollection::default(), MetricKindCollection::default()).unwrap(); + + metric_collection + .set_gauge(&metric_name!("test_gauge"), &label_set, 1.0, time) + .unwrap(); + + assert_eq!( + metric_collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), + Some(Gauge::new(1.0)) + ); + } + + #[test] + fn it_should_allow_describing_a_gauge_before_using_it() { + let mut metric_collection = + MetricCollection::new(MetricKindCollection::default(), MetricKindCollection::default()).unwrap(); + + metric_collection.describe_gauge(&metric_name!("test_gauge"), None, None); + + assert!(metric_collection.contains_gauge(&metric_name!("test_gauge"))); + } + + #[test] + fn it_should_not_allow_duplicate_metric_names_when_instantiating() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let result = MetricKindCollection::new(vec![ + Metric::new( + metric_name!("test_gauge"), + None, + None, + SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]).unwrap(), + ), + Metric::new( + metric_name!("test_gauge"), + None, + None, + SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]).unwrap(), + ), + ]); + + assert!(result.is_err()); + } + } + + mod metric_kind_collection { + + use crate::counter::Counter; + use crate::gauge::Gauge; + use crate::metric::Metric; + use crate::metric_collection::{Error, MetricKindCollection}; + use crate::metric_name; + + #[test] + fn it_should_not_allow_merging_counter_metric_collections_with_name_collisions() { + let mut collection1 = MetricKindCollection::::default(); + collection1.insert(Metric::::new_empty_with_name(metric_name!("test_metric"))); + + let mut collection2 = MetricKindCollection::::default(); + collection2.insert(Metric::::new_empty_with_name(metric_name!("test_metric"))); + + let result = collection1.merge(&collection2); + + assert!( + result.is_err() + && matches!(result, Err(Error::MetricNameCollisionInMerge { metric_name }) if metric_name == metric_name!("test_metric")) + ); + } + + #[test] + fn it_should_not_allow_merging_gauge_metric_collections_with_name_collisions() { + let mut collection1 = MetricKindCollection::::default(); + collection1.insert(Metric::::new_empty_with_name(metric_name!("test_metric"))); + + let mut collection2 = MetricKindCollection::::default(); + collection2.insert(Metric::::new_empty_with_name(metric_name!("test_metric"))); + + let result = collection1.merge(&collection2); + + assert!( + result.is_err() + && matches!(result, Err(Error::MetricNameCollisionInMerge { metric_name }) if metric_name == metric_name!("test_metric")) + ); + } + } +} diff --git a/packages/metrics/src/prometheus.rs b/packages/metrics/src/prometheus.rs new file mode 100644 index 000000000..bf058e442 --- /dev/null +++ b/packages/metrics/src/prometheus.rs @@ -0,0 +1,15 @@ +pub trait PrometheusSerializable { + /// Convert the implementing type into a Prometheus exposition format string. + /// + /// # Returns + /// + /// A `String` containing the serialized representation. + fn to_prometheus(&self) -> String; +} + +// Blanket implementation for references +impl PrometheusSerializable for &T { + fn to_prometheus(&self) -> String { + (*self).to_prometheus() + } +} diff --git a/packages/metrics/src/sample.rs b/packages/metrics/src/sample.rs new file mode 100644 index 000000000..63f46b9b8 --- /dev/null +++ b/packages/metrics/src/sample.rs @@ -0,0 +1,469 @@ +use chrono::{DateTime, Utc}; +use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::counter::Counter; +use super::gauge::Gauge; +use super::label::LabelSet; +use super::prometheus::PrometheusSerializable; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Sample { + #[serde(flatten)] + measurement: Measurement, + + #[serde(rename = "labels")] + label_set: LabelSet, +} + +impl Sample { + #[must_use] + pub fn new(value: T, recorded_at: DurationSinceUnixEpoch, label_set: LabelSet) -> Self { + let data = Measurement { value, recorded_at }; + + Self { + measurement: data, + label_set, + } + } + + #[must_use] + pub fn measurement(&self) -> &Measurement { + &self.measurement + } + + #[must_use] + pub fn value(&self) -> &T { + &self.measurement.value + } + + #[must_use] + pub fn recorded_at(&self) -> DurationSinceUnixEpoch { + self.measurement.recorded_at + } + + #[must_use] + pub fn labels(&self) -> &LabelSet { + &self.label_set + } +} + +impl PrometheusSerializable for Sample { + fn to_prometheus(&self) -> String { + if self.label_set.is_empty() { + format!(" {}", self.measurement.to_prometheus()) + } else { + format!("{} {}", self.label_set.to_prometheus(), self.measurement.to_prometheus()) + } + } +} + +impl Sample { + pub fn increment(&mut self, time: DurationSinceUnixEpoch) { + self.measurement.increment(time); + } +} + +impl Sample { + pub fn set(&mut self, value: f64, time: DurationSinceUnixEpoch) { + self.measurement.set(value, time); + } + + pub fn increment(&mut self, time: DurationSinceUnixEpoch) { + self.measurement.increment(time); + } + + pub fn decrement(&mut self, time: DurationSinceUnixEpoch) { + self.measurement.decrement(time); + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Measurement { + /// The value of the sample. + value: T, + + /// The time when the sample was last updated. + #[serde(serialize_with = "serialize_duration", deserialize_with = "deserialize_duration")] + recorded_at: DurationSinceUnixEpoch, +} + +impl Measurement { + #[must_use] + pub fn new(value: T, recorded_at: DurationSinceUnixEpoch) -> Self { + Self { value, recorded_at } + } + + #[must_use] + pub fn value(&self) -> &T { + &self.value + } + + #[must_use] + pub fn recorded_at(&self) -> DurationSinceUnixEpoch { + self.recorded_at + } + + fn set_recorded_at(&mut self, time: DurationSinceUnixEpoch) { + self.recorded_at = time; + } +} + +impl From> for (LabelSet, Measurement) { + fn from(sample: Sample) -> Self { + (sample.label_set, sample.measurement) + } +} + +impl PrometheusSerializable for Measurement { + fn to_prometheus(&self) -> String { + self.value.to_prometheus() + } +} + +impl Measurement { + pub fn increment(&mut self, time: DurationSinceUnixEpoch) { + self.value.increment(1); + self.set_recorded_at(time); + } + + pub fn absolute(&mut self, value: u64, time: DurationSinceUnixEpoch) { + self.value.absolute(value); + self.set_recorded_at(time); + } +} + +impl Measurement { + pub fn set(&mut self, value: f64, time: DurationSinceUnixEpoch) { + self.value.set(value); + self.set_recorded_at(time); + } + + pub fn increment(&mut self, time: DurationSinceUnixEpoch) { + self.value.increment(1.0); + self.set_recorded_at(time); + } + + pub fn decrement(&mut self, time: DurationSinceUnixEpoch) { + self.value.decrement(1.0); + self.set_recorded_at(time); + } +} + +/// Serializes the `recorded_at` field as a string in ISO 8601 format (RFC 3339). +/// +/// # Errors +/// +/// Returns an error if: +/// - The conversion from `u64` to `i64` fails. +/// - The timestamp is invalid. +fn serialize_duration(duration: &DurationSinceUnixEpoch, serializer: S) -> Result +where + S: Serializer, +{ + let secs = i64::try_from(duration.as_secs()).map_err(|_| serde::ser::Error::custom("Timestamp too large"))?; + let nanos = duration.subsec_nanos(); + + let datetime = DateTime::from_timestamp(secs, nanos).ok_or_else(|| serde::ser::Error::custom("Invalid timestamp"))?; + + serializer.serialize_str(&datetime.to_rfc3339()) // Serializes as ISO 8601 (RFC 3339) +} + +fn deserialize_duration<'de, D>(deserializer: D) -> Result +where + D: Deserializer<'de>, +{ + // Deserialize theISO 8601 (RFC 3339) formatted string + let datetime_str = String::deserialize(deserializer)?; + + let datetime = + DateTime::parse_from_rfc3339(&datetime_str).map_err(|e| de::Error::custom(format!("Invalid datetime format: {e}")))?; + + let datetime_utc = datetime.with_timezone(&Utc); + + let secs = u64::try_from(datetime_utc.timestamp()).map_err(|_| de::Error::custom("Timestamp out of range"))?; + + Ok(DurationSinceUnixEpoch::new(secs, datetime_utc.timestamp_subsec_nanos())) +} + +#[cfg(test)] +mod tests { + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use super::*; + + // Helper function to create a sample update time. + fn updated_at_time() -> DurationSinceUnixEpoch { + DurationSinceUnixEpoch::from_secs(1_743_552_000) + } + + #[test] + fn it_should_have_a_value() { + let sample = Sample::new( + 42, + DurationSinceUnixEpoch::from_secs(1_743_552_000), + LabelSet::from(vec![("test", "label")]), + ); + + assert_eq!(sample.value(), &42); + } + + #[test] + fn it_should_record_the_latest_update_time() { + let sample = Sample::new( + 42, + DurationSinceUnixEpoch::from_secs(1_743_552_000), + LabelSet::from(vec![("test", "label")]), + ); + + assert_eq!(sample.recorded_at(), updated_at_time()); + } + + #[test] + fn it_should_include_a_label_set() { + let sample = Sample::new( + 42, + DurationSinceUnixEpoch::from_secs(1_743_552_000), + LabelSet::from(vec![("test", "label")]), + ); + + assert_eq!(sample.labels(), &LabelSet::from(vec![("test", "label")])); + } + + mod for_counter_type_sample { + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::label::LabelSet; + use crate::prometheus::PrometheusSerializable; + use crate::sample::tests::updated_at_time; + use crate::sample::{Counter, Sample}; + + #[test] + fn it_should_allow_a_counter_type_value() { + let sample = Sample::new( + Counter::new(42), + DurationSinceUnixEpoch::from_secs(1_743_552_000), + LabelSet::from(vec![("label_name", "label vale")]), + ); + + assert_eq!(sample.value(), &Counter::new(42)); + } + + #[test] + fn it_should_allow_incrementing_the_counter() { + let mut sample = Sample::new(Counter::default(), DurationSinceUnixEpoch::default(), LabelSet::default()); + + sample.increment(updated_at_time()); + + assert_eq!(sample.value(), &Counter::new(1)); + } + + #[test] + fn it_should_record_the_latest_update_time_when_the_counter_is_incremented() { + let mut sample = Sample::new(Counter::default(), DurationSinceUnixEpoch::default(), LabelSet::default()); + + let time = updated_at_time(); + + sample.increment(time); + + assert_eq!(sample.recorded_at(), time); + } + + #[test] + fn it_should_allow_exporting_to_prometheus_format() { + let counter = Counter::new(42); + + let labels = LabelSet::from(vec![("label_name", "label_value"), ("method", "GET")]); + + let sample = Sample::new(counter, DurationSinceUnixEpoch::default(), labels); + + assert_eq!(sample.to_prometheus(), r#"{label_name="label_value",method="GET"} 42"#); + } + + #[test] + fn it_should_allow_exporting_to_prometheus_format_with_empty_label_set() { + let counter = Counter::new(42); + + let sample = Sample::new(counter, DurationSinceUnixEpoch::default(), LabelSet::default()); + + assert_eq!(sample.to_prometheus(), " 42"); + } + } + mod for_gauge_type_sample { + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::label::LabelSet; + use crate::prometheus::PrometheusSerializable; + use crate::sample::tests::updated_at_time; + use crate::sample::{Gauge, Sample}; + + #[test] + fn it_should_allow_a_counter_type_value() { + let sample = Sample::new( + Gauge::new(42.0), + DurationSinceUnixEpoch::from_secs(1_743_552_000), + LabelSet::from(vec![("label_name", "label vale")]), + ); + + assert_eq!(sample.value(), &Gauge::new(42.0)); + } + + #[test] + fn it_should_allow_setting_a_value() { + let mut sample = Sample::new(Gauge::default(), DurationSinceUnixEpoch::default(), LabelSet::default()); + + sample.set(1.0, updated_at_time()); + + assert_eq!(sample.value(), &Gauge::new(1.0)); + } + + #[test] + fn it_should_allow_incrementing_the_value() { + let mut sample = Sample::new(Gauge::new(0.0), DurationSinceUnixEpoch::default(), LabelSet::default()); + + sample.increment(updated_at_time()); + + assert_eq!(sample.value(), &Gauge::new(1.0)); + } + + #[test] + fn it_should_allow_decrementing_the_value() { + let mut sample = Sample::new(Gauge::new(1.0), DurationSinceUnixEpoch::default(), LabelSet::default()); + + sample.decrement(updated_at_time()); + + assert_eq!(sample.value(), &Gauge::new(0.0)); + } + + #[test] + fn it_should_record_the_latest_update_time_when_the_counter_is_incremented() { + let mut sample = Sample::new(Gauge::default(), DurationSinceUnixEpoch::default(), LabelSet::default()); + + let time = updated_at_time(); + + sample.set(1.0, time); + + assert_eq!(sample.recorded_at(), time); + } + + #[test] + fn it_should_allow_exporting_to_prometheus_format() { + let counter = Gauge::new(42.0); + + let labels = LabelSet::from(vec![("label_name", "label_value"), ("method", "GET")]); + + let sample = Sample::new(counter, DurationSinceUnixEpoch::default(), labels); + + assert_eq!(sample.to_prometheus(), r#"{label_name="label_value",method="GET"} 42"#); + } + + #[test] + fn it_should_allow_exporting_to_prometheus_format_with_empty_label_set() { + let gauge = Gauge::new(42.0); + + let sample = Sample::new(gauge, DurationSinceUnixEpoch::default(), LabelSet::default()); + + assert_eq!(sample.to_prometheus(), " 42"); + } + } + + mod serialization_to_json { + use pretty_assertions::assert_eq; + use serde_json::json; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::label::LabelSet; + use crate::sample::tests::updated_at_time; + use crate::sample::Sample; + + #[test] + fn test_serialization_round_trip() { + let original = Sample::new(42, updated_at_time(), LabelSet::from(vec![("test", "serialization")])); + + let json = serde_json::to_string(&original).unwrap(); + let deserialized: Sample = serde_json::from_str(&json).unwrap(); + + assert_eq!(original.measurement.value, deserialized.measurement.value); + assert_eq!(original.measurement.recorded_at, deserialized.measurement.recorded_at); + assert_eq!(original.label_set, deserialized.label_set); + } + + #[test] + fn test_rfc3339_serialization_format_for_update_time() { + let sample = Sample::new( + 42, + DurationSinceUnixEpoch::new(1_743_552_000, 100), + LabelSet::from(vec![("label_name", "label value")]), + ); + + let json = serde_json::to_string(&sample).unwrap(); + + let expected_json = r#" + { + "value": 42, + "recorded_at": "2025-04-02T00:00:00.000000100+00:00", + "labels": [ + { + "name": "label_name", + "value": "label value" + } + ] + } + "#; + + assert_eq!( + serde_json::from_str::(&json).unwrap(), + serde_json::from_str::(expected_json).unwrap() + ); + } + + #[test] + fn test_invalid_update_timestamp_serialization() { + let timestamp_too_large = DurationSinceUnixEpoch::new(i64::MAX as u64 + 1, 0); + + let sample = Sample::new(42, timestamp_too_large, LabelSet::from(vec![("label_name", "label value")])); + + let result = serde_json::to_string(&sample); + + assert!(result.is_err()); + assert!(result.unwrap_err().to_string().contains("Timestamp too large")); + } + + #[test] + fn test_invalid_update_datetime_deserialization() { + let invalid_json = json!( + r#" + { + "value": 42, + "recorded_at": "1-1-2023T25:00:00Z", + "labels": [ + { + "name": "label_name", + "value": "label value" + } + ] + } + "# + ); + + let result: Result = serde_json::from_value(invalid_json); + + assert!(result.unwrap_err().to_string().contains("invalid type")); + } + + #[test] + fn test_update_datetime_high_precision_nanoseconds() { + let sample = Sample::new( + 42, + DurationSinceUnixEpoch::new(1_743_552_000, 100), + LabelSet::from(vec![("label_name", "label value")]), + ); + + let json = serde_json::to_string(&sample).unwrap(); + + let deserialized: Sample = serde_json::from_str(&json).unwrap(); + + assert_eq!(deserialized, sample); + } + } +} diff --git a/packages/metrics/src/sample_collection.rs b/packages/metrics/src/sample_collection.rs new file mode 100644 index 000000000..e520d7310 --- /dev/null +++ b/packages/metrics/src/sample_collection.rs @@ -0,0 +1,543 @@ +use std::collections::hash_map::Iter; +use std::collections::HashMap; +use std::fmt::Write as _; + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::counter::Counter; +use super::gauge::Gauge; +use super::label::LabelSet; +use super::prometheus::PrometheusSerializable; +use super::sample::Sample; +use crate::sample::Measurement; + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct SampleCollection { + samples: HashMap>, +} + +impl SampleCollection { + /// Creates a new `MetricKindCollection` from a vector of metrics + /// + /// # Errors + /// + /// Returns an error if there are duplicate `LabelSets` in the provided + /// samples. + pub fn new(samples: Vec>) -> Result { + let mut map: HashMap> = HashMap::with_capacity(samples.len()); + + for sample in samples { + let (label_set, sample_data): (LabelSet, Measurement) = sample.into(); + + let label_set_clone = label_set.clone(); + + if let Some(_old_measurement) = map.insert(label_set, sample_data) { + return Err(Error::DuplicateLabelSetInList { + label_set: label_set_clone, + }); + } + } + + Ok(Self { samples: map }) + } + + #[must_use] + pub fn get(&self, label: &LabelSet) -> Option<&Measurement> { + self.samples.get(label) + } + + #[must_use] + pub fn len(&self) -> usize { + self.samples.len() + } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.samples.is_empty() + } + + #[must_use] + #[allow(clippy::iter_without_into_iter)] + pub fn iter(&self) -> Iter<'_, LabelSet, Measurement> { + self.samples.iter() + } +} + +#[derive(thiserror::Error, Debug, Clone)] +pub enum Error { + #[error("Found duplicate label set in list. Label set must be unique in a SampleCollection.")] + DuplicateLabelSetInList { label_set: LabelSet }, +} + +impl SampleCollection { + pub fn increment(&mut self, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + let sample = self + .samples + .entry(label_set.clone()) + .or_insert_with(|| Measurement::new(Counter::default(), time)); + + sample.increment(time); + } + + pub fn absolute(&mut self, label_set: &LabelSet, value: u64, time: DurationSinceUnixEpoch) { + let sample = self + .samples + .entry(label_set.clone()) + .or_insert_with(|| Measurement::new(Counter::default(), time)); + + sample.absolute(value, time); + } +} + +impl SampleCollection { + pub fn set(&mut self, label_set: &LabelSet, value: f64, time: DurationSinceUnixEpoch) { + let sample = self + .samples + .entry(label_set.clone()) + .or_insert_with(|| Measurement::new(Gauge::default(), time)); + + sample.set(value, time); + } + + pub fn increment(&mut self, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + let sample = self + .samples + .entry(label_set.clone()) + .or_insert_with(|| Measurement::new(Gauge::default(), time)); + + sample.increment(time); + } + + pub fn decrement(&mut self, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + let sample = self + .samples + .entry(label_set.clone()) + .or_insert_with(|| Measurement::new(Gauge::default(), time)); + + sample.decrement(time); + } +} + +impl Serialize for SampleCollection { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut samples: Vec> = vec![]; + + for (label_set, sample_data) in &self.samples { + samples.push(Sample::new(sample_data.value(), sample_data.recorded_at(), label_set.clone())); + } + + samples.serialize(serializer) + } +} + +impl<'de, T> Deserialize<'de> for SampleCollection +where + T: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let samples = Vec::>::deserialize(deserializer)?; + + let sample_collection = SampleCollection::new(samples).map_err(serde::de::Error::custom)?; + + Ok(sample_collection) + } +} + +impl PrometheusSerializable for SampleCollection { + fn to_prometheus(&self) -> String { + let mut output = String::new(); + + for (label_set, sample_data) in &self.samples { + if label_set.is_empty() { + let _ = write!(output, "{}", sample_data.to_prometheus()); + } else { + let _ = write!(output, "{} {}", label_set.to_prometheus(), sample_data.to_prometheus()); + } + } + + output + } +} + +#[cfg(test)] +mod tests { + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::counter::Counter; + use crate::label::LabelSet; + use crate::sample::Sample; + use crate::sample_collection::SampleCollection; + + fn sample_update_time() -> DurationSinceUnixEpoch { + DurationSinceUnixEpoch::from_secs(1_743_552_000) + } + + #[test] + fn it_should_fail_trying_to_create_a_sample_collection_with_duplicate_label_sets() { + let samples = vec![ + Sample::new(Counter::default(), sample_update_time(), LabelSet::default()), + Sample::new(Counter::default(), sample_update_time(), LabelSet::default()), + ]; + + let result = SampleCollection::new(samples); + + assert!(result.is_err()); + } + + #[test] + fn it_should_return_a_sample_searching_by_label_set_with_one_empty_label_set() { + let label_set = LabelSet::default(); + + let sample = Sample::new(Counter::default(), sample_update_time(), label_set.clone()); + + let collection = SampleCollection::new(vec![sample.clone()]).unwrap(); + + let retrieved = collection.get(&label_set); + + assert_eq!(retrieved.unwrap(), sample.measurement()); + } + + #[test] + fn it_should_return_a_sample_searching_by_label_set_with_two_label_sets() { + let label_set_1 = LabelSet::from(vec![("label_name_1", "label value 1")]); + let label_set_2 = LabelSet::from(vec![("label_name_2", "label value 2")]); + + let sample_1 = Sample::new(Counter::new(1), sample_update_time(), label_set_1.clone()); + let sample_2 = Sample::new(Counter::new(2), sample_update_time(), label_set_2.clone()); + + let collection = SampleCollection::new(vec![sample_1.clone(), sample_2.clone()]).unwrap(); + + let retrieved = collection.get(&label_set_1); + assert_eq!(retrieved.unwrap(), sample_1.measurement()); + + let retrieved = collection.get(&label_set_2); + assert_eq!(retrieved.unwrap(), sample_2.measurement()); + } + + #[test] + fn it_should_return_the_number_of_samples_in_the_collection() { + let samples = vec![Sample::new(Counter::default(), sample_update_time(), LabelSet::default())]; + let collection = SampleCollection::new(samples).unwrap(); + assert_eq!(collection.len(), 1); + } + + #[test] + fn it_should_return_zero_number_of_samples_when_empty() { + let empty = SampleCollection::::default(); + assert_eq!(empty.len(), 0); + } + + #[test] + fn it_should_indicate_is_it_is_empty() { + let empty = SampleCollection::::default(); + assert!(empty.is_empty()); + + let samples = vec![Sample::new(Counter::default(), sample_update_time(), LabelSet::default())]; + let collection = SampleCollection::new(samples).unwrap(); + assert!(!collection.is_empty()); + } + + mod json_serialization { + use crate::counter::Counter; + use crate::label::LabelSet; + use crate::sample::Sample; + use crate::sample_collection::tests::sample_update_time; + use crate::sample_collection::SampleCollection; + + #[test] + fn it_should_be_serializable_and_deserializable_for_json_format() { + let sample = Sample::new(Counter::default(), sample_update_time(), LabelSet::default()); + let collection = SampleCollection::new(vec![sample]).unwrap(); + + let serialized = serde_json::to_string(&collection).unwrap(); + let deserialized: SampleCollection = serde_json::from_str(&serialized).unwrap(); + + assert_eq!(deserialized, collection); + } + + #[test] + fn it_should_fail_deserializing_from_json_with_duplicate_label_sets() { + let samples = vec![ + Sample::new(Counter::default(), sample_update_time(), LabelSet::default()), + Sample::new(Counter::default(), sample_update_time(), LabelSet::default()), + ]; + + let serialized = serde_json::to_string(&samples).unwrap(); + + let result: Result, _> = serde_json::from_str(&serialized); + + assert!(result.is_err()); + } + } + + mod prometheus_serialization { + use crate::counter::Counter; + use crate::label::LabelSet; + use crate::prometheus::PrometheusSerializable; + use crate::sample::Sample; + use crate::sample_collection::tests::sample_update_time; + use crate::sample_collection::SampleCollection; + use crate::tests::format_prometheus_output; + + #[test] + fn it_should_be_exportable_to_prometheus_format_when_empty() { + let sample = Sample::new(Counter::default(), sample_update_time(), LabelSet::default()); + let collection = SampleCollection::new(vec![sample]).unwrap(); + + let prometheus_output = collection.to_prometheus(); + + assert!(!prometheus_output.is_empty()); + } + + #[test] + fn it_should_be_exportable_to_prometheus_format() { + let sample = Sample::new( + Counter::new(1), + sample_update_time(), + LabelSet::from(vec![("labe_name_1", "label value value 1")]), + ); + + let collection = SampleCollection::new(vec![sample]).unwrap(); + + let prometheus_output = collection.to_prometheus(); + + let expected_prometheus_output = format_prometheus_output("{labe_name_1=\"label value value 1\"} 1"); + + assert_eq!(prometheus_output, expected_prometheus_output); + } + } + + #[cfg(test)] + mod for_counters { + + use std::ops::Add; + + use super::super::LabelSet; + use super::*; + + #[test] + fn it_should_increment_the_counter_for_a_preexisting_label_set() { + let label_set = LabelSet::default(); + let mut collection = SampleCollection::::default(); + + // Initialize the sample + collection.increment(&label_set, sample_update_time()); + + // Verify initial state + let sample = collection.get(&label_set).unwrap(); + assert_eq!(sample.value(), &Counter::new(1)); + + // Increment again + collection.increment(&label_set, sample_update_time()); + let sample = collection.get(&label_set).unwrap(); + assert_eq!(*sample.value(), Counter::new(2)); + } + + #[test] + fn it_should_allow_increment_the_counter_for_a_non_existent_label_set() { + let label_set = LabelSet::default(); + let mut collection = SampleCollection::::default(); + + // Increment a non-existent label + collection.increment(&label_set, sample_update_time()); + + // Verify the label exists + assert!(collection.get(&label_set).is_some()); + let sample = collection.get(&label_set).unwrap(); + assert_eq!(*sample.value(), Counter::new(1)); + } + + #[test] + fn it_should_update_the_latest_update_time_when_incremented() { + let label_set = LabelSet::default(); + let initial_time = sample_update_time(); + + let mut collection = SampleCollection::::default(); + collection.increment(&label_set, initial_time); + + // Increment with a new time + let new_time = initial_time.add(DurationSinceUnixEpoch::from_secs(1)); + collection.increment(&label_set, new_time); + + let sample = collection.get(&label_set).unwrap(); + assert_eq!(sample.recorded_at(), new_time); + assert_eq!(*sample.value(), Counter::new(2)); + } + + #[test] + fn it_should_increment_the_counter_for_multiple_labels() { + let label1 = LabelSet::from([("name", "value1")]); + let label2 = LabelSet::from([("name", "value2")]); + let now = sample_update_time(); + + let mut collection = SampleCollection::::default(); + + collection.increment(&label1, now); + collection.increment(&label2, now); + + assert_eq!(collection.get(&label1).unwrap().value(), &Counter::new(1)); + assert_eq!(collection.get(&label2).unwrap().value(), &Counter::new(1)); + assert_eq!(collection.len(), 2); + } + + #[test] + fn it_should_allow_setting_absolute_value_for_a_counter() { + let label_set = LabelSet::default(); + let mut collection = SampleCollection::::default(); + + // Set absolute value for a non-existent label + collection.absolute(&label_set, 42, sample_update_time()); + + // Verify the label exists and has the absolute value + assert!(collection.get(&label_set).is_some()); + let sample = collection.get(&label_set).unwrap(); + assert_eq!(*sample.value(), Counter::new(42)); + } + + #[test] + fn it_should_allow_setting_absolute_value_for_existing_counter() { + let label_set = LabelSet::default(); + let mut collection = SampleCollection::::default(); + + // Initialize the sample with increment + collection.increment(&label_set, sample_update_time()); + + // Verify initial state + let sample = collection.get(&label_set).unwrap(); + assert_eq!(sample.value(), &Counter::new(1)); + + // Set absolute value + collection.absolute(&label_set, 100, sample_update_time()); + let sample = collection.get(&label_set).unwrap(); + assert_eq!(*sample.value(), Counter::new(100)); + } + + #[test] + fn it_should_update_time_when_setting_absolute_value() { + let label_set = LabelSet::default(); + let initial_time = sample_update_time(); + let mut collection = SampleCollection::::default(); + + // Set absolute value with initial time + collection.absolute(&label_set, 50, initial_time); + + // Set absolute value with a new time + let new_time = initial_time.add(DurationSinceUnixEpoch::from_secs(1)); + collection.absolute(&label_set, 75, new_time); + + let sample = collection.get(&label_set).unwrap(); + assert_eq!(sample.recorded_at(), new_time); + assert_eq!(*sample.value(), Counter::new(75)); + } + } + + #[cfg(test)] + mod for_gauges { + + use std::ops::Add; + + use super::super::LabelSet; + use super::*; + use crate::gauge::Gauge; + + #[test] + fn it_should_allow_setting_the_gauge_for_a_preexisting_label_set() { + let label_set = LabelSet::default(); + let mut collection = SampleCollection::::default(); + + // Initialize the sample + collection.set(&label_set, 1.0, sample_update_time()); + + // Verify initial state + let sample = collection.get(&label_set).unwrap(); + assert_eq!(sample.value(), &Gauge::new(1.0)); + + // Set again + collection.set(&label_set, 2.0, sample_update_time()); + let sample = collection.get(&label_set).unwrap(); + assert_eq!(*sample.value(), Gauge::new(2.0)); + } + + #[test] + fn it_should_allow_setting_the_gauge_for_a_non_existent_label_set() { + let label_set = LabelSet::default(); + let mut collection = SampleCollection::::default(); + + // Set a non-existent label + collection.set(&label_set, 1.0, sample_update_time()); + + // Verify the label exists + assert!(collection.get(&label_set).is_some()); + let sample = collection.get(&label_set).unwrap(); + assert_eq!(*sample.value(), Gauge::new(1.0)); + } + + #[test] + fn it_should_update_the_latest_update_time_when_setting() { + let label_set = LabelSet::default(); + let initial_time = sample_update_time(); + + let mut collection = SampleCollection::::default(); + collection.set(&label_set, 1.0, initial_time); + + // Set with a new time + let new_time = initial_time.add(DurationSinceUnixEpoch::from_secs(1)); + collection.set(&label_set, 2.0, new_time); + + let sample = collection.get(&label_set).unwrap(); + assert_eq!(sample.recorded_at(), new_time); + assert_eq!(*sample.value(), Gauge::new(2.0)); + } + + #[test] + fn it_should_allow_setting_the_gauge_for_multiple_labels() { + let label1 = LabelSet::from([("name", "value1")]); + let label2 = LabelSet::from([("name", "value2")]); + let now = sample_update_time(); + + let mut collection = SampleCollection::::default(); + + collection.set(&label1, 1.0, now); + collection.set(&label2, 2.0, now); + + assert_eq!(collection.get(&label1).unwrap().value(), &Gauge::new(1.0)); + assert_eq!(collection.get(&label2).unwrap().value(), &Gauge::new(2.0)); + assert_eq!(collection.len(), 2); + } + + #[test] + fn it_should_allow_incrementing_the_gauge() { + let label_set = LabelSet::default(); + let mut collection = SampleCollection::::default(); + + // Initialize the sample + collection.set(&label_set, 1.0, sample_update_time()); + + // Increment + collection.increment(&label_set, sample_update_time()); + let sample = collection.get(&label_set).unwrap(); + assert_eq!(*sample.value(), Gauge::new(2.0)); + } + + #[test] + fn it_should_allow_decrementing_the_gauge() { + let label_set = LabelSet::default(); + let mut collection = SampleCollection::::default(); + + // Initialize the sample + collection.set(&label_set, 1.0, sample_update_time()); + + // Increment + collection.decrement(&label_set, sample_update_time()); + let sample = collection.get(&label_set).unwrap(); + assert_eq!(*sample.value(), Gauge::new(0.0)); + } + } +} diff --git a/packages/metrics/src/unit.rs b/packages/metrics/src/unit.rs new file mode 100644 index 000000000..43b42bf79 --- /dev/null +++ b/packages/metrics/src/unit.rs @@ -0,0 +1,30 @@ +//! This module defines the `Unit` enum, which represents various units of +//! measurement. +//! +//! The `Unit` enum is used to specify the unit of measurement for metrics. +//! +//! They were copied from the `metrics` crate, to allow future compatibility. + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Unit { + Count, + Percent, + Seconds, + Milliseconds, + Microseconds, + Nanoseconds, + Tebibytes, + Gibibytes, + Mebibytes, + Kibibytes, + Bytes, + TerabitsPerSecond, + GigabitsPerSecond, + MegabitsPerSecond, + KilobitsPerSecond, + BitsPerSecond, + CountPerSecond, +} diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index bba45cf5d..c9ce64177 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -1,11 +1,31 @@ [package] -name = "torrust-tracker-primitives" description = "A library with the primitive types shared by the Torrust tracker packages." -license = "AGPL-3.0" -version.workspace = true +keywords = [ "api", "library", "primitives" ] +name = "torrust-tracker-primitives" +readme = "README.md" + authors.workspace = true +documentation.workspace = true edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true [dependencies] -serde = { version = "1.0", features = ["derive"] } -derive_more = "0.99" +aquatic_udp_protocol = "0" +binascii = "0" +bittorrent-primitives = "0.1.0" +derive_more = { version = "2", features = [ "constructor" ] } +serde = { version = "1", features = [ "derive" ] } +tdyne-peer-id = "1" +tdyne-peer-id-registry = "0" +thiserror = "2" +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +url = "2.5.4" +zerocopy = "0.7" + +[dev-dependencies] +rstest = "0.25.0" diff --git a/packages/primitives/src/core.rs b/packages/primitives/src/core.rs new file mode 100644 index 000000000..aa2fe6926 --- /dev/null +++ b/packages/primitives/src/core.rs @@ -0,0 +1,88 @@ +use std::collections::HashMap; +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use derive_more::derive::Constructor; +use torrust_tracker_configuration::AnnouncePolicy; + +use crate::peer; +use crate::swarm_metadata::SwarmMetadata; + +/// Structure that holds the data returned by the `announce` request. +#[derive(Clone, Debug, PartialEq, Constructor, Default)] +pub struct AnnounceData { + /// The list of peers that are downloading the same torrent. + /// It excludes the peer that made the request. + pub peers: Vec>, + /// Swarm statistics + pub stats: SwarmMetadata, + pub policy: AnnouncePolicy, +} + +/// Structure that holds the data returned by the `scrape` request. +#[derive(Debug, PartialEq, Default)] +pub struct ScrapeData { + /// A map of infohashes and swarm metadata for each torrent. + pub files: HashMap, +} + +impl ScrapeData { + /// Creates a new empty `ScrapeData` with no files (torrents). + #[must_use] + pub fn empty() -> Self { + let files: HashMap = HashMap::new(); + Self { files } + } + + /// Creates a new `ScrapeData` with zeroed metadata for each torrent. + #[must_use] + pub fn zeroed(info_hashes: &Vec) -> Self { + let mut scrape_data = Self::empty(); + + for info_hash in info_hashes { + scrape_data.add_file(info_hash, SwarmMetadata::zeroed()); + } + + scrape_data + } + + /// Adds a torrent to the `ScrapeData`. + pub fn add_file(&mut self, info_hash: &InfoHash, swarm_metadata: SwarmMetadata) { + self.files.insert(*info_hash, swarm_metadata); + } + + /// Adds a torrent to the `ScrapeData` with zeroed metadata. + pub fn add_file_with_zeroed_metadata(&mut self, info_hash: &InfoHash) { + self.files.insert(*info_hash, SwarmMetadata::zeroed()); + } +} + +#[cfg(test)] +mod tests { + + use bittorrent_primitives::info_hash::InfoHash; + + use crate::core::ScrapeData; + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } + + #[test] + fn it_should_be_able_to_build_a_zeroed_scrape_data_for_a_list_of_info_hashes() { + // Zeroed scrape data is used when the authentication for the scrape request fails. + + let sample_info_hash = sample_info_hash(); + + let mut expected_scrape_data = ScrapeData::empty(); + expected_scrape_data.add_file_with_zeroed_metadata(&sample_info_hash); + + assert_eq!(ScrapeData::zeroed(&vec![sample_info_hash]), expected_scrape_data); + } +} diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index e6f8cb93b..ec2edda97 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -4,44 +4,19 @@ //! which is a `BitTorrent` tracker server. These structures are used not only //! by the tracker server crate, but also by other crates in the Torrust //! ecosystem. -use serde::{Deserialize, Serialize}; +pub mod core; +pub mod pagination; +pub mod peer; +pub mod service_binding; +pub mod swarm_metadata; -/// The database management system used by the tracker. -/// -/// Refer to: -/// -/// - [Torrust Tracker Configuration](https://docs.rs/torrust-tracker-configuration). -/// - [Torrust Tracker](https://docs.rs/torrust-tracker). -/// -/// For more information about persistence. -#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, derive_more::Display, Clone)] -pub enum DatabaseDriver { - // TODO: Move to the database crate once that gets its own crate. - /// The Sqlite3 database driver. - Sqlite3, - /// The MySQL database driver. - MySQL, -} +use std::collections::BTreeMap; +use std::time::Duration; -/// The mode the tracker will run in. -/// -/// Refer to [Torrust Tracker Configuration](https://docs.rs/torrust-tracker-configuration) -/// to know how to configure the tracker to run in each mode. -#[derive(Serialize, Deserialize, Copy, Clone, PartialEq, Eq, Debug)] -pub enum TrackerMode { - /// Will track every new info hash and serve every peer. - #[serde(rename = "public")] - Public, +use bittorrent_primitives::info_hash::InfoHash; - /// Will only track whitelisted info hashes. - #[serde(rename = "listed")] - Listed, +/// Duration since the Unix Epoch. +pub type DurationSinceUnixEpoch = Duration; - /// Will only serve authenticated peers - #[serde(rename = "private")] - Private, - - /// Will only track whitelisted info hashes and serve authenticated peers - #[serde(rename = "private_listed")] - PrivateListed, -} +pub type NumberOfDownloads = u32; +pub type NumberOfDownloadsBTreeMap = BTreeMap; diff --git a/packages/primitives/src/pagination.rs b/packages/primitives/src/pagination.rs new file mode 100644 index 000000000..96b5ad662 --- /dev/null +++ b/packages/primitives/src/pagination.rs @@ -0,0 +1,46 @@ +use derive_more::Constructor; +use serde::Deserialize; + +/// A struct to keep information about the page when results are being paginated +#[derive(Deserialize, Copy, Clone, Debug, PartialEq, Constructor)] +pub struct Pagination { + /// The page number, starting at 0 + pub offset: u32, + /// Page size. The number of results per page + pub limit: u32, +} + +impl Pagination { + #[must_use] + pub fn new_with_options(offset_option: Option, limit_option: Option) -> Self { + let offset = match offset_option { + Some(offset) => offset, + None => Pagination::default_offset(), + }; + let limit = match limit_option { + Some(offset) => offset, + None => Pagination::default_limit(), + }; + + Self { offset, limit } + } + + #[must_use] + pub fn default_offset() -> u32 { + 0 + } + + #[must_use] + pub fn default_limit() -> u32 { + 4000 + } +} + +impl Default for Pagination { + fn default() -> Self { + Self { + offset: Self::default_offset(), + limit: Self::default_limit(), + } + } +} diff --git a/packages/primitives/src/peer.rs b/packages/primitives/src/peer.rs new file mode 100644 index 000000000..ef47f28f8 --- /dev/null +++ b/packages/primitives/src/peer.rs @@ -0,0 +1,707 @@ +//! Peer struct used by the core `Tracker`. +//! +//! A sample peer: +//! +//! ```rust,no_run +//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +//! use torrust_tracker_primitives::peer; +//! use std::net::SocketAddr; +//! use std::net::IpAddr; +//! use std::net::Ipv4Addr; +//! use torrust_tracker_primitives::DurationSinceUnixEpoch; +//! +//! +//! peer::Peer { +//! peer_id: PeerId(*b"-qB00000000000000000"), +//! peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), +//! updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), +//! uploaded: NumberOfBytes::new(0), +//! downloaded: NumberOfBytes::new(0), +//! left: NumberOfBytes::new(0), +//! event: AnnounceEvent::Started, +//! }; +//! ``` + +use std::fmt; +use std::net::{IpAddr, SocketAddr}; +use std::ops::{Deref, DerefMut}; +use std::str::FromStr; +use std::sync::Arc; + +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +use serde::Serialize; +use zerocopy::FromBytes as _; + +use crate::DurationSinceUnixEpoch; + +pub type PeerAnnouncement = Peer; + +#[derive(Debug, Serialize, Copy, Clone, PartialEq, Eq, Hash)] +#[serde(rename_all_fields = "lowercase")] +pub enum PeerRole { + Seeder, + Leecher, +} + +impl PeerRole { + /// Returns the opposite role: Seeder becomes Leecher, and vice versa. + #[must_use] + pub fn opposite(self) -> Self { + match self { + PeerRole::Seeder => PeerRole::Leecher, + PeerRole::Leecher => PeerRole::Seeder, + } + } +} + +impl fmt::Display for PeerRole { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + PeerRole::Seeder => write!(f, "seeder"), + PeerRole::Leecher => write!(f, "leecher"), + } + } +} + +impl FromStr for PeerRole { + type Err = ParsePeerRoleError; + + fn from_str(s: &str) -> Result { + match s.to_lowercase().as_str() { + "seeder" => Ok(PeerRole::Seeder), + "leecher" => Ok(PeerRole::Leecher), + _ => Err(ParsePeerRoleError::InvalidPeerRole { + location: Location::caller(), + raw_param: s.to_string(), + }), + } + } +} + +#[derive(Error, Debug)] +pub enum ParsePeerRoleError { + #[error("invalid param {raw_param} in {location}")] + InvalidPeerRole { + location: &'static Location<'static>, + raw_param: String, + }, +} + +/// Peer struct used by the core `Tracker`. +/// +/// A sample peer: +/// +/// ```rust,no_run +/// use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +/// use torrust_tracker_primitives::peer; +/// use std::net::SocketAddr; +/// use std::net::IpAddr; +/// use std::net::Ipv4Addr; +/// use torrust_tracker_primitives::DurationSinceUnixEpoch; +/// +/// +/// peer::Peer { +/// peer_id: PeerId(*b"-qB00000000000000000"), +/// peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), +/// updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), +/// uploaded: NumberOfBytes::new(0), +/// downloaded: NumberOfBytes::new(0), +/// left: NumberOfBytes::new(0), +/// event: AnnounceEvent::Started, +/// }; +/// ``` +#[derive(Debug, Clone, Serialize, Copy, PartialEq, Eq, Hash)] +pub struct Peer { + /// ID used by the downloader peer + #[serde(serialize_with = "ser_peer_id")] + pub peer_id: PeerId, + /// The IP and port this peer is listening on + pub peer_addr: SocketAddr, + /// The last time the the tracker receive an announce request from this peer (timestamp) + #[serde(serialize_with = "ser_unix_time_value")] + pub updated: DurationSinceUnixEpoch, + /// The total amount of bytes uploaded by this peer so far + #[serde(serialize_with = "ser_number_of_bytes")] + pub uploaded: NumberOfBytes, + /// The total amount of bytes downloaded by this peer so far + #[serde(serialize_with = "ser_number_of_bytes")] + pub downloaded: NumberOfBytes, + /// The number of bytes this peer still has to download + #[serde(serialize_with = "ser_number_of_bytes")] + pub left: NumberOfBytes, + /// This is an optional key which maps to started, completed, or stopped (or empty, which is the same as not being present). + #[serde(serialize_with = "ser_announce_event")] + pub event: AnnounceEvent, +} + +/// Serializes a `DurationSinceUnixEpoch` as a Unix timestamp in milliseconds. +/// # Errors +/// +/// Will return `serde::Serializer::Error` if unable to serialize the `unix_time_value`. +pub fn ser_unix_time_value(unix_time_value: &DurationSinceUnixEpoch, ser: S) -> Result { + #[allow(clippy::cast_possible_truncation)] + ser.serialize_u64(unix_time_value.as_millis() as u64) +} + +#[derive(Serialize)] +pub enum AnnounceEventSer { + Started, + Stopped, + Completed, + None, +} + +/// Serializes a `Announce Event` as a enum. +/// +/// # Errors +/// +/// If will return an error if the internal serializer was to fail. +pub fn ser_announce_event(announce_event: &AnnounceEvent, ser: S) -> Result { + let event_ser = match announce_event { + AnnounceEvent::Started => AnnounceEventSer::Started, + AnnounceEvent::Stopped => AnnounceEventSer::Stopped, + AnnounceEvent::Completed => AnnounceEventSer::Completed, + AnnounceEvent::None => AnnounceEventSer::None, + }; + + ser.serialize_some(&event_ser) +} + +/// Serializes a `Announce Event` as a i64. +/// +/// # Errors +/// +/// If will return an error if the internal serializer was to fail. +pub fn ser_number_of_bytes(number_of_bytes: &NumberOfBytes, ser: S) -> Result { + ser.serialize_i64(number_of_bytes.0.get()) +} + +/// Serializes a `PeerId` as a `peer::Id`. +/// +/// # Errors +/// +/// If will return an error if the internal serializer was to fail. +pub fn ser_peer_id(peer_id: &PeerId, ser: S) -> Result { + let id = Id { data: *peer_id }; + ser.serialize_some(&id) +} + +impl Ord for Peer { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.peer_id.cmp(&other.peer_id) + } +} + +impl PartialOrd for Peer { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +pub trait ReadInfo { + fn is_seeder(&self) -> bool; + fn is_leecher(&self) -> bool; + fn get_event(&self) -> AnnounceEvent; + fn get_id(&self) -> PeerId; + fn get_updated(&self) -> DurationSinceUnixEpoch; + fn get_address(&self) -> SocketAddr; +} + +impl ReadInfo for Peer { + fn is_seeder(&self) -> bool { + self.left.0.get() <= 0 && self.event != AnnounceEvent::Stopped + } + + fn is_leecher(&self) -> bool { + !self.is_seeder() + } + + fn get_event(&self) -> AnnounceEvent { + self.event + } + + fn get_id(&self) -> PeerId { + self.peer_id + } + + fn get_updated(&self) -> DurationSinceUnixEpoch { + self.updated + } + + fn get_address(&self) -> SocketAddr { + self.peer_addr + } +} + +impl ReadInfo for Arc { + fn is_seeder(&self) -> bool { + self.left.0.get() <= 0 && self.event != AnnounceEvent::Stopped + } + + fn is_leecher(&self) -> bool { + !self.is_seeder() + } + + fn get_event(&self) -> AnnounceEvent { + self.event + } + + fn get_id(&self) -> PeerId { + self.peer_id + } + + fn get_updated(&self) -> DurationSinceUnixEpoch { + self.updated + } + + fn get_address(&self) -> SocketAddr { + self.peer_addr + } +} + +impl Peer { + #[must_use] + pub fn is_seeder(&self) -> bool { + self.left.0.get() <= 0 && self.event != AnnounceEvent::Stopped + } + + #[must_use] + pub fn is_leecher(&self) -> bool { + !self.is_seeder() + } + + #[must_use] + pub fn is_completed(&self) -> bool { + self.event == AnnounceEvent::Completed + } + + #[must_use] + pub fn role(&self) -> PeerRole { + if self.is_seeder() { + PeerRole::Seeder + } else { + PeerRole::Leecher + } + } + + pub fn ip(&mut self) -> IpAddr { + self.peer_addr.ip() + } + + pub fn change_ip(&mut self, new_ip: &IpAddr) { + self.peer_addr = SocketAddr::new(*new_ip, self.peer_addr.port()); + } + + pub fn mark_as_completed(&mut self) { + self.event = AnnounceEvent::Completed; + } + + #[must_use] + pub fn into_completed(self) -> Self { + Self { + event: AnnounceEvent::Completed, + ..self + } + } + + #[must_use] + pub fn into_seeder(self) -> Self { + Self { + left: NumberOfBytes::new(0), + ..self + } + } +} + +use std::panic::Location; + +use thiserror::Error; + +/// Error returned when trying to convert an invalid peer id from another type. +/// +/// Usually because the source format does not contain 20 bytes. +#[derive(Error, Debug)] +pub enum IdConversionError { + #[error("not enough bytes for peer id: {message} {location}")] + NotEnoughBytes { + location: &'static Location<'static>, + message: String, + }, + #[error("too many bytes for peer id: {message} {location}")] + TooManyBytes { + location: &'static Location<'static>, + message: String, + }, +} + +pub struct Id { + data: PeerId, +} + +impl From for Id { + fn from(id: PeerId) -> Self { + Self { data: id } + } +} + +impl Deref for Id { + type Target = PeerId; + + fn deref(&self) -> &Self::Target { + &self.data + } +} + +impl DerefMut for Id { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.data + } +} + +impl Id { + #[must_use] + pub fn new(number: T) -> Self + where + T: Into, + { + let number: i128 = number.into(); + let number = number.to_le_bytes(); + let bytes = [ + 0u8, 0u8, 0u8, 0u8, number[0], number[1], number[2], number[3], number[4], number[5], number[6], number[7], + number[8], number[9], number[10], number[11], number[12], number[13], number[14], number[15], + ]; + + let data = PeerId(bytes); + Id { data } + } +} + +impl TryFrom> for Id { + type Error = IdConversionError; + + fn try_from(bytes: Vec) -> Result { + if bytes.len() < PEER_ID_BYTES_LEN { + return Err(IdConversionError::NotEnoughBytes { + location: Location::caller(), + message: format! {"got {} bytes, expected {}", bytes.len(), PEER_ID_BYTES_LEN}, + }); + } + if bytes.len() > PEER_ID_BYTES_LEN { + return Err(IdConversionError::TooManyBytes { + location: Location::caller(), + message: format! {"got {} bytes, expected {}", bytes.len(), PEER_ID_BYTES_LEN}, + }); + } + + let data = PeerId::read_from(&bytes).expect("it should have the correct amount of bytes"); + Ok(Self { data }) + } +} + +impl std::fmt::Display for Id { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.to_hex_string() { + Some(hex) => write!(f, "{hex}"), + None => write!(f, ""), + } + } +} + +pub const PEER_ID_BYTES_LEN: usize = 20; + +impl Id { + #[must_use] + /// Converts to hex string. + /// + /// For the `PeerId` `-qB00000000000000000` it returns `2d71423030303030303030303030303030303030` + /// + /// For example: + /// + ///```text + /// Bytes = Hex + /// -qB00000000000000000 = 2d71423030303030303030303030303030303030 + /// -qB00000000000000000 = 2d 71 42 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 + /// + /// ------------- + /// |Char | Hex | + /// ------------- + /// | - | 2D | + /// | q | 71 | + /// | B | 42 | + /// | 0 | 30 | + /// ------------- + /// ``` + /// + /// Return `None` is some of the bytes are invalid UTF8 values. + /// + /// # Panics + /// + /// It will panic if the `binascii::bin2hex` from a too-small output buffer. + pub fn to_hex_string(&self) -> Option { + let buff_size = self.0.len() * 2; + let mut tmp: Vec = vec![0; buff_size]; + + binascii::bin2hex(&self.0, &mut tmp).unwrap(); + + match std::str::from_utf8(&tmp) { + Ok(hex) => Some(format!("0x{hex}")), + Err(_) => None, + } + } + + #[must_use] + pub fn get_client_name(&self) -> Option { + let peer_id = tdyne_peer_id::PeerId::from(self.0); + tdyne_peer_id_registry::parse(peer_id).ok().map(|parsed| parsed.client) + } +} + +impl Serialize for Id { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + #[derive(Serialize)] + struct PeerIdInfo { + id: Option, + client: Option, + } + + let obj = PeerIdInfo { + id: self.to_hex_string(), + client: self.get_client_name(), + }; + obj.serialize(serializer) + } +} + +/// Marker Trait for Peer Vectors +pub trait Encoding: From + PartialEq {} + +impl FromIterator for Vec

{ + fn from_iter>(iter: T) -> Self { + let mut peers: Vec

= vec![]; + + for peer in iter { + peers.push(peer.into()); + } + + peers + } +} + +pub mod fixture { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + + use super::{Id, Peer, PeerId}; + use crate::DurationSinceUnixEpoch; + + #[derive(PartialEq, Debug)] + + pub struct PeerBuilder { + peer: Peer, + } + + #[allow(clippy::derivable_impls)] + impl Default for PeerBuilder { + fn default() -> Self { + Self { peer: Peer::default() } + } + } + + impl PeerBuilder { + #[allow(dead_code)] + #[must_use] + pub fn seeder() -> Self { + let peer = Peer { + peer_id: PeerId(*b"-qB00000000000000001"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), + event: AnnounceEvent::Completed, + }; + + Self { peer } + } + + #[allow(dead_code)] + #[must_use] + pub fn leecher() -> Self { + let peer = Peer { + peer_id: PeerId(*b"-qB00000000000000002"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(10), + event: AnnounceEvent::Started, + }; + + Self { peer } + } + + #[allow(dead_code)] + #[must_use] + pub fn with_peer_id(mut self, peer_id: &PeerId) -> Self { + self.peer.peer_id = *peer_id; + self + } + + #[allow(dead_code)] + #[must_use] + pub fn with_peer_addr(mut self, peer_addr: &SocketAddr) -> Self { + self.peer.peer_addr = *peer_addr; + self + } + + #[must_use] + pub fn with_peer_address(mut self, peer_addr: SocketAddr) -> Self { + self.peer.peer_addr = peer_addr; + self + } + + #[must_use] + pub fn updated_on(mut self, updated: DurationSinceUnixEpoch) -> Self { + self.peer.updated = updated; + self + } + + #[must_use] + pub fn with_bytes_left_to_download(mut self, left: i64) -> Self { + self.peer.left = NumberOfBytes::new(left); + self + } + + #[must_use] + pub fn with_no_bytes_left_to_download(mut self) -> Self { + self.peer.left = NumberOfBytes::new(0); + self + } + + #[must_use] + pub fn last_updated_on(mut self, updated: DurationSinceUnixEpoch) -> Self { + self.peer.updated = updated; + self + } + + #[must_use] + pub fn with_event(mut self, event: AnnounceEvent) -> Self { + self.peer.event = event; + self + } + + #[must_use] + pub fn with_event_started(mut self) -> Self { + self.peer.event = AnnounceEvent::Started; + self + } + + #[must_use] + pub fn with_event_completed(mut self) -> Self { + self.peer.event = AnnounceEvent::Completed; + self + } + + #[must_use] + pub fn build(self) -> Peer { + self.into() + } + + #[must_use] + pub fn into(self) -> Peer { + self.peer + } + } + + impl Default for Peer { + fn default() -> Self { + Self { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), + event: AnnounceEvent::Started, + } + } + } + + impl Default for Id { + fn default() -> Self { + let data = PeerId(*b"-qB00000000000000000"); + Self { data } + } + } +} + +#[cfg(test)] +pub mod test { + + mod peer { + use crate::peer::fixture::PeerBuilder; + + #[test] + fn should_be_comparable() { + let seeder1 = PeerBuilder::seeder().build(); + let seeder2 = PeerBuilder::seeder().build(); + + let leecher1 = PeerBuilder::leecher().build(); + + assert!(seeder1 == seeder2); + assert!(seeder1 != leecher1); + } + } + + mod torrent_peer_id { + use aquatic_udp_protocol::PeerId; + + use crate::peer; + + #[test] + #[should_panic = "NotEnoughBytes"] + fn should_fail_trying_to_convert_from_a_byte_vector_with_less_than_20_bytes() { + let _ = peer::Id::try_from([0; 19].to_vec()).unwrap(); + } + + #[test] + #[should_panic = "TooManyBytes"] + fn should_fail_trying_to_convert_from_a_byte_vector_with_more_than_20_bytes() { + let _ = peer::Id::try_from([0; 21].to_vec()).unwrap(); + } + + #[test] + fn should_be_converted_to_hex_string() { + let id = peer::Id { + data: PeerId(*b"-qB00000000000000000"), + }; + assert_eq!(id.to_hex_string().unwrap(), "0x2d71423030303030303030303030303030303030"); + + let id = peer::Id { + data: PeerId([ + 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, + ]), + }; + assert_eq!(id.to_hex_string().unwrap(), "0x009f9296009f9296009f9296009f9296009f9296"); + } + + #[test] + fn should_be_converted_into_string_type_using_the_hex_string_format() { + let id = peer::Id { + data: PeerId(*b"-qB00000000000000000"), + }; + assert_eq!(id.to_string(), "0x2d71423030303030303030303030303030303030"); + + let id = peer::Id { + data: PeerId([ + 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, + ]), + }; + assert_eq!(id.to_string(), "0x009f9296009f9296009f9296009f9296009f9296"); + } + } +} diff --git a/packages/primitives/src/service_binding.rs b/packages/primitives/src/service_binding.rs new file mode 100644 index 000000000..c1ec308c8 --- /dev/null +++ b/packages/primitives/src/service_binding.rs @@ -0,0 +1,297 @@ +use std::fmt; +use std::net::{IpAddr, SocketAddr}; + +use serde::{Deserialize, Serialize}; +use url::Url; + +const DUAL_STACK_IP_V4_MAPPED_V6_PREFIX: &str = "::ffff:"; + +/// Represents the supported network protocols. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)] +pub enum Protocol { + UDP, + HTTP, + HTTPS, +} + +impl fmt::Display for Protocol { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let proto_str = match self { + Protocol::UDP => "udp", + Protocol::HTTP => "http", + Protocol::HTTPS => "https", + }; + write!(f, "{proto_str}") + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)] +pub enum IpType { + /// Represents a plain IPv4 or IPv6 address. + Plain, + + /// Represents an IPv6 address that is a mapped IPv4 address. + /// + /// This is used for IPv6 addresses that represent an IPv4 address in a dual-stack network. + /// + /// For example: `[::ffff:192.0.2.33]` + V4MappedV6, +} + +impl fmt::Display for IpType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let ip_type_str = match self { + Self::Plain => "plain", + Self::V4MappedV6 => "v4_mapped_v6", + }; + write!(f, "{ip_type_str}") + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)] +pub enum IpFamily { + // IPv4 + Inet, + // IPv6 + Inet6, +} + +impl fmt::Display for IpFamily { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let ip_family_str = match self { + Self::Inet => "inet", + Self::Inet6 => "inet6", + }; + write!(f, "{ip_family_str}") + } +} + +impl From for IpFamily { + fn from(ip: IpAddr) -> Self { + if ip.is_ipv4() { + return IpFamily::Inet; + } + + if ip.is_ipv6() { + return IpFamily::Inet6; + } + + panic!("Unsupported IP address type: {ip}"); + } +} + +#[derive(thiserror::Error, Debug, Clone)] +pub enum Error { + #[error("The port number cannot be zero. It must be an assigned valid port.")] + PortZeroNotAllowed, +} + +/// Represents a network service binding, encapsulating protocol and socket +/// address. +/// +/// This struct is used to define how a service binds to a network interface and +/// port. +/// +/// It's an URL without path and some restrictions: +/// +/// - Only some schemes are accepted: `udp`, `http`, `https`. +/// - The port number must be greater than zero. The service should be already +/// listening on that port. +/// - The authority part of the URL must be a valid socket address (wildcard is +/// accepted). +/// +/// Besides it accepts some non well-formed URLs, like: +/// or . Those URLs are not valid because they use non +/// standard ports (80 and 443). +/// +/// NOTICE: It does not represent a public valid URL clients can connect to. It +/// represents the service's internal URL configuration after assigning a port. +/// If the port in the configuration is not zero, it's basically the same +/// information you get from the configuration (binding address + protocol). +/// +/// # Examples +/// +/// ``` +/// use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +/// use torrust_tracker_primitives::service_binding::{ServiceBinding, Protocol}; +/// +/// let service_binding = ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(); +/// +/// assert_eq!(service_binding.url().to_string(), "http://127.0.0.1:7070/".to_string()); +/// ``` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)] +pub struct ServiceBinding { + /// The network protocol used by the service (UDP, HTTP, HTTPS). + protocol: Protocol, + + /// The socket address (IP and port) to which the service binds. + bind_address: SocketAddr, +} + +impl ServiceBinding { + /// # Errors + /// + /// This function will return an error if the port number is zero. + pub fn new(protocol: Protocol, bind_address: SocketAddr) -> Result { + if bind_address.port() == 0 { + return Err(Error::PortZeroNotAllowed); + } + + Ok(Self { protocol, bind_address }) + } + + /// Returns the protocol used by the service. + #[must_use] + pub fn protocol(&self) -> Protocol { + self.protocol.clone() + } + + #[must_use] + pub fn bind_address(&self) -> SocketAddr { + self.bind_address + } + + #[must_use] + pub fn bind_address_ip_type(&self) -> IpType { + if self.is_v4_mapped_v6() { + return IpType::V4MappedV6; + } + + IpType::Plain + } + + #[must_use] + pub fn bind_address_ip_family(&self) -> IpFamily { + self.bind_address.ip().into() + } + + /// # Panics + /// + /// It never panics because the URL is always valid. + #[must_use] + pub fn url(&self) -> Url { + Url::parse(&format!("{}://{}", self.protocol, self.bind_address)) + .expect("Service binding can always be parsed into a URL") + } + + fn is_v4_mapped_v6(&self) -> bool { + self.bind_address.ip().is_ipv6() + && self + .bind_address + .ip() + .to_string() + .starts_with(DUAL_STACK_IP_V4_MAPPED_V6_PREFIX) + } +} + +impl From for Url { + fn from(service_binding: ServiceBinding) -> Self { + service_binding.url() + } +} + +impl fmt::Display for ServiceBinding { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.url()) + } +} + +#[cfg(test)] +mod tests { + + mod the_service_binding { + use std::net::SocketAddr; + use std::str::FromStr; + + use rstest::rstest; + use url::Url; + + use crate::service_binding::{Error, IpType, Protocol, ServiceBinding}; + + #[rstest] + #[case("wildcard_ip", Protocol::UDP, SocketAddr::from_str("0.0.0.0:6969").unwrap())] + #[case("udp_service", Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap())] + #[case("http_service", Protocol::HTTP, SocketAddr::from_str("127.0.0.1:7070").unwrap())] + #[case("https_service", Protocol::HTTPS, SocketAddr::from_str("127.0.0.1:7070").unwrap())] + fn should_allow_a_subset_of_urls(#[case] case: &str, #[case] protocol: Protocol, #[case] bind_address: SocketAddr) { + let service_binding = ServiceBinding::new(protocol.clone(), bind_address); + + assert!(service_binding.is_ok(), "{}", format!("{case} failed: {service_binding:?}")); + } + + #[test] + fn should_not_allow_undefined_port_zero() { + let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("127.0.0.1:0").unwrap()); + + assert!(matches!(service_binding, Err(Error::PortZeroNotAllowed))); + } + + #[test] + fn should_return_the_bind_address() { + let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap()).unwrap(); + + assert_eq!( + service_binding.bind_address(), + SocketAddr::from_str("127.0.0.1:6969").unwrap() + ); + } + + #[test] + fn should_return_the_bind_address_plain_type_for_ipv4_ips() { + let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap()).unwrap(); + + assert_eq!(service_binding.bind_address_ip_type(), IpType::Plain); + } + + #[test] + fn should_return_the_bind_address_plain_type_for_ipv6_ips() { + let service_binding = + ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("[0:0:0:0:0:0:0:1]:6969").unwrap()).unwrap(); + + assert_eq!(service_binding.bind_address_ip_type(), IpType::Plain); + } + + #[test] + fn should_return_the_bind_address_v4_mapped_v7_type_for_ipv4_ips_mapped_to_ipv6() { + let service_binding = + ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("[::ffff:192.0.2.33]:6969").unwrap()).unwrap(); + + assert_eq!(service_binding.bind_address_ip_type(), IpType::V4MappedV6); + } + + #[test] + fn should_return_the_corresponding_url() { + let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap()).unwrap(); + + assert_eq!(service_binding.url(), Url::parse("udp://127.0.0.1:6969").unwrap()); + } + + #[test] + fn should_be_converted_into_an_url() { + let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap()).unwrap(); + + let url: Url = service_binding.clone().into(); + + assert_eq!(url, Url::parse("udp://127.0.0.1:6969").unwrap()); + } + + #[rstest] + #[case("udp_service", Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap(), "udp://127.0.0.1:6969")] + #[case("http_service", Protocol::HTTP, SocketAddr::from_str("127.0.0.1:7070").unwrap(), "http://127.0.0.1:7070/")] + #[case("https_service", Protocol::HTTPS, SocketAddr::from_str("127.0.0.1:7070").unwrap(), "https://127.0.0.1:7070/")] + fn should_always_have_a_corresponding_unique_url( + #[case] case: &str, + #[case] protocol: Protocol, + #[case] bind_address: SocketAddr, + #[case] expected_url: String, + ) { + let service_binding = ServiceBinding::new(protocol.clone(), bind_address).unwrap(); + + assert_eq!( + service_binding.url().to_string(), + expected_url, + "{case} failed: {service_binding:?}", + ); + } + } +} diff --git a/packages/primitives/src/swarm_metadata.rs b/packages/primitives/src/swarm_metadata.rs new file mode 100644 index 000000000..57ba816d3 --- /dev/null +++ b/packages/primitives/src/swarm_metadata.rs @@ -0,0 +1,72 @@ +use std::ops::AddAssign; + +use derive_more::Constructor; + +/// Swarm statistics for one torrent. +/// +/// Swarm metadata dictionary in the scrape response. +/// +/// See [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Constructor)] +pub struct SwarmMetadata { + /// (i.e `completed`): The number of peers that have ever completed + /// downloading a given torrent. + pub downloaded: u32, + + /// (i.e `seeders`): The number of active peers that have completed + /// downloading (seeders) a given torrent. + pub complete: u32, + + /// (i.e `leechers`): The number of active peers that have not completed + /// downloading (leechers) a given torrent. + pub incomplete: u32, +} + +impl SwarmMetadata { + #[must_use] + pub fn zeroed() -> Self { + Self::default() + } + + #[must_use] + pub fn downloads(&self) -> u32 { + self.downloaded + } + + #[must_use] + pub fn seeders(&self) -> u32 { + self.complete + } + + #[must_use] + pub fn leechers(&self) -> u32 { + self.incomplete + } +} + +/// Structure that holds aggregate swarm metadata. +/// +/// Metrics are aggregate values for all active torrents/swarms. +#[derive(Copy, Clone, Debug, PartialEq, Default)] +pub struct AggregateActiveSwarmMetadata { + /// Total number of peers that have ever completed downloading. + pub total_downloaded: u64, + + /// Total number of seeders. + pub total_complete: u64, + + /// Total number of leechers. + pub total_incomplete: u64, + + /// Total number of torrents. + pub total_torrents: u64, +} + +impl AddAssign for AggregateActiveSwarmMetadata { + fn add_assign(&mut self, rhs: Self) { + self.total_complete += rhs.total_complete; + self.total_downloaded += rhs.total_downloaded; + self.total_incomplete += rhs.total_incomplete; + self.total_torrents += rhs.total_torrents; + } +} diff --git a/packages/rest-tracker-api-client/Cargo.toml b/packages/rest-tracker-api-client/Cargo.toml new file mode 100644 index 000000000..47307df9a --- /dev/null +++ b/packages/rest-tracker-api-client/Cargo.toml @@ -0,0 +1,23 @@ +[package] +description = "A library to interact with the Torrust Tracker REST API." +keywords = [ "bittorrent", "client", "tracker" ] +license = "LGPL-3.0" +name = "torrust-rest-tracker-api-client" +readme = "README.md" + +authors.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +hyper = "1" +reqwest = { version = "0", features = [ "json", "query" ] } +serde = { version = "1", features = [ "derive" ] } +thiserror = "2" +url = { version = "2", features = [ "serde" ] } +uuid = { version = "1", features = [ "v4" ] } diff --git a/packages/rest-tracker-api-client/README.md b/packages/rest-tracker-api-client/README.md new file mode 100644 index 000000000..3c10cdb5c --- /dev/null +++ b/packages/rest-tracker-api-client/README.md @@ -0,0 +1,23 @@ +# Torrust Tracker API Client + +A library to interact with the Torrust Tracker REST API. + +## License + +**Copyright (c) 2024 The Torrust Developers.** + +This program is free software: you can redistribute it and/or modify it under the terms of the [GNU Lesser General Public License][LGPL_3_0] as published by the [Free Software Foundation][FSF], version 3. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the [GNU Lesser General Public License][LGPL_3_0] for more details. + +You should have received a copy of the *GNU Lesser General Public License* along with this program. If not, see . + +Some files include explicit copyright notices and/or license notices. + +### Legacy Exception + +For prosperity, versions of Torrust BitTorrent Tracker Client that are older than five years are automatically granted the [MIT-0][MIT_0] license in addition to the existing [LGPL-3.0-only][LGPL_3_0] license. + +[LGPL_3_0]: ./LICENSE +[MIT_0]: ./docs/licenses/LICENSE-MIT_0 +[FSF]: https://www.fsf.org/ diff --git a/packages/rest-tracker-api-client/docs/licenses/LICENSE-MIT_0 b/packages/rest-tracker-api-client/docs/licenses/LICENSE-MIT_0 new file mode 100644 index 000000000..fc06cc4fe --- /dev/null +++ b/packages/rest-tracker-api-client/docs/licenses/LICENSE-MIT_0 @@ -0,0 +1,14 @@ +MIT No Attribution + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/rest-tracker-api-client/src/common/http.rs b/packages/rest-tracker-api-client/src/common/http.rs new file mode 100644 index 000000000..adbc7dc15 --- /dev/null +++ b/packages/rest-tracker-api-client/src/common/http.rs @@ -0,0 +1,57 @@ +pub type ReqwestQuery = Vec; +pub type ReqwestQueryParam = (String, String); + +/// URL Query component +#[derive(Default, Debug)] +pub struct Query { + params: Vec, +} + +impl Query { + #[must_use] + pub fn empty() -> Self { + Self { params: vec![] } + } + + #[must_use] + pub fn params(params: Vec) -> Self { + Self { params } + } + + pub fn add_param(&mut self, param: QueryParam) { + self.params.push(param); + } +} + +impl From for ReqwestQuery { + fn from(url_search_params: Query) -> Self { + url_search_params + .params + .iter() + .map(|param| ReqwestQueryParam::from((*param).clone())) + .collect() + } +} + +/// URL query param +#[derive(Clone, Debug)] +pub struct QueryParam { + name: String, + value: String, +} + +impl QueryParam { + #[must_use] + pub fn new(name: &str, value: &str) -> Self { + Self { + name: name.to_string(), + value: value.to_string(), + } + } +} + +impl From for ReqwestQueryParam { + fn from(param: QueryParam) -> Self { + (param.name, param.value) + } +} diff --git a/packages/rest-tracker-api-client/src/common/mod.rs b/packages/rest-tracker-api-client/src/common/mod.rs new file mode 100644 index 000000000..3883215fc --- /dev/null +++ b/packages/rest-tracker-api-client/src/common/mod.rs @@ -0,0 +1 @@ +pub mod http; diff --git a/packages/rest-tracker-api-client/src/connection_info.rs b/packages/rest-tracker-api-client/src/connection_info.rs new file mode 100644 index 000000000..1224527ae --- /dev/null +++ b/packages/rest-tracker-api-client/src/connection_info.rs @@ -0,0 +1,154 @@ +use std::str::FromStr; + +use thiserror::Error; +use url::Url; + +#[derive(Clone)] +pub struct ConnectionInfo { + pub origin: Origin, + pub api_token: Option, +} + +impl ConnectionInfo { + #[must_use] + pub fn authenticated(origin: Origin, api_token: &str) -> Self { + Self { + origin, + api_token: Some(api_token.to_string()), + } + } + + #[must_use] + pub fn anonymous(origin: Origin) -> Self { + Self { origin, api_token: None } + } +} + +/// Represents the origin of a HTTP request. +/// +/// The format of the origin is a URL, but only the scheme, host, and port are used. +/// +/// Pattern: `scheme://host:port/` +#[derive(Debug, Clone)] +pub struct Origin { + url: Url, +} + +#[derive(Debug, Error)] +pub enum OriginError { + #[error("Invalid URL: {0}")] + InvalidUrl(#[from] url::ParseError), + + #[error("URL is missing scheme or host")] + InvalidOrigin, + + #[error("Invalid URL scheme, only http and https are supported")] + InvalidScheme, +} + +impl FromStr for Origin { + type Err = OriginError; + + fn from_str(s: &str) -> Result { + let mut url = Url::parse(s).map_err(OriginError::InvalidUrl)?; + + // Ensure the URL has a scheme and host + if url.scheme().is_empty() || url.host().is_none() { + return Err(OriginError::InvalidOrigin); + } + + if url.scheme() != "http" && url.scheme() != "https" { + return Err(OriginError::InvalidScheme); + } + + // Retain only the origin components + url.set_path("/"); + url.set_query(None); + url.set_fragment(None); + + Ok(Origin { url }) + } +} + +impl std::fmt::Display for Origin { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.url) + } +} + +impl Origin { + /// # Errors + /// + /// Will return an error if the string is not a valid URL containing a + /// scheme and host. + pub fn new(s: &str) -> Result { + s.parse() + } + + #[must_use] + pub fn url(&self) -> &Url { + &self.url + } +} + +#[cfg(test)] +mod tests { + mod origin { + use crate::connection_info::Origin; + + #[test] + fn should_be_parsed_from_a_string_representing_a_url() { + let origin = Origin::new("https://example.com:8080/path?query#fragment").unwrap(); + + assert_eq!(origin.to_string(), "https://example.com:8080/"); + } + + mod when_parsing_from_url_string { + use crate::connection_info::Origin; + + #[test] + fn should_ignore_default_ports() { + let origin = Origin::new("http://example.com:80").unwrap(); // DevSkim: ignore DS137138 + assert_eq!(origin.to_string(), "http://example.com/"); // DevSkim: ignore DS137138 + + let origin = Origin::new("https://example.com:443").unwrap(); + assert_eq!(origin.to_string(), "https://example.com/"); + } + + #[test] + fn should_add_the_slash_after_the_host() { + let origin = Origin::new("https://example.com:1212").unwrap(); + + assert_eq!(origin.to_string(), "https://example.com:1212/"); + } + + #[test] + fn should_remove_extra_path_and_query_parameters() { + let origin = Origin::new("https://example.com:1212/path/to/resource?query=1#fragment").unwrap(); + + assert_eq!(origin.to_string(), "https://example.com:1212/"); + } + + #[test] + fn should_fail_when_the_scheme_is_missing() { + let result = Origin::new("example.com"); + + assert!(result.is_err()); + } + + #[test] + fn should_fail_when_the_scheme_is_not_supported() { + let result = Origin::new("udp://example.com"); + + assert!(result.is_err()); + } + + #[test] + fn should_fail_when_the_host_is_missing() { + let result = Origin::new("http://"); + + assert!(result.is_err()); + } + } + } +} diff --git a/packages/rest-tracker-api-client/src/lib.rs b/packages/rest-tracker-api-client/src/lib.rs new file mode 100644 index 000000000..baf80e3cd --- /dev/null +++ b/packages/rest-tracker-api-client/src/lib.rs @@ -0,0 +1,3 @@ +pub mod common; +pub mod connection_info; +pub mod v1; diff --git a/packages/rest-tracker-api-client/src/v1/client.rs b/packages/rest-tracker-api-client/src/v1/client.rs new file mode 100644 index 000000000..02a5b0d9c --- /dev/null +++ b/packages/rest-tracker-api-client/src/v1/client.rs @@ -0,0 +1,265 @@ +use std::time::Duration; + +use hyper::{header, HeaderMap}; +use reqwest::{Error, Response}; +use serde::Serialize; +use url::Url; +use uuid::Uuid; + +use crate::common::http::{Query, QueryParam, ReqwestQuery}; +use crate::connection_info::ConnectionInfo; + +pub const TOKEN_PARAM_NAME: &str = "token"; +pub const AUTH_BEARER_TOKEN_HEADER_PREFIX: &str = "Bearer"; + +const API_PATH: &str = "api/v1/"; +const DEFAULT_REQUEST_TIMEOUT_IN_SECS: u64 = 5; + +/// API Client +#[allow(clippy::struct_field_names)] +pub struct Client { + connection_info: ConnectionInfo, + base_path: String, + http_client: reqwest::Client, +} + +impl Client { + /// # Errors + /// + /// Will return an error if the HTTP client can't be created. + pub fn new(connection_info: ConnectionInfo) -> Result { + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(DEFAULT_REQUEST_TIMEOUT_IN_SECS)) + .build()?; + + Ok(Self { + connection_info, + base_path: API_PATH.to_string(), + http_client: client, + }) + } + + pub async fn generate_auth_key(&self, seconds_valid: i32, headers: Option) -> Response { + self.post_empty(&format!("key/{}", &seconds_valid), headers).await + } + + pub async fn add_auth_key(&self, add_key_form: AddKeyForm, headers: Option) -> Response { + self.post_form("keys", &add_key_form, headers).await + } + + pub async fn delete_auth_key(&self, key: &str, headers: Option) -> Response { + self.delete(&format!("key/{}", &key), headers).await + } + + pub async fn reload_keys(&self, headers: Option) -> Response { + self.get("keys/reload", Query::default(), headers).await + } + + pub async fn whitelist_a_torrent(&self, info_hash: &str, headers: Option) -> Response { + self.post_empty(&format!("whitelist/{}", &info_hash), headers).await + } + + pub async fn remove_torrent_from_whitelist(&self, info_hash: &str, headers: Option) -> Response { + self.delete(&format!("whitelist/{}", &info_hash), headers).await + } + + pub async fn reload_whitelist(&self, headers: Option) -> Response { + self.get("whitelist/reload", Query::default(), headers).await + } + + pub async fn get_torrent(&self, info_hash: &str, headers: Option) -> Response { + self.get(&format!("torrent/{}", &info_hash), Query::default(), headers).await + } + + pub async fn get_torrents(&self, params: Query, headers: Option) -> Response { + self.get("torrents", params, headers).await + } + + pub async fn get_tracker_statistics(&self, headers: Option) -> Response { + self.get("stats", Query::default(), headers).await + } + + pub async fn get(&self, path: &str, params: Query, headers: Option) -> Response { + let mut query: Query = params; + + if let Some(token) = &self.connection_info.api_token { + query.add_param(QueryParam::new(TOKEN_PARAM_NAME, token)); + } + + self.get_request_with_query(path, query, headers).await + } + + /// # Panics + /// + /// Will panic if the request can't be sent + pub async fn post_empty(&self, path: &str, headers: Option) -> Response { + let builder = self.http_client.post(self.base_url(path).clone()); + + let builder = match headers { + Some(headers) => builder.headers(headers), + None => builder, + }; + + let builder = match &self.connection_info.api_token { + Some(token) => builder.header(header::AUTHORIZATION, format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}")), + None => builder, + }; + + builder.send().await.unwrap() + } + + /// # Panics + /// + /// Will panic if the request can't be sent + pub async fn post_form(&self, path: &str, form: &T, headers: Option) -> Response { + let builder = self.http_client.post(self.base_url(path).clone()).json(&form); + + let builder = match headers { + Some(headers) => builder.headers(headers), + None => builder, + }; + + let builder = match &self.connection_info.api_token { + Some(token) => builder.header(header::AUTHORIZATION, format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}")), + None => builder, + }; + + builder.send().await.unwrap() + } + + /// # Panics + /// + /// Will panic if the request can't be sent + async fn delete(&self, path: &str, headers: Option) -> Response { + let builder = self.http_client.delete(self.base_url(path).clone()); + + let builder = match headers { + Some(headers) => builder.headers(headers), + None => builder, + }; + + let builder = match &self.connection_info.api_token { + Some(token) => builder.header(header::AUTHORIZATION, format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}")), + None => builder, + }; + + builder.send().await.unwrap() + } + + /// # Panics + /// + /// Will panic if it can't convert the authentication token to a `HeaderValue`. + pub async fn get_request_with_query(&self, path: &str, params: Query, headers: Option) -> Response { + match &self.connection_info.api_token { + Some(token) => { + let headers = if let Some(headers) = headers { + // Headers provided -> add auth token if not already present + + if headers.get(header::AUTHORIZATION).is_some() { + // Auth token already present -> use provided + headers + } else { + let mut headers = headers; + + headers.insert( + header::AUTHORIZATION, + format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}") + .parse() + .expect("the auth token is not a valid header value"), + ); + + headers + } + } else { + // No headers provided -> create headers with auth token + + let mut headers = HeaderMap::new(); + + headers.insert( + header::AUTHORIZATION, + format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}") + .parse() + .expect("the auth token is not a valid header value"), + ); + + headers + }; + + get(self.base_url(path), Some(params), Some(headers)).await + } + None => get(self.base_url(path), Some(params), headers).await, + } + } + + pub async fn get_request(&self, path: &str) -> Response { + get(self.base_url(path), None, None).await + } + + fn base_url(&self, path: &str) -> Url { + Url::parse(&format!("{}{}{path}", &self.connection_info.origin, &self.base_path)).unwrap() + } +} + +/// # Panics +/// +/// Will panic if the request can't be sent +pub async fn get(path: Url, query: Option, headers: Option) -> Response { + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(DEFAULT_REQUEST_TIMEOUT_IN_SECS)) + .build() + .unwrap(); + + let mut request_builder = client.get(path); + + if let Some(params) = query { + request_builder = request_builder.query(&ReqwestQuery::from(params)); + } + + if let Some(headers) = headers { + request_builder = request_builder.headers(headers); + } + + request_builder.send().await.unwrap() +} + +/// Returns a `HeaderMap` with a request id header. +/// +/// # Panics +/// +/// Will panic if the request ID can't be parsed into a `HeaderValue`. +#[must_use] +pub fn headers_with_request_id(request_id: Uuid) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert( + "x-request-id", + request_id + .to_string() + .parse() + .expect("the request ID is not a valid header value"), + ); + headers +} + +/// Returns a `HeaderMap` with an authorization token. +/// +/// # Panics +/// +/// Will panic if the token can't be parsed into a `HeaderValue`. +#[must_use] +pub fn headers_with_auth_token(token: &str) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert( + header::AUTHORIZATION, + format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}") + .parse() + .expect("the auth token is not a valid header value"), + ); + headers +} + +#[derive(Serialize, Debug)] +pub struct AddKeyForm { + #[serde(rename = "key")] + pub opt_key: Option, + pub seconds_valid: Option, +} diff --git a/packages/rest-tracker-api-client/src/v1/mod.rs b/packages/rest-tracker-api-client/src/v1/mod.rs new file mode 100644 index 000000000..b9babe5bc --- /dev/null +++ b/packages/rest-tracker-api-client/src/v1/mod.rs @@ -0,0 +1 @@ +pub mod client; diff --git a/packages/rest-tracker-api-core/Cargo.toml b/packages/rest-tracker-api-core/Cargo.toml new file mode 100644 index 000000000..0808c2dd6 --- /dev/null +++ b/packages/rest-tracker-api-core/Cargo.toml @@ -0,0 +1,30 @@ +[package] +authors.workspace = true +description = "A library with the core functionality needed to implement a BitTorrent UDP tracker." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = [ "api", "bittorrent", "core", "library", "tracker" ] +license.workspace = true +name = "torrust-rest-tracker-api-core" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "../http-tracker-core" } +bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } +bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "../udp-tracker-core" } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } +tokio-util = "0.7.15" +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } +torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker-server" } + +[dev-dependencies] +torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } diff --git a/packages/rest-tracker-api-core/LICENSE b/packages/rest-tracker-api-core/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/rest-tracker-api-core/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/rest-tracker-api-core/README.md b/packages/rest-tracker-api-core/README.md new file mode 100644 index 000000000..96bf17bf7 --- /dev/null +++ b/packages/rest-tracker-api-core/README.md @@ -0,0 +1,11 @@ +# BitTorrent UDP Tracker Core library + +A library with the core functionality needed to implement the Torrust Tracker API + +## Documentation + +[Crate documentation](https://docs.rs/torrust-tracker-api-core). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/rest-tracker-api-core/src/container.rs b/packages/rest-tracker-api-core/src/container.rs new file mode 100644 index 000000000..bcc5a0186 --- /dev/null +++ b/packages/rest-tracker-api-core/src/container.rs @@ -0,0 +1,93 @@ +use std::sync::Arc; + +use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; +use bittorrent_tracker_core::container::TrackerCoreContainer; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; +use bittorrent_udp_tracker_core::services::banning::BanService; +use bittorrent_udp_tracker_core::{self}; +use tokio::sync::RwLock; +use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; +use torrust_udp_tracker_server::container::UdpTrackerServerContainer; + +pub struct TrackerHttpApiCoreContainer { + pub http_api_config: Arc, + + // Swarm Coordination Registry Container + pub swarm_coordination_registry_container: Arc, + + // Tracker core + pub tracker_core_container: Arc, + + // HTTP tracker core + pub http_stats_repository: Arc, + + // UDP tracker core + pub ban_service: Arc>, + pub udp_core_stats_repository: Arc, + pub udp_server_stats_repository: Arc, +} + +impl TrackerHttpApiCoreContainer { + #[must_use] + pub fn initialize( + core_config: &Arc, + http_tracker_config: &Arc, + udp_tracker_config: &Arc, + http_api_config: &Arc, + ) -> Arc { + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + core_config.tracker_usage_statistics.into(), + )); + + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + core_config, + &swarm_coordination_registry_container, + )); + + let http_tracker_core_container = + HttpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, http_tracker_config); + + let udp_tracker_core_container = + UdpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, udp_tracker_config); + + let udp_tracker_server_container = UdpTrackerServerContainer::initialize(core_config); + + Self::initialize_from( + &swarm_coordination_registry_container, + &tracker_core_container, + &http_tracker_core_container, + &udp_tracker_core_container, + &udp_tracker_server_container, + http_api_config, + ) + } + + #[must_use] + pub fn initialize_from( + swarm_coordination_registry_container: &Arc, + tracker_core_container: &Arc, + http_tracker_core_container: &Arc, + udp_tracker_core_container: &Arc, + udp_tracker_server_container: &Arc, + http_api_config: &Arc, + ) -> Arc { + Arc::new(TrackerHttpApiCoreContainer { + http_api_config: http_api_config.clone(), + + // Swarm Coordination Registry Container + swarm_coordination_registry_container: swarm_coordination_registry_container.clone(), + + // Tracker core + tracker_core_container: tracker_core_container.clone(), + + // HTTP tracker core + http_stats_repository: http_tracker_core_container.stats_repository.clone(), + + // UDP tracker core + ban_service: udp_tracker_core_container.ban_service.clone(), + udp_core_stats_repository: udp_tracker_core_container.stats_repository.clone(), + udp_server_stats_repository: udp_tracker_server_container.stats_repository.clone(), + }) + } +} diff --git a/packages/rest-tracker-api-core/src/lib.rs b/packages/rest-tracker-api-core/src/lib.rs new file mode 100644 index 000000000..ddf1d9afd --- /dev/null +++ b/packages/rest-tracker-api-core/src/lib.rs @@ -0,0 +1,2 @@ +pub mod container; +pub mod statistics; diff --git a/packages/rest-tracker-api-core/src/statistics/metrics.rs b/packages/rest-tracker-api-core/src/statistics/metrics.rs new file mode 100644 index 000000000..ecdecd130 --- /dev/null +++ b/packages/rest-tracker-api-core/src/statistics/metrics.rs @@ -0,0 +1,118 @@ +use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; + +/// Metrics collected by the tracker at the swarm layer. +#[derive(Copy, Clone, Debug, PartialEq, Default)] +pub struct TorrentsMetrics { + /// Total number of peers that have ever completed downloading. + pub total_downloaded: u64, + + /// Total number of seeders. + pub total_complete: u64, + + /// Total number of leechers. + pub total_incomplete: u64, + + /// Total number of torrents. + pub total_torrents: u64, +} + +impl From for TorrentsMetrics { + fn from(value: AggregateActiveSwarmMetadata) -> Self { + Self { + total_downloaded: value.total_downloaded, + total_complete: value.total_complete, + total_incomplete: value.total_incomplete, + total_torrents: value.total_torrents, + } + } +} + +/// Metrics collected by the tracker at the delivery layer. +/// +/// - Number of connections handled +/// - Number of `announce` requests handled +/// - Number of `scrape` request handled +/// +/// These metrics are collected for each connection type: UDP and HTTP +/// and also for each IP version used by the peers: IPv4 and IPv6. +#[derive(Debug, PartialEq, Default)] +pub struct ProtocolMetrics { + /// Total number of TCP (HTTP tracker) connections from IPv4 peers. + /// Since the HTTP tracker spec does not require a handshake, this metric + /// increases for every HTTP request. + #[deprecated(since = "3.1.0")] + pub tcp4_connections_handled: u64, + + /// Total number of TCP (HTTP tracker) `announce` requests from IPv4 peers. + pub tcp4_announces_handled: u64, + + /// Total number of TCP (HTTP tracker) `scrape` requests from IPv4 peers. + pub tcp4_scrapes_handled: u64, + + /// Total number of TCP (HTTP tracker) connections from IPv6 peers. + #[deprecated(since = "3.1.0")] + pub tcp6_connections_handled: u64, + + /// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers. + pub tcp6_announces_handled: u64, + + /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. + pub tcp6_scrapes_handled: u64, + + // UDP + /// Total number of UDP (UDP tracker) requests aborted. + pub udp_requests_aborted: u64, + + /// Total number of UDP (UDP tracker) requests banned. + pub udp_requests_banned: u64, + + /// Total number of banned IPs. + pub udp_banned_ips_total: u64, + + /// Average rounded time spent processing UDP connect requests. + pub udp_avg_connect_processing_time_ns: u64, + + /// Average rounded time spent processing UDP announce requests. + pub udp_avg_announce_processing_time_ns: u64, + + /// Average rounded time spent processing UDP scrape requests. + pub udp_avg_scrape_processing_time_ns: u64, + + // UDPv4 + /// Total number of UDP (UDP tracker) requests from IPv4 peers. + pub udp4_requests: u64, + + /// Total number of UDP (UDP tracker) connections from IPv4 peers. + pub udp4_connections_handled: u64, + + /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. + pub udp4_announces_handled: u64, + + /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. + pub udp4_scrapes_handled: u64, + + /// Total number of UDP (UDP tracker) responses from IPv4 peers. + pub udp4_responses: u64, + + /// Total number of UDP (UDP tracker) `error` requests from IPv4 peers. + pub udp4_errors_handled: u64, + + // UDPv6 + /// Total number of UDP (UDP tracker) requests from IPv6 peers. + pub udp6_requests: u64, + + /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. + pub udp6_connections_handled: u64, + + /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. + pub udp6_announces_handled: u64, + + /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. + pub udp6_scrapes_handled: u64, + + /// Total number of UDP (UDP tracker) responses from IPv6 peers. + pub udp6_responses: u64, + + /// Total number of UDP (UDP tracker) `error` requests from IPv6 peers. + pub udp6_errors_handled: u64, +} diff --git a/packages/rest-tracker-api-core/src/statistics/mod.rs b/packages/rest-tracker-api-core/src/statistics/mod.rs new file mode 100644 index 000000000..a3c8a4b0e --- /dev/null +++ b/packages/rest-tracker-api-core/src/statistics/mod.rs @@ -0,0 +1,2 @@ +pub mod metrics; +pub mod services; diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs new file mode 100644 index 000000000..f87cb8c76 --- /dev/null +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -0,0 +1,260 @@ +use std::sync::Arc; + +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use bittorrent_udp_tracker_core::services::banning::BanService; +use bittorrent_udp_tracker_core::{self}; +use tokio::sync::RwLock; +use torrust_tracker_metrics::metric_collection::MetricCollection; +use torrust_udp_tracker_server::statistics::{self as udp_server_statistics}; + +use super::metrics::TorrentsMetrics; +use crate::statistics::metrics::ProtocolMetrics; + +/// All the metrics collected by the tracker. +#[derive(Debug, PartialEq)] +pub struct TrackerMetrics { + /// Domain level metrics. + /// + /// General metrics for all torrents (number of seeders, leechers, etcetera) + pub torrents_metrics: TorrentsMetrics, + + /// Application level metrics. Usage statistics/metrics. + /// + /// Metrics about how the tracker is been used (number of udp announce requests, number of http scrape requests, etcetera) + pub protocol_metrics: ProtocolMetrics, +} + +/// It returns all the [`TrackerMetrics`] +pub async fn get_metrics( + in_memory_torrent_repository: Arc, + tracker_core_stats_repository: Arc, + http_stats_repository: Arc, + udp_server_stats_repository: Arc, +) -> TrackerMetrics { + TrackerMetrics { + torrents_metrics: get_torrents_metrics(in_memory_torrent_repository, tracker_core_stats_repository).await, + protocol_metrics: get_protocol_metrics(http_stats_repository.clone(), udp_server_stats_repository.clone()).await, + } +} + +async fn get_torrents_metrics( + in_memory_torrent_repository: Arc, + + tracker_core_stats_repository: Arc, +) -> TorrentsMetrics { + let aggregate_active_swarm_metadata = in_memory_torrent_repository.get_aggregate_swarm_metadata().await; + + let mut torrents_metrics: TorrentsMetrics = aggregate_active_swarm_metadata.into(); + torrents_metrics.total_downloaded = tracker_core_stats_repository.get_torrents_downloads_total().await; + + torrents_metrics +} + +#[allow(deprecated)] +#[allow(clippy::too_many_lines)] +async fn get_protocol_metrics( + http_stats_repository: Arc, + udp_server_stats_repository: Arc, +) -> ProtocolMetrics { + let http_stats = http_stats_repository.get_stats().await; + let udp_server_stats = udp_server_stats_repository.get_stats().await; + + // TCPv4 + + let tcp4_announces_handled = http_stats.tcp4_announces_handled(); + let tcp4_scrapes_handled = http_stats.tcp4_scrapes_handled(); + + // TCPv6 + + let tcp6_announces_handled = http_stats.tcp6_announces_handled(); + let tcp6_scrapes_handled = http_stats.tcp6_scrapes_handled(); + + // UDP + + let udp_requests_aborted = udp_server_stats.udp_requests_aborted_total(); + let udp_requests_banned = udp_server_stats.udp_requests_banned_total(); + let udp_banned_ips_total = udp_server_stats.udp_banned_ips_total(); + let udp_avg_connect_processing_time_ns = udp_server_stats.udp_avg_connect_processing_time_ns_averaged(); + let udp_avg_announce_processing_time_ns = udp_server_stats.udp_avg_announce_processing_time_ns_averaged(); + let udp_avg_scrape_processing_time_ns = udp_server_stats.udp_avg_scrape_processing_time_ns_averaged(); + + // UDPv4 + + let udp4_requests = udp_server_stats.udp4_requests_received_total(); + let udp4_connections_handled = udp_server_stats.udp4_connect_requests_accepted_total(); + let udp4_announces_handled = udp_server_stats.udp4_announce_requests_accepted_total(); + let udp4_scrapes_handled = udp_server_stats.udp4_scrape_requests_accepted_total(); + let udp4_responses = udp_server_stats.udp4_responses_sent_total(); + let udp4_errors_handled = udp_server_stats.udp4_errors_total(); + + // UDPv6 + + let udp6_requests = udp_server_stats.udp6_requests_received_total(); + let udp6_connections_handled = udp_server_stats.udp6_connect_requests_accepted_total(); + let udp6_announces_handled = udp_server_stats.udp6_announce_requests_accepted_total(); + let udp6_scrapes_handled = udp_server_stats.udp6_scrape_requests_accepted_total(); + let udp6_responses = udp_server_stats.udp6_responses_sent_total(); + let udp6_errors_handled = udp_server_stats.udp6_errors_total(); + + // For backward compatibility we keep the `tcp4_connections_handled` and + // `tcp6_connections_handled` metrics. They don't make sense for the HTTP + // tracker, but we keep them for now. In new major versions we should remove + // them. + + ProtocolMetrics { + // TCPv4 + tcp4_connections_handled: tcp4_announces_handled + tcp4_scrapes_handled, + tcp4_announces_handled, + tcp4_scrapes_handled, + // TCPv6 + tcp6_connections_handled: tcp6_announces_handled + tcp6_scrapes_handled, + tcp6_announces_handled, + tcp6_scrapes_handled, + // UDP + udp_requests_aborted, + udp_requests_banned, + udp_banned_ips_total, + udp_avg_connect_processing_time_ns, + udp_avg_announce_processing_time_ns, + udp_avg_scrape_processing_time_ns, + // UDPv4 + udp4_requests, + udp4_connections_handled, + udp4_announces_handled, + udp4_scrapes_handled, + udp4_responses, + udp4_errors_handled, + // UDPv6 + udp6_requests, + udp6_connections_handled, + udp6_announces_handled, + udp6_scrapes_handled, + udp6_responses, + udp6_errors_handled, + } +} + +#[derive(Debug, PartialEq)] +pub struct TrackerLabeledMetrics { + pub metrics: MetricCollection, +} + +/// It returns all the [`TrackerLabeledMetrics`] +/// +/// # Panics +/// +/// Will panic if the metrics cannot be merged. This could happen if the +/// packages are producing duplicate metric names, for example. +pub async fn get_labeled_metrics( + in_memory_torrent_repository: Arc, + ban_service: Arc>, + swarms_stats_repository: Arc, + tracker_core_stats_repository: Arc, + http_stats_repository: Arc, + udp_stats_repository: Arc, + udp_server_stats_repository: Arc, +) -> TrackerLabeledMetrics { + let _torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata(); + let _udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); + + let swarms_stats = swarms_stats_repository.get_metrics().await; + let tracker_core_stats = tracker_core_stats_repository.get_metrics().await; + let http_stats = http_stats_repository.get_stats().await; + let udp_stats_repository = udp_stats_repository.get_stats().await; + let udp_server_stats = udp_server_stats_repository.get_stats().await; + + // Merge all the metrics into a single collection + let mut metrics = MetricCollection::default(); + + metrics + .merge(&swarms_stats.metric_collection) + .expect("msg: failed to merge torrent repository metrics"); + metrics + .merge(&tracker_core_stats.metric_collection) + .expect("msg: failed to merge tracker core metrics"); + metrics + .merge(&http_stats.metric_collection) + .expect("msg: failed to merge HTTP core metrics"); + metrics + .merge(&udp_stats_repository.metric_collection) + .expect("failed to merge UDP core metrics"); + metrics + .merge(&udp_server_stats.metric_collection) + .expect("failed to merge UDP server metrics"); + + TrackerLabeledMetrics { metrics } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use bittorrent_http_tracker_core::event::bus::EventBus; + use bittorrent_http_tracker_core::event::sender::Broadcaster; + use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; + use bittorrent_http_tracker_core::statistics::repository::Repository; + use bittorrent_tracker_core::container::TrackerCoreContainer; + use bittorrent_tracker_core::{self}; + use bittorrent_udp_tracker_core::services::banning::BanService; + use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; + use tokio::sync::RwLock; + use tokio_util::sync::CancellationToken; + use torrust_tracker_configuration::Configuration; + use torrust_tracker_events::bus::SenderStatus; + use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; + use torrust_tracker_test_helpers::configuration; + + use crate::statistics::metrics::{ProtocolMetrics, TorrentsMetrics}; + use crate::statistics::services::{get_metrics, TrackerMetrics}; + + pub fn tracker_configuration() -> Configuration { + configuration::ephemeral() + } + + #[tokio::test] + async fn the_statistics_service_should_return_the_tracker_metrics() { + let cancellation_token = CancellationToken::new(); + + let config = tracker_configuration(); + let core_config = Arc::new(config.core.clone()); + + let swarm_coordination_registry_container = + Arc::new(SwarmCoordinationRegistryContainer::initialize(SenderStatus::Enabled)); + + let tracker_core_container = + TrackerCoreContainer::initialize_from(&core_config, &swarm_coordination_registry_container.clone()); + + let _ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + + // HTTP core stats + let http_core_broadcaster = Broadcaster::default(); + let http_stats_repository = Arc::new(Repository::new()); + let http_stats_event_bus = Arc::new(EventBus::new( + config.core.tracker_usage_statistics.into(), + http_core_broadcaster.clone(), + )); + + if config.core.tracker_usage_statistics { + let _unused = run_event_listener(http_stats_event_bus.receiver(), cancellation_token, &http_stats_repository); + } + + // UDP server stats + let udp_server_stats_repository = Arc::new(torrust_udp_tracker_server::statistics::repository::Repository::new()); + + let tracker_metrics = get_metrics( + tracker_core_container.in_memory_torrent_repository.clone(), + tracker_core_container.stats_repository.clone(), + http_stats_repository.clone(), + udp_server_stats_repository.clone(), + ) + .await; + + assert_eq!( + tracker_metrics, + TrackerMetrics { + torrents_metrics: TorrentsMetrics::default(), + protocol_metrics: ProtocolMetrics::default(), + } + ); + } +} diff --git a/packages/server-lib/Cargo.toml b/packages/server-lib/Cargo.toml new file mode 100644 index 000000000..fbd7a7a7f --- /dev/null +++ b/packages/server-lib/Cargo.toml @@ -0,0 +1,24 @@ +[package] +authors.workspace = true +description = "Common functionality used in all Torrust HTTP servers." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = [ "lib", "server", "torrust" ] +license.workspace = true +name = "torrust-server-lib" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +derive_more = { version = "2", features = [ "as_ref", "constructor", "display", "from" ] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +tower-http = { version = "0", features = [ "compression-full", "cors", "propagate-header", "request-id", "trace" ] } +tracing = "0" + +[dev-dependencies] +rstest = "0.25.0" diff --git a/packages/server-lib/LICENSE b/packages/server-lib/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/server-lib/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/server-lib/README.md b/packages/server-lib/README.md new file mode 100644 index 000000000..820225a00 --- /dev/null +++ b/packages/server-lib/README.md @@ -0,0 +1,11 @@ +# Torrust Server Lib + +Common functionality used in all Torrust HTTP servers. + +## Documentation + +[Crate documentation](https://docs.rs/torrust-axum-server). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/server-lib/src/lib.rs b/packages/server-lib/src/lib.rs new file mode 100644 index 000000000..324041822 --- /dev/null +++ b/packages/server-lib/src/lib.rs @@ -0,0 +1,3 @@ +pub mod logging; +pub mod registar; +pub mod signals; diff --git a/packages/server-lib/src/logging.rs b/packages/server-lib/src/logging.rs new file mode 100644 index 000000000..c63ba3caf --- /dev/null +++ b/packages/server-lib/src/logging.rs @@ -0,0 +1,58 @@ +use std::fmt; +use std::time::Duration; + +use tower_http::LatencyUnit; + +/// This is the prefix used in logs to identify a started service. +/// +/// For example: +/// +/// ```text +/// 2024-06-25T12:36:25.025312Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969 +/// 2024-06-25T12:36:25.025445Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070 +/// 2024-06-25T12:36:25.025527Z INFO API: Started on: http://0.0.0.0:1212 +/// 2024-06-25T12:36:25.025580Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 +/// ``` +pub const STARTED_ON: &str = "Started on"; + +/* + +todo: we should use a field fot the URL. + +For example, instead of: + +``` +2024-06-25T12:36:25.025312Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969 +``` + +We should use something like: + +``` +2024-06-25T12:36:25.025312Z INFO UDP TRACKER started_at_url=udp://0.0.0.0:6969 +``` + +*/ + +pub struct Latency { + unit: LatencyUnit, + duration: Duration, +} + +impl Latency { + #[must_use] + pub fn new(unit: LatencyUnit, duration: Duration) -> Self { + Self { unit, duration } + } +} + +impl fmt::Display for Latency { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.unit { + LatencyUnit::Seconds => write!(f, "{} s", self.duration.as_secs_f64()), + LatencyUnit::Millis => write!(f, "{} ms", self.duration.as_millis()), + LatencyUnit::Micros => write!(f, "{} μs", self.duration.as_micros()), + LatencyUnit::Nanos => write!(f, "{} ns", self.duration.as_nanos()), + _ => panic!("Invalid latency unit"), + } + } +} diff --git a/packages/server-lib/src/registar.rs b/packages/server-lib/src/registar.rs new file mode 100644 index 000000000..efa94034b --- /dev/null +++ b/packages/server-lib/src/registar.rs @@ -0,0 +1,101 @@ +//! Registar. Registers Services for Health Check. + +use std::collections::HashMap; +use std::sync::Arc; + +use derive_more::Constructor; +use tokio::sync::Mutex; +use tokio::task::JoinHandle; +use torrust_tracker_primitives::service_binding::ServiceBinding; + +/// A [`ServiceHeathCheckResult`] is returned by a completed health check. +pub type ServiceHeathCheckResult = Result; + +/// The [`ServiceHealthCheckJob`] has a health check job with it's metadata +/// +/// The `job` awaits a [`ServiceHeathCheckResult`]. +#[derive(Debug, Constructor)] +pub struct ServiceHealthCheckJob { + pub service_binding: ServiceBinding, + pub info: String, + pub service_type: String, + pub job: JoinHandle, +} + +/// The function specification [`FnSpawnServiceHeathCheck`]. +/// +/// A function fulfilling this specification will spawn a new [`ServiceHealthCheckJob`]. +pub type FnSpawnServiceHeathCheck = fn(&ServiceBinding) -> ServiceHealthCheckJob; + +/// A [`ServiceRegistration`] is provided to the [`Registar`] for registration. +/// +/// Each registration includes a function that fulfils the [`FnSpawnServiceHeathCheck`] specification. +#[derive(Clone, Debug, Constructor)] +pub struct ServiceRegistration { + service_binding: ServiceBinding, + check_fn: FnSpawnServiceHeathCheck, +} + +impl ServiceRegistration { + #[must_use] + pub fn spawn_check(&self) -> ServiceHealthCheckJob { + (self.check_fn)(&self.service_binding) + } +} + +/// A [`ServiceRegistrationForm`] will return a completed [`ServiceRegistration`] to the [`Registar`]. +pub type ServiceRegistrationForm = tokio::sync::oneshot::Sender; + +/// The [`ServiceRegistry`] contains each unique [`ServiceRegistration`] by it's [`SocketAddr`]. +pub type ServiceRegistry = Arc>>; + +/// The [`Registar`] manages the [`ServiceRegistry`]. +#[derive(Clone, Debug)] +pub struct Registar { + registry: ServiceRegistry, +} + +#[allow(clippy::derivable_impls)] +impl Default for Registar { + fn default() -> Self { + Self { + registry: ServiceRegistry::default(), + } + } +} + +impl Registar { + pub fn new(register: ServiceRegistry) -> Self { + Self { registry: register } + } + + /// Registers a Service + #[must_use] + pub fn give_form(&self) -> ServiceRegistrationForm { + let (tx, rx) = tokio::sync::oneshot::channel::(); + let register = self.clone(); + tokio::spawn(async move { + register.insert(rx).await; + }); + tx + } + + /// Inserts a listing into the registry. + async fn insert(&self, rx: tokio::sync::oneshot::Receiver) { + tracing::debug!("Waiting for the started service to send registration data ..."); + + let service_registration = rx + .await + .expect("it should receive the service registration from the started service"); + + let mut mutex = self.registry.lock().await; + + mutex.insert(service_registration.service_binding.clone(), service_registration); + } + + /// Returns the [`ServiceRegistry`] of services + #[must_use] + pub fn entries(&self) -> ServiceRegistry { + self.registry.clone() + } +} diff --git a/packages/server-lib/src/signals.rs b/packages/server-lib/src/signals.rs new file mode 100644 index 000000000..581729e57 --- /dev/null +++ b/packages/server-lib/src/signals.rs @@ -0,0 +1,77 @@ +//! This module contains functions to handle signals. +use derive_more::Display; +use torrust_tracker_primitives::service_binding::ServiceBinding; +use tracing::instrument; + +/// This is the message that the "launcher" spawned task sends to the main +/// application process to notify the service was successfully started. +/// +#[derive(Debug)] +pub struct Started { + pub service_binding: ServiceBinding, + pub address: std::net::SocketAddr, +} + +/// This is the message that the "launcher" spawned task receives from the main +/// application process to notify the service to shutdown. +/// +#[derive(Copy, Clone, Debug, Display)] +pub enum Halted { + Normal, +} + +/// Resolves on `ctrl_c` or the `terminate` signal. +/// +/// # Panics +/// +/// Will panic if the `ctrl_c` or `terminate` signal resolves with an error. +#[instrument(skip())] +pub async fn global_shutdown_signal() { + let ctrl_c = async { + tokio::signal::ctrl_c().await.expect("failed to install Ctrl+C handler"); + }; + + #[cfg(unix)] + let terminate = async { + tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) + .expect("failed to install signal handler") + .recv() + .await; + }; + + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); + + tokio::select! { + () = ctrl_c => {tracing::warn!("caught interrupt signal (ctrl-c), halting...");}, + () = terminate => {tracing::warn!("caught interrupt signal (terminate), halting...");} + } +} + +/// Resolves when the `stop_receiver` or the `global_shutdown_signal()` resolves. +/// +/// # Panics +/// +/// Will panic if the `stop_receiver` resolves with an error. +#[instrument(skip(rx_halt))] +pub async fn shutdown_signal(rx_halt: tokio::sync::oneshot::Receiver) { + let halt = async { + match rx_halt.await { + Ok(signal) => signal, + Err(err) => panic!("Failed to install stop signal: {err}"), + } + }; + + tokio::select! { + signal = halt => { tracing::debug!("Halt signal processed: {}", signal) }, + () = global_shutdown_signal() => { tracing::debug!("Global shutdown signal processed") } + } +} + +/// Same as `shutdown_signal()`, but shows a message when it resolves. +#[instrument(skip(rx_halt))] +pub async fn shutdown_signal_with_message(rx_halt: tokio::sync::oneshot::Receiver, message: String) { + shutdown_signal(rx_halt).await; + + tracing::info!("{message}"); +} diff --git a/packages/swarm-coordination-registry/.gitignore b/packages/swarm-coordination-registry/.gitignore new file mode 100644 index 000000000..c9907ae11 --- /dev/null +++ b/packages/swarm-coordination-registry/.gitignore @@ -0,0 +1 @@ +/.coverage/ diff --git a/packages/swarm-coordination-registry/Cargo.toml b/packages/swarm-coordination-registry/Cargo.toml new file mode 100644 index 000000000..f9513d3c4 --- /dev/null +++ b/packages/swarm-coordination-registry/Cargo.toml @@ -0,0 +1,41 @@ +[package] +description = "A library that provides a repository of torrents files and their peers." +keywords = [ "library", "repository", "torrents" ] +name = "torrust-tracker-swarm-coordination-registry" +readme = "README.md" + +authors.workspace = true +categories.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +bittorrent-primitives = "0.1.0" +chrono = { version = "0", default-features = false, features = [ "clock" ] } +crossbeam-skiplist = "0" +futures = "0" +serde = { version = "1.0.219", features = [ "derive" ] } +thiserror = "2.0.12" +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } +tokio-util = "0.7.15" +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } +torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +tracing = "0" + +[dev-dependencies] +async-std = { version = "1", features = [ "attributes", "tokio1" ] } +criterion = { version = "0", features = [ "async_tokio" ] } +mockall = "0" +rand = "0" +rstest = "0" +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } diff --git a/packages/swarm-coordination-registry/README.md b/packages/swarm-coordination-registry/README.md new file mode 100644 index 000000000..a8c55746b --- /dev/null +++ b/packages/swarm-coordination-registry/README.md @@ -0,0 +1,22 @@ +# Torrust Tracker Torrent Repository + +A library to provide a torrent repository to the [Torrust Tracker](https://github.com/torrust/torrust-tracker). + +Its main responsibilities include: + +- Managing Torrent Entries: It stores, retrieves, and manages torrent entries, which are torrents being tracked. +- Persistence: It supports lading tracked torrents from a persistent storage, ensuring that torrent data can be restored across restarts. +- Pagination and sorting: It provides paginated and stable/sorted access to torrent entries. +- Peer management: It manages peers associated with torrents, including removing inactive peers and handling torrents with no peers (peerless torrents). +- Policy handling: It supports different policies for handling torrents, such as persisting, removing, or custom policies for torrents with no peers. +- Metrics: It can provide metrics about the torrents, such as counts or statuses, likely for monitoring or statistics. + +This repo is a core component for managing the state and lifecycle of torrents and their peers in a BitTorrent tracker, with peer management, and flexible policies. + +## Documentation + +[Crate documentation](https://docs.rs/torrust-tracker-torrent-repository). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/swarm-coordination-registry/src/container.rs b/packages/swarm-coordination-registry/src/container.rs new file mode 100644 index 000000000..718e3ee52 --- /dev/null +++ b/packages/swarm-coordination-registry/src/container.rs @@ -0,0 +1,38 @@ +use std::sync::Arc; + +use torrust_tracker_events::bus::SenderStatus; + +use crate::event::bus::EventBus; +use crate::event::sender::Broadcaster; +use crate::event::{self}; +use crate::statistics::repository::Repository; +use crate::{statistics, Registry}; + +pub struct SwarmCoordinationRegistryContainer { + pub swarms: Arc, + pub event_bus: Arc, + pub stats_event_sender: event::sender::Sender, + pub stats_repository: Arc, +} + +impl SwarmCoordinationRegistryContainer { + #[must_use] + pub fn initialize(sender_status: SenderStatus) -> Self { + // // Swarm Coordination Registry Container stats + let broadcaster = Broadcaster::default(); + let stats_repository = Arc::new(Repository::new()); + + let event_bus = Arc::new(EventBus::new(sender_status, broadcaster.clone())); + + let stats_event_sender = event_bus.sender(); + + let swarms = Arc::new(Registry::new(stats_event_sender.clone())); + + Self { + swarms, + event_bus, + stats_event_sender, + stats_repository, + } + } +} diff --git a/packages/swarm-coordination-registry/src/event.rs b/packages/swarm-coordination-registry/src/event.rs new file mode 100644 index 000000000..65a65ce8c --- /dev/null +++ b/packages/swarm-coordination-registry/src/event.rs @@ -0,0 +1,111 @@ +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::peer::{Peer, PeerAnnouncement}; + +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum Event { + TorrentAdded { + info_hash: InfoHash, + announcement: PeerAnnouncement, + }, + TorrentRemoved { + info_hash: InfoHash, + }, + PeerAdded { + info_hash: InfoHash, + peer: Peer, + }, + PeerRemoved { + info_hash: InfoHash, + peer: Peer, + }, + PeerUpdated { + info_hash: InfoHash, + old_peer: Peer, + new_peer: Peer, + }, + PeerDownloadCompleted { + info_hash: InfoHash, + peer: Peer, + }, +} + +pub mod sender { + use std::sync::Arc; + + use super::Event; + + pub type Sender = Option>>; + pub type Broadcaster = torrust_tracker_events::broadcaster::Broadcaster; + + #[cfg(test)] + pub mod tests { + + use futures::future::{self, BoxFuture}; + use mockall::mock; + use mockall::predicate::eq; + use torrust_tracker_events::sender::{SendError, Sender}; + + use crate::event::Event; + + mock! { + pub EventSender {} + + impl Sender for EventSender { + type Event = Event; + + fn send(&self, event: Event) -> BoxFuture<'static,Option > > > ; + } + } + + pub fn expect_event(mock: &mut MockEventSender, event: Event) { + mock.expect_send() + .with(eq(event)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + } + + pub fn expect_event_sequence(mock: &mut MockEventSender, event: Vec) { + for e in event { + expect_event(mock, e); + } + } + } +} + +pub mod receiver { + use super::Event; + + pub type Receiver = Box>; +} + +pub mod bus { + use crate::event::Event; + + pub type EventBus = torrust_tracker_events::bus::EventBus; +} + +#[cfg(test)] +pub mod test { + + use torrust_tracker_primitives::peer::Peer; + + use super::Event; + use crate::tests::sample_info_hash; + + #[test] + fn events_should_be_comparable() { + let info_hash = sample_info_hash(); + + let event1 = Event::TorrentAdded { + info_hash, + announcement: Peer::default(), + }; + + let event2 = Event::TorrentRemoved { info_hash }; + + let event1_clone = event1.clone(); + + assert!(event1 == event1_clone); + assert!(event1 != event2); + } +} diff --git a/packages/swarm-coordination-registry/src/lib.rs b/packages/swarm-coordination-registry/src/lib.rs new file mode 100644 index 000000000..eb2721a0c --- /dev/null +++ b/packages/swarm-coordination-registry/src/lib.rs @@ -0,0 +1,145 @@ +pub mod container; +pub mod event; +pub mod statistics; +pub mod swarm; + +use std::sync::Arc; + +use tokio::sync::Mutex; +use torrust_tracker_clock::clock; + +pub type Registry = swarm::registry::Registry; +pub type CoordinatorHandle = Arc>; +pub type Coordinator = swarm::coordinator::Coordinator; + +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; + +pub const SWARM_COORDINATION_REGISTRY_LOG_TARGET: &str = "SWARM_COORDINATION_REGISTRY"; + +#[cfg(test)] +pub(crate) mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash_one() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash_alphabetically_ordered_after_sample_info_hash_one() -> InfoHash { + "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } + + /// Sample peer whose state is not relevant for the tests. + #[must_use] + pub fn sample_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } + } + + #[must_use] + pub fn sample_peer_one() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000001"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } + } + + #[must_use] + pub fn sample_peer_two() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000002"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)), 8082), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } + } + + #[must_use] + pub fn seeder() -> Peer { + complete_peer() + } + + #[must_use] + pub fn leecher() -> Peer { + incomplete_peer() + } + + /// A peer that counts as `complete` is swarm metadata + /// IMPORTANT!: it only counts if the it has been announce at least once before + /// announcing the `AnnounceEvent::Completed` event. + #[must_use] + pub fn complete_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } + } + + /// A peer that counts as `incomplete` is swarm metadata + #[must_use] + pub fn incomplete_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(1000), // Still bytes to download + event: AnnounceEvent::Started, + } + } +} diff --git a/packages/swarm-coordination-registry/src/statistics/activity_metrics_updater.rs b/packages/swarm-coordination-registry/src/statistics/activity_metrics_updater.rs new file mode 100644 index 000000000..cf814e810 --- /dev/null +++ b/packages/swarm-coordination-registry/src/statistics/activity_metrics_updater.rs @@ -0,0 +1,104 @@ +//! Job that runs a task on intervals to update peers' activity metrics. +use std::sync::Arc; + +use chrono::Utc; +use tokio::task::JoinHandle; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_primitives::DurationSinceUnixEpoch; +use tracing::instrument; + +use super::repository::Repository; +use crate::statistics::{SWARM_COORDINATION_REGISTRY_PEERS_INACTIVE_TOTAL, SWARM_COORDINATION_REGISTRY_TORRENTS_INACTIVE_TOTAL}; +use crate::{CurrentClock, Registry}; + +#[must_use] +#[instrument(skip(swarms, stats_repository))] +pub fn start_job( + swarms: &Arc, + stats_repository: &Arc, + inactivity_cutoff: DurationSinceUnixEpoch, +) -> JoinHandle<()> { + let weak_swarms = std::sync::Arc::downgrade(swarms); + let weak_stats_repository = std::sync::Arc::downgrade(stats_repository); + + let interval_in_secs = 15; // todo: make this configurable + + tokio::spawn(async move { + let interval = std::time::Duration::from_secs(interval_in_secs); + let mut interval = tokio::time::interval(interval); + interval.tick().await; + + loop { + tokio::select! { + _ = tokio::signal::ctrl_c() => { + tracing::info!("Stopping peers activity metrics update job (ctrl-c signal received) ..."); + break; + } + _ = interval.tick() => { + if let (Some(swarms), Some(stats_repository)) = (weak_swarms.upgrade(), weak_stats_repository.upgrade()) { + update_activity_metrics(interval_in_secs, &swarms, &stats_repository, inactivity_cutoff).await; + } else { + tracing::info!("Stopping peers activity metrics update job (can't upgrade weak pointers) ..."); + break; + } + } + } + } + }) +} + +async fn update_activity_metrics( + interval_in_secs: u64, + swarms: &Arc, + stats_repository: &Arc, + inactivity_cutoff: DurationSinceUnixEpoch, +) { + let start_time = Utc::now().time(); + + tracing::debug!( + "Updating peers and torrents activity metrics (executed every {} secs) ...", + interval_in_secs + ); + + let activity_metadata = swarms.get_activity_metadata(inactivity_cutoff).await; + + activity_metadata.log(); + + update_inactive_peers_total(stats_repository, activity_metadata.inactive_peers_total).await; + update_inactive_torrents_total(stats_repository, activity_metadata.inactive_torrents_total).await; + + tracing::debug!( + "Peers and torrents activity metrics updated in {} ms", + (Utc::now().time() - start_time).num_milliseconds() + ); +} + +async fn update_inactive_peers_total(stats_repository: &Arc, inactive_peers_total: usize) { + #[allow(clippy::cast_precision_loss)] + let inactive_peers_total = inactive_peers_total as f64; + + let _unused = stats_repository + .set_gauge( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_INACTIVE_TOTAL), + &LabelSet::default(), + inactive_peers_total, + CurrentClock::now(), + ) + .await; +} + +async fn update_inactive_torrents_total(stats_repository: &Arc, inactive_torrents_total: usize) { + #[allow(clippy::cast_precision_loss)] + let inactive_torrents_total = inactive_torrents_total as f64; + + let _unused = stats_repository + .set_gauge( + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_INACTIVE_TOTAL), + &LabelSet::default(), + inactive_torrents_total, + CurrentClock::now(), + ) + .await; +} diff --git a/packages/swarm-coordination-registry/src/statistics/event/handler.rs b/packages/swarm-coordination-registry/src/statistics/event/handler.rs new file mode 100644 index 000000000..1d3f8f32c --- /dev/null +++ b/packages/swarm-coordination-registry/src/statistics/event/handler.rs @@ -0,0 +1,655 @@ +use std::sync::Arc; + +use torrust_tracker_metrics::label::{LabelSet, LabelValue}; +use torrust_tracker_metrics::{label_name, metric_name}; +use torrust_tracker_primitives::peer::Peer; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::Event; +use crate::statistics::repository::Repository; +use crate::statistics::{ + SWARM_COORDINATION_REGISTRY_PEERS_ADDED_TOTAL, SWARM_COORDINATION_REGISTRY_PEERS_COMPLETED_STATE_REVERTED_TOTAL, + SWARM_COORDINATION_REGISTRY_PEERS_REMOVED_TOTAL, SWARM_COORDINATION_REGISTRY_PEERS_UPDATED_TOTAL, + SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL, SWARM_COORDINATION_REGISTRY_TORRENTS_ADDED_TOTAL, + SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL, SWARM_COORDINATION_REGISTRY_TORRENTS_REMOVED_TOTAL, + SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL, +}; + +#[allow(clippy::too_many_lines)] +pub async fn handle_event(event: Event, stats_repository: &Arc, now: DurationSinceUnixEpoch) { + match event { + // Torrent events + Event::TorrentAdded { info_hash, .. } => { + tracing::debug!(info_hash = ?info_hash, "Torrent added",); + + let _unused = stats_repository + .increment_gauge( + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL), + &LabelSet::default(), + now, + ) + .await; + + let _unused = stats_repository + .increment_counter( + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_ADDED_TOTAL), + &LabelSet::default(), + now, + ) + .await; + } + Event::TorrentRemoved { info_hash } => { + tracing::debug!(info_hash = ?info_hash, "Torrent removed",); + + let _unused = stats_repository + .decrement_gauge( + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL), + &LabelSet::default(), + now, + ) + .await; + + let _unused = stats_repository + .increment_counter( + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_REMOVED_TOTAL), + &LabelSet::default(), + now, + ) + .await; + } + + // Peer events + Event::PeerAdded { info_hash, peer } => { + tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer added", ); + + let label_set = label_set_for_peer(&peer); + + let _unused = stats_repository + .increment_gauge( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL), + &label_set, + now, + ) + .await; + + let _unused = stats_repository + .increment_counter(&metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_ADDED_TOTAL), &label_set, now) + .await; + } + Event::PeerRemoved { info_hash, peer } => { + tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer removed", ); + + let label_set = label_set_for_peer(&peer); + + let _unused = stats_repository + .decrement_gauge( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL), + &label_set, + now, + ) + .await; + + let _unused = stats_repository + .increment_counter( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_REMOVED_TOTAL), + &label_set, + now, + ) + .await; + } + Event::PeerUpdated { + info_hash, + old_peer, + new_peer, + } => { + tracing::debug!(info_hash = ?info_hash, old_peer = ?old_peer, new_peer = ?new_peer, "Peer updated", ); + + // If the peer's role has changed, we need to adjust the number of + // connections + if old_peer.role() != new_peer.role() { + let _unused = stats_repository + .increment_gauge( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL), + &label_set_for_peer(&new_peer), + now, + ) + .await; + + let _unused = stats_repository + .decrement_gauge( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL), + &label_set_for_peer(&old_peer), + now, + ) + .await; + } + + // If the peer reverted from a completed state to any other state, + // we need to increment the counter for reverted completed. + if old_peer.is_completed() && !new_peer.is_completed() { + let _unused = stats_repository + .increment_counter( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_COMPLETED_STATE_REVERTED_TOTAL), + &LabelSet::default(), + now, + ) + .await; + } + + // Regardless of the role change, we still need to increment the + // counter for updated peers. + let label_set = label_set_for_peer(&new_peer); + + let _unused = stats_repository + .increment_counter( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_UPDATED_TOTAL), + &label_set, + now, + ) + .await; + } + Event::PeerDownloadCompleted { info_hash, peer } => { + tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer download completed", ); + + let _unused: Result<(), torrust_tracker_metrics::metric_collection::Error> = stats_repository + .increment_counter( + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL), + &label_set_for_peer(&peer), + now, + ) + .await; + } + } +} + +/// Returns the label set to be included in the metrics for the given peer. +pub(crate) fn label_set_for_peer(peer: &Peer) -> LabelSet { + if peer.is_seeder() { + (label_name!("peer_role"), LabelValue::new("seeder")).into() + } else { + (label_name!("peer_role"), LabelValue::new("leecher")).into() + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use aquatic_udp_protocol::NumberOfBytes; + use torrust_tracker_metrics::label::LabelSet; + use torrust_tracker_metrics::metric::MetricName; + use torrust_tracker_primitives::peer::{Peer, PeerRole}; + + use crate::statistics::repository::Repository; + use crate::tests::{leecher, seeder}; + + fn make_peer(role: PeerRole) -> Peer { + match role { + PeerRole::Seeder => seeder(), + PeerRole::Leecher => leecher(), + } + } + + // It returns a peer with the opposite role of the given peer. + fn make_opposite_role_peer(peer: &Peer) -> Peer { + let mut opposite_role_peer = *peer; + + match peer.role() { + PeerRole::Seeder => { + opposite_role_peer.left = NumberOfBytes::new(1); + } + PeerRole::Leecher => { + opposite_role_peer.left = NumberOfBytes::new(0); + } + } + + opposite_role_peer + } + + pub async fn expect_counter_metric_to_be( + stats_repository: &Arc, + metric_name: &MetricName, + label_set: &LabelSet, + expected_value: u64, + ) { + let value = get_counter_metric(stats_repository, metric_name, label_set).await; + assert_eq!(value.to_string(), expected_value.to_string()); + } + + async fn get_counter_metric(stats_repository: &Arc, metric_name: &MetricName, label_set: &LabelSet) -> u64 { + stats_repository + .get_metrics() + .await + .metric_collection + .get_counter_value(metric_name, label_set) + .unwrap_or_else(|| panic!("Failed to get counter value for metric name '{metric_name}' and label set '{label_set}'")) + .value() + } + + async fn expect_gauge_metric_to_be( + stats_repository: &Arc, + metric_name: &MetricName, + label_set: &LabelSet, + expected_value: f64, + ) { + let value = get_gauge_metric(stats_repository, metric_name, label_set).await; + assert_eq!(value.to_string(), expected_value.to_string()); + } + + async fn get_gauge_metric(stats_repository: &Arc, metric_name: &MetricName, label_set: &LabelSet) -> f64 { + stats_repository + .get_metrics() + .await + .metric_collection + .get_gauge_value(metric_name, label_set) + .unwrap_or_else(|| panic!("Failed to get gauge value for metric name '{metric_name}' and label set '{label_set}'")) + .value() + } + + mod for_torrent_metrics { + + use std::sync::Arc; + + use torrust_tracker_clock::clock::stopped::Stopped; + use torrust_tracker_clock::clock::{self, Time}; + use torrust_tracker_metrics::label::LabelSet; + use torrust_tracker_metrics::metric_name; + + use crate::event::Event; + use crate::statistics::event::handler::handle_event; + use crate::statistics::event::handler::tests::{expect_counter_metric_to_be, expect_gauge_metric_to_be}; + use crate::statistics::repository::Repository; + use crate::statistics::{ + SWARM_COORDINATION_REGISTRY_TORRENTS_ADDED_TOTAL, SWARM_COORDINATION_REGISTRY_TORRENTS_REMOVED_TOTAL, + SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL, + }; + use crate::tests::{sample_info_hash, sample_peer}; + use crate::CurrentClock; + + #[tokio::test] + async fn it_should_increment_the_number_of_torrents_when_a_torrent_added_event_is_received() { + clock::Stopped::local_set_to_unix_epoch(); + + let stats_repository = Arc::new(Repository::new()); + + handle_event( + Event::TorrentAdded { + info_hash: sample_info_hash(), + announcement: sample_peer(), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_gauge_metric_to_be( + &stats_repository, + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL), + &LabelSet::default(), + 1.0, + ) + .await; + } + + #[tokio::test] + async fn it_should_decrement_the_number_of_torrents_when_a_torrent_removed_event_is_received() { + clock::Stopped::local_set_to_unix_epoch(); + + let stats_repository = Arc::new(Repository::new()); + let metric_name = metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL); + let label_set = LabelSet::default(); + + // Increment the gauge first to simulate a torrent being added. + stats_repository + .increment_gauge(&metric_name, &label_set, CurrentClock::now()) + .await + .unwrap(); + + handle_event( + Event::TorrentRemoved { + info_hash: sample_info_hash(), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_gauge_metric_to_be(&stats_repository, &metric_name, &label_set, 0.0).await; + } + + #[tokio::test] + async fn it_should_increment_the_number_of_torrents_added_when_a_torrent_added_event_is_received() { + clock::Stopped::local_set_to_unix_epoch(); + + let stats_repository = Arc::new(Repository::new()); + + handle_event( + Event::TorrentAdded { + info_hash: sample_info_hash(), + announcement: sample_peer(), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_counter_metric_to_be( + &stats_repository, + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_ADDED_TOTAL), + &LabelSet::default(), + 1, + ) + .await; + } + + #[tokio::test] + async fn it_should_increment_the_number_of_torrents_removed_when_a_torrent_removed_event_is_received() { + clock::Stopped::local_set_to_unix_epoch(); + + let stats_repository = Arc::new(Repository::new()); + + handle_event( + Event::TorrentRemoved { + info_hash: sample_info_hash(), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_counter_metric_to_be( + &stats_repository, + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_REMOVED_TOTAL), + &LabelSet::default(), + 1, + ) + .await; + } + } + + mod for_peer_metrics { + use std::sync::Arc; + + use torrust_tracker_clock::clock::stopped::Stopped; + use torrust_tracker_clock::clock::{self, Time}; + use torrust_tracker_metrics::metric_name; + + use crate::event::Event; + use crate::statistics::event::handler::tests::expect_counter_metric_to_be; + use crate::statistics::event::handler::{handle_event, label_set_for_peer}; + use crate::statistics::repository::Repository; + use crate::statistics::{ + SWARM_COORDINATION_REGISTRY_PEERS_ADDED_TOTAL, SWARM_COORDINATION_REGISTRY_PEERS_REMOVED_TOTAL, + SWARM_COORDINATION_REGISTRY_PEERS_UPDATED_TOTAL, + }; + use crate::tests::{sample_info_hash, sample_peer}; + use crate::CurrentClock; + + mod peer_connections_total { + + use std::sync::Arc; + + use rstest::rstest; + use torrust_tracker_clock::clock::stopped::Stopped; + use torrust_tracker_clock::clock::{self, Time}; + use torrust_tracker_metrics::label::LabelValue; + use torrust_tracker_metrics::{label_name, metric_name}; + use torrust_tracker_primitives::peer::PeerRole; + + use crate::event::Event; + use crate::statistics::event::handler::handle_event; + use crate::statistics::event::handler::tests::{ + expect_gauge_metric_to_be, get_gauge_metric, make_opposite_role_peer, make_peer, + }; + use crate::statistics::repository::Repository; + use crate::statistics::SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL; + use crate::tests::sample_info_hash; + use crate::CurrentClock; + + #[rstest] + #[case("seeder")] + #[case("leecher")] + #[tokio::test] + async fn it_should_increment_the_number_of_peer_connections_when_a_peer_added_event_is_received( + #[case] role: PeerRole, + ) { + clock::Stopped::local_set_to_unix_epoch(); + + let peer = make_peer(role); + + let stats_repository = Arc::new(Repository::new()); + let metric_name = metric_name!(SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL); + let label_set = (label_name!("peer_role"), LabelValue::new(&role.to_string())).into(); + + handle_event( + Event::PeerAdded { + info_hash: sample_info_hash(), + peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_gauge_metric_to_be(&stats_repository, &metric_name, &label_set, 1.0).await; + } + + #[rstest] + #[case("seeder")] + #[case("leecher")] + #[tokio::test] + async fn it_should_decrement_the_number_of_peer_connections_when_a_peer_removed_event_is_received( + #[case] role: PeerRole, + ) { + clock::Stopped::local_set_to_unix_epoch(); + + let peer = make_peer(role); + + let stats_repository = Arc::new(Repository::new()); + + let metric_name = metric_name!(SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL); + let label_set = (label_name!("peer_role"), LabelValue::new(&role.to_string())).into(); + + // Increment the gauge first to simulate a peer being added. + stats_repository + .increment_gauge(&metric_name, &label_set, CurrentClock::now()) + .await + .unwrap(); + + handle_event( + Event::PeerRemoved { + info_hash: sample_info_hash(), + peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_gauge_metric_to_be(&stats_repository, &metric_name, &label_set, 0.0).await; + } + + #[rstest] + #[case("seeder")] + #[case("leecher")] + #[tokio::test] + async fn it_should_adjust_the_number_of_seeders_and_leechers_when_a_peer_updated_event_is_received_and_the_peer_changed_its_role( + #[case] old_role: PeerRole, + ) { + clock::Stopped::local_set_to_unix_epoch(); + + let stats_repository = Arc::new(Repository::new()); + + let old_peer = make_peer(old_role); + let new_peer = make_opposite_role_peer(&old_peer); + + let metric_name = metric_name!(SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL); + let old_role_label_set = (label_name!("peer_role"), LabelValue::new(&old_peer.role().to_string())).into(); + let new_role_label_set = (label_name!("peer_role"), LabelValue::new(&new_peer.role().to_string())).into(); + + // Increment the gauge first by simulating a peer was added. + handle_event( + Event::PeerAdded { + info_hash: sample_info_hash(), + peer: old_peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let old_role_total = get_gauge_metric(&stats_repository, &metric_name, &old_role_label_set).await; + let new_role_total = 0.0; + + // The peer's role has changed, so we need to increment the new + // role and decrement the old one. + handle_event( + Event::PeerUpdated { + info_hash: sample_info_hash(), + old_peer, + new_peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + // The peer's role has changed, so the new role has incremented. + expect_gauge_metric_to_be(&stats_repository, &metric_name, &new_role_label_set, new_role_total + 1.0).await; + + // And the old role has decremented. + expect_gauge_metric_to_be(&stats_repository, &metric_name, &old_role_label_set, old_role_total - 1.0).await; + } + } + + #[tokio::test] + async fn it_should_increment_the_number_of_peers_added_when_a_peer_added_event_is_received() { + clock::Stopped::local_set_to_unix_epoch(); + + let stats_repository = Arc::new(Repository::new()); + + let peer = sample_peer(); + + handle_event( + Event::PeerAdded { + info_hash: sample_info_hash(), + peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_counter_metric_to_be( + &stats_repository, + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_ADDED_TOTAL), + &label_set_for_peer(&peer), + 1, + ) + .await; + } + + #[tokio::test] + async fn it_should_increment_the_number_of_peers_removed_when_a_peer_removed_event_is_received() { + clock::Stopped::local_set_to_unix_epoch(); + + let stats_repository = Arc::new(Repository::new()); + + let peer = sample_peer(); + + handle_event( + Event::PeerRemoved { + info_hash: sample_info_hash(), + peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_counter_metric_to_be( + &stats_repository, + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_REMOVED_TOTAL), + &label_set_for_peer(&peer), + 1, + ) + .await; + } + + #[tokio::test] + async fn it_should_increment_the_number_of_peers_updated_when_a_peer_updated_event_is_received() { + clock::Stopped::local_set_to_unix_epoch(); + + let stats_repository = Arc::new(Repository::new()); + + let new_peer = sample_peer(); + + handle_event( + Event::PeerUpdated { + info_hash: sample_info_hash(), + old_peer: sample_peer(), + new_peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_counter_metric_to_be( + &stats_repository, + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_UPDATED_TOTAL), + &label_set_for_peer(&new_peer), + 1, + ) + .await; + } + + mod torrent_downloads_total { + + use std::sync::Arc; + + use rstest::rstest; + use torrust_tracker_clock::clock::stopped::Stopped; + use torrust_tracker_clock::clock::{self, Time}; + use torrust_tracker_metrics::label::LabelValue; + use torrust_tracker_metrics::{label_name, metric_name}; + use torrust_tracker_primitives::peer::PeerRole; + + use crate::event::Event; + use crate::statistics::event::handler::handle_event; + use crate::statistics::event::handler::tests::{expect_counter_metric_to_be, make_peer}; + use crate::statistics::repository::Repository; + use crate::statistics::SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL; + use crate::tests::sample_info_hash; + use crate::CurrentClock; + + #[rstest] + #[case("seeder")] + #[case("leecher")] + #[tokio::test] + async fn it_should_increment_the_number_of_downloads_when_a_peer_downloaded_event_is_received( + #[case] role: PeerRole, + ) { + clock::Stopped::local_set_to_unix_epoch(); + + let peer = make_peer(role); + + let stats_repository = Arc::new(Repository::new()); + let metric_name = metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL); + let label_set = (label_name!("peer_role"), LabelValue::new(&role.to_string())).into(); + + handle_event( + Event::PeerDownloadCompleted { + info_hash: sample_info_hash(), + peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_counter_metric_to_be(&stats_repository, &metric_name, &label_set, 1).await; + } + } + } +} diff --git a/packages/swarm-coordination-registry/src/statistics/event/listener.rs b/packages/swarm-coordination-registry/src/statistics/event/listener.rs new file mode 100644 index 000000000..b578d1284 --- /dev/null +++ b/packages/swarm-coordination-registry/src/statistics/event/listener.rs @@ -0,0 +1,58 @@ +use std::sync::Arc; + +use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_events::receiver::RecvError; + +use super::handler::handle_event; +use crate::event::receiver::Receiver; +use crate::statistics::repository::Repository; +use crate::{CurrentClock, SWARM_COORDINATION_REGISTRY_LOG_TARGET}; + +#[must_use] +pub fn run_event_listener( + receiver: Receiver, + cancellation_token: CancellationToken, + repository: &Arc, +) -> JoinHandle<()> { + let stats_repository = repository.clone(); + + tracing::info!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Starting swarm coordination registry event listener"); + + tokio::spawn(async move { + dispatch_events(receiver, cancellation_token, stats_repository).await; + + tracing::info!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Swarm coordination registry listener finished"); + }) +} + +async fn dispatch_events(mut receiver: Receiver, cancellation_token: CancellationToken, stats_repository: Arc) { + loop { + tokio::select! { + biased; + + () = cancellation_token.cancelled() => { + tracing::info!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Received cancellation request, shutting down swarm coordination registry event listener."); + break; + } + + result = receiver.recv() => { + match result { + Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, + Err(e) => { + match e { + RecvError::Closed => { + tracing::info!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Swarm coordination registry event receiver closed."); + break; + } + RecvError::Lagged(n) => { + tracing::warn!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Swarm coordination registry event receiver lagged by {} events.", n); + } + } + } + } + } + } + } +} diff --git a/packages/swarm-coordination-registry/src/statistics/event/mod.rs b/packages/swarm-coordination-registry/src/statistics/event/mod.rs new file mode 100644 index 000000000..dae683398 --- /dev/null +++ b/packages/swarm-coordination-registry/src/statistics/event/mod.rs @@ -0,0 +1,2 @@ +pub mod handler; +pub mod listener; diff --git a/packages/swarm-coordination-registry/src/statistics/metrics.rs b/packages/swarm-coordination-registry/src/statistics/metrics.rs new file mode 100644 index 000000000..d62a1ba6e --- /dev/null +++ b/packages/swarm-coordination-registry/src/statistics/metrics.rs @@ -0,0 +1,63 @@ +use serde::Serialize; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::{Error, MetricCollection}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +/// Metrics collected by the torrent repository. +#[derive(Debug, Clone, PartialEq, Default, Serialize)] +pub struct Metrics { + /// A collection of metrics. + pub metric_collection: MetricCollection, +} + +impl Metrics { + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn increment_counter( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.increment_counter(metric_name, labels, now) + } + + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn set_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.set_gauge(metric_name, labels, value, now) + } + + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn increment_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.increment_gauge(metric_name, labels, now) + } + + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn decrement_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.decrement_gauge(metric_name, labels, now) + } +} diff --git a/packages/swarm-coordination-registry/src/statistics/mod.rs b/packages/swarm-coordination-registry/src/statistics/mod.rs new file mode 100644 index 000000000..a4bf4c018 --- /dev/null +++ b/packages/swarm-coordination-registry/src/statistics/mod.rs @@ -0,0 +1,117 @@ +pub mod activity_metrics_updater; +pub mod event; +pub mod metrics; +pub mod repository; + +use metrics::Metrics; +use torrust_tracker_metrics::metric::description::MetricDescription; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_metrics::unit::Unit; + +// Torrent metrics + +const SWARM_COORDINATION_REGISTRY_TORRENTS_ADDED_TOTAL: &str = "swarm_coordination_registry_torrents_added_total"; +const SWARM_COORDINATION_REGISTRY_TORRENTS_REMOVED_TOTAL: &str = "swarm_coordination_registry_torrents_removed_total"; + +const SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL: &str = "swarm_coordination_registry_torrents_total"; +const SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL: &str = "swarm_coordination_registry_torrents_downloads_total"; +const SWARM_COORDINATION_REGISTRY_TORRENTS_INACTIVE_TOTAL: &str = "swarm_coordination_registry_torrents_inactive_total"; + +// Peers metrics + +const SWARM_COORDINATION_REGISTRY_PEERS_ADDED_TOTAL: &str = "swarm_coordination_registry_peers_added_total"; +const SWARM_COORDINATION_REGISTRY_PEERS_REMOVED_TOTAL: &str = "swarm_coordination_registry_peers_removed_total"; +const SWARM_COORDINATION_REGISTRY_PEERS_UPDATED_TOTAL: &str = "swarm_coordination_registry_peers_updated_total"; + +const SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL: &str = "swarm_coordination_registry_peer_connections_total"; +const SWARM_COORDINATION_REGISTRY_UNIQUE_PEERS_TOTAL: &str = "swarm_coordination_registry_unique_peers_total"; // todo: not implemented yet +const SWARM_COORDINATION_REGISTRY_PEERS_INACTIVE_TOTAL: &str = "swarm_coordination_registry_peers_inactive_total"; +const SWARM_COORDINATION_REGISTRY_PEERS_COMPLETED_STATE_REVERTED_TOTAL: &str = + "swarm_coordination_registry_peers_completed_state_reverted_total"; + +#[must_use] +pub fn describe_metrics() -> Metrics { + let mut metrics = Metrics::default(); + + // Torrent metrics + + metrics.metric_collection.describe_counter( + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_ADDED_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("The total number of torrents added.")), + ); + + metrics.metric_collection.describe_counter( + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_REMOVED_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("The total number of torrents removed.")), + ); + + metrics.metric_collection.describe_gauge( + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("The total number of torrents.")), + ); + + metrics.metric_collection.describe_counter( + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("The total number of torrent downloads.")), + ); + + metrics.metric_collection.describe_gauge( + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_INACTIVE_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("The total number of inactive torrents.")), + ); + + // Peers metrics + + metrics.metric_collection.describe_counter( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_ADDED_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("The total number of peers added.")), + ); + + metrics.metric_collection.describe_counter( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_REMOVED_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("The total number of peers removed.")), + ); + + metrics.metric_collection.describe_counter( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_UPDATED_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("The total number of peers updated.")), + ); + + metrics.metric_collection.describe_gauge( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new( + "The total number of peer connections (one connection per torrent).", + )), + ); + + metrics.metric_collection.describe_gauge( + &metric_name!(SWARM_COORDINATION_REGISTRY_UNIQUE_PEERS_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("The total number of unique peers.")), + ); + + metrics.metric_collection.describe_gauge( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_INACTIVE_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("The total number of inactive peers.")), + ); + + metrics.metric_collection.describe_counter( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_COMPLETED_STATE_REVERTED_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new( + "The total number of peers whose completed state was reverted.", + )), + ); + + metrics +} diff --git a/packages/swarm-coordination-registry/src/statistics/repository.rs b/packages/swarm-coordination-registry/src/statistics/repository.rs new file mode 100644 index 000000000..fe1292d00 --- /dev/null +++ b/packages/swarm-coordination-registry/src/statistics/repository.rs @@ -0,0 +1,132 @@ +use std::sync::Arc; + +use tokio::sync::{RwLock, RwLockReadGuard}; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::Error; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::describe_metrics; +use super::metrics::Metrics; + +/// A repository for the torrent repository metrics. +#[derive(Clone)] +pub struct Repository { + pub stats: Arc>, +} + +impl Default for Repository { + fn default() -> Self { + Self::new() + } +} + +impl Repository { + #[must_use] + pub fn new() -> Self { + let stats = Arc::new(RwLock::new(describe_metrics())); + + Self { stats } + } + + pub async fn get_metrics(&self) -> RwLockReadGuard<'_, Metrics> { + self.stats.read().await + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increment the counter. + pub async fn increment_counter( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.increment_counter(metric_name, labels, now); + + drop(stats_lock); + + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to increment the counter: {}", err), + } + + result + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// set the gauge. + pub async fn set_gauge( + &self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.set_gauge(metric_name, labels, value, now); + + drop(stats_lock); + + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to set the gauge: {}", err), + } + + result + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increment the gauge. + pub async fn increment_gauge( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.increment_gauge(metric_name, labels, now); + + drop(stats_lock); + + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to increment the gauge: {}", err), + } + + result + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// decrement the gauge. + pub async fn decrement_gauge( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.decrement_gauge(metric_name, labels, now); + + drop(stats_lock); + + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to decrement the gauge: {}", err), + } + + result + } +} diff --git a/packages/swarm-coordination-registry/src/swarm/coordinator.rs b/packages/swarm-coordination-registry/src/swarm/coordinator.rs new file mode 100644 index 000000000..433ab9d32 --- /dev/null +++ b/packages/swarm-coordination-registry/src/swarm/coordinator.rs @@ -0,0 +1,1040 @@ +//! A swarm is a collection of peers that are all trying to download the same +//! torrent. +use std::collections::BTreeMap; +use std::net::SocketAddr; +use std::sync::Arc; + +use aquatic_udp_protocol::AnnounceEvent; +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::peer::{self, Peer, PeerAnnouncement}; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::sender::Sender; +use crate::event::Event; + +#[derive(Clone)] +pub struct Coordinator { + info_hash: InfoHash, + peers: BTreeMap>, + metadata: SwarmMetadata, + event_sender: Sender, +} + +impl Coordinator { + #[must_use] + pub fn new(info_hash: &InfoHash, downloaded: u32, event_sender: Sender) -> Self { + Self { + info_hash: *info_hash, + peers: BTreeMap::new(), + metadata: SwarmMetadata::new(downloaded, 0, 0), + event_sender, + } + } + + pub async fn handle_announcement(&mut self, incoming_announce: &PeerAnnouncement) { + let _previous_peer = match peer::ReadInfo::get_event(incoming_announce) { + AnnounceEvent::Started | AnnounceEvent::None | AnnounceEvent::Completed => { + self.upsert_peer(Arc::new(*incoming_announce)).await + } + AnnounceEvent::Stopped => self.remove_peer(&incoming_announce.peer_addr).await, + }; + } + + pub async fn remove_inactive(&mut self, current_cutoff: DurationSinceUnixEpoch) -> usize { + let peers_to_remove = self.inactive_peers(current_cutoff); + + for peer_addr in &peers_to_remove { + self.remove_peer(peer_addr).await; + } + + peers_to_remove.len() + } + + #[must_use] + pub fn get(&self, peer_addr: &SocketAddr) -> Option<&Arc> { + self.peers.get(peer_addr) + } + + #[must_use] + pub fn peers(&self, limit: Option) -> Vec> { + match limit { + Some(limit) => self.peers.values().take(limit).cloned().collect(), + None => self.peers.values().cloned().collect(), + } + } + + #[must_use] + pub fn peers_excluding(&self, peer_addr: &SocketAddr, limit: Option) -> Vec> { + match limit { + Some(limit) => self + .peers + .values() + // Take peers which are not the client peer + .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *peer_addr) + // Limit the number of peers on the result + .take(limit) + .cloned() + .collect(), + None => self + .peers + .values() + // Take peers which are not the client peer + .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *peer_addr) + .cloned() + .collect(), + } + } + + #[must_use] + pub fn metadata(&self) -> SwarmMetadata { + self.metadata + } + + /// Returns the number of seeders and leechers in the swarm. + /// + /// # Panics + /// + /// This function will panic if the `complete` or `incomplete` fields in the + /// `metadata` field cannot be converted to `usize`. + #[must_use] + pub fn seeders_and_leechers(&self) -> (usize, usize) { + let seeders = self + .metadata + .complete + .try_into() + .expect("Failed to convert 'complete' (seeders) count to usize"); + let leechers = self + .metadata + .incomplete + .try_into() + .expect("Failed to convert 'incomplete' (leechers) count to usize"); + + (seeders, leechers) + } + + #[must_use] + pub fn count_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> usize { + self.peers + .iter() + .filter(|(_, peer)| peer::ReadInfo::get_updated(&**peer) <= current_cutoff) + .count() + } + + #[must_use] + pub fn get_activity_metadata(&self, current_cutoff: DurationSinceUnixEpoch) -> ActivityMetadata { + let inactive_peers_total = self.count_inactive_peers(current_cutoff); + + let active_peers_total = self.len() - inactive_peers_total; + + let is_active = active_peers_total > 0; + + ActivityMetadata::new(is_active, active_peers_total, inactive_peers_total) + } + + #[must_use] + pub fn len(&self) -> usize { + self.peers.len() + } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.peers.is_empty() + } + + #[must_use] + pub fn is_peerless(&self) -> bool { + self.is_empty() + } + + /// Returns true if the swarm meets the retention policy, meaning that + /// it should be kept in the list of swarms. + #[must_use] + pub fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + !self.should_be_removed(policy) + } + + async fn upsert_peer(&mut self, incoming_announce: Arc) -> Option> { + let announcement = incoming_announce.clone(); + + if let Some(previous_announce) = self.peers.insert(incoming_announce.peer_addr, incoming_announce) { + let downloads_increased = self.update_metadata_on_update(&previous_announce, &announcement); + + self.trigger_peer_updated_event(&previous_announce, &announcement).await; + + if downloads_increased { + self.trigger_peer_download_completed_event(&announcement).await; + } + + Some(previous_announce) + } else { + self.update_metadata_on_insert(&announcement); + + self.trigger_peer_added_event(&announcement).await; + + None + } + } + + async fn remove_peer(&mut self, peer_addr: &SocketAddr) -> Option> { + if let Some(old_peer) = self.peers.remove(peer_addr) { + self.update_metadata_on_removal(&old_peer); + + self.trigger_peer_removed_event(&old_peer).await; + + Some(old_peer) + } else { + None + } + } + + #[must_use] + fn inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> Vec { + self.peers + .iter() + .filter(|(_, peer)| peer::ReadInfo::get_updated(&**peer) <= current_cutoff) + .map(|(addr, _)| *addr) + .collect() + } + + /// Returns true if the swarm should be removed according to the retention + /// policy. + fn should_be_removed(&self, policy: &TrackerPolicy) -> bool { + policy.remove_peerless_torrents && self.is_empty() + } + + fn update_metadata_on_insert(&mut self, added_peer: &Arc) { + if added_peer.is_seeder() { + self.metadata.complete += 1; + } else { + self.metadata.incomplete += 1; + } + } + + fn update_metadata_on_removal(&mut self, removed_peer: &Arc) { + if removed_peer.is_seeder() { + self.metadata.complete -= 1; + } else { + self.metadata.incomplete -= 1; + } + } + + fn update_metadata_on_update( + &mut self, + previous_announce: &Arc, + new_announce: &Arc, + ) -> bool { + let mut downloads_increased = false; + + if previous_announce.role() != new_announce.role() { + if new_announce.is_seeder() { + self.metadata.complete += 1; + self.metadata.incomplete -= 1; + } else { + self.metadata.complete -= 1; + self.metadata.incomplete += 1; + } + } + + if new_announce.is_completed() && !previous_announce.is_completed() { + self.metadata.downloaded += 1; + downloads_increased = true; + } + + downloads_increased + } + + async fn trigger_peer_added_event(&self, announcement: &Arc) { + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender + .send(Event::PeerAdded { + info_hash: self.info_hash, + peer: *announcement.clone(), + }) + .await; + } + } + + async fn trigger_peer_removed_event(&self, old_peer: &Arc) { + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender + .send(Event::PeerRemoved { + info_hash: self.info_hash, + peer: *old_peer.clone(), + }) + .await; + } + } + + async fn trigger_peer_updated_event(&self, old_announce: &Arc, new_announce: &Arc) { + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender + .send(Event::PeerUpdated { + info_hash: self.info_hash, + old_peer: *old_announce.clone(), + new_peer: *new_announce.clone(), + }) + .await; + } + } + + async fn trigger_peer_download_completed_event(&self, new_announce: &Arc) { + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender + .send(Event::PeerDownloadCompleted { + info_hash: self.info_hash, + peer: *new_announce.clone(), + }) + .await; + } + } +} + +#[derive(Clone)] +pub struct ActivityMetadata { + /// Indicates if the swarm is active. It's inactive if there are no active + /// peers. + pub is_active: bool, + + /// The number of active peers in the swarm. + pub active_peers_total: usize, + + /// The number of inactive peers in the swarm. + pub inactive_peers_total: usize, +} + +impl ActivityMetadata { + #[must_use] + pub fn new(is_active: bool, active_peers_total: usize, inactive_peers_total: usize) -> Self { + Self { + is_active, + active_peers_total, + inactive_peers_total, + } + } +} + +#[cfg(test)] +mod tests { + + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::PeerId; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::swarm::coordinator::Coordinator; + use crate::tests::sample_info_hash; + + #[test] + fn it_should_be_empty_when_no_peers_have_been_inserted() { + let swarm = Coordinator::new(&sample_info_hash(), 0, None); + + assert!(swarm.is_empty()); + } + + #[test] + fn it_should_have_zero_length_when_no_peers_have_been_inserted() { + let swarm = Coordinator::new(&sample_info_hash(), 0, None); + + assert_eq!(swarm.len(), 0); + } + + #[tokio::test] + async fn it_should_allow_inserting_a_new_peer() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let peer = PeerBuilder::default().build(); + + assert_eq!(swarm.upsert_peer(peer.into()).await, None); + } + + #[tokio::test] + async fn it_should_allow_updating_a_preexisting_peer() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let peer = PeerBuilder::default().build(); + + swarm.upsert_peer(peer.into()).await; + + assert_eq!(swarm.upsert_peer(peer.into()).await, Some(Arc::new(peer))); + } + + #[tokio::test] + async fn it_should_allow_getting_all_peers() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let peer = PeerBuilder::default().build(); + + swarm.upsert_peer(peer.into()).await; + + assert_eq!(swarm.peers(None), [Arc::new(peer)]); + } + + #[tokio::test] + async fn it_should_allow_getting_one_peer_by_id() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let peer = PeerBuilder::default().build(); + + swarm.upsert_peer(peer.into()).await; + + assert_eq!(swarm.get(&peer.peer_addr), Some(Arc::new(peer)).as_ref()); + } + + #[tokio::test] + async fn it_should_increase_the_number_of_peers_after_inserting_a_new_one() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let peer = PeerBuilder::default().build(); + + swarm.upsert_peer(peer.into()).await; + + assert_eq!(swarm.len(), 1); + } + + #[tokio::test] + async fn it_should_decrease_the_number_of_peers_after_removing_one() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let peer = PeerBuilder::default().build(); + + swarm.upsert_peer(peer.into()).await; + + swarm.remove_peer(&peer.peer_addr).await; + + assert!(swarm.is_empty()); + } + + #[tokio::test] + async fn it_should_allow_removing_an_existing_peer() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let peer = PeerBuilder::default().build(); + + swarm.upsert_peer(peer.into()).await; + + let old = swarm.remove_peer(&peer.peer_addr).await; + + assert_eq!(old, Some(Arc::new(peer))); + assert_eq!(swarm.get(&peer.peer_addr), None); + } + + #[tokio::test] + async fn it_should_allow_removing_a_non_existing_peer() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let peer = PeerBuilder::default().build(); + + assert_eq!(swarm.remove_peer(&peer.peer_addr).await, None); + } + + #[tokio::test] + async fn it_should_allow_getting_all_peers_excluding_peers_with_a_given_address() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let peer1 = PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000001")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 6969)) + .build(); + swarm.upsert_peer(peer1.into()).await; + + let peer2 = PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000002")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) + .build(); + swarm.upsert_peer(peer2.into()).await; + + assert_eq!(swarm.peers_excluding(&peer2.peer_addr, None), [Arc::new(peer1)]); + } + + #[tokio::test] + async fn it_should_count_inactive_peers() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let one_second = DurationSinceUnixEpoch::new(1, 0); + + // Insert the peer + let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); + let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); + swarm.upsert_peer(peer.into()).await; + + let inactive_peers_total = swarm.count_inactive_peers(last_update_time + one_second); + + assert_eq!(inactive_peers_total, 1); + } + + #[tokio::test] + async fn it_should_remove_inactive_peers() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let one_second = DurationSinceUnixEpoch::new(1, 0); + + // Insert the peer + let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); + let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); + swarm.upsert_peer(peer.into()).await; + + // Remove peers not updated since one second after inserting the peer + swarm.remove_inactive(last_update_time + one_second).await; + + assert_eq!(swarm.len(), 0); + } + + #[tokio::test] + async fn it_should_not_remove_active_peers() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let one_second = DurationSinceUnixEpoch::new(1, 0); + + // Insert the peer + let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); + let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); + swarm.upsert_peer(peer.into()).await; + + // Remove peers not updated since one second before inserting the peer. + swarm.remove_inactive(last_update_time.checked_sub(one_second).unwrap()).await; + + assert_eq!(swarm.len(), 1); + } + + mod for_retaining_policy { + + use torrust_tracker_configuration::TrackerPolicy; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + + use crate::tests::sample_info_hash; + use crate::Coordinator; + + fn empty_swarm() -> Coordinator { + Coordinator::new(&sample_info_hash(), 0, None) + } + + async fn not_empty_swarm() -> Coordinator { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + swarm.upsert_peer(PeerBuilder::default().build().into()).await; + swarm + } + + async fn not_empty_swarm_with_downloads() -> Coordinator { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let mut peer = PeerBuilder::leecher().build(); + + swarm.upsert_peer(peer.into()).await; + + peer.event = aquatic_udp_protocol::AnnounceEvent::Completed; + + swarm.upsert_peer(peer.into()).await; + + assert!(swarm.metadata().downloads() > 0); + + swarm + } + + fn remove_peerless_torrents_policy() -> TrackerPolicy { + TrackerPolicy { + remove_peerless_torrents: true, + ..Default::default() + } + } + + fn don_not_remove_peerless_torrents_policy() -> TrackerPolicy { + TrackerPolicy { + remove_peerless_torrents: false, + ..Default::default() + } + } + + mod when_removing_peerless_torrents_is_enabled { + + use torrust_tracker_configuration::TrackerPolicy; + + use crate::swarm::coordinator::tests::for_retaining_policy::{ + empty_swarm, not_empty_swarm, not_empty_swarm_with_downloads, remove_peerless_torrents_policy, + }; + + #[test] + fn it_should_be_removed_if_the_swarm_is_empty() { + assert!(empty_swarm().should_be_removed(&remove_peerless_torrents_policy())); + } + + #[tokio::test] + async fn it_should_not_be_removed_is_the_swarm_is_not_empty() { + assert!(!not_empty_swarm().await.should_be_removed(&remove_peerless_torrents_policy())); + } + + #[tokio::test] + async fn it_should_not_be_removed_even_if_the_swarm_is_empty_if_we_need_to_track_stats_for_downloads_and_there_has_been_downloads( + ) { + let policy = TrackerPolicy { + remove_peerless_torrents: true, + persistent_torrent_completed_stat: true, + ..Default::default() + }; + + assert!(!not_empty_swarm_with_downloads().await.should_be_removed(&policy)); + } + } + + mod when_removing_peerless_torrents_is_disabled { + + use crate::swarm::coordinator::tests::for_retaining_policy::{ + don_not_remove_peerless_torrents_policy, empty_swarm, not_empty_swarm, + }; + + #[test] + fn it_should_not_be_removed_even_if_the_swarm_is_empty() { + assert!(!empty_swarm().should_be_removed(&don_not_remove_peerless_torrents_policy())); + } + + #[tokio::test] + async fn it_should_not_be_removed_is_the_swarm_is_not_empty() { + assert!(!not_empty_swarm() + .await + .should_be_removed(&don_not_remove_peerless_torrents_policy())); + } + } + } + + #[tokio::test] + async fn it_should_allow_inserting_two_identical_peers_except_for_the_socket_address() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let peer1 = PeerBuilder::default() + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 6969)) + .build(); + swarm.upsert_peer(peer1.into()).await; + + let peer2 = PeerBuilder::default() + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) + .build(); + swarm.upsert_peer(peer2.into()).await; + + assert_eq!(swarm.len(), 2); + } + + #[tokio::test] + async fn it_should_not_allow_inserting_two_peers_with_different_peer_id_but_the_same_socket_address() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + // When that happens the peer ID will be changed in the swarm. + // In practice, it's like if the peer had changed its ID. + + let peer1 = PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000001")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 6969)) + .build(); + swarm.upsert_peer(peer1.into()).await; + + let peer2 = PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000002")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 6969)) + .build(); + swarm.upsert_peer(peer2.into()).await; + + assert_eq!(swarm.len(), 1); + } + + #[tokio::test] + async fn it_should_return_the_swarm_metadata() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let seeder = PeerBuilder::seeder().build(); + let leecher = PeerBuilder::leecher().build(); + + swarm.upsert_peer(seeder.into()).await; + swarm.upsert_peer(leecher.into()).await; + + assert_eq!( + swarm.metadata(), + SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 1, + } + ); + } + + #[tokio::test] + async fn it_should_return_the_number_of_seeders_in_the_list() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let seeder = PeerBuilder::seeder().build(); + let leecher = PeerBuilder::leecher().build(); + + swarm.upsert_peer(seeder.into()).await; + swarm.upsert_peer(leecher.into()).await; + + let (seeders, _leechers) = swarm.seeders_and_leechers(); + + assert_eq!(seeders, 1); + } + + #[tokio::test] + async fn it_should_return_the_number_of_leechers_in_the_list() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let seeder = PeerBuilder::seeder().build(); + let leecher = PeerBuilder::leecher().build(); + + swarm.upsert_peer(seeder.into()).await; + swarm.upsert_peer(leecher.into()).await; + + let (_seeders, leechers) = swarm.seeders_and_leechers(); + + assert_eq!(leechers, 1); + } + + #[tokio::test] + async fn it_should_be_a_peerless_swarm_when_it_does_not_contain_any_peers() { + let swarm = Coordinator::new(&sample_info_hash(), 0, None); + assert!(swarm.is_peerless()); + } + + mod updating_the_swarm_metadata { + + mod when_a_new_peer_is_added { + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + + use crate::swarm::coordinator::Coordinator; + use crate::tests::sample_info_hash; + + #[tokio::test] + async fn it_should_increase_the_number_of_leechers_if_the_new_peer_is_a_leecher_() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let leechers = swarm.metadata().leechers(); + + let leecher = PeerBuilder::leecher().build(); + + swarm.upsert_peer(leecher.into()).await; + + assert_eq!(swarm.metadata().leechers(), leechers + 1); + } + + #[tokio::test] + async fn it_should_increase_the_number_of_seeders_if_the_new_peer_is_a_seeder() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let seeders = swarm.metadata().seeders(); + + let seeder = PeerBuilder::seeder().build(); + + swarm.upsert_peer(seeder.into()).await; + + assert_eq!(swarm.metadata().seeders(), seeders + 1); + } + + #[tokio::test] + async fn it_should_not_increasing_the_number_of_downloads_if_the_new_peer_has_completed_downloading_as_it_was_not_previously_known( + ) { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let downloads = swarm.metadata().downloads(); + + let seeder = PeerBuilder::seeder().build(); + + swarm.upsert_peer(seeder.into()).await; + + assert_eq!(swarm.metadata().downloads(), downloads); + } + } + + mod when_a_peer_is_removed { + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + + use crate::swarm::coordinator::Coordinator; + use crate::tests::sample_info_hash; + + #[tokio::test] + async fn it_should_decrease_the_number_of_leechers_if_the_removed_peer_was_a_leecher() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let leecher = PeerBuilder::leecher().build(); + + swarm.upsert_peer(leecher.into()).await; + + let leechers = swarm.metadata().leechers(); + + swarm.remove_peer(&leecher.peer_addr).await; + + assert_eq!(swarm.metadata().leechers(), leechers - 1); + } + + #[tokio::test] + async fn it_should_decrease_the_number_of_seeders_if_the_removed_peer_was_a_seeder() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let seeder = PeerBuilder::seeder().build(); + + swarm.upsert_peer(seeder.into()).await; + + let seeders = swarm.metadata().seeders(); + + swarm.remove_peer(&seeder.peer_addr).await; + + assert_eq!(swarm.metadata().seeders(), seeders - 1); + } + } + + mod when_a_peer_is_removed_due_to_inactivity { + use std::time::Duration; + + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + + use crate::swarm::coordinator::Coordinator; + use crate::tests::sample_info_hash; + + #[tokio::test] + async fn it_should_decrease_the_number_of_leechers_when_a_removed_peer_is_a_leecher() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let leecher = PeerBuilder::leecher().build(); + + swarm.upsert_peer(leecher.into()).await; + + let leechers = swarm.metadata().leechers(); + + swarm.remove_inactive(leecher.updated + Duration::from_secs(1)).await; + + assert_eq!(swarm.metadata().leechers(), leechers - 1); + } + + #[tokio::test] + async fn it_should_decrease_the_number_of_seeders_when_the_removed_peer_is_a_seeder() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let seeder = PeerBuilder::seeder().build(); + + swarm.upsert_peer(seeder.into()).await; + + let seeders = swarm.metadata().seeders(); + + swarm.remove_inactive(seeder.updated + Duration::from_secs(1)).await; + + assert_eq!(swarm.metadata().seeders(), seeders - 1); + } + } + + mod for_changes_in_existing_peers { + use aquatic_udp_protocol::NumberOfBytes; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + + use crate::swarm::coordinator::Coordinator; + use crate::tests::sample_info_hash; + + #[tokio::test] + async fn it_should_increase_seeders_and_decreasing_leechers_when_the_peer_changes_from_leecher_to_seeder_() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let mut peer = PeerBuilder::leecher().build(); + + swarm.upsert_peer(peer.into()).await; + + let leechers = swarm.metadata().leechers(); + let seeders = swarm.metadata().seeders(); + + peer.left = NumberOfBytes::new(0); // Convert to seeder + + swarm.upsert_peer(peer.into()).await; + + assert_eq!(swarm.metadata().seeders(), seeders + 1); + assert_eq!(swarm.metadata().leechers(), leechers - 1); + } + + #[tokio::test] + async fn it_should_increase_leechers_and_decreasing_seeders_when_the_peer_changes_from_seeder_to_leecher() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let mut peer = PeerBuilder::seeder().build(); + + swarm.upsert_peer(peer.into()).await; + + let leechers = swarm.metadata().leechers(); + let seeders = swarm.metadata().seeders(); + + peer.left = NumberOfBytes::new(10); // Convert to leecher + + swarm.upsert_peer(peer.into()).await; + + assert_eq!(swarm.metadata().leechers(), leechers + 1); + assert_eq!(swarm.metadata().seeders(), seeders - 1); + } + + #[tokio::test] + async fn it_should_increase_the_number_of_downloads_when_the_peer_announces_completed_downloading() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let mut peer = PeerBuilder::leecher().build(); + + swarm.upsert_peer(peer.into()).await; + + let downloads = swarm.metadata().downloads(); + + peer.event = aquatic_udp_protocol::AnnounceEvent::Completed; + + swarm.upsert_peer(peer.into()).await; + + assert_eq!(swarm.metadata().downloads(), downloads + 1); + } + + #[tokio::test] + async fn it_should_not_increasing_the_number_of_downloads_when_the_peer_announces_completed_downloading_twice_() { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); + + let mut peer = PeerBuilder::leecher().build(); + + swarm.upsert_peer(peer.into()).await; + + let downloads = swarm.metadata().downloads(); + + peer.event = aquatic_udp_protocol::AnnounceEvent::Completed; + + swarm.upsert_peer(peer.into()).await; + + swarm.upsert_peer(peer.into()).await; + + assert_eq!(swarm.metadata().downloads(), downloads + 1); + } + } + } + + mod triggering_events { + + use std::sync::Arc; + + use aquatic_udp_protocol::AnnounceEvent::Started; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::event::sender::tests::{expect_event_sequence, MockEventSender}; + use crate::event::Event; + use crate::swarm::coordinator::Coordinator; + use crate::tests::sample_info_hash; + + #[tokio::test] + async fn it_should_trigger_an_event_when_a_new_peer_is_added() { + let info_hash = sample_info_hash(); + let peer = PeerBuilder::leecher().build(); + + let mut event_sender_mock = MockEventSender::new(); + + expect_event_sequence(&mut event_sender_mock, vec![Event::PeerAdded { info_hash, peer }]); + + let mut swarm = Coordinator::new(&sample_info_hash(), 0, Some(Arc::new(event_sender_mock))); + + swarm.upsert_peer(peer.into()).await; + } + + #[tokio::test] + async fn it_should_trigger_an_event_when_a_peer_is_directly_removed() { + let info_hash = sample_info_hash(); + let peer = PeerBuilder::leecher().build(); + + let mut event_sender_mock = MockEventSender::new(); + + expect_event_sequence( + &mut event_sender_mock, + vec![Event::PeerAdded { info_hash, peer }, Event::PeerRemoved { info_hash, peer }], + ); + + let mut swarm = Coordinator::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); + + // Insert the peer + swarm.upsert_peer(peer.into()).await; + + swarm.remove_peer(&peer.peer_addr).await; + } + + #[tokio::test] + async fn it_should_trigger_an_event_when_a_peer_is_removed_due_to_inactivity() { + let info_hash = sample_info_hash(); + let peer = PeerBuilder::leecher().build(); + + let mut event_sender_mock = MockEventSender::new(); + + expect_event_sequence( + &mut event_sender_mock, + vec![Event::PeerAdded { info_hash, peer }, Event::PeerRemoved { info_hash, peer }], + ); + + let mut swarm = Coordinator::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); + + // Insert the peer + swarm.upsert_peer(peer.into()).await; + + // Peers not updated after this time will be removed + let current_cutoff = peer.updated + DurationSinceUnixEpoch::from_secs(1); + + swarm.remove_inactive(current_cutoff).await; + } + + #[tokio::test] + async fn it_should_trigger_an_event_when_a_peer_is_updated() { + let info_hash = sample_info_hash(); + let peer = PeerBuilder::leecher().with_event(Started).build(); + + let mut event_sender_mock = MockEventSender::new(); + + expect_event_sequence( + &mut event_sender_mock, + vec![ + Event::PeerAdded { info_hash, peer }, + Event::PeerUpdated { + info_hash, + old_peer: peer, + new_peer: peer, + }, + ], + ); + + let mut swarm = Coordinator::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); + + // Insert the peer + swarm.upsert_peer(peer.into()).await; + + // Update the peer + swarm.upsert_peer(peer.into()).await; + } + + #[tokio::test] + async fn it_should_trigger_an_event_when_a_peer_completes_a_download() { + let info_hash = sample_info_hash(); + let started_peer = PeerBuilder::leecher().with_event(Started).build(); + let completed_peer = started_peer.into_completed(); + + let mut event_sender_mock = MockEventSender::new(); + + expect_event_sequence( + &mut event_sender_mock, + vec![ + Event::PeerAdded { + info_hash, + peer: started_peer, + }, + Event::PeerUpdated { + info_hash, + old_peer: started_peer, + new_peer: completed_peer, + }, + Event::PeerDownloadCompleted { + info_hash, + peer: completed_peer, + }, + ], + ); + + let mut swarm = Coordinator::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); + + // Insert the peer + swarm.upsert_peer(started_peer.into()).await; + + // Announce as completed + swarm.upsert_peer(completed_peer.into()).await; + } + } +} diff --git a/packages/swarm-coordination-registry/src/swarm/mod.rs b/packages/swarm-coordination-registry/src/swarm/mod.rs new file mode 100644 index 000000000..925ae4948 --- /dev/null +++ b/packages/swarm-coordination-registry/src/swarm/mod.rs @@ -0,0 +1,2 @@ +pub mod coordinator; +pub mod registry; diff --git a/packages/swarm-coordination-registry/src/swarm/registry.rs b/packages/swarm-coordination-registry/src/swarm/registry.rs new file mode 100644 index 000000000..c8e98f307 --- /dev/null +++ b/packages/swarm-coordination-registry/src/swarm/registry.rs @@ -0,0 +1,1447 @@ +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use crossbeam_skiplist::SkipMap; +use tokio::sync::Mutex; +use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; + +use crate::event::sender::Sender; +use crate::event::Event; +use crate::swarm::coordinator::Coordinator; +use crate::CoordinatorHandle; + +#[derive(Default)] +pub struct Registry { + swarms: SkipMap, + event_sender: Sender, +} + +impl Registry { + #[must_use] + pub fn new(event_sender: Sender) -> Self { + Self { + swarms: SkipMap::new(), + event_sender, + } + } + + /// Upsert a peer into the swarm of a torrent. + /// + /// Optionally, it can also preset the number of downloads of the torrent + /// only if it's the first time the torrent is being inserted. + /// + /// # Arguments + /// + /// * `info_hash` - The info hash of the torrent. + /// * `peer` - The peer to upsert. + /// * `opt_persistent_torrent` - The optional persisted data about a torrent + /// (number of downloads for the torrent). + /// + /// # Returns + /// + /// Returns `true` if the number of downloads was increased because the peer + /// completed the download. + /// + /// # Errors + /// + /// This function panics if the lock for the swarm handle cannot be acquired. + pub async fn handle_announcement( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + opt_persistent_torrent: Option, + ) -> Result<(), Error> { + let swarm_handle = match self.swarms.get(info_hash) { + None => { + let number_of_downloads = opt_persistent_torrent.unwrap_or_default(); + + let new_swarm_handle = + CoordinatorHandle::new(Coordinator::new(info_hash, number_of_downloads, self.event_sender.clone()).into()); + + let new_swarm_handle = self.swarms.get_or_insert(*info_hash, new_swarm_handle); + + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender + .send(Event::TorrentAdded { + info_hash: *info_hash, + announcement: *peer, + }) + .await; + } + + new_swarm_handle + } + Some(existing_swarm_handle) => existing_swarm_handle, + }; + + let mut swarm = swarm_handle.value().lock().await; + + swarm.handle_announcement(peer).await; + + Ok(()) + } + + /// Inserts a new swarm. Only used for testing purposes. + pub fn insert(&self, info_hash: &InfoHash, swarm: Coordinator) { + // code-review: swarms builder? or constructor from vec? + // It's only used for testing purposes. It allows to pre-define the + // initial state of the swarm without having to go through the upsert + // process. + + let swarm_handle = Arc::new(Mutex::new(swarm)); + + self.swarms.insert(*info_hash, swarm_handle); + + // IMPORTANT: Notice this does not send an event because is used only + // for testing purposes. The event is sent only when the torrent is + // announced for the first time. + } + + /// Removes a torrent entry from the repository. + /// + /// # Returns + /// + /// An `Option` containing the removed torrent entry if it existed. + #[must_use] + pub async fn remove(&self, key: &InfoHash) -> Option { + let swarm_handle = self.swarms.remove(key).map(|entry| entry.value().clone()); + + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender.send(Event::TorrentRemoved { info_hash: *key }).await; + } + + swarm_handle + } + + /// Retrieves a tracked torrent handle by its infohash. + /// + /// # Returns + /// + /// An `Option` containing the tracked torrent handle if found. + #[must_use] + pub fn get(&self, key: &InfoHash) -> Option { + let maybe_entry = self.swarms.get(key); + maybe_entry.map(|entry| entry.value().clone()) + } + + /// Retrieves a paginated list of tracked torrent handles. + /// + /// This method returns a vector of tuples, each containing an infohash and + /// its associated tracked torrent handle. The pagination parameters + /// (offset and limit) can be used to control the size of the result set. + /// + /// # Returns + /// + /// A vector of `(InfoHash, TorrentEntry)` tuples. + #[must_use] + pub fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, CoordinatorHandle)> { + match pagination { + Some(pagination) => self + .swarms + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + None => self + .swarms + .iter() + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + } + } + + /// Retrieves swarm metadata for a given torrent. + /// + /// # Returns + /// + /// A `SwarmMetadata` struct containing the aggregated torrent data if found. + /// + /// # Errors + /// + /// This function panics if the lock for the swarm handle cannot be acquired. + pub async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Result, Error> { + match self.swarms.get(info_hash) { + None => Ok(None), + Some(swarm_handle) => { + let swarm = swarm_handle.value().lock().await; + Ok(Some(swarm.metadata())) + } + } + } + + /// Retrieves swarm metadata for a given torrent. + /// + /// # Returns + /// + /// A `SwarmMetadata` struct containing the aggregated torrent data if it's + /// found or a zeroed metadata struct if not. + /// + /// # Errors + /// + /// This function returns an error if it fails to acquire the lock for the + /// swarm handle. + pub async fn get_swarm_metadata_or_default(&self, info_hash: &InfoHash) -> Result { + match self.get_swarm_metadata(info_hash).await { + Ok(Some(swarm_metadata)) => Ok(swarm_metadata), + Ok(None) => Ok(SwarmMetadata::zeroed()), + Err(err) => Err(err), + } + } + + /// Retrieves torrent peers for a given torrent and client, excluding the + /// requesting client. + /// + /// This method filters out the client making the request (based on its + /// network address) and returns up to a maximum number of peers, defined by + /// the greater of the provided limit or the global `TORRENT_PEERS_LIMIT`. + /// + /// # Returns + /// + /// A vector of peers (wrapped in `Arc`) representing the active peers for + /// the torrent, excluding the requesting client. + /// + /// # Errors + /// + /// This function returns an error if it fails to acquire the lock for the + /// swarm handle. + pub async fn get_peers_peers_excluding( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + limit: usize, + ) -> Result>, Error> { + match self.get(info_hash) { + None => Ok(vec![]), + Some(swarm_handle) => { + let swarm = swarm_handle.lock().await; + Ok(swarm.peers_excluding(&peer.peer_addr, Some(limit))) + } + } + } + + /// Retrieves the list of peers for a given torrent. + /// + /// This method returns up to `TORRENT_PEERS_LIMIT` peers for the torrent + /// specified by the info-hash. + /// + /// # Returns + /// + /// A vector of peers (wrapped in `Arc`) representing the active peers for + /// the torrent. + /// + /// # Errors + /// + /// This function returns an error if it fails to acquire the lock for the + /// swarm handle. + pub async fn get_swarm_peers(&self, info_hash: &InfoHash, limit: usize) -> Result>, Error> { + match self.get(info_hash) { + None => Ok(vec![]), + Some(swarm_handle) => { + let swarm = swarm_handle.lock().await; + Ok(swarm.peers(Some(limit))) + } + } + } + + pub async fn get_activity_metadata(&self, current_cutoff: DurationSinceUnixEpoch) -> AggregateActivityMetadata { + let mut active_peers_total = 0; + let mut inactive_peers_total = 0; + let mut active_torrents_total = 0; + + for swarm_handle in &self.swarms { + let swarm = swarm_handle.value().lock().await; + + let activity_metadata = swarm.get_activity_metadata(current_cutoff); + + if activity_metadata.is_active { + active_torrents_total += 1; + } + + active_peers_total += activity_metadata.active_peers_total; + inactive_peers_total += activity_metadata.inactive_peers_total; + } + + AggregateActivityMetadata { + active_peers_total, + inactive_peers_total, + active_torrents_total, + inactive_torrents_total: self.len() - active_torrents_total, + } + } + + /// Counts the number of inactive peers across all torrents. + pub async fn count_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> usize { + let mut inactive_peers_total = 0; + + for swarm_handle in &self.swarms { + let swarm = swarm_handle.value().lock().await; + inactive_peers_total += swarm.count_inactive_peers(current_cutoff); + } + + inactive_peers_total + } + + /// Removes inactive peers from all torrent entries. + /// + /// A peer is considered inactive if its last update timestamp is older than + /// the provided cutoff time. + /// + /// # Errors + /// + /// This function returns an error if it fails to acquire the lock for any + /// swarm handle. + pub async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> Result { + tracing::info!( + "Removing inactive peers since: {:?} ...", + convert_from_timestamp_to_datetime_utc(current_cutoff) + ); + + let mut inactive_peers_removed = 0; + + for swarm_handle in &self.swarms { + let mut swarm = swarm_handle.value().lock().await; + let removed = swarm.remove_inactive(current_cutoff).await; + inactive_peers_removed += removed; + } + + tracing::info!(inactive_peers_removed = inactive_peers_removed); + + Ok(inactive_peers_removed) + } + + /// Removes torrent entries that have no active peers. + /// + /// Depending on the tracker policy, torrents without any peers may be + /// removed to conserve memory. + /// + /// # Errors + /// + /// This function returns an error if it fails to acquire the lock for any + /// swarm handle. + pub async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) -> Result { + tracing::info!("Removing peerless torrents ..."); + + let mut peerless_torrents_removed = 0; + + for swarm_handle in &self.swarms { + let swarm = swarm_handle.value().lock().await; + + if swarm.meets_retaining_policy(policy) { + continue; + } + + let info_hash = *swarm_handle.key(); + + swarm_handle.remove(); + + peerless_torrents_removed += 1; + + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender.send(Event::TorrentRemoved { info_hash }).await; + } + } + + tracing::info!(peerless_torrents_removed = peerless_torrents_removed); + + Ok(peerless_torrents_removed) + } + + /// Imports persistent torrent data into the in-memory repository. + /// + /// This method takes a set of persisted torrent entries (e.g., from a + /// database) and imports them into the in-memory repository for immediate + /// access. + pub fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) -> u64 { + tracing::info!("Importing persisted info about torrents ..."); + + let mut torrents_imported = 0; + + for (info_hash, completed) in persistent_torrents { + if self.swarms.contains_key(info_hash) { + continue; + } + + let entry = CoordinatorHandle::new(Coordinator::new(info_hash, *completed, self.event_sender.clone()).into()); + + // Since SkipMap is lock-free the torrent could have been inserted + // after checking if it exists. + self.swarms.get_or_insert(*info_hash, entry); + + torrents_imported += 1; + } + + tracing::info!(imported_torrents = torrents_imported); + + torrents_imported + } + + /// Calculates and returns overall torrent metrics. + /// + /// The returned [`AggregateSwarmMetadata`] contains aggregate data such as + /// the total number of torrents, total complete (seeders), incomplete + /// (leechers), and downloaded counts. + /// + /// # Returns + /// + /// A [`AggregateSwarmMetadata`] struct with the aggregated metrics. + /// + /// # Errors + /// + /// This function returns an error if it fails to acquire the lock for any + /// swarm handle. + pub async fn get_aggregate_swarm_metadata(&self) -> Result { + let mut metrics = AggregateActiveSwarmMetadata::default(); + + for swarm_handle in &self.swarms { + let swarm = swarm_handle.value().lock().await; + + let stats = swarm.metadata(); + + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + Ok(metrics) + } + + /// Counts the number of torrents that are peerless (i.e., have no active + /// peers). + /// + /// # Returns + /// + /// A `usize` representing the number of peerless torrents. + /// + /// # Errors + /// + /// This function returns an error if it fails to acquire the lock for any + /// swarm handle. + pub async fn count_peerless_torrents(&self) -> Result { + let mut peerless_torrents = 0; + + for swarm_handle in &self.swarms { + let swarm = swarm_handle.value().lock().await; + + if swarm.is_peerless() { + peerless_torrents += 1; + } + } + + Ok(peerless_torrents) + } + + /// Counts the total number of peers across all torrents. + /// + /// # Returns + /// + /// A `usize` representing the total number of peers. + /// + /// # Errors + /// + /// This function returns an error if it fails to acquire the lock for any + /// swarm handle. + pub async fn count_peers(&self) -> Result { + let mut peers = 0; + + for swarm_handle in &self.swarms { + let swarm = swarm_handle.value().lock().await; + + peers += swarm.len(); + } + + Ok(peers) + } + + #[must_use] + pub fn len(&self) -> usize { + self.swarms.len() + } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.swarms.is_empty() + } + + pub fn contains(&self, key: &InfoHash) -> bool { + self.swarms.contains_key(key) + } +} + +#[derive(thiserror::Error, Debug, Clone)] +pub enum Error {} + +#[derive(Clone, Debug, Default)] +pub struct AggregateActivityMetadata { + /// The number of active peers in all swarms. + pub active_peers_total: usize, + + /// The number of inactive peers in all swarms. + pub inactive_peers_total: usize, + + /// The number of active torrents. + pub active_torrents_total: usize, + + /// The number of inactive torrents. + pub inactive_torrents_total: usize, +} + +impl AggregateActivityMetadata { + pub fn log(&self) { + tracing::info!( + active_peers_total = self.active_peers_total, + inactive_peers_total = self.inactive_peers_total, + active_torrents_total = self.active_torrents_total, + inactive_torrents_total = self.inactive_torrents_total + ); + } +} +#[cfg(test)] +mod tests { + + mod the_swarm_repository { + + use std::sync::Arc; + + use aquatic_udp_protocol::PeerId; + + use crate::swarm::registry::Registry; + use crate::tests::{sample_info_hash, sample_peer}; + + /// It generates a peer id from a number where the number is the last + /// part of the peer ID. For example, for `12` it returns + /// `-qB00000000000000012`. + fn numeric_peer_id(two_digits_value: i32) -> PeerId { + // Format idx as a string with leading zeros, ensuring it has exactly 2 digits + let idx_str = format!("{two_digits_value:02}"); + + // Create the base part of the peer ID. + let base = b"-qB00000000000000000"; + + // Concatenate the base with idx bytes, ensuring the total length is 20 bytes. + let mut peer_id_bytes = [0u8; 20]; + peer_id_bytes[..base.len()].copy_from_slice(base); + peer_id_bytes[base.len() - idx_str.len()..].copy_from_slice(idx_str.as_bytes()); + + PeerId(peer_id_bytes) + } + + // The `TorrentRepository` has these responsibilities: + // - To maintain the peer lists for each torrent. + // - To maintain the the torrent entries, which contains all the info + // about the torrents, including the peer lists. + // - To return the torrent entries (swarm handles). + // - To return the peer lists for a given torrent. + // - To return the torrent metrics. + // - To return the swarm metadata for a given torrent. + // - To handle the persistence of the torrent entries. + + #[tokio::test] + async fn it_should_return_zero_length_when_it_has_no_swarms() { + let swarms = Arc::new(Registry::default()); + assert_eq!(swarms.len(), 0); + } + + #[tokio::test] + async fn it_should_return_the_length_when_it_has_swarms() { + let swarms = Arc::new(Registry::default()); + let info_hash = sample_info_hash(); + let peer = sample_peer(); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + assert_eq!(swarms.len(), 1); + } + + #[tokio::test] + async fn it_should_be_empty_when_it_has_no_swarms() { + let swarms = Arc::new(Registry::default()); + assert!(swarms.is_empty()); + + let info_hash = sample_info_hash(); + let peer = sample_peer(); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + assert!(!swarms.is_empty()); + } + + #[tokio::test] + async fn it_should_not_be_empty_when_it_has_at_least_one_swarm() { + let swarms = Arc::new(Registry::default()); + let info_hash = sample_info_hash(); + let peer = sample_peer(); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + + assert!(!swarms.is_empty()); + } + + mod maintaining_the_peer_lists { + + use std::sync::Arc; + + use crate::swarm::registry::Registry; + use crate::tests::{sample_info_hash, sample_peer}; + + #[tokio::test] + async fn it_should_add_the_first_peer_to_the_torrent_peer_list() { + let swarms = Arc::new(Registry::default()); + + let info_hash = sample_info_hash(); + + swarms.handle_announcement(&info_hash, &sample_peer(), None).await.unwrap(); + + assert!(swarms.get(&info_hash).is_some()); + } + + #[tokio::test] + async fn it_should_allow_adding_the_same_peer_twice_to_the_torrent_peer_list() { + let swarms = Arc::new(Registry::default()); + + let info_hash = sample_info_hash(); + + swarms.handle_announcement(&info_hash, &sample_peer(), None).await.unwrap(); + swarms.handle_announcement(&info_hash, &sample_peer(), None).await.unwrap(); + + assert!(swarms.get(&info_hash).is_some()); + } + } + + mod returning_peer_lists_for_a_torrent { + + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::swarm::registry::tests::the_swarm_repository::numeric_peer_id; + use crate::swarm::registry::Registry; + use crate::tests::{sample_info_hash, sample_peer}; + + #[tokio::test] + async fn it_should_return_the_peers_for_a_given_torrent() { + let swarms = Arc::new(Registry::default()); + + let info_hash = sample_info_hash(); + let peer = sample_peer(); + + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + + let peers = swarms.get_swarm_peers(&info_hash, 74).await.unwrap(); + + assert_eq!(peers, vec![Arc::new(peer)]); + } + + #[tokio::test] + async fn it_should_return_an_empty_list_or_peers_for_a_non_existing_torrent() { + let swarms = Arc::new(Registry::default()); + + let peers = swarms.get_swarm_peers(&sample_info_hash(), 74).await.unwrap(); + + assert!(peers.is_empty()); + } + + #[tokio::test] + async fn it_should_return_74_peers_at_the_most_for_a_given_torrent() { + let swarms = Arc::new(Registry::default()); + + let info_hash = sample_info_hash(); + + for idx in 1..=75 { + let peer = Peer { + peer_id: numeric_peer_id(idx), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + }; + + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + } + + let peers = swarms.get_swarm_peers(&info_hash, 74).await.unwrap(); + + assert_eq!(peers.len(), 74); + } + + mod excluding_the_client_peer { + + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::swarm::registry::tests::the_swarm_repository::numeric_peer_id; + use crate::swarm::registry::Registry; + use crate::tests::{sample_info_hash, sample_peer}; + + #[tokio::test] + async fn it_should_return_an_empty_peer_list_for_a_non_existing_torrent() { + let swarms = Arc::new(Registry::default()); + + let peers = swarms + .get_peers_peers_excluding(&sample_info_hash(), &sample_peer(), TORRENT_PEERS_LIMIT) + .await + .unwrap(); + + assert_eq!(peers, vec![]); + } + + #[tokio::test] + async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { + let swarms = Arc::new(Registry::default()); + + let info_hash = sample_info_hash(); + let peer = sample_peer(); + + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + + let peers = swarms + .get_peers_peers_excluding(&info_hash, &peer, TORRENT_PEERS_LIMIT) + .await + .unwrap(); + + assert_eq!(peers, vec![]); + } + + #[tokio::test] + async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { + let swarms = Arc::new(Registry::default()); + + let info_hash = sample_info_hash(); + + let excluded_peer = sample_peer(); + + swarms.handle_announcement(&info_hash, &excluded_peer, None).await.unwrap(); + + // Add 74 peers + for idx in 2..=75 { + let peer = Peer { + peer_id: numeric_peer_id(idx), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + }; + + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + } + + let peers = swarms + .get_peers_peers_excluding(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT) + .await + .unwrap(); + + assert_eq!(peers.len(), 74); + } + } + } + + mod maintaining_the_torrent_entries { + + use std::ops::Add; + use std::sync::Arc; + use std::time::Duration; + + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_configuration::TrackerPolicy; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::swarm::registry::Registry; + use crate::tests::{sample_info_hash, sample_peer}; + + #[tokio::test] + async fn it_should_remove_a_torrent_entry() { + let swarms = Arc::new(Registry::default()); + + let info_hash = sample_info_hash(); + swarms.handle_announcement(&info_hash, &sample_peer(), None).await.unwrap(); + + let _unused = swarms.remove(&info_hash).await; + + assert!(swarms.get(&info_hash).is_none()); + } + + #[tokio::test] + async fn it_should_count_inactive_peers() { + let swarms = Arc::new(Registry::default()); + + let info_hash = sample_info_hash(); + let mut peer = sample_peer(); + peer.updated = DurationSinceUnixEpoch::new(0, 0); + + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + + // Cut off time is 1 second after the peer was updated + let inactive_peers_total = swarms.count_inactive_peers(peer.updated.add(Duration::from_secs(1))).await; + + assert_eq!(inactive_peers_total, 1); + } + + #[tokio::test] + async fn it_should_remove_peers_that_have_not_been_updated_after_a_cutoff_time() { + let swarms = Arc::new(Registry::default()); + + let info_hash = sample_info_hash(); + let mut peer = sample_peer(); + peer.updated = DurationSinceUnixEpoch::new(0, 0); + + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + + // Cut off time is 1 second after the peer was updated + swarms + .remove_inactive_peers(peer.updated.add(Duration::from_secs(1))) + .await + .unwrap(); + + assert!(!swarms + .get_swarm_peers(&info_hash, 74) + .await + .unwrap() + .contains(&Arc::new(peer))); + } + + async fn initialize_repository_with_one_torrent_without_peers(info_hash: &InfoHash) -> Arc { + let swarms = Arc::new(Registry::default()); + + // Insert a sample peer for the torrent to force adding the torrent entry + let mut peer = sample_peer(); + peer.updated = DurationSinceUnixEpoch::new(0, 0); + swarms.handle_announcement(info_hash, &peer, None).await.unwrap(); + + // Remove the peer + swarms + .remove_inactive_peers(peer.updated.add(Duration::from_secs(1))) + .await + .unwrap(); + + swarms + } + + #[tokio::test] + async fn it_should_remove_torrents_without_peers() { + let info_hash = sample_info_hash(); + + let swarms = initialize_repository_with_one_torrent_without_peers(&info_hash).await; + + let tracker_policy = TrackerPolicy { + remove_peerless_torrents: true, + ..Default::default() + }; + + swarms.remove_peerless_torrents(&tracker_policy).await.unwrap(); + + assert!(swarms.get(&info_hash).is_none()); + } + } + mod returning_torrent_entries { + + use std::sync::Arc; + + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + + use crate::swarm::registry::Registry; + use crate::tests::{sample_info_hash, sample_peer}; + use crate::{Coordinator, CoordinatorHandle}; + + /// `TorrentEntry` data is not directly accessible. It's only + /// accessible through the trait methods. We need this temporary + /// DTO to write simple and more readable assertions. + #[derive(Debug, Clone, PartialEq)] + struct TorrentEntryInfo { + swarm_metadata: SwarmMetadata, + peers: Vec, + number_of_peers: usize, + } + + async fn torrent_entry_info(swarm_handle: CoordinatorHandle) -> TorrentEntryInfo { + let torrent_guard = swarm_handle.lock().await; + torrent_guard.clone().into() + } + + #[allow(clippy::from_over_into)] + impl Into for Coordinator { + fn into(self) -> TorrentEntryInfo { + let torrent_entry_info = TorrentEntryInfo { + swarm_metadata: self.metadata(), + peers: self.peers(None).iter().map(|peer| *peer.clone()).collect(), + number_of_peers: self.len(), + }; + torrent_entry_info + } + } + + #[tokio::test] + async fn it_should_return_one_torrent_entry_by_infohash() { + let swarms = Arc::new(Registry::default()); + + let info_hash = sample_info_hash(); + let peer = sample_peer(); + + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + + let torrent_entry_info = torrent_entry_info(swarms.get(&info_hash).unwrap()).await; + + assert_eq!( + TorrentEntryInfo { + swarm_metadata: SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0 + }, + peers: vec!(peer), + number_of_peers: 1 + }, + torrent_entry_info + ); + } + + mod it_should_return_many_torrent_entries { + use std::sync::Arc; + + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + + use crate::swarm::registry::tests::the_swarm_repository::returning_torrent_entries::{ + torrent_entry_info, TorrentEntryInfo, + }; + use crate::swarm::registry::Registry; + use crate::tests::{sample_info_hash, sample_peer}; + + #[tokio::test] + async fn without_pagination() { + let swarms = Arc::new(Registry::default()); + + let info_hash = sample_info_hash(); + let peer = sample_peer(); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + + let torrent_entries = swarms.get_paginated(None); + + assert_eq!(torrent_entries.len(), 1); + + let torrent_entry = torrent_entry_info(torrent_entries.first().unwrap().1.clone()).await; + + assert_eq!( + TorrentEntryInfo { + swarm_metadata: SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0 + }, + peers: vec!(peer), + number_of_peers: 1 + }, + torrent_entry + ); + } + + mod with_pagination { + use std::sync::Arc; + + use torrust_tracker_primitives::pagination::Pagination; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + + use crate::swarm::registry::tests::the_swarm_repository::returning_torrent_entries::{ + torrent_entry_info, TorrentEntryInfo, + }; + use crate::swarm::registry::Registry; + use crate::tests::{ + sample_info_hash_alphabetically_ordered_after_sample_info_hash_one, sample_info_hash_one, + sample_peer_one, sample_peer_two, + }; + + #[tokio::test] + async fn it_should_return_the_first_page() { + let swarms = Arc::new(Registry::default()); + + // Insert one torrent entry + let info_hash_one = sample_info_hash_one(); + let peer_one = sample_peer_one(); + swarms.handle_announcement(&info_hash_one, &peer_one, None).await.unwrap(); + + // Insert another torrent entry + let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); + let peer_two = sample_peer_two(); + swarms.handle_announcement(&info_hash_one, &peer_two, None).await.unwrap(); + + // Get only the first page where page size is 1 + let torrent_entries = swarms.get_paginated(Some(&Pagination { offset: 0, limit: 1 })); + + assert_eq!(torrent_entries.len(), 1); + + let torrent_entry_info = torrent_entry_info(torrent_entries.first().unwrap().1.clone()).await; + + assert_eq!( + TorrentEntryInfo { + swarm_metadata: SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0 + }, + peers: vec!(peer_one), + number_of_peers: 1 + }, + torrent_entry_info + ); + } + + #[tokio::test] + async fn it_should_return_the_second_page() { + let swarms = Arc::new(Registry::default()); + + // Insert one torrent entry + let info_hash_one = sample_info_hash_one(); + let peer_one = sample_peer_one(); + swarms.handle_announcement(&info_hash_one, &peer_one, None).await.unwrap(); + + // Insert another torrent entry + let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); + let peer_two = sample_peer_two(); + swarms.handle_announcement(&info_hash_one, &peer_two, None).await.unwrap(); + + // Get only the first page where page size is 1 + let torrent_entries = swarms.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); + + assert_eq!(torrent_entries.len(), 1); + + let torrent_entry_info = torrent_entry_info(torrent_entries.first().unwrap().1.clone()).await; + + assert_eq!( + TorrentEntryInfo { + swarm_metadata: SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0 + }, + peers: vec!(peer_two), + number_of_peers: 1 + }, + torrent_entry_info + ); + } + + #[tokio::test] + async fn it_should_allow_changing_the_page_size() { + let swarms = Arc::new(Registry::default()); + + // Insert one torrent entry + let info_hash_one = sample_info_hash_one(); + let peer_one = sample_peer_one(); + swarms.handle_announcement(&info_hash_one, &peer_one, None).await.unwrap(); + + // Insert another torrent entry + let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); + let peer_two = sample_peer_two(); + swarms.handle_announcement(&info_hash_one, &peer_two, None).await.unwrap(); + + // Get only the first page where page size is 1 + let torrent_entries = swarms.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); + + assert_eq!(torrent_entries.len(), 1); + } + } + } + } + + mod returning_aggregate_swarm_metadata { + + use std::sync::Arc; + + use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; + use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; + + use crate::swarm::registry::Registry; + use crate::tests::{complete_peer, leecher, sample_info_hash, seeder}; + + // todo: refactor to use test parametrization + + #[tokio::test] + async fn it_should_get_empty_aggregate_swarm_metadata_when_there_are_no_torrents() { + let swarms = Arc::new(Registry::default()); + + let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().await.unwrap(); + + assert_eq!( + aggregate_swarm_metadata, + AggregateActiveSwarmMetadata { + total_complete: 0, + total_downloaded: 0, + total_incomplete: 0, + total_torrents: 0 + } + ); + } + + #[tokio::test] + async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_leecher() { + let swarms = Arc::new(Registry::default()); + + swarms + .handle_announcement(&sample_info_hash(), &leecher(), None) + .await + .unwrap(); + + let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().await.unwrap(); + + assert_eq!( + aggregate_swarm_metadata, + AggregateActiveSwarmMetadata { + total_complete: 0, + total_downloaded: 0, + total_incomplete: 1, + total_torrents: 1, + } + ); + } + + #[tokio::test] + async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_seeder() { + let swarms = Arc::new(Registry::default()); + + swarms + .handle_announcement(&sample_info_hash(), &seeder(), None) + .await + .unwrap(); + + let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().await.unwrap(); + + assert_eq!( + aggregate_swarm_metadata, + AggregateActiveSwarmMetadata { + total_complete: 1, + total_downloaded: 0, + total_incomplete: 0, + total_torrents: 1, + } + ); + } + + #[tokio::test] + async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_completed_peer() { + let swarms = Arc::new(Registry::default()); + + swarms + .handle_announcement(&sample_info_hash(), &complete_peer(), None) + .await + .unwrap(); + + let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().await.unwrap(); + + assert_eq!( + aggregate_swarm_metadata, + AggregateActiveSwarmMetadata { + total_complete: 1, + total_downloaded: 0, + total_incomplete: 0, + total_torrents: 1, + } + ); + } + + #[tokio::test] + async fn it_should_return_the_aggregate_swarm_metadata_when_there_are_multiple_torrents() { + let swarms = Arc::new(Registry::default()); + + let start_time = std::time::Instant::now(); + for i in 0..1_000_000 { + swarms + .handle_announcement(&gen_seeded_infohash(&i), &leecher(), None) + .await + .unwrap(); + } + let result_a = start_time.elapsed(); + + let start_time = std::time::Instant::now(); + let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().await.unwrap(); + let result_b = start_time.elapsed(); + + assert_eq!( + (aggregate_swarm_metadata), + (AggregateActiveSwarmMetadata { + total_complete: 0, + total_downloaded: 0, + total_incomplete: 1_000_000, + total_torrents: 1_000_000, + }), + "{result_a:?} {result_b:?}" + ); + } + + mod it_should_count_peerless_torrents { + use std::sync::Arc; + + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::swarm::registry::Registry; + use crate::tests::{sample_info_hash, sample_peer}; + + #[tokio::test] + async fn no_peerless_torrents() { + let swarms = Arc::new(Registry::default()); + assert_eq!(swarms.count_peerless_torrents().await.unwrap(), 0); + } + + #[tokio::test] + async fn one_peerless_torrents() { + let info_hash = sample_info_hash(); + let peer = sample_peer(); + + let swarms = Arc::new(Registry::default()); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + + let current_cutoff = peer.updated + DurationSinceUnixEpoch::from_secs(1); + swarms.remove_inactive_peers(current_cutoff).await.unwrap(); + + assert_eq!(swarms.count_peerless_torrents().await.unwrap(), 1); + } + } + + mod it_should_count_peers { + use std::sync::Arc; + + use crate::swarm::registry::Registry; + use crate::tests::{sample_info_hash, sample_peer}; + + #[tokio::test] + async fn no_peers() { + let swarms = Arc::new(Registry::default()); + assert_eq!(swarms.count_peers().await.unwrap(), 0); + } + + #[tokio::test] + async fn one_peer() { + let info_hash = sample_info_hash(); + let peer = sample_peer(); + + let swarms = Arc::new(Registry::default()); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + + assert_eq!(swarms.count_peers().await.unwrap(), 1); + } + } + } + + mod returning_swarm_metadata { + + use std::sync::Arc; + + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + + use crate::swarm::registry::Registry; + use crate::tests::{leecher, sample_info_hash}; + + #[tokio::test] + async fn it_should_get_swarm_metadata_for_an_existing_torrent() { + let swarms = Arc::new(Registry::default()); + + let infohash = sample_info_hash(); + + swarms.handle_announcement(&infohash, &leecher(), None).await.unwrap(); + + let swarm_metadata = swarms.get_swarm_metadata_or_default(&infohash).await.unwrap(); + + assert_eq!( + swarm_metadata, + SwarmMetadata { + complete: 0, + downloaded: 0, + incomplete: 1, + } + ); + } + + #[tokio::test] + async fn it_should_return_zeroed_swarm_metadata_for_a_non_existing_torrent() { + let swarms = Arc::new(Registry::default()); + + let swarm_metadata = swarms.get_swarm_metadata_or_default(&sample_info_hash()).await.unwrap(); + + assert_eq!(swarm_metadata, SwarmMetadata::zeroed()); + } + } + + mod handling_persistence { + + use std::sync::Arc; + + use torrust_tracker_primitives::NumberOfDownloadsBTreeMap; + + use crate::swarm::registry::Registry; + use crate::tests::{leecher, sample_info_hash}; + + #[tokio::test] + async fn it_should_allow_importing_persisted_torrent_entries() { + let swarms = Arc::new(Registry::default()); + + let infohash = sample_info_hash(); + + let mut persistent_torrents = NumberOfDownloadsBTreeMap::default(); + + persistent_torrents.insert(infohash, 1); + + swarms.import_persistent(&persistent_torrents); + + let swarm_metadata = swarms.get_swarm_metadata_or_default(&infohash).await.unwrap(); + + // Only the number of downloads is persisted. + assert_eq!(swarm_metadata.downloaded, 1); + } + + #[tokio::test] + async fn it_should_allow_overwriting_a_previously_imported_persisted_torrent() { + // code-review: do we want to allow this? + + let swarms = Arc::new(Registry::default()); + + let infohash = sample_info_hash(); + + let mut persistent_torrents = NumberOfDownloadsBTreeMap::default(); + + persistent_torrents.insert(infohash, 1); + persistent_torrents.insert(infohash, 2); + + swarms.import_persistent(&persistent_torrents); + + let swarm_metadata = swarms.get_swarm_metadata_or_default(&infohash).await.unwrap(); + + // It takes the last value + assert_eq!(swarm_metadata.downloaded, 2); + } + + #[tokio::test] + async fn it_should_now_allow_importing_a_persisted_torrent_if_it_already_exists() { + let swarms = Arc::new(Registry::default()); + + let infohash = sample_info_hash(); + + // Insert a new the torrent entry + swarms.handle_announcement(&infohash, &leecher(), None).await.unwrap(); + let initial_number_of_downloads = swarms.get_swarm_metadata_or_default(&infohash).await.unwrap().downloaded; + + // Try to import the torrent entry + let new_number_of_downloads = initial_number_of_downloads + 1; + let mut persistent_torrents = NumberOfDownloadsBTreeMap::default(); + persistent_torrents.insert(infohash, new_number_of_downloads); + swarms.import_persistent(&persistent_torrents); + + // The number of downloads should not be changed + assert_eq!( + swarms.get_swarm_metadata_or_default(&infohash).await.unwrap().downloaded, + initial_number_of_downloads + ); + } + } + } + + mod triggering_events { + + use std::sync::Arc; + + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::event::sender::tests::{expect_event_sequence, MockEventSender}; + use crate::event::Event; + use crate::swarm::registry::Registry; + use crate::tests::sample_info_hash; + + #[tokio::test] + async fn it_should_trigger_an_event_when_a_new_torrent_is_added() { + let info_hash = sample_info_hash(); + let peer = PeerBuilder::leecher().build(); + + let mut event_sender_mock = MockEventSender::new(); + + expect_event_sequence( + &mut event_sender_mock, + vec![ + Event::TorrentAdded { + info_hash, + announcement: peer, + }, + Event::PeerAdded { info_hash, peer }, + ], + ); + + let swarms = Registry::new(Some(Arc::new(event_sender_mock))); + + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + } + + #[tokio::test] + async fn it_should_trigger_an_event_when_a_torrent_is_directly_removed() { + let info_hash = sample_info_hash(); + let peer = PeerBuilder::leecher().build(); + + let mut event_sender_mock = MockEventSender::new(); + + expect_event_sequence( + &mut event_sender_mock, + vec![ + Event::TorrentAdded { + info_hash, + announcement: peer, + }, + Event::PeerAdded { info_hash, peer }, + Event::TorrentRemoved { info_hash }, + ], + ); + + let swarms = Registry::new(Some(Arc::new(event_sender_mock))); + + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + + swarms.remove(&info_hash).await.unwrap(); + } + + #[tokio::test] + async fn it_should_trigger_an_event_when_a_peerless_torrent_is_removed() { + let info_hash = sample_info_hash(); + let peer = PeerBuilder::leecher().build(); + + let mut event_sender_mock = MockEventSender::new(); + + expect_event_sequence( + &mut event_sender_mock, + vec![ + Event::TorrentAdded { + info_hash, + announcement: peer, + }, + Event::PeerAdded { info_hash, peer }, + Event::PeerRemoved { info_hash, peer }, + Event::TorrentRemoved { info_hash }, + ], + ); + + let swarms = Registry::new(Some(Arc::new(event_sender_mock))); + + // Add the new torrent + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + + // Remove the peer + let current_cutoff = peer.updated + DurationSinceUnixEpoch::from_secs(1); + swarms.remove_inactive_peers(current_cutoff).await.unwrap(); + + // Remove peerless torrents + + let tracker_policy = torrust_tracker_configuration::TrackerPolicy { + remove_peerless_torrents: true, + ..Default::default() + }; + + swarms.remove_peerless_torrents(&tracker_policy).await.unwrap(); + } + } +} diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 5d360d101..fb240730d 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -1,13 +1,21 @@ [package] -name = "torrust-tracker-test-helpers" description = "A library providing helpers for testing the Torrust tracker." -license = "AGPL-3.0" -version.workspace = true +keywords = [ "helper", "library", "testing" ] +name = "torrust-tracker-test-helpers" +readme = "README.md" + authors.workspace = true +documentation.workspace = true edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true [dependencies] -lazy_static = "1.4" -rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.2", path = "../configuration"} -torrust-tracker-primitives = { version = "3.0.0-alpha.2", path = "../primitives"} +rand = "0" +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +tracing = "0" +tracing-subscriber = { version = "0", features = [ "json" ] } diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 437475ee2..ffe3af3b2 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -1,9 +1,10 @@ //! Tracker configuration factories for testing. use std::env; -use std::net::IpAddr; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; +use std::path::PathBuf; +use std::time::Duration; -use torrust_tracker_configuration::Configuration; -use torrust_tracker_primitives::TrackerMode; +use torrust_tracker_configuration::{Configuration, HttpApi, HttpTracker, Threshold, UdpTracker}; use crate::random; @@ -13,11 +14,11 @@ use crate::random; /// > **NOTICE**: This configuration is not meant to be used in production. /// /// > **NOTICE**: Port 0 is used for ephemeral ports, which means that the OS -/// will assign a random free port for the tracker to use. +/// > will assign a random free port for the tracker to use. /// -/// > **NOTICE**: You can change the log level to `debug` to see the logs of the -/// tracker while running the tests. That can be particularly useful when -/// debugging tests. +/// > **NOTICE**: You can change the log threshold to `debug` to see the logs of the +/// > tracker while running the tests. That can be particularly useful when +/// > debugging tests. /// /// # Panics /// @@ -27,41 +28,63 @@ pub fn ephemeral() -> Configuration { // todo: disable services that are not needed. // For example: a test for the UDP tracker should disable the API and HTTP tracker. - let mut config = Configuration { - log_level: Some("off".to_owned()), // Change to `debug` for tests debugging - ..Default::default() - }; + let mut config = Configuration::default(); + + // This have to be Off otherwise the tracing global subscriber + // initialization will panic because you can't set a global subscriber more + // than once. You can use enable logging in tests with: + // `crate::common::logging::setup(LevelFilter::ERROR);` + // That will also allow you to capture logs and write assertions on them. + config.logging.threshold = Threshold::Off; // Ephemeral socket address for API let api_port = 0u16; - config.http_api.enabled = true; - config.http_api.bind_address = format!("127.0.0.1:{}", &api_port); + let mut http_api = HttpApi { + bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), api_port), + ..Default::default() + }; + http_api.add_token("admin", "MyAccessToken"); + config.http_api = Some(http_api); + + // Ephemeral socket address for Health Check API + let health_check_api_port = 0u16; + config.health_check_api.bind_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), health_check_api_port); // Ephemeral socket address for UDP tracker let udp_port = 0u16; - config.udp_trackers[0].enabled = true; - config.udp_trackers[0].bind_address = format!("127.0.0.1:{}", &udp_port); + config.udp_trackers = Some(vec![UdpTracker { + bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), udp_port), + cookie_lifetime: Duration::from_secs(120), + tracker_usage_statistics: true, + }]); // Ephemeral socket address for HTTP tracker let http_port = 0u16; - config.http_trackers[0].enabled = true; - config.http_trackers[0].bind_address = format!("127.0.0.1:{}", &http_port); + config.http_trackers = Some(vec![HttpTracker { + bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), http_port), + tsl_config: None, + tracker_usage_statistics: true, + }]); - // Ephemeral sqlite database - let temp_directory = env::temp_dir(); - let random_db_id = random::string(16); - let temp_file = temp_directory.join(format!("data_{random_db_id}.db")); - config.db_path = temp_file.to_str().unwrap().to_owned(); + let temp_file = ephemeral_sqlite_database(); + temp_file.to_str().unwrap().clone_into(&mut config.core.database.path); config } +#[must_use] +pub fn ephemeral_sqlite_database() -> PathBuf { + let temp_directory = env::temp_dir(); + let random_db_id = random::string(16); + temp_directory.join(format!("data_{random_db_id}.db")) +} + /// Ephemeral configuration with reverse proxy enabled. #[must_use] pub fn ephemeral_with_reverse_proxy() -> Configuration { let mut cfg = ephemeral(); - cfg.on_reverse_proxy = true; + cfg.core.net.on_reverse_proxy = true; cfg } @@ -71,47 +94,48 @@ pub fn ephemeral_with_reverse_proxy() -> Configuration { pub fn ephemeral_without_reverse_proxy() -> Configuration { let mut cfg = ephemeral(); - cfg.on_reverse_proxy = false; + cfg.core.net.on_reverse_proxy = false; cfg } /// Ephemeral configuration with `public` mode. #[must_use] -pub fn ephemeral_mode_public() -> Configuration { +pub fn ephemeral_public() -> Configuration { let mut cfg = ephemeral(); - cfg.mode = TrackerMode::Public; + cfg.core.private = false; cfg } /// Ephemeral configuration with `private` mode. #[must_use] -pub fn ephemeral_mode_private() -> Configuration { +pub fn ephemeral_private() -> Configuration { let mut cfg = ephemeral(); - cfg.mode = TrackerMode::Private; + cfg.core.private = true; cfg } /// Ephemeral configuration with `listed` mode. #[must_use] -pub fn ephemeral_mode_whitelisted() -> Configuration { +pub fn ephemeral_listed() -> Configuration { let mut cfg = ephemeral(); - cfg.mode = TrackerMode::Listed; + cfg.core.listed = true; cfg } /// Ephemeral configuration with `private_listed` mode. #[must_use] -pub fn ephemeral_mode_private_whitelisted() -> Configuration { +pub fn ephemeral_private_and_listed() -> Configuration { let mut cfg = ephemeral(); - cfg.mode = TrackerMode::PrivateListed; + cfg.core.private = true; + cfg.core.listed = true; cfg } @@ -121,7 +145,7 @@ pub fn ephemeral_mode_private_whitelisted() -> Configuration { pub fn ephemeral_with_external_ip(ip: IpAddr) -> Configuration { let mut cfg = ephemeral(); - cfg.external_ip = Some(ip.to_string()); + cfg.core.net.external_ip = Some(ip); cfg } @@ -132,11 +156,31 @@ pub fn ephemeral_with_external_ip(ip: IpAddr) -> Configuration { pub fn ephemeral_ipv6() -> Configuration { let mut cfg = ephemeral(); - let ipv6 = format!("[::]:{}", 0); + let ipv6 = SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0); + + if let Some(ref mut http_api) = cfg.http_api { + http_api.bind_address.clone_from(&ipv6); + } + + if let Some(ref mut http_trackers) = cfg.http_trackers { + http_trackers[0].bind_address.clone_from(&ipv6); + } + + if let Some(ref mut udp_trackers) = cfg.udp_trackers { + udp_trackers[0].bind_address.clone_from(&ipv6); + } + + cfg +} + +/// Ephemeral without running any services. +#[must_use] +pub fn ephemeral_with_no_services() -> Configuration { + let mut cfg = ephemeral(); - cfg.http_api.bind_address = ipv6.clone(); - cfg.http_trackers[0].bind_address = ipv6.clone(); - cfg.udp_trackers[0].bind_address = ipv6; + cfg.http_api = None; + cfg.http_trackers = None; + cfg.udp_trackers = None; cfg } diff --git a/packages/test-helpers/src/lib.rs b/packages/test-helpers/src/lib.rs index e66ea2adc..bd67ca770 100644 --- a/packages/test-helpers/src/lib.rs +++ b/packages/test-helpers/src/lib.rs @@ -2,4 +2,5 @@ //! //! A collection of functions and types to help with testing the tracker server. pub mod configuration; +pub mod logging; pub mod random; diff --git a/packages/test-helpers/src/logging.rs b/packages/test-helpers/src/logging.rs new file mode 100644 index 000000000..564074f3e --- /dev/null +++ b/packages/test-helpers/src/logging.rs @@ -0,0 +1,156 @@ +//! Setup for logging in tests. +use std::collections::VecDeque; +use std::io; +use std::sync::{Mutex, MutexGuard, Once, OnceLock}; + +use torrust_tracker_configuration::logging::TraceStyle; +use tracing::level_filters::LevelFilter; +use tracing_subscriber::fmt::MakeWriter; + +static INIT: Once = Once::new(); + +/// A global buffer containing the latest lines captured from logs. +#[doc(hidden)] +pub fn captured_logs_buffer() -> &'static Mutex { + static CAPTURED_LOGS_GLOBAL_BUFFER: OnceLock> = OnceLock::new(); + CAPTURED_LOGS_GLOBAL_BUFFER.get_or_init(|| Mutex::new(CircularBuffer::new(10000, 200))) +} + +pub fn setup() { + INIT.call_once(|| { + tracing_init(LevelFilter::ERROR, &TraceStyle::Default); + }); +} + +fn tracing_init(level_filter: LevelFilter, style: &TraceStyle) { + let mock_writer = LogCapturer::new(captured_logs_buffer()); + + let builder = tracing_subscriber::fmt() + .with_max_level(level_filter) + .with_ansi(true) + .with_test_writer() + .with_writer(mock_writer); + + let () = match style { + TraceStyle::Default => builder.init(), + TraceStyle::Pretty(display_filename) => builder.pretty().with_file(*display_filename).init(), + TraceStyle::Compact => builder.compact().init(), + TraceStyle::Json => builder.json().init(), + }; + + tracing::info!("Logging initialized"); +} + +/// It returns true is there is a log line containing all the texts passed. +/// +/// # Panics +/// +/// Will panic if it can't get the lock for the global buffer or convert it into +/// a vec. +#[must_use] +#[allow(dead_code)] +pub fn logs_contains_a_line_with(texts: &[&str]) -> bool { + // code-review: we can search directly in the buffer instead of converting + // the buffer into a string but that would slow down the tests because + // cloning should be faster that locking the buffer for searching. + // Because the buffer is not big. + let logs = String::from_utf8(captured_logs_buffer().lock().unwrap().as_vec()).unwrap(); + + for line in logs.split('\n') { + if contains(line, texts) { + return true; + } + } + + false +} + +#[allow(dead_code)] +fn contains(text: &str, texts: &[&str]) -> bool { + texts.iter().all(|&word| text.contains(word)) +} + +/// A tracing writer which captures the latests logs lines into a buffer. +/// It's used to capture the logs in the tests. +#[derive(Debug)] +pub struct LogCapturer<'a> { + logs: &'a Mutex, +} + +impl<'a> LogCapturer<'a> { + pub fn new(buf: &'a Mutex) -> Self { + Self { logs: buf } + } + + fn buf(&self) -> io::Result> { + self.logs.lock().map_err(|_| io::Error::from(io::ErrorKind::Other)) + } +} + +impl io::Write for LogCapturer<'_> { + fn write(&mut self, buf: &[u8]) -> io::Result { + print!("{}", String::from_utf8(buf.to_vec()).unwrap()); + + let mut target = self.buf()?; + + target.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.buf()?.flush() + } +} + +impl MakeWriter<'_> for LogCapturer<'_> { + type Writer = Self; + + fn make_writer(&self) -> Self::Writer { + LogCapturer::new(self.logs) + } +} + +#[derive(Debug)] +pub struct CircularBuffer { + max_size: usize, + buffer: VecDeque, +} + +impl CircularBuffer { + #[must_use] + pub fn new(max_lines: usize, average_line_size: usize) -> Self { + Self { + max_size: max_lines * average_line_size, + buffer: VecDeque::with_capacity(max_lines * average_line_size), + } + } + + /// # Errors + /// + /// Won't return any error. + #[allow(clippy::unnecessary_wraps)] + pub fn write(&mut self, buf: &[u8]) -> io::Result { + for &byte in buf { + if self.buffer.len() == self.max_size { + // Remove oldest byte to make space + self.buffer.pop_front(); + } + self.buffer.push_back(byte); + } + + Ok(buf.len()) + } + + /// # Errors + /// + /// Won't return any error. + #[allow(clippy::unnecessary_wraps)] + #[allow(clippy::unused_self)] + pub fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + + #[must_use] + pub fn as_vec(&self) -> Vec { + self.buffer.iter().copied().collect() + } +} diff --git a/packages/test-helpers/src/random.rs b/packages/test-helpers/src/random.rs index 2133dcd29..62265dbd7 100644 --- a/packages/test-helpers/src/random.rs +++ b/packages/test-helpers/src/random.rs @@ -1,10 +1,10 @@ //! Random data generators for testing. -use rand::distributions::Alphanumeric; -use rand::{thread_rng, Rng}; +use rand::distr::Alphanumeric; +use rand::{rng, RngExt}; /// Returns a random alphanumeric string of a certain size. /// /// It is useful for generating random names, IDs, etc for testing. pub fn string(size: usize) -> String { - thread_rng().sample_iter(&Alphanumeric).take(size).map(char::from).collect() + rng().sample_iter(&Alphanumeric).take(size).map(char::from).collect() } diff --git a/packages/torrent-repository-benchmarking/Cargo.toml b/packages/torrent-repository-benchmarking/Cargo.toml new file mode 100644 index 000000000..653ad8102 --- /dev/null +++ b/packages/torrent-repository-benchmarking/Cargo.toml @@ -0,0 +1,38 @@ +[package] +description = "A library to runt benchmarking for different implementations of a repository of torrents files and their peers." +keywords = [ "library", "repository", "torrents" ] +name = "torrust-tracker-torrent-repository-benchmarking" +readme = "README.md" + +authors.workspace = true +categories.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +bittorrent-primitives = "0.1.0" +crossbeam-skiplist = "0" +dashmap = "6" +futures = "0" +parking_lot = "0" +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +zerocopy = "0.7" + +[dev-dependencies] +async-std = { version = "1", features = [ "attributes", "tokio1" ] } +criterion = { version = "0", features = [ "async_tokio" ] } +rstest = "0" + +[[bench]] +harness = false +name = "repository_benchmark" diff --git a/packages/torrent-repository-benchmarking/README.md b/packages/torrent-repository-benchmarking/README.md new file mode 100644 index 000000000..a0556a58f --- /dev/null +++ b/packages/torrent-repository-benchmarking/README.md @@ -0,0 +1,32 @@ +# Torrust Tracker Swarm Coordination Registry Benchmarking + +A library to runt benchmarking for different implementations of a repository of torrents files and their peers. Torrent repositories are used by the [Torrust Tracker](https://github.com/torrust/torrust-tracker). + +## Benchmarking + +```console +cargo bench -p torrust-tracker-torrent-repository +``` + +Example partial output: + +```output + Running benches/repository_benchmark.rs (target/release/deps/repository_benchmark-a9b0013c8d09c3c3) +add_one_torrent/RwLockStd + time: [63.057 ns 63.242 ns 63.506 ns] +Found 12 outliers among 100 measurements (12.00%) + 2 (2.00%) low severe + 2 (2.00%) low mild + 2 (2.00%) high mild + 6 (6.00%) high severe +add_one_torrent/RwLockStdMutexStd + time: [62.505 ns 63.077 ns 63.817 ns] +``` + +## Documentation + +[Crate documentation](https://docs.rs/torrust-tracker-torrent-repository). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/torrent-repository-benchmarking/benches/helpers/asyn.rs b/packages/torrent-repository-benchmarking/benches/helpers/asyn.rs new file mode 100644 index 000000000..4deb1955a --- /dev/null +++ b/packages/torrent-repository-benchmarking/benches/helpers/asyn.rs @@ -0,0 +1,153 @@ +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use bittorrent_primitives::info_hash::InfoHash; +use futures::stream::FuturesUnordered; +use torrust_tracker_torrent_repository_benchmarking::repository::RepositoryAsync; + +use super::utils::{generate_unique_info_hashes, DEFAULT_PEER}; + +pub async fn add_one_torrent(samples: u64) -> Duration +where + V: RepositoryAsync + Default, +{ + let start = Instant::now(); + + for _ in 0..samples { + let torrent_repository = V::default(); + + let info_hash = InfoHash::default(); + + torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; + + torrent_repository.get_swarm_metadata(&info_hash).await; + } + + start.elapsed() +} + +// Add one torrent ten thousand times in parallel (depending on the set worker threads) +pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: u64, sleep: Option) -> Duration +where + V: RepositoryAsync + Default, + Arc: Clone + Send + Sync + 'static, +{ + let torrent_repository = Arc::::default(); + let info_hash = InfoHash::default(); + let handles = FuturesUnordered::new(); + + // Add the torrent/peer to the torrent repository + torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; + + torrent_repository.get_swarm_metadata(&info_hash).await; + + let start = Instant::now(); + + for _ in 0..samples { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; + + torrent_repository_clone.get_swarm_metadata(&info_hash).await; + + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() +} + +// Add ten thousand torrents in parallel (depending on the set worker threads) +pub async fn add_multiple_torrents_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: u64, + sleep: Option, +) -> Duration +where + V: RepositoryAsync + Default, + Arc: Clone + Send + Sync + 'static, +{ + let torrent_repository = Arc::::default(); + let info_hashes = generate_unique_info_hashes(samples.try_into().expect("it should fit in a usize")); + let handles = FuturesUnordered::new(); + + let start = Instant::now(); + + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; + + torrent_repository_clone.get_swarm_metadata(&info_hash).await; + + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() +} + +// Async update ten thousand torrents in parallel (depending on the set worker threads) +pub async fn update_multiple_torrents_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: u64, + sleep: Option, +) -> Duration +where + V: RepositoryAsync + Default, + Arc: Clone + Send + Sync + 'static, +{ + let torrent_repository = Arc::::default(); + let info_hashes = generate_unique_info_hashes(samples.try_into().expect("it should fit in usize")); + let handles = FuturesUnordered::new(); + + // Add the torrents/peers to the torrent repository + for info_hash in &info_hashes { + torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER, None).await; + torrent_repository.get_swarm_metadata(info_hash).await; + } + + let start = Instant::now(); + + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; + torrent_repository_clone.get_swarm_metadata(&info_hash).await; + + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() +} diff --git a/packages/torrent-repository-benchmarking/benches/helpers/mod.rs b/packages/torrent-repository-benchmarking/benches/helpers/mod.rs new file mode 100644 index 000000000..1026aa4bf --- /dev/null +++ b/packages/torrent-repository-benchmarking/benches/helpers/mod.rs @@ -0,0 +1,3 @@ +pub mod asyn; +pub mod sync; +pub mod utils; diff --git a/packages/torrent-repository-benchmarking/benches/helpers/sync.rs b/packages/torrent-repository-benchmarking/benches/helpers/sync.rs new file mode 100644 index 000000000..2cefb5a4a --- /dev/null +++ b/packages/torrent-repository-benchmarking/benches/helpers/sync.rs @@ -0,0 +1,155 @@ +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use bittorrent_primitives::info_hash::InfoHash; +use futures::stream::FuturesUnordered; +use torrust_tracker_torrent_repository_benchmarking::repository::Repository; + +use super::utils::{generate_unique_info_hashes, DEFAULT_PEER}; + +// Simply add one torrent +#[must_use] +pub fn add_one_torrent(samples: u64) -> Duration +where + V: Repository + Default, +{ + let start = Instant::now(); + + for _ in 0..samples { + let torrent_repository = V::default(); + + let info_hash = InfoHash::default(); + + torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER, None); + + torrent_repository.get_swarm_metadata(&info_hash); + } + + start.elapsed() +} + +// Add one torrent ten thousand times in parallel (depending on the set worker threads) +pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: u64, sleep: Option) -> Duration +where + V: Repository + Default, + Arc: Clone + Send + Sync + 'static, +{ + let torrent_repository = Arc::::default(); + let info_hash = InfoHash::default(); + let handles = FuturesUnordered::new(); + + // Add the torrent/peer to the torrent repository + torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER, None); + + torrent_repository.get_swarm_metadata(&info_hash); + + let start = Instant::now(); + + for _ in 0..samples { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None); + + torrent_repository_clone.get_swarm_metadata(&info_hash); + + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() +} + +// Add ten thousand torrents in parallel (depending on the set worker threads) +pub async fn add_multiple_torrents_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: u64, + sleep: Option, +) -> Duration +where + V: Repository + Default, + Arc: Clone + Send + Sync + 'static, +{ + let torrent_repository = Arc::::default(); + let info_hashes = generate_unique_info_hashes(samples.try_into().expect("it should fit in a usize")); + let handles = FuturesUnordered::new(); + + let start = Instant::now(); + + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None); + + torrent_repository_clone.get_swarm_metadata(&info_hash); + + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() +} + +// Update ten thousand torrents in parallel (depending on the set worker threads) +pub async fn update_multiple_torrents_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: u64, + sleep: Option, +) -> Duration +where + V: Repository + Default, + Arc: Clone + Send + Sync + 'static, +{ + let torrent_repository = Arc::::default(); + let info_hashes = generate_unique_info_hashes(samples.try_into().expect("it should fit in usize")); + let handles = FuturesUnordered::new(); + + // Add the torrents/peers to the torrent repository + for info_hash in &info_hashes { + torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER, None); + torrent_repository.get_swarm_metadata(info_hash); + } + + let start = Instant::now(); + + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None); + torrent_repository_clone.get_swarm_metadata(&info_hash); + + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() +} diff --git a/packages/torrent-repository-benchmarking/benches/helpers/utils.rs b/packages/torrent-repository-benchmarking/benches/helpers/utils.rs new file mode 100644 index 000000000..16ba0bf7f --- /dev/null +++ b/packages/torrent-repository-benchmarking/benches/helpers/utils.rs @@ -0,0 +1,41 @@ +use std::collections::HashSet; +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::peer::Peer; +use torrust_tracker_primitives::DurationSinceUnixEpoch; +use zerocopy::I64; + +pub const DEFAULT_PEER: Peer = Peer { + peer_id: PeerId([0; 20]), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080), + updated: DurationSinceUnixEpoch::from_secs(0), + uploaded: NumberOfBytes(I64::ZERO), + downloaded: NumberOfBytes(I64::ZERO), + left: NumberOfBytes(I64::ZERO), + event: AnnounceEvent::Started, +}; + +#[must_use] +#[allow(clippy::missing_panics_doc)] +pub fn generate_unique_info_hashes(size: usize) -> Vec { + let mut result = HashSet::new(); + + let mut bytes = [0u8; 20]; + + #[allow(clippy::cast_possible_truncation)] + for i in 0..size { + bytes[0] = (i & 0xFF) as u8; + bytes[1] = ((i >> 8) & 0xFF) as u8; + bytes[2] = ((i >> 16) & 0xFF) as u8; + bytes[3] = ((i >> 24) & 0xFF) as u8; + + let info_hash = InfoHash::from_bytes(&bytes); + result.insert(info_hash); + } + + assert_eq!(result.len(), size); + + result.into_iter().collect() +} diff --git a/packages/torrent-repository-benchmarking/benches/repository_benchmark.rs b/packages/torrent-repository-benchmarking/benches/repository_benchmark.rs new file mode 100644 index 000000000..f5f8e4b28 --- /dev/null +++ b/packages/torrent-repository-benchmarking/benches/repository_benchmark.rs @@ -0,0 +1,270 @@ +use std::time::Duration; + +mod helpers; + +use criterion::{criterion_group, criterion_main, Criterion}; +use torrust_tracker_torrent_repository_benchmarking::{ + TorrentsDashMapMutexStd, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, TorrentsRwLockTokio, + TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexParkingLot, TorrentsSkipMapMutexStd, + TorrentsSkipMapRwLockParkingLot, +}; + +use crate::helpers::{asyn, sync}; + +fn add_one_torrent(c: &mut Criterion) { + let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); + + let mut group = c.benchmark_group("add_one_torrent"); + + group.warm_up_time(Duration::from_millis(500)); + group.measurement_time(Duration::from_secs(1)); + + group.bench_function("RwLockStd", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + + group.bench_function("RwLockStdMutexStd", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + + group.bench_function("RwLockStdMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(asyn::add_one_torrent::); + }); + + group.bench_function("RwLockTokio", |b| { + b.to_async(&rt).iter_custom(asyn::add_one_torrent::); + }); + + group.bench_function("RwLockTokioMutexStd", |b| { + b.to_async(&rt) + .iter_custom(asyn::add_one_torrent::); + }); + + group.bench_function("RwLockTokioMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(asyn::add_one_torrent::); + }); + + group.bench_function("SkipMapMutexStd", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + + group.bench_function("SkipMapMutexParkingLot", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + + group.bench_function("SkipMapRwLockParkingLot", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + + group.bench_function("DashMapMutexStd", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + + group.finish(); +} + +fn add_multiple_torrents_in_parallel(c: &mut Criterion) { + let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); + + let mut group = c.benchmark_group("add_multiple_torrents_in_parallel"); + + //group.sampling_mode(criterion::SamplingMode::Flat); + //group.sample_size(10); + + group.warm_up_time(Duration::from_millis(500)); + group.measurement_time(Duration::from_secs(1)); + + group.bench_function("RwLockStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("SkipMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("SkipMapMutexParkingLot", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("SkipMapRwLockParkingLot", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("DashMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.finish(); +} + +fn update_one_torrent_in_parallel(c: &mut Criterion) { + let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); + + let mut group = c.benchmark_group("update_one_torrent_in_parallel"); + + //group.sampling_mode(criterion::SamplingMode::Flat); + //group.sample_size(10); + + group.warm_up_time(Duration::from_millis(500)); + group.measurement_time(Duration::from_secs(1)); + + group.bench_function("RwLockStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("SkipMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("SkipMapMutexParkingLot", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("SkipMapRwLockParkingLot", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("DashMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.finish(); +} + +fn update_multiple_torrents_in_parallel(c: &mut Criterion) { + let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); + + let mut group = c.benchmark_group("update_multiple_torrents_in_parallel"); + + //group.sampling_mode(criterion::SamplingMode::Flat); + //group.sample_size(10); + + group.warm_up_time(Duration::from_millis(500)); + group.measurement_time(Duration::from_secs(1)); + + group.bench_function("RwLockStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexTokio", |b| { + b.to_async(&rt).iter_custom(|iters| { + asyn::update_multiple_torrents_in_parallel::(&rt, iters, None) + }); + }); + + group.bench_function("SkipMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("SkipMapMutexParkingLot", |b| { + b.to_async(&rt).iter_custom(|iters| { + sync::update_multiple_torrents_in_parallel::(&rt, iters, None) + }); + }); + + group.bench_function("SkipMapRwLockParkingLot", |b| { + b.to_async(&rt).iter_custom(|iters| { + sync::update_multiple_torrents_in_parallel::(&rt, iters, None) + }); + }); + + group.bench_function("DashMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.finish(); +} + +criterion_group!( + benches, + add_one_torrent, + add_multiple_torrents_in_parallel, + update_one_torrent_in_parallel, + update_multiple_torrents_in_parallel +); +criterion_main!(benches); diff --git a/packages/torrent-repository-benchmarking/src/entry/mod.rs b/packages/torrent-repository-benchmarking/src/entry/mod.rs new file mode 100644 index 000000000..b920839d9 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/entry/mod.rs @@ -0,0 +1,92 @@ +use std::fmt::Debug; +use std::net::SocketAddr; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +use self::peer_list::PeerList; + +pub mod mutex_parking_lot; +pub mod mutex_std; +pub mod mutex_tokio; +pub mod peer_list; +pub mod rw_lock_parking_lot; +pub mod single; + +pub trait Entry { + /// It returns the swarm metadata (statistics) as a struct: + /// + /// `(seeders, completed, leechers)` + fn get_swarm_metadata(&self) -> SwarmMetadata; + + /// Returns True if Still a Valid Entry according to the Tracker Policy + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool; + + /// Returns True if the Peers is Empty + fn peers_is_empty(&self) -> bool; + + /// Returns the number of Peers + fn get_peers_len(&self) -> usize; + + /// Get all swarm peers, optionally limiting the result. + fn get_peers(&self, limit: Option) -> Vec>; + + /// It returns the list of peers for a given peer client, optionally limiting the + /// result. + /// + /// It filters out the input peer, typically because we want to return this + /// list of peers to that client peer. + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec>; + + /// It updates a peer and returns true if the number of complete downloads have increased. + /// + /// The number of peers that have complete downloading is synchronously updated when peers are updated. + /// That's the total torrent downloads counter. + fn upsert_peer(&mut self, peer: &peer::Peer) -> bool; + + /// It removes peer from the swarm that have not been updated for more than `current_cutoff` seconds + fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch); +} + +#[allow(clippy::module_name_repetitions)] +pub trait EntrySync { + fn get_swarm_metadata(&self) -> SwarmMetadata; + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool; + fn peers_is_empty(&self) -> bool; + fn get_peers_len(&self) -> usize; + fn get_peers(&self, limit: Option) -> Vec>; + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec>; + fn upsert_peer(&self, peer: &peer::Peer) -> bool; + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch); +} + +#[allow(clippy::module_name_repetitions)] +pub trait EntryAsync { + fn get_swarm_metadata(&self) -> impl std::future::Future + Send; + fn meets_retaining_policy(self, policy: &TrackerPolicy) -> impl std::future::Future + Send; + fn peers_is_empty(&self) -> impl std::future::Future + Send; + fn get_peers_len(&self) -> impl std::future::Future + Send; + fn get_peers(&self, limit: Option) -> impl std::future::Future>> + Send; + fn get_peers_for_client( + &self, + client: &SocketAddr, + limit: Option, + ) -> impl std::future::Future>> + Send; + fn upsert_peer(self, peer: &peer::Peer) -> impl std::future::Future + Send; + fn remove_inactive_peers(self, current_cutoff: DurationSinceUnixEpoch) -> impl std::future::Future + Send; +} + +/// A data structure containing all the information about a torrent in the tracker. +/// +/// This is the tracker entry for a given torrent and contains the swarm data, +/// that's the list of all the peers trying to download the same torrent. +/// The tracker keeps one entry like this for every torrent. +#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Torrent { + /// A network of peers that are all trying to download the torrent associated to this entry + pub(crate) swarm: PeerList, + /// The number of peers that have ever completed downloading the torrent associated to this entry + pub(crate) downloaded: u32, +} diff --git a/packages/torrent-repository-benchmarking/src/entry/mutex_parking_lot.rs b/packages/torrent-repository-benchmarking/src/entry/mutex_parking_lot.rs new file mode 100644 index 000000000..738c3ff9d --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/entry/mutex_parking_lot.rs @@ -0,0 +1,49 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +use super::{Entry, EntrySync}; +use crate::{EntryMutexParkingLot, EntrySingle}; + +impl EntrySync for EntryMutexParkingLot { + fn get_swarm_metadata(&self) -> SwarmMetadata { + self.lock().get_swarm_metadata() + } + + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + self.lock().meets_retaining_policy(policy) + } + + fn peers_is_empty(&self) -> bool { + self.lock().peers_is_empty() + } + + fn get_peers_len(&self) -> usize { + self.lock().get_peers_len() + } + + fn get_peers(&self, limit: Option) -> Vec> { + self.lock().get_peers(limit) + } + + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + self.lock().get_peers_for_client(client, limit) + } + + fn upsert_peer(&self, peer: &peer::Peer) -> bool { + self.lock().upsert_peer(peer) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + self.lock().remove_inactive_peers(current_cutoff); + } +} + +impl From for EntryMutexParkingLot { + fn from(entry: EntrySingle) -> Self { + Arc::new(parking_lot::Mutex::new(entry)) + } +} diff --git a/packages/torrent-repository-benchmarking/src/entry/mutex_std.rs b/packages/torrent-repository-benchmarking/src/entry/mutex_std.rs new file mode 100644 index 000000000..0ab70a96f --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/entry/mutex_std.rs @@ -0,0 +1,51 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +use super::{Entry, EntrySync}; +use crate::{EntryMutexStd, EntrySingle}; + +impl EntrySync for EntryMutexStd { + fn get_swarm_metadata(&self) -> SwarmMetadata { + self.lock().expect("it should get a lock").get_swarm_metadata() + } + + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + self.lock().expect("it should get a lock").meets_retaining_policy(policy) + } + + fn peers_is_empty(&self) -> bool { + self.lock().expect("it should get a lock").peers_is_empty() + } + + fn get_peers_len(&self) -> usize { + self.lock().expect("it should get a lock").get_peers_len() + } + + fn get_peers(&self, limit: Option) -> Vec> { + self.lock().expect("it should get lock").get_peers(limit) + } + + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + self.lock().expect("it should get lock").get_peers_for_client(client, limit) + } + + fn upsert_peer(&self, peer: &peer::Peer) -> bool { + self.lock().expect("it should lock the entry").upsert_peer(peer) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + self.lock() + .expect("it should lock the entry") + .remove_inactive_peers(current_cutoff); + } +} + +impl From for EntryMutexStd { + fn from(entry: EntrySingle) -> Self { + Arc::new(std::sync::Mutex::new(entry)) + } +} diff --git a/packages/torrent-repository-benchmarking/src/entry/mutex_tokio.rs b/packages/torrent-repository-benchmarking/src/entry/mutex_tokio.rs new file mode 100644 index 000000000..6db789a72 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/entry/mutex_tokio.rs @@ -0,0 +1,49 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +use super::{Entry, EntryAsync}; +use crate::{EntryMutexTokio, EntrySingle}; + +impl EntryAsync for EntryMutexTokio { + async fn get_swarm_metadata(&self) -> SwarmMetadata { + self.lock().await.get_swarm_metadata() + } + + async fn meets_retaining_policy(self, policy: &TrackerPolicy) -> bool { + self.lock().await.meets_retaining_policy(policy) + } + + async fn peers_is_empty(&self) -> bool { + self.lock().await.peers_is_empty() + } + + async fn get_peers_len(&self) -> usize { + self.lock().await.get_peers_len() + } + + async fn get_peers(&self, limit: Option) -> Vec> { + self.lock().await.get_peers(limit) + } + + async fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + self.lock().await.get_peers_for_client(client, limit) + } + + async fn upsert_peer(self, peer: &peer::Peer) -> bool { + self.lock().await.upsert_peer(peer) + } + + async fn remove_inactive_peers(self, current_cutoff: DurationSinceUnixEpoch) { + self.lock().await.remove_inactive_peers(current_cutoff); + } +} + +impl From for EntryMutexTokio { + fn from(entry: EntrySingle) -> Self { + Arc::new(tokio::sync::Mutex::new(entry)) + } +} diff --git a/packages/torrent-repository-benchmarking/src/entry/peer_list.rs b/packages/torrent-repository-benchmarking/src/entry/peer_list.rs new file mode 100644 index 000000000..976e89d03 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/entry/peer_list.rs @@ -0,0 +1,286 @@ +//! A peer list. +use std::net::SocketAddr; +use std::sync::Arc; + +use aquatic_udp_protocol::PeerId; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +// code-review: the current implementation uses the peer Id as the ``BTreeMap`` +// key. That would allow adding two identical peers except for the Id. +// For example, two peers with the same socket address but a different peer Id +// would be allowed. That would lead to duplicated peers in the tracker responses. + +#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct PeerList { + peers: std::collections::BTreeMap>, +} + +impl PeerList { + #[must_use] + pub fn len(&self) -> usize { + self.peers.len() + } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.peers.is_empty() + } + + pub fn upsert(&mut self, value: Arc) -> Option> { + self.peers.insert(value.peer_id, value) + } + + pub fn remove(&mut self, key: &PeerId) -> Option> { + self.peers.remove(key) + } + + pub fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { + self.peers + .retain(|_, peer| peer::ReadInfo::get_updated(peer) > current_cutoff); + } + + #[must_use] + pub fn get(&self, peer_id: &PeerId) -> Option<&Arc> { + self.peers.get(peer_id) + } + + #[must_use] + pub fn get_all(&self, limit: Option) -> Vec> { + match limit { + Some(limit) => self.peers.values().take(limit).cloned().collect(), + None => self.peers.values().cloned().collect(), + } + } + + #[must_use] + pub fn seeders_and_leechers(&self) -> (usize, usize) { + let seeders = self.peers.values().filter(|peer| peer.is_seeder()).count(); + let leechers = self.len() - seeders; + + (seeders, leechers) + } + + #[must_use] + pub fn get_peers_excluding_addr(&self, peer_addr: &SocketAddr, limit: Option) -> Vec> { + match limit { + Some(limit) => self + .peers + .values() + // Take peers which are not the client peer + .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *peer_addr) + // Limit the number of peers on the result + .take(limit) + .cloned() + .collect(), + None => self + .peers + .values() + // Take peers which are not the client peer + .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *peer_addr) + .cloned() + .collect(), + } + } +} + +#[cfg(test)] +mod tests { + + mod it_should { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::PeerId; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::entry::peer_list::PeerList; + + #[test] + fn be_empty_when_no_peers_have_been_inserted() { + let peer_list = PeerList::default(); + + assert!(peer_list.is_empty()); + } + + #[test] + fn have_zero_length_when_no_peers_have_been_inserted() { + let peer_list = PeerList::default(); + + assert_eq!(peer_list.len(), 0); + } + + #[test] + fn allow_inserting_a_new_peer() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + assert_eq!(peer_list.upsert(peer.into()), None); + } + + #[test] + fn allow_updating_a_preexisting_peer() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + assert_eq!(peer_list.upsert(peer.into()), Some(Arc::new(peer))); + } + + #[test] + fn allow_getting_all_peers() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + assert_eq!(peer_list.get_all(None), [Arc::new(peer)]); + } + + #[test] + fn allow_getting_one_peer_by_id() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + assert_eq!(peer_list.get(&peer.peer_id), Some(Arc::new(peer)).as_ref()); + } + + #[test] + fn increase_the_number_of_peers_after_inserting_a_new_one() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + assert_eq!(peer_list.len(), 1); + } + + #[test] + fn decrease_the_number_of_peers_after_removing_one() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + peer_list.remove(&peer.peer_id); + + assert!(peer_list.is_empty()); + } + + #[test] + fn allow_removing_an_existing_peer() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + peer_list.remove(&peer.peer_id); + + assert_eq!(peer_list.get(&peer.peer_id), None); + } + + #[test] + fn allow_getting_all_peers_excluding_peers_with_a_given_address() { + let mut peer_list = PeerList::default(); + + let peer1 = PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000001")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 6969)) + .build(); + peer_list.upsert(peer1.into()); + + let peer2 = PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000002")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) + .build(); + peer_list.upsert(peer2.into()); + + assert_eq!(peer_list.get_peers_excluding_addr(&peer2.peer_addr, None), [Arc::new(peer1)]); + } + + #[test] + fn return_the_number_of_seeders_in_the_list() { + let mut peer_list = PeerList::default(); + + let seeder = PeerBuilder::seeder().build(); + let leecher = PeerBuilder::leecher().build(); + + peer_list.upsert(seeder.into()); + peer_list.upsert(leecher.into()); + + let (seeders, _leechers) = peer_list.seeders_and_leechers(); + + assert_eq!(seeders, 1); + } + + #[test] + fn return_the_number_of_leechers_in_the_list() { + let mut peer_list = PeerList::default(); + + let seeder = PeerBuilder::seeder().build(); + let leecher = PeerBuilder::leecher().build(); + + peer_list.upsert(seeder.into()); + peer_list.upsert(leecher.into()); + + let (_seeders, leechers) = peer_list.seeders_and_leechers(); + + assert_eq!(leechers, 1); + } + + #[test] + fn remove_inactive_peers() { + let mut peer_list = PeerList::default(); + let one_second = DurationSinceUnixEpoch::new(1, 0); + + // Insert the peer + let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); + let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); + peer_list.upsert(peer.into()); + + // Remove peers not updated since one second after inserting the peer + peer_list.remove_inactive_peers(last_update_time + one_second); + + assert_eq!(peer_list.len(), 0); + } + + #[test] + fn not_remove_active_peers() { + let mut peer_list = PeerList::default(); + let one_second = DurationSinceUnixEpoch::new(1, 0); + + // Insert the peer + let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); + let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); + peer_list.upsert(peer.into()); + + // Remove peers not updated since one second before inserting the peer. + peer_list.remove_inactive_peers(last_update_time.checked_sub(one_second).unwrap()); + + assert_eq!(peer_list.len(), 1); + } + + #[test] + fn allow_inserting_two_identical_peers_except_for_the_id() { + let mut peer_list = PeerList::default(); + + let peer1 = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000001")).build(); + peer_list.upsert(peer1.into()); + + let peer2 = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000002")).build(); + peer_list.upsert(peer2.into()); + + assert_eq!(peer_list.len(), 2); + } + } +} diff --git a/packages/torrent-repository-benchmarking/src/entry/rw_lock_parking_lot.rs b/packages/torrent-repository-benchmarking/src/entry/rw_lock_parking_lot.rs new file mode 100644 index 000000000..ac0dc0b30 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/entry/rw_lock_parking_lot.rs @@ -0,0 +1,49 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +use super::{Entry, EntrySync}; +use crate::{EntryRwLockParkingLot, EntrySingle}; + +impl EntrySync for EntryRwLockParkingLot { + fn get_swarm_metadata(&self) -> SwarmMetadata { + self.read().get_swarm_metadata() + } + + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + self.read().meets_retaining_policy(policy) + } + + fn peers_is_empty(&self) -> bool { + self.read().peers_is_empty() + } + + fn get_peers_len(&self) -> usize { + self.read().get_peers_len() + } + + fn get_peers(&self, limit: Option) -> Vec> { + self.read().get_peers(limit) + } + + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + self.read().get_peers_for_client(client, limit) + } + + fn upsert_peer(&self, peer: &peer::Peer) -> bool { + self.write().upsert_peer(peer) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + self.write().remove_inactive_peers(current_cutoff); + } +} + +impl From for EntryRwLockParkingLot { + fn from(entry: EntrySingle) -> Self { + Arc::new(parking_lot::RwLock::new(entry)) + } +} diff --git a/packages/torrent-repository-benchmarking/src/entry/single.rs b/packages/torrent-repository-benchmarking/src/entry/single.rs new file mode 100644 index 000000000..0f922bd02 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/entry/single.rs @@ -0,0 +1,81 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use aquatic_udp_protocol::AnnounceEvent; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::peer::{self}; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::Entry; +use crate::EntrySingle; + +impl Entry for EntrySingle { + #[allow(clippy::cast_possible_truncation)] + fn get_swarm_metadata(&self) -> SwarmMetadata { + let (seeders, leechers) = self.swarm.seeders_and_leechers(); + + SwarmMetadata { + downloaded: self.downloaded, + complete: seeders as u32, + incomplete: leechers as u32, + } + } + + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + if policy.persistent_torrent_completed_stat && self.downloaded > 0 { + return true; + } + + if policy.remove_peerless_torrents && self.swarm.is_empty() { + return false; + } + + true + } + + fn peers_is_empty(&self) -> bool { + self.swarm.is_empty() + } + + fn get_peers_len(&self) -> usize { + self.swarm.len() + } + + fn get_peers(&self, limit: Option) -> Vec> { + self.swarm.get_all(limit) + } + + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + self.swarm.get_peers_excluding_addr(client, limit) + } + + fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { + let mut number_of_downloads_increased: bool = false; + + match peer::ReadInfo::get_event(peer) { + AnnounceEvent::Stopped => { + drop(self.swarm.remove(&peer::ReadInfo::get_id(peer))); + } + AnnounceEvent::Completed => { + let previous = self.swarm.upsert(Arc::new(*peer)); + // Don't count if peer was not previously known and not already completed. + if previous.is_some_and(|p| p.event != AnnounceEvent::Completed) { + self.downloaded += 1; + number_of_downloads_increased = true; + } + } + _ => { + // `Started` event (first announced event) or + // `None` event (announcements done at regular intervals). + drop(self.swarm.upsert(Arc::new(*peer))); + } + } + + number_of_downloads_increased + } + + fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { + self.swarm.remove_inactive_peers(current_cutoff); + } +} diff --git a/packages/torrent-repository-benchmarking/src/lib.rs b/packages/torrent-repository-benchmarking/src/lib.rs new file mode 100644 index 000000000..a8955808e --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/lib.rs @@ -0,0 +1,44 @@ +use std::sync::Arc; + +use repository::dash_map_mutex_std::XacrimonDashMap; +use repository::rw_lock_std::RwLockStd; +use repository::rw_lock_tokio::RwLockTokio; +use repository::skip_map_mutex_std::CrossbeamSkipList; +use torrust_tracker_clock::clock; + +pub mod entry; +pub mod repository; + +// Repo Entries + +pub type EntrySingle = entry::Torrent; +pub type EntryMutexStd = Arc>; +pub type EntryMutexTokio = Arc>; +pub type EntryMutexParkingLot = Arc>; +pub type EntryRwLockParkingLot = Arc>; + +// Repos + +pub type TorrentsRwLockStd = RwLockStd; +pub type TorrentsRwLockStdMutexStd = RwLockStd; +pub type TorrentsRwLockStdMutexTokio = RwLockStd; +pub type TorrentsRwLockTokio = RwLockTokio; +pub type TorrentsRwLockTokioMutexStd = RwLockTokio; +pub type TorrentsRwLockTokioMutexTokio = RwLockTokio; + +pub type TorrentsSkipMapMutexStd = CrossbeamSkipList; +pub type TorrentsSkipMapMutexParkingLot = CrossbeamSkipList; +pub type TorrentsSkipMapRwLockParkingLot = CrossbeamSkipList; + +pub type TorrentsDashMapMutexStd = XacrimonDashMap; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs new file mode 100644 index 000000000..fec94b4a5 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs @@ -0,0 +1,111 @@ +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use dashmap::DashMap; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; + +use super::Repository; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntrySync}; +use crate::{EntryMutexStd, EntrySingle}; + +#[derive(Default, Debug)] +pub struct XacrimonDashMap { + pub torrents: DashMap, +} + +impl Repository for XacrimonDashMap +where + EntryMutexStd: EntrySync, + EntrySingle: Entry, +{ + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + // todo: load persistent torrent data if provided + + if let Some(entry) = self.torrents.get(info_hash) { + entry.upsert_peer(peer) + } else { + let _unused = self.torrents.insert(*info_hash, Arc::default()); + if let Some(entry) = self.torrents.get(info_hash) { + entry.upsert_peer(peer) + } else { + false + } + } + } + + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.torrents.get(info_hash).map(|entry| entry.value().get_swarm_metadata()) + } + + fn get(&self, key: &InfoHash) -> Option { + let maybe_entry = self.torrents.get(key); + maybe_entry.map(|entry| entry.clone()) + } + + fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); + + for entry in &self.torrents { + let stats = entry.value().lock().expect("it should get a lock").get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { + match pagination { + Some(pagination) => self + .torrents + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + None => self + .torrents + .iter() + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { + for (info_hash, completed) in persistent_torrents { + if self.torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexStd::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + self.torrents.insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + self.torrents.remove(key).map(|(_key, value)| value.clone()) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + for entry in &self.torrents { + entry.value().remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + self.torrents.retain(|_, entry| entry.meets_retaining_policy(policy)); + } +} diff --git a/packages/torrent-repository-benchmarking/src/repository/mod.rs b/packages/torrent-repository-benchmarking/src/repository/mod.rs new file mode 100644 index 000000000..cf58838a1 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/mod.rs @@ -0,0 +1,46 @@ +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; + +pub mod dash_map_mutex_std; +pub mod rw_lock_std; +pub mod rw_lock_std_mutex_std; +pub mod rw_lock_std_mutex_tokio; +pub mod rw_lock_tokio; +pub mod rw_lock_tokio_mutex_std; +pub mod rw_lock_tokio_mutex_tokio; +pub mod skip_map_mutex_std; + +use std::fmt::Debug; + +pub trait Repository: Debug + Default + Sized + 'static { + fn get(&self, key: &InfoHash) -> Option; + fn get_metrics(&self) -> AggregateActiveSwarmMetadata; + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, T)>; + fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap); + fn remove(&self, key: &InfoHash) -> Option; + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch); + fn remove_peerless_torrents(&self, policy: &TrackerPolicy); + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option) -> bool; + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option; +} + +#[allow(clippy::module_name_repetitions)] +pub trait RepositoryAsync: Debug + Default + Sized + 'static { + fn get(&self, key: &InfoHash) -> impl std::future::Future> + Send; + fn get_metrics(&self) -> impl std::future::Future + Send; + fn get_paginated(&self, pagination: Option<&Pagination>) -> impl std::future::Future> + Send; + fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) -> impl std::future::Future + Send; + fn remove(&self, key: &InfoHash) -> impl std::future::Future> + Send; + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> impl std::future::Future + Send; + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) -> impl std::future::Future + Send; + fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + opt_persistent_torrent: Option, + ) -> impl std::future::Future + Send; + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> impl std::future::Future> + Send; +} diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs new file mode 100644 index 000000000..5000579dd --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs @@ -0,0 +1,132 @@ +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; + +use super::Repository; +use crate::entry::peer_list::PeerList; +use crate::entry::Entry; +use crate::{EntrySingle, TorrentsRwLockStd}; + +#[derive(Default, Debug)] +pub struct RwLockStd { + pub(crate) torrents: std::sync::RwLock>, +} + +impl RwLockStd { + /// # Panics + /// + /// Panics if unable to get a lock. + pub fn write( + &self, + ) -> std::sync::RwLockWriteGuard<'_, std::collections::BTreeMap> { + self.torrents.write().expect("it should get lock") + } +} + +impl TorrentsRwLockStd { + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("it should get the read lock") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("it should get the write lock") + } +} + +impl Repository for TorrentsRwLockStd +where + EntrySingle: Entry, +{ + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + // todo: load persistent torrent data if provided + + let mut db = self.get_torrents_mut(); + + let entry = db.entry(*info_hash).or_insert(EntrySingle::default()); + + entry.upsert_peer(peer) + } + + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.get(info_hash).map(|entry| entry.get_swarm_metadata()) + } + + fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents(); + db.get(key).cloned() + } + + fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); + + for entry in self.get_torrents().values() { + let stats = entry.get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntrySingle)> { + let db = self.get_torrents(); + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { + let mut torrents = self.get_torrents_mut(); + + for (info_hash, downloaded) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = EntrySingle { + swarm: PeerList::default(), + downloaded: *downloaded, + }; + + torrents.insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut(); + db.remove(key) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let mut db = self.get_torrents_mut(); + let entries = db.values_mut(); + + for entry in entries { + entry.remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut(); + + db.retain(|_, e| e.meets_retaining_policy(policy)); + } +} diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs new file mode 100644 index 000000000..085256ff1 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs @@ -0,0 +1,130 @@ +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; + +use super::Repository; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntrySync}; +use crate::{EntryMutexStd, EntrySingle, TorrentsRwLockStdMutexStd}; + +impl TorrentsRwLockStdMutexStd { + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("unable to get torrent list") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("unable to get writable torrent list") + } +} + +impl Repository for TorrentsRwLockStdMutexStd +where + EntryMutexStd: EntrySync, + EntrySingle: Entry, +{ + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + // todo: load persistent torrent data if provided + + let maybe_entry = self.get_torrents().get(info_hash).cloned(); + + let entry = if let Some(entry) = maybe_entry { + entry + } else { + let mut db = self.get_torrents_mut(); + let entry = db.entry(*info_hash).or_insert(Arc::default()); + entry.clone() + }; + + entry.upsert_peer(peer) + } + + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.get_torrents() + .get(info_hash) + .map(super::super::entry::EntrySync::get_swarm_metadata) + } + + fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents(); + db.get(key).cloned() + } + + fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); + + for entry in self.get_torrents().values() { + let stats = entry.lock().expect("it should get a lock").get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { + let db = self.get_torrents(); + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { + let mut torrents = self.get_torrents_mut(); + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexStd::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + torrents.insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut(); + db.remove(key) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let db = self.get_torrents(); + let entries = db.values().cloned(); + + for entry in entries { + entry.remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut(); + + db.retain(|_, e| e.lock().expect("it should lock entry").meets_retaining_policy(policy)); + } +} diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs new file mode 100644 index 000000000..9fd451149 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs @@ -0,0 +1,167 @@ +use std::iter::zip; +use std::pin::Pin; +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use futures::future::join_all; +use futures::{Future, FutureExt}; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; + +use super::RepositoryAsync; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntryAsync}; +use crate::{EntryMutexTokio, EntrySingle, TorrentsRwLockStdMutexTokio}; + +impl TorrentsRwLockStdMutexTokio { + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("unable to get torrent list") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("unable to get writable torrent list") + } +} + +impl RepositoryAsync for TorrentsRwLockStdMutexTokio +where + EntryMutexTokio: EntryAsync, + EntrySingle: Entry, +{ + async fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + _opt_persistent_torrent: Option, + ) -> bool { + // todo: load persistent torrent data if provided + + let maybe_entry = self.get_torrents().get(info_hash).cloned(); + + let entry = if let Some(entry) = maybe_entry { + entry + } else { + let mut db = self.get_torrents_mut(); + let entry = db.entry(*info_hash).or_insert(Arc::default()); + entry.clone() + }; + + entry.upsert_peer(peer).await + } + + async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + let maybe_entry = self.get_torrents().get(info_hash).cloned(); + + match maybe_entry { + Some(entry) => Some(entry.get_swarm_metadata().await), + None => None, + } + } + + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents(); + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexTokio)> { + let db = self.get_torrents(); + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); + + let entries: Vec<_> = self.get_torrents().values().cloned().collect(); + + for entry in entries { + let stats = entry.lock().await.get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + async fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { + let mut db = self.get_torrents_mut(); + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if db.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexTokio::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + db.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut(); + db.remove(key) + } + + async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let handles: Vec + Send>>>; + { + let db = self.get_torrents(); + handles = db + .values() + .cloned() + .map(|e| e.remove_inactive_peers(current_cutoff).boxed()) + .collect(); + } + join_all(handles).await; + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let handles: Vec> + Send>>>; + + { + let db = self.get_torrents(); + + handles = zip(db.keys().copied(), db.values().cloned()) + .map(|(infohash, torrent)| { + torrent + .meets_retaining_policy(policy) + .map(move |should_be_retained| if should_be_retained { None } else { Some(infohash) }) + .boxed() + }) + .collect::>(); + } + + let not_good = join_all(handles).await; + + let mut db = self.get_torrents_mut(); + + for remove in not_good.into_iter().flatten() { + drop(db.remove(&remove)); + } + } +} diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs new file mode 100644 index 000000000..e85200aeb --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs @@ -0,0 +1,138 @@ +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; + +use super::RepositoryAsync; +use crate::entry::peer_list::PeerList; +use crate::entry::Entry; +use crate::{EntrySingle, TorrentsRwLockTokio}; + +#[derive(Default, Debug)] +pub struct RwLockTokio { + pub(crate) torrents: tokio::sync::RwLock>, +} + +impl RwLockTokio { + pub fn write( + &self, + ) -> impl std::future::Future< + Output = tokio::sync::RwLockWriteGuard<'_, std::collections::BTreeMap>, + > { + self.torrents.write() + } +} + +impl TorrentsRwLockTokio { + async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>( + &'a self, + ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl RepositoryAsync for TorrentsRwLockTokio +where + EntrySingle: Entry, +{ + async fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + _opt_persistent_torrent: Option, + ) -> bool { + // todo: load persistent torrent data if provided + + let mut db = self.get_torrents_mut().await; + + let entry = db.entry(*info_hash).or_insert(EntrySingle::default()); + + entry.upsert_peer(peer) + } + + async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.get(info_hash).await.map(|entry| entry.get_swarm_metadata()) + } + + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents().await; + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntrySingle)> { + let db = self.get_torrents().await; + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); + + for entry in self.get_torrents().await.values() { + let stats = entry.get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + async fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { + let mut torrents = self.get_torrents_mut().await; + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + }; + + torrents.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut().await; + db.remove(key) + } + + async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let mut db = self.get_torrents_mut().await; + let entries = db.values_mut(); + + for entry in entries { + entry.remove_inactive_peers(current_cutoff); + } + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut().await; + + db.retain(|_, e| e.meets_retaining_policy(policy)); + } +} diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs new file mode 100644 index 000000000..8d6584713 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs @@ -0,0 +1,135 @@ +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; + +use super::RepositoryAsync; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntrySync}; +use crate::{EntryMutexStd, EntrySingle, TorrentsRwLockTokioMutexStd}; + +impl TorrentsRwLockTokioMutexStd { + async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>( + &'a self, + ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl RepositoryAsync for TorrentsRwLockTokioMutexStd +where + EntryMutexStd: EntrySync, + EntrySingle: Entry, +{ + async fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + _opt_persistent_torrent: Option, + ) -> bool { + // todo: load persistent torrent data if provided + + let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); + + let entry = if let Some(entry) = maybe_entry { + entry + } else { + let mut db = self.get_torrents_mut().await; + let entry = db.entry(*info_hash).or_insert(Arc::default()); + entry.clone() + }; + + entry.upsert_peer(peer) + } + + async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.get(info_hash).await.map(|entry| entry.get_swarm_metadata()) + } + + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents().await; + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { + let db = self.get_torrents().await; + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); + + for entry in self.get_torrents().await.values() { + let stats = entry.get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + async fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { + let mut torrents = self.get_torrents_mut().await; + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexStd::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + torrents.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut().await; + db.remove(key) + } + + async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let db = self.get_torrents().await; + let entries = db.values().cloned(); + + for entry in entries { + entry.remove_inactive_peers(current_cutoff); + } + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut().await; + + db.retain(|_, e| e.lock().expect("it should lock entry").meets_retaining_policy(policy)); + } +} diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs new file mode 100644 index 000000000..c8f499e03 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs @@ -0,0 +1,148 @@ +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; + +use super::RepositoryAsync; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntryAsync}; +use crate::{EntryMutexTokio, EntrySingle, TorrentsRwLockTokioMutexTokio}; + +impl TorrentsRwLockTokioMutexTokio { + async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>( + &'a self, + ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl RepositoryAsync for TorrentsRwLockTokioMutexTokio +where + EntryMutexTokio: EntryAsync, + EntrySingle: Entry, +{ + async fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + _opt_persistent_torrent: Option, + ) -> bool { + // todo: load persistent torrent data if provided + + let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); + + let entry = if let Some(entry) = maybe_entry { + entry + } else { + let mut db = self.get_torrents_mut().await; + let entry = db.entry(*info_hash).or_insert(Arc::default()); + entry.clone() + }; + + entry.upsert_peer(peer).await + } + + async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + match self.get(info_hash).await { + Some(entry) => Some(entry.get_swarm_metadata().await), + None => None, + } + } + + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents().await; + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexTokio)> { + let db = self.get_torrents().await; + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); + + for entry in self.get_torrents().await.values() { + let stats = entry.get_swarm_metadata().await; + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + async fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { + let mut db = self.get_torrents_mut().await; + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if db.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexTokio::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + db.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut().await; + db.remove(key) + } + + async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let db = self.get_torrents().await; + let entries = db.values().cloned(); + + for entry in entries { + entry.remove_inactive_peers(current_cutoff).await; + } + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut().await; + + let mut not_good = Vec::::default(); + + for (&infohash, torrent) in db.iter() { + if !torrent.clone().meets_retaining_policy(policy).await { + not_good.push(infohash); + } + } + + for remove in not_good { + drop(db.remove(&remove)); + } + } +} diff --git a/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs new file mode 100644 index 000000000..0432b13d0 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs @@ -0,0 +1,328 @@ +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use crossbeam_skiplist::SkipMap; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; + +use super::Repository; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntrySync}; +use crate::{EntryMutexParkingLot, EntryMutexStd, EntryRwLockParkingLot, EntrySingle}; + +#[derive(Default, Debug)] +pub struct CrossbeamSkipList { + pub torrents: SkipMap, +} + +impl Repository for CrossbeamSkipList +where + EntryMutexStd: EntrySync, + EntrySingle: Entry, +{ + /// Upsert a peer into the swarm of a torrent. + /// + /// Optionally, it can also preset the number of downloads of the torrent + /// only if it's the first time the torrent is being inserted. + /// + /// # Arguments + /// + /// * `info_hash` - The info hash of the torrent. + /// * `peer` - The peer to upsert. + /// * `opt_persistent_torrent` - The optional persisted data about a torrent + /// (number of downloads for the torrent). + /// + /// # Returns + /// + /// Returns `true` if the number of downloads was increased because the peer + /// completed the download. + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option) -> bool { + if let Some(existing_entry) = self.torrents.get(info_hash) { + existing_entry.value().upsert_peer(peer) + } else { + let new_entry = if let Some(number_of_downloads) = opt_persistent_torrent { + EntryMutexStd::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: number_of_downloads, + } + .into(), + ) + } else { + EntryMutexStd::default() + }; + + let inserted_entry = self.torrents.get_or_insert(*info_hash, new_entry); + + inserted_entry.value().upsert_peer(peer) + } + } + + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.torrents.get(info_hash).map(|entry| entry.value().get_swarm_metadata()) + } + + fn get(&self, key: &InfoHash) -> Option { + let maybe_entry = self.torrents.get(key); + maybe_entry.map(|entry| entry.value().clone()) + } + + fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); + + for entry in &self.torrents { + let stats = entry.value().lock().expect("it should get a lock").get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { + match pagination { + Some(pagination) => self + .torrents + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + None => self + .torrents + .iter() + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { + for (info_hash, completed) in persistent_torrents { + if self.torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexStd::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + // Since SkipMap is lock-free the torrent could have been inserted + // after checking if it exists. + self.torrents.get_or_insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + self.torrents.remove(key).map(|entry| entry.value().clone()) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + for entry in &self.torrents { + entry.value().remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + for entry in &self.torrents { + if entry.value().meets_retaining_policy(policy) { + continue; + } + + entry.remove(); + } + } +} + +impl Repository for CrossbeamSkipList +where + EntryRwLockParkingLot: EntrySync, + EntrySingle: Entry, +{ + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + // todo: load persistent torrent data if provided + + let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); + entry.value().upsert_peer(peer) + } + + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.torrents.get(info_hash).map(|entry| entry.value().get_swarm_metadata()) + } + + fn get(&self, key: &InfoHash) -> Option { + let maybe_entry = self.torrents.get(key); + maybe_entry.map(|entry| entry.value().clone()) + } + + fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); + + for entry in &self.torrents { + let stats = entry.value().read().get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryRwLockParkingLot)> { + match pagination { + Some(pagination) => self + .torrents + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + None => self + .torrents + .iter() + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { + for (info_hash, completed) in persistent_torrents { + if self.torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryRwLockParkingLot::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + // Since SkipMap is lock-free the torrent could have been inserted + // after checking if it exists. + self.torrents.get_or_insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + self.torrents.remove(key).map(|entry| entry.value().clone()) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + for entry in &self.torrents { + entry.value().remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + for entry in &self.torrents { + if entry.value().meets_retaining_policy(policy) { + continue; + } + + entry.remove(); + } + } +} + +impl Repository for CrossbeamSkipList +where + EntryMutexParkingLot: EntrySync, + EntrySingle: Entry, +{ + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + // todo: load persistent torrent data if provided + + let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); + entry.value().upsert_peer(peer) + } + + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.torrents.get(info_hash).map(|entry| entry.value().get_swarm_metadata()) + } + + fn get(&self, key: &InfoHash) -> Option { + let maybe_entry = self.torrents.get(key); + maybe_entry.map(|entry| entry.value().clone()) + } + + fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); + + for entry in &self.torrents { + let stats = entry.value().lock().get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexParkingLot)> { + match pagination { + Some(pagination) => self + .torrents + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + None => self + .torrents + .iter() + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { + for (info_hash, completed) in persistent_torrents { + if self.torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexParkingLot::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + // Since SkipMap is lock-free the torrent could have been inserted + // after checking if it exists. + self.torrents.get_or_insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + self.torrents.remove(key).map(|entry| entry.value().clone()) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + for entry in &self.torrents { + entry.value().remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + for entry in &self.torrents { + if entry.value().meets_retaining_policy(policy) { + continue; + } + + entry.remove(); + } + } +} diff --git a/packages/torrent-repository-benchmarking/tests/common/mod.rs b/packages/torrent-repository-benchmarking/tests/common/mod.rs new file mode 100644 index 000000000..efdf7f742 --- /dev/null +++ b/packages/torrent-repository-benchmarking/tests/common/mod.rs @@ -0,0 +1,3 @@ +pub mod repo; +pub mod torrent; +pub mod torrent_peer_builder; diff --git a/packages/torrent-repository-benchmarking/tests/common/repo.rs b/packages/torrent-repository-benchmarking/tests/common/repo.rs new file mode 100644 index 000000000..2987240ef --- /dev/null +++ b/packages/torrent-repository-benchmarking/tests/common/repo.rs @@ -0,0 +1,242 @@ +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; +use torrust_tracker_torrent_repository_benchmarking::repository::{Repository as _, RepositoryAsync as _}; +use torrust_tracker_torrent_repository_benchmarking::{ + EntrySingle, TorrentsDashMapMutexStd, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, + TorrentsRwLockTokio, TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexParkingLot, + TorrentsSkipMapMutexStd, TorrentsSkipMapRwLockParkingLot, +}; + +#[derive(Debug)] +pub(crate) enum Repo { + RwLockStd(TorrentsRwLockStd), + RwLockStdMutexStd(TorrentsRwLockStdMutexStd), + RwLockStdMutexTokio(TorrentsRwLockStdMutexTokio), + RwLockTokio(TorrentsRwLockTokio), + RwLockTokioMutexStd(TorrentsRwLockTokioMutexStd), + RwLockTokioMutexTokio(TorrentsRwLockTokioMutexTokio), + SkipMapMutexStd(TorrentsSkipMapMutexStd), + SkipMapMutexParkingLot(TorrentsSkipMapMutexParkingLot), + SkipMapRwLockParkingLot(TorrentsSkipMapRwLockParkingLot), + DashMapMutexStd(TorrentsDashMapMutexStd), +} + +impl Repo { + pub(crate) async fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + opt_persistent_torrent: Option, + ) -> bool { + match self { + Repo::RwLockStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), + Repo::RwLockStdMutexStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), + Repo::RwLockStdMutexTokio(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent).await, + Repo::RwLockTokio(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent).await, + Repo::RwLockTokioMutexStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent).await, + Repo::RwLockTokioMutexTokio(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent).await, + Repo::SkipMapMutexStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), + Repo::SkipMapMutexParkingLot(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), + Repo::SkipMapRwLockParkingLot(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), + Repo::DashMapMutexStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), + } + } + + pub(crate) async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + match self { + Repo::RwLockStd(repo) => repo.get_swarm_metadata(info_hash), + Repo::RwLockStdMutexStd(repo) => repo.get_swarm_metadata(info_hash), + Repo::RwLockStdMutexTokio(repo) => repo.get_swarm_metadata(info_hash).await, + Repo::RwLockTokio(repo) => repo.get_swarm_metadata(info_hash).await, + Repo::RwLockTokioMutexStd(repo) => repo.get_swarm_metadata(info_hash).await, + Repo::RwLockTokioMutexTokio(repo) => repo.get_swarm_metadata(info_hash).await, + Repo::SkipMapMutexStd(repo) => repo.get_swarm_metadata(info_hash), + Repo::SkipMapMutexParkingLot(repo) => repo.get_swarm_metadata(info_hash), + Repo::SkipMapRwLockParkingLot(repo) => repo.get_swarm_metadata(info_hash), + Repo::DashMapMutexStd(repo) => repo.get_swarm_metadata(info_hash), + } + } + + pub(crate) async fn get(&self, key: &InfoHash) -> Option { + match self { + Repo::RwLockStd(repo) => repo.get(key), + Repo::RwLockStdMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), + Repo::RwLockStdMutexTokio(repo) => Some(repo.get(key).await?.lock().await.clone()), + Repo::RwLockTokio(repo) => repo.get(key).await, + Repo::RwLockTokioMutexStd(repo) => Some(repo.get(key).await?.lock().unwrap().clone()), + Repo::RwLockTokioMutexTokio(repo) => Some(repo.get(key).await?.lock().await.clone()), + Repo::SkipMapMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), + Repo::SkipMapMutexParkingLot(repo) => Some(repo.get(key)?.lock().clone()), + Repo::SkipMapRwLockParkingLot(repo) => Some(repo.get(key)?.read().clone()), + Repo::DashMapMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), + } + } + + pub(crate) async fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + match self { + Repo::RwLockStd(repo) => repo.get_metrics(), + Repo::RwLockStdMutexStd(repo) => repo.get_metrics(), + Repo::RwLockStdMutexTokio(repo) => repo.get_metrics().await, + Repo::RwLockTokio(repo) => repo.get_metrics().await, + Repo::RwLockTokioMutexStd(repo) => repo.get_metrics().await, + Repo::RwLockTokioMutexTokio(repo) => repo.get_metrics().await, + Repo::SkipMapMutexStd(repo) => repo.get_metrics(), + Repo::SkipMapMutexParkingLot(repo) => repo.get_metrics(), + Repo::SkipMapRwLockParkingLot(repo) => repo.get_metrics(), + Repo::DashMapMutexStd(repo) => repo.get_metrics(), + } + } + + pub(crate) async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntrySingle)> { + match self { + Repo::RwLockStd(repo) => repo.get_paginated(pagination), + Repo::RwLockStdMutexStd(repo) => repo + .get_paginated(pagination) + .iter() + .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) + .collect(), + Repo::RwLockStdMutexTokio(repo) => { + let mut v: Vec<(InfoHash, EntrySingle)> = vec![]; + + for (i, t) in repo.get_paginated(pagination).await { + v.push((i, t.lock().await.clone())); + } + v + } + Repo::RwLockTokio(repo) => repo.get_paginated(pagination).await, + Repo::RwLockTokioMutexStd(repo) => repo + .get_paginated(pagination) + .await + .iter() + .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) + .collect(), + Repo::RwLockTokioMutexTokio(repo) => { + let mut v: Vec<(InfoHash, EntrySingle)> = vec![]; + + for (i, t) in repo.get_paginated(pagination).await { + v.push((i, t.lock().await.clone())); + } + v + } + Repo::SkipMapMutexStd(repo) => repo + .get_paginated(pagination) + .iter() + .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) + .collect(), + Repo::SkipMapMutexParkingLot(repo) => repo + .get_paginated(pagination) + .iter() + .map(|(i, t)| (*i, t.lock().clone())) + .collect(), + Repo::SkipMapRwLockParkingLot(repo) => repo + .get_paginated(pagination) + .iter() + .map(|(i, t)| (*i, t.read().clone())) + .collect(), + Repo::DashMapMutexStd(repo) => repo + .get_paginated(pagination) + .iter() + .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) + .collect(), + } + } + + pub(crate) async fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { + match self { + Repo::RwLockStd(repo) => repo.import_persistent(persistent_torrents), + Repo::RwLockStdMutexStd(repo) => repo.import_persistent(persistent_torrents), + Repo::RwLockStdMutexTokio(repo) => repo.import_persistent(persistent_torrents).await, + Repo::RwLockTokio(repo) => repo.import_persistent(persistent_torrents).await, + Repo::RwLockTokioMutexStd(repo) => repo.import_persistent(persistent_torrents).await, + Repo::RwLockTokioMutexTokio(repo) => repo.import_persistent(persistent_torrents).await, + Repo::SkipMapMutexStd(repo) => repo.import_persistent(persistent_torrents), + Repo::SkipMapMutexParkingLot(repo) => repo.import_persistent(persistent_torrents), + Repo::SkipMapRwLockParkingLot(repo) => repo.import_persistent(persistent_torrents), + Repo::DashMapMutexStd(repo) => repo.import_persistent(persistent_torrents), + } + } + + pub(crate) async fn remove(&self, key: &InfoHash) -> Option { + match self { + Repo::RwLockStd(repo) => repo.remove(key), + Repo::RwLockStdMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), + Repo::RwLockStdMutexTokio(repo) => Some(repo.remove(key).await?.lock().await.clone()), + Repo::RwLockTokio(repo) => repo.remove(key).await, + Repo::RwLockTokioMutexStd(repo) => Some(repo.remove(key).await?.lock().unwrap().clone()), + Repo::RwLockTokioMutexTokio(repo) => Some(repo.remove(key).await?.lock().await.clone()), + Repo::SkipMapMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), + Repo::SkipMapMutexParkingLot(repo) => Some(repo.remove(key)?.lock().clone()), + Repo::SkipMapRwLockParkingLot(repo) => Some(repo.remove(key)?.write().clone()), + Repo::DashMapMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), + } + } + + pub(crate) async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + match self { + Repo::RwLockStd(repo) => repo.remove_inactive_peers(current_cutoff), + Repo::RwLockStdMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), + Repo::RwLockStdMutexTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, + Repo::RwLockTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, + Repo::RwLockTokioMutexStd(repo) => repo.remove_inactive_peers(current_cutoff).await, + Repo::RwLockTokioMutexTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, + Repo::SkipMapMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), + Repo::SkipMapMutexParkingLot(repo) => repo.remove_inactive_peers(current_cutoff), + Repo::SkipMapRwLockParkingLot(repo) => repo.remove_inactive_peers(current_cutoff), + Repo::DashMapMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), + } + } + + pub(crate) async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + match self { + Repo::RwLockStd(repo) => repo.remove_peerless_torrents(policy), + Repo::RwLockStdMutexStd(repo) => repo.remove_peerless_torrents(policy), + Repo::RwLockStdMutexTokio(repo) => repo.remove_peerless_torrents(policy).await, + Repo::RwLockTokio(repo) => repo.remove_peerless_torrents(policy).await, + Repo::RwLockTokioMutexStd(repo) => repo.remove_peerless_torrents(policy).await, + Repo::RwLockTokioMutexTokio(repo) => repo.remove_peerless_torrents(policy).await, + Repo::SkipMapMutexStd(repo) => repo.remove_peerless_torrents(policy), + Repo::SkipMapMutexParkingLot(repo) => repo.remove_peerless_torrents(policy), + Repo::SkipMapRwLockParkingLot(repo) => repo.remove_peerless_torrents(policy), + Repo::DashMapMutexStd(repo) => repo.remove_peerless_torrents(policy), + } + } + + pub(crate) async fn insert(&self, info_hash: &InfoHash, torrent: EntrySingle) -> Option { + match self { + Repo::RwLockStd(repo) => { + repo.write().insert(*info_hash, torrent); + } + Repo::RwLockStdMutexStd(repo) => { + repo.write().insert(*info_hash, torrent.into()); + } + Repo::RwLockStdMutexTokio(repo) => { + repo.write().insert(*info_hash, torrent.into()); + } + Repo::RwLockTokio(repo) => { + repo.write().await.insert(*info_hash, torrent); + } + Repo::RwLockTokioMutexStd(repo) => { + repo.write().await.insert(*info_hash, torrent.into()); + } + Repo::RwLockTokioMutexTokio(repo) => { + repo.write().await.insert(*info_hash, torrent.into()); + } + Repo::SkipMapMutexStd(repo) => { + repo.torrents.insert(*info_hash, torrent.into()); + } + Repo::SkipMapMutexParkingLot(repo) => { + repo.torrents.insert(*info_hash, torrent.into()); + } + Repo::SkipMapRwLockParkingLot(repo) => { + repo.torrents.insert(*info_hash, torrent.into()); + } + Repo::DashMapMutexStd(repo) => { + repo.torrents.insert(*info_hash, torrent.into()); + } + } + self.get(info_hash).await + } +} diff --git a/packages/torrent-repository-benchmarking/tests/common/torrent.rs b/packages/torrent-repository-benchmarking/tests/common/torrent.rs new file mode 100644 index 000000000..02874f9fc --- /dev/null +++ b/packages/torrent-repository-benchmarking/tests/common/torrent.rs @@ -0,0 +1,101 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; +use torrust_tracker_torrent_repository_benchmarking::entry::{Entry as _, EntryAsync as _, EntrySync as _}; +use torrust_tracker_torrent_repository_benchmarking::{ + EntryMutexParkingLot, EntryMutexStd, EntryMutexTokio, EntryRwLockParkingLot, EntrySingle, +}; + +#[derive(Debug, Clone)] +pub(crate) enum Torrent { + Single(EntrySingle), + MutexStd(EntryMutexStd), + MutexTokio(EntryMutexTokio), + MutexParkingLot(EntryMutexParkingLot), + RwLockParkingLot(EntryRwLockParkingLot), +} + +impl Torrent { + pub(crate) async fn get_stats(&self) -> SwarmMetadata { + match self { + Torrent::Single(entry) => entry.get_swarm_metadata(), + Torrent::MutexStd(entry) => entry.get_swarm_metadata(), + Torrent::MutexTokio(entry) => entry.clone().get_swarm_metadata().await, + Torrent::MutexParkingLot(entry) => entry.clone().get_swarm_metadata(), + Torrent::RwLockParkingLot(entry) => entry.clone().get_swarm_metadata(), + } + } + + pub(crate) async fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + match self { + Torrent::Single(entry) => entry.meets_retaining_policy(policy), + Torrent::MutexStd(entry) => entry.meets_retaining_policy(policy), + Torrent::MutexTokio(entry) => entry.clone().meets_retaining_policy(policy).await, + Torrent::MutexParkingLot(entry) => entry.meets_retaining_policy(policy), + Torrent::RwLockParkingLot(entry) => entry.meets_retaining_policy(policy), + } + } + + pub(crate) async fn peers_is_empty(&self) -> bool { + match self { + Torrent::Single(entry) => entry.peers_is_empty(), + Torrent::MutexStd(entry) => entry.peers_is_empty(), + Torrent::MutexTokio(entry) => entry.clone().peers_is_empty().await, + Torrent::MutexParkingLot(entry) => entry.peers_is_empty(), + Torrent::RwLockParkingLot(entry) => entry.peers_is_empty(), + } + } + + pub(crate) async fn get_peers_len(&self) -> usize { + match self { + Torrent::Single(entry) => entry.get_peers_len(), + Torrent::MutexStd(entry) => entry.get_peers_len(), + Torrent::MutexTokio(entry) => entry.clone().get_peers_len().await, + Torrent::MutexParkingLot(entry) => entry.get_peers_len(), + Torrent::RwLockParkingLot(entry) => entry.get_peers_len(), + } + } + + pub(crate) async fn get_peers(&self, limit: Option) -> Vec> { + match self { + Torrent::Single(entry) => entry.get_peers(limit), + Torrent::MutexStd(entry) => entry.get_peers(limit), + Torrent::MutexTokio(entry) => entry.clone().get_peers(limit).await, + Torrent::MutexParkingLot(entry) => entry.get_peers(limit), + Torrent::RwLockParkingLot(entry) => entry.get_peers(limit), + } + } + + pub(crate) async fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + match self { + Torrent::Single(entry) => entry.get_peers_for_client(client, limit), + Torrent::MutexStd(entry) => entry.get_peers_for_client(client, limit), + Torrent::MutexTokio(entry) => entry.clone().get_peers_for_client(client, limit).await, + Torrent::MutexParkingLot(entry) => entry.get_peers_for_client(client, limit), + Torrent::RwLockParkingLot(entry) => entry.get_peers_for_client(client, limit), + } + } + + pub(crate) async fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { + match self { + Torrent::Single(entry) => entry.upsert_peer(peer), + Torrent::MutexStd(entry) => entry.upsert_peer(peer), + Torrent::MutexTokio(entry) => entry.clone().upsert_peer(peer).await, + Torrent::MutexParkingLot(entry) => entry.upsert_peer(peer), + Torrent::RwLockParkingLot(entry) => entry.upsert_peer(peer), + } + } + + pub(crate) async fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { + match self { + Torrent::Single(entry) => entry.remove_inactive_peers(current_cutoff), + Torrent::MutexStd(entry) => entry.remove_inactive_peers(current_cutoff), + Torrent::MutexTokio(entry) => entry.clone().remove_inactive_peers(current_cutoff).await, + Torrent::MutexParkingLot(entry) => entry.remove_inactive_peers(current_cutoff), + Torrent::RwLockParkingLot(entry) => entry.remove_inactive_peers(current_cutoff), + } + } +} diff --git a/packages/torrent-repository-benchmarking/tests/common/torrent_peer_builder.rs b/packages/torrent-repository-benchmarking/tests/common/torrent_peer_builder.rs new file mode 100644 index 000000000..48aa981cd --- /dev/null +++ b/packages/torrent-repository-benchmarking/tests/common/torrent_peer_builder.rs @@ -0,0 +1,26 @@ +use torrust_tracker_primitives::peer::fixture::PeerBuilder; +use torrust_tracker_primitives::peer::{self}; + +/// A torrent seeder is a peer with 0 bytes left to download which +/// has not announced it has stopped +#[must_use] +pub fn a_completed_peer(id: i32) -> peer::Peer { + let peer_id = peer::Id::new(id); + PeerBuilder::default() + .with_bytes_left_to_download(0) + .with_event_completed() + .with_peer_id(&peer_id) + .into() +} + +/// A torrent leecher is a peer that is not a seeder. +/// Leecher: left > 0 OR event = Stopped +#[must_use] +pub fn a_started_peer(id: i32) -> peer::Peer { + let peer_id = peer::Id::new(id); + PeerBuilder::default() + .with_bytes_left_to_download(1) + .with_event_started() + .with_peer_id(&peer_id) + .into() +} diff --git a/packages/torrent-repository-benchmarking/tests/entry/mod.rs b/packages/torrent-repository-benchmarking/tests/entry/mod.rs new file mode 100644 index 000000000..86ca891d4 --- /dev/null +++ b/packages/torrent-repository-benchmarking/tests/entry/mod.rs @@ -0,0 +1,444 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::time::Duration; + +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; +use rstest::{fixture, rstest}; +use torrust_tracker_clock::clock::stopped::Stopped as _; +use torrust_tracker_clock::clock::{self, Time as _}; +use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; +use torrust_tracker_primitives::peer; +use torrust_tracker_primitives::peer::Peer; +use torrust_tracker_torrent_repository_benchmarking::{ + EntryMutexParkingLot, EntryMutexStd, EntryMutexTokio, EntryRwLockParkingLot, EntrySingle, +}; + +use crate::common::torrent::Torrent; +use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; +use crate::CurrentClock; + +#[fixture] +fn single() -> Torrent { + Torrent::Single(EntrySingle::default()) +} +#[fixture] +fn mutex_std() -> Torrent { + Torrent::MutexStd(EntryMutexStd::default()) +} + +#[fixture] +fn mutex_tokio() -> Torrent { + Torrent::MutexTokio(EntryMutexTokio::default()) +} + +#[fixture] +fn mutex_parking_lot() -> Torrent { + Torrent::MutexParkingLot(EntryMutexParkingLot::default()) +} + +#[fixture] +fn rw_lock_parking_lot() -> Torrent { + Torrent::RwLockParkingLot(EntryRwLockParkingLot::default()) +} + +#[fixture] +fn policy_none() -> TrackerPolicy { + TrackerPolicy::new(0, false, false) +} + +#[fixture] +fn policy_persist() -> TrackerPolicy { + TrackerPolicy::new(0, true, false) +} + +#[fixture] +fn policy_remove() -> TrackerPolicy { + TrackerPolicy::new(0, false, true) +} + +#[fixture] +fn policy_remove_persist() -> TrackerPolicy { + TrackerPolicy::new(0, true, true) +} + +pub enum Makes { + Empty, + Started, + Completed, + Downloaded, + Three, +} + +async fn make(torrent: &mut Torrent, makes: &Makes) -> Vec { + match makes { + Makes::Empty => vec![], + Makes::Started => { + let peer = a_started_peer(1); + torrent.upsert_peer(&peer).await; + vec![peer] + } + Makes::Completed => { + let peer = a_completed_peer(2); + torrent.upsert_peer(&peer).await; + vec![peer] + } + Makes::Downloaded => { + let mut peer = a_started_peer(3); + torrent.upsert_peer(&peer).await; + peer.event = AnnounceEvent::Completed; + peer.left = NumberOfBytes::new(0); + torrent.upsert_peer(&peer).await; + vec![peer] + } + Makes::Three => { + let peer_1 = a_started_peer(1); + torrent.upsert_peer(&peer_1).await; + + let peer_2 = a_completed_peer(2); + torrent.upsert_peer(&peer_2).await; + + let mut peer_3 = a_started_peer(3); + torrent.upsert_peer(&peer_3).await; + peer_3.event = AnnounceEvent::Completed; + peer_3.left = NumberOfBytes::new(0); + torrent.upsert_peer(&peer_3).await; + vec![peer_1, peer_2, peer_3] + } + } +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[tokio::test] +async fn it_should_be_empty_by_default( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + make(&mut torrent, makes).await; + + assert_eq!(torrent.get_peers_len().await, 0); +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_check_if_entry_should_be_retained_based_on_the_tracker_policy( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, + #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, +) { + make(&mut torrent, makes).await; + + let has_peers = !torrent.peers_is_empty().await; + let has_downloads = torrent.get_stats().await.downloaded != 0; + + match (policy.remove_peerless_torrents, policy.persistent_torrent_completed_stat) { + // remove torrents without peers, and keep completed download stats + (true, true) => match (has_peers, has_downloads) { + // no peers, but has downloads + // peers, with or without downloads + (false, true) | (true, true | false) => assert!(torrent.meets_retaining_policy(&policy).await), + // no peers and no downloads + (false, false) => assert!(!torrent.meets_retaining_policy(&policy).await), + }, + // remove torrents without peers and drop completed download stats + (true, false) => match (has_peers, has_downloads) { + // peers, with or without downloads + (true, true | false) => assert!(torrent.meets_retaining_policy(&policy).await), + // no peers and with or without downloads + (false, true | false) => assert!(!torrent.meets_retaining_policy(&policy).await), + }, + // keep torrents without peers, but keep or drop completed download stats + (false, true | false) => assert!(torrent.meets_retaining_policy(&policy).await), + } +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_get_peers_for_torrent_entry( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + let peers = make(&mut torrent, makes).await; + + let torrent_peers = torrent.get_peers(None).await; + + assert_eq!(torrent_peers.len(), peers.len()); + + for peer in torrent_peers { + assert!(peers.contains(&peer)); + } +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_update_a_peer(#[values(single(), mutex_std(), mutex_tokio())] mut torrent: Torrent, #[case] makes: &Makes) { + make(&mut torrent, makes).await; + + // Make and insert a new peer. + let mut peer = a_started_peer(-1); + torrent.upsert_peer(&peer).await; + + // Get the Inserted Peer by Id. + let peers = torrent.get_peers(None).await; + let original = peers + .iter() + .find(|p| peer::ReadInfo::get_id(*p) == peer::ReadInfo::get_id(&peer)) + .expect("it should find peer by id"); + + assert_eq!(original.event, AnnounceEvent::Started, "it should be as created"); + + // Announce "Completed" torrent download event. + peer.event = AnnounceEvent::Completed; + torrent.upsert_peer(&peer).await; + + // Get the Updated Peer by Id. + let peers = torrent.get_peers(None).await; + let updated = peers + .iter() + .find(|p| peer::ReadInfo::get_id(*p) == peer::ReadInfo::get_id(&peer)) + .expect("it should find peer by id"); + + assert_eq!(updated.event, AnnounceEvent::Completed, "it should be updated"); +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_remove_a_peer_upon_stopped_announcement( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + use torrust_tracker_primitives::peer::ReadInfo as _; + + make(&mut torrent, makes).await; + + let mut peer = a_started_peer(-1); + + torrent.upsert_peer(&peer).await; + + // The started peer should be inserted. + let peers = torrent.get_peers(None).await; + let original = peers + .iter() + .find(|p| p.get_id() == peer.get_id()) + .expect("it should find peer by id"); + + assert_eq!(original.event, AnnounceEvent::Started); + + // Change peer to "Stopped" and insert. + peer.event = AnnounceEvent::Stopped; + torrent.upsert_peer(&peer).await; + + // It should be removed now. + let peers = torrent.get_peers(None).await; + + assert_eq!( + peers.iter().find(|p| p.get_id() == peer.get_id()), + None, + "it should be removed" + ); +} + +#[rstest] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloaded_statistic( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + make(&mut torrent, makes).await; + let downloaded = torrent.get_stats().await.downloaded; + + let peers = torrent.get_peers(None).await; + let mut peer = **peers.first().expect("there should be a peer"); + + let is_already_completed = peer.event == AnnounceEvent::Completed; + + // Announce "Completed" torrent download event. + peer.event = AnnounceEvent::Completed; + + torrent.upsert_peer(&peer).await; + let stats = torrent.get_stats().await; + + if is_already_completed { + assert_eq!(stats.downloaded, downloaded); + } else { + assert_eq!(stats.downloaded, downloaded + 1); + } +} + +#[rstest] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_update_a_peer_as_a_seeder( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + let peers = make(&mut torrent, makes).await; + let completed = u32::try_from(peers.iter().filter(|p| p.is_seeder()).count()).expect("it_should_not_be_so_many"); + + let peers = torrent.get_peers(None).await; + let mut peer = **peers.first().expect("there should be a peer"); + + let is_already_non_left = peer.left == NumberOfBytes::new(0); + + // Set Bytes Left to Zero + peer.left = NumberOfBytes::new(0); + torrent.upsert_peer(&peer).await; + let stats = torrent.get_stats().await; + + if is_already_non_left { + // it was already complete + assert_eq!(stats.complete, completed); + } else { + // now it is complete + assert_eq!(stats.complete, completed + 1); + } +} + +#[rstest] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_update_a_peer_as_incomplete( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + let peers = make(&mut torrent, makes).await; + let incomplete = u32::try_from(peers.iter().filter(|p| !p.is_seeder()).count()).expect("it should not be so many"); + + let peers = torrent.get_peers(None).await; + let mut peer = **peers.first().expect("there should be a peer"); + + let completed_already = peer.left == NumberOfBytes::new(0); + + // Set Bytes Left to no Zero + peer.left = NumberOfBytes::new(1); + torrent.upsert_peer(&peer).await; + let stats = torrent.get_stats().await; + + if completed_already { + // now it is incomplete + assert_eq!(stats.incomplete, incomplete + 1); + } else { + // was already incomplete + assert_eq!(stats.incomplete, incomplete); + } +} + +#[rstest] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_get_peers_excluding_the_client_socket( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + make(&mut torrent, makes).await; + + let peers = torrent.get_peers(None).await; + let mut peer = **peers.first().expect("there should be a peer"); + + let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8081); + + // for this test, we should not already use this socket. + assert_ne!(peer.peer_addr, socket); + + // it should get the peer as it dose not share the socket. + assert!(torrent.get_peers_for_client(&socket, None).await.contains(&peer.into())); + + // set the address to the socket. + peer.peer_addr = socket; + torrent.upsert_peer(&peer).await; // Add peer + + // It should not include the peer that has the same socket. + assert!(!torrent.get_peers_for_client(&socket, None).await.contains(&peer.into())); +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_limit_the_number_of_peers_returned( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + make(&mut torrent, makes).await; + + // We add one more peer than the scrape limit + for peer_number in 1..=74 + 1 { + let mut peer = a_started_peer(1); + peer.peer_id = *peer::Id::new(peer_number); + torrent.upsert_peer(&peer).await; + } + + let peers = torrent.get_peers(Some(TORRENT_PEERS_LIMIT)).await; + + assert_eq!(peers.len(), 74); +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_remove_inactive_peers_beyond_cutoff( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + const TIMEOUT: Duration = Duration::from_secs(120); + const EXPIRE: Duration = Duration::from_secs(121); + + let peers = make(&mut torrent, makes).await; + + let mut peer = a_completed_peer(-1); + + let now = clock::Working::now(); + clock::Stopped::local_set(&now); + + peer.updated = now + .checked_sub(EXPIRE) + .expect("it_should_remove_inactive_peers_beyond_cutoff: EXPIRE must not exceed now"); + + torrent.upsert_peer(&peer).await; + + assert_eq!(torrent.get_peers_len().await, peers.len() + 1); + + let current_cutoff = CurrentClock::now_sub(&TIMEOUT).unwrap_or_default(); + torrent.remove_inactive_peers(current_cutoff).await; + + assert_eq!(torrent.get_peers_len().await, peers.len()); +} diff --git a/packages/torrent-repository-benchmarking/tests/integration.rs b/packages/torrent-repository-benchmarking/tests/integration.rs new file mode 100644 index 000000000..5aab67b03 --- /dev/null +++ b/packages/torrent-repository-benchmarking/tests/integration.rs @@ -0,0 +1,22 @@ +//! Integration tests. +//! +//! ```text +//! cargo test --test integration +//! ``` + +use torrust_tracker_clock::clock; + +pub mod common; +mod entry; +mod repository; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/packages/torrent-repository-benchmarking/tests/repository/mod.rs b/packages/torrent-repository-benchmarking/tests/repository/mod.rs new file mode 100644 index 000000000..fb0b8fcff --- /dev/null +++ b/packages/torrent-repository-benchmarking/tests/repository/mod.rs @@ -0,0 +1,640 @@ +use std::collections::{BTreeMap, HashSet}; +use std::hash::{DefaultHasher, Hash, Hasher}; + +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; +use bittorrent_primitives::info_hash::InfoHash; +use rstest::{fixture, rstest}; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::NumberOfDownloadsBTreeMap; +use torrust_tracker_torrent_repository_benchmarking::entry::Entry as _; +use torrust_tracker_torrent_repository_benchmarking::repository::dash_map_mutex_std::XacrimonDashMap; +use torrust_tracker_torrent_repository_benchmarking::repository::rw_lock_std::RwLockStd; +use torrust_tracker_torrent_repository_benchmarking::repository::rw_lock_tokio::RwLockTokio; +use torrust_tracker_torrent_repository_benchmarking::repository::skip_map_mutex_std::CrossbeamSkipList; +use torrust_tracker_torrent_repository_benchmarking::EntrySingle; + +use crate::common::repo::Repo; +use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; + +#[fixture] +fn standard() -> Repo { + Repo::RwLockStd(RwLockStd::default()) +} + +#[fixture] +fn standard_mutex() -> Repo { + Repo::RwLockStdMutexStd(RwLockStd::default()) +} + +#[fixture] +fn standard_tokio() -> Repo { + Repo::RwLockStdMutexTokio(RwLockStd::default()) +} + +#[fixture] +fn tokio_std() -> Repo { + Repo::RwLockTokio(RwLockTokio::default()) +} + +#[fixture] +fn tokio_mutex() -> Repo { + Repo::RwLockTokioMutexStd(RwLockTokio::default()) +} + +#[fixture] +fn tokio_tokio() -> Repo { + Repo::RwLockTokioMutexTokio(RwLockTokio::default()) +} + +#[fixture] +fn skip_list_mutex_std() -> Repo { + Repo::SkipMapMutexStd(CrossbeamSkipList::default()) +} + +#[fixture] +fn skip_list_mutex_parking_lot() -> Repo { + Repo::SkipMapMutexParkingLot(CrossbeamSkipList::default()) +} + +#[fixture] +fn skip_list_rw_lock_parking_lot() -> Repo { + Repo::SkipMapRwLockParkingLot(CrossbeamSkipList::default()) +} + +#[fixture] +fn dash_map_std() -> Repo { + Repo::DashMapMutexStd(XacrimonDashMap::default()) +} + +type Entries = Vec<(InfoHash, EntrySingle)>; + +#[fixture] +fn empty() -> Entries { + vec![] +} + +#[fixture] +fn default() -> Entries { + vec![(InfoHash::default(), EntrySingle::default())] +} + +#[fixture] +fn started() -> Entries { + let mut torrent = EntrySingle::default(); + torrent.upsert_peer(&a_started_peer(1)); + vec![(InfoHash::default(), torrent)] +} + +#[fixture] +fn completed() -> Entries { + let mut torrent = EntrySingle::default(); + torrent.upsert_peer(&a_completed_peer(2)); + vec![(InfoHash::default(), torrent)] +} + +#[fixture] +fn downloaded() -> Entries { + let mut torrent = EntrySingle::default(); + let mut peer = a_started_peer(3); + torrent.upsert_peer(&peer); + peer.event = AnnounceEvent::Completed; + peer.left = NumberOfBytes::new(0); + torrent.upsert_peer(&peer); + vec![(InfoHash::default(), torrent)] +} + +#[fixture] +fn three() -> Entries { + let mut started = EntrySingle::default(); + let started_h = &mut DefaultHasher::default(); + started.upsert_peer(&a_started_peer(1)); + started.hash(started_h); + + let mut completed = EntrySingle::default(); + let completed_h = &mut DefaultHasher::default(); + completed.upsert_peer(&a_completed_peer(2)); + completed.hash(completed_h); + + let mut downloaded = EntrySingle::default(); + let downloaded_h = &mut DefaultHasher::default(); + let mut downloaded_peer = a_started_peer(3); + downloaded.upsert_peer(&downloaded_peer); + downloaded_peer.event = AnnounceEvent::Completed; + downloaded_peer.left = NumberOfBytes::new(0); + downloaded.upsert_peer(&downloaded_peer); + downloaded.hash(downloaded_h); + + vec![ + (InfoHash::from(&started_h.clone()), started), + (InfoHash::from(&completed_h.clone()), completed), + (InfoHash::from(&downloaded_h.clone()), downloaded), + ] +} + +#[fixture] +fn many_out_of_order() -> Entries { + let mut entries: HashSet<(InfoHash, EntrySingle)> = HashSet::default(); + + for i in 0..408 { + let mut entry = EntrySingle::default(); + entry.upsert_peer(&a_started_peer(i)); + + entries.insert((InfoHash::from(&i), entry)); + } + + // we keep the random order from the hashed set for the vector. + entries.iter().map(|(i, e)| (*i, e.clone())).collect() +} + +#[fixture] +fn many_hashed_in_order() -> Entries { + let mut entries: BTreeMap = BTreeMap::default(); + + for i in 0..408 { + let mut entry = EntrySingle::default(); + entry.upsert_peer(&a_started_peer(i)); + + let hash: &mut DefaultHasher = &mut DefaultHasher::default(); + hash.write_i32(i); + + entries.insert(InfoHash::from(&hash.clone()), entry); + } + + // We return the entries in-order from from the b-tree map. + entries.iter().map(|(i, e)| (*i, e.clone())).collect() +} + +#[fixture] +fn persistent_empty() -> NumberOfDownloadsBTreeMap { + NumberOfDownloadsBTreeMap::default() +} + +#[fixture] +fn persistent_single() -> NumberOfDownloadsBTreeMap { + let hash = &mut DefaultHasher::default(); + + hash.write_u8(1); + let t = [(InfoHash::from(&hash.clone()), 0_u32)]; + + t.iter().copied().collect() +} + +#[fixture] +fn persistent_three() -> NumberOfDownloadsBTreeMap { + let hash = &mut DefaultHasher::default(); + + hash.write_u8(1); + let info_1 = InfoHash::from(&hash.clone()); + hash.write_u8(2); + let info_2 = InfoHash::from(&hash.clone()); + hash.write_u8(3); + let info_3 = InfoHash::from(&hash.clone()); + + let t = [(info_1, 1_u32), (info_2, 2_u32), (info_3, 3_u32)]; + + t.iter().copied().collect() +} + +async fn make(repo: &Repo, entries: &Entries) { + for (info_hash, entry) in entries { + repo.insert(info_hash, entry.clone()).await; + } +} + +#[fixture] +fn paginated_limit_zero() -> Pagination { + Pagination::new(0, 0) +} + +#[fixture] +fn paginated_limit_one() -> Pagination { + Pagination::new(0, 1) +} + +#[fixture] +fn paginated_limit_one_offset_one() -> Pagination { + Pagination::new(1, 1) +} + +#[fixture] +fn policy_none() -> TrackerPolicy { + TrackerPolicy::new(0, false, false) +} + +#[fixture] +fn policy_persist() -> TrackerPolicy { + TrackerPolicy::new(0, true, false) +} + +#[fixture] +fn policy_remove() -> TrackerPolicy { + TrackerPolicy::new(0, false, true) +} + +#[fixture] +fn policy_remove_persist() -> TrackerPolicy { + TrackerPolicy::new(0, true, true) +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_get_a_torrent_entry( + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_mutex_std(), + skip_list_mutex_parking_lot(), + skip_list_rw_lock_parking_lot(), + dash_map_std() + )] + repo: Repo, + #[case] entries: Entries, +) { + make(&repo, &entries).await; + + if let Some((info_hash, torrent)) = entries.first() { + assert_eq!(repo.get(info_hash).await, Some(torrent.clone())); + } else { + assert_eq!(repo.get(&InfoHash::default()).await, None); + } +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_mutex_std(), + skip_list_mutex_parking_lot(), + skip_list_rw_lock_parking_lot() + )] + repo: Repo, + #[case] entries: Entries, + many_out_of_order: Entries, +) { + make(&repo, &entries).await; + + let entries_a = repo.get_paginated(None).await.iter().map(|(i, _)| *i).collect::>(); + + make(&repo, &many_out_of_order).await; + + let entries_b = repo.get_paginated(None).await.iter().map(|(i, _)| *i).collect::>(); + + let is_equal = entries_b.iter().take(entries_a.len()).copied().collect::>() == entries_a; + + let is_sorted = entries_b.windows(2).all(|w| w[0] <= w[1]); + + assert!( + is_equal || is_sorted, + "The order is unstable: {is_equal}, or is sorted {is_sorted}." + ); +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_get_paginated( + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_mutex_std(), + skip_list_mutex_parking_lot(), + skip_list_rw_lock_parking_lot() + )] + repo: Repo, + #[case] entries: Entries, + #[values(paginated_limit_zero(), paginated_limit_one(), paginated_limit_one_offset_one())] paginated: Pagination, +) { + make(&repo, &entries).await; + + let mut info_hashes = repo.get_paginated(None).await.iter().map(|(i, _)| *i).collect::>(); + info_hashes.sort(); + + match paginated { + // it should return empty if limit is zero. + Pagination { limit: 0, .. } => assert_eq!(repo.get_paginated(Some(&paginated)).await, vec![]), + + // it should return a single entry if the limit is one. + Pagination { limit: 1, offset: 0 } => { + if info_hashes.is_empty() { + assert_eq!(repo.get_paginated(Some(&paginated)).await.len(), 0); + } else { + let page = repo.get_paginated(Some(&paginated)).await; + assert_eq!(page.len(), 1); + assert_eq!(page.first().map(|(i, _)| i), info_hashes.first()); + } + } + + // it should return the only the second entry if both the limit and the offset are one. + Pagination { limit: 1, offset: 1 } if info_hashes.len() > 1 => { + let page = repo.get_paginated(Some(&paginated)).await; + assert_eq!(page.len(), 1); + assert_eq!(page[0].0, info_hashes[1]); + } + // the other cases are not yet tested. + _ => {} + } +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_get_metrics( + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_mutex_std(), + skip_list_mutex_parking_lot(), + skip_list_rw_lock_parking_lot(), + dash_map_std() + )] + repo: Repo, + #[case] entries: Entries, +) { + use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; + + make(&repo, &entries).await; + + let mut metrics = AggregateActiveSwarmMetadata::default(); + + for (_, torrent) in entries { + let stats = torrent.get_swarm_metadata(); + + metrics.total_torrents += 1; + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + } + + assert_eq!(repo.get_metrics().await, metrics); +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_import_persistent_torrents( + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_mutex_std(), + skip_list_mutex_parking_lot(), + skip_list_rw_lock_parking_lot(), + dash_map_std() + )] + repo: Repo, + #[case] entries: Entries, + #[values(persistent_empty(), persistent_single(), persistent_three())] persistent_torrents: NumberOfDownloadsBTreeMap, +) { + make(&repo, &entries).await; + + let mut downloaded = repo.get_metrics().await.total_downloaded; + for d in persistent_torrents.values() { + downloaded += u64::from(*d); + } + + repo.import_persistent(&persistent_torrents).await; + + assert_eq!(repo.get_metrics().await.total_downloaded, downloaded); + + for (entry, _) in persistent_torrents { + assert!(repo.get(&entry).await.is_some()); + } +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_remove_an_entry( + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_mutex_std(), + skip_list_mutex_parking_lot(), + skip_list_rw_lock_parking_lot(), + dash_map_std() + )] + repo: Repo, + #[case] entries: Entries, +) { + make(&repo, &entries).await; + + for (info_hash, torrent) in entries { + assert_eq!(repo.get(&info_hash).await, Some(torrent.clone())); + assert_eq!(repo.remove(&info_hash).await, Some(torrent)); + + assert_eq!(repo.get(&info_hash).await, None); + assert_eq!(repo.remove(&info_hash).await, None); + } + + assert_eq!(repo.get_metrics().await.total_torrents, 0); +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_remove_inactive_peers( + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_mutex_std(), + skip_list_mutex_parking_lot(), + skip_list_rw_lock_parking_lot(), + dash_map_std() + )] + repo: Repo, + #[case] entries: Entries, +) { + use std::time::Duration; + + use torrust_tracker_clock::clock::stopped::Stopped as _; + use torrust_tracker_clock::clock::{self, Time as _}; + use torrust_tracker_primitives::peer; + + use crate::CurrentClock; + + const TIMEOUT: Duration = Duration::from_secs(120); + const EXPIRE: Duration = Duration::from_secs(121); + + make(&repo, &entries).await; + + let info_hash: InfoHash; + let mut peer: peer::Peer; + + // Generate a new infohash and peer. + { + let hash = &mut DefaultHasher::default(); + hash.write_u8(255); + info_hash = InfoHash::from(&hash.clone()); + peer = a_completed_peer(-1); + } + + // Set the last updated time of the peer to be 121 seconds ago. + { + let now = clock::Working::now(); + clock::Stopped::local_set(&now); + + peer.updated = now + .checked_sub(EXPIRE) + .expect("it_should_remove_inactive_peers_beyond_cutoff: EXPIRE must not exceed now"); + } + + // Insert the infohash and peer into the repository + // and verify there is an extra torrent entry. + { + repo.upsert_peer(&info_hash, &peer, None).await; + assert_eq!(repo.get_metrics().await.total_torrents, entries.len() as u64 + 1); + } + + // Insert the infohash and peer into the repository + // and verify the swarm metadata was updated. + { + repo.upsert_peer(&info_hash, &peer, None).await; + let stats = repo.get_swarm_metadata(&info_hash).await; + assert_eq!( + stats, + Some(SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0 + }) + ); + } + + // Verify that this new peer was inserted into the repository. + { + let entry = repo.get(&info_hash).await.expect("it_should_get_some"); + assert!(entry.get_peers(None).contains(&peer.into())); + } + + // Remove peers that have not been updated since the timeout (120 seconds ago). + { + repo.remove_inactive_peers(CurrentClock::now_sub(&TIMEOUT).expect("it should get a time passed")) + .await; + } + + // Verify that the this peer was removed from the repository. + { + let entry = repo.get(&info_hash).await.expect("it_should_get_some"); + assert!(!entry.get_peers(None).contains(&peer.into())); + } +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_remove_peerless_torrents( + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_mutex_std(), + skip_list_mutex_parking_lot(), + skip_list_rw_lock_parking_lot(), + dash_map_std() + )] + repo: Repo, + #[case] entries: Entries, + #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, +) { + make(&repo, &entries).await; + + repo.remove_peerless_torrents(&policy).await; + + let torrents = repo.get_paginated(None).await; + + for (_, entry) in torrents { + assert!(entry.meets_retaining_policy(&policy)); + } +} diff --git a/packages/tracker-client/Cargo.toml b/packages/tracker-client/Cargo.toml new file mode 100644 index 000000000..0cd419471 --- /dev/null +++ b/packages/tracker-client/Cargo.toml @@ -0,0 +1,37 @@ +[package] +description = "A library with the generic tracker clients." +keywords = [ "bittorrent", "client", "tracker" ] +license = "LGPL-3.0" +name = "bittorrent-tracker-client" +readme = "README.md" + +authors.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +bittorrent-primitives = "0.1.0" +derive_more = { version = "2", features = [ "as_ref", "constructor", "from" ] } +hyper = "1" +percent-encoding = "2" +reqwest = { version = "0", features = [ "json" ] } +serde = { version = "1", features = [ "derive" ] } +serde_bencode = "0" +serde_bytes = "0" +serde_repr = "0" +thiserror = "2" +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +tracing = "0" +zerocopy = "0.7" + +[package.metadata.cargo-machete] +ignored = [ "serde_bytes" ] diff --git a/packages/tracker-client/README.md b/packages/tracker-client/README.md new file mode 100644 index 000000000..ebd0c4bda --- /dev/null +++ b/packages/tracker-client/README.md @@ -0,0 +1,25 @@ +# BitTorrent Tracker Client + +A library to interact with BitTorrent trackers. + +> **Disclaimer**: This project is actively under development. We’re currently extracting and refining common types from the[Torrust Tracker](https://github.com/torrust/torrust-tracker) to make them available to the BitTorrent community in Rust. While these types are functional, they are not yet ready for use in production or third-party projects. + +## License + +**Copyright (c) 2024 The Torrust Developers.** + +This program is free software: you can redistribute it and/or modify it under the terms of the [GNU Lesser General Public License][LGPL_3_0] as published by the [Free Software Foundation][FSF], version 3. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the [GNU Lesser General Public License][LGPL_3_0] for more details. + +You should have received a copy of the *GNU Lesser General Public License* along with this program. If not, see . + +Some files include explicit copyright notices and/or license notices. + +### Legacy Exception + +For prosperity, versions of Torrust BitTorrent Tracker Client that are older than five years are automatically granted the [MIT-0][MIT_0] license in addition to the existing [LGPL-3.0-only][LGPL_3_0] license. + +[LGPL_3_0]: ./LICENSE +[MIT_0]: ./docs/licenses/LICENSE-MIT_0 +[FSF]: https://www.fsf.org/ diff --git a/packages/tracker-client/docs/licenses/LICENSE-MIT_0 b/packages/tracker-client/docs/licenses/LICENSE-MIT_0 new file mode 100644 index 000000000..fc06cc4fe --- /dev/null +++ b/packages/tracker-client/docs/licenses/LICENSE-MIT_0 @@ -0,0 +1,14 @@ +MIT No Attribution + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/tracker-client/src/http/client/mod.rs b/packages/tracker-client/src/http/client/mod.rs new file mode 100644 index 000000000..50e979c79 --- /dev/null +++ b/packages/tracker-client/src/http/client/mod.rs @@ -0,0 +1,221 @@ +pub mod requests; +pub mod responses; + +use std::net::IpAddr; +use std::sync::Arc; +use std::time::Duration; + +use derive_more::Display; +use hyper::StatusCode; +use requests::{announce, scrape}; +use reqwest::{Response, Url}; +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +#[derive(Debug, Clone, Error)] +pub enum Error { + #[error("Failed to Build a Http Client: {err:?}")] + ClientBuildingError { err: Arc }, + #[error("Failed to get a response: {err:?}")] + ResponseError { err: Arc }, + #[error("Returned a non-success code: \"{code}\" with the response: \"{response:?}\"")] + UnsuccessfulResponse { code: StatusCode, response: Arc }, +} + +/// HTTP Tracker Client +#[allow(clippy::struct_field_names)] +pub struct Client { + http_client: reqwest::Client, + base_url: Url, + key: Option, +} + +/// URL components in this context: +/// +/// ```text +/// http://127.0.0.1:62304/announce/YZ....rJ?info_hash=%9C8B%22%13%E3%0B%FF%21%2B0%C3%60%D2o%9A%02%13d%22 +/// \_____________________/\_______________/ \__________________________________________________________/ +/// | | | +/// base url path query +/// ``` +impl Client { + /// # Errors + /// + /// This method fails if the client builder fails. + pub fn new(base_url: Url, timeout: Duration) -> Result { + let client = reqwest::Client::builder() + .timeout(timeout) + .build() + .map_err(|e| Error::ClientBuildingError { err: e.into() })?; + + Ok(Self { + base_url, + http_client: client, + key: None, + }) + } + + /// Creates the new client binding it to an specific local address. + /// + /// # Errors + /// + /// This method fails if the client builder fails. + pub fn bind(base_url: Url, timeout: Duration, local_address: IpAddr) -> Result { + let client = reqwest::Client::builder() + .timeout(timeout) + .local_address(local_address) + .build() + .map_err(|e| Error::ClientBuildingError { err: e.into() })?; + + Ok(Self { + base_url, + http_client: client, + key: None, + }) + } + + /// # Errors + /// + /// This method fails if the client builder fails. + pub fn authenticated(base_url: Url, timeout: Duration, key: Key) -> Result { + let client = reqwest::Client::builder() + .timeout(timeout) + .build() + .map_err(|e| Error::ClientBuildingError { err: e.into() })?; + + Ok(Self { + base_url, + http_client: client, + key: Some(key), + }) + } + + /// # Errors + /// + /// This method fails if the returned response was not successful + pub async fn announce(&self, query: &announce::Query) -> Result { + let response = self.get(&self.build_announce_path_and_query(query)).await?; + + if response.status().is_success() { + Ok(response) + } else { + Err(Error::UnsuccessfulResponse { + code: response.status(), + response: response.into(), + }) + } + } + + /// # Errors + /// + /// This method fails if the returned response was not successful + pub async fn scrape(&self, query: &scrape::Query) -> Result { + let response = self.get(&self.build_scrape_path_and_query(query)).await?; + + if response.status().is_success() { + Ok(response) + } else { + Err(Error::UnsuccessfulResponse { + code: response.status(), + response: response.into(), + }) + } + } + + /// # Errors + /// + /// This method fails if the returned response was not successful + pub async fn announce_with_header(&self, query: &announce::Query, key: &str, value: &str) -> Result { + let response = self + .get_with_header(&self.build_announce_path_and_query(query), key, value) + .await?; + + if response.status().is_success() { + Ok(response) + } else { + Err(Error::UnsuccessfulResponse { + code: response.status(), + response: response.into(), + }) + } + } + + /// # Errors + /// + /// This method fails if the returned response was not successful + pub async fn health_check(&self) -> Result { + let response = self.get(&self.build_path("health_check")).await?; + + if response.status().is_success() { + Ok(response) + } else { + Err(Error::UnsuccessfulResponse { + code: response.status(), + response: response.into(), + }) + } + } + + /// # Errors + /// + /// This method fails if there was an error while sending request. + pub async fn get(&self, path: &str) -> Result { + self.http_client + .get(self.build_url(path)) + .send() + .await + .map_err(|e| Error::ResponseError { err: e.into() }) + } + + /// # Errors + /// + /// This method fails if there was an error while sending request. + pub async fn get_with_header(&self, path: &str, key: &str, value: &str) -> Result { + self.http_client + .get(self.build_url(path)) + .header(key, value) + .send() + .await + .map_err(|e| Error::ResponseError { err: e.into() }) + } + + fn build_announce_path_and_query(&self, query: &announce::Query) -> String { + format!("{}?{query}", self.build_path("announce")) + } + + fn build_scrape_path_and_query(&self, query: &scrape::Query) -> String { + format!("{}?{query}", self.build_path("scrape")) + } + + fn build_path(&self, path: &str) -> String { + match &self.key { + Some(key) => format!("{path}/{key}"), + None => path.to_string(), + } + } + + fn build_url(&self, path: &str) -> String { + let base_url = self.base_url(); + format!("{base_url}{path}") + } + + fn base_url(&self) -> String { + self.base_url.to_string() + } +} + +/// A token used for authentication. +#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Display, Hash)] +pub struct Key(String); + +impl Key { + #[must_use] + pub fn new(value: &str) -> Self { + Self(value.to_owned()) + } + + #[must_use] + pub fn value(&self) -> &str { + &self.0 + } +} diff --git a/packages/tracker-client/src/http/client/requests/announce.rs b/packages/tracker-client/src/http/client/requests/announce.rs new file mode 100644 index 000000000..87bdbad52 --- /dev/null +++ b/packages/tracker-client/src/http/client/requests/announce.rs @@ -0,0 +1,275 @@ +use std::fmt; +use std::net::{IpAddr, Ipv4Addr}; +use std::str::FromStr; + +use aquatic_udp_protocol::PeerId; +use bittorrent_primitives::info_hash::InfoHash; +use serde_repr::Serialize_repr; + +use crate::http::{percent_encode_byte_array, ByteArray20}; + +pub struct Query { + pub info_hash: ByteArray20, + pub peer_addr: IpAddr, + pub downloaded: BaseTenASCII, + pub uploaded: BaseTenASCII, + pub peer_id: ByteArray20, + pub port: PortNumber, + pub left: BaseTenASCII, + pub event: Option, + pub compact: Option, +} + +impl fmt::Display for Query { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.build()) + } +} + +/// HTTP Tracker Announce Request: +/// +/// +/// +/// Some parameters in the specification are not implemented in this tracker yet. +impl Query { + /// It builds the URL query component for the announce request. + /// + /// This custom URL query params encoding is needed because `reqwest` does not allow + /// bytes arrays in query parameters. More info on this issue: + /// + /// + #[must_use] + pub fn build(&self) -> String { + self.params().to_string() + } + + #[must_use] + pub fn params(&self) -> QueryParams { + QueryParams::from(self) + } +} + +pub type BaseTenASCII = u64; +pub type PortNumber = u16; + +pub enum Event { + Started, + Stopped, + Completed, +} + +impl fmt::Display for Event { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Event::Started => write!(f, "started"), + Event::Stopped => write!(f, "stopped"), + Event::Completed => write!(f, "completed"), + } + } +} + +#[derive(Serialize_repr, PartialEq, Debug)] +#[repr(u8)] +pub enum Compact { + Accepted = 1, + NotAccepted = 0, +} + +impl fmt::Display for Compact { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Compact::Accepted => write!(f, "1"), + Compact::NotAccepted => write!(f, "0"), + } + } +} + +pub struct QueryBuilder { + announce_query: Query, +} + +impl QueryBuilder { + /// # Panics + /// + /// Will panic if the default info-hash value is not a valid info-hash. + #[must_use] + pub fn with_default_values() -> QueryBuilder { + let default_announce_query = Query { + info_hash: InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap().0, // DevSkim: ignore DS173237 + peer_addr: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 88)), + downloaded: 0, + uploaded: 0, + peer_id: PeerId(*b"-qB00000000000000001").0, + port: 17548, + left: 0, + event: Some(Event::Started), + compact: Some(Compact::NotAccepted), + }; + Self { + announce_query: default_announce_query, + } + } + + #[must_use] + pub fn with_info_hash(mut self, info_hash: &InfoHash) -> Self { + self.announce_query.info_hash = info_hash.0; + self + } + + #[must_use] + pub fn with_peer_id(mut self, peer_id: &PeerId) -> Self { + self.announce_query.peer_id = peer_id.0; + self + } + + #[must_use] + pub fn with_compact(mut self, compact: Compact) -> Self { + self.announce_query.compact = Some(compact); + self + } + + #[must_use] + pub fn with_peer_addr(mut self, peer_addr: &IpAddr) -> Self { + self.announce_query.peer_addr = *peer_addr; + self + } + + #[must_use] + pub fn without_compact(mut self) -> Self { + self.announce_query.compact = None; + self + } + + #[must_use] + pub fn query(self) -> Query { + self.announce_query + } +} + +/// It contains all the GET parameters that can be used in a HTTP Announce request. +/// +/// Sample Announce URL with all the GET parameters (mandatory and optional): +/// +/// ```text +/// http://127.0.0.1:7070/announce? +/// info_hash=%9C8B%22%13%E3%0B%FF%21%2B0%C3%60%D2o%9A%02%13d%22 (mandatory) +/// peer_addr=192.168.1.88 +/// downloaded=0 +/// uploaded=0 +/// peer_id=%2DqB00000000000000000 (mandatory) +/// port=17548 (mandatory) +/// left=0 +/// event=completed +/// compact=0 +/// ``` +pub struct QueryParams { + pub info_hash: Option, + pub peer_addr: Option, + pub downloaded: Option, + pub uploaded: Option, + pub peer_id: Option, + pub port: Option, + pub left: Option, + pub event: Option, + pub compact: Option, +} + +impl std::fmt::Display for QueryParams { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut params = vec![]; + + if let Some(info_hash) = &self.info_hash { + params.push(("info_hash", info_hash)); + } + if let Some(peer_addr) = &self.peer_addr { + params.push(("peer_addr", peer_addr)); + } + if let Some(downloaded) = &self.downloaded { + params.push(("downloaded", downloaded)); + } + if let Some(uploaded) = &self.uploaded { + params.push(("uploaded", uploaded)); + } + if let Some(peer_id) = &self.peer_id { + params.push(("peer_id", peer_id)); + } + if let Some(port) = &self.port { + params.push(("port", port)); + } + if let Some(left) = &self.left { + params.push(("left", left)); + } + if let Some(event) = &self.event { + params.push(("event", event)); + } + if let Some(compact) = &self.compact { + params.push(("compact", compact)); + } + + let query = params + .iter() + .map(|param| format!("{}={}", param.0, param.1)) + .collect::>() + .join("&"); + + write!(f, "{query}") + } +} + +impl QueryParams { + pub fn from(announce_query: &Query) -> Self { + let event = announce_query.event.as_ref().map(std::string::ToString::to_string); + let compact = announce_query.compact.as_ref().map(std::string::ToString::to_string); + + Self { + info_hash: Some(percent_encode_byte_array(&announce_query.info_hash)), + peer_addr: Some(announce_query.peer_addr.to_string()), + downloaded: Some(announce_query.downloaded.to_string()), + uploaded: Some(announce_query.uploaded.to_string()), + peer_id: Some(percent_encode_byte_array(&announce_query.peer_id)), + port: Some(announce_query.port.to_string()), + left: Some(announce_query.left.to_string()), + event, + compact, + } + } + + pub fn remove_optional_params(&mut self) { + // todo: make them optional with the Option<...> in the AnnounceQuery struct + // if they are really optional. So that we can crete a minimal AnnounceQuery + // instead of removing the optional params afterwards. + // + // The original specification on: + // + // says only `ip` and `event` are optional. + // + // On + // says only `ip`, `numwant`, `key` and `trackerid` are optional. + // + // but the server is responding if all these params are not included. + self.peer_addr = None; + self.downloaded = None; + self.uploaded = None; + self.left = None; + self.event = None; + self.compact = None; + } + + /// # Panics + /// + /// Will panic if invalid param name is provided. + pub fn set(&mut self, param_name: &str, param_value: &str) { + match param_name { + "info_hash" => self.info_hash = Some(param_value.to_string()), + "peer_addr" => self.peer_addr = Some(param_value.to_string()), + "downloaded" => self.downloaded = Some(param_value.to_string()), + "uploaded" => self.uploaded = Some(param_value.to_string()), + "peer_id" => self.peer_id = Some(param_value.to_string()), + "port" => self.port = Some(param_value.to_string()), + "left" => self.left = Some(param_value.to_string()), + "event" => self.event = Some(param_value.to_string()), + "compact" => self.compact = Some(param_value.to_string()), + &_ => panic!("Invalid param name for announce query"), + } + } +} diff --git a/packages/tracker-client/src/http/client/requests/mod.rs b/packages/tracker-client/src/http/client/requests/mod.rs new file mode 100644 index 000000000..776d2dfbf --- /dev/null +++ b/packages/tracker-client/src/http/client/requests/mod.rs @@ -0,0 +1,2 @@ +pub mod announce; +pub mod scrape; diff --git a/packages/tracker-client/src/http/client/requests/scrape.rs b/packages/tracker-client/src/http/client/requests/scrape.rs new file mode 100644 index 000000000..b25c3c4c7 --- /dev/null +++ b/packages/tracker-client/src/http/client/requests/scrape.rs @@ -0,0 +1,172 @@ +use std::error::Error; +use std::fmt::{self}; +use std::str::FromStr; + +use bittorrent_primitives::info_hash::InfoHash; + +use crate::http::{percent_encode_byte_array, ByteArray20}; + +pub struct Query { + pub info_hash: Vec, +} + +impl fmt::Display for Query { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.build()) + } +} + +#[derive(Debug)] +#[allow(dead_code)] +pub struct ConversionError(String); + +impl fmt::Display for ConversionError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Invalid infohash: {}", self.0) + } +} + +impl Error for ConversionError {} + +impl TryFrom<&[String]> for Query { + type Error = ConversionError; + + fn try_from(info_hashes: &[String]) -> Result { + let mut validated_info_hashes: Vec = Vec::new(); + + for info_hash in info_hashes { + let validated_info_hash = InfoHash::from_str(info_hash).map_err(|_| ConversionError(info_hash.clone()))?; + validated_info_hashes.push(validated_info_hash.0); + } + + Ok(Self { + info_hash: validated_info_hashes, + }) + } +} + +impl TryFrom> for Query { + type Error = ConversionError; + + fn try_from(info_hashes: Vec) -> Result { + let mut validated_info_hashes: Vec = Vec::new(); + + for info_hash in info_hashes { + let validated_info_hash = InfoHash::from_str(&info_hash).map_err(|_| ConversionError(info_hash.clone()))?; + validated_info_hashes.push(validated_info_hash.0); + } + + Ok(Self { + info_hash: validated_info_hashes, + }) + } +} + +/// HTTP Tracker Scrape Request: +/// +/// +impl Query { + /// It builds the URL query component for the scrape request. + /// + /// This custom URL query params encoding is needed because `reqwest` does not allow + /// bytes arrays in query parameters. More info on this issue: + /// + /// + #[must_use] + pub fn build(&self) -> String { + self.params().to_string() + } + + #[must_use] + pub fn params(&self) -> QueryParams { + QueryParams::from(self) + } +} + +pub struct QueryBuilder { + scrape_query: Query, +} + +impl Default for QueryBuilder { + fn default() -> Self { + let default_scrape_query = Query { + info_hash: [InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap().0].to_vec(), // DevSkim: ignore DS173237 + }; + Self { + scrape_query: default_scrape_query, + } + } +} + +impl QueryBuilder { + #[must_use] + pub fn with_one_info_hash(mut self, info_hash: &InfoHash) -> Self { + self.scrape_query.info_hash = [info_hash.0].to_vec(); + self + } + + #[must_use] + pub fn add_info_hash(mut self, info_hash: &InfoHash) -> Self { + self.scrape_query.info_hash.push(info_hash.0); + self + } + + #[must_use] + pub fn query(self) -> Query { + self.scrape_query + } +} + +/// It contains all the GET parameters that can be used in a HTTP Scrape request. +/// +/// The `info_hash` param is the percent encoded of the the 20-byte array info hash. +/// +/// Sample Scrape URL with all the GET parameters: +/// +/// For `IpV4`: +/// +/// ```text +/// http://127.0.0.1:7070/scrape?info_hash=%9C8B%22%13%E3%0B%FF%21%2B0%C3%60%D2o%9A%02%13d%22 +/// ``` +/// +/// For `IpV6`: +/// +/// ```text +/// http://[::1]:7070/scrape?info_hash=%9C8B%22%13%E3%0B%FF%21%2B0%C3%60%D2o%9A%02%13d%22 +/// ``` +/// +/// You can add as many info hashes as you want, just adding the same param again. +pub struct QueryParams { + pub info_hash: Vec, +} + +impl QueryParams { + pub fn set_one_info_hash_param(&mut self, info_hash: &str) { + self.info_hash = vec![info_hash.to_string()]; + } +} + +impl std::fmt::Display for QueryParams { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let query = self + .info_hash + .iter() + .map(|info_hash| format!("info_hash={}", &info_hash)) + .collect::>() + .join("&"); + + write!(f, "{query}") + } +} + +impl QueryParams { + pub fn from(scrape_query: &Query) -> Self { + let info_hashes = scrape_query + .info_hash + .iter() + .map(percent_encode_byte_array) + .collect::>(); + + Self { info_hash: info_hashes } + } +} diff --git a/packages/tracker-client/src/http/client/responses/announce.rs b/packages/tracker-client/src/http/client/responses/announce.rs new file mode 100644 index 000000000..7f2d3611c --- /dev/null +++ b/packages/tracker-client/src/http/client/responses/announce.rs @@ -0,0 +1,126 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + +use serde::{Deserialize, Serialize}; +use torrust_tracker_primitives::peer; +use zerocopy::AsBytes as _; + +#[derive(Serialize, Deserialize, Debug, PartialEq)] +pub struct Announce { + pub complete: u32, + pub incomplete: u32, + pub interval: u32, + #[serde(rename = "min interval")] + pub min_interval: u32, + pub peers: Vec, // Peers using IPV4 and IPV6 +} + +#[derive(Serialize, Deserialize, Debug, PartialEq)] +pub struct DictionaryPeer { + pub ip: String, + #[serde(rename = "peer id")] + #[serde(with = "serde_bytes")] + pub peer_id: Vec, + pub port: u16, +} + +impl From for DictionaryPeer { + fn from(peer: peer::Peer) -> Self { + DictionaryPeer { + peer_id: peer.peer_id.as_bytes().to_vec(), + ip: peer.peer_addr.ip().to_string(), + port: peer.peer_addr.port(), + } + } +} + +#[derive(Serialize, Deserialize, Debug, PartialEq)] +pub struct DeserializedCompact { + pub complete: u32, + pub incomplete: u32, + pub interval: u32, + #[serde(rename = "min interval")] + pub min_interval: u32, + #[serde(with = "serde_bytes")] + pub peers: Vec, +} + +impl DeserializedCompact { + /// # Errors + /// + /// Will return an error if bytes can't be deserialized. + pub fn from_bytes(bytes: &[u8]) -> Result { + serde_bencode::from_bytes::(bytes) + } +} + +#[derive(Debug, PartialEq)] +pub struct Compact { + // code-review: there could be a way to deserialize this struct directly + // by using serde instead of doing it manually. Or at least using a custom deserializer. + pub complete: u32, + pub incomplete: u32, + pub interval: u32, + pub min_interval: u32, + pub peers: CompactPeerList, +} + +#[derive(Debug, PartialEq)] +pub struct CompactPeerList { + peers: Vec, +} + +impl CompactPeerList { + #[must_use] + pub fn new(peers: Vec) -> Self { + Self { peers } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct CompactPeer { + ip: Ipv4Addr, + port: u16, +} + +impl CompactPeer { + /// # Panics + /// + /// Will panic if the provided socket address is a IPv6 IP address. + /// It's not supported for compact peers. + #[must_use] + pub fn new(socket_addr: &SocketAddr) -> Self { + match socket_addr.ip() { + IpAddr::V4(ip) => Self { + ip, + port: socket_addr.port(), + }, + IpAddr::V6(_ip) => panic!("IPV6 is not supported for compact peer"), + } + } + + #[must_use] + pub fn new_from_bytes(bytes: &[u8]) -> Self { + Self { + ip: Ipv4Addr::new(bytes[0], bytes[1], bytes[2], bytes[3]), + port: u16::from_be_bytes([bytes[4], bytes[5]]), + } + } +} + +impl From for Compact { + fn from(compact_announce: DeserializedCompact) -> Self { + let mut peers = vec![]; + + for peer_bytes in compact_announce.peers.chunks_exact(6) { + peers.push(CompactPeer::new_from_bytes(peer_bytes)); + } + + Self { + complete: compact_announce.complete, + incomplete: compact_announce.incomplete, + interval: compact_announce.interval, + min_interval: compact_announce.min_interval, + peers: CompactPeerList::new(peers), + } + } +} diff --git a/packages/tracker-client/src/http/client/responses/error.rs b/packages/tracker-client/src/http/client/responses/error.rs new file mode 100644 index 000000000..00befdb54 --- /dev/null +++ b/packages/tracker-client/src/http/client/responses/error.rs @@ -0,0 +1,7 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, Debug, PartialEq)] +pub struct Error { + #[serde(rename = "failure reason")] + pub failure_reason: String, +} diff --git a/packages/tracker-client/src/http/client/responses/mod.rs b/packages/tracker-client/src/http/client/responses/mod.rs new file mode 100644 index 000000000..bdc689056 --- /dev/null +++ b/packages/tracker-client/src/http/client/responses/mod.rs @@ -0,0 +1,3 @@ +pub mod announce; +pub mod error; +pub mod scrape; diff --git a/packages/tracker-client/src/http/client/responses/scrape.rs b/packages/tracker-client/src/http/client/responses/scrape.rs new file mode 100644 index 000000000..6c0e8800a --- /dev/null +++ b/packages/tracker-client/src/http/client/responses/scrape.rs @@ -0,0 +1,230 @@ +use std::collections::HashMap; +use std::fmt::Write; +use std::str; + +use serde::ser::SerializeMap; +use serde::{Deserialize, Serialize, Serializer}; +use serde_bencode::value::Value; + +use crate::http::{ByteArray20, InfoHash}; + +#[derive(Debug, PartialEq, Default, Deserialize)] +pub struct Response { + pub files: HashMap, +} + +impl Response { + #[must_use] + pub fn with_one_file(info_hash_bytes: ByteArray20, file: File) -> Self { + let mut files: HashMap = HashMap::new(); + files.insert(info_hash_bytes, file); + Self { files } + } + + /// # Errors + /// + /// Will return an error if the deserialized bencoded response can't not be converted into a valid response. + /// + /// # Panics + /// + /// Will panic if it can't deserialize the bencoded response. + pub fn try_from_bencoded(bytes: &[u8]) -> Result { + let scrape_response: DeserializedResponse = + serde_bencode::from_bytes(bytes).expect("provided bytes should be a valid bencoded response"); + Self::try_from(scrape_response) + } +} + +#[derive(Serialize, Deserialize, Debug, PartialEq, Default)] +pub struct File { + pub complete: i64, // The number of active peers that have completed downloading + pub downloaded: i64, // The number of peers that have ever completed downloading + pub incomplete: i64, // The number of active peers that have not completed downloading +} + +impl File { + #[must_use] + pub fn zeroed() -> Self { + Self::default() + } +} + +impl TryFrom for Response { + type Error = BencodeParseError; + + fn try_from(scrape_response: DeserializedResponse) -> Result { + parse_bencoded_response(&scrape_response.files) + } +} + +#[derive(Serialize, Deserialize, Debug, PartialEq)] +struct DeserializedResponse { + pub files: Value, +} + +// Custom serialization for Response +impl Serialize for Response { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut map = serializer.serialize_map(Some(self.files.len()))?; + for (key, value) in &self.files { + // Convert ByteArray20 key to hex string + let hex_key = byte_array_to_hex_string(key); + map.serialize_entry(&hex_key, value)?; + } + map.end() + } +} + +// Helper function to convert ByteArray20 to hex string +fn byte_array_to_hex_string(byte_array: &ByteArray20) -> String { + let mut hex_string = String::with_capacity(byte_array.len() * 2); + for byte in byte_array { + write!(hex_string, "{byte:02x}").expect("Writing to string should never fail"); + } + hex_string +} + +#[derive(Default)] +pub struct ResponseBuilder { + response: Response, +} + +impl ResponseBuilder { + #[must_use] + pub fn add_file(mut self, info_hash_bytes: ByteArray20, file: File) -> Self { + self.response.files.insert(info_hash_bytes, file); + self + } + + #[must_use] + pub fn build(self) -> Response { + self.response + } +} + +#[derive(Debug)] +pub enum BencodeParseError { + InvalidValueExpectedDict { value: Value }, + InvalidValueExpectedInt { value: Value }, + InvalidFileField { value: Value }, + MissingFileField { field_name: String }, +} + +/// It parses a bencoded scrape response into a `Response` struct. +/// +/// For example: +/// +/// ```text +/// d5:filesd20:xxxxxxxxxxxxxxxxxxxxd8:completei11e10:downloadedi13772e10:incompletei19e +/// 20:yyyyyyyyyyyyyyyyyyyyd8:completei21e10:downloadedi206e10:incompletei20eee +/// ``` +/// +/// Response (JSON encoded for readability): +/// +/// ```text +/// { +/// 'files': { +/// 'xxxxxxxxxxxxxxxxxxxx': {'complete': 11, 'downloaded': 13772, 'incomplete': 19}, +/// 'yyyyyyyyyyyyyyyyyyyy': {'complete': 21, 'downloaded': 206, 'incomplete': 20} +/// } +/// } +fn parse_bencoded_response(value: &Value) -> Result { + let mut files: HashMap = HashMap::new(); + + match value { + Value::Dict(dict) => { + for file_element in dict { + let info_hash_byte_vec = file_element.0; + let file_value = file_element.1; + + let file = parse_bencoded_file(file_value).unwrap(); + + files.insert(InfoHash::new(info_hash_byte_vec).bytes(), file); + } + } + _ => return Err(BencodeParseError::InvalidValueExpectedDict { value: value.clone() }), + } + + Ok(Response { files }) +} + +/// It parses a bencoded dictionary into a `File` struct. +/// +/// For example: +/// +/// +/// ```text +/// d8:completei11e10:downloadedi13772e10:incompletei19ee +/// ``` +/// +/// into: +/// +/// ```text +/// File { +/// complete: 11, +/// downloaded: 13772, +/// incomplete: 19, +/// } +/// ``` +fn parse_bencoded_file(value: &Value) -> Result { + let file = match &value { + Value::Dict(dict) => { + let mut complete = None; + let mut downloaded = None; + let mut incomplete = None; + + for file_field in dict { + let field_name = file_field.0; + + let field_value = match file_field.1 { + Value::Int(number) => Ok(*number), + _ => Err(BencodeParseError::InvalidValueExpectedInt { + value: file_field.1.clone(), + }), + }?; + + if field_name == b"complete" { + complete = Some(field_value); + } else if field_name == b"downloaded" { + downloaded = Some(field_value); + } else if field_name == b"incomplete" { + incomplete = Some(field_value); + } else { + return Err(BencodeParseError::InvalidFileField { + value: file_field.1.clone(), + }); + } + } + + if complete.is_none() { + return Err(BencodeParseError::MissingFileField { + field_name: "complete".to_string(), + }); + } + + if downloaded.is_none() { + return Err(BencodeParseError::MissingFileField { + field_name: "downloaded".to_string(), + }); + } + + if incomplete.is_none() { + return Err(BencodeParseError::MissingFileField { + field_name: "incomplete".to_string(), + }); + } + + File { + complete: complete.unwrap(), + downloaded: downloaded.unwrap(), + incomplete: incomplete.unwrap(), + } + } + _ => return Err(BencodeParseError::InvalidValueExpectedDict { value: value.clone() }), + }; + + Ok(file) +} diff --git a/packages/tracker-client/src/http/mod.rs b/packages/tracker-client/src/http/mod.rs new file mode 100644 index 000000000..d8f8242e8 --- /dev/null +++ b/packages/tracker-client/src/http/mod.rs @@ -0,0 +1,42 @@ +pub mod client; + +use percent_encoding::NON_ALPHANUMERIC; + +pub type ByteArray20 = [u8; 20]; + +#[must_use] +pub fn percent_encode_byte_array(bytes: &ByteArray20) -> String { + percent_encoding::percent_encode(bytes, NON_ALPHANUMERIC).to_string() +} + +pub struct InfoHash(ByteArray20); + +impl InfoHash { + #[must_use] + pub fn new(vec: &[u8]) -> Self { + let mut byte_array_20: ByteArray20 = Default::default(); + byte_array_20.clone_from_slice(vec); + Self(byte_array_20) + } + + #[must_use] + pub fn bytes(&self) -> ByteArray20 { + self.0 + } +} + +#[cfg(test)] +mod tests { + use crate::http::percent_encode_byte_array; + + #[test] + fn it_should_encode_a_20_byte_array() { + assert_eq!( + percent_encode_byte_array(&[ + 0x3b, 0x24, 0x55, 0x04, 0xcf, 0x5f, 0x11, 0xbb, 0xdb, 0xe1, 0x20, 0x1c, 0xea, 0x6a, 0x6b, 0xf4, 0x5a, 0xee, 0x1b, + 0xc0, + ]), + "%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0" + ); + } +} diff --git a/packages/tracker-client/src/lib.rs b/packages/tracker-client/src/lib.rs new file mode 100644 index 000000000..b08eaa622 --- /dev/null +++ b/packages/tracker-client/src/lib.rs @@ -0,0 +1,2 @@ +pub mod http; +pub mod udp; diff --git a/packages/tracker-client/src/udp/client.rs b/packages/tracker-client/src/udp/client.rs new file mode 100644 index 000000000..94c882d29 --- /dev/null +++ b/packages/tracker-client/src/udp/client.rs @@ -0,0 +1,273 @@ +use core::result::Result::{Err, Ok}; +use std::io::Cursor; +use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr}; +use std::sync::Arc; +use std::time::Duration; + +use aquatic_udp_protocol::{ConnectRequest, Request, Response, TransactionId}; +use tokio::net::UdpSocket; +use tokio::time; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; +use torrust_tracker_primitives::service_binding::ServiceBinding; +use zerocopy::network_endian::I32; + +use super::Error; +use crate::udp::MAX_PACKET_SIZE; + +pub const UDP_CLIENT_LOG_TARGET: &str = "UDP CLIENT"; + +#[allow(clippy::module_name_repetitions)] +#[derive(Debug)] +pub struct UdpClient { + /// The socket to connect to + pub socket: Arc, + + /// Timeout for sending and receiving packets + pub timeout: Duration, +} + +impl UdpClient { + /// Creates a new `UdpClient` bound to the default port and ipv6 address + /// + /// # Errors + /// + /// Will return error if unable to bind to any port or ip address. + /// + async fn bound_to_default_ipv4(timeout: Duration) -> Result { + let addr = SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), 0); + + Self::bound(addr, timeout).await + } + + /// Creates a new `UdpClient` bound to the default port and ipv6 address + /// + /// # Errors + /// + /// Will return error if unable to bind to any port or ip address. + /// + async fn bound_to_default_ipv6(timeout: Duration) -> Result { + let addr = SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), 0); + + Self::bound(addr, timeout).await + } + + /// Creates a new `UdpClient` connected to a Udp server + /// + /// # Errors + /// + /// Will return any errors present in the call stack + /// + pub async fn connected(remote_addr: SocketAddr, timeout: Duration) -> Result { + let client = if remote_addr.is_ipv4() { + Self::bound_to_default_ipv4(timeout).await? + } else { + Self::bound_to_default_ipv6(timeout).await? + }; + + client.connect(remote_addr).await?; + Ok(client) + } + + /// Creates a `[UdpClient]` bound to a Socket. + /// + /// # Panics + /// + /// Panics if unable to get the `local_addr` of the bound socket. + /// + /// # Errors + /// + /// This function will return an error if the binding takes to long + /// or if there is an underlying OS error. + pub async fn bound(addr: SocketAddr, timeout: Duration) -> Result { + tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "binding to socket: {addr:?} ..."); + + let socket = time::timeout(timeout, UdpSocket::bind(addr)) + .await + .map_err(|_| Error::TimeoutWhileBindingToSocket { addr })? + .map_err(|e| Error::UnableToBindToSocket { err: e.into(), addr })?; + + let addr = socket.local_addr().expect("it should get the local address"); + + tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "bound to socket: {addr:?}."); + + let udp_client = Self { + socket: Arc::new(socket), + timeout, + }; + + Ok(udp_client) + } + + /// # Errors + /// + /// Will return error if can't connect to the socket. + pub async fn connect(&self, remote_addr: SocketAddr) -> Result<(), Error> { + tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "connecting to remote: {remote_addr:?} ..."); + + let () = time::timeout(self.timeout, self.socket.connect(remote_addr)) + .await + .map_err(|_| Error::TimeoutWhileConnectingToRemote { remote_addr })? + .map_err(|e| Error::UnableToConnectToRemote { + err: e.into(), + remote_addr, + })?; + + tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "connected to remote: {remote_addr:?}."); + + Ok(()) + } + + /// # Errors + /// + /// Will return error if: + /// + /// - Can't write to the socket. + /// - Can't send data. + pub async fn send(&self, bytes: &[u8]) -> Result { + tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "sending {bytes:?} ..."); + + let () = time::timeout(self.timeout, self.socket.writable()) + .await + .map_err(|_| Error::TimeoutWaitForWriteableSocket)? + .map_err(|e| Error::UnableToGetWritableSocket { err: e.into() })?; + + let sent_bytes = time::timeout(self.timeout, self.socket.send(bytes)) + .await + .map_err(|_| Error::TimeoutWhileSendingData { data: bytes.to_vec() })? + .map_err(|e| Error::UnableToSendData { + err: e.into(), + data: bytes.to_vec(), + })?; + + tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "sent {sent_bytes} bytes to remote."); + + Ok(sent_bytes) + } + + /// # Errors + /// + /// Will return error if: + /// + /// - Can't read from the socket. + /// - Can't receive data. + /// + /// # Panics + /// + pub async fn receive(&self) -> Result, Error> { + tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "receiving ..."); + + let mut buffer = [0u8; MAX_PACKET_SIZE]; + + let () = time::timeout(self.timeout, self.socket.readable()) + .await + .map_err(|_| Error::TimeoutWaitForReadableSocket)? + .map_err(|e| Error::UnableToGetReadableSocket { err: e.into() })?; + + let received_bytes = time::timeout(self.timeout, self.socket.recv(&mut buffer)) + .await + .map_err(|_| Error::TimeoutWhileReceivingData)? + .map_err(|e| Error::UnableToReceivingData { err: e.into() })?; + + let mut received: Vec = buffer.to_vec(); + Vec::truncate(&mut received, received_bytes); + + tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "received {received_bytes} bytes: {received:?}"); + + Ok(received) + } +} + +#[allow(clippy::module_name_repetitions)] +#[derive(Debug)] +pub struct UdpTrackerClient { + pub client: UdpClient, +} + +impl UdpTrackerClient { + /// Creates a new `UdpTrackerClient` connected to a Udp Tracker server + /// + /// # Errors + /// + /// If unable to connect to the remote address. + /// + pub async fn new(remote_addr: SocketAddr, timeout: Duration) -> Result { + let client = UdpClient::connected(remote_addr, timeout).await?; + Ok(UdpTrackerClient { client }) + } + + /// # Errors + /// + /// Will return error if can't write request to bytes. + pub async fn send(&self, request: Request) -> Result { + tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "sending request {request:?} ..."); + + // Write request into a buffer + // todo: optimize the pre-allocated amount based upon request type. + let mut writer = Cursor::new(Vec::with_capacity(200)); + let () = request + .write_bytes(&mut writer) + .map_err(|e| Error::UnableToWriteDataFromRequest { err: e.into(), request })?; + + self.client.send(writer.get_ref()).await + } + + /// # Errors + /// + /// Will return error if can't create response from the received payload (bytes buffer). + pub async fn receive(&self) -> Result { + let response = self.client.receive().await?; + + tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "received {} bytes: {response:?}", response.len()); + + Response::parse_bytes(&response, true).map_err(|e| Error::UnableToParseResponse { err: e.into(), response }) + } +} + +/// Helper Function to Check if a UDP Service is Connectable +/// +/// # Panics +/// +/// It will return an error if unable to connect to the UDP service. +/// +/// # Errors +/// +pub async fn check(service_binding: &ServiceBinding) -> Result { + let remote_addr = service_binding.bind_address(); + + tracing::debug!("Checking Service (detail): {remote_addr:?}."); + + match UdpTrackerClient::new(remote_addr, DEFAULT_TIMEOUT).await { + Ok(client) => { + let connect_request = ConnectRequest { + transaction_id: TransactionId(I32::new(123)), + }; + + // client.send() return usize, but doesn't use here + match client.send(connect_request.into()).await { + Ok(_) => (), + Err(e) => tracing::debug!("Error: {e:?}."), + } + + let process = move |response| { + if matches!(response, Response::Connect(_connect_response)) { + Ok("Connected".to_string()) + } else { + Err("Did not Connect".to_string()) + } + }; + + let sleep = time::sleep(Duration::from_secs(2)); + tokio::pin!(sleep); + + tokio::select! { + () = &mut sleep => { + Err("Timed Out".to_string()) + } + response = client.receive() => { + process(response.unwrap()) + } + } + } + Err(e) => Err(format!("{e:?}")), + } +} diff --git a/packages/tracker-client/src/udp/mod.rs b/packages/tracker-client/src/udp/mod.rs new file mode 100644 index 000000000..b9d5f34f6 --- /dev/null +++ b/packages/tracker-client/src/udp/mod.rs @@ -0,0 +1,68 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use aquatic_udp_protocol::Request; +use thiserror::Error; +use torrust_tracker_located_error::DynError; + +pub mod client; + +/// The maximum number of bytes in a UDP packet. +pub const MAX_PACKET_SIZE: usize = 1496; +/// A magic 64-bit integer constant defined in the protocol that is used to +/// identify the protocol. +pub const PROTOCOL_ID: i64 = 0x0417_2710_1980; + +#[derive(Debug, Clone, Error)] +pub enum Error { + #[error("Timeout while waiting for socket to bind: {addr:?}")] + TimeoutWhileBindingToSocket { addr: SocketAddr }, + + #[error("Failed to bind to socket: {addr:?}, with error: {err:?}")] + UnableToBindToSocket { err: Arc, addr: SocketAddr }, + + #[error("Timeout while waiting for connection to remote: {remote_addr:?}")] + TimeoutWhileConnectingToRemote { remote_addr: SocketAddr }, + + #[error("Failed to connect to remote: {remote_addr:?}, with error: {err:?}")] + UnableToConnectToRemote { + err: Arc, + remote_addr: SocketAddr, + }, + + #[error("Timeout while waiting for the socket to become writable.")] + TimeoutWaitForWriteableSocket, + + #[error("Failed to get writable socket: {err:?}")] + UnableToGetWritableSocket { err: Arc }, + + #[error("Timeout while trying to send data: {data:?}")] + TimeoutWhileSendingData { data: Vec }, + + #[error("Failed to send data: {data:?}, with error: {err:?}")] + UnableToSendData { err: Arc, data: Vec }, + + #[error("Timeout while waiting for the socket to become readable.")] + TimeoutWaitForReadableSocket, + + #[error("Failed to get readable socket: {err:?}")] + UnableToGetReadableSocket { err: Arc }, + + #[error("Timeout while trying to receive data.")] + TimeoutWhileReceivingData, + + #[error("Failed to receive data: {err:?}")] + UnableToReceivingData { err: Arc }, + + #[error("Failed to get data from request: {request:?}, with error: {err:?}")] + UnableToWriteDataFromRequest { err: Arc, request: Request }, + + #[error("Failed to parse response: {response:?}, with error: {err:?}")] + UnableToParseResponse { err: Arc, response: Vec }, +} + +impl From for DynError { + fn from(e: Error) -> Self { + Arc::new(Box::new(e)) + } +} diff --git a/packages/tracker-core/.gitignore b/packages/tracker-core/.gitignore new file mode 100644 index 000000000..c5cb1afac --- /dev/null +++ b/packages/tracker-core/.gitignore @@ -0,0 +1 @@ +.coverage \ No newline at end of file diff --git a/packages/tracker-core/Cargo.toml b/packages/tracker-core/Cargo.toml new file mode 100644 index 000000000..fb864cde7 --- /dev/null +++ b/packages/tracker-core/Cargo.toml @@ -0,0 +1,46 @@ +[package] +authors.workspace = true +description = "A library with the core functionality needed to implement a BitTorrent tracker." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = [ "api", "bittorrent", "core", "library", "tracker" ] +license.workspace = true +name = "bittorrent-tracker-core" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +bittorrent-primitives = "0.1.0" +chrono = { version = "0", default-features = false, features = [ "clock" ] } +derive_more = { version = "2", features = [ "as_ref", "constructor", "from" ] } +mockall = "0" +r2d2 = "0" +r2d2_mysql = "25" +r2d2_sqlite = { version = "0", features = [ "bundled" ] } +rand = "0" +serde = { version = "1", features = [ "derive" ] } +serde_json = { version = "1", features = [ "preserve_order" ] } +thiserror = "2" +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } +tokio-util = "0.7.15" +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } +torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } +torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } +tracing = "0" + +[dev-dependencies] +local-ip-address = "0" +mockall = "0" +testcontainers = "0" +torrust-rest-tracker-api-client = { version = "3.0.0-develop", path = "../rest-tracker-api-client" } +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } +url = "2.5.4" diff --git a/packages/tracker-core/LICENSE b/packages/tracker-core/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/tracker-core/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/tracker-core/README.md b/packages/tracker-core/README.md new file mode 100644 index 000000000..f80243d29 --- /dev/null +++ b/packages/tracker-core/README.md @@ -0,0 +1,39 @@ +# BitTorrent Core Tracker library + +A library with the core functionality needed to implement a BitTorrent tracker. + +You usually don’t need to use this library directly. Instead, you should use the [Torrust Tracker](https://github.com/torrust/torrust-tracker). If you want to build your own tracker, you can use this library as the core functionality. In that case, you should add the delivery layer (HTTP or UDP) on top of this library. + +> **Disclaimer**: This library is actively under development. We’re currently extracting and refining common types from the[Torrust Tracker](https://github.com/torrust/torrust-tracker) to make them available to the BitTorrent community in Rust. While these types are functional, they are not yet ready for use in production or third-party projects. + +## Documentation + +[Crate documentation](https://docs.rs/bittorrent-tracker-core). + +## Testing + +Run tests including tests for MySQL driver: + +```console +TORRUST_TRACKER_CORE_RUN_MYSQL_DRIVER_TEST=true cargo test +``` + +> NOTE: MySQL driver requires docker to run. We don't run them by default because we don't want to run them when we build container images. The Torrust Tracker container build runs unit tests for all dependencies, including this library. + +Show coverage report: + +```console +TORRUST_TRACKER_CORE_RUN_MYSQL_DRIVER_TEST=true cargo +stable llvm-cov +``` + +Export coverage report to `lcov` format: + +```console +TORRUST_TRACKER_CORE_RUN_MYSQL_DRIVER_TEST=true cargo +stable llvm-cov --lcov --output-path=./.coverage/lcov.info +``` + +If you use Visual Studio Code, you can use the [Coverage Gutters](https://marketplace.visualstudio.com/items?itemName=semasquare.vscode-coverage-gutters) extension to view the coverage lines. + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/tracker-core/migrations/README.md b/packages/tracker-core/migrations/README.md new file mode 100644 index 000000000..090c46ccb --- /dev/null +++ b/packages/tracker-core/migrations/README.md @@ -0,0 +1,5 @@ +# Database Migrations + +We don't support automatic migrations yet. The tracker creates all the needed tables when it starts. The SQL sentences are hardcoded in each database driver. + +The migrations in this folder were introduced to add some new changes (permanent keys) and to allow users to migrate to the new version. In the future, we will remove the hardcoded SQL and start using a Rust crate for database migrations. For the time being, if you are using the initial schema described in the migration `20240730183000_torrust_tracker_create_all_tables.sql` you will need to run all the subsequent migrations manually. diff --git a/packages/tracker-core/migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql b/packages/tracker-core/migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql new file mode 100644 index 000000000..ab160bd75 --- /dev/null +++ b/packages/tracker-core/migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql @@ -0,0 +1,22 @@ +CREATE TABLE + IF NOT EXISTS whitelist ( + id integer PRIMARY KEY AUTO_INCREMENT, + info_hash VARCHAR(40) NOT NULL UNIQUE + ); + +# todo: rename to `torrent_metrics` +CREATE TABLE + IF NOT EXISTS torrents ( + id integer PRIMARY KEY AUTO_INCREMENT, + info_hash VARCHAR(40) NOT NULL UNIQUE, + completed INTEGER DEFAULT 0 NOT NULL + ); + +CREATE TABLE + IF NOT EXISTS `keys` ( + `id` INT NOT NULL AUTO_INCREMENT, + `key` VARCHAR(32) NOT NULL, + `valid_until` INT (10) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE (`key`) + ); \ No newline at end of file diff --git a/packages/tracker-core/migrations/mysql/20240730183500_torrust_tracker_keys_valid_until_nullable.sql b/packages/tracker-core/migrations/mysql/20240730183500_torrust_tracker_keys_valid_until_nullable.sql new file mode 100644 index 000000000..2602797d6 --- /dev/null +++ b/packages/tracker-core/migrations/mysql/20240730183500_torrust_tracker_keys_valid_until_nullable.sql @@ -0,0 +1 @@ +ALTER TABLE `keys` CHANGE `valid_until` `valid_until` INT (10); \ No newline at end of file diff --git a/packages/tracker-core/migrations/mysql/20250527093000_torrust_tracker_new_torrent_aggregate_metrics_table.sql b/packages/tracker-core/migrations/mysql/20250527093000_torrust_tracker_new_torrent_aggregate_metrics_table.sql new file mode 100644 index 000000000..36f940cc3 --- /dev/null +++ b/packages/tracker-core/migrations/mysql/20250527093000_torrust_tracker_new_torrent_aggregate_metrics_table.sql @@ -0,0 +1,6 @@ +CREATE TABLE + IF NOT EXISTS torrent_aggregate_metrics ( + id integer PRIMARY KEY AUTO_INCREMENT, + metric_name VARCHAR(50) NOT NULL UNIQUE, + value INTEGER DEFAULT 0 NOT NULL + ); \ No newline at end of file diff --git a/packages/tracker-core/migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql b/packages/tracker-core/migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql new file mode 100644 index 000000000..c5bcad926 --- /dev/null +++ b/packages/tracker-core/migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql @@ -0,0 +1,20 @@ +CREATE TABLE + IF NOT EXISTS whitelist ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + info_hash TEXT NOT NULL UNIQUE + ); + +# todo: rename to `torrent_metrics` +CREATE TABLE + IF NOT EXISTS torrents ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + info_hash TEXT NOT NULL UNIQUE, + completed INTEGER DEFAULT 0 NOT NULL + ); + +CREATE TABLE + IF NOT EXISTS keys ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + key TEXT NOT NULL UNIQUE, + valid_until INTEGER NOT NULL + ); \ No newline at end of file diff --git a/packages/tracker-core/migrations/sqlite/20240730183500_torrust_tracker_keys_valid_until_nullable.sql b/packages/tracker-core/migrations/sqlite/20240730183500_torrust_tracker_keys_valid_until_nullable.sql new file mode 100644 index 000000000..c6746e3ee --- /dev/null +++ b/packages/tracker-core/migrations/sqlite/20240730183500_torrust_tracker_keys_valid_until_nullable.sql @@ -0,0 +1,12 @@ +CREATE TABLE + IF NOT EXISTS keys_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + key TEXT NOT NULL UNIQUE, + valid_until INTEGER + ); + +INSERT INTO keys_new SELECT * FROM `keys`; + +DROP TABLE `keys`; + +ALTER TABLE keys_new RENAME TO `keys`; \ No newline at end of file diff --git a/packages/tracker-core/migrations/sqlite/20250527093000_torrust_tracker_new_torrent_aggregate_metrics_table.sql b/packages/tracker-core/migrations/sqlite/20250527093000_torrust_tracker_new_torrent_aggregate_metrics_table.sql new file mode 100644 index 000000000..34166903c --- /dev/null +++ b/packages/tracker-core/migrations/sqlite/20250527093000_torrust_tracker_new_torrent_aggregate_metrics_table.sql @@ -0,0 +1,6 @@ +CREATE TABLE + IF NOT EXISTS torrent_aggregate_metrics ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + metric_name TEXT NOT NULL UNIQUE, + value INTEGER DEFAULT 0 NOT NULL + ); \ No newline at end of file diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs new file mode 100644 index 000000000..0b6bffd31 --- /dev/null +++ b/packages/tracker-core/src/announce_handler.rs @@ -0,0 +1,689 @@ +//! Announce handler. +//! +//! Handling `announce` requests is the most important task for a `BitTorrent` +//! tracker. +//! +//! A `BitTorrent` swarm is a network of peers that are all trying to download +//! the same torrent. When a peer wants to find other peers it announces itself +//! to the swarm via the tracker. The peer sends its data to the tracker so that +//! the tracker can add it to the swarm. The tracker responds to the peer with +//! the list of other peers in the swarm so that the peer can contact them to +//! start downloading pieces of the file from them. +//! +//! Once you have instantiated the `AnnounceHandler` you can `announce` a new [`peer::Peer`](torrust_tracker_primitives) with: +//! +//! ```rust,no_run +//! use std::net::SocketAddr; +//! use std::net::IpAddr; +//! use std::net::Ipv4Addr; +//! use std::str::FromStr; +//! +//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +//! use torrust_tracker_primitives::DurationSinceUnixEpoch; +//! use torrust_tracker_primitives::peer; +//! use bittorrent_primitives::info_hash::InfoHash; +//! +//! let info_hash = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(); +//! +//! let peer = peer::Peer { +//! peer_id: PeerId(*b"-qB00000000000000001"), +//! peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), +//! updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), +//! uploaded: NumberOfBytes::new(0), +//! downloaded: NumberOfBytes::new(0), +//! left: NumberOfBytes::new(0), +//! event: AnnounceEvent::Completed, +//! }; +//! +//! let peer_ip = IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()); +//! ``` +//! +//! ```text +//! let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip).await; +//! ``` +//! +//! The handler returns the list of peers for the torrent with the infohash +//! `3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0`, filtering out the peer that is +//! making the `announce` request. +//! +//! > **NOTICE**: that the peer argument is mutable because the handler can +//! > change the peer IP if the peer is using a loopback IP. +//! +//! The `peer_ip` argument is the resolved peer ip. It's a common practice that +//! trackers ignore the peer ip in the `announce` request params, and resolve +//! the peer ip using the IP of the client making the request. As the tracker is +//! a domain service, the peer IP must be provided for the handler user, which +//! is usually a higher component with access the the request metadata, for +//! example, connection data, proxy headers, etcetera. +//! +//! The returned struct is: +//! +//! ```rust,no_run +//! use torrust_tracker_primitives::peer; +//! use torrust_tracker_configuration::AnnouncePolicy; +//! +//! pub struct AnnounceData { +//! pub peers: Vec, +//! pub swarm_stats: SwarmMetadata, +//! pub policy: AnnouncePolicy, // the tracker announce policy. +//! } +//! +//! pub struct SwarmMetadata { +//! pub completed: u32, // The number of peers that have ever completed downloading +//! pub seeders: u32, // The number of active peers that have completed downloading (seeders) +//! pub leechers: u32, // The number of active peers that have not completed downloading (leechers) +//! } +//! +//! // Core tracker configuration +//! pub struct AnnounceInterval { +//! // ... +//! pub interval: u32, // Interval in seconds that the client should wait between sending regular announce requests to the tracker +//! pub interval_min: u32, // Minimum announce interval. Clients must not reannounce more frequently than this +//! // ... +//! } +//! ``` +//! +//! ## Related BEPs: +//! +//! Refer to `BitTorrent` BEPs and other sites for more information about the `announce` request: +//! +//! - [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) +//! - [BEP 23. Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) +//! - [Vuze docs](https://wiki.vuze.com/w/Announce) +use std::net::IpAddr; +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::{Core, TORRENT_PEERS_LIMIT}; +use torrust_tracker_primitives::core::AnnounceData; +use torrust_tracker_primitives::{peer, NumberOfDownloads}; + +use super::torrent::repository::in_memory::InMemoryTorrentRepository; +use crate::databases; +use crate::error::AnnounceError; +use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; +use crate::whitelist::authorization::WhitelistAuthorization; + +/// Handles `announce` requests from `BitTorrent` clients. +pub struct AnnounceHandler { + /// The tracker configuration. + config: Core, + + /// Service for authorizing access to whitelisted torrents. + whitelist_authorization: Arc, + + /// Repository for in-memory torrent data. + in_memory_torrent_repository: Arc, + + /// Repository for persistent torrent data (database). + db_downloads_metric_repository: Arc, +} + +impl AnnounceHandler { + /// Creates a new `AnnounceHandler`. + #[must_use] + pub fn new( + config: &Core, + whitelist_authorization: &Arc, + in_memory_torrent_repository: &Arc, + db_downloads_metric_repository: &Arc, + ) -> Self { + Self { + whitelist_authorization: whitelist_authorization.clone(), + config: config.clone(), + in_memory_torrent_repository: in_memory_torrent_repository.clone(), + db_downloads_metric_repository: db_downloads_metric_repository.clone(), + } + } + + /// Processes an announce request from a peer. + /// + /// BEP 03: [The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html). + /// + /// # Parameters + /// + /// - `info_hash`: The unique identifier of the torrent. + /// - `peer`: The peer announcing itself (may be updated if IP is adjusted). + /// - `remote_client_ip`: The IP address of the client making the request. + /// - `peers_wanted`: Specifies how many peers the client wants in the response. + /// + /// # Returns + /// + /// An `AnnounceData` struct containing the list of peers, swarm statistics, and tracker policy. + /// + /// # Errors + /// + /// Returns an error if the tracker is running in `listed` mode and the + /// torrent is not whitelisted. + pub async fn handle_announcement( + &self, + info_hash: &InfoHash, + peer: &mut peer::Peer, + remote_client_ip: &IpAddr, + peers_wanted: &PeersWanted, + ) -> Result { + self.whitelist_authorization.authorize(info_hash).await?; + + peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.net.external_ip)); + + self.in_memory_torrent_repository + .handle_announcement(info_hash, peer, self.load_downloads_metric_if_needed(info_hash)?) + .await; + + Ok(self.build_announce_data(info_hash, peer, peers_wanted).await) + } + + /// Loads the number of downloads for a torrent if needed. + fn load_downloads_metric_if_needed( + &self, + info_hash: &InfoHash, + ) -> Result, databases::error::Error> { + if self.config.tracker_policy.persistent_torrent_completed_stat && !self.in_memory_torrent_repository.contains(info_hash) + { + Ok(self.db_downloads_metric_repository.load_torrent_downloads(info_hash)?) + } else { + Ok(None) + } + } + + /// Builds the announce data for the peer making the request. + async fn build_announce_data(&self, info_hash: &InfoHash, peer: &peer::Peer, peers_wanted: &PeersWanted) -> AnnounceData { + let peers = self + .in_memory_torrent_repository + .get_peers_for(info_hash, peer, peers_wanted.limit()) + .await; + + let swarm_metadata = self + .in_memory_torrent_repository + .get_swarm_metadata_or_default(info_hash) + .await; + + AnnounceData { + peers, + stats: swarm_metadata, + policy: self.config.announce_policy, + } + } +} + +/// Specifies how many peers a client wants in the announce response. +#[derive(Clone, Debug, PartialEq, Default)] +pub enum PeersWanted { + /// Request as many peers as possible (default behavior). + #[default] + AsManyAsPossible, + + /// Request a specific number of peers. + Only { amount: usize }, +} + +impl PeersWanted { + /// Request a specific number of peers. + #[must_use] + pub fn only(limit: u32) -> Self { + limit.into() + } + + /// Returns the maximum number of peers allowed based on the request and tracker limit. + fn limit(&self) -> usize { + match self { + PeersWanted::AsManyAsPossible => TORRENT_PEERS_LIMIT, + PeersWanted::Only { amount } => *amount, + } + } +} + +impl From for PeersWanted { + fn from(value: i32) -> Self { + if value <= 0 { + return PeersWanted::AsManyAsPossible; + } + + // This conversion is safe because `value > 0` + let amount = usize::try_from(value).unwrap(); + + PeersWanted::Only { + amount: amount.min(TORRENT_PEERS_LIMIT), + } + } +} + +impl From for PeersWanted { + fn from(value: u32) -> Self { + if value == 0 { + return PeersWanted::AsManyAsPossible; + } + + let amount = value as usize; + + PeersWanted::Only { + amount: amount.min(TORRENT_PEERS_LIMIT), + } + } +} + +/// Assigns the correct IP address to a peer based on tracker settings. +/// +/// If the client IP is a loopback address and the tracker has an external IP +/// configured, the external IP will be assigned to the peer. +#[must_use] +fn assign_ip_address_to_peer(remote_client_ip: &IpAddr, tracker_external_ip: Option) -> IpAddr { + if let Some(host_ip) = tracker_external_ip.filter(|_| remote_client_ip.is_loopback()) { + host_ip + } else { + *remote_client_ip + } +} + +#[cfg(test)] +mod tests { + mod the_announce_handler { + + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::str::FromStr; + use std::sync::Arc; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + use torrust_tracker_test_helpers::configuration; + + use crate::announce_handler::AnnounceHandler; + use crate::scrape_handler::ScrapeHandler; + use crate::test_helpers::tests::initialize_handlers; + + fn public_tracker() -> (Arc, Arc) { + let config = configuration::ephemeral_public(); + initialize_handlers(&config) + } + + // The client peer IP + fn peer_ip() -> IpAddr { + IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) + } + + /// Sample peer when for tests that need more than one peer + fn sample_peer_1() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000001"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), + event: AnnounceEvent::Completed, + } + } + + /// Sample peer when for tests that need more than one peer + fn sample_peer_2() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000002"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)), 8082), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), + event: AnnounceEvent::Completed, + } + } + + /// Sample peer when for tests that need more than two peer + fn sample_peer_3() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000003"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 3)), 8082), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), + event: AnnounceEvent::Completed, + } + } + + mod for_all_tracker_config_modes { + + mod handling_an_announce_request { + + use std::sync::Arc; + + use crate::announce_handler::tests::the_announce_handler::{ + peer_ip, public_tracker, sample_peer_1, sample_peer_2, sample_peer_3, + }; + use crate::announce_handler::PeersWanted; + use crate::test_helpers::tests::{sample_info_hash, sample_peer}; + + mod should_assign_the_ip_to_the_peer { + + use std::net::{IpAddr, Ipv4Addr}; + + use crate::announce_handler::assign_ip_address_to_peer; + + #[test] + fn using_the_source_ip_instead_of_the_ip_in_the_announce_request() { + let remote_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)); + + let peer_ip = assign_ip_address_to_peer(&remote_ip, None); + + assert_eq!(peer_ip, remote_ip); + } + + mod and_when_the_client_ip_is_a_ipv4_loopback_ip { + + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + use std::str::FromStr; + + use crate::announce_handler::assign_ip_address_to_peer; + + #[test] + fn it_should_use_the_loopback_ip_if_the_tracker_does_not_have_the_external_ip_configuration() { + let remote_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); + + let peer_ip = assign_ip_address_to_peer(&remote_ip, None); + + assert_eq!(peer_ip, remote_ip); + } + + #[test] + fn it_should_use_the_external_tracker_ip_in_tracker_configuration_if_it_is_defined() { + let remote_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); + + let tracker_external_ip = IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()); + + let peer_ip = assign_ip_address_to_peer(&remote_ip, Some(tracker_external_ip)); + + assert_eq!(peer_ip, tracker_external_ip); + } + + #[test] + fn it_should_use_the_external_ip_in_the_tracker_configuration_if_it_is_defined_even_if_the_external_ip_is_an_ipv6_ip( + ) { + let remote_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); + + let tracker_external_ip = + IpAddr::V6(Ipv6Addr::from_str("2345:0425:2CA1:0000:0000:0567:5673:23b5").unwrap()); + + let peer_ip = assign_ip_address_to_peer(&remote_ip, Some(tracker_external_ip)); + + assert_eq!(peer_ip, tracker_external_ip); + } + } + + mod and_when_client_ip_is_a_ipv6_loopback_ip { + + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + use std::str::FromStr; + + use crate::announce_handler::assign_ip_address_to_peer; + + #[test] + fn it_should_use_the_loopback_ip_if_the_tracker_does_not_have_the_external_ip_configuration() { + let remote_ip = IpAddr::V6(Ipv6Addr::LOCALHOST); + + let peer_ip = assign_ip_address_to_peer(&remote_ip, None); + + assert_eq!(peer_ip, remote_ip); + } + + #[test] + fn it_should_use_the_external_ip_in_tracker_configuration_if_it_is_defined() { + let remote_ip = IpAddr::V6(Ipv6Addr::LOCALHOST); + + let tracker_external_ip = + IpAddr::V6(Ipv6Addr::from_str("2345:0425:2CA1:0000:0000:0567:5673:23b5").unwrap()); + + let peer_ip = assign_ip_address_to_peer(&remote_ip, Some(tracker_external_ip)); + + assert_eq!(peer_ip, tracker_external_ip); + } + + #[test] + fn it_should_use_the_external_ip_in_the_tracker_configuration_if_it_is_defined_even_if_the_external_ip_is_an_ipv4_ip( + ) { + let remote_ip = IpAddr::V6(Ipv6Addr::LOCALHOST); + + let tracker_external_ip = IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()); + + let peer_ip = assign_ip_address_to_peer(&remote_ip, Some(tracker_external_ip)); + + assert_eq!(peer_ip, tracker_external_ip); + } + } + } + + #[tokio::test] + async fn it_should_return_the_announce_data_with_an_empty_peer_list_when_it_is_the_first_announced_peer() { + let (announce_handler, _scrape_handler) = public_tracker(); + + let mut peer = sample_peer(); + + let announce_data = announce_handler + .handle_announcement(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) + .await + .unwrap(); + + assert_eq!(announce_data.peers, vec![]); + } + + #[tokio::test] + async fn it_should_return_the_announce_data_with_the_previously_announced_peers() { + let (announce_handler, _scrape_handler) = public_tracker(); + + let mut previously_announced_peer = sample_peer_1(); + announce_handler + .handle_announcement( + &sample_info_hash(), + &mut previously_announced_peer, + &peer_ip(), + &PeersWanted::AsManyAsPossible, + ) + .await + .unwrap(); + + let mut peer = sample_peer_2(); + let announce_data = announce_handler + .handle_announcement(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) + .await + .unwrap(); + + assert_eq!(announce_data.peers, vec![Arc::new(previously_announced_peer)]); + } + + #[tokio::test] + async fn it_should_allow_peers_to_get_only_a_subset_of_the_peers_in_the_swarm() { + let (announce_handler, _scrape_handler) = public_tracker(); + + let mut previously_announced_peer_1 = sample_peer_1(); + announce_handler + .handle_announcement( + &sample_info_hash(), + &mut previously_announced_peer_1, + &peer_ip(), + &PeersWanted::AsManyAsPossible, + ) + .await + .unwrap(); + + let mut previously_announced_peer_2 = sample_peer_2(); + announce_handler + .handle_announcement( + &sample_info_hash(), + &mut previously_announced_peer_2, + &peer_ip(), + &PeersWanted::AsManyAsPossible, + ) + .await + .unwrap(); + + let mut peer = sample_peer_3(); + let announce_data = announce_handler + .handle_announcement(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::only(1)) + .await + .unwrap(); + + // It should return only one peer. There is no guarantee on + // which peer will be returned. + assert!( + announce_data.peers == vec![Arc::new(previously_announced_peer_1)] + || announce_data.peers == vec![Arc::new(previously_announced_peer_2)] + ); + } + + mod it_should_update_the_swarm_stats_for_the_torrent { + + use crate::announce_handler::tests::the_announce_handler::{peer_ip, public_tracker}; + use crate::announce_handler::PeersWanted; + use crate::test_helpers::tests::{completed_peer, leecher, sample_info_hash, seeder, started_peer}; + + #[tokio::test] + async fn when_the_peer_is_a_seeder() { + let (announce_handler, _scrape_handler) = public_tracker(); + + let mut peer = seeder(); + + let announce_data = announce_handler + .handle_announcement(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) + .await + .unwrap(); + + assert_eq!(announce_data.stats.complete, 1); + } + + #[tokio::test] + async fn when_the_peer_is_a_leecher() { + let (announce_handler, _scrape_handler) = public_tracker(); + + let mut peer = leecher(); + + let announce_data = announce_handler + .handle_announcement(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) + .await + .unwrap(); + + assert_eq!(announce_data.stats.incomplete, 1); + } + + #[tokio::test] + async fn when_a_previously_announced_started_peer_has_completed_downloading() { + let (announce_handler, _scrape_handler) = public_tracker(); + + // We have to announce with "started" event because peer does not count if peer was not previously known + let mut started_peer = started_peer(); + announce_handler + .handle_announcement( + &sample_info_hash(), + &mut started_peer, + &peer_ip(), + &PeersWanted::AsManyAsPossible, + ) + .await + .unwrap(); + + let mut completed_peer = completed_peer(); + let announce_data = announce_handler + .handle_announcement( + &sample_info_hash(), + &mut completed_peer, + &peer_ip(), + &PeersWanted::AsManyAsPossible, + ) + .await + .unwrap(); + + assert_eq!(announce_data.stats.downloaded, 1); + } + } + } + } + + mod should_allow_the_client_peers_to_specified_the_number_of_peers_wanted { + + use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; + + use crate::announce_handler::PeersWanted; + + #[test] + fn it_should_return_the_maximin_number_of_peers_by_default() { + let peers_wanted = PeersWanted::default(); + + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + } + + #[test] + fn it_should_return_74_at_the_most_if_the_client_wants_them_all() { + let peers_wanted = PeersWanted::AsManyAsPossible; + + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + } + + #[test] + fn it_should_allow_limiting_the_peer_list() { + let peers_wanted = PeersWanted::only(10); + + assert_eq!(peers_wanted.limit(), 10); + } + + fn maximum_as_u32() -> u32 { + u32::try_from(TORRENT_PEERS_LIMIT).unwrap() + } + + fn maximum_as_i32() -> i32 { + i32::try_from(TORRENT_PEERS_LIMIT).unwrap() + } + + #[test] + fn it_should_return_the_maximum_when_wanting_more_than_the_maximum() { + let peers_wanted = PeersWanted::only(maximum_as_u32() + 1); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + } + + #[test] + fn it_should_return_the_maximum_when_wanting_only_zero() { + let peers_wanted = PeersWanted::only(0); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + } + + #[test] + fn it_should_convert_the_peers_wanted_number_from_i32() { + // Negative. It should return the maximum + let peers_wanted: PeersWanted = (-1i32).into(); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + + // Zero. It should return the maximum + let peers_wanted: PeersWanted = 0i32.into(); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + + // Greater than the maximum. It should return the maximum + let peers_wanted: PeersWanted = (maximum_as_i32() + 1).into(); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + + // The maximum + let peers_wanted: PeersWanted = (maximum_as_i32()).into(); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + + // Smaller than the maximum + let peers_wanted: PeersWanted = (maximum_as_i32() - 1).into(); + assert_eq!(i32::try_from(peers_wanted.limit()).unwrap(), maximum_as_i32() - 1); + } + + #[test] + fn it_should_convert_the_peers_wanted_number_from_u32() { + // Zero. It should return the maximum + let peers_wanted: PeersWanted = 0u32.into(); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + + // Greater than the maximum. It should return the maximum + let peers_wanted: PeersWanted = (maximum_as_u32() + 1).into(); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + + // The maximum + let peers_wanted: PeersWanted = (maximum_as_u32()).into(); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + + // Smaller than the maximum + let peers_wanted: PeersWanted = (maximum_as_u32() - 1).into(); + assert_eq!(i32::try_from(peers_wanted.limit()).unwrap(), maximum_as_i32() - 1); + } + } + } +} diff --git a/packages/tracker-core/src/authentication/handler.rs b/packages/tracker-core/src/authentication/handler.rs new file mode 100644 index 000000000..178895b8d --- /dev/null +++ b/packages/tracker-core/src/authentication/handler.rs @@ -0,0 +1,684 @@ +//! This module implements the `KeysHandler` service +//! +//! It's responsible for managing authentication keys for the `BitTorrent` tracker. +//! +//! The service handles both persistent and in-memory storage of peer keys, and +//! supports adding new keys (either pre-generated or randomly created), +//! removing keys, and loading keys from the database into memory. Keys can be +//! either permanent or expire after a configurable duration per key. +use std::sync::Arc; +use std::time::Duration; + +use torrust_tracker_clock::clock::Time; +use torrust_tracker_located_error::Located; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::key::repository::in_memory::InMemoryKeyRepository; +use super::key::repository::persisted::DatabaseKeyRepository; +use super::{key, CurrentClock, Key, PeerKey}; +use crate::databases; +use crate::error::PeerKeyError; + +/// Contains the information needed to add a new tracker key. +/// +/// A new key can either be a pre-generated key provided by the user or can be +/// randomly generated by the application. Additionally, the key may be set to +/// expire after a certain number of seconds, or be permanent (if no expiration +/// is specified). +#[derive(Debug)] +pub struct AddKeyRequest { + /// The pre-generated key as a string. If `None` the service will generate a + /// random key. + pub opt_key: Option, + + /// The duration (in seconds) for which the key is valid. Use `None` for + /// permanent keys. + pub opt_seconds_valid: Option, +} + +/// The `KeysHandler` service manages the creation, addition, removal, and loading +/// of authentication keys for the tracker. +/// +/// It uses both a persistent (database) repository and an in-memory repository +/// to manage keys. +pub struct KeysHandler { + /// The database repository for storing authentication keys persistently. + db_key_repository: Arc, + + /// The in-memory repository for caching authentication keys. + in_memory_key_repository: Arc, +} + +impl KeysHandler { + /// Creates a new instance of the `KeysHandler` service. + /// + /// # Parameters + /// + /// - `db_key_repository`: A shared reference to the database key repository. + /// - `in_memory_key_repository`: A shared reference to the in-memory key + /// repository. + #[must_use] + pub fn new(db_key_repository: &Arc, in_memory_key_repository: &Arc) -> Self { + Self { + db_key_repository: db_key_repository.clone(), + in_memory_key_repository: in_memory_key_repository.clone(), + } + } + + /// Adds a new peer key to the tracker. + /// + /// The key may be pre-generated or generated on-the-fly. + /// + /// Depending on whether an expiration duration is specified, the key will + /// be either expiring or permanent. + /// + /// # Parameters + /// + /// - `add_key_req`: The request containing options for key creation. + /// + /// # Errors + /// + /// Returns an error if: + /// + /// - The provided key duration exceeds the maximum allowed value. + /// - The provided pre-generated key is invalid. + /// - There is an error persisting the key in the database. + pub async fn add_peer_key(&self, add_key_req: AddKeyRequest) -> Result { + if let Some(pre_existing_key) = add_key_req.opt_key { + // Pre-generated key + + if let Some(seconds_valid) = add_key_req.opt_seconds_valid { + // Expiring key + + let Some(valid_until) = CurrentClock::now_add(&Duration::from_secs(seconds_valid)) else { + return Err(PeerKeyError::DurationOverflow { seconds_valid }); + }; + + let key = pre_existing_key.parse::(); + + match key { + Ok(key) => match self.add_expiring_peer_key(key, Some(valid_until)).await { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { + source: Located(err).into(), + }), + }, + Err(err) => Err(PeerKeyError::InvalidKey { + key: pre_existing_key, + source: Located(err).into(), + }), + } + } else { + // Permanent key + + let key = pre_existing_key.parse::(); + + match key { + Ok(key) => match self.add_permanent_peer_key(key).await { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { + source: Located(err).into(), + }), + }, + Err(err) => Err(PeerKeyError::InvalidKey { + key: pre_existing_key, + source: Located(err).into(), + }), + } + } + } else { + // New randomly generate key + + if let Some(seconds_valid) = add_key_req.opt_seconds_valid { + // Expiring key + + match self + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) + .await + { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { + source: Located(err).into(), + }), + } + } else { + // Permanent key + + match self.generate_permanent_peer_key().await { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { + source: Located(err).into(), + }), + } + } + } + } + + /// Generates a new permanent authentication key. + /// + /// Permanent keys do not expire. + /// + /// # Errors + /// + /// Returns a `databases::error::Error` if the key cannot be persisted in + /// the database. + pub(crate) async fn generate_permanent_peer_key(&self) -> Result { + self.generate_expiring_peer_key(None).await + } + + /// Generates a new authentication key with an optional expiration lifetime. + /// + /// If a `lifetime` is provided, the generated key will expire after that + /// duration. The new key is stored both in the database and in memory. + /// + /// # Parameters + /// + /// - `lifetime`: An optional duration specifying how long the key is valid. + /// + /// # Errors + /// + /// Returns a `databases::error::Error` if there is an issue adding the key + /// to the database. + pub async fn generate_expiring_peer_key(&self, lifetime: Option) -> Result { + let peer_key = key::generate_key(lifetime); + + self.db_key_repository.add(&peer_key)?; + + self.in_memory_key_repository.insert(&peer_key).await; + + Ok(peer_key) + } + + /// Adds a pre-generated permanent authentication key. + /// + /// Internally, this calls `add_expiring_peer_key` with no expiration. + /// + /// # Parameters + /// + /// - `key`: The pre-generated key. + /// + /// # Errors + /// + /// Returns a `databases::error::Error` if there is an issue persisting the + /// key. + pub(crate) async fn add_permanent_peer_key(&self, key: Key) -> Result { + self.add_expiring_peer_key(key, None).await + } + + /// Adds a pre-generated authentication key with an optional expiration. + /// + /// The key is stored in both the database and the in-memory repository. + /// + /// # Parameters + /// + /// - `key`: The pre-generated key. + /// - `valid_until`: An optional timestamp (as a duration since the Unix + /// epoch) after which the key expires. + /// + /// # Errors + /// + /// Returns a `databases::error::Error` if there is an issue adding the key + /// to the database. + pub(crate) async fn add_expiring_peer_key( + &self, + key: Key, + valid_until: Option, + ) -> Result { + let peer_key = PeerKey { key, valid_until }; + + // code-review: should we return a friendly error instead of the DB + // constrain error when the key already exist? For now, it's returning + // the specif error for each DB driver when a UNIQUE constrain fails. + self.db_key_repository.add(&peer_key)?; + + self.in_memory_key_repository.insert(&peer_key).await; + + Ok(peer_key) + } + + /// Removes an authentication key. + /// + /// The key is removed from both the database and the in-memory repository. + /// + /// # Parameters + /// + /// - `key`: A reference to the key to be removed. + /// + /// # Errors + /// + /// Returns a `databases::error::Error` if the key cannot be removed from + /// the database. + pub async fn remove_peer_key(&self, key: &Key) -> Result<(), databases::error::Error> { + self.db_key_repository.remove(key)?; + + self.remove_in_memory_auth_key(key).await; + + Ok(()) + } + + /// Removes an authentication key from the in-memory repository. + /// + /// This function does not interact with the database. + /// + /// # Parameters + /// + /// - `key`: A reference to the key to be removed. + pub(crate) async fn remove_in_memory_auth_key(&self, key: &Key) { + self.in_memory_key_repository.remove(key).await; + } + + /// Loads all authentication keys from the database into the in-memory + /// repository. + /// + /// This is useful during tracker startup to ensure that all persisted keys + /// are available in memory. + /// + /// # Errors + /// + /// Returns a `databases::error::Error` if there is an issue loading the keys from the database. + pub async fn load_peer_keys_from_database(&self) -> Result<(), databases::error::Error> { + let keys_from_database = self.db_key_repository.load_keys()?; + + self.in_memory_key_repository.reset_with(keys_from_database).await; + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + + mod the_keys_handler_when_the_tracker_is_configured_as_private { + + use std::sync::Arc; + + use torrust_tracker_configuration::Configuration; + use torrust_tracker_test_helpers::configuration; + + use crate::authentication::handler::KeysHandler; + use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::databases::setup::initialize_database; + use crate::databases::Database; + + fn instantiate_keys_handler() -> KeysHandler { + let config = configuration::ephemeral_private(); + + instantiate_keys_handler_with_configuration(&config) + } + + fn instantiate_keys_handler_with_database(database: &Arc>) -> KeysHandler { + let db_key_repository = Arc::new(DatabaseKeyRepository::new(database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + KeysHandler::new(&db_key_repository, &in_memory_key_repository) + } + + fn instantiate_keys_handler_with_configuration(config: &Configuration) -> KeysHandler { + // todo: pass only Core configuration + + let database = initialize_database(&config.core); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + KeysHandler::new(&db_key_repository, &in_memory_key_repository) + } + + mod handling_expiring_peer_keys { + + use std::time::Duration; + + use torrust_tracker_clock::clock::Time; + + use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::instantiate_keys_handler; + use crate::CurrentClock; + + #[tokio::test] + async fn it_should_generate_the_key() { + let keys_handler = instantiate_keys_handler(); + + let peer_key = keys_handler + .generate_expiring_peer_key(Some(Duration::from_secs(100))) + .await + .unwrap(); + + assert_eq!( + peer_key.valid_until, + Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) + ); + } + + mod randomly_generated { + use std::panic::Location; + use std::sync::Arc; + use std::time::Duration; + + use mockall::predicate::function; + use torrust_tracker_clock::clock::stopped::Stopped; + use torrust_tracker_clock::clock::{self, Time}; + + use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::{ + instantiate_keys_handler, instantiate_keys_handler_with_database, + }; + use crate::authentication::handler::AddKeyRequest; + use crate::authentication::PeerKey; + use crate::databases::driver::Driver; + use crate::databases::{self, Database, MockDatabase}; + use crate::error::PeerKeyError; + use crate::CurrentClock; + + #[tokio::test] + async fn it_should_add_a_randomly_generated_key() { + let keys_handler = instantiate_keys_handler(); + + let peer_key = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: None, + opt_seconds_valid: Some(100), + }) + .await + .unwrap(); + + assert_eq!( + peer_key.valid_until, + Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) + ); + } + + #[tokio::test] + async fn it_should_fail_adding_a_randomly_generated_key_when_there_is_a_database_error() { + clock::Stopped::local_set(&Duration::from_secs(0)); + + // The key should be valid the next 60 seconds. + let expected_valid_until = clock::Stopped::now_add(&Duration::from_secs(60)).unwrap(); + + let mut database_mock = MockDatabase::default(); + database_mock + .expect_add_key_to_keys() + .with(function(move |peer_key: &PeerKey| { + peer_key.valid_until == Some(expected_valid_until) + })) + .times(1) + .returning(|_peer_key| { + Err(databases::error::Error::InsertFailed { + location: Location::caller(), + driver: Driver::Sqlite3, + }) + }); + let database_mock: Arc> = Arc::new(Box::new(database_mock)); + + let keys_handler = instantiate_keys_handler_with_database(&database_mock); + + let result = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: None, + opt_seconds_valid: Some(60), // The key is valid for 60 seconds. + }) + .await; + + assert!(matches!(result.unwrap_err(), PeerKeyError::DatabaseError { .. })); + } + } + + mod pre_generated { + use std::panic::Location; + use std::sync::Arc; + use std::time::Duration; + + use mockall::predicate; + use torrust_tracker_clock::clock::stopped::Stopped; + use torrust_tracker_clock::clock::{self, Time}; + + use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::{ + instantiate_keys_handler, instantiate_keys_handler_with_database, + }; + use crate::authentication::handler::AddKeyRequest; + use crate::authentication::{Key, PeerKey}; + use crate::databases::driver::Driver; + use crate::databases::{self, Database, MockDatabase}; + use crate::error::PeerKeyError; + use crate::CurrentClock; + + #[tokio::test] + async fn it_should_add_a_pre_generated_key() { + let keys_handler = instantiate_keys_handler(); + + let peer_key = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: Some(100), + }) + .await + .unwrap(); + + assert_eq!( + peer_key, + PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()), + } + ); + } + + #[tokio::test] + async fn it_should_fail_adding_a_pre_generated_key_when_the_key_duration_exceeds_the_maximum_duration() { + let keys_handler = instantiate_keys_handler(); + + let result = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: Some(u64::MAX), + }) + .await; + + assert!(matches!(result.unwrap_err(), PeerKeyError::DurationOverflow { .. })); + } + + #[tokio::test] + async fn it_should_fail_adding_a_pre_generated_key_when_the_key_is_invalid() { + let keys_handler = instantiate_keys_handler(); + + let result = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: Some("INVALID KEY".to_string()), + opt_seconds_valid: Some(100), + }) + .await; + + assert!(matches!(result.unwrap_err(), PeerKeyError::InvalidKey { .. })); + } + + #[tokio::test] + async fn it_should_fail_adding_a_pre_generated_key_when_there_is_a_database_error() { + clock::Stopped::local_set(&Duration::from_secs(0)); + + // The key should be valid the next 60 seconds. + let expected_valid_until = clock::Stopped::now_add(&Duration::from_secs(60)).unwrap(); + let expected_peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(expected_valid_until), + }; + + let mut database_mock = MockDatabase::default(); + database_mock + .expect_add_key_to_keys() + .with(predicate::eq(expected_peer_key)) + .times(1) + .returning(|_peer_key| { + Err(databases::error::Error::InsertFailed { + location: Location::caller(), + driver: Driver::Sqlite3, + }) + }); + let database_mock: Arc> = Arc::new(Box::new(database_mock)); + + let keys_handler = instantiate_keys_handler_with_database(&database_mock); + + let result = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: Some(60), // The key is valid for 60 seconds. + }) + .await; + + assert!(matches!(result.unwrap_err(), PeerKeyError::DatabaseError { .. })); + } + } + } + + mod handling_permanent_peer_keys { + + mod randomly_generated { + + use std::panic::Location; + use std::sync::Arc; + + use mockall::predicate::function; + + use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::{ + instantiate_keys_handler, instantiate_keys_handler_with_database, + }; + use crate::authentication::handler::AddKeyRequest; + use crate::authentication::PeerKey; + use crate::databases::driver::Driver; + use crate::databases::{self, Database, MockDatabase}; + use crate::error::PeerKeyError; + + #[tokio::test] + async fn it_should_generate_the_key() { + let keys_handler = instantiate_keys_handler(); + + let peer_key = keys_handler.generate_permanent_peer_key().await.unwrap(); + + assert_eq!(peer_key.valid_until, None); + } + + #[tokio::test] + async fn it_should_add_a_randomly_generated_key() { + let keys_handler = instantiate_keys_handler(); + + let peer_key = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: None, + opt_seconds_valid: None, + }) + .await + .unwrap(); + + assert_eq!(peer_key.valid_until, None); + } + + #[tokio::test] + async fn it_should_fail_adding_a_randomly_generated_key_when_there_is_a_database_error() { + let mut database_mock = MockDatabase::default(); + database_mock + .expect_add_key_to_keys() + .with(function(move |peer_key: &PeerKey| peer_key.valid_until.is_none())) + .times(1) + .returning(|_peer_key| { + Err(databases::error::Error::InsertFailed { + location: Location::caller(), + driver: Driver::Sqlite3, + }) + }); + let database_mock: Arc> = Arc::new(Box::new(database_mock)); + + let keys_handler = instantiate_keys_handler_with_database(&database_mock); + + let result = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: None, + opt_seconds_valid: None, + }) + .await; + + assert!(matches!(result.unwrap_err(), PeerKeyError::DatabaseError { .. })); + } + } + + mod pre_generated_keys { + + use std::panic::Location; + use std::sync::Arc; + + use mockall::predicate; + + use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::{ + instantiate_keys_handler, instantiate_keys_handler_with_database, + }; + use crate::authentication::handler::AddKeyRequest; + use crate::authentication::{Key, PeerKey}; + use crate::databases::driver::Driver; + use crate::databases::{self, Database, MockDatabase}; + use crate::error::PeerKeyError; + + #[tokio::test] + async fn it_should_add_a_pre_generated_key() { + let keys_handler = instantiate_keys_handler(); + + let peer_key = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: None, + }) + .await + .unwrap(); + + assert_eq!( + peer_key, + PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: None, + } + ); + } + + #[tokio::test] + async fn it_should_fail_adding_a_pre_generated_key_when_the_key_is_invalid() { + let keys_handler = instantiate_keys_handler(); + + let result = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: Some("INVALID KEY".to_string()), + opt_seconds_valid: None, + }) + .await; + + assert!(matches!(result.unwrap_err(), PeerKeyError::InvalidKey { .. })); + } + + #[tokio::test] + async fn it_should_fail_adding_a_pre_generated_key_when_there_is_a_database_error() { + let expected_peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: None, + }; + + let mut database_mock = MockDatabase::default(); + database_mock + .expect_add_key_to_keys() + .with(predicate::eq(expected_peer_key)) + .times(1) + .returning(|_peer_key| { + Err(databases::error::Error::InsertFailed { + location: Location::caller(), + driver: Driver::Sqlite3, + }) + }); + let database_mock: Arc> = Arc::new(Box::new(database_mock)); + + let keys_handler = instantiate_keys_handler_with_database(&database_mock); + + let result = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: None, + }) + .await; + + assert!(matches!(result.unwrap_err(), PeerKeyError::DatabaseError { .. })); + } + } + } + } +} diff --git a/packages/tracker-core/src/authentication/key/mod.rs b/packages/tracker-core/src/authentication/key/mod.rs new file mode 100644 index 000000000..44bbd0688 --- /dev/null +++ b/packages/tracker-core/src/authentication/key/mod.rs @@ -0,0 +1,306 @@ +//! Tracker authentication services and types. +//! +//! This module provides functions and data structures for handling tracker keys. +//! Tracker keys are tokens used to authenticate tracker clients when the +//! tracker is running in `private` mode. +//! +//! Authentication keys are used exclusively by HTTP trackers. Every key has an +//! expiration time, meaning that it is only valid for a predetermined period. +//! Once the expiration time is reached, an expiring key will be rejected. +//! +//! The primary key structure is [`PeerKey`], which couples a randomly generated +//! [`Key`] (a 32-character alphanumeric string) with an optional expiration +//! timestamp. +//! +//! # Examples +//! +//! Generating a new key valid for `9999` seconds: +//! +//! ```rust +//! use bittorrent_tracker_core::authentication; +//! use std::time::Duration; +//! +//! let expiring_key = authentication::key::generate_key(Some(Duration::new(9999, 0))); +//! +//! // Later, verify that the key is still valid. +//! assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); +//! ``` +//! +//! The core key types are defined as follows: +//! +//! ```rust +//! use bittorrent_tracker_core::authentication::Key; +//! use torrust_tracker_primitives::DurationSinceUnixEpoch; +//! +//! pub struct PeerKey { +//! /// A random 32-character authentication token (e.g., `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ`) +//! pub key: Key, +//! +//! /// The timestamp after which the key expires. If `None`, the key is permanent. +//! pub valid_until: Option, +//! } +//! ``` +pub mod peer_key; +pub mod repository; + +use std::panic::Location; +use std::sync::Arc; +use std::time::Duration; + +use thiserror::Error; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_located_error::{DynError, LocatedError}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::CurrentClock; + +pub type PeerKey = peer_key::PeerKey; +pub type Key = peer_key::Key; +pub type ParseKeyError = peer_key::ParseKeyError; + +/// HTTP tracker authentication key length. +/// +/// For more information see function [`generate_key`](crate::authentication::key::generate_key) to generate the +/// [`PeerKey`](crate::authentication::PeerKey). +pub(crate) const AUTH_KEY_LENGTH: usize = 32; + +/// It generates a new permanent random key [`PeerKey`]. +#[cfg(test)] +#[must_use] +pub(crate) fn generate_permanent_key() -> PeerKey { + generate_key(None) +} + +/// It generates a new expiring random key [`PeerKey`]. +#[cfg(test)] +#[must_use] +pub(crate) fn generate_expiring_key(lifetime: Duration) -> PeerKey { + generate_key(Some(lifetime)) +} + +/// Generates a new random 32-character authentication key (`PeerKey`). +/// +/// If a lifetime is provided, the generated key will expire after the specified +/// duration; otherwise, the key is permanent (i.e., it never expires). +/// +/// # Panics +/// +/// Panics if the addition of the lifetime to the current time overflows +/// (an extremely unlikely event). +/// +/// # Arguments +/// +/// * `lifetime`: An optional duration specifying how long the key is valid. +/// If `None`, the key is permanent. +/// +/// # Examples +/// +/// ```rust +/// use bittorrent_tracker_core::authentication::key; +/// use std::time::Duration; +/// +/// // Generate an expiring key valid for 3600 seconds. +/// let expiring_key = key::generate_key(Some(Duration::from_secs(3600))); +/// +/// // Generate a permanent key. +/// let permanent_key = key::generate_key(None); +/// ``` +#[must_use] +pub fn generate_key(lifetime: Option) -> PeerKey { + let random_key = Key::random(); + + if let Some(lifetime) = lifetime { + tracing::debug!("Generated key: {}, valid for: {:?} seconds", random_key, lifetime); + + PeerKey { + key: random_key, + valid_until: Some(CurrentClock::now_add(&lifetime).unwrap()), + } + } else { + tracing::debug!("Generated key: {}, permanent", random_key); + + PeerKey { + key: random_key, + valid_until: None, + } + } +} + +/// Verifies whether a given authentication key (`PeerKey`) is still valid. +/// +/// For expiring keys, this function compares the key's expiration timestamp +/// against the current time. Permanent keys (with `None` as their expiration) +/// are always valid. +/// +/// # Errors +/// +/// Returns a verification error of type [`enum@Error`] if the key has expired. +/// +/// # Examples +/// +/// ```rust +/// use bittorrent_tracker_core::authentication::key; +/// use std::time::Duration; +/// +/// let expiring_key = key::generate_key(Some(Duration::from_secs(100))); +/// +/// // If the key's expiration time has passed, the verification will fail. +/// assert!(key::verify_key_expiration(&expiring_key).is_ok()); +/// ``` +pub fn verify_key_expiration(auth_key: &PeerKey) -> Result<(), Error> { + let current_time: DurationSinceUnixEpoch = CurrentClock::now(); + + match auth_key.valid_until { + Some(valid_until) => { + if valid_until < current_time { + Err(Error::KeyExpired { + location: Location::caller(), + }) + } else { + Ok(()) + } + } + None => Ok(()), // Permanent key + } +} + +/// Verification error. Error returned when an [`PeerKey`] cannot be +/// verified with the [`crate::authentication::key::verify_key_expiration`] function. +#[derive(Debug, Error, Clone)] +#[allow(dead_code)] +pub enum Error { + /// Wraps an underlying error encountered during key verification. + #[error("Key could not be verified: {source}")] + KeyVerificationError { + source: LocatedError<'static, dyn std::error::Error + Send + Sync>, + }, + + /// Indicates that the key could not be read or found. + #[error("Failed to read key: {key}, {location}")] + UnableToReadKey { + location: &'static Location<'static>, + key: Box, + }, + + /// Indicates that the key has expired. + #[error("Key has expired, {location}")] + KeyExpired { location: &'static Location<'static> }, + + /// Indicates that the required key for authentication was not provided. + #[error("Missing authentication key, {location}")] + MissingAuthKey { location: &'static Location<'static> }, +} + +impl From for Error { + fn from(e: r2d2_sqlite::rusqlite::Error) -> Self { + Error::KeyVerificationError { + source: (Arc::new(e) as DynError).into(), + } + } +} + +#[cfg(test)] +mod tests { + + mod the_expiring_peer_key { + + use std::time::Duration; + + use torrust_tracker_clock::clock; + use torrust_tracker_clock::clock::stopped::Stopped as _; + + use crate::authentication; + + #[test] + fn should_be_displayed() { + // Set the time to the current time. + clock::Stopped::local_set_to_unix_epoch(); + + let expiring_key = authentication::key::generate_key(Some(Duration::from_secs(0))); + + assert_eq!( + expiring_key.to_string(), + format!("key: `{}`, valid until `1970-01-01 00:00:00 UTC`", expiring_key.key) // cspell:disable-line + ); + } + + #[test] + fn should_be_generated_with_a_expiration_time() { + let expiring_key = authentication::key::generate_key(Some(Duration::new(9999, 0))); + + assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); + } + + #[test] + fn expiration_verification_should_fail_when_the_key_has_expired() { + // Set the time to the current time. + clock::Stopped::local_set_to_system_time_now(); + + // Make key that is valid for 19 seconds. + let expiring_key = authentication::key::generate_key(Some(Duration::from_secs(19))); + + // Mock the time has passed 10 sec. + clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); + + assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); + + // Mock the time has passed another 10 sec. + clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); + + assert!(authentication::key::verify_key_expiration(&expiring_key).is_err()); + } + } + + mod the_permanent_peer_key { + + use std::time::Duration; + + use torrust_tracker_clock::clock; + use torrust_tracker_clock::clock::stopped::Stopped as _; + + use crate::authentication; + + #[test] + fn should_be_displayed() { + // Set the time to the current time. + clock::Stopped::local_set_to_unix_epoch(); + + let expiring_key = authentication::key::generate_key(Some(Duration::from_secs(0))); + + assert_eq!( + expiring_key.to_string(), + format!("key: `{}`, valid until `1970-01-01 00:00:00 UTC`", expiring_key.key) // cspell:disable-line + ); + } + + #[test] + fn should_be_generated_without_expiration_time() { + let expiring_key = authentication::key::generate_permanent_key(); + + assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); + } + + #[test] + fn expiration_verification_should_always_succeed() { + let expiring_key = authentication::key::generate_permanent_key(); + + // Mock the time has passed 10 years. + clock::Stopped::local_add(&Duration::from_secs(10 * 365 * 24 * 60 * 60)).unwrap(); + + assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); + } + } + + mod the_key_verification_error { + use crate::authentication::key; + + #[test] + fn could_be_a_database_error() { + let err = r2d2_sqlite::rusqlite::Error::InvalidQuery; + + let err: key::Error = err.into(); + + assert!(matches!(err, key::Error::KeyVerificationError { .. })); + } + } +} diff --git a/packages/tracker-core/src/authentication/key/peer_key.rs b/packages/tracker-core/src/authentication/key/peer_key.rs new file mode 100644 index 000000000..ba648ad2f --- /dev/null +++ b/packages/tracker-core/src/authentication/key/peer_key.rs @@ -0,0 +1,321 @@ +//! Authentication keys for private trackers. +//! +//! This module defines the types and functionality for managing authentication +//! keys used by the tracker. These keys, represented by the `Key` and `PeerKey` +//! types, are essential for authenticating peers in private tracker +//! environments. +//! +//! A `Key` is a 32-character alphanumeric token, while a `PeerKey` couples a +//! `Key` with an optional expiration timestamp. If the expiration is set (via +//! `valid_until`), the key will become invalid after that time. +use std::str::FromStr; +use std::time::Duration; + +use derive_more::Display; +use rand::distr::Alphanumeric; +use rand::{rng, RngExt}; +use serde::{Deserialize, Serialize}; +use thiserror::Error; +use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::AUTH_KEY_LENGTH; + +/// A peer authentication key with an optional expiration time. +/// +/// A `PeerKey` associates a generated `Key` (a 32-character alphanumeric string) +/// with an optional expiration timestamp (`valid_until`). If `valid_until` is +/// `None`, the key is considered permanent. +/// +/// # Example +/// +/// ```rust +/// use std::time::Duration; +/// use bittorrent_tracker_core::authentication::key::peer_key::{Key, PeerKey}; +/// +/// let expiring_key = PeerKey { +/// key: Key::random(), +/// valid_until: Some(Duration::from_secs(3600)), // Expires in 1 hour +/// }; +/// +/// let permanent_key = PeerKey { +/// key: Key::random(), +/// valid_until: None, +/// }; +/// ``` +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct PeerKey { + /// A 32-character authentication key. For example: `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ` + pub key: Key, + + /// An optional expiration timestamp. If set, the key becomes invalid after + /// this time. A value of `None` indicates a permanent key. + pub valid_until: Option, +} + +impl PartialEq for PeerKey { + fn eq(&self, other: &Self) -> bool { + // When comparing two PeerKeys, ignore fractions of seconds since only + // whole seconds are stored in the database. + self.key == other.key + && match (&self.valid_until, &other.valid_until) { + (Some(a), Some(b)) => a.as_secs() == b.as_secs(), + (None, None) => true, + _ => false, + } + } +} + +impl Eq for PeerKey {} + +impl std::fmt::Display for PeerKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.expiry_time() { + Some(expire_time) => write!(f, "key: `{}`, valid until `{}`", self.key, expire_time), + None => write!(f, "key: `{}`, permanent", self.key), + } + } +} + +impl PeerKey { + #[must_use] + pub fn key(&self) -> Key { + self.key.clone() + } + + /// Computes and returns the expiration time as a UTC `DateTime`, if one + /// exists. + /// + /// The returned time is derived from the stored seconds since the Unix + /// epoch. Note that any fractional seconds are discarded since only whole + /// seconds are stored in the database. + /// + /// # Panics + /// + /// Panics if the key's timestamp overflows the internal `i64` type (this is + /// extremely unlikely, happening roughly 292.5 billion years from now). + #[must_use] + pub fn expiry_time(&self) -> Option> { + // We remove the fractions of seconds because we only store the seconds + // in the database. + self.valid_until + .map(|valid_until| convert_from_timestamp_to_datetime_utc(Duration::from_secs(valid_until.as_secs()))) + } +} + +/// A token used for authentication. +/// +/// The `Key` type encapsulates a 32-character string that must consist solely +/// of ASCII alphanumeric characters (0-9, a-z, A-Z). This key is used by the +/// tracker to authenticate peers. +/// +/// # Examples +/// +/// Creating a key from a valid string: +/// +/// ``` +/// use bittorrent_tracker_core::authentication::key::peer_key::Key; +/// let key = Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); +/// ``` +/// +/// Generating a random key: +/// +/// ``` +/// use bittorrent_tracker_core::authentication::key::peer_key::Key; +/// let random_key = Key::random(); +/// ``` +#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Display, Hash)] +pub struct Key(String); + +impl Key { + /// Constructs a new `Key` from the given string. + /// + /// # Errors + /// + /// Returns a `ParseKeyError` if: + /// + /// - The input string does not have exactly 32 characters. + /// - The input string contains characters that are not ASCII alphanumeric. + pub fn new(value: &str) -> Result { + if value.len() != AUTH_KEY_LENGTH { + return Err(ParseKeyError::InvalidKeyLength); + } + + if !value.chars().all(|c| c.is_ascii_alphanumeric()) { + return Err(ParseKeyError::InvalidChars); + } + + Ok(Self(value.to_owned())) + } + + /// Generates a new random authentication key. + /// + /// The random key is generated by sampling 32 ASCII alphanumeric characters. + /// + /// # Panics + /// + /// Panics if the random number generator fails to produce a valid key + /// (extremely unlikely). + pub fn random() -> Self { + let random_id: String = rng() + .sample_iter(&Alphanumeric) + .take(AUTH_KEY_LENGTH) + .map(char::from) + .collect(); + random_id.parse::().expect("Failed to generate a valid random key") + } + + #[must_use] + pub fn value(&self) -> &str { + &self.0 + } +} + +/// Errors that can occur when parsing a string into a `Key`. +/// +/// # Examples +/// +/// ```rust +/// use bittorrent_tracker_core::authentication::Key; +/// use std::str::FromStr; +/// +/// let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; +/// let key = Key::from_str(key_string); +/// +/// assert!(key.is_ok()); +/// assert_eq!(key.unwrap().to_string(), key_string); +/// ``` +/// +/// If the string does not contains a valid key, the parser function will return +/// this error. +#[derive(Debug, Error)] +pub enum ParseKeyError { + /// The provided key does not have exactly 32 characters. + #[error("Invalid key length. Key must be have 32 chars")] + InvalidKeyLength, + + /// The provided key contains invalid characters. Only ASCII alphanumeric + /// characters are allowed. + #[error("Invalid chars for key. Key can only alphanumeric chars (0-9, a-z, A-Z)")] + InvalidChars, +} + +impl FromStr for Key { + type Err = ParseKeyError; + + fn from_str(s: &str) -> Result { + Key::new(s)?; + Ok(Self(s.to_string())) + } +} + +#[cfg(test)] +mod tests { + + mod key { + use std::str::FromStr; + + use crate::authentication::Key; + + #[test] + fn should_be_parsed_from_an_string() { + let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; + let key = Key::from_str(key_string); + + assert!(key.is_ok()); + assert_eq!(key.unwrap().to_string(), key_string); + } + + #[test] + fn should_be_generated_randomly() { + let _key = Key::random(); + } + + #[test] + fn length_should_be_32() { + let key = Key::new(""); + assert!(key.is_err()); + + let string_longer_than_32 = "012345678901234567890123456789012"; // DevSkim: ignore DS173237 + let key = Key::new(string_longer_than_32); + assert!(key.is_err()); + } + + #[test] + fn should_only_include_alphanumeric_chars() { + let key = Key::new("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); + assert!(key.is_err()); + } + + #[test] + fn should_return_a_reference_to_the_inner_string() { + let key = Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); // DevSkim: ignore DS173237 + + assert_eq!(key.value(), "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"); // DevSkim: ignore DS173237 + } + } + + mod peer_key { + + use std::time::Duration; + + use crate::authentication::key::peer_key::{Key, PeerKey}; + + #[test] + fn could_have_an_expiration_time() { + let expiring_key = PeerKey { + key: Key::random(), + valid_until: Some(Duration::from_secs(100)), + }; + + assert_eq!(expiring_key.expiry_time().unwrap().to_string(), "1970-01-01 00:01:40 UTC"); + } + + #[test] + fn could_be_permanent() { + let permanent_key = PeerKey { + key: Key::random(), + valid_until: None, + }; + + assert_eq!(permanent_key.expiry_time(), None); + } + + mod expiring { + use std::time::Duration; + + use crate::authentication::key::peer_key::{Key, PeerKey}; + + #[test] + fn should_be_displayed_when_it_is_expiring() { + let expiring_key = PeerKey { + key: Key::random(), + valid_until: Some(Duration::from_secs(100)), + }; + + assert_eq!( + expiring_key.to_string(), + format!("key: `{}`, valid until `1970-01-01 00:01:40 UTC`", expiring_key.key) // cspell:disable-line + ); + } + } + + mod permanent { + + use crate::authentication::key::peer_key::{Key, PeerKey}; + + #[test] + fn should_be_displayed_when_it_is_permanent() { + let permanent_key = PeerKey { + key: Key::random(), + valid_until: None, + }; + + assert_eq!( + permanent_key.to_string(), + format!("key: `{}`, permanent", permanent_key.key) // cspell:disable-line + ); + } + } + } +} diff --git a/packages/tracker-core/src/authentication/key/repository/in_memory.rs b/packages/tracker-core/src/authentication/key/repository/in_memory.rs new file mode 100644 index 000000000..5911771d4 --- /dev/null +++ b/packages/tracker-core/src/authentication/key/repository/in_memory.rs @@ -0,0 +1,188 @@ +//! In-memory implementation of the authentication key repository. +use crate::authentication::key::{Key, PeerKey}; + +/// An in-memory repository for storing authentication keys. +/// +/// This repository maintains a mapping between a peer's [`Key`] and its +/// corresponding [`PeerKey`]. It is designed for use in private tracker +/// environments where keys are maintained in memory. +#[derive(Debug, Default)] +pub struct InMemoryKeyRepository { + /// Tracker users' keys. Only for private trackers. + keys: tokio::sync::RwLock>, +} + +impl InMemoryKeyRepository { + /// Inserts a new authentication key into the repository. + /// + /// This function acquires a write lock on the internal storage and inserts + /// the provided [`PeerKey`], using its inner [`Key`] as the map key. + /// + /// # Arguments + /// + /// * `auth_key` - A reference to the [`PeerKey`] to be inserted. + pub(crate) async fn insert(&self, auth_key: &PeerKey) { + self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); + } + + /// Removes an authentication key from the repository. + /// + /// This function acquires a write lock on the internal storage and removes + /// the key that matches the provided [`Key`]. + /// + /// # Arguments + /// + /// * `key` - A reference to the [`Key`] corresponding to the key to be removed. + pub(crate) async fn remove(&self, key: &Key) { + self.keys.write().await.remove(key); + } + + /// Retrieves an authentication key from the repository. + /// + /// This function acquires a read lock on the internal storage and returns a + /// cloned [`PeerKey`] if the provided [`Key`] exists. + /// + /// # Arguments + /// + /// * `key` - A reference to the [`Key`] to look up. + /// + /// # Returns + /// + /// An `Option` containing the matching key if found, or `None` + /// otherwise. + pub(crate) async fn get(&self, key: &Key) -> Option { + self.keys.read().await.get(key).cloned() + } + + /// Clears all authentication keys from the repository. + /// + /// This function acquires a write lock on the internal storage and removes + /// all entries. + #[allow(dead_code)] + pub(crate) async fn clear(&self) { + let mut keys = self.keys.write().await; + keys.clear(); + } + + /// Resets the repository with a new list of authentication keys. + /// + /// This function clears all existing keys and then inserts each key from + /// the provided vector. + /// + /// # Arguments + /// + /// * `peer_keys` - A vector of [`PeerKey`] instances that will replace the + /// current set of keys. + pub async fn reset_with(&self, peer_keys: Vec) { + let mut keys_lock = self.keys.write().await; + + keys_lock.clear(); + + for key in peer_keys { + keys_lock.insert(key.key.clone(), key.clone()); + } + } +} + +#[cfg(test)] +mod tests { + + mod the_in_memory_key_repository_should { + use std::time::Duration; + + use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::authentication::key::Key; + use crate::authentication::PeerKey; + + #[tokio::test] + async fn insert_a_new_peer_key() { + let repository = InMemoryKeyRepository::default(); + + let new_peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + repository.insert(&new_peer_key).await; + + let peer_key = repository.get(&new_peer_key.key).await; + + assert_eq!(peer_key, Some(new_peer_key)); + } + + #[tokio::test] + async fn remove_a_new_peer_key() { + let repository = InMemoryKeyRepository::default(); + + let new_peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + repository.insert(&new_peer_key).await; + + repository.remove(&new_peer_key.key).await; + + let peer_key = repository.get(&new_peer_key.key).await; + + assert_eq!(peer_key, None); + } + + #[tokio::test] + async fn get_a_new_peer_key_by_its_internal_key() { + let repository = InMemoryKeyRepository::default(); + + let expected_peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + repository.insert(&expected_peer_key).await; + + let peer_key = repository.get(&expected_peer_key.key).await; + + assert_eq!(peer_key, Some(expected_peer_key)); + } + + #[tokio::test] + async fn clear_all_peer_keys() { + let repository = InMemoryKeyRepository::default(); + + let new_peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + repository.insert(&new_peer_key).await; + + repository.clear().await; + + let peer_key = repository.get(&new_peer_key.key).await; + + assert_eq!(peer_key, None); + } + + #[tokio::test] + async fn reset_the_peer_keys_with_a_new_list_of_keys() { + let repository = InMemoryKeyRepository::default(); + + let old_peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + repository.insert(&old_peer_key).await; + + let new_peer_key = PeerKey { + key: Key::new("kqdVKHlKKWXzAideqI5gvjBP4jdbe5dW").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + repository.reset_with(vec![new_peer_key.clone()]).await; + + let peer_key = repository.get(&new_peer_key.key).await; + + assert_eq!(peer_key, Some(new_peer_key)); + } + } +} diff --git a/packages/tracker-core/src/authentication/key/repository/mod.rs b/packages/tracker-core/src/authentication/key/repository/mod.rs new file mode 100644 index 000000000..3df783622 --- /dev/null +++ b/packages/tracker-core/src/authentication/key/repository/mod.rs @@ -0,0 +1,3 @@ +//! Key repository implementations. +pub mod in_memory; +pub mod persisted; diff --git a/packages/tracker-core/src/authentication/key/repository/persisted.rs b/packages/tracker-core/src/authentication/key/repository/persisted.rs new file mode 100644 index 000000000..e84a23c9b --- /dev/null +++ b/packages/tracker-core/src/authentication/key/repository/persisted.rs @@ -0,0 +1,159 @@ +//! The database repository for the authentication keys. +use std::sync::Arc; + +use crate::authentication::key::{Key, PeerKey}; +use crate::databases::{self, Database}; + +/// A repository for storing authentication keys in a persistent database. +/// +/// This repository provides methods to add, remove, and load authentication +/// keys from the underlying database. It wraps an instance of a type +/// implementing the [`Database`] trait. +pub struct DatabaseKeyRepository { + database: Arc>, +} + +impl DatabaseKeyRepository { + /// Creates a new `DatabaseKeyRepository` instance. + /// + /// # Arguments + /// + /// * `database` - A shared reference to a boxed database implementation. + /// + /// # Returns + /// + /// A new instance of `DatabaseKeyRepository` + #[must_use] + pub fn new(database: &Arc>) -> Self { + Self { + database: database.clone(), + } + } + + /// Adds a new authentication key to the database. + /// + /// # Arguments + /// + /// * `peer_key` - A reference to the [`PeerKey`] to be persisted. + /// + /// # Errors + /// + /// Returns a [`databases::error::Error`] if the key cannot be added. + pub(crate) fn add(&self, peer_key: &PeerKey) -> Result<(), databases::error::Error> { + self.database.add_key_to_keys(peer_key)?; + Ok(()) + } + + /// Removes an authentication key from the database. + /// + /// # Arguments + /// + /// * `key` - A reference to the [`Key`] corresponding to the key to remove. + /// + /// # Errors + /// + /// Returns a [`databases::error::Error`] if the key cannot be removed. + pub(crate) fn remove(&self, key: &Key) -> Result<(), databases::error::Error> { + self.database.remove_key_from_keys(key)?; + Ok(()) + } + + /// Loads all authentication keys from the database. + /// + /// # Errors + /// + /// Returns a [`databases::error::Error`] if the keys cannot be loaded. + /// + /// # Returns + /// + /// A vector containing all persisted [`PeerKey`] entries. + pub(crate) fn load_keys(&self) -> Result, databases::error::Error> { + let keys = self.database.load_keys()?; + Ok(keys) + } +} + +#[cfg(test)] +mod tests { + + mod the_persisted_key_repository_should { + + use std::time::Duration; + + use torrust_tracker_configuration::Core; + use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; + + use crate::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::authentication::{Key, PeerKey}; + use crate::databases::setup::initialize_database; + + fn ephemeral_configuration() -> Core { + let mut config = Core::default(); + let temp_file = ephemeral_sqlite_database(); + temp_file.to_str().unwrap().clone_into(&mut config.database.path); + config + } + + #[test] + fn persist_a_new_peer_key() { + let configuration = ephemeral_configuration(); + + let database = initialize_database(&configuration); + + let repository = DatabaseKeyRepository::new(&database); + + let peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + let result = repository.add(&peer_key); + assert!(result.is_ok()); + + let keys = repository.load_keys().unwrap(); + assert_eq!(keys, vec!(peer_key)); + } + + #[test] + fn remove_a_persisted_peer_key() { + let configuration = ephemeral_configuration(); + + let database = initialize_database(&configuration); + + let repository = DatabaseKeyRepository::new(&database); + + let peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + let _unused = repository.add(&peer_key); + + let result = repository.remove(&peer_key.key); + assert!(result.is_ok()); + + let keys = repository.load_keys().unwrap(); + assert!(keys.is_empty()); + } + + #[test] + fn load_all_persisted_peer_keys() { + let configuration = ephemeral_configuration(); + + let database = initialize_database(&configuration); + + let repository = DatabaseKeyRepository::new(&database); + + let peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + let _unused = repository.add(&peer_key); + + let keys = repository.load_keys().unwrap(); + + assert_eq!(keys, vec!(peer_key)); + } + } +} diff --git a/packages/tracker-core/src/authentication/mod.rs b/packages/tracker-core/src/authentication/mod.rs new file mode 100644 index 000000000..12b742b8b --- /dev/null +++ b/packages/tracker-core/src/authentication/mod.rs @@ -0,0 +1,242 @@ +//! Tracker authentication services and structs. +//! +//! One of the crate responsibilities is to create and keep authentication keys. +//! Auth keys are used by HTTP trackers when the tracker is running in `private` +//! mode. +//! +//! HTTP tracker's clients need to obtain an authentication key before starting +//! requesting the tracker. Once they get one they have to include a `PATH` +//! param with the key in all the HTTP requests. For example, when a peer wants +//! to `announce` itself it has to use the HTTP tracker endpoint: +//! +//! `GET /announce/:key` +//! +//! The common way to obtain the keys is by using the tracker API directly or +//! via other applications like the [Torrust Index](https://github.com/torrust/torrust-index). +use crate::CurrentClock; + +pub mod handler; +pub mod key; +pub mod service; + +pub type PeerKey = key::PeerKey; +pub type Key = key::Key; +pub type Error = key::Error; + +#[cfg(test)] +mod tests { + + // Integration tests for authentication. + + mod the_tracker_configured_as_private { + + use std::sync::Arc; + use std::time::Duration; + + use torrust_tracker_configuration::v2_0_0::core::PrivateMode; + use torrust_tracker_configuration::Configuration; + use torrust_tracker_test_helpers::configuration; + + use crate::authentication::handler::KeysHandler; + use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::authentication::service; + use crate::authentication::service::AuthenticationService; + use crate::databases::setup::initialize_database; + + fn instantiate_keys_manager_and_authentication() -> (Arc, Arc) { + let config = configuration::ephemeral_private(); + + instantiate_keys_manager_and_authentication_with_configuration(&config) + } + + fn instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled( + ) -> (Arc, Arc) { + let mut config = configuration::ephemeral_private(); + + config.core.private_mode = Some(PrivateMode { + check_keys_expiration: false, + }); + + instantiate_keys_manager_and_authentication_with_configuration(&config) + } + + fn instantiate_keys_manager_and_authentication_with_configuration( + config: &Configuration, + ) -> (Arc, Arc) { + let database = initialize_database(&config.core); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(service::AuthenticationService::new(&config.core, &in_memory_key_repository)); + let keys_handler = Arc::new(KeysHandler::new( + &db_key_repository.clone(), + &in_memory_key_repository.clone(), + )); + + (keys_handler, authentication_service) + } + + #[tokio::test] + async fn it_should_remove_an_authentication_key() { + let (keys_manager, authentication_service) = instantiate_keys_manager_and_authentication(); + + let expiring_key = keys_manager + .generate_expiring_peer_key(Some(Duration::from_secs(100))) + .await + .unwrap(); + + let result = keys_manager.remove_peer_key(&expiring_key.key()).await; + + assert!(result.is_ok()); + + // The key should no longer be valid + assert!(authentication_service.authenticate(&expiring_key.key()).await.is_err()); + } + + #[tokio::test] + async fn it_should_load_authentication_keys_from_the_database() { + let (keys_manager, authentication_service) = instantiate_keys_manager_and_authentication(); + + let expiring_key = keys_manager + .generate_expiring_peer_key(Some(Duration::from_secs(100))) + .await + .unwrap(); + + // Remove the newly generated key in memory + keys_manager.remove_in_memory_auth_key(&expiring_key.key()).await; + + let result = keys_manager.load_peer_keys_from_database().await; + + assert!(result.is_ok()); + + // The key should no longer be valid + assert!(authentication_service.authenticate(&expiring_key.key()).await.is_ok()); + } + + mod with_expiring_and { + + mod randomly_generated_keys { + use std::time::Duration; + + use crate::authentication::tests::the_tracker_configured_as_private::{ + instantiate_keys_manager_and_authentication, + instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled, + }; + use crate::authentication::Key; + + #[tokio::test] + async fn it_should_authenticate_a_peer_with_the_key() { + let (keys_manager, authentication_service) = instantiate_keys_manager_and_authentication(); + + let peer_key = keys_manager + .generate_expiring_peer_key(Some(Duration::from_secs(100))) + .await + .unwrap(); + + let result = authentication_service.authenticate(&peer_key.key()).await; + + assert!(result.is_ok()); + } + + #[tokio::test] + async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { + let (keys_manager, authentication_service) = + instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled(); + + let past_timestamp = Duration::ZERO; + + let peer_key = keys_manager + .add_expiring_peer_key(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), Some(past_timestamp)) + .await + .unwrap(); + + assert!(authentication_service.authenticate(&peer_key.key()).await.is_ok()); + } + } + + mod pre_generated_keys { + + use crate::authentication::handler::AddKeyRequest; + use crate::authentication::tests::the_tracker_configured_as_private::{ + instantiate_keys_manager_and_authentication, + instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled, + }; + use crate::authentication::Key; + + #[tokio::test] + async fn it_should_authenticate_a_peer_with_the_key() { + let (keys_manager, authentication_service) = instantiate_keys_manager_and_authentication(); + + let peer_key = keys_manager + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: Some(100), + }) + .await + .unwrap(); + + let result = authentication_service.authenticate(&peer_key.key()).await; + + assert!(result.is_ok()); + } + + #[tokio::test] + async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { + let (keys_manager, authentication_service) = + instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled(); + + let peer_key = keys_manager + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: Some(0), + }) + .await + .unwrap(); + + assert!(authentication_service.authenticate(&peer_key.key()).await.is_ok()); + } + } + } + + mod with_permanent_and { + + mod randomly_generated_keys { + use crate::authentication::tests::the_tracker_configured_as_private::instantiate_keys_manager_and_authentication; + + #[tokio::test] + async fn it_should_authenticate_a_peer_with_the_key() { + let (keys_manager, authentication_service) = instantiate_keys_manager_and_authentication(); + + let peer_key = keys_manager.generate_permanent_peer_key().await.unwrap(); + + let result = authentication_service.authenticate(&peer_key.key()).await; + + assert!(result.is_ok()); + } + } + + mod pre_generated_keys { + use crate::authentication::handler::AddKeyRequest; + use crate::authentication::tests::the_tracker_configured_as_private::instantiate_keys_manager_and_authentication; + use crate::authentication::Key; + + #[tokio::test] + async fn it_should_authenticate_a_peer_with_the_key() { + let (keys_manager, authentication_service) = instantiate_keys_manager_and_authentication(); + + let peer_key = keys_manager + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: None, + }) + .await + .unwrap(); + + let result = authentication_service.authenticate(&peer_key.key()).await; + + assert!(result.is_ok()); + } + } + } + } +} diff --git a/packages/tracker-core/src/authentication/service.rs b/packages/tracker-core/src/authentication/service.rs new file mode 100644 index 000000000..75b28944f --- /dev/null +++ b/packages/tracker-core/src/authentication/service.rs @@ -0,0 +1,313 @@ +//! Authentication service. +use std::panic::Location; +use std::sync::Arc; + +use torrust_tracker_configuration::Core; + +use super::key::repository::in_memory::InMemoryKeyRepository; +use super::{key, Error, Key}; + +/// The authentication service responsible for validating peer keys. +/// +/// The service uses an in-memory key repository along with the tracker +/// configuration to determine whether a given peer key is valid. In a private +/// tracker, only registered keys (and optionally unexpired keys) are allowed. +#[derive(Debug)] +pub struct AuthenticationService { + /// The tracker configuration. + config: Core, + + /// In-memory implementation of the authentication key repository. + in_memory_key_repository: Arc, +} + +impl AuthenticationService { + /// Creates a new instance of the `AuthenticationService`. + /// + /// # Parameters + /// + /// - `config`: A reference to the tracker core configuration. + /// - `in_memory_key_repository`: A shared reference to an in-memory key + /// repository. + /// + /// # Returns + /// + /// An `AuthenticationService` instance initialized with the given + /// configuration and repository. + #[must_use] + pub fn new(config: &Core, in_memory_key_repository: &Arc) -> Self { + Self { + config: config.clone(), + in_memory_key_repository: in_memory_key_repository.clone(), + } + } + + /// Authenticates a peer key against the tracker's authentication key list. + /// + /// For private trackers, the key must be registered (and optionally not + /// expired) to be considered valid. For public trackers, authentication + /// always succeeds. + /// + /// # Parameters + /// + /// - `key`: A reference to the peer key that needs to be authenticated. + /// + /// # Errors + /// + /// Returns an error if: + /// + /// - The tracker is in private mode and the key cannot be found in the + /// repository. + /// - The key is found but fails the expiration check (if expiration is enforced). + pub async fn authenticate(&self, key: &Key) -> Result<(), Error> { + if self.tracker_is_private() { + self.verify_auth_key(key).await + } else { + Ok(()) + } + } + + /// Returns `true` is the tracker is in private mode. + #[must_use] + fn tracker_is_private(&self) -> bool { + self.config.private + } + + /// Verifies the authentication key against the in-memory repository. + /// + /// This function retrieves the key from the repository. If the key is not + /// found, it returns an error with the caller's location. If the key is + /// found, the function then checks the key's expiration based on the + /// tracker configuration. The behavior differs depending on whether a + /// `private` configuration is provided and whether key expiration checking + /// is enabled. + /// + /// # Parameters + /// + /// - `key`: A reference to the peer key that needs to be verified. + /// + /// # Errors + /// + /// Returns an error if: + /// + /// - The key is not found in the repository. + /// - The key fails the expiration check when such verification is required. + async fn verify_auth_key(&self, key: &Key) -> Result<(), Error> { + match self.in_memory_key_repository.get(key).await { + None => Err(Error::UnableToReadKey { + location: Location::caller(), + key: Box::new(key.clone()), + }), + Some(key) => match self.config.private_mode { + Some(private_mode) => { + if private_mode.check_keys_expiration { + return key::verify_key_expiration(&key); + } + + Ok(()) + } + None => key::verify_key_expiration(&key), + }, + } + } +} + +#[cfg(test)] +mod tests { + + mod the_authentication_service { + + mod when_the_tracker_is_public { + + use std::str::FromStr; + use std::sync::Arc; + + use torrust_tracker_configuration::Core; + + use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::authentication::service::AuthenticationService; + use crate::authentication::{self}; + + fn instantiate_authentication_for_public_tracker() -> AuthenticationService { + let config = Core { + private: false, + ..Default::default() + }; + + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + AuthenticationService::new(&config, &in_memory_key_repository.clone()) + } + + #[tokio::test] + async fn it_should_always_authenticate_when_the_tracker_is_public() { + let authentication = instantiate_authentication_for_public_tracker(); + + let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + + let result = authentication.authenticate(&unregistered_key).await; + + assert!(result.is_ok()); + } + } + + mod when_the_tracker_is_private { + + use std::str::FromStr; + use std::sync::Arc; + use std::time::Duration; + + use torrust_tracker_configuration::v2_0_0::core::PrivateMode; + use torrust_tracker_configuration::Core; + + use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::authentication::service::AuthenticationService; + use crate::authentication::{self, PeerKey}; + + fn instantiate_authentication_for_private_tracker() -> AuthenticationService { + let config = Core { + private: true, + ..Default::default() + }; + + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + AuthenticationService::new(&config, &in_memory_key_repository.clone()) + } + + #[tokio::test] + async fn it_should_authenticate_a_registered_key() { + let config = Core { + private: true, + ..Default::default() + }; + + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + let key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + + in_memory_key_repository + .insert(&PeerKey { + key: key.clone(), + valid_until: None, + }) + .await; + + let authentication = AuthenticationService::new(&config, &in_memory_key_repository.clone()); + + let result = authentication.authenticate(&key).await; + + assert!(result.is_ok()); + } + + #[tokio::test] + async fn it_should_not_authenticate_an_unregistered_key() { + let authentication = instantiate_authentication_for_private_tracker(); + + let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + + let result = authentication.authenticate(&unregistered_key).await; + + assert!(result.is_err()); + } + + #[tokio::test] + async fn it_should_not_authenticate_a_registered_but_expired_key_by_default() { + let config = Core { + private: true, + ..Default::default() + }; + + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + let key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + + // Register the key with an immediate expiration date. + in_memory_key_repository + .insert(&PeerKey { + key: key.clone(), + valid_until: Some(Duration::from_secs(0)), + }) + .await; + + let authentication = AuthenticationService::new(&config, &in_memory_key_repository.clone()); + + let result = authentication.authenticate(&key).await; + + assert!(result.is_err()); + } + + #[tokio::test] + async fn it_should_not_authenticate_a_registered_but_expired_key_when_the_tracker_is_explicitly_configured_to_check_keys_expiration( + ) { + let config = Core { + private: true, + private_mode: Some(PrivateMode { + check_keys_expiration: true, + }), + ..Default::default() + }; + + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + let key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + + // Register the key with an immediate expiration date. + in_memory_key_repository + .insert(&PeerKey { + key: key.clone(), + valid_until: Some(Duration::from_secs(0)), + }) + .await; + + let authentication = AuthenticationService::new(&config, &in_memory_key_repository.clone()); + + let result = authentication.authenticate(&key).await; + + assert!(result.is_err()); + } + + mod but_the_key_expiration_check_is_disabled_by_configuration { + use std::str::FromStr; + use std::sync::Arc; + use std::time::Duration; + + use torrust_tracker_configuration::v2_0_0::core::PrivateMode; + use torrust_tracker_configuration::Core; + + use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::authentication::service::AuthenticationService; + use crate::authentication::{self, PeerKey}; + + #[tokio::test] + async fn it_should_authenticate_an_expired_registered_key() { + let config = Core { + private: true, + private_mode: Some(PrivateMode { + check_keys_expiration: false, + }), + ..Default::default() + }; + + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + let key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + + // Register the key with an immediate expiration date. + in_memory_key_repository + .insert(&PeerKey { + key: key.clone(), + valid_until: Some(Duration::from_secs(0)), + }) + .await; + + let authentication = AuthenticationService::new(&config, &in_memory_key_repository.clone()); + + let result = authentication.authenticate(&key).await; + + assert!(result.is_ok()); + } + } + } + } +} diff --git a/packages/tracker-core/src/container.rs b/packages/tracker-core/src/container.rs new file mode 100644 index 000000000..93b8efd7e --- /dev/null +++ b/packages/tracker-core/src/container.rs @@ -0,0 +1,94 @@ +use std::sync::Arc; + +use torrust_tracker_configuration::Core; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; + +use crate::announce_handler::AnnounceHandler; +use crate::authentication::handler::KeysHandler; +use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; +use crate::authentication::key::repository::persisted::DatabaseKeyRepository; +use crate::authentication::service::AuthenticationService; +use crate::databases::setup::initialize_database; +use crate::databases::Database; +use crate::scrape_handler::ScrapeHandler; +use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; +use crate::torrent::manager::TorrentsManager; +use crate::torrent::repository::in_memory::InMemoryTorrentRepository; +use crate::whitelist::authorization::WhitelistAuthorization; +use crate::whitelist::manager::WhitelistManager; +use crate::whitelist::repository::in_memory::InMemoryWhitelist; +use crate::whitelist::setup::initialize_whitelist_manager; +use crate::{statistics, whitelist}; + +pub struct TrackerCoreContainer { + pub core_config: Arc, + pub database: Arc>, + pub announce_handler: Arc, + pub scrape_handler: Arc, + pub keys_handler: Arc, + pub authentication_service: Arc, + pub in_memory_whitelist: Arc, + pub whitelist_authorization: Arc, + pub whitelist_manager: Arc, + pub in_memory_torrent_repository: Arc, + pub db_downloads_metric_repository: Arc, + pub torrents_manager: Arc, + pub stats_repository: Arc, +} + +impl TrackerCoreContainer { + #[must_use] + pub fn initialize_from( + core_config: &Arc, + swarm_coordination_registry_container: &Arc, + ) -> Self { + let database = initialize_database(core_config); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(core_config, &in_memory_whitelist.clone())); + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(AuthenticationService::new(core_config, &in_memory_key_repository)); + let keys_handler = Arc::new(KeysHandler::new( + &db_key_repository.clone(), + &in_memory_key_repository.clone(), + )); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::new( + swarm_coordination_registry_container.swarms.clone(), + )); + let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + + let torrents_manager = Arc::new(TorrentsManager::new( + core_config, + &in_memory_torrent_repository, + &db_downloads_metric_repository, + )); + + let stats_repository = Arc::new(statistics::repository::Repository::new()); + + let announce_handler = Arc::new(AnnounceHandler::new( + core_config, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_downloads_metric_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + Self { + core_config: core_config.clone(), + database, + announce_handler, + scrape_handler, + keys_handler, + authentication_service, + in_memory_whitelist, + whitelist_authorization, + whitelist_manager, + in_memory_torrent_repository, + db_downloads_metric_repository, + torrents_manager, + stats_repository, + } + } +} diff --git a/packages/tracker-core/src/databases/driver/mod.rs b/packages/tracker-core/src/databases/driver/mod.rs new file mode 100644 index 000000000..6c849bb70 --- /dev/null +++ b/packages/tracker-core/src/databases/driver/mod.rs @@ -0,0 +1,344 @@ +//! Database driver factory. +use mysql::Mysql; +use serde::{Deserialize, Serialize}; +use sqlite::Sqlite; + +use super::error::Error; +use super::Database; + +/// Metric name in DB for the total number of downloads across all torrents. +const TORRENTS_DOWNLOADS_TOTAL: &str = "torrents_downloads_total"; + +/// The database management system used by the tracker. +/// +/// Refer to: +/// +/// - [Torrust Tracker Configuration](https://docs.rs/torrust-tracker-configuration). +/// - [Torrust Tracker](https://docs.rs/torrust-tracker). +/// +/// For more information about persistence. +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, derive_more::Display, Clone)] +pub enum Driver { + /// The Sqlite3 database driver. + Sqlite3, + /// The `MySQL` database driver. + MySQL, +} + +/// It builds a new database driver. +/// +/// Example for `SQLite3`: +/// +/// ```text +/// use bittorrent_tracker_core::databases; +/// use bittorrent_tracker_core::databases::driver::Driver; +/// +/// let db_driver = Driver::Sqlite3; +/// let db_path = "./storage/tracker/lib/database/sqlite3.db".to_string(); +/// let database = databases::driver::build(&db_driver, &db_path); +/// ``` +/// +/// Example for `MySQL`: +/// +/// ```text +/// use bittorrent_tracker_core::databases; +/// use bittorrent_tracker_core::databases::driver::Driver; +/// +/// let db_driver = Driver::MySQL; +/// let db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker".to_string(); +/// let database = databases::driver::build(&db_driver, &db_path); +/// ``` +/// +/// Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) +/// for more information about the database configuration. +/// +/// > **WARNING**: The driver instantiation runs database migrations. +/// +/// # Errors +/// +/// This function will return an error if unable to connect to the database. +/// +/// # Panics +/// +/// This function will panic if unable to create database tables. +pub mod mysql; +pub mod sqlite; + +/// It builds a new database driver. +/// +/// # Panics +/// +/// Will panic if unable to create database tables. +/// +/// # Errors +/// +/// Will return `Error` if unable to build the driver. +pub(crate) fn build(driver: &Driver, db_path: &str) -> Result, Error> { + let database: Box = match driver { + Driver::Sqlite3 => Box::new(Sqlite::new(db_path)?), + Driver::MySQL => Box::new(Mysql::new(db_path)?), + }; + + database.create_database_tables().expect("Could not create database tables."); + + Ok(database) +} + +#[cfg(test)] +pub(crate) mod tests { + use std::sync::Arc; + use std::time::Duration; + + use crate::databases::Database; + + pub async fn run_tests(driver: &Arc>) { + // Since the interface is very simple and there are no conflicts between + // tests, we share the same database. If we want to isolate the tests in + // the future, we can create a new database for each test. + + database_setup(driver).await; + + // Persistent torrents (stats) + + // Torrent metrics + handling_torrent_persistence::it_should_save_and_load_persistent_torrents(driver); + handling_torrent_persistence::it_should_load_all_persistent_torrents(driver); + handling_torrent_persistence::it_should_increase_the_number_of_downloads_for_a_given_torrent(driver); + // Aggregate metrics for all torrents + handling_torrent_persistence::it_should_save_and_load_the_global_number_of_downloads(driver); + handling_torrent_persistence::it_should_load_the_global_number_of_downloads(driver); + handling_torrent_persistence::it_should_increase_the_global_number_of_downloads(driver); + + // Authentication keys (for private trackers) + + handling_authentication_keys::it_should_load_the_keys(driver); + + // Permanent keys + handling_authentication_keys::it_should_save_and_load_permanent_authentication_keys(driver); + handling_authentication_keys::it_should_remove_a_permanent_authentication_key(driver); + + // Expiring keys + handling_authentication_keys::it_should_save_and_load_expiring_authentication_keys(driver); + handling_authentication_keys::it_should_remove_an_expiring_authentication_key(driver); + + // Whitelist (for listed trackers) + + handling_the_whitelist::it_should_load_the_whitelist(driver); + handling_the_whitelist::it_should_add_and_get_infohashes(driver); + handling_the_whitelist::it_should_remove_an_infohash_from_the_whitelist(driver); + handling_the_whitelist::it_should_fail_trying_to_add_the_same_infohash_twice(driver); + } + + /// It initializes the database schema. + /// + /// Since the drop SQL queries don't check if the tables already exist, + /// we have to create them first, and then drop them. + /// + /// The method to drop tables does not use "DROP TABLE IF EXISTS". We can + /// change this function when we update the `Database::drop_database_tables` + /// method to use "DROP TABLE IF EXISTS". + async fn database_setup(driver: &Arc>) { + create_database_tables(driver).await.expect("database tables creation failed"); + driver.drop_database_tables().expect("old database tables deletion failed"); + create_database_tables(driver) + .await + .expect("database tables creation from empty schema failed"); + } + + async fn create_database_tables(driver: &Arc>) -> Result<(), Box> { + for _ in 0..5 { + if driver.create_database_tables().is_ok() { + return Ok(()); + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + Err("Database is not ready after retries.".into()) + } + + mod handling_torrent_persistence { + + use std::sync::Arc; + + use crate::databases::Database; + use crate::test_helpers::tests::sample_info_hash; + + // Metrics per torrent + + pub fn it_should_save_and_load_persistent_torrents(driver: &Arc>) { + let infohash = sample_info_hash(); + + let number_of_downloads = 1; + + driver.save_torrent_downloads(&infohash, number_of_downloads).unwrap(); + + let number_of_downloads = driver.load_torrent_downloads(&infohash).unwrap().unwrap(); + + assert_eq!(number_of_downloads, 1); + } + + pub fn it_should_load_all_persistent_torrents(driver: &Arc>) { + let infohash = sample_info_hash(); + + let number_of_downloads = 1; + + driver.save_torrent_downloads(&infohash, number_of_downloads).unwrap(); + + let torrents = driver.load_all_torrents_downloads().unwrap(); + + assert_eq!(torrents.len(), 1); + assert_eq!(torrents.get(&infohash), Some(number_of_downloads).as_ref()); + } + + pub fn it_should_increase_the_number_of_downloads_for_a_given_torrent(driver: &Arc>) { + let infohash = sample_info_hash(); + + let number_of_downloads = 1; + + driver.save_torrent_downloads(&infohash, number_of_downloads).unwrap(); + + driver.increase_downloads_for_torrent(&infohash).unwrap(); + + let number_of_downloads = driver.load_torrent_downloads(&infohash).unwrap().unwrap(); + + assert_eq!(number_of_downloads, 2); + } + + // Aggregate metrics for all torrents + + pub fn it_should_save_and_load_the_global_number_of_downloads(driver: &Arc>) { + let number_of_downloads = 1; + + driver.save_global_downloads(number_of_downloads).unwrap(); + + let number_of_downloads = driver.load_global_downloads().unwrap().unwrap(); + + assert_eq!(number_of_downloads, 1); + } + + pub fn it_should_load_the_global_number_of_downloads(driver: &Arc>) { + let number_of_downloads = 1; + + driver.save_global_downloads(number_of_downloads).unwrap(); + + let number_of_downloads = driver.load_global_downloads().unwrap().unwrap(); + + assert_eq!(number_of_downloads, 1); + } + + pub fn it_should_increase_the_global_number_of_downloads(driver: &Arc>) { + let number_of_downloads = 1; + + driver.save_global_downloads(number_of_downloads).unwrap(); + + driver.increase_global_downloads().unwrap(); + + let number_of_downloads = driver.load_global_downloads().unwrap().unwrap(); + + assert_eq!(number_of_downloads, 2); + } + } + + mod handling_authentication_keys { + + use std::sync::Arc; + use std::time::Duration; + + use crate::authentication::key::{generate_expiring_key, generate_permanent_key}; + use crate::databases::Database; + + pub fn it_should_load_the_keys(driver: &Arc>) { + let permanent_peer_key = generate_permanent_key(); + driver.add_key_to_keys(&permanent_peer_key).unwrap(); + + let expiring_peer_key = generate_expiring_key(Duration::from_secs(120)); + driver.add_key_to_keys(&expiring_peer_key).unwrap(); + + let keys = driver.load_keys().unwrap(); + + assert!(keys.contains(&permanent_peer_key)); + assert!(keys.contains(&expiring_peer_key)); + } + + pub fn it_should_save_and_load_permanent_authentication_keys(driver: &Arc>) { + let peer_key = generate_permanent_key(); + driver.add_key_to_keys(&peer_key).unwrap(); + + let stored_peer_key = driver.get_key_from_keys(&peer_key.key()).unwrap().unwrap(); + + assert_eq!(stored_peer_key, peer_key); + } + + pub fn it_should_save_and_load_expiring_authentication_keys(driver: &Arc>) { + let peer_key = generate_expiring_key(Duration::from_secs(120)); + driver.add_key_to_keys(&peer_key).unwrap(); + + let stored_peer_key = driver.get_key_from_keys(&peer_key.key()).unwrap().unwrap(); + + assert_eq!(stored_peer_key, peer_key); + assert_eq!(stored_peer_key.expiry_time(), peer_key.expiry_time()); + } + + pub fn it_should_remove_a_permanent_authentication_key(driver: &Arc>) { + let peer_key = generate_permanent_key(); + driver.add_key_to_keys(&peer_key).unwrap(); + + driver.remove_key_from_keys(&peer_key.key()).unwrap(); + + assert!(driver.get_key_from_keys(&peer_key.key()).unwrap().is_none()); + } + + pub fn it_should_remove_an_expiring_authentication_key(driver: &Arc>) { + let peer_key = generate_expiring_key(Duration::from_secs(120)); + driver.add_key_to_keys(&peer_key).unwrap(); + + driver.remove_key_from_keys(&peer_key.key()).unwrap(); + + assert!(driver.get_key_from_keys(&peer_key.key()).unwrap().is_none()); + } + } + + mod handling_the_whitelist { + + use std::sync::Arc; + + use crate::databases::Database; + use crate::test_helpers::tests::random_info_hash; + + pub fn it_should_load_the_whitelist(driver: &Arc>) { + let infohash = random_info_hash(); + driver.add_info_hash_to_whitelist(infohash).unwrap(); + + let whitelist = driver.load_whitelist().unwrap(); + + assert!(whitelist.contains(&infohash)); + } + + pub fn it_should_add_and_get_infohashes(driver: &Arc>) { + let infohash = random_info_hash(); + + driver.add_info_hash_to_whitelist(infohash).unwrap(); + + let stored_infohash = driver.get_info_hash_from_whitelist(infohash).unwrap().unwrap(); + + assert_eq!(stored_infohash, infohash); + } + + pub fn it_should_remove_an_infohash_from_the_whitelist(driver: &Arc>) { + let infohash = random_info_hash(); + driver.add_info_hash_to_whitelist(infohash).unwrap(); + + driver.remove_info_hash_from_whitelist(infohash).unwrap(); + + assert!(driver.get_info_hash_from_whitelist(infohash).unwrap().is_none()); + } + + pub fn it_should_fail_trying_to_add_the_same_infohash_twice(driver: &Arc>) { + let infohash = random_info_hash(); + + driver.add_info_hash_to_whitelist(infohash).unwrap(); + let result = driver.add_info_hash_to_whitelist(infohash); + + assert!(result.is_err()); + } + } +} diff --git a/packages/tracker-core/src/databases/driver/mysql.rs b/packages/tracker-core/src/databases/driver/mysql.rs new file mode 100644 index 000000000..da2f86ce8 --- /dev/null +++ b/packages/tracker-core/src/databases/driver/mysql.rs @@ -0,0 +1,483 @@ +//! The `MySQL` database driver. +//! +//! This module provides an implementation of the [`Database`] trait for `MySQL` +//! using the `r2d2_mysql` connection pool. It configures the MySQL connection +//! based on a URL, creates the necessary tables (for torrent metrics, torrent +//! whitelist, and authentication keys), and implements all CRUD operations +//! required by the persistence layer. +use std::str::FromStr; +use std::time::Duration; + +use bittorrent_primitives::info_hash::InfoHash; +use r2d2::Pool; +use r2d2_mysql::mysql::prelude::Queryable; +use r2d2_mysql::mysql::{params, Opts, OptsBuilder}; +use r2d2_mysql::MySqlConnectionManager; +use torrust_tracker_primitives::{NumberOfDownloads, NumberOfDownloadsBTreeMap}; + +use super::{Database, Driver, Error, TORRENTS_DOWNLOADS_TOTAL}; +use crate::authentication::key::AUTH_KEY_LENGTH; +use crate::authentication::{self, Key}; + +const DRIVER: Driver = Driver::MySQL; + +/// `MySQL` driver implementation. +/// +/// This struct encapsulates a connection pool for `MySQL`, built using the +/// `r2d2_mysql` connection manager. It implements the [`Database`] trait to +/// provide persistence operations. +pub(crate) struct Mysql { + pool: Pool, +} + +impl Mysql { + /// It instantiates a new `MySQL` database driver. + /// + /// Refer to [`databases::Database::new`](crate::core::databases::Database::new). + /// + /// # Errors + /// + /// Will return `r2d2::Error` if `db_path` is not able to create `MySQL` database. + pub fn new(db_path: &str) -> Result { + let opts = Opts::from_url(db_path)?; + let builder = OptsBuilder::from_opts(opts); + let manager = MySqlConnectionManager::new(builder); + let pool = r2d2::Pool::builder().build(manager).map_err(|e| (e, DRIVER))?; + + Ok(Self { pool }) + } + + fn load_torrent_aggregate_metric(&self, metric_name: &str) -> Result, Error> { + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let query = conn.exec_first::( + "SELECT value FROM torrent_aggregate_metrics WHERE metric_name = :metric_name", + params! { "metric_name" => metric_name }, + ); + + let persistent_torrent = query?; + + Ok(persistent_torrent) + } + + fn save_torrent_aggregate_metric(&self, metric_name: &str, completed: NumberOfDownloads) -> Result<(), Error> { + const COMMAND : &str = "INSERT INTO torrent_aggregate_metrics (metric_name, value) VALUES (:metric_name, :completed) ON DUPLICATE KEY UPDATE value = VALUES(value)"; + + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + Ok(conn.exec_drop(COMMAND, params! { metric_name, completed })?) + } +} + +impl Database for Mysql { + /// Refer to [`databases::Database::create_database_tables`](crate::core::databases::Database::create_database_tables). + fn create_database_tables(&self) -> Result<(), Error> { + let create_whitelist_table = " + CREATE TABLE IF NOT EXISTS whitelist ( + id integer PRIMARY KEY AUTO_INCREMENT, + info_hash VARCHAR(40) NOT NULL UNIQUE + );" + .to_string(); + + let create_torrents_table = " + CREATE TABLE IF NOT EXISTS torrents ( + id integer PRIMARY KEY AUTO_INCREMENT, + info_hash VARCHAR(40) NOT NULL UNIQUE, + completed INTEGER DEFAULT 0 NOT NULL + );" + .to_string(); + + let create_torrent_aggregate_metrics_table = " + CREATE TABLE IF NOT EXISTS torrent_aggregate_metrics ( + id integer PRIMARY KEY AUTO_INCREMENT, + metric_name VARCHAR(50) NOT NULL UNIQUE, + value INTEGER DEFAULT 0 NOT NULL + );" + .to_string(); + + let create_keys_table = format!( + " + CREATE TABLE IF NOT EXISTS `keys` ( + `id` INT NOT NULL AUTO_INCREMENT, + `key` VARCHAR({}) NOT NULL, + `valid_until` INT(10), + PRIMARY KEY (`id`), + UNIQUE (`key`) + );", + i8::try_from(AUTH_KEY_LENGTH).expect("authentication key length should fit within a i8!") + ); + + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + conn.query_drop(&create_torrents_table) + .expect("Could not create torrents table."); + conn.query_drop(&create_torrent_aggregate_metrics_table) + .expect("Could not create create_torrent_aggregate_metrics_table table."); + conn.query_drop(&create_keys_table).expect("Could not create keys table."); + conn.query_drop(&create_whitelist_table) + .expect("Could not create whitelist table."); + + Ok(()) + } + + /// Refer to [`databases::Database::drop_database_tables`](crate::core::databases::Database::drop_database_tables). + fn drop_database_tables(&self) -> Result<(), Error> { + let drop_whitelist_table = " + DROP TABLE `whitelist`;" + .to_string(); + + let drop_torrents_table = " + DROP TABLE `torrents`;" + .to_string(); + + let drop_keys_table = " + DROP TABLE `keys`;" + .to_string(); + + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + conn.query_drop(&drop_whitelist_table) + .expect("Could not drop `whitelist` table."); + conn.query_drop(&drop_torrents_table) + .expect("Could not drop `torrents` table."); + conn.query_drop(&drop_keys_table).expect("Could not drop `keys` table."); + + Ok(()) + } + + /// Refer to [`databases::Database::load_persistent_torrents`](crate::core::databases::Database::load_persistent_torrents). + fn load_all_torrents_downloads(&self) -> Result { + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let torrents = conn.query_map( + "SELECT info_hash, completed FROM torrents", + |(info_hash_string, completed): (String, u32)| { + let info_hash = InfoHash::from_str(&info_hash_string).unwrap(); + (info_hash, completed) + }, + )?; + + Ok(torrents.iter().copied().collect()) + } + + /// Refer to [`databases::Database::load_persistent_torrent`](crate::core::databases::Database::load_persistent_torrent). + fn load_torrent_downloads(&self, info_hash: &InfoHash) -> Result, Error> { + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let query = conn.exec_first::( + "SELECT completed FROM torrents WHERE info_hash = :info_hash", + params! { "info_hash" => info_hash.to_hex_string() }, + ); + + let persistent_torrent = query?; + + Ok(persistent_torrent) + } + + /// Refer to [`databases::Database::save_persistent_torrent`](crate::core::databases::Database::save_persistent_torrent). + fn save_torrent_downloads(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { + const COMMAND : &str = "INSERT INTO torrents (info_hash, completed) VALUES (:info_hash_str, :completed) ON DUPLICATE KEY UPDATE completed = VALUES(completed)"; + + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let info_hash_str = info_hash.to_string(); + + Ok(conn.exec_drop(COMMAND, params! { info_hash_str, completed })?) + } + + /// Refer to [`databases::Database::increase_number_of_downloads`](crate::core::databases::Database::increase_number_of_downloads). + fn increase_downloads_for_torrent(&self, info_hash: &InfoHash) -> Result<(), Error> { + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let info_hash_str = info_hash.to_string(); + + conn.exec_drop( + "UPDATE torrents SET completed = completed + 1 WHERE info_hash = :info_hash_str", + params! { info_hash_str }, + )?; + + Ok(()) + } + + /// Refer to [`databases::Database::load_global_number_of_downloads`](crate::core::databases::Database::load_global_number_of_downloads). + fn load_global_downloads(&self) -> Result, Error> { + self.load_torrent_aggregate_metric(TORRENTS_DOWNLOADS_TOTAL) + } + + /// Refer to [`databases::Database::save_global_number_of_downloads`](crate::core::databases::Database::save_global_number_of_downloads). + fn save_global_downloads(&self, downloaded: NumberOfDownloads) -> Result<(), Error> { + self.save_torrent_aggregate_metric(TORRENTS_DOWNLOADS_TOTAL, downloaded) + } + + /// Refer to [`databases::Database::increase_global_number_of_downloads`](crate::core::databases::Database::increase_global_number_of_downloads). + fn increase_global_downloads(&self) -> Result<(), Error> { + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let metric_name = TORRENTS_DOWNLOADS_TOTAL; + + conn.exec_drop( + "UPDATE torrent_aggregate_metrics SET value = value + 1 WHERE metric_name = :metric_name", + params! { metric_name }, + )?; + + Ok(()) + } + + /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). + fn load_keys(&self) -> Result, Error> { + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let keys = conn.query_map( + "SELECT `key`, valid_until FROM `keys`", + |(key, valid_until): (String, Option)| match valid_until { + Some(valid_until) => authentication::PeerKey { + key: key.parse::().unwrap(), + valid_until: Some(Duration::from_secs(valid_until.unsigned_abs())), + }, + None => authentication::PeerKey { + key: key.parse::().unwrap(), + valid_until: None, + }, + }, + )?; + + Ok(keys) + } + + /// Refer to [`databases::Database::load_whitelist`](crate::core::databases::Database::load_whitelist). + fn load_whitelist(&self) -> Result, Error> { + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let info_hashes = conn.query_map("SELECT info_hash FROM whitelist", |info_hash: String| { + InfoHash::from_str(&info_hash).unwrap() + })?; + + Ok(info_hashes) + } + + /// Refer to [`databases::Database::get_info_hash_from_whitelist`](crate::core::databases::Database::get_info_hash_from_whitelist). + fn get_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result, Error> { + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let select = conn.exec_first::( + "SELECT info_hash FROM whitelist WHERE info_hash = :info_hash", + params! { "info_hash" => info_hash.to_hex_string() }, + )?; + + let info_hash = select.map(|f| InfoHash::from_str(&f).expect("Failed to decode InfoHash String from DB!")); + + Ok(info_hash) + } + + /// Refer to [`databases::Database::add_info_hash_to_whitelist`](crate::core::databases::Database::add_info_hash_to_whitelist). + fn add_info_hash_to_whitelist(&self, info_hash: InfoHash) -> Result { + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let info_hash_str = info_hash.to_string(); + + conn.exec_drop( + "INSERT INTO whitelist (info_hash) VALUES (:info_hash_str)", + params! { info_hash_str }, + )?; + + Ok(1) + } + + /// Refer to [`databases::Database::remove_info_hash_from_whitelist`](crate::core::databases::Database::remove_info_hash_from_whitelist). + fn remove_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result { + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let info_hash = info_hash.to_string(); + + conn.exec_drop("DELETE FROM whitelist WHERE info_hash = :info_hash", params! { info_hash })?; + + Ok(1) + } + + /// Refer to [`databases::Database::get_key_from_keys`](crate::core::databases::Database::get_key_from_keys). + fn get_key_from_keys(&self, key: &Key) -> Result, Error> { + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let query = conn.exec_first::<(String, Option), _, _>( + "SELECT `key`, valid_until FROM `keys` WHERE `key` = :key", + params! { "key" => key.to_string() }, + ); + + let key = query?; + + Ok(key.map(|(key, opt_valid_until)| match opt_valid_until { + Some(valid_until) => authentication::PeerKey { + key: key.parse::().unwrap(), + valid_until: Some(Duration::from_secs(valid_until.unsigned_abs())), + }, + None => authentication::PeerKey { + key: key.parse::().unwrap(), + valid_until: None, + }, + })) + } + + /// Refer to [`databases::Database::add_key_to_keys`](crate::core::databases::Database::add_key_to_keys). + fn add_key_to_keys(&self, auth_key: &authentication::PeerKey) -> Result { + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + match auth_key.valid_until { + Some(valid_until) => conn.exec_drop( + "INSERT INTO `keys` (`key`, valid_until) VALUES (:key, :valid_until)", + params! { "key" => auth_key.key.to_string(), "valid_until" => valid_until.as_secs().to_string() }, + )?, + None => conn.exec_drop( + "INSERT INTO `keys` (`key`) VALUES (:key)", + params! { "key" => auth_key.key.to_string() }, + )?, + } + + Ok(1) + } + + /// Refer to [`databases::Database::remove_key_from_keys`](crate::core::databases::Database::remove_key_from_keys). + fn remove_key_from_keys(&self, key: &Key) -> Result { + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + conn.exec_drop("DELETE FROM `keys` WHERE `key` = :key", params! { "key" => key.to_string() })?; + + Ok(1) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use testcontainers::core::IntoContainerPort; + /* + We run a MySQL container and run all the tests against the same container and database. + + Test for this driver are executed with: + + `TORRUST_TRACKER_CORE_RUN_MYSQL_DRIVER_TEST=true cargo test` + + The `Database` trait is very simple and we only have one driver that needs + a container. In the future we might want to use different approaches like: + + - https://github.com/testcontainers/testcontainers-rs/issues/707 + - https://www.infinyon.com/blog/2021/04/rust-custom-test-harness/ + - https://github.com/torrust/torrust-tracker/blob/develop/src/bin/e2e_tests_runner.rs + + If we increase the number of methods or the number or drivers. + */ + use testcontainers::runners::AsyncRunner; + use testcontainers::{ContainerAsync, GenericImage, ImageExt}; + use torrust_tracker_configuration::Core; + + use super::Mysql; + use crate::databases::driver::tests::run_tests; + use crate::databases::Database; + + #[derive(Debug, Default)] + struct StoppedMysqlContainer {} + + impl StoppedMysqlContainer { + async fn run(self, config: &MysqlConfiguration) -> Result> { + let container = GenericImage::new("mysql", "8.0") + .with_exposed_port(config.internal_port.tcp()) + // todo: this does not work + //.with_wait_for(WaitFor::message_on_stdout("ready for connections")) + .with_env_var("MYSQL_ROOT_PASSWORD", config.db_root_password.clone()) + .with_env_var("MYSQL_DATABASE", config.database.clone()) + .with_env_var("MYSQL_ROOT_HOST", "%") + .start() + .await?; + + Ok(RunningMysqlContainer::new(container, config.internal_port)) + } + } + + struct RunningMysqlContainer { + container: ContainerAsync, + internal_port: u16, + } + + impl RunningMysqlContainer { + fn new(container: ContainerAsync, internal_port: u16) -> Self { + Self { + container, + internal_port, + } + } + + async fn stop(self) { + self.container.stop().await.unwrap(); + } + + async fn get_host(&self) -> url::Host { + self.container.get_host().await.unwrap() + } + + async fn get_host_port_ipv4(&self) -> u16 { + self.container.get_host_port_ipv4(self.internal_port).await.unwrap() + } + } + + impl Default for MysqlConfiguration { + fn default() -> Self { + Self { + internal_port: 3306, + database: "torrust_tracker_test".to_string(), + db_user: "root".to_string(), + db_root_password: "test".to_string(), + } + } + } + + struct MysqlConfiguration { + pub internal_port: u16, + pub database: String, + pub db_user: String, + pub db_root_password: String, + } + + fn core_configuration(host: &url::Host, port: u16, mysql_configuration: &MysqlConfiguration) -> Core { + let mut config = Core::default(); + + let database = mysql_configuration.database.clone(); + let db_user = mysql_configuration.db_user.clone(); + let db_password = mysql_configuration.db_root_password.clone(); + + config.database.path = format!("mysql://{db_user}:{db_password}@{host}:{port}/{database}"); + + config + } + + fn initialize_driver(config: &Core) -> Arc> { + let driver: Arc> = Arc::new(Box::new(Mysql::new(&config.database.path).unwrap())); + driver + } + + #[tokio::test] + async fn run_mysql_driver_tests() -> Result<(), Box> { + if std::env::var("TORRUST_TRACKER_CORE_RUN_MYSQL_DRIVER_TEST").is_err() { + println!("Skipping the MySQL driver tests."); + return Ok(()); + } + + let mysql_configuration = MysqlConfiguration::default(); + + let stopped_mysql_container = StoppedMysqlContainer::default(); + + let mysql_container = stopped_mysql_container.run(&mysql_configuration).await.unwrap(); + + let host = mysql_container.get_host().await; + let port = mysql_container.get_host_port_ipv4().await; + + let config = core_configuration(&host, port, &mysql_configuration); + + let driver = initialize_driver(&config); + + run_tests(&driver).await; + + mysql_container.stop().await; + + Ok(()) + } +} diff --git a/packages/tracker-core/src/databases/driver/sqlite.rs b/packages/tracker-core/src/databases/driver/sqlite.rs new file mode 100644 index 000000000..d08351aa8 --- /dev/null +++ b/packages/tracker-core/src/databases/driver/sqlite.rs @@ -0,0 +1,437 @@ +//! The `SQLite3` database driver. +//! +//! This module provides an implementation of the [`Database`] trait for +//! `SQLite3` using the `r2d2_sqlite` connection pool. It defines the schema for +//! whitelist, torrent metrics, and authentication keys, and provides methods +//! to create and drop tables as well as perform CRUD operations on these +//! persistent objects. +use std::panic::Location; +use std::str::FromStr; + +use bittorrent_primitives::info_hash::InfoHash; +use r2d2::Pool; +use r2d2_sqlite::rusqlite::params; +use r2d2_sqlite::rusqlite::types::Null; +use r2d2_sqlite::SqliteConnectionManager; +use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; + +use super::{Database, Driver, Error, TORRENTS_DOWNLOADS_TOTAL}; +use crate::authentication::{self, Key}; + +const DRIVER: Driver = Driver::Sqlite3; + +/// `SQLite` driver implementation. +/// +/// This struct encapsulates a connection pool for `SQLite` using the `r2d2_sqlite` +/// connection manager. +pub(crate) struct Sqlite { + pool: Pool, +} + +impl Sqlite { + /// Instantiates a new `SQLite3` database driver. + /// + /// This function creates a connection manager for the `SQLite` database + /// located at `db_path` and then builds a connection pool using `r2d2`. If + /// the pool cannot be created, an error is returned (wrapped with the + /// appropriate driver information). + /// + /// # Arguments + /// + /// * `db_path` - A string slice representing the file path to the `SQLite` database. + /// + /// # Errors + /// + /// Returns an [`Error`] if the connection pool cannot be built. + pub fn new(db_path: &str) -> Result { + let manager = SqliteConnectionManager::file(db_path); + let pool = r2d2::Pool::builder().build(manager).map_err(|e| (e, DRIVER))?; + + Ok(Self { pool }) + } + + fn load_torrent_aggregate_metric(&self, metric_name: &str) -> Result, Error> { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let mut stmt = conn.prepare("SELECT value FROM torrent_aggregate_metrics WHERE metric_name = ?")?; + + let mut rows = stmt.query([metric_name])?; + + let persistent_torrent = rows.next()?; + + Ok(persistent_torrent.map(|f| { + let value: i64 = f.get(0).unwrap(); + u32::try_from(value).unwrap() + })) + } + + fn save_torrent_aggregate_metric(&self, metric_name: &str, completed: NumberOfDownloads) -> Result<(), Error> { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let insert = conn.execute( + "INSERT INTO torrent_aggregate_metrics (metric_name, value) VALUES (?1, ?2) ON CONFLICT(metric_name) DO UPDATE SET value = ?2", + [metric_name.to_string(), completed.to_string()], + )?; + + if insert == 0 { + Err(Error::InsertFailed { + location: Location::caller(), + driver: DRIVER, + }) + } else { + Ok(()) + } + } +} + +impl Database for Sqlite { + /// Refer to [`databases::Database::create_database_tables`](crate::core::databases::Database::create_database_tables). + fn create_database_tables(&self) -> Result<(), Error> { + let create_whitelist_table = " + CREATE TABLE IF NOT EXISTS whitelist ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + info_hash TEXT NOT NULL UNIQUE + );" + .to_string(); + + let create_torrents_table = " + CREATE TABLE IF NOT EXISTS torrents ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + info_hash TEXT NOT NULL UNIQUE, + completed INTEGER DEFAULT 0 NOT NULL + );" + .to_string(); + + let create_torrent_aggregate_metrics_table = " + CREATE TABLE IF NOT EXISTS torrent_aggregate_metrics ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + metric_name TEXT NOT NULL UNIQUE, + value INTEGER DEFAULT 0 NOT NULL + );" + .to_string(); + + let create_keys_table = " + CREATE TABLE IF NOT EXISTS keys ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + key TEXT NOT NULL UNIQUE, + valid_until INTEGER + );" + .to_string(); + + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + conn.execute(&create_whitelist_table, [])?; + conn.execute(&create_keys_table, [])?; + conn.execute(&create_torrents_table, [])?; + conn.execute(&create_torrent_aggregate_metrics_table, [])?; + + Ok(()) + } + + /// Refer to [`databases::Database::drop_database_tables`](crate::core::databases::Database::drop_database_tables). + fn drop_database_tables(&self) -> Result<(), Error> { + let drop_whitelist_table = " + DROP TABLE whitelist;" + .to_string(); + + let drop_torrents_table = " + DROP TABLE torrents;" + .to_string(); + + let drop_keys_table = " + DROP TABLE keys;" + .to_string(); + + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + conn.execute(&drop_whitelist_table, []) + .and_then(|_| conn.execute(&drop_torrents_table, [])) + .and_then(|_| conn.execute(&drop_keys_table, []))?; + + Ok(()) + } + + /// Refer to [`databases::Database::load_persistent_torrents`](crate::core::databases::Database::load_persistent_torrents). + fn load_all_torrents_downloads(&self) -> Result { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let mut stmt = conn.prepare("SELECT info_hash, completed FROM torrents")?; + + let torrent_iter = stmt.query_map([], |row| { + let info_hash_string: String = row.get(0)?; + let info_hash = InfoHash::from_str(&info_hash_string).unwrap(); + let completed: u32 = row.get(1)?; + Ok((info_hash, completed)) + })?; + + Ok(torrent_iter.filter_map(std::result::Result::ok).collect()) + } + + /// Refer to [`databases::Database::load_persistent_torrent`](crate::core::databases::Database::load_persistent_torrent). + fn load_torrent_downloads(&self, info_hash: &InfoHash) -> Result, Error> { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let mut stmt = conn.prepare("SELECT completed FROM torrents WHERE info_hash = ?")?; + + let mut rows = stmt.query([info_hash.to_hex_string()])?; + + let persistent_torrent = rows.next()?; + + Ok(persistent_torrent.map(|f| { + let completed: i64 = f.get(0).unwrap(); + u32::try_from(completed).unwrap() + })) + } + + /// Refer to [`databases::Database::save_persistent_torrent`](crate::core::databases::Database::save_persistent_torrent). + fn save_torrent_downloads(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let insert = conn.execute( + "INSERT INTO torrents (info_hash, completed) VALUES (?1, ?2) ON CONFLICT(info_hash) DO UPDATE SET completed = ?2", + [info_hash.to_string(), completed.to_string()], + )?; + + if insert == 0 { + Err(Error::InsertFailed { + location: Location::caller(), + driver: DRIVER, + }) + } else { + Ok(()) + } + } + + /// Refer to [`databases::Database::increase_number_of_downloads`](crate::core::databases::Database::increase_number_of_downloads). + fn increase_downloads_for_torrent(&self, info_hash: &InfoHash) -> Result<(), Error> { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let _ = conn.execute( + "UPDATE torrents SET completed = completed + 1 WHERE info_hash = ?", + [info_hash.to_string()], + )?; + + Ok(()) + } + + /// Refer to [`databases::Database::load_global_number_of_downloads`](crate::core::databases::Database::load_global_number_of_downloads). + fn load_global_downloads(&self) -> Result, Error> { + self.load_torrent_aggregate_metric(TORRENTS_DOWNLOADS_TOTAL) + } + + /// Refer to [`databases::Database::save_global_number_of_downloads`](crate::core::databases::Database::save_global_number_of_downloads). + fn save_global_downloads(&self, downloaded: NumberOfDownloads) -> Result<(), Error> { + self.save_torrent_aggregate_metric(TORRENTS_DOWNLOADS_TOTAL, downloaded) + } + + /// Refer to [`databases::Database::increase_global_number_of_downloads`](crate::core::databases::Database::increase_global_number_of_downloads). + fn increase_global_downloads(&self) -> Result<(), Error> { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let metric_name = TORRENTS_DOWNLOADS_TOTAL; + + let _ = conn.execute( + "UPDATE torrent_aggregate_metrics SET value = value + 1 WHERE metric_name = ?", + [metric_name], + )?; + + Ok(()) + } + + /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). + fn load_keys(&self) -> Result, Error> { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let mut stmt = conn.prepare("SELECT key, valid_until FROM keys")?; + + let keys_iter = stmt.query_map([], |row| { + let key: String = row.get(0)?; + let opt_valid_until: Option = row.get(1)?; + + match opt_valid_until { + Some(valid_until) => Ok(authentication::PeerKey { + key: key.parse::().unwrap(), + valid_until: Some(DurationSinceUnixEpoch::from_secs(valid_until.unsigned_abs())), + }), + None => Ok(authentication::PeerKey { + key: key.parse::().unwrap(), + valid_until: None, + }), + } + })?; + + let keys: Vec = keys_iter.filter_map(std::result::Result::ok).collect(); + + Ok(keys) + } + + /// Refer to [`databases::Database::load_whitelist`](crate::core::databases::Database::load_whitelist). + fn load_whitelist(&self) -> Result, Error> { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let mut stmt = conn.prepare("SELECT info_hash FROM whitelist")?; + + let info_hash_iter = stmt.query_map([], |row| { + let info_hash: String = row.get(0)?; + + Ok(InfoHash::from_str(&info_hash).unwrap()) + })?; + + let info_hashes: Vec = info_hash_iter.filter_map(std::result::Result::ok).collect(); + + Ok(info_hashes) + } + + /// Refer to [`databases::Database::get_info_hash_from_whitelist`](crate::core::databases::Database::get_info_hash_from_whitelist). + fn get_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result, Error> { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let mut stmt = conn.prepare("SELECT info_hash FROM whitelist WHERE info_hash = ?")?; + + let mut rows = stmt.query([info_hash.to_hex_string()])?; + + let query = rows.next()?; + + Ok(query.map(|f| InfoHash::from_str(&f.get_unwrap::<_, String>(0)).unwrap())) + } + + /// Refer to [`databases::Database::add_info_hash_to_whitelist`](crate::core::databases::Database::add_info_hash_to_whitelist). + fn add_info_hash_to_whitelist(&self, info_hash: InfoHash) -> Result { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let insert = conn.execute("INSERT INTO whitelist (info_hash) VALUES (?)", [info_hash.to_string()])?; + + if insert == 0 { + Err(Error::InsertFailed { + location: Location::caller(), + driver: DRIVER, + }) + } else { + Ok(insert) + } + } + + /// Refer to [`databases::Database::remove_info_hash_from_whitelist`](crate::core::databases::Database::remove_info_hash_from_whitelist). + fn remove_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let deleted = conn.execute("DELETE FROM whitelist WHERE info_hash = ?", [info_hash.to_string()])?; + + if deleted == 1 { + // should only remove a single record. + Ok(deleted) + } else { + Err(Error::DeleteFailed { + location: Location::caller(), + error_code: deleted, + driver: DRIVER, + }) + } + } + + /// Refer to [`databases::Database::get_key_from_keys`](crate::core::databases::Database::get_key_from_keys). + fn get_key_from_keys(&self, key: &Key) -> Result, Error> { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let mut stmt = conn.prepare("SELECT key, valid_until FROM keys WHERE key = ?")?; + + let mut rows = stmt.query([key.to_string()])?; + + let key = rows.next()?; + + Ok(key.map(|f| { + let valid_until: Option = f.get(1).unwrap(); + let key: String = f.get(0).unwrap(); + + match valid_until { + Some(valid_until) => authentication::PeerKey { + key: key.parse::().unwrap(), + valid_until: Some(DurationSinceUnixEpoch::from_secs(valid_until.unsigned_abs())), + }, + None => authentication::PeerKey { + key: key.parse::().unwrap(), + valid_until: None, + }, + } + })) + } + + /// Refer to [`databases::Database::add_key_to_keys`](crate::core::databases::Database::add_key_to_keys). + fn add_key_to_keys(&self, auth_key: &authentication::PeerKey) -> Result { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let insert = match auth_key.valid_until { + Some(valid_until) => conn.execute( + "INSERT INTO keys (key, valid_until) VALUES (?1, ?2)", + [auth_key.key.to_string(), valid_until.as_secs().to_string()], + )?, + None => conn.execute( + "INSERT INTO keys (key, valid_until) VALUES (?1, ?2)", + params![auth_key.key.to_string(), Null], + )?, + }; + + if insert == 0 { + Err(Error::InsertFailed { + location: Location::caller(), + driver: DRIVER, + }) + } else { + Ok(insert) + } + } + + /// Refer to [`databases::Database::remove_key_from_keys`](crate::core::databases::Database::remove_key_from_keys). + fn remove_key_from_keys(&self, key: &Key) -> Result { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let deleted = conn.execute("DELETE FROM keys WHERE key = ?", [key.to_string()])?; + + if deleted == 1 { + // should only remove a single record. + Ok(deleted) + } else { + Err(Error::DeleteFailed { + location: Location::caller(), + error_code: deleted, + driver: DRIVER, + }) + } + } +} + +#[cfg(test)] +mod tests { + + use std::sync::Arc; + + use torrust_tracker_configuration::Core; + use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; + + use crate::databases::driver::sqlite::Sqlite; + use crate::databases::driver::tests::run_tests; + use crate::databases::Database; + + fn ephemeral_configuration() -> Core { + let mut config = Core::default(); + let temp_file = ephemeral_sqlite_database(); + temp_file.to_str().unwrap().clone_into(&mut config.database.path); + config + } + + fn initialize_driver(config: &Core) -> Arc> { + let driver: Arc> = Arc::new(Box::new(Sqlite::new(&config.database.path).unwrap())); + driver + } + + #[tokio::test] + async fn run_sqlite_driver_tests() -> Result<(), Box> { + let config = ephemeral_configuration(); + + let driver = initialize_driver(&config); + + run_tests(&driver).await; + + Ok(()) + } +} diff --git a/packages/tracker-core/src/databases/error.rs b/packages/tracker-core/src/databases/error.rs new file mode 100644 index 000000000..2df2cb277 --- /dev/null +++ b/packages/tracker-core/src/databases/error.rs @@ -0,0 +1,173 @@ +//! Database errors. +//! +//! This module defines the [`Error`] enum used to represent errors that occur +//! during database operations. These errors encapsulate issues such as missing +//! query results, malformed queries, connection failures, and connection pool +//! creation errors. Each error variant includes contextual information such as +//! the associated database driver and, when applicable, the source error. +//! +//! External errors from database libraries (e.g., `rusqlite`, `mysql`) are +//! converted into this error type using the provided `From` implementations. +use std::panic::Location; +use std::sync::Arc; + +use r2d2_mysql::mysql::UrlError; +use torrust_tracker_located_error::{DynError, Located, LocatedError}; + +use super::driver::Driver; + +/// Database error type that encapsulates various failures encountered during +/// database operations. +#[derive(thiserror::Error, Debug, Clone)] +pub enum Error { + /// Indicates that a query unexpectedly returned no rows. + /// + /// This error variant is used when a query that is expected to return a + /// result does not. + #[error("The {driver} query unexpectedly returned nothing: {source}")] + QueryReturnedNoRows { + source: LocatedError<'static, dyn std::error::Error + Send + Sync>, + driver: Driver, + }, + + /// Indicates that the query was malformed. + /// + /// This error variant is used when the SQL query itself is invalid or + /// improperly formatted. + #[error("The {driver} query was malformed: {source}")] + InvalidQuery { + source: LocatedError<'static, dyn std::error::Error + Send + Sync>, + driver: Driver, + }, + + /// Indicates a failure to insert a record into the database. + /// + /// This error is raised when an insertion operation fails. + #[error("Unable to insert record into {driver} database, {location}")] + InsertFailed { + location: &'static Location<'static>, + driver: Driver, + }, + + /// Indicates a failure to update a record into the database. + /// + /// This error is raised when an insertion operation fails. + #[error("Unable to update record into {driver} database, {location}")] + UpdateFailed { + location: &'static Location<'static>, + driver: Driver, + }, + + /// Indicates a failure to delete a record from the database. + /// + /// This error includes an error code that may be returned by the database + /// driver. + #[error("Failed to remove record from {driver} database, error-code: {error_code}, {location}")] + DeleteFailed { + location: &'static Location<'static>, + error_code: usize, + driver: Driver, + }, + + /// Indicates a failure to connect to the database. + /// + /// This error variant wraps connection-related errors, such as those caused by an invalid URL. + #[error("Failed to connect to {driver} database: {source}")] + ConnectionError { + source: LocatedError<'static, UrlError>, + driver: Driver, + }, + + /// Indicates a failure to create a connection pool. + /// + /// This error variant is used when the connection pool creation (using r2d2) fails. + #[error("Failed to create r2d2 {driver} connection pool: {source}")] + ConnectionPool { + source: LocatedError<'static, r2d2::Error>, + driver: Driver, + }, +} + +impl From for Error { + #[track_caller] + fn from(err: r2d2_sqlite::rusqlite::Error) -> Self { + match err { + r2d2_sqlite::rusqlite::Error::QueryReturnedNoRows => Error::QueryReturnedNoRows { + source: (Arc::new(err) as DynError).into(), + driver: Driver::Sqlite3, + }, + _ => Error::InvalidQuery { + source: (Arc::new(err) as DynError).into(), + driver: Driver::Sqlite3, + }, + } + } +} + +impl From for Error { + #[track_caller] + fn from(err: r2d2_mysql::mysql::Error) -> Self { + let e: DynError = Arc::new(err); + Error::InvalidQuery { + source: e.into(), + driver: Driver::MySQL, + } + } +} + +impl From for Error { + #[track_caller] + fn from(err: UrlError) -> Self { + Self::ConnectionError { + source: Located(err).into(), + driver: Driver::MySQL, + } + } +} + +impl From<(r2d2::Error, Driver)> for Error { + #[track_caller] + fn from(e: (r2d2::Error, Driver)) -> Self { + let (err, driver) = e; + Self::ConnectionPool { + source: Located(err).into(), + driver, + } + } +} + +#[cfg(test)] +mod tests { + use r2d2_mysql::mysql; + + use crate::databases::error::Error; + + #[test] + fn it_should_build_a_database_error_from_a_rusqlite_error() { + let err: Error = r2d2_sqlite::rusqlite::Error::InvalidQuery.into(); + + assert!(matches!(err, Error::InvalidQuery { .. })); + } + + #[test] + fn it_should_build_an_specific_database_error_from_a_no_rows_returned_rusqlite_error() { + let err: Error = r2d2_sqlite::rusqlite::Error::QueryReturnedNoRows.into(); + + assert!(matches!(err, Error::QueryReturnedNoRows { .. })); + } + + #[test] + fn it_should_build_a_database_error_from_a_mysql_error() { + let url_err = mysql::error::UrlError::BadUrl; + let err: Error = r2d2_mysql::mysql::Error::UrlError(url_err).into(); + + assert!(matches!(err, Error::InvalidQuery { .. })); + } + + #[test] + fn it_should_build_a_database_error_from_a_mysql_url_error() { + let err: Error = mysql::error::UrlError::BadUrl.into(); + + assert!(matches!(err, Error::ConnectionError { .. })); + } +} diff --git a/packages/tracker-core/src/databases/mod.rs b/packages/tracker-core/src/databases/mod.rs new file mode 100644 index 000000000..c9d89769a --- /dev/null +++ b/packages/tracker-core/src/databases/mod.rs @@ -0,0 +1,272 @@ +//! The persistence module. +//! +//! Persistence is currently implemented using a single [`Database`] trait. +//! +//! There are two implementations of the trait (two drivers): +//! +//! - **`MySQL`** +//! - **`Sqlite`** +//! +//! > **NOTICE**: There are no database migrations at this time. If schema +//! > changes occur, either migration functionality will be implemented or a +//! > script will be provided to migrate to the new schema. +//! +//! The persistent objects handled by this module include: +//! +//! - **Torrent metrics**: Metrics such as the number of completed downloads for +//! each torrent. +//! - **Torrent whitelist**: A list of torrents (by infohash) that are allowed. +//! - **Authentication keys**: Expiring authentication keys used to secure +//! access to private trackers. +//! +//! # Torrent Metrics +//! +//! | Field | Sample data | Description | +//! |-------------|--------------------------------------------|-----------------------------------------------------------------------------| +//! | `id` | 1 | Auto-increment id | +//! | `info_hash` | `c1277613db1d28709b034a017ab2cae4be07ae10` | `BitTorrent` infohash V1 | +//! | `completed` | 20 | The number of peers that have completed downloading the associated torrent. | +//! +//! > **NOTICE**: The peer list for a torrent is not persisted. Because peers re-announce at +//! > intervals, the peer list is regenerated periodically. +//! +//! # Torrent Whitelist +//! +//! | Field | Sample data | Description | +//! |-------------|--------------------------------------------|--------------------------------| +//! | `id` | 1 | Auto-increment id | +//! | `info_hash` | `c1277613db1d28709b034a017ab2cae4be07ae10` | `BitTorrent` infohash V1 | +//! +//! # Authentication Keys +//! +//! | Field | Sample data | Description | +//! |---------------|------------------------------------|--------------------------------------| +//! | `id` | 1 | Auto-increment id | +//! | `key` | `IrweYtVuQPGbG9Jzx1DihcPmJGGpVy82` | Authentication token (32 chars) | +//! | `valid_until` | 1672419840 | Timestamp indicating expiration time | +//! +//! > **NOTICE**: All authentication keys must have an expiration date. +pub mod driver; +pub mod error; +pub mod setup; + +use bittorrent_primitives::info_hash::InfoHash; +use mockall::automock; +use torrust_tracker_primitives::{NumberOfDownloads, NumberOfDownloadsBTreeMap}; + +use self::error::Error; +use crate::authentication::{self, Key}; + +/// The persistence trait. +/// +/// This trait defines all the methods required to interact with the database, +/// including creating and dropping schema tables, and CRUD operations for +/// torrent metrics, whitelists, and authentication keys. Implementations of +/// this trait must ensure that operations are safe, consistent, and report +/// errors using the [`Error`] type. +#[automock] +pub trait Database: Sync + Send { + /// Creates the necessary database tables. + /// + /// The SQL queries for table creation are hardcoded in the trait implementation. + /// + /// # Context: Schema + /// + /// # Errors + /// + /// Returns an [`Error`] if the tables cannot be created. + fn create_database_tables(&self) -> Result<(), Error>; + + /// Drops the database tables. + /// + /// This operation removes the persistent schema. + /// + /// # Context: Schema + /// + /// # Errors + /// + /// Returns an [`Error`] if the tables cannot be dropped. + fn drop_database_tables(&self) -> Result<(), Error>; + + // Torrent Metrics + + /// Loads torrent metrics data from the database for all torrents. + /// + /// This function returns the persistent torrent metrics as a collection of + /// tuples, where each tuple contains an [`InfoHash`] and the `downloaded` + /// counter (i.e. the number of times the torrent has been downloaded). + /// + /// # Context: Torrent Metrics + /// + /// # Errors + /// + /// Returns an [`Error`] if the metrics cannot be loaded. + fn load_all_torrents_downloads(&self) -> Result; + + /// Loads torrent metrics data from the database for one torrent. + /// + /// # Context: Torrent Metrics + /// + /// # Errors + /// + /// Returns an [`Error`] if the metrics cannot be loaded. + fn load_torrent_downloads(&self, info_hash: &InfoHash) -> Result, Error>; + + /// Saves torrent metrics data into the database. + /// + /// # Arguments + /// + /// * `info_hash` - A reference to the torrent's info hash. + /// * `downloaded` - The number of times the torrent has been downloaded. + /// + /// # Context: Torrent Metrics + /// + /// # Errors + /// + /// Returns an [`Error`] if the metrics cannot be saved. + fn save_torrent_downloads(&self, info_hash: &InfoHash, downloaded: u32) -> Result<(), Error>; + + /// Increases the number of downloads for a given torrent. + /// + /// It does not create a new entry if the torrent is not found and it does + /// not return an error. + /// + /// # Context: Torrent Metrics + /// + /// # Arguments + /// + /// * `info_hash` - A reference to the torrent's info hash. + /// + /// # Errors + /// + /// Returns an [`Error`] if the query failed. + fn increase_downloads_for_torrent(&self, info_hash: &InfoHash) -> Result<(), Error>; + + /// Loads the total number of downloads for all torrents from the database. + /// + /// # Context: Torrent Metrics + /// + /// # Errors + /// + /// Returns an [`Error`] if the total downloads cannot be loaded. + fn load_global_downloads(&self) -> Result, Error>; + + /// Saves the total number of downloads for all torrents into the database. + /// + /// # Context: Torrent Metrics + /// + /// # Arguments + /// + /// * `info_hash` - A reference to the torrent's info hash. + /// * `downloaded` - The number of times the torrent has been downloaded. + /// + /// # Errors + /// + /// Returns an [`Error`] if the total downloads cannot be saved. + fn save_global_downloads(&self, downloaded: NumberOfDownloads) -> Result<(), Error>; + + /// Increases the total number of downloads for all torrents. + /// + /// # Context: Torrent Metrics + /// + /// # Errors + /// + /// Returns an [`Error`] if the query failed. + fn increase_global_downloads(&self) -> Result<(), Error>; + + // Whitelist + + /// Loads the whitelisted torrents from the database. + /// + /// # Context: Whitelist + /// + /// # Errors + /// + /// Returns an [`Error`] if the whitelist cannot be loaded. + fn load_whitelist(&self) -> Result, Error>; + + /// Retrieves a whitelisted torrent from the database. + /// + /// Returns `Some(InfoHash)` if the torrent is in the whitelist, or `None` + /// otherwise. + /// + /// # Context: Whitelist + /// + /// # Errors + /// + /// Returns an [`Error`] if the whitelist cannot be queried. + fn get_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result, Error>; + + /// Adds a torrent to the whitelist. + /// + /// # Context: Whitelist + /// + /// # Errors + /// + /// Returns an [`Error`] if the torrent cannot be added to the whitelist. + fn add_info_hash_to_whitelist(&self, info_hash: InfoHash) -> Result; + + /// Checks whether a torrent is whitelisted. + /// + /// This default implementation returns `true` if the infohash is included + /// in the whitelist, or `false` otherwise. + /// + /// # Context: Whitelist + /// + /// # Errors + /// + /// Returns an [`Error`] if the whitelist cannot be queried. + fn is_info_hash_whitelisted(&self, info_hash: InfoHash) -> Result { + Ok(self.get_info_hash_from_whitelist(info_hash)?.is_some()) + } + + /// Removes a torrent from the whitelist. + /// + /// # Context: Whitelist + /// + /// # Errors + /// + /// Returns an [`Error`] if the torrent cannot be removed from the whitelist. + fn remove_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result; + + // Authentication keys + + /// Loads all authentication keys from the database. + /// + /// # Context: Authentication Keys + /// + /// # Errors + /// + /// Returns an [`Error`] if the keys cannot be loaded. + fn load_keys(&self) -> Result, Error>; + + /// Retrieves a specific authentication key from the database. + /// + /// Returns `Some(PeerKey)` if a key corresponding to the provided [`Key`] + /// exists, or `None` otherwise. + /// + /// # Context: Authentication Keys + /// + /// # Errors + /// + /// Returns an [`Error`] if the key cannot be queried. + fn get_key_from_keys(&self, key: &Key) -> Result, Error>; + + /// Adds an authentication key to the database. + /// + /// # Context: Authentication Keys + /// + /// # Errors + /// + /// Returns an [`Error`] if the key cannot be saved. + fn add_key_to_keys(&self, auth_key: &authentication::PeerKey) -> Result; + + /// Removes an authentication key from the database. + /// + /// # Context: Authentication Keys + /// + /// # Errors + /// + /// Returns an [`Error`] if the key cannot be removed. + fn remove_key_from_keys(&self, key: &Key) -> Result; +} diff --git a/packages/tracker-core/src/databases/setup.rs b/packages/tracker-core/src/databases/setup.rs new file mode 100644 index 000000000..6ba9f2a64 --- /dev/null +++ b/packages/tracker-core/src/databases/setup.rs @@ -0,0 +1,61 @@ +//! This module provides functionality for setting up databases. +use std::sync::Arc; + +use torrust_tracker_configuration::Core; + +use super::driver::{self, Driver}; +use super::Database; + +/// Initializes and returns a database instance based on the provided configuration. +/// +/// This function creates a new database instance according to the settings +/// defined in the [`Core`] configuration. It selects the appropriate driver +/// (either `Sqlite3` or `MySQL`) as specified in `config.database.driver` and +/// attempts to build the database connection using the path defined in +/// `config.database.path`. +/// +/// The resulting database instance is wrapped in a shared pointer (`Arc`) to a +/// boxed trait object, allowing safe sharing of the database connection across +/// multiple threads. +/// +/// # Panics +/// +/// This function will panic if the database cannot be initialized (i.e., if the +/// driver fails to build the connection). This is enforced by the use of +/// [`expect`](std::result::Result::expect) in the implementation. +/// +/// # Example +/// +/// ```rust,no_run +/// use torrust_tracker_configuration::Core; +/// use bittorrent_tracker_core::databases::setup::initialize_database; +/// +/// // Create a default configuration (ensure it is properly set up for your environment) +/// let config = Core::default(); +/// +/// // Initialize the database; this will panic if initialization fails. +/// let database = initialize_database(&config); +/// +/// // The returned database instance can now be used for persistence operations. +/// ``` +#[must_use] +pub fn initialize_database(config: &Core) -> Arc> { + let driver = match config.database.driver { + torrust_tracker_configuration::Driver::Sqlite3 => Driver::Sqlite3, + torrust_tracker_configuration::Driver::MySQL => Driver::MySQL, + }; + + Arc::new(driver::build(&driver, &config.database.path).expect("Database driver build failed.")) +} + +#[cfg(test)] +mod tests { + use super::initialize_database; + use crate::test_helpers::tests::ephemeral_configuration; + + #[test] + fn it_should_initialize_the_sqlite_database() { + let config = ephemeral_configuration(); + let _database = initialize_database(&config); + } +} diff --git a/packages/tracker-core/src/error.rs b/packages/tracker-core/src/error.rs new file mode 100644 index 000000000..866aa64c5 --- /dev/null +++ b/packages/tracker-core/src/error.rs @@ -0,0 +1,205 @@ +//! Core tracker errors. +//! +//! This module defines the error types used internally by the `BitTorrent` +//! tracker core. +//! +//! These errors encapsulate issues such as whitelisting violations, invalid +//! peer key data, and database persistence failures. Each error variant +//! includes contextual information (such as source code location) to facilitate +//! debugging. +use std::panic::Location; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_located_error::LocatedError; + +use super::authentication::key::ParseKeyError; +use super::databases; +use crate::authentication; + +/// Wrapper for all errors returned by the tracker core. +#[derive(thiserror::Error, Debug, Clone)] +pub enum TrackerCoreError { + /// Error returned when there was an error with the tracker core announce handler. + #[error("Tracker core announce error: {source}")] + AnnounceError { source: AnnounceError }, + + /// Error returned when there was an error with the tracker core scrape handler. + #[error("Tracker core scrape error: {source}")] + ScrapeError { source: ScrapeError }, + + /// Error returned when there was an error with the tracker core whitelist. + #[error("Tracker core whitelist error: {source}")] + WhitelistError { source: WhitelistError }, + + /// Error returned when there was an error with the authentication in the tracker core. + #[error("Tracker core authentication error: {source}")] + AuthenticationError { source: authentication::key::Error }, +} + +impl From for TrackerCoreError { + fn from(announce_error: AnnounceError) -> Self { + Self::AnnounceError { source: announce_error } + } +} + +impl From for TrackerCoreError { + fn from(scrape_error: ScrapeError) -> Self { + Self::ScrapeError { source: scrape_error } + } +} + +impl From for TrackerCoreError { + fn from(whitelist_error: WhitelistError) -> Self { + Self::WhitelistError { source: whitelist_error } + } +} + +impl From for TrackerCoreError { + fn from(whitelist_error: authentication::key::Error) -> Self { + Self::AuthenticationError { source: whitelist_error } + } +} + +/// Errors related to announce requests. +#[derive(thiserror::Error, Debug, Clone)] +pub enum AnnounceError { + /// Wraps errors related to torrent whitelisting. + #[error("Whitelist error: {0}")] + Whitelist(#[from] WhitelistError), + + /// Wraps errors related to database. + #[error("Database error: {0}")] + Database(#[from] databases::error::Error), +} + +/// Errors related to scrape requests. +#[derive(thiserror::Error, Debug, Clone)] +pub enum ScrapeError { + /// Wraps errors related to torrent whitelisting. + #[error("Whitelist error: {0}")] + Whitelist(#[from] WhitelistError), +} + +/// Errors related to torrent whitelisting. +/// +/// This error is returned when an operation involves a torrent that is not +/// present in the whitelist. +#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)] +pub enum WhitelistError { + /// Indicates that the torrent identified by `info_hash` is not whitelisted. + #[error("The torrent: {info_hash}, is not whitelisted, {location}")] + TorrentNotWhitelisted { + info_hash: InfoHash, + location: &'static Location<'static>, + }, +} + +/// Errors related to peer key operations. +/// +/// This error type covers issues encountered during the handling of peer keys, +/// including validation of key durations, parsing errors, and database +/// persistence problems. +#[allow(clippy::module_name_repetitions)] +#[derive(thiserror::Error, Debug, Clone)] +pub enum PeerKeyError { + /// Returned when the duration specified for the peer key exceeds the + /// maximum. + #[error("Invalid peer key duration: {seconds_valid:?}, is not valid")] + DurationOverflow { seconds_valid: u64 }, + + /// Returned when the provided peer key is invalid. + #[error("Invalid key: {key}")] + InvalidKey { + key: String, + source: LocatedError<'static, ParseKeyError>, + }, + + /// Returned when persisting the peer key to the database fails. + #[error("Can't persist key: {source}")] + DatabaseError { + source: LocatedError<'static, databases::error::Error>, + }, +} + +#[cfg(test)] +mod tests { + + mod whitelist_error { + + use crate::error::WhitelistError; + use crate::test_helpers::tests::sample_info_hash; + + #[test] + fn torrent_not_whitelisted() { + let err = WhitelistError::TorrentNotWhitelisted { + info_hash: sample_info_hash(), + location: std::panic::Location::caller(), + }; + + let err_msg = format!("{err}"); + + assert!( + err_msg.contains(&format!("The torrent: {}, is not whitelisted", sample_info_hash())), + "Error message did not contain expected text: {err_msg}" + ); + } + } + + mod peer_key_error { + use torrust_tracker_located_error::Located; + + use crate::databases::driver::Driver; + use crate::error::PeerKeyError; + use crate::{authentication, databases}; + + #[test] + fn duration_overflow() { + let seconds_valid = 100; + + let err = PeerKeyError::DurationOverflow { seconds_valid }; + + let err_msg = format!("{err}"); + + assert!( + err_msg.contains(&format!("Invalid peer key duration: {seconds_valid}")), + "Error message did not contain expected text: {err_msg}" + ); + } + + #[test] + fn parsing_from_string() { + let err = authentication::key::ParseKeyError::InvalidKeyLength; + + let err = PeerKeyError::InvalidKey { + key: "INVALID KEY".to_string(), + source: Located(err).into(), + }; + + let err_msg = format!("{err}"); + + assert!( + err_msg.contains(&"Invalid key: INVALID KEY".to_string()), + "Error message did not contain expected text: {err_msg}" + ); + } + + #[test] + fn persisting_into_database() { + let err = databases::error::Error::InsertFailed { + location: std::panic::Location::caller(), + driver: Driver::Sqlite3, + }; + + let err = PeerKeyError::DatabaseError { + source: Located(err).into(), + }; + + let err_msg = format!("{err}"); + + assert!( + err_msg.contains(&"Can't persist key".to_string()), + "Error message did not contain expected text: {err}" + ); + } + } +} diff --git a/packages/tracker-core/src/lib.rs b/packages/tracker-core/src/lib.rs new file mode 100644 index 000000000..5167abf51 --- /dev/null +++ b/packages/tracker-core/src/lib.rs @@ -0,0 +1,273 @@ +//! The core `bittorrent-tracker-core` crate contains the generic `BitTorrent` +//! tracker logic which is independent of the delivery layer. +//! +//! It contains the tracker services and their dependencies. It's a domain layer +//! which does not specify how the end user should connect to the `Tracker`. +//! +//! Typically this crate is intended to be used by higher components like: +//! +//! - A UDP tracker +//! - A HTTP tracker +//! - A tracker REST API +//! +//! ```text +//! Delivery layer | Domain layer +//! ----------------------------------- +//! HTTP tracker | +//! UDP tracker |-> Core tracker +//! Tracker REST API | +//! ``` +//! +//! # Table of contents +//! +//! - [Introduction](#introduction) +//! - [Configuration](#configuration) +//! - [Announce handler](#announce-handler) +//! - [Scrape handler](#scrape-handler) +//! - [Authentication](#authentication) +//! - [Databases](#databases) +//! - [Torrent](#torrent) +//! - [Whitelist](#whitelist) +//! +//! # Introduction +//! +//! The main purpose of this crate is to provide a generic `BitTorrent` tracker. +//! +//! It has two main responsibilities: +//! +//! - To handle **announce** requests. +//! - To handle **scrape** requests. +//! +//! The crate has also other features: +//! +//! - **Authentication**: It handles authentication keys which are used by HTTP trackers. +//! - **Persistence**: It handles persistence of data into a database. +//! - **Torrent**: It handles the torrent data. +//! - **Whitelist**: When the tracker runs in [`listed`](https://docs.rs/torrust-tracker-configuration/latest/torrust_tracker_configuration/type.Core.html) mode +//! all operations are restricted to whitelisted torrents. +//! +//! Refer to [torrust-tracker-configuration](https://docs.rs/torrust-tracker-configuration) +//! crate docs to get more information about the tracker settings. +//! +//! # Configuration +//! +//! You can control the behavior of this crate with the `Core` settings: +//! +//! ```toml +//! [logging] +//! threshold = "debug" +//! +//! [core] +//! inactive_peer_cleanup_interval = 600 +//! listed = false +//! private = false +//! tracker_usage_statistics = true +//! +//! [core.announce_policy] +//! interval = 120 +//! interval_min = 120 +//! +//! [core.database] +//! driver = "sqlite3" +//! path = "./storage/tracker/lib/database/sqlite3.db" +//! +//! [core.net] +//! on_reverse_proxy = false +//! external_ip = "2.137.87.41" +//! +//! [core.tracker_policy] +//! max_peer_timeout = 900 +//! persistent_torrent_completed_stat = false +//! remove_peerless_torrents = true +//! ``` +//! +//! Refer to the [`configuration` module documentation](https://docs.rs/torrust-tracker-configuration) to get more information about all options. +//! +//! # Announce handler +//! +//! The `AnnounceHandler` is responsible for handling announce requests. +//! +//! Please refer to the [`announce_handler`] documentation. +//! +//! # Scrape handler +//! +//! The `ScrapeHandler` is responsible for handling scrape requests. +//! +//! Please refer to the [`scrape_handler`] documentation. +//! +//! # Authentication +//! +//! The `Authentication` module is responsible for handling authentication keys which are used by HTTP trackers. +//! +//! Please refer to the [`authentication`] documentation. +//! +//! # Databases +//! +//! The `Databases` module is responsible for handling persistence of data into a database. +//! +//! Please refer to the [`databases`] documentation. +//! +//! # Torrent +//! +//! The `Torrent` module is responsible for handling the torrent data. +//! +//! Please refer to the [`torrent`] documentation. +//! +//! # Whitelist +//! +//! The `Whitelist` module is responsible for handling the whitelist. +//! +//! Please refer to the [`whitelist`] documentation. +pub mod announce_handler; +pub mod authentication; +pub mod container; +pub mod databases; +pub mod error; +pub mod scrape_handler; +pub mod statistics; +pub mod torrent; +pub mod whitelist; + +pub mod peer_tests; +pub mod test_helpers; + +use torrust_tracker_clock::clock; + +/// The maximum number of torrents that can be returned in an `scrape` response. +/// +/// The [BEP 15. UDP Tracker Protocol for `BitTorrent`](https://www.bittorrent.org/beps/bep_0015.html) +/// defines this limit: +/// +/// "Up to about 74 torrents can be scraped at once. A full scrape can't be done +/// with this protocol." +/// +/// The [BEP 48. Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) +/// does not specifically mention this limit, but the limit is being used for +/// both the UDP and HTTP trackers since it's applied at the domain level. +pub const MAX_SCRAPE_TORRENTS: u8 = 74; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; + +pub const TRACKER_CORE_LOG_TARGET: &str = "TRACKER_CORE"; + +#[cfg(test)] +mod tests { + mod the_tracker { + use std::sync::Arc; + + use torrust_tracker_test_helpers::configuration; + + use crate::announce_handler::AnnounceHandler; + use crate::scrape_handler::ScrapeHandler; + use crate::test_helpers::tests::initialize_handlers; + + fn initialize_handlers_for_public_tracker() -> (Arc, Arc) { + let config = configuration::ephemeral_public(); + initialize_handlers(&config) + } + + fn initialize_handlers_for_listed_tracker() -> (Arc, Arc) { + let config = configuration::ephemeral_listed(); + initialize_handlers(&config) + } + + mod for_all_config_modes { + + mod handling_a_scrape_request { + + use std::net::{IpAddr, Ipv4Addr}; + + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::core::ScrapeData; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + + use crate::announce_handler::PeersWanted; + use crate::test_helpers::tests::{complete_peer, incomplete_peer}; + use crate::tests::the_tracker::initialize_handlers_for_public_tracker; + + #[tokio::test] + async fn it_should_return_the_swarm_metadata_for_the_requested_file_if_the_tracker_has_that_torrent() { + let (announce_handler, scrape_handler) = initialize_handlers_for_public_tracker(); + + let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // DevSkim: ignore DS173237 + + // Announce a "complete" peer for the torrent + let mut complete_peer = complete_peer(); + announce_handler + .handle_announcement( + &info_hash, + &mut complete_peer, + &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 10)), + &PeersWanted::AsManyAsPossible, + ) + .await + .unwrap(); + + // Announce an "incomplete" peer for the torrent + let mut incomplete_peer = incomplete_peer(); + announce_handler + .handle_announcement( + &info_hash, + &mut incomplete_peer, + &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 11)), + &PeersWanted::AsManyAsPossible, + ) + .await + .unwrap(); + + // Scrape + let scrape_data = scrape_handler.handle_scrape(&vec![info_hash]).await.unwrap(); + + // The expected swarm metadata for the torrent + let mut expected_scrape_data = ScrapeData::empty(); + expected_scrape_data.add_file( + &info_hash, + SwarmMetadata { + complete: 1, // the "incomplete" announced + downloaded: 0, // the "complete" peer download does not count because it was not previously known + incomplete: 1, // the "incomplete" peer announced + }, + ); + + assert_eq!(scrape_data, expected_scrape_data); + } + } + } + + mod configured_as_whitelisted { + + mod handling_a_scrape_request { + + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::core::ScrapeData; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + + use crate::tests::the_tracker::initialize_handlers_for_listed_tracker; + + #[tokio::test] + async fn it_should_return_the_zeroed_swarm_metadata_for_the_requested_file_if_it_is_not_whitelisted() { + let (_announce_handler, scrape_handler) = initialize_handlers_for_listed_tracker(); + + let non_whitelisted_info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // DevSkim: ignore DS173237 + + let scrape_data = scrape_handler.handle_scrape(&vec![non_whitelisted_info_hash]).await.unwrap(); + + // The expected zeroed swarm metadata for the file + let mut expected_scrape_data = ScrapeData::empty(); + expected_scrape_data.add_file(&non_whitelisted_info_hash, SwarmMetadata::zeroed()); + + assert_eq!(scrape_data, expected_scrape_data); + } + } + } + } +} diff --git a/packages/tracker-core/src/peer_tests.rs b/packages/tracker-core/src/peer_tests.rs new file mode 100644 index 000000000..b60ca3f6d --- /dev/null +++ b/packages/tracker-core/src/peer_tests.rs @@ -0,0 +1,47 @@ +#![cfg(test)] + +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +use torrust_tracker_clock::clock::stopped::Stopped as _; +use torrust_tracker_clock::clock::{self, Time}; +use torrust_tracker_primitives::peer; + +use crate::CurrentClock; + +#[test] +fn it_should_be_serializable() { + clock::Stopped::local_set_to_unix_epoch(); + + let torrent_peer = peer::Peer { + peer_id: PeerId(*b"-qB0000-000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: CurrentClock::now(), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), + event: AnnounceEvent::Started, + }; + + let raw_json = serde_json::to_string(&torrent_peer).unwrap(); + + let expected_raw_json = r#" + { + "peer_id": { + "id": "0x2d7142303030302d303030303030303030303030", + "client": "qBittorrent" + }, + "peer_addr":"126.0.0.1:8080", + "updated":0, + "uploaded":0, + "downloaded":0, + "left":0, + "event":"Started" + } + "#; + + assert_eq!( + serde_json::from_str::(&raw_json).unwrap(), + serde_json::from_str::(expected_raw_json).unwrap() + ); +} diff --git a/packages/tracker-core/src/scrape_handler.rs b/packages/tracker-core/src/scrape_handler.rs new file mode 100644 index 000000000..9c94a4e50 --- /dev/null +++ b/packages/tracker-core/src/scrape_handler.rs @@ -0,0 +1,187 @@ +//! Scrape handler. +//! +//! The `scrape` request allows clients to query metadata about the swarm in bulk. +//! +//! An `scrape` request includes a list of infohashes whose swarm metadata you +//! want to collect. +//! +//! ## Scrape Response Format +//! +//! The returned struct is: +//! +//! ```rust,no_run +//! use bittorrent_primitives::info_hash::InfoHash; +//! use std::collections::HashMap; +//! +//! pub struct ScrapeData { +//! pub files: HashMap, +//! } +//! +//! pub struct SwarmMetadata { +//! pub complete: u32, // The number of active peers that have completed downloading (seeders) +//! pub downloaded: u32, // The number of peers that have ever completed downloading +//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers) +//! } +//! ``` +//! +//! ## Example JSON Response +//! +//! The JSON representation of a sample `scrape` response would be like the following: +//! +//! ```json +//! { +//! 'files': { +//! 'xxxxxxxxxxxxxxxxxxxx': {'complete': 11, 'downloaded': 13772, 'incomplete': 19}, +//! 'yyyyyyyyyyyyyyyyyyyy': {'complete': 21, 'downloaded': 206, 'incomplete': 20} +//! } +//! } +//! ``` +//! +//! `xxxxxxxxxxxxxxxxxxxx` and `yyyyyyyyyyyyyyyyyyyy` are 20-byte infohash arrays. +//! There are two data structures for infohashes: byte arrays and hex strings: +//! +//! ```rust,no_run +//! use bittorrent_primitives::info_hash::InfoHash; +//! use std::str::FromStr; +//! +//! let info_hash: InfoHash = [255u8; 20].into(); +//! +//! assert_eq!( +//! info_hash, +//! InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap() +//! ); +//! ``` +//! +//! ## References: +//! +//! Refer to `BitTorrent` BEPs and other sites for more information about the `scrape` request: +//! +//! - [BEP 48. Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) +//! - [BEP 15. UDP Tracker Protocol for `BitTorrent`. Scrape section](https://www.bittorrent.org/beps/bep_0015.html) +//! - [Vuze docs](https://wiki.vuze.com/w/Scrape) +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::core::ScrapeData; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + +use super::torrent::repository::in_memory::InMemoryTorrentRepository; +use super::whitelist; +use crate::error::ScrapeError; + +/// Handles scrape requests, providing torrent swarm metadata. +pub struct ScrapeHandler { + /// Service for authorizing access to whitelisted torrents. + whitelist_authorization: Arc, + + /// The in-memory torrents repository. + in_memory_torrent_repository: Arc, +} + +impl ScrapeHandler { + /// Creates a new `ScrapeHandler` instance. + #[must_use] + pub fn new( + whitelist_authorization: &Arc, + in_memory_torrent_repository: &Arc, + ) -> Self { + Self { + whitelist_authorization: whitelist_authorization.clone(), + in_memory_torrent_repository: in_memory_torrent_repository.clone(), + } + } + + /// Handles a scrape request for multiple torrents. + /// + /// - Returns metadata for each requested torrent. + /// - If a torrent isn't whitelisted or doesn't exist, returns zeroed stats. + /// + /// # Errors + /// + /// It does not return any errors for the time being. The error is returned + /// to avoid breaking changes in the future if we decide to return errors. + /// For example, a new tracker configuration option could be added to return + /// an error if a torrent is not whitelisted instead of returning zeroed + /// stats. + /// + /// # BEP Reference: + /// + /// [BEP 48: Scrape Protocol](https://www.bittorrent.org/beps/bep_0048.html) + pub async fn handle_scrape(&self, info_hashes: &Vec) -> Result { + let mut scrape_data = ScrapeData::empty(); + + for info_hash in info_hashes { + let swarm_metadata = match self.whitelist_authorization.authorize(info_hash).await { + Ok(()) => { + self.in_memory_torrent_repository + .get_swarm_metadata_or_default(info_hash) + .await + } + Err(_) => SwarmMetadata::zeroed(), + }; + scrape_data.add_file(info_hash, swarm_metadata); + } + + Ok(scrape_data) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::core::ScrapeData; + use torrust_tracker_test_helpers::configuration; + + use super::ScrapeHandler; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::whitelist::{self}; + + fn scrape_handler() -> ScrapeHandler { + let config = configuration::ephemeral_public(); + + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(whitelist::authorization::WhitelistAuthorization::new( + &config.core, + &in_memory_whitelist.clone(), + )); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository) + } + + #[tokio::test] + async fn it_should_return_a_zeroed_swarm_metadata_for_the_requested_file_if_the_tracker_does_not_have_that_torrent() { + let scrape_handler = scrape_handler(); + + let info_hashes = vec!["3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap()]; // DevSkim: ignore DS173237 + + let scrape_data = scrape_handler.handle_scrape(&info_hashes).await.unwrap(); + + let mut expected_scrape_data = ScrapeData::empty(); + + expected_scrape_data.add_file_with_zeroed_metadata(&info_hashes[0]); + + assert_eq!(scrape_data, expected_scrape_data); + } + + #[tokio::test] + async fn it_should_allow_scraping_for_multiple_torrents() { + let scrape_handler = scrape_handler(); + + let info_hashes = vec![ + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), // DevSkim: ignore DS173237 + "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1".parse::().unwrap(), // DevSkim: ignore DS173237 + ]; + + let scrape_data = scrape_handler.handle_scrape(&info_hashes).await.unwrap(); + + let mut expected_scrape_data = ScrapeData::empty(); + expected_scrape_data.add_file_with_zeroed_metadata(&info_hashes[0]); + expected_scrape_data.add_file_with_zeroed_metadata(&info_hashes[1]); + + assert_eq!(scrape_data, expected_scrape_data); + } +} diff --git a/packages/tracker-core/src/statistics/event/handler.rs b/packages/tracker-core/src/statistics/event/handler.rs new file mode 100644 index 000000000..9a5182f25 --- /dev/null +++ b/packages/tracker-core/src/statistics/event/handler.rs @@ -0,0 +1,77 @@ +use std::sync::Arc; + +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_primitives::DurationSinceUnixEpoch; +use torrust_tracker_swarm_coordination_registry::event::Event; + +use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; +use crate::statistics::repository::Repository; +use crate::statistics::TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL; + +pub async fn handle_event( + event: Event, + stats_repository: &Arc, + db_downloads_metric_repository: &Arc, + persistent_torrent_completed_stat: bool, + now: DurationSinceUnixEpoch, +) { + match event { + // Torrent events + Event::TorrentAdded { info_hash, .. } => { + tracing::debug!(info_hash = ?info_hash, "Torrent added",); + } + Event::TorrentRemoved { info_hash } => { + tracing::debug!(info_hash = ?info_hash, "Torrent removed",); + } + + // Peer events + Event::PeerAdded { info_hash, peer } => { + tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer added", ); + } + Event::PeerRemoved { info_hash, peer } => { + tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer removed", ); + } + Event::PeerUpdated { + info_hash, + old_peer, + new_peer, + } => { + tracing::debug!(info_hash = ?info_hash, old_peer = ?old_peer, new_peer = ?new_peer, "Peer updated"); + } + Event::PeerDownloadCompleted { info_hash, peer } => { + tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer download completed", ); + + // Increment the number of downloads for all the torrents in memory + let _unused = stats_repository + .increment_counter( + &metric_name!(TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL), + &LabelSet::default(), + now, + ) + .await; + + if persistent_torrent_completed_stat { + // Increment the number of downloads for the torrent in the database + match db_downloads_metric_repository.increase_downloads_for_torrent(&info_hash) { + Ok(()) => { + tracing::debug!(info_hash = ?info_hash, "Number of torrent downloads increased"); + } + Err(err) => { + tracing::error!(info_hash = ?info_hash, error = ?err, "Failed to increase number of downloads for the torrent"); + } + } + + // Increment the global number of downloads (for all torrents) in the database + match db_downloads_metric_repository.increase_global_downloads() { + Ok(()) => { + tracing::debug!("Global number of downloads increased"); + } + Err(err) => { + tracing::error!(error = ?err, "Failed to increase global number of downloads"); + } + } + } + } + } +} diff --git a/packages/tracker-core/src/statistics/event/listener.rs b/packages/tracker-core/src/statistics/event/listener.rs new file mode 100644 index 000000000..8d2d74c71 --- /dev/null +++ b/packages/tracker-core/src/statistics/event/listener.rs @@ -0,0 +1,80 @@ +use std::sync::Arc; + +use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_events::receiver::RecvError; +use torrust_tracker_swarm_coordination_registry::event::receiver::Receiver; + +use super::handler::handle_event; +use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; +use crate::statistics::repository::Repository; +use crate::{CurrentClock, TRACKER_CORE_LOG_TARGET}; + +#[must_use] +pub fn run_event_listener( + receiver: Receiver, + cancellation_token: CancellationToken, + repository: &Arc, + db_downloads_metric_repository: &Arc, + persistent_torrent_completed_stat: bool, +) -> JoinHandle<()> { + let stats_repository = repository.clone(); + let db_downloads_metric_repository: Arc = db_downloads_metric_repository.clone(); + + tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Starting tracker core event listener"); + + tokio::spawn(async move { + dispatch_events( + receiver, + cancellation_token, + stats_repository, + db_downloads_metric_repository, + persistent_torrent_completed_stat, + ) + .await; + + tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Tracker core listener finished"); + }) +} + +async fn dispatch_events( + mut receiver: Receiver, + cancellation_token: CancellationToken, + stats_repository: Arc, + db_downloads_metric_repository: Arc, + persistent_torrent_completed_stat: bool, +) { + loop { + tokio::select! { + biased; + + () = cancellation_token.cancelled() => { + tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Received cancellation request, shutting down tracker core event listener."); + break; + } + + result = receiver.recv() => { + match result { + Ok(event) => handle_event( + event, + &stats_repository, + &db_downloads_metric_repository, + persistent_torrent_completed_stat, + CurrentClock::now()).await, + Err(e) => { + match e { + RecvError::Closed => { + tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Tracker core event receiver closed"); + break; + } + RecvError::Lagged(n) => { + tracing::warn!(target: TRACKER_CORE_LOG_TARGET, "Tracker core event receiver lagged by {} events", n); + } + } + } + } + } + } + } +} diff --git a/packages/tracker-core/src/statistics/event/mod.rs b/packages/tracker-core/src/statistics/event/mod.rs new file mode 100644 index 000000000..dae683398 --- /dev/null +++ b/packages/tracker-core/src/statistics/event/mod.rs @@ -0,0 +1,2 @@ +pub mod handler; +pub mod listener; diff --git a/packages/tracker-core/src/statistics/metrics.rs b/packages/tracker-core/src/statistics/metrics.rs new file mode 100644 index 000000000..a5caaf1cf --- /dev/null +++ b/packages/tracker-core/src/statistics/metrics.rs @@ -0,0 +1,76 @@ +use serde::Serialize; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::{Error, MetricCollection}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +/// Metrics collected by the torrent repository. +#[derive(Debug, Clone, PartialEq, Default, Serialize)] +pub struct Metrics { + /// A collection of metrics. + pub metric_collection: MetricCollection, +} + +impl Metrics { + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn increment_counter( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.increment_counter(metric_name, labels, now) + } + + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn set_counter( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + value: u64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.set_counter(metric_name, labels, value, now) + } + + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn set_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.set_gauge(metric_name, labels, value, now) + } + + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn increment_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.increment_gauge(metric_name, labels, now) + } + + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn decrement_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.decrement_gauge(metric_name, labels, now) + } +} diff --git a/packages/tracker-core/src/statistics/mod.rs b/packages/tracker-core/src/statistics/mod.rs new file mode 100644 index 000000000..fdb8e8fd4 --- /dev/null +++ b/packages/tracker-core/src/statistics/mod.rs @@ -0,0 +1,28 @@ +pub mod event; +pub mod metrics; +pub mod persisted; +pub mod repository; + +use metrics::Metrics; +use torrust_tracker_metrics::metric::description::MetricDescription; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_metrics::unit::Unit; + +// Torrent metrics + +const TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL: &str = "tracker_core_persistent_torrents_downloads_total"; + +#[must_use] +pub fn describe_metrics() -> Metrics { + let mut metrics = Metrics::default(); + + // Torrent metrics + + metrics.metric_collection.describe_counter( + &metric_name!(TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("The total number of torrent downloads (persisted).")), + ); + + metrics +} diff --git a/packages/tracker-core/src/statistics/persisted/downloads.rs b/packages/tracker-core/src/statistics/persisted/downloads.rs new file mode 100644 index 000000000..6248bdc73 --- /dev/null +++ b/packages/tracker-core/src/statistics/persisted/downloads.rs @@ -0,0 +1,200 @@ +//! The repository that stored persistent torrents' data into the database. +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::{NumberOfDownloads, NumberOfDownloadsBTreeMap}; + +use crate::databases::error::Error; +use crate::databases::Database; + +/// It persists torrent metrics in a database. +/// +/// This repository persists only a subset of the torrent data: the torrent +/// metrics, specifically the number of downloads (or completed counts) for each +/// torrent. It relies on a database driver (either `SQLite3` or `MySQL`) that +/// implements the [`Database`] trait to perform the actual persistence +/// operations. +/// +/// # Note +/// +/// Not all in-memory torrent data is persisted; only the aggregate metrics are +/// stored. +pub struct DatabaseDownloadsMetricRepository { + /// A shared reference to the database driver implementation. + /// + /// The driver must implement the [`Database`] trait. This allows for + /// different underlying implementations (e.g., `SQLite3` or `MySQL`) to be + /// used interchangeably. + database: Arc>, +} + +impl DatabaseDownloadsMetricRepository { + /// Creates a new instance of `DatabasePersistentTorrentRepository`. + /// + /// # Arguments + /// + /// * `database` - A shared reference to a boxed database driver + /// implementing the [`Database`] trait. + /// + /// # Returns + /// + /// A new `DatabasePersistentTorrentRepository` instance with a cloned + /// reference to the provided database. + #[must_use] + pub fn new(database: &Arc>) -> DatabaseDownloadsMetricRepository { + Self { + database: database.clone(), + } + } + + // Single Torrent Metrics + + /// Increases the number of downloads for a given torrent. + /// + /// If the torrent is not found, it creates a new entry. + /// + /// # Arguments + /// + /// * `info_hash` - The info hash of the torrent. + /// + /// # Errors + /// + /// Returns an [`Error`] if the database operation fails. + pub(crate) fn increase_downloads_for_torrent(&self, info_hash: &InfoHash) -> Result<(), Error> { + let torrent = self.load_torrent_downloads(info_hash)?; + + match torrent { + Some(_number_of_downloads) => self.database.increase_downloads_for_torrent(info_hash), + None => self.save_torrent_downloads(info_hash, 1), + } + } + + /// Loads all persistent torrent metrics from the database. + /// + /// This function retrieves the torrent metrics (e.g., download counts) from the persistent store + /// and returns them as a [`PersistentTorrents`] map. + /// + /// # Errors + /// + /// Returns an [`Error`] if the underlying database query fails. + pub(crate) fn load_all_torrents_downloads(&self) -> Result { + self.database.load_all_torrents_downloads() + } + + /// Loads one persistent torrent metrics from the database. + /// + /// This function retrieves the torrent metrics (e.g., download counts) from the persistent store + /// and returns them as a [`PersistentTorrents`] map. + /// + /// # Errors + /// + /// Returns an [`Error`] if the underlying database query fails. + pub(crate) fn load_torrent_downloads(&self, info_hash: &InfoHash) -> Result, Error> { + self.database.load_torrent_downloads(info_hash) + } + + /// Saves the persistent torrent metric into the database. + /// + /// This function stores or updates the download count for the torrent + /// identified by the provided infohash. + /// + /// # Arguments + /// + /// * `info_hash` - The info hash of the torrent. + /// * `downloaded` - The number of times the torrent has been downloaded. + /// + /// # Errors + /// + /// Returns an [`Error`] if the database operation fails. + pub(crate) fn save_torrent_downloads(&self, info_hash: &InfoHash, downloaded: u32) -> Result<(), Error> { + self.database.save_torrent_downloads(info_hash, downloaded) + } + + // Aggregate Metrics + + /// Increases the global number of downloads for all torrent. + /// + /// If the metric is not found, it creates it. + /// + /// # Errors + /// + /// Returns an [`Error`] if the database operation fails. + pub(crate) fn increase_global_downloads(&self) -> Result<(), Error> { + let torrent = self.database.load_global_downloads()?; + + match torrent { + Some(_number_of_downloads) => self.database.increase_global_downloads(), + None => self.database.save_global_downloads(1), + } + } + + /// Loads the global number of downloads for all torrents from the database. + /// + /// # Errors + /// + /// Returns an [`Error`] if the underlying database query fails. + pub(crate) fn load_global_downloads(&self) -> Result, Error> { + self.database.load_global_downloads() + } +} + +#[cfg(test)] +mod tests { + + use torrust_tracker_primitives::NumberOfDownloadsBTreeMap; + + use super::DatabaseDownloadsMetricRepository; + use crate::databases::setup::initialize_database; + use crate::test_helpers::tests::{ephemeral_configuration, sample_info_hash, sample_info_hash_one, sample_info_hash_two}; + + fn initialize_db_persistent_torrent_repository() -> DatabaseDownloadsMetricRepository { + let config = ephemeral_configuration(); + let database = initialize_database(&config); + DatabaseDownloadsMetricRepository::new(&database) + } + + #[test] + fn it_saves_the_numbers_of_downloads_for_a_torrent_into_the_database() { + let repository = initialize_db_persistent_torrent_repository(); + + let infohash = sample_info_hash(); + + repository.save_torrent_downloads(&infohash, 1).unwrap(); + + let torrents = repository.load_all_torrents_downloads().unwrap(); + + assert_eq!(torrents.get(&infohash), Some(1).as_ref()); + } + + #[test] + fn it_increases_the_numbers_of_downloads_for_a_torrent_into_the_database() { + let repository = initialize_db_persistent_torrent_repository(); + + let infohash = sample_info_hash(); + + repository.increase_downloads_for_torrent(&infohash).unwrap(); + + let torrents = repository.load_all_torrents_downloads().unwrap(); + + assert_eq!(torrents.get(&infohash), Some(1).as_ref()); + } + + #[test] + fn it_loads_the_numbers_of_downloads_for_all_torrents_from_the_database() { + let repository = initialize_db_persistent_torrent_repository(); + + let infohash_one = sample_info_hash_one(); + let infohash_two = sample_info_hash_two(); + + repository.save_torrent_downloads(&infohash_one, 1).unwrap(); + repository.save_torrent_downloads(&infohash_two, 2).unwrap(); + + let torrents = repository.load_all_torrents_downloads().unwrap(); + + let mut expected_torrents = NumberOfDownloadsBTreeMap::new(); + expected_torrents.insert(infohash_one, 1); + expected_torrents.insert(infohash_two, 2); + + assert_eq!(torrents, expected_torrents); + } +} diff --git a/packages/tracker-core/src/statistics/persisted/mod.rs b/packages/tracker-core/src/statistics/persisted/mod.rs new file mode 100644 index 000000000..86c28370d --- /dev/null +++ b/packages/tracker-core/src/statistics/persisted/mod.rs @@ -0,0 +1,59 @@ +pub mod downloads; + +use std::sync::Arc; + +use thiserror::Error; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::{metric_collection, metric_name}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::repository::Repository; +use super::TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL; +use crate::databases; +use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; + +/// Loads persisted metrics from the database and sets them in the stats repository. +/// +/// # Errors +/// +/// This function will return an error if the database query fails or if the +/// metric collection fails to set the initial metric values. +pub async fn load_persisted_metrics( + stats_repository: &Arc, + db_downloads_metric_repository: &Arc, + now: DurationSinceUnixEpoch, +) -> Result<(), Error> { + if let Some(downloads) = db_downloads_metric_repository.load_global_downloads()? { + stats_repository + .set_counter( + &metric_name!(TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL), + &LabelSet::default(), + u64::from(downloads), + now, + ) + .await?; + } + + Ok(()) +} + +#[derive(Error, Debug, Clone)] +pub enum Error { + #[error("Database error: {err}")] + DatabaseError { err: databases::error::Error }, + + #[error("Metrics error: {err}")] + MetricsError { err: metric_collection::Error }, +} + +impl From for Error { + fn from(err: databases::error::Error) -> Self { + Self::DatabaseError { err } + } +} + +impl From for Error { + fn from(err: metric_collection::Error) -> Self { + Self::MetricsError { err } + } +} diff --git a/packages/tracker-core/src/statistics/repository.rs b/packages/tracker-core/src/statistics/repository.rs new file mode 100644 index 000000000..21b1da7f2 --- /dev/null +++ b/packages/tracker-core/src/statistics/repository.rs @@ -0,0 +1,176 @@ +use std::sync::Arc; + +use tokio::sync::{RwLock, RwLockReadGuard}; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::Error; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::metrics::Metrics; +use super::{describe_metrics, TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL}; + +/// A repository for the torrent repository metrics. +#[derive(Clone)] +pub struct Repository { + pub stats: Arc>, +} + +impl Default for Repository { + fn default() -> Self { + Self::new() + } +} + +impl Repository { + #[must_use] + pub fn new() -> Self { + let stats = Arc::new(RwLock::new(describe_metrics())); + + Self { stats } + } + + pub async fn get_metrics(&self) -> RwLockReadGuard<'_, Metrics> { + self.stats.read().await + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increment the counter. + pub async fn increment_counter( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.increment_counter(metric_name, labels, now); + + drop(stats_lock); + + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to increment the counter: {}", err), + } + + result + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increment the counter. + pub async fn set_counter( + &self, + metric_name: &MetricName, + labels: &LabelSet, + value: u64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.set_counter(metric_name, labels, value, now); + + drop(stats_lock); + + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to set the counter: {}", err), + } + + result + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// set the gauge. + pub async fn set_gauge( + &self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.set_gauge(metric_name, labels, value, now); + + drop(stats_lock); + + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to set the gauge: {}", err), + } + + result + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increment the gauge. + pub async fn increment_gauge( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.increment_gauge(metric_name, labels, now); + + drop(stats_lock); + + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to increment the gauge: {}", err), + } + + result + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// decrement the gauge. + pub async fn decrement_gauge( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.decrement_gauge(metric_name, labels, now); + + drop(stats_lock); + + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to decrement the gauge: {}", err), + } + + result + } + + /// Get the total number of torrent downloads. + /// + /// The value is persisted in database if persistence for downloads metrics is enabled. + pub async fn get_torrents_downloads_total(&self) -> u64 { + let metrics = self.get_metrics().await; + + let downloads = metrics.metric_collection.get_counter_value( + &metric_name!(TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL), + &LabelSet::default(), + ); + + if let Some(downloads) = downloads { + downloads.value() + } else { + 0 + } + } +} diff --git a/packages/tracker-core/src/test_helpers.rs b/packages/tracker-core/src/test_helpers.rs new file mode 100644 index 000000000..bf21e6f94 --- /dev/null +++ b/packages/tracker-core/src/test_helpers.rs @@ -0,0 +1,184 @@ +//! Some generic test helpers functions. + +#[cfg(test)] +pub(crate) mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use bittorrent_primitives::info_hash::InfoHash; + use rand::RngExt; + use torrust_tracker_configuration::Configuration; + #[cfg(test)] + use torrust_tracker_configuration::Core; + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + #[cfg(test)] + use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; + + use crate::announce_handler::AnnounceHandler; + use crate::databases::setup::initialize_database; + use crate::scrape_handler::ScrapeHandler; + use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::whitelist::{self}; + + /// Generates a random `InfoHash`. + #[must_use] + pub fn random_info_hash() -> InfoHash { + let mut rng = rand::rng(); + let mut random_bytes = [0u8; 20]; + rng.fill(&mut random_bytes); + + InfoHash::from_bytes(&random_bytes) + } + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash_one() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash_two() -> InfoHash { + "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } + + /// Sample peer whose state is not relevant for the tests. + #[must_use] + pub fn sample_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } + } + + #[must_use] + pub fn seeder() -> Peer { + complete_peer() + } + + #[must_use] + pub fn leecher() -> Peer { + incomplete_peer() + } + + #[must_use] + pub fn started_peer() -> Peer { + incomplete_peer() + } + + #[must_use] + pub fn completed_peer() -> Peer { + complete_peer() + } + + /// A peer that counts as `complete` is swarm metadata + /// IMPORTANT!: it only counts if the it has been announce at least once before + /// announcing the `AnnounceEvent::Completed` event. + #[must_use] + pub fn complete_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000001"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } + } + + /// A peer that counts as `incomplete` is swarm metadata + #[must_use] + pub fn incomplete_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000002"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(1000), // Still bytes to download + event: AnnounceEvent::Started, + } + } + + #[must_use] + pub fn initialize_handlers(config: &Configuration) -> (Arc, Arc) { + let database = initialize_database(&config.core); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(whitelist::authorization::WhitelistAuthorization::new( + &config.core, + &in_memory_whitelist.clone(), + )); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_downloads_metric_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + (announce_handler, scrape_handler) + } + + /// # Panics + /// + /// Will panic if the temporary database file path is not a valid UFT string. + #[cfg(test)] + #[must_use] + pub fn ephemeral_configuration() -> Core { + let mut config = Core::default(); + + let temp_file = ephemeral_sqlite_database(); + temp_file.to_str().unwrap().clone_into(&mut config.database.path); + + config + } + + /// # Panics + /// + /// Will panic if the temporary database file path is not a valid UFT string. + #[cfg(test)] + #[must_use] + pub fn ephemeral_configuration_for_listed_tracker() -> Core { + let mut config = Core { + listed: true, + ..Default::default() + }; + + let temp_file = ephemeral_sqlite_database(); + temp_file.to_str().unwrap().clone_into(&mut config.database.path); + + config + } +} diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs new file mode 100644 index 000000000..5acc27980 --- /dev/null +++ b/packages/tracker-core/src/torrent/manager.rs @@ -0,0 +1,302 @@ +//! Torrents manager. +use std::sync::Arc; +use std::time::Duration; + +use torrust_tracker_clock::clock::Time; +use torrust_tracker_configuration::Core; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::repository::in_memory::InMemoryTorrentRepository; +use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; +use crate::{databases, CurrentClock}; + +/// The `TorrentsManager` is responsible for managing torrent entries by +/// integrating persistent storage and in-memory state. It provides methods to +/// load torrent data from the database into memory, and to periodically clean +/// up stale torrent entries by removing inactive peers or entire torrent +/// entries that no longer have active peers. +/// +/// This manager relies on two repositories: +/// +/// - An **in-memory repository** to provide fast access to the current torrent +/// state. +/// - A **persistent repository** that stores aggregate torrent metrics (e.g., +/// seeders count) across tracker restarts. +pub struct TorrentsManager { + /// The tracker configuration. + config: Core, + + /// The in-memory torrents repository. + in_memory_torrent_repository: Arc, + + /// The download metrics repository. + db_downloads_metric_repository: Arc, +} + +impl TorrentsManager { + /// Creates a new instance of `TorrentsManager`. + /// + /// # Arguments + /// + /// * `config` - A reference to the tracker configuration. + /// * `in_memory_torrent_repository` - A shared reference to the in-memory + /// repository of torrents. + /// * `db_downloads_metric_repository` - A shared reference to the persistent + /// repository for torrent metrics. + /// + /// # Returns + /// + /// A new `TorrentsManager` instance with cloned references of the provided dependencies. + #[must_use] + pub fn new( + config: &Core, + in_memory_torrent_repository: &Arc, + db_downloads_metric_repository: &Arc, + ) -> Self { + Self { + config: config.clone(), + in_memory_torrent_repository: in_memory_torrent_repository.clone(), + db_downloads_metric_repository: db_downloads_metric_repository.clone(), + } + } + + /// Loads torrents from the database into the in-memory repository. + /// + /// This function retrieves the list of persistent torrent entries (which + /// include only the aggregate metrics, not the detailed peer lists) from + /// the database, and then imports that data into the in-memory repository. + /// + /// # Errors + /// + /// Returns a `databases::error::Error` if unable to load the persistent + /// torrent data. + pub fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { + let persistent_torrents = self.db_downloads_metric_repository.load_all_torrents_downloads()?; + + self.in_memory_torrent_repository.import_persistent(&persistent_torrents); + + Ok(()) + } + + /// Cleans up torrent entries by removing inactive peers and, optionally, + /// torrents with no active peers. + /// + /// This function performs two cleanup tasks: + /// + /// 1. It removes peers from torrent entries that have not been updated + /// within a cutoff time. The cutoff time is calculated as the current + /// time minus the maximum allowed peer timeout, as specified in the + /// tracker policy. + /// 2. If the tracker is configured to remove peerless torrents + /// (`remove_peerless_torrents` is set), it removes entire torrent + /// entries that have no active peers. + pub async fn cleanup_torrents(&self) { + self.log_aggregate_swarm_metadata().await; + + self.remove_inactive_peers().await; + + self.log_aggregate_swarm_metadata().await; + + self.remove_peerless_torrents().await; + + self.log_aggregate_swarm_metadata().await; + } + + async fn remove_inactive_peers(&self) { + self.in_memory_torrent_repository + .remove_inactive_peers(self.current_cutoff()) + .await; + } + + fn current_cutoff(&self) -> DurationSinceUnixEpoch { + CurrentClock::now_sub(&Duration::from_secs(u64::from(self.config.tracker_policy.max_peer_timeout))).unwrap_or_default() + } + + async fn remove_peerless_torrents(&self) { + if self.config.tracker_policy.remove_peerless_torrents { + self.in_memory_torrent_repository + .remove_peerless_torrents(&self.config.tracker_policy) + .await; + } + } + + async fn log_aggregate_swarm_metadata(&self) { + // Pre-calculated data + let aggregate_swarm_metadata = self.in_memory_torrent_repository.get_aggregate_swarm_metadata().await; + + tracing::info!(name: "pre_calculated_aggregate_swarm_metadata", + torrents = aggregate_swarm_metadata.total_torrents, + downloads = aggregate_swarm_metadata.total_downloaded, + seeders = aggregate_swarm_metadata.total_complete, + leechers = aggregate_swarm_metadata.total_incomplete, + ); + + // Hot data (iterating over data structures) + let peerless_torrents = self.in_memory_torrent_repository.count_peerless_torrents().await; + let peers = self.in_memory_torrent_repository.count_peers().await; + + tracing::info!(name: "hot_aggregate_swarm_metadata", + peerless_torrents = peerless_torrents, + peers = peers, + ); + } +} + +#[cfg(test)] +mod tests { + + use std::sync::Arc; + + use torrust_tracker_configuration::Core; + use torrust_tracker_swarm_coordination_registry::Registry; + + use super::{DatabaseDownloadsMetricRepository, TorrentsManager}; + use crate::databases::setup::initialize_database; + use crate::test_helpers::tests::{ephemeral_configuration, sample_info_hash}; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + + struct TorrentsManagerDeps { + config: Arc, + in_memory_torrent_repository: Arc, + database_persistent_torrent_repository: Arc, + } + + fn initialize_torrents_manager() -> (Arc, Arc) { + let config = ephemeral_configuration(); + initialize_torrents_manager_with(config.clone()) + } + + fn initialize_torrents_manager_with(config: Core) -> (Arc, Arc) { + let swarms = Arc::new(Registry::default()); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::new(swarms)); + let database = initialize_database(&config); + let database_persistent_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + + let torrents_manager = Arc::new(TorrentsManager::new( + &config, + &in_memory_torrent_repository, + &database_persistent_torrent_repository, + )); + + ( + torrents_manager, + Arc::new(TorrentsManagerDeps { + config: Arc::new(config), + in_memory_torrent_repository, + database_persistent_torrent_repository, + }), + ) + } + + #[tokio::test] + async fn it_should_load_the_numbers_of_downloads_for_all_torrents_from_the_database() { + let (torrents_manager, services) = initialize_torrents_manager(); + + let infohash = sample_info_hash(); + + services + .database_persistent_torrent_repository + .save_torrent_downloads(&infohash, 1) + .unwrap(); + + torrents_manager.load_torrents_from_database().unwrap(); + + assert_eq!( + services + .in_memory_torrent_repository + .get(&infohash) + .unwrap() + .lock() + .await + .metadata() + .downloaded, + 1 + ); + } + + mod cleaning_torrents { + use std::ops::Add; + use std::sync::Arc; + use std::time::Duration; + + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_clock::clock::stopped::Stopped; + use torrust_tracker_clock::clock::{self}; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::test_helpers::tests::{ephemeral_configuration, sample_info_hash, sample_peer}; + use crate::torrent::manager::tests::{initialize_torrents_manager, initialize_torrents_manager_with}; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + + #[tokio::test] + async fn it_should_remove_peers_that_have_not_been_updated_after_a_cutoff_time() { + let (torrents_manager, services) = initialize_torrents_manager(); + + let infohash = sample_info_hash(); + + clock::Stopped::local_set(&Duration::from_secs(0)); + + // Add a peer to the torrent + let mut peer = sample_peer(); + peer.updated = DurationSinceUnixEpoch::new(0, 0); + services + .in_memory_torrent_repository + .handle_announcement(&infohash, &peer, None) + .await; + + // Simulate the time has passed 1 second more than the max peer timeout. + clock::Stopped::local_add(&Duration::from_secs( + (services.config.tracker_policy.max_peer_timeout + 1).into(), + )) + .unwrap(); + + torrents_manager.cleanup_torrents().await; + + assert!(services.in_memory_torrent_repository.get(&infohash).is_none()); + } + + async fn add_a_peerless_torrent(infohash: &InfoHash, in_memory_torrent_repository: &Arc) { + // Add a peer to the torrent + let mut peer = sample_peer(); + peer.updated = DurationSinceUnixEpoch::new(0, 0); + in_memory_torrent_repository.handle_announcement(infohash, &peer, None).await; + + // Remove the peer. The torrent is now peerless. + in_memory_torrent_repository + .remove_inactive_peers(peer.updated.add(Duration::from_secs(1))) + .await; + } + + #[tokio::test] + async fn it_should_remove_torrents_that_have_no_peers_when_it_is_configured_to_do_so() { + let mut config = ephemeral_configuration(); + config.tracker_policy.remove_peerless_torrents = true; + + let (torrents_manager, services) = initialize_torrents_manager_with(config); + + let infohash = sample_info_hash(); + + add_a_peerless_torrent(&infohash, &services.in_memory_torrent_repository).await; + + torrents_manager.cleanup_torrents().await; + + assert!(services.in_memory_torrent_repository.get(&infohash).is_none()); + } + + #[tokio::test] + async fn it_should_retain_peerless_torrents_when_it_is_configured_to_do_so() { + let mut config = ephemeral_configuration(); + config.tracker_policy.remove_peerless_torrents = false; + + let (torrents_manager, services) = initialize_torrents_manager_with(config); + + let infohash = sample_info_hash(); + + add_a_peerless_torrent(&infohash, &services.in_memory_torrent_repository).await; + + torrents_manager.cleanup_torrents().await; + + assert!(services.in_memory_torrent_repository.get(&infohash).is_some()); + } + } +} diff --git a/packages/tracker-core/src/torrent/mod.rs b/packages/tracker-core/src/torrent/mod.rs new file mode 100644 index 000000000..01d33b893 --- /dev/null +++ b/packages/tracker-core/src/torrent/mod.rs @@ -0,0 +1,168 @@ +//! Swarm Data Structures. +//! +//! This module defines the primary data structures used to store and manage +//! swarm data within the tracker. In `BitTorrent` terminology, a "swarm" is +//! the collection of peers that are sharing or downloading a given torrent. +//! +//! There are two main types of data stored: +//! +//! - **Torrent Entry** (`Entry`): Contains all the information the tracker +//! stores for a single torrent, including the list of peers currently in the +//! swarm. This data is crucial for peers to locate each other and initiate +//! downloads. +//! +//! - **Swarm Metadata** (`SwarmMetadata`): Contains aggregate data derived from +//! all torrent entries. This metadata is split into: +//! - **Active Peers Data:** Metrics related to the peers that are currently +//! active in the swarm. +//! - **Historical Data:** Metrics collected since the tracker started, such +//! as the total number of completed downloads. +//! +//! ## Metrics Collected +//! +//! The tracker collects and aggregates the following metrics: +//! +//! - The total number of peers that have completed downloading the torrent +//! since the tracker began collecting metrics. +//! - The number of completed downloads from peers that remain active (i.e., seeders). +//! - The number of active peers that have not completed downloading the torrent (i.e., leechers). +//! +//! This information is used both to inform peers about available connections +//! and to provide overall swarm statistics. +//! +//! This module re-exports core types from the torrent repository crate to +//! simplify integration. +//! +//! ## Internal Data Structures +//! +//! The [`torrent`](crate::torrent) module contains all the data structures +//! stored by the tracker except for peers. +//! +//! We can represent the data stored in memory internally by the tracker with +//! this JSON object: +//! +//! ```json +//! { +//! "c1277613db1d28709b034a017ab2cae4be07ae10": { +//! "completed": 0, +//! "peers": { +//! "-qB00000000000000001": { +//! "peer_id": "-qB00000000000000001", +//! "peer_addr": "2.137.87.41:1754", +//! "updated": 1672419840, +//! "uploaded": 120, +//! "downloaded": 60, +//! "left": 60, +//! "event": "started" +//! }, +//! "-qB00000000000000002": { +//! "peer_id": "-qB00000000000000002", +//! "peer_addr": "23.17.287.141:2345", +//! "updated": 1679415984, +//! "uploaded": 80, +//! "downloaded": 20, +//! "left": 40, +//! "event": "started" +//! } +//! } +//! } +//! } +//! ``` +//! +//! The tracker maintains an indexed-by-info-hash list of torrents. For each +//! torrent, it stores a torrent `Entry`. The torrent entry has two attributes: +//! +//! - `completed`: which is hte number of peers that have completed downloading +//! the torrent file/s. As they have completed downloading, they have a full +//! version of the torrent data, and they can provide the full data to other +//! peers. That's why they are also known as "seeders". +//! - `peers`: an indexed and orderer list of peer for the torrent. Each peer +//! contains the data received from the peer in the `announce` request. +//! +//! The [`crate::torrent`] module not only contains the original data obtained +//! from peer via `announce` requests, it also contains aggregate data that can +//! be derived from the original data. For example: +//! +//! ```rust,no_run +//! pub struct SwarmMetadata { +//! pub complete: u32, // The number of active peers that have completed downloading (seeders) +//! pub downloaded: u32, // The number of peers that have ever completed downloading +//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers) +//! } +//! ``` +//! +//! > **NOTICE**: that `complete` or `completed` peers are the peers that have +//! > completed downloading, but only the active ones are considered "seeders". +//! +//! `SwarmMetadata` struct follows name conventions for `scrape` responses. See +//! [BEP 48](https://www.bittorrent.org/beps/bep_0048.html), while `SwarmMetadata` +//! is used for the rest of cases. +//! +//! ## Peers +//! +//! A `Peer` is the struct used by the tracker to keep peers data: +//! +//! ```rust,no_run +//! use std::net::SocketAddr; +//! use aquatic_udp_protocol::PeerId; +//! use torrust_tracker_primitives::DurationSinceUnixEpoch; +//! use aquatic_udp_protocol::NumberOfBytes; +//! use aquatic_udp_protocol::AnnounceEvent; +//! +//! pub struct Peer { +//! pub peer_id: PeerId, // The peer ID +//! pub peer_addr: SocketAddr, // Peer socket address +//! pub updated: DurationSinceUnixEpoch, // Last time (timestamp) when the peer was updated +//! pub uploaded: NumberOfBytes, // Number of bytes the peer has uploaded so far +//! pub downloaded: NumberOfBytes, // Number of bytes the peer has downloaded so far +//! pub left: NumberOfBytes, // The number of bytes this peer still has to download +//! pub event: AnnounceEvent, // The event the peer has announced: `started`, `completed`, `stopped` +//! } +//! ``` +//! +//! Notice that most of the attributes are obtained from the `announce` request. +//! For example, an HTTP announce request would contain the following `GET` parameters: +//! +//! +//! +//! The `Tracker` keeps an in-memory ordered data structure with all the torrents and a list of peers for each torrent, together with some swarm metrics. +//! +//! We can represent the data stored in memory with this JSON object: +//! +//! ```json +//! { +//! "c1277613db1d28709b034a017ab2cae4be07ae10": { +//! "completed": 0, +//! "peers": { +//! "-qB00000000000000001": { +//! "peer_id": "-qB00000000000000001", +//! "peer_addr": "2.137.87.41:1754", +//! "updated": 1672419840, +//! "uploaded": 120, +//! "downloaded": 60, +//! "left": 60, +//! "event": "started" +//! }, +//! "-qB00000000000000002": { +//! "peer_id": "-qB00000000000000002", +//! "peer_addr": "23.17.287.141:2345", +//! "updated": 1679415984, +//! "uploaded": 80, +//! "downloaded": 20, +//! "left": 40, +//! "event": "started" +//! } +//! } +//! } +//! } +//! ``` +//! +//! That JSON object does not exist, it's only a representation of the `Tracker` torrents data. +//! +//! `c1277613db1d28709b034a017ab2cae4be07ae10` is the torrent infohash and `completed` contains the number of peers +//! that have a full version of the torrent data, also known as seeders. +//! +//! Refer to [`peer`](torrust_tracker_primitives::peer) for more information about peers. +pub mod manager; +pub mod repository; +pub mod services; diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs new file mode 100644 index 000000000..e50a82933 --- /dev/null +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -0,0 +1,276 @@ +//! In-memory torrents repository. +use std::cmp::max; +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; +use torrust_tracker_swarm_coordination_registry::{CoordinatorHandle, Registry}; + +/// In-memory repository for torrent entries. +/// +/// This repository manages the torrent entries and their associated peer lists +/// in memory. It is built on top of a high-performance data structure (the +/// production implementation) and provides methods to update, query, and remove +/// torrent entries as well as to import persisted data. +/// +/// Multiple implementations were considered, and the chosen implementation is +/// used in production. Other implementations are kept for reference. +#[derive(Default)] +pub struct InMemoryTorrentRepository { + /// The underlying in-memory data structure that stores swarms data. + swarms: Arc, +} + +impl InMemoryTorrentRepository { + #[must_use] + pub fn new(swarms: Arc) -> Self { + Self { swarms } + } + + /// Inserts or updates a peer in the torrent entry corresponding to the + /// given infohash. + /// + /// If the torrent entry already exists, the peer is added to its peer list; + /// otherwise, a new torrent entry is created. + /// + /// # Arguments + /// + /// * `info_hash` - The unique identifier of the torrent. + /// * `peer` - The peer to insert or update in the torrent entry. + /// + /// # Returns + /// + /// `true` if the peer stats were updated. + /// + /// # Panics + /// + /// This function panics if the underling swarms return an error. + pub async fn handle_announcement( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + opt_persistent_torrent: Option, + ) { + self.swarms + .handle_announcement(info_hash, peer, opt_persistent_torrent) + .await + .expect("Failed to upsert the peer in swarms"); + } + + /// Removes inactive peers from all torrent entries. + /// + /// A peer is considered inactive if its last update timestamp is older than + /// the provided cutoff time. + /// + /// # Arguments + /// + /// * `current_cutoff` - The cutoff timestamp; peers not updated since this + /// time will be removed. + /// + /// # Panics + /// + /// This function panics if the underling swarms return an error. + pub(crate) async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + self.swarms + .remove_inactive_peers(current_cutoff) + .await + .expect("Failed to remove inactive peers from swarms"); + } + + /// Removes torrent entries that have no active peers. + /// + /// Depending on the tracker policy, torrents without any peers may be + /// removed to conserve memory. + /// + /// # Arguments + /// + /// * `policy` - The tracker policy containing the configuration for + /// removing peerless torrents. + /// + /// # Panics + /// + /// This function panics if the underling swarms return an error. + pub(crate) async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + self.swarms + .remove_peerless_torrents(policy) + .await + .expect("Failed to remove peerless torrents from swarms"); + } + + /// Retrieves a torrent entry by its infohash. + /// + /// # Arguments + /// + /// * `key` - The info hash of the torrent. + /// + /// # Returns + /// + /// An `Option` containing the torrent entry if found. + #[must_use] + pub(crate) fn get(&self, key: &InfoHash) -> Option { + self.swarms.get(key) + } + + /// Retrieves a paginated list of torrent entries. + /// + /// This method returns a vector of tuples, each containing an infohash and + /// its associated torrent entry. The pagination parameters (offset and limit) + /// can be used to control the size of the result set. + /// + /// # Arguments + /// + /// * `pagination` - An optional reference to a `Pagination` object. + /// + /// # Returns + /// + /// A vector of `(InfoHash, TorrentEntry)` tuples. + #[must_use] + pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, CoordinatorHandle)> { + self.swarms.get_paginated(pagination) + } + + /// Retrieves swarm metadata for a given torrent. + /// + /// This method returns the swarm metadata (aggregate information such as + /// peer counts) for the torrent specified by the infohash. If the torrent + /// entry is not found, a zeroed metadata struct is returned. + /// + /// # Arguments + /// + /// * `info_hash` - The info hash of the torrent. + /// + /// # Returns + /// + /// A `SwarmMetadata` struct containing the aggregated torrent data. + /// + /// # Panics + /// + /// This function panics if the underling swarms return an error.s + #[must_use] + pub(crate) async fn get_swarm_metadata_or_default(&self, info_hash: &InfoHash) -> SwarmMetadata { + self.swarms + .get_swarm_metadata_or_default(info_hash) + .await + .expect("Failed to get swarm metadata") + } + + /// Retrieves torrent peers for a given torrent and client, excluding the + /// requesting client. + /// + /// This method filters out the client making the request (based on its + /// network address) and returns up to a maximum number of peers, defined by + /// the greater of the provided limit or the global `TORRENT_PEERS_LIMIT`. + /// + /// # Arguments + /// + /// * `info_hash` - The info hash of the torrent. + /// * `peer` - The client peer that should be excluded from the returned list. + /// * `limit` - The maximum number of peers to return. + /// + /// # Returns + /// + /// A vector of peers (wrapped in `Arc`) representing the active peers for + /// the torrent, excluding the requesting client. + /// + /// # Panics + /// + /// This function panics if the underling swarms return an error. + #[must_use] + pub(crate) async fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { + self.swarms + .get_peers_peers_excluding(info_hash, peer, max(limit, TORRENT_PEERS_LIMIT)) + .await + .expect("Failed to get other peers in swarm") + } + + /// Retrieves the list of peers for a given torrent. + /// + /// This method returns up to `TORRENT_PEERS_LIMIT` peers for the torrent + /// specified by the info-hash. + /// + /// # Arguments + /// + /// * `info_hash` - The info hash of the torrent. + /// + /// # Returns + /// + /// A vector of peers (wrapped in `Arc`) representing the active peers for + /// the torrent. + /// + /// # Panics + /// + /// This function panics if the underling swarms return an error. + #[must_use] + pub async fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { + // todo: pass the limit as an argument like `get_peers_for` + self.swarms + .get_swarm_peers(info_hash, TORRENT_PEERS_LIMIT) + .await + .expect("Failed to get other peers in swarm") + } + + /// Calculates and returns overall torrent metrics. + /// + /// The returned [`AggregateSwarmMetadata`] contains aggregate data such as + /// the total number of torrents, total complete (seeders), incomplete + /// (leechers), and downloaded counts. + /// + /// # Returns + /// + /// A [`AggregateSwarmMetadata`] struct with the aggregated metrics. + /// + /// # Panics + /// + /// This function panics if the underling swarms return an error. + #[must_use] + pub async fn get_aggregate_swarm_metadata(&self) -> AggregateActiveSwarmMetadata { + self.swarms + .get_aggregate_swarm_metadata() + .await + .expect("Failed to get aggregate swarm metadata") + } + + /// Counts the number of peerless torrents in the repository. + /// + /// # Panics + /// + /// This function panics if the underling swarms return an error. + #[must_use] + pub async fn count_peerless_torrents(&self) -> usize { + self.swarms + .count_peerless_torrents() + .await + .expect("Failed to count peerless torrents") + } + + /// Counts the number of peers in the repository. + /// + /// # Panics + /// + /// This function panics if the underling swarms return an error. + #[must_use] + pub async fn count_peers(&self) -> usize { + self.swarms.count_peers().await.expect("Failed to count peers") + } + + /// Imports persistent torrent data into the in-memory repository. + /// + /// This method takes a set of persisted torrent entries (e.g., from a database) + /// and imports them into the in-memory repository for immediate access. + /// + /// # Arguments + /// + /// * `persistent_torrents` - A reference to the persisted torrent data. + pub fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { + self.swarms.import_persistent(persistent_torrents); + } + + /// Checks if the repository contains a torrent entry for the given infohash. + #[must_use] + pub fn contains(&self, info_hash: &InfoHash) -> bool { + self.swarms.contains(info_hash) + } +} diff --git a/packages/tracker-core/src/torrent/repository/mod.rs b/packages/tracker-core/src/torrent/repository/mod.rs new file mode 100644 index 000000000..d8325dec5 --- /dev/null +++ b/packages/tracker-core/src/torrent/repository/mod.rs @@ -0,0 +1,2 @@ +//! Torrent repository implementations. +pub mod in_memory; diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs new file mode 100644 index 000000000..874ad1349 --- /dev/null +++ b/packages/tracker-core/src/torrent/services.rs @@ -0,0 +1,455 @@ +//! Core tracker domain services. +//! +//! This module defines the primary services for retrieving torrent-related data +//! from the tracker. There are two main services: +//! +//! - [`get_torrent_info`]: Returns all available data (including the list of +//! peers) about a single torrent. +//! - [`get_torrents_page`] and [`get_torrents`]: Return summarized data about +//! multiple torrents, excluding the peer list. +//! +//! The full torrent info is represented by the [`Info`] struct, which includes +//! swarm data (peer list) and aggregate metrics. The [`BasicInfo`] struct +//! provides similar data but without the list of peers, making it suitable for +//! bulk queries. +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::peer; + +use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + +/// Full torrent information, including swarm (peer) details. +/// +/// This struct contains all the information that the tracker holds about a +/// torrent, including the infohash, aggregate swarm metrics (seeders, leechers, +/// completed downloads), and the complete list of peers in the swarm. +#[derive(Debug, PartialEq)] +pub struct Info { + /// The infohash of the torrent this data is related to + pub info_hash: InfoHash, + + /// The total number of seeders for this torrent. Peer that actively serving + /// a full copy of the torrent data + pub seeders: u64, + + /// The total number of peers that have ever complete downloading this + /// torrent + pub completed: u64, + + /// The total number of leechers for this torrent. Peers that actively + /// downloading this torrent + pub leechers: u64, + + /// The swarm: the list of peers that are actively trying to download or + /// serving this torrent + pub peers: Option>, +} + +/// Basic torrent information, excluding the list of peers. +/// +/// This struct contains the same aggregate metrics as [`Info`] (infohash, +/// seeders, completed, leechers) but omits the peer list. It is used when only +/// summary information is needed. +#[derive(Debug, PartialEq, Clone)] +pub struct BasicInfo { + /// The infohash of the torrent this data is related to + pub info_hash: InfoHash, + + /// The total number of seeders for this torrent. Peer that actively serving + /// a full copy of the torrent data + pub seeders: u64, + + /// The total number of peers that have ever complete downloading this + /// torrent + pub completed: u64, + + /// The total number of leechers for this torrent. Peers that actively + /// downloading this torrent + pub leechers: u64, +} + +/// Retrieves complete torrent information for a given torrent. +/// +/// This function queries the in-memory torrent repository for a torrent entry +/// matching the provided infohash. If found, it extracts the swarm metadata +/// (aggregate metrics) and the current list of peers, and returns an [`Info`] +/// struct. +/// +/// # Arguments +/// +/// * `in_memory_torrent_repository` - A shared reference to the in-memory +/// torrent repository. +/// * `info_hash` - A reference to the torrent's infohash. +/// +/// # Returns +/// +/// An [`Option`] which is: +/// - `Some(Info)` if the torrent exists in the repository. +/// - `None` if the torrent is not found. +/// +/// # Panics +/// +/// This function panics if the lock for the torrent entry cannot be obtained. +#[must_use] +pub async fn get_torrent_info( + in_memory_torrent_repository: &Arc, + info_hash: &InfoHash, +) -> Option { + let torrent_entry_option = in_memory_torrent_repository.get(info_hash); + + let torrent_entry = torrent_entry_option?; + + let stats = torrent_entry.lock().await.metadata(); + + let peers = torrent_entry.lock().await.peers(None); + + let peers = Some(peers.iter().map(|peer| **peer).collect()); + + Some(Info { + info_hash: *info_hash, + seeders: u64::from(stats.complete), + completed: u64::from(stats.downloaded), + leechers: u64::from(stats.incomplete), + peers, + }) +} + +/// Retrieves summarized torrent information for a paginated set of torrents. +/// +/// This function returns a vector of [`BasicInfo`] structures for torrents in +/// the repository, according to the provided pagination parameters. The +/// returned data excludes the peer list, providing only aggregate metrics. +/// +/// # Arguments +/// +/// * `in_memory_torrent_repository` - A shared reference to the in-memory +/// torrent repository. +/// * `pagination` - An optional reference to a [`Pagination`] object specifying +/// offset and limit. +/// +/// # Returns +/// +/// A vector of [`BasicInfo`] structs representing the summarized data of the +/// torrents. +/// +/// # Panics +/// +/// This function panics if the lock for the torrent entry cannot be obtained. +#[must_use] +pub async fn get_torrents_page( + in_memory_torrent_repository: &Arc, + pagination: Option<&Pagination>, +) -> Vec { + let mut basic_infos: Vec = vec![]; + + for (info_hash, torrent_entry) in in_memory_torrent_repository.get_paginated(pagination) { + let stats = torrent_entry.lock().await.metadata(); + + basic_infos.push(BasicInfo { + info_hash, + seeders: u64::from(stats.complete), + completed: u64::from(stats.downloaded), + leechers: u64::from(stats.incomplete), + }); + } + + basic_infos +} + +/// Retrieves summarized torrent information for a specified list of torrents. +/// +/// This function iterates over a slice of infohashes, fetches the corresponding +/// swarm metadata from the in-memory repository (if available), and returns a +/// vector of [`BasicInfo`] structs. This function is useful for bulk queries +/// where detailed peer information is not required. +/// +/// # Arguments +/// +/// * `in_memory_torrent_repository` - A shared reference to the in-memory +/// torrent repository. +/// * `info_hashes` - A slice of infohashes for which to retrieve the torrent +/// information. +/// +/// # Returns +/// +/// A vector of [`BasicInfo`] structs for the requested torrents. +/// +/// # Panics +/// +/// This function panics if the lock for the torrent entry cannot be obtained. +#[must_use] +pub async fn get_torrents( + in_memory_torrent_repository: &Arc, + info_hashes: &[InfoHash], +) -> Vec { + let mut basic_infos: Vec = vec![]; + + for info_hash in info_hashes { + if let Some(torrent_entry) = in_memory_torrent_repository.get(info_hash) { + let metadata = torrent_entry.lock().await.metadata(); + + basic_infos.push(BasicInfo { + info_hash: *info_hash, + seeders: u64::from(metadata.complete), + completed: u64::from(metadata.downloaded), + leechers: u64::from(metadata.incomplete), + }); + } + } + + basic_infos +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + + fn sample_peer() -> peer::Peer { + peer::Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), + event: AnnounceEvent::Started, + } + } + + mod getting_a_torrent_info { + + use std::str::FromStr; + use std::sync::Arc; + + use bittorrent_primitives::info_hash::InfoHash; + + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::torrent::services::tests::sample_peer; + use crate::torrent::services::{get_torrent_info, Info}; + + #[tokio::test] + async fn it_should_return_none_if_the_tracker_does_not_have_the_torrent() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let torrent_info = get_torrent_info( + &in_memory_torrent_repository, + &InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(), // DevSkim: ignore DS173237 + ) + .await; + + assert!(torrent_info.is_none()); + } + + #[tokio::test] + async fn it_should_return_the_torrent_info_if_the_tracker_has_the_torrent() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 + let info_hash = InfoHash::from_str(&hash).unwrap(); + in_memory_torrent_repository + .handle_announcement(&info_hash, &sample_peer(), None) + .await; + + let torrent_info = get_torrent_info(&in_memory_torrent_repository, &info_hash).await.unwrap(); + + assert_eq!( + torrent_info, + Info { + info_hash: InfoHash::from_str(&hash).unwrap(), + seeders: 1, + completed: 0, + leechers: 0, + peers: Some(vec![sample_peer()]), + } + ); + } + } + + mod searching_for_torrents { + + use std::str::FromStr; + use std::sync::Arc; + + use bittorrent_primitives::info_hash::InfoHash; + + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::torrent::services::tests::sample_peer; + use crate::torrent::services::{get_torrents_page, BasicInfo, Pagination}; + + #[tokio::test] + async fn it_should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())).await; + + assert_eq!(torrents, vec![]); + } + + #[tokio::test] + async fn it_should_return_a_summarized_info_for_all_torrents() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 + let info_hash = InfoHash::from_str(&hash).unwrap(); + + in_memory_torrent_repository + .handle_announcement(&info_hash, &sample_peer(), None) + .await; + + let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())).await; + + assert_eq!( + torrents, + vec![BasicInfo { + info_hash: InfoHash::from_str(&hash).unwrap(), + seeders: 1, + completed: 0, + leechers: 0, + }] + ); + } + + #[tokio::test] + async fn it_should_allow_limiting_the_number_of_torrents_in_the_result() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 + let info_hash1 = InfoHash::from_str(&hash1).unwrap(); + + let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 + let info_hash2 = InfoHash::from_str(&hash2).unwrap(); + + in_memory_torrent_repository + .handle_announcement(&info_hash1, &sample_peer(), None) + .await; + in_memory_torrent_repository + .handle_announcement(&info_hash2, &sample_peer(), None) + .await; + + let offset = 0; + let limit = 1; + + let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::new(offset, limit))).await; + + assert_eq!(torrents.len(), 1); + } + + #[tokio::test] + async fn it_should_allow_using_pagination_in_the_result() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 + let info_hash1 = InfoHash::from_str(&hash1).unwrap(); + + let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 + let info_hash2 = InfoHash::from_str(&hash2).unwrap(); + + in_memory_torrent_repository + .handle_announcement(&info_hash1, &sample_peer(), None) + .await; + in_memory_torrent_repository + .handle_announcement(&info_hash2, &sample_peer(), None) + .await; + + let offset = 1; + let limit = 4000; + + let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::new(offset, limit))).await; + + assert_eq!(torrents.len(), 1); + assert_eq!( + torrents, + vec![BasicInfo { + info_hash: InfoHash::from_str(&hash1).unwrap(), + seeders: 1, + completed: 0, + leechers: 0, + }] + ); + } + + #[tokio::test] + async fn it_should_return_torrents_ordered_by_info_hash() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 + let info_hash1 = InfoHash::from_str(&hash1).unwrap(); + in_memory_torrent_repository + .handle_announcement(&info_hash1, &sample_peer(), None) + .await; + + let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 + let info_hash2 = InfoHash::from_str(&hash2).unwrap(); + in_memory_torrent_repository + .handle_announcement(&info_hash2, &sample_peer(), None) + .await; + + let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())).await; + + assert_eq!( + torrents, + vec![ + BasicInfo { + info_hash: InfoHash::from_str(&hash2).unwrap(), + seeders: 1, + completed: 0, + leechers: 0, + }, + BasicInfo { + info_hash: InfoHash::from_str(&hash1).unwrap(), + seeders: 1, + completed: 0, + leechers: 0, + } + ] + ); + } + } + + mod getting_basic_torrent_info_for_multiple_torrents_at_once { + + use std::sync::Arc; + + use crate::test_helpers::tests::sample_info_hash; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::torrent::services::tests::sample_peer; + use crate::torrent::services::{get_torrents, BasicInfo}; + + #[tokio::test] + async fn it_should_return_an_empty_list_if_none_of_the_requested_torrents_is_found() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let torrent_info = get_torrents(&in_memory_torrent_repository, &[sample_info_hash()]).await; + + assert!(torrent_info.is_empty()); + } + + #[tokio::test] + async fn it_should_return_a_list_with_basic_info_about_the_requested_torrents() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let info_hash = sample_info_hash(); + + in_memory_torrent_repository + .handle_announcement(&info_hash, &sample_peer(), None) + .await; + + let torrent_info = get_torrents(&in_memory_torrent_repository, &[info_hash]).await; + + assert_eq!( + torrent_info, + vec!(BasicInfo { + info_hash, + seeders: 1, + completed: 0, + leechers: 0, + }) + ); + } + } +} diff --git a/packages/tracker-core/src/whitelist/authorization.rs b/packages/tracker-core/src/whitelist/authorization.rs new file mode 100644 index 000000000..a8323457b --- /dev/null +++ b/packages/tracker-core/src/whitelist/authorization.rs @@ -0,0 +1,183 @@ +//! Whitelist authorization. +use std::panic::Location; +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::Core; +use tracing::instrument; + +use super::repository::in_memory::InMemoryWhitelist; +use crate::error::WhitelistError; + +/// Manages the authorization of torrents based on the whitelist. +/// +/// Used to determine whether a given torrent (`infohash`) is allowed +/// to be announced or scraped from the tracker. +pub struct WhitelistAuthorization { + /// Core tracker configuration. + config: Core, + + /// The in-memory list of allowed torrents. + in_memory_whitelist: Arc, +} + +impl WhitelistAuthorization { + /// Creates a new `WhitelistAuthorization` instance. + /// + /// # Arguments + /// - `config`: Tracker configuration. + /// - `in_memory_whitelist`: The in-memory whitelist instance. + /// + /// # Returns + /// A new `WhitelistAuthorization` instance. + pub fn new(config: &Core, in_memory_whitelist: &Arc) -> Self { + Self { + config: config.clone(), + in_memory_whitelist: in_memory_whitelist.clone(), + } + } + + /// Checks whether a torrent is authorized. + /// + /// - If the tracker is **public**, all torrents are authorized. + /// - If the tracker is **private** (listed mode), only whitelisted torrents + /// are authorized. + /// + /// # Errors + /// Returns `WhitelistError::TorrentNotWhitelisted` if the tracker is in `listed` mode + /// and the `info_hash` is not in the whitelist. + #[instrument(skip(self, info_hash), err)] + pub async fn authorize(&self, info_hash: &InfoHash) -> Result<(), WhitelistError> { + if !self.is_listed() { + return Ok(()); + } + + if self.is_info_hash_whitelisted(info_hash).await { + return Ok(()); + } + + Err(WhitelistError::TorrentNotWhitelisted { + info_hash: *info_hash, + location: Location::caller(), + }) + } + + /// Checks if the tracker is running in "listed" mode. + fn is_listed(&self) -> bool { + self.config.listed + } + + /// Checks if a torrent is present in the whitelist. + async fn is_info_hash_whitelisted(&self, info_hash: &InfoHash) -> bool { + self.in_memory_whitelist.contains(info_hash).await + } +} + +#[cfg(test)] +mod tests { + + mod the_whitelist_authorization_for_announce_and_scrape_actions { + use std::sync::Arc; + + use torrust_tracker_configuration::Core; + + use crate::whitelist::authorization::WhitelistAuthorization; + use crate::whitelist::repository::in_memory::InMemoryWhitelist; + + fn initialize_whitelist_authorization_with(config: &Core) -> Arc { + let (whitelist_authorization, _in_memory_whitelist) = + initialize_whitelist_authorization_and_dependencies_with(config); + whitelist_authorization + } + + fn initialize_whitelist_authorization_and_dependencies_with( + config: &Core, + ) -> (Arc, Arc) { + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(config, &in_memory_whitelist.clone())); + + (whitelist_authorization, in_memory_whitelist) + } + + mod when_the_tacker_is_configured_as_listed { + + use torrust_tracker_configuration::Core; + + use crate::error::WhitelistError; + use crate::test_helpers::tests::sample_info_hash; + use crate::whitelist::authorization::tests::the_whitelist_authorization_for_announce_and_scrape_actions::{ + initialize_whitelist_authorization_and_dependencies_with, initialize_whitelist_authorization_with, + }; + + fn configuration_for_listed_tracker() -> Core { + Core { + listed: true, + ..Default::default() + } + } + + #[tokio::test] + async fn should_authorize_a_whitelisted_infohash() { + let (whitelist_authorization, in_memory_whitelist) = + initialize_whitelist_authorization_and_dependencies_with(&configuration_for_listed_tracker()); + + let info_hash = sample_info_hash(); + + let _unused = in_memory_whitelist.add(&info_hash).await; + + let result = whitelist_authorization.authorize(&info_hash).await; + + assert!(result.is_ok()); + } + + #[tokio::test] + async fn should_not_authorize_a_non_whitelisted_infohash() { + let whitelist_authorization = initialize_whitelist_authorization_with(&configuration_for_listed_tracker()); + + let result = whitelist_authorization.authorize(&sample_info_hash()).await; + + assert!(matches!(result.unwrap_err(), WhitelistError::TorrentNotWhitelisted { .. })); + } + } + + mod when_the_tacker_is_not_configured_as_listed { + + use torrust_tracker_configuration::Core; + + use crate::test_helpers::tests::sample_info_hash; + use crate::whitelist::authorization::tests::the_whitelist_authorization_for_announce_and_scrape_actions::{ + initialize_whitelist_authorization_and_dependencies_with, initialize_whitelist_authorization_with, + }; + + fn configuration_for_non_listed_tracker() -> Core { + Core { + listed: false, + ..Default::default() + } + } + + #[tokio::test] + async fn should_authorize_a_whitelisted_infohash() { + let (whitelist_authorization, in_memory_whitelist) = + initialize_whitelist_authorization_and_dependencies_with(&configuration_for_non_listed_tracker()); + + let info_hash = sample_info_hash(); + + let _unused = in_memory_whitelist.add(&info_hash).await; + + let result = whitelist_authorization.authorize(&info_hash).await; + + assert!(result.is_ok()); + } + + #[tokio::test] + async fn should_also_authorize_a_non_whitelisted_infohash() { + let whitelist_authorization = initialize_whitelist_authorization_with(&configuration_for_non_listed_tracker()); + + let result = whitelist_authorization.authorize(&sample_info_hash()).await; + + assert!(result.is_ok()); + } + } + } +} diff --git a/packages/tracker-core/src/whitelist/manager.rs b/packages/tracker-core/src/whitelist/manager.rs new file mode 100644 index 000000000..452fcb6c5 --- /dev/null +++ b/packages/tracker-core/src/whitelist/manager.rs @@ -0,0 +1,184 @@ +//! Whitelist manager. +//! +//! This module provides the `WhitelistManager` struct, which is responsible for +//! managing the whitelist of torrents. +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; + +use super::repository::in_memory::InMemoryWhitelist; +use super::repository::persisted::DatabaseWhitelist; +use crate::databases; +/// Manages the whitelist of allowed torrents. +/// +/// This structure handles both the in-memory and persistent representations of +/// the whitelist. It is primarily relevant for private trackers that restrict +/// access to specific torrents. +pub struct WhitelistManager { + /// The in-memory list of allowed torrents. + in_memory_whitelist: Arc, + + /// The persisted list of allowed torrents. + database_whitelist: Arc, +} + +impl WhitelistManager { + /// Creates a new `WhitelistManager` instance. + /// + /// # Arguments + /// + /// - `database_whitelist`: Persistent database-backed whitelist repository. + /// - `in_memory_whitelist`: In-memory whitelist repository for fast runtime + /// access. + /// + /// # Returns + /// + /// A new `WhitelistManager` instance. + #[must_use] + pub fn new(database_whitelist: Arc, in_memory_whitelist: Arc) -> Self { + Self { + in_memory_whitelist, + database_whitelist, + } + } + + /// Adds a torrent to the whitelist. + /// + /// This operation is relevant for private trackers to control which + /// torrents are allowed. + /// + /// # Errors + /// Returns a `database::Error` if the operation fails in the database. + pub async fn add_torrent_to_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + self.database_whitelist.add(info_hash)?; + self.in_memory_whitelist.add(info_hash).await; + Ok(()) + } + + /// Removes a torrent from the whitelist. + /// + /// This operation is relevant for private trackers to revoke access to + /// specific torrents. + /// + /// # Errors + /// Returns a `database::Error` if the operation fails in the database. + pub async fn remove_torrent_from_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + self.database_whitelist.remove(info_hash)?; + self.in_memory_whitelist.remove(info_hash).await; + Ok(()) + } + + /// Loads the whitelist from the database into memory. + /// + /// This is useful when restarting the tracker to ensure the in-memory + /// whitelist is synchronized with the database. + /// + /// # Errors + /// Returns a `database::Error` if the operation fails to load from the database. + pub async fn load_whitelist_from_database(&self) -> Result<(), databases::error::Error> { + let whitelisted_torrents_from_database = self.database_whitelist.load_from_database()?; + + self.in_memory_whitelist.clear().await; + + for info_hash in whitelisted_torrents_from_database { + let _: bool = self.in_memory_whitelist.add(&info_hash).await; + } + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + + use std::sync::Arc; + + use torrust_tracker_configuration::Core; + + use crate::databases::setup::initialize_database; + use crate::databases::Database; + use crate::test_helpers::tests::ephemeral_configuration_for_listed_tracker; + use crate::whitelist::manager::WhitelistManager; + use crate::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::whitelist::repository::persisted::DatabaseWhitelist; + + struct WhitelistManagerDeps { + pub _database: Arc>, + pub database_whitelist: Arc, + pub in_memory_whitelist: Arc, + } + + fn initialize_whitelist_manager_for_whitelisted_tracker() -> (Arc, Arc) { + let config = ephemeral_configuration_for_listed_tracker(); + initialize_whitelist_manager_and_deps(&config) + } + + fn initialize_whitelist_manager_and_deps(config: &Core) -> (Arc, Arc) { + let database = initialize_database(config); + let database_whitelist = Arc::new(DatabaseWhitelist::new(database.clone())); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + + let whitelist_manager = Arc::new(WhitelistManager::new(database_whitelist.clone(), in_memory_whitelist.clone())); + + ( + whitelist_manager, + Arc::new(WhitelistManagerDeps { + _database: database, + database_whitelist, + in_memory_whitelist, + }), + ) + } + + mod configured_as_whitelisted { + + mod handling_the_torrent_whitelist { + use crate::test_helpers::tests::sample_info_hash; + use crate::whitelist::manager::tests::initialize_whitelist_manager_for_whitelisted_tracker; + + #[tokio::test] + async fn it_should_add_a_torrent_to_the_whitelist() { + let (whitelist_manager, services) = initialize_whitelist_manager_for_whitelisted_tracker(); + + let info_hash = sample_info_hash(); + + whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); + + assert!(services.in_memory_whitelist.contains(&info_hash).await); + assert!(services.database_whitelist.load_from_database().unwrap().contains(&info_hash)); + } + + #[tokio::test] + async fn it_should_remove_a_torrent_from_the_whitelist() { + let (whitelist_manager, services) = initialize_whitelist_manager_for_whitelisted_tracker(); + + let info_hash = sample_info_hash(); + + whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); + + whitelist_manager.remove_torrent_from_whitelist(&info_hash).await.unwrap(); + + assert!(!services.in_memory_whitelist.contains(&info_hash).await); + assert!(!services.database_whitelist.load_from_database().unwrap().contains(&info_hash)); + } + + mod persistence { + use crate::test_helpers::tests::sample_info_hash; + use crate::whitelist::manager::tests::initialize_whitelist_manager_for_whitelisted_tracker; + + #[tokio::test] + async fn it_should_load_the_whitelist_from_the_database() { + let (whitelist_manager, services) = initialize_whitelist_manager_for_whitelisted_tracker(); + + let info_hash = sample_info_hash(); + + services.database_whitelist.add(&info_hash).unwrap(); + + whitelist_manager.load_whitelist_from_database().await.unwrap(); + + assert!(services.in_memory_whitelist.contains(&info_hash).await); + } + } + } + } +} diff --git a/packages/tracker-core/src/whitelist/mod.rs b/packages/tracker-core/src/whitelist/mod.rs new file mode 100644 index 000000000..d9ad18311 --- /dev/null +++ b/packages/tracker-core/src/whitelist/mod.rs @@ -0,0 +1,58 @@ +//! This module contains the logic to manage the torrent whitelist. +//! +//! In tracker configurations where the tracker operates in "listed" mode, only +//! torrents that have been explicitly added to the whitelist are allowed to +//! perform announce and scrape actions. This module provides all the +//! functionality required to manage such a whitelist. +//! +//! The module is organized into the following submodules: +//! +//! - **`authorization`**: Contains the logic to authorize torrents based on their +//! whitelist status. +//! - **`manager`**: Provides high-level management functions for the whitelist, +//! such as adding or removing torrents. +//! - **`repository`**: Implements persistence for whitelist data. +//! - **`setup`**: Provides initialization routines for setting up the whitelist +//! system. +//! - **`test_helpers`**: Contains helper functions and fixtures for testing +//! whitelist functionality. +pub mod authorization; +pub mod manager; +pub mod repository; +pub mod setup; +pub mod test_helpers; + +#[cfg(test)] +mod tests { + + mod configured_as_whitelisted { + + mod handling_authorization { + use crate::test_helpers::tests::sample_info_hash; + use crate::whitelist::test_helpers::tests::initialize_whitelist_services_for_listed_tracker; + + #[tokio::test] + async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { + let (whitelist_authorization, whitelist_manager) = initialize_whitelist_services_for_listed_tracker(); + + let info_hash = sample_info_hash(); + + let result = whitelist_manager.add_torrent_to_whitelist(&info_hash).await; + assert!(result.is_ok()); + + let result = whitelist_authorization.authorize(&info_hash).await; + assert!(result.is_ok()); + } + + #[tokio::test] + async fn it_should_not_authorize_the_announce_and_scrape_actions_on_not_whitelisted_torrents() { + let (whitelist_authorization, _whitelist_manager) = initialize_whitelist_services_for_listed_tracker(); + + let info_hash = sample_info_hash(); + + let result = whitelist_authorization.authorize(&info_hash).await; + assert!(result.is_err()); + } + } + } +} diff --git a/packages/tracker-core/src/whitelist/repository/in_memory.rs b/packages/tracker-core/src/whitelist/repository/in_memory.rs new file mode 100644 index 000000000..0cee3a94b --- /dev/null +++ b/packages/tracker-core/src/whitelist/repository/in_memory.rs @@ -0,0 +1,97 @@ +//! The in-memory list of allowed torrents. +use bittorrent_primitives::info_hash::InfoHash; + +/// In-memory whitelist to manage allowed torrents. +/// +/// Stores `InfoHash` values for quick lookup and modification. +#[derive(Debug, Default)] +pub struct InMemoryWhitelist { + /// A thread-safe set of whitelisted `InfoHash` values. + whitelist: tokio::sync::RwLock>, +} + +impl InMemoryWhitelist { + /// Adds a torrent to the in-memory whitelist. + /// + /// # Returns + /// + /// - `true` if the torrent was newly added. + /// - `false` if the torrent was already in the whitelist. + pub async fn add(&self, info_hash: &InfoHash) -> bool { + self.whitelist.write().await.insert(*info_hash) + } + + /// Removes a torrent from the in-memory whitelist. + /// + /// # Returns + /// + /// - `true` if the torrent was present and removed. + /// - `false` if the torrent was not found. + pub(crate) async fn remove(&self, info_hash: &InfoHash) -> bool { + self.whitelist.write().await.remove(info_hash) + } + + /// Checks if a torrent is in the whitelist. + pub async fn contains(&self, info_hash: &InfoHash) -> bool { + self.whitelist.read().await.contains(info_hash) + } + + /// Clears all torrents from the whitelist. + pub(crate) async fn clear(&self) { + let mut whitelist = self.whitelist.write().await; + whitelist.clear(); + } +} + +#[cfg(test)] +mod tests { + + use crate::test_helpers::tests::sample_info_hash; + use crate::whitelist::repository::in_memory::InMemoryWhitelist; + + #[tokio::test] + async fn should_allow_adding_a_new_torrent_to_the_whitelist() { + let info_hash = sample_info_hash(); + + let whitelist = InMemoryWhitelist::default(); + + whitelist.add(&info_hash).await; + + assert!(whitelist.contains(&info_hash).await); + } + + #[tokio::test] + async fn should_allow_removing_a_new_torrent_to_the_whitelist() { + let info_hash = sample_info_hash(); + + let whitelist = InMemoryWhitelist::default(); + + whitelist.add(&info_hash).await; + whitelist.remove(&sample_info_hash()).await; + + assert!(!whitelist.contains(&info_hash).await); + } + + #[tokio::test] + async fn should_allow_clearing_the_whitelist() { + let info_hash = sample_info_hash(); + + let whitelist = InMemoryWhitelist::default(); + + whitelist.add(&info_hash).await; + whitelist.clear().await; + + assert!(!whitelist.contains(&info_hash).await); + } + + #[tokio::test] + async fn should_allow_checking_if_an_infohash_is_whitelisted() { + let info_hash = sample_info_hash(); + + let whitelist = InMemoryWhitelist::default(); + + whitelist.add(&info_hash).await; + + assert!(whitelist.contains(&info_hash).await); + } +} diff --git a/packages/tracker-core/src/whitelist/repository/mod.rs b/packages/tracker-core/src/whitelist/repository/mod.rs new file mode 100644 index 000000000..d900a8c29 --- /dev/null +++ b/packages/tracker-core/src/whitelist/repository/mod.rs @@ -0,0 +1,3 @@ +//! Repository implementations for the whitelist. +pub mod in_memory; +pub mod persisted; diff --git a/packages/tracker-core/src/whitelist/repository/persisted.rs b/packages/tracker-core/src/whitelist/repository/persisted.rs new file mode 100644 index 000000000..eec6704d6 --- /dev/null +++ b/packages/tracker-core/src/whitelist/repository/persisted.rs @@ -0,0 +1,142 @@ +//! The repository that persists the whitelist. +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; + +use crate::databases::{self, Database}; + +/// The persisted list of allowed torrents. +/// +/// This repository handles adding, removing, and loading torrents +/// from a persistent database like `SQLite` or `MySQL`ç. +pub struct DatabaseWhitelist { + /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) + /// or [`MySQL`](crate::core::databases::mysql) + database: Arc>, +} + +impl DatabaseWhitelist { + /// Creates a new `DatabaseWhitelist`. + #[must_use] + pub fn new(database: Arc>) -> Self { + Self { database } + } + + /// Adds a torrent to the whitelist if not already present. + /// + /// # Errors + /// Returns a `database::Error` if unable to add the `info_hash` to the + /// whitelist. + pub(crate) fn add(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; + + if is_whitelisted { + return Ok(()); + } + + self.database.add_info_hash_to_whitelist(*info_hash)?; + + Ok(()) + } + + /// Removes a torrent from the whitelist if it exists. + /// + /// # Errors + /// Returns a `database::Error` if unable to remove the `info_hash`. + pub(crate) fn remove(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; + + if !is_whitelisted { + return Ok(()); + } + + self.database.remove_info_hash_from_whitelist(*info_hash)?; + + Ok(()) + } + + /// Loads the entire whitelist from the database. + /// + /// # Errors + /// Returns a `database::Error` if unable to load whitelisted `info_hash` + /// values. + pub(crate) fn load_from_database(&self) -> Result, databases::error::Error> { + self.database.load_whitelist() + } +} + +#[cfg(test)] +mod tests { + mod the_persisted_whitelist_repository { + + use crate::databases::setup::initialize_database; + use crate::test_helpers::tests::{ephemeral_configuration_for_listed_tracker, sample_info_hash}; + use crate::whitelist::repository::persisted::DatabaseWhitelist; + + fn initialize_database_whitelist() -> DatabaseWhitelist { + let configuration = ephemeral_configuration_for_listed_tracker(); + let database = initialize_database(&configuration); + DatabaseWhitelist::new(database) + } + + #[test] + fn should_add_a_new_infohash_to_the_list() { + let whitelist = initialize_database_whitelist(); + + let infohash = sample_info_hash(); + + let _result = whitelist.add(&infohash); + + assert_eq!(whitelist.load_from_database().unwrap(), vec!(infohash)); + } + + #[test] + fn should_remove_a_infohash_from_the_list() { + let whitelist = initialize_database_whitelist(); + + let infohash = sample_info_hash(); + + let _result = whitelist.add(&infohash); + + let _result = whitelist.remove(&infohash); + + assert_eq!(whitelist.load_from_database().unwrap(), vec!()); + } + + #[test] + fn should_load_all_infohashes_from_the_database() { + let whitelist = initialize_database_whitelist(); + + let infohash = sample_info_hash(); + + let _result = whitelist.add(&infohash); + + let result = whitelist.load_from_database().unwrap(); + + assert_eq!(result, vec!(infohash)); + } + + #[test] + fn should_not_add_the_same_infohash_to_the_list_twice() { + let whitelist = initialize_database_whitelist(); + + let infohash = sample_info_hash(); + + let _result = whitelist.add(&infohash); + let _result = whitelist.add(&infohash); + + assert_eq!(whitelist.load_from_database().unwrap(), vec!(infohash)); + } + + #[test] + fn should_not_fail_removing_an_infohash_that_is_not_in_the_list() { + let whitelist = initialize_database_whitelist(); + + let infohash = sample_info_hash(); + + let result = whitelist.remove(&infohash); + + assert!(result.is_ok()); + } + } +} diff --git a/packages/tracker-core/src/whitelist/setup.rs b/packages/tracker-core/src/whitelist/setup.rs new file mode 100644 index 000000000..cb18c1478 --- /dev/null +++ b/packages/tracker-core/src/whitelist/setup.rs @@ -0,0 +1,41 @@ +//! Initializes the whitelist manager. +//! +//! This module provides functions to set up the `WhitelistManager`, which is responsible +//! for managing whitelisted torrents in both the in-memory and persistent database repositories. +use std::sync::Arc; + +use super::manager::WhitelistManager; +use super::repository::in_memory::InMemoryWhitelist; +use super::repository::persisted::DatabaseWhitelist; +use crate::databases::Database; + +/// Initializes the `WhitelistManager` by combining in-memory and database +/// repositories. +/// +/// The `WhitelistManager` handles the operations related to whitelisted +/// torrents, such as adding, removing, and verifying torrents in the whitelist. +/// It operates with: +/// +/// 1. **In-Memory Whitelist:** Provides fast, runtime-based access to +/// whitelisted torrents. +/// 2. **Database Whitelist:** Ensures persistent storage of the whitelist data. +/// +/// # Arguments +/// +/// * `database` - An `Arc>` representing the database connection, +/// sed for persistent whitelist storage. +/// * `in_memory_whitelist` - An `Arc` representing the in-memory +/// whitelist repository for fast access. +/// +/// # Returns +/// +/// An `Arc` instance that manages both the in-memory and database +/// whitelist repositories. +#[must_use] +pub fn initialize_whitelist_manager( + database: Arc>, + in_memory_whitelist: Arc, +) -> Arc { + let database_whitelist = Arc::new(DatabaseWhitelist::new(database)); + Arc::new(WhitelistManager::new(database_whitelist, in_memory_whitelist)) +} diff --git a/packages/tracker-core/src/whitelist/test_helpers.rs b/packages/tracker-core/src/whitelist/test_helpers.rs new file mode 100644 index 000000000..cf1699be4 --- /dev/null +++ b/packages/tracker-core/src/whitelist/test_helpers.rs @@ -0,0 +1,35 @@ +//! Generic test helper functions for the whitelist module. +//! +//! This module provides utility functions to initialize the whitelist services required for testing. +//! In particular, it sets up the `WhitelistAuthorization` and `WhitelistManager` services using a +//! configured database and an in-memory whitelist repository. +#[cfg(test)] +pub(crate) mod tests { + + use std::sync::Arc; + + use torrust_tracker_configuration::Configuration; + + use crate::databases::setup::initialize_database; + use crate::whitelist::authorization::WhitelistAuthorization; + use crate::whitelist::manager::WhitelistManager; + use crate::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::whitelist::setup::initialize_whitelist_manager; + + #[must_use] + pub fn initialize_whitelist_services(config: &Configuration) -> (Arc, Arc) { + let database = initialize_database(&config.core); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + + (whitelist_authorization, whitelist_manager) + } + + #[must_use] + pub fn initialize_whitelist_services_for_listed_tracker() -> (Arc, Arc) { + use torrust_tracker_test_helpers::configuration; + + initialize_whitelist_services(&configuration::ephemeral_listed()) + } +} diff --git a/packages/tracker-core/tests/common/fixtures.rs b/packages/tracker-core/tests/common/fixtures.rs new file mode 100644 index 000000000..ea9c93a65 --- /dev/null +++ b/packages/tracker-core/tests/common/fixtures.rs @@ -0,0 +1,52 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::str::FromStr; + +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::Core; +use torrust_tracker_primitives::peer::Peer; +use torrust_tracker_primitives::DurationSinceUnixEpoch; +use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; + +/// # Panics +/// +/// Will panic if the temporary file path is not a valid UTF-8 string. +#[must_use] +pub fn ephemeral_configuration() -> Core { + let mut config = Core::default(); + + let temp_file = ephemeral_sqlite_database(); + temp_file.to_str().unwrap().clone_into(&mut config.database.path); + + config +} + +/// # Panics +/// +/// Will panic if the string representation of the info hash is not a valid infohash. +#[must_use] +pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") +} + +/// Sample peer whose state is not relevant for the tests. +#[must_use] +pub fn sample_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(remote_client_ip(), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } +} + +// The client peer IP. +#[must_use] +pub fn remote_client_ip() -> IpAddr { + IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) +} diff --git a/packages/tracker-core/tests/common/mod.rs b/packages/tracker-core/tests/common/mod.rs new file mode 100644 index 000000000..414e9d7b5 --- /dev/null +++ b/packages/tracker-core/tests/common/mod.rs @@ -0,0 +1,2 @@ +pub mod fixtures; +pub mod test_env; diff --git a/packages/tracker-core/tests/common/test_env.rs b/packages/tracker-core/tests/common/test_env.rs new file mode 100644 index 000000000..3fe0464fe --- /dev/null +++ b/packages/tracker-core/tests/common/test_env.rs @@ -0,0 +1,180 @@ +use std::net::IpAddr; +use std::sync::Arc; + +use aquatic_udp_protocol::AnnounceEvent; +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::announce_handler::PeersWanted; +use bittorrent_tracker_core::container::TrackerCoreContainer; +use bittorrent_tracker_core::statistics::persisted::load_persisted_metrics; +use tokio::task::yield_now; +use tokio_util::sync::CancellationToken; +use torrust_tracker_configuration::Core; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_primitives::core::{AnnounceData, ScrapeData}; +use torrust_tracker_primitives::peer::Peer; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::DurationSinceUnixEpoch; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; + +pub struct TestEnv { + pub swarm_coordination_registry_container: Arc, + pub tracker_core_container: Arc, +} + +impl TestEnv { + #[must_use] + pub async fn started(core_config: Core) -> Self { + let test_env = TestEnv::new(core_config); + test_env.start().await; + test_env + } + + #[must_use] + pub fn new(core_config: Core) -> Self { + let core_config = Arc::new(core_config); + + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + core_config.tracker_usage_statistics.into(), + )); + + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + &core_config, + &swarm_coordination_registry_container, + )); + + Self { + swarm_coordination_registry_container, + tracker_core_container, + } + } + + pub async fn start(&self) { + let now = DurationSinceUnixEpoch::from_secs(0); + self.load_persisted_metrics(now).await; + self.run_jobs().await; + } + + async fn load_persisted_metrics(&self, now: DurationSinceUnixEpoch) { + load_persisted_metrics( + &self.tracker_core_container.stats_repository, + &self.tracker_core_container.db_downloads_metric_repository, + now, + ) + .await + .unwrap(); + } + + async fn run_jobs(&self) { + let mut jobs = vec![]; + let cancellation_token = CancellationToken::new(); + + let job = torrust_tracker_swarm_coordination_registry::statistics::event::listener::run_event_listener( + self.swarm_coordination_registry_container.event_bus.receiver(), + cancellation_token.clone(), + &self.swarm_coordination_registry_container.stats_repository, + ); + + jobs.push(job); + + let job = bittorrent_tracker_core::statistics::event::listener::run_event_listener( + self.swarm_coordination_registry_container.event_bus.receiver(), + cancellation_token.clone(), + &self.tracker_core_container.stats_repository, + &self.tracker_core_container.db_downloads_metric_repository, + self.tracker_core_container + .core_config + .tracker_policy + .persistent_torrent_completed_stat, + ); + jobs.push(job); + + // Give the event listeners some time to start + // todo: they should notify when they are ready + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + + pub async fn announce_peer_started( + &mut self, + mut peer: Peer, + remote_client_ip: &IpAddr, + info_hash: &InfoHash, + ) -> AnnounceData { + peer.event = AnnounceEvent::Started; + + let announce_data = self + .tracker_core_container + .announce_handler + .handle_announcement(info_hash, &mut peer, remote_client_ip, &PeersWanted::AsManyAsPossible) + .await + .unwrap(); + + // Give time to the event listeners to process the event + yield_now().await; + + announce_data + } + + pub async fn announce_peer_completed( + &mut self, + mut peer: Peer, + remote_client_ip: &IpAddr, + info_hash: &InfoHash, + ) -> AnnounceData { + peer.event = AnnounceEvent::Completed; + + let announce_data = self + .tracker_core_container + .announce_handler + .handle_announcement(info_hash, &mut peer, remote_client_ip, &PeersWanted::AsManyAsPossible) + .await + .unwrap(); + + // Give time to the event listeners to process the event + yield_now().await; + + announce_data + } + + pub async fn scrape(&self, info_hash: &InfoHash) -> ScrapeData { + self.tracker_core_container + .scrape_handler + .handle_scrape(&vec![*info_hash]) + .await + .unwrap() + } + + pub async fn increase_number_of_downloads(&mut self, peer: Peer, remote_client_ip: &IpAddr, info_hash: &InfoHash) { + let _announce_data = self.announce_peer_started(peer, remote_client_ip, info_hash).await; + let announce_data = self.announce_peer_completed(peer, remote_client_ip, info_hash).await; + + assert_eq!(announce_data.stats.downloads(), 1); + } + + pub async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.swarm_coordination_registry_container + .swarms + .get_swarm_metadata(info_hash) + .await + .unwrap() + } + + pub async fn remove_swarm(&self, info_hash: &InfoHash) { + self.swarm_coordination_registry_container + .swarms + .remove(info_hash) + .await + .unwrap(); + } + + pub async fn get_counter_value(&self, metric_name: &str) -> u64 { + self.tracker_core_container + .stats_repository + .get_metrics() + .await + .metric_collection + .get_counter_value(&MetricName::new(metric_name), &LabelSet::default()) + .unwrap() + .value() + } +} diff --git a/packages/tracker-core/tests/integration.rs b/packages/tracker-core/tests/integration.rs new file mode 100644 index 000000000..b170aaebd --- /dev/null +++ b/packages/tracker-core/tests/integration.rs @@ -0,0 +1,113 @@ +mod common; + +use common::fixtures::{ephemeral_configuration, remote_client_ip, sample_info_hash, sample_peer}; +use common::test_env::TestEnv; +use torrust_tracker_configuration::AnnouncePolicy; +use torrust_tracker_primitives::core::AnnounceData; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + +#[tokio::test] +async fn it_should_handle_the_announce_request() { + let mut test_env = TestEnv::started(ephemeral_configuration()).await; + + let announce_data = test_env + .announce_peer_started(sample_peer(), &remote_client_ip(), &sample_info_hash()) + .await; + + assert_eq!( + announce_data, + AnnounceData { + peers: vec![], + stats: SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0 + }, + policy: AnnouncePolicy { + interval: 120, + interval_min: 120 + } + } + ); +} + +#[tokio::test] +async fn it_should_not_return_the_peer_making_the_announce_request() { + let mut test_env = TestEnv::started(ephemeral_configuration()).await; + + let announce_data = test_env + .announce_peer_started(sample_peer(), &remote_client_ip(), &sample_info_hash()) + .await; + + assert_eq!(announce_data.peers.len(), 0); +} + +#[tokio::test] +async fn it_should_handle_the_scrape_request() { + let mut test_env = TestEnv::started(ephemeral_configuration()).await; + + let info_hash = sample_info_hash(); + + let _announce_data = test_env + .announce_peer_started(sample_peer(), &remote_client_ip(), &info_hash) + .await; + + let scrape_data = test_env.scrape(&info_hash).await; + + assert!(scrape_data.files.contains_key(&info_hash)); +} + +#[tokio::test] +async fn it_should_persist_the_number_of_completed_peers_for_each_torrent_into_the_database() { + let mut core_config = ephemeral_configuration(); + core_config.tracker_policy.persistent_torrent_completed_stat = true; + + let mut test_env = TestEnv::started(core_config).await; + + let info_hash = sample_info_hash(); + + test_env + .increase_number_of_downloads(sample_peer(), &remote_client_ip(), &info_hash) + .await; + + assert!(test_env.get_swarm_metadata(&info_hash).await.unwrap().downloads() == 1); + + test_env.remove_swarm(&info_hash).await; + + // Ensure the swarm metadata is removed + assert!(test_env.get_swarm_metadata(&info_hash).await.is_none()); + + // Load torrents from the database to ensure the completed stats are persisted + test_env + .tracker_core_container + .torrents_manager + .load_torrents_from_database() + .unwrap(); + + assert!(test_env.get_swarm_metadata(&info_hash).await.unwrap().downloads() == 1); +} + +#[tokio::test] +async fn it_should_persist_the_global_number_of_completed_peers_into_the_database() { + let mut core_config = ephemeral_configuration(); + + core_config.tracker_policy.persistent_torrent_completed_stat = true; + + let mut test_env = TestEnv::started(core_config.clone()).await; + + test_env + .increase_number_of_downloads(sample_peer(), &remote_client_ip(), &sample_info_hash()) + .await; + + // We run a new instance of the test environment to simulate a restart. + // The new instance uses the same underlying database. + + let new_test_env = TestEnv::started(core_config).await; + + assert_eq!( + new_test_env + .get_counter_value("tracker_core_persistent_torrents_downloads_total") + .await, + 1 + ); +} diff --git a/packages/udp-protocol/Cargo.toml b/packages/udp-protocol/Cargo.toml new file mode 100644 index 000000000..3bcde9a95 --- /dev/null +++ b/packages/udp-protocol/Cargo.toml @@ -0,0 +1,20 @@ +[package] +description = "A library with the primitive types and functions for the BitTorrent UDP tracker protocol." +keywords = [ "bittorrent", "library", "primitives", "udp" ] +name = "bittorrent-udp-tracker-protocol" +readme = "README.md" + +authors.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } diff --git a/packages/udp-protocol/LICENSE b/packages/udp-protocol/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/udp-protocol/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/udp-protocol/README.md b/packages/udp-protocol/README.md new file mode 100644 index 000000000..4f63fb675 --- /dev/null +++ b/packages/udp-protocol/README.md @@ -0,0 +1,11 @@ +# BitTorrent UDP Tracker Protocol + +A library with the primitive types and functions used by BitTorrent UDP trackers. + +## Documentation + +[Crate documentation](https://docs.rs/bittorrent-udp-protocol). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/udp-protocol/src/lib.rs b/packages/udp-protocol/src/lib.rs new file mode 100644 index 000000000..f0983a7ba --- /dev/null +++ b/packages/udp-protocol/src/lib.rs @@ -0,0 +1,15 @@ +//! Primitive types and functions for `BitTorrent` UDP trackers. +pub mod peer_builder; + +use torrust_tracker_clock::clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/packages/udp-protocol/src/peer_builder.rs b/packages/udp-protocol/src/peer_builder.rs new file mode 100644 index 000000000..a42ddfaa5 --- /dev/null +++ b/packages/udp-protocol/src/peer_builder.rs @@ -0,0 +1,26 @@ +//! Logic to extract the peer info from the announce request. +use std::net::{IpAddr, SocketAddr}; + +use torrust_tracker_clock::clock::Time; +use torrust_tracker_primitives::peer; + +use crate::CurrentClock; + +/// Extracts the [`peer::Peer`] info from the +/// announce request. +/// +/// # Arguments +/// +/// * `peer_ip` - The real IP address of the peer, not the one in the announce request. +#[must_use] +pub fn from_request(announce_request: &aquatic_udp_protocol::AnnounceRequest, peer_ip: &IpAddr) -> peer::Peer { + peer::Peer { + peer_id: announce_request.peer_id, + peer_addr: SocketAddr::new(*peer_ip, announce_request.port.0.into()), + updated: CurrentClock::now(), + uploaded: announce_request.bytes_uploaded, + downloaded: announce_request.bytes_downloaded, + left: announce_request.bytes_left, + event: announce_request.event.into(), + } +} diff --git a/packages/udp-tracker-core/Cargo.toml b/packages/udp-tracker-core/Cargo.toml new file mode 100644 index 000000000..828b3aff2 --- /dev/null +++ b/packages/udp-tracker-core/Cargo.toml @@ -0,0 +1,48 @@ +[package] +authors.workspace = true +description = "A library with the core functionality needed to implement a BitTorrent UDP tracker." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = [ "api", "bittorrent", "core", "library", "tracker" ] +license.workspace = true +name = "bittorrent-udp-tracker-core" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +bittorrent-primitives = "0.1.0" +bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } +bittorrent-udp-tracker-protocol = { version = "3.0.0-develop", path = "../udp-protocol" } +bloom = "0.3.2" +blowfish = "0" +cipher = "0.4" +criterion = { version = "0.5.1", features = [ "async_tokio" ] } +futures = "0" +generic-array = "0" +lazy_static = "1" +rand = "0" +serde = "1.0.219" +thiserror = "2" +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync", "time" ] } +tokio-util = "0.7.15" +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } +torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } +tracing = "0" +zerocopy = "0.7" + +[dev-dependencies] +mockall = "0" +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } + +[[bench]] +harness = false +name = "udp_tracker_core_benchmark" diff --git a/packages/udp-tracker-core/LICENSE b/packages/udp-tracker-core/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/udp-tracker-core/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/udp-tracker-core/README.md b/packages/udp-tracker-core/README.md new file mode 100644 index 000000000..625e5d011 --- /dev/null +++ b/packages/udp-tracker-core/README.md @@ -0,0 +1,15 @@ +# BitTorrent UDP Tracker Core library + +A library with the core functionality needed to implement a BitTorrent UDP tracker. + +You usually don’t need to use this library directly. Instead, you should use the [Torrust Tracker](https://github.com/torrust/torrust-tracker). If you want to build your own tracker, you can use this library as the core functionality. + +> **Disclaimer**: This library is actively under development. We’re currently extracting and refining common types from the[Torrust Tracker](https://github.com/torrust/torrust-tracker) to make them available to the BitTorrent community in Rust. While these types are functional, they are not yet ready for use in production or third-party projects. + +## Documentation + +[Crate documentation](https://docs.rs/bittorrent-udp-tracker-core). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/udp-tracker-core/benches/helpers/mod.rs b/packages/udp-tracker-core/benches/helpers/mod.rs new file mode 100644 index 000000000..ea1959bb4 --- /dev/null +++ b/packages/udp-tracker-core/benches/helpers/mod.rs @@ -0,0 +1,2 @@ +pub mod sync; +mod utils; diff --git a/packages/udp-tracker-core/benches/helpers/sync.rs b/packages/udp-tracker-core/benches/helpers/sync.rs new file mode 100644 index 000000000..e8ec1ce03 --- /dev/null +++ b/packages/udp-tracker-core/benches/helpers/sync.rs @@ -0,0 +1,31 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use bittorrent_udp_tracker_core::event::bus::EventBus; +use bittorrent_udp_tracker_core::event::sender::Broadcaster; +use bittorrent_udp_tracker_core::services::connect::ConnectService; +use torrust_tracker_events::bus::SenderStatus; +use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + +use crate::helpers::utils::{sample_ipv4_remote_addr, sample_issue_time}; + +#[allow(clippy::unused_async)] +pub async fn connect_once(samples: u64) -> Duration { + let client_socket_addr = sample_ipv4_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let udp_core_broadcaster = Broadcaster::default(); + let event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); + + let udp_core_stats_event_sender = event_bus.sender(); + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + let start = Instant::now(); + + for _ in 0..samples { + let _response = connect_service.handle_connect(client_socket_addr, server_service_binding.clone(), sample_issue_time()); + } + + start.elapsed() +} diff --git a/packages/udp-tracker-core/benches/helpers/utils.rs b/packages/udp-tracker-core/benches/helpers/utils.rs new file mode 100644 index 000000000..1423d4bcd --- /dev/null +++ b/packages/udp-tracker-core/benches/helpers/utils.rs @@ -0,0 +1,27 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + +use bittorrent_udp_tracker_core::event::Event; +use futures::future::BoxFuture; +use mockall::mock; +use torrust_tracker_events::sender::SendError; + +pub(crate) fn sample_ipv4_remote_addr() -> SocketAddr { + sample_ipv4_socket_address() +} + +pub(crate) fn sample_ipv4_socket_address() -> SocketAddr { + SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080) +} + +pub(crate) fn sample_issue_time() -> f64 { + 1_000_000_000_f64 +} + +mock! { + pub(crate) UdpCoreStatsEventSender {} + impl torrust_tracker_events::sender::Sender for UdpCoreStatsEventSender { + type Event = Event; + + fn send(&self, event: Event) -> BoxFuture<'static,Option > > > ; + } +} diff --git a/packages/udp-tracker-core/benches/udp_tracker_core_benchmark.rs b/packages/udp-tracker-core/benches/udp_tracker_core_benchmark.rs new file mode 100644 index 000000000..90fc721d0 --- /dev/null +++ b/packages/udp-tracker-core/benches/udp_tracker_core_benchmark.rs @@ -0,0 +1,20 @@ +mod helpers; + +use std::time::Duration; + +use criterion::{criterion_group, criterion_main, Criterion}; + +use crate::helpers::sync; + +fn bench_connect_once(c: &mut Criterion) { + let mut group = c.benchmark_group("udp_tracker/connect_once"); + group.warm_up_time(Duration::from_millis(500)); + group.measurement_time(Duration::from_secs(1)); + + group.bench_function("connect_once", |b| { + b.iter(|| sync::connect_once(100)); + }); +} + +criterion_group!(benches, bench_connect_once); +criterion_main!(benches); diff --git a/packages/udp-tracker-core/src/connection_cookie.rs b/packages/udp-tracker-core/src/connection_cookie.rs new file mode 100644 index 000000000..ce255705f --- /dev/null +++ b/packages/udp-tracker-core/src/connection_cookie.rs @@ -0,0 +1,334 @@ +//! Module for Generating and Verifying Connection IDs (Cookies) in the UDP Tracker Protocol +//! +//! **Overview:** +//! +//! In the `BitTorrent` UDP tracker protocol, clients initiate communication by obtaining a connection ID from the server. This connection ID serves as a safeguard against IP spoofing and replay attacks, ensuring that only legitimate clients can interact with the tracker. +//! +//! To maintain a stateless server architecture, this module implements a method for generating and verifying connection IDs based on the client's fingerprint (typically derived from the client's IP address) and the time of issuance, without storing state on the server. +//! +//! The connection ID is an encrypted, opaque cookie held by the client. Since the same server that generates the cookie also validates it, endianness is not a concern. +//! +//! **Connection ID Generation Algorithm:** +//! +//! 1. **Issue Time (`issue_at`):** +//! - Obtain a 64-bit floating-point number (`f64`), this number should be a normal number. +//! +//! 2. **Fingerprint:** +//! - Use an 8-byte fingerprint unique to the client (e.g., derived from the client's IP address). +//! +//! 3. **Assemble Cookie Value:** +//! - Interpret the bytes of `issue_at` as a 64-bit integer (`i64`) without altering the bit pattern. +//! - Similarly, interpret the fingerprint bytes as an `i64`. +//! - Compute the cookie value: +//! ```rust,ignore +//! let cookie_value = issue_at_i64.wrapping_add(fingerprint_i64); +//! ``` +//! - *Note:* Wrapping addition handles potential integer overflows gracefully. +//! +//! 4. **Encrypt Cookie Value:** +//! - Encrypt `cookie_value` using a symmetric block cipher obtained from `Current::get_cipher()`. +//! - The encrypted `cookie_value` becomes the connection ID sent to the client. +//! +//! **Connection ID Verification Algorithm:** +//! +//! When a client sends a request with a connection ID, the server verifies it using the following steps: +//! +//! 1. **Decrypt Connection ID:** +//! - Decrypt the received connection ID using the same cipher to retrieve `cookie_value`. +//! - *Important:* The decryption is non-authenticated, meaning it does not verify the integrity or authenticity of the ciphertext. The decrypted `cookie_value` can be any byte sequence, including manipulated data. +//! +//! 2. **Recover Issue Time:** +//! - Interpret the fingerprint bytes as `i64`. +//! - Compute the issue time: +//! ```rust,ignore +//! let issue_at_i64 = cookie_value.wrapping_sub(fingerprint_i64); +//! ``` +//! - *Note:* Wrapping subtraction handles potential integer underflows gracefully. +//! - Reinterpret `issue_at_i64` bytes as an `f64` to get `issue_time`. +//! +//! 3. **Validate Issue Time:** +//! - **Handling Arbitrary `issue_time` Values:** +//! - Since the decrypted `cookie_value` may be arbitrary, `issue_time` can be any `f64` value, including special values like `NaN`, positive or negative infinity, and subnormal numbers. +//! - **Validation Steps:** +//! - **Step 1:** Check if `issue_time` is finite using `issue_time.is_finite()`. +//! - If `issue_time` is `NaN` or infinite, it is considered invalid. +//! - **Step 2:** If `issue_time` is finite, perform range checks: +//! - Verify that `min <= issue_time <= max`. +//! - If `issue_time` passes these checks, accept the connection ID; otherwise, reject it with an appropriate error. +//! +//! **Security Considerations:** +//! +//! - **Non-Authenticated Encryption:** +//! - Due to protocol constraints (an 8-byte connection ID), using an authenticated encryption algorithm is not feasible. +//! - As a result, attackers might attempt to forge or manipulate connection IDs. +//! - However, the probability of an arbitrary 64-bit value decrypting to a valid `issue_time` within the acceptable range is extremely low, effectively serving as a form of authentication. +//! +//! - **Handling Special `f64` Values:** +//! - By checking `issue_time.is_finite()`, the implementation excludes `NaN` and infinite values, ensuring that only valid, finite timestamps are considered. +//! +//! - **Probability of Successful Attack:** +//! - Given the narrow valid time window (usually around 2 minutes) compared to the vast range of `f64` values, the chance of successfully guessing a valid `issue_time` is negligible. +//! +//! **Key Points:** +//! +//! - The server maintains a stateless design, reducing resource consumption and complexity. +//! - Wrapping arithmetic ensures that the addition and subtraction of `i64` values are safe from overflow or underflow issues. +//! - The validation process is robust against malformed or malicious connection IDs due to stringent checks on the deserialized `issue_time`. +//! - The module leverages existing cryptographic primitives while acknowledging and addressing the limitations imposed by the protocol's specifications. +//! + +use aquatic_udp_protocol::ConnectionId as Cookie; +use cookie_builder::{assemble, decode, disassemble, encode}; +use thiserror::Error; +use tracing::instrument; +use zerocopy::AsBytes; + +use crate::crypto::keys::CipherArrayBlowfish; + +/// Error returned when there was an error with the connection cookie. +#[derive(Error, Debug, Clone, PartialEq)] +pub enum ConnectionCookieError { + #[error("cookie value is not normal: {not_normal_value}")] + ValueNotNormal { not_normal_value: f64 }, + + #[error("cookie value is expired: {expired_value}, expected > {min_value}")] + ValueExpired { expired_value: f64, min_value: f64 }, + + #[error("cookie value is from future: {future_value}, expected < {max_value}")] + ValueFromFuture { future_value: f64, max_value: f64 }, +} + +/// Generates a new connection cookie. +/// +/// # Errors +/// +/// It would error if the supplied `issue_at` value is a zero, infinite, subnormal, or NaN. +/// +/// # Panics +/// +/// It would panic if the cookie is not exactly 8 bytes is size. +/// +#[instrument(err)] +pub fn make(fingerprint: u64, issue_at: f64) -> Result { + if !issue_at.is_normal() { + return Err(ConnectionCookieError::ValueNotNormal { + not_normal_value: issue_at, + }); + } + + let cookie = assemble(fingerprint, issue_at); + let cookie = encode(cookie); + + // using `read_from` as the array may be not correctly aligned + Ok(zerocopy::FromBytes::read_from(cookie.as_slice()).expect("it should be the same size")) +} + +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::net::SocketAddr; +use std::ops::Range; + +/// Checks if the supplied `connection_cookie` is valid. +/// +/// # Errors +/// +/// It would error if the connection cookie is somehow invalid or expired. +/// +/// # Panics +/// +/// It would panic if the range start is not smaller than it's end. +#[instrument] +pub fn check(cookie: &Cookie, fingerprint: u64, valid_range: Range) -> Result { + assert!(valid_range.start <= valid_range.end, "range start is larger than range end"); + + let cookie_bytes = CipherArrayBlowfish::from_slice(cookie.0.as_bytes()); + let cookie_bytes = decode(*cookie_bytes); + + let issue_time = disassemble(fingerprint, cookie_bytes); + + if !issue_time.is_normal() { + return Err(ConnectionCookieError::ValueNotNormal { + not_normal_value: issue_time, + }); + } + + if issue_time < valid_range.start { + return Err(ConnectionCookieError::ValueExpired { + expired_value: issue_time, + min_value: valid_range.start, + }); + } + + if issue_time > valid_range.end { + return Err(ConnectionCookieError::ValueFromFuture { + future_value: issue_time, + max_value: valid_range.end, + }); + } + + Ok(issue_time) +} + +#[must_use] +pub fn gen_remote_fingerprint(remote_addr: &SocketAddr) -> u64 { + let mut state = DefaultHasher::new(); + remote_addr.hash(&mut state); + state.finish() +} + +mod cookie_builder { + use cipher::{BlockDecrypt, BlockEncrypt}; + use tracing::instrument; + use zerocopy::{byteorder, AsBytes as _, NativeEndian}; + + pub type CookiePlainText = CipherArrayBlowfish; + pub type CookieCipherText = CipherArrayBlowfish; + + use crate::crypto::keys::{CipherArrayBlowfish, Current, Keeper}; + + #[instrument()] + pub(super) fn assemble(fingerprint: u64, issue_at: f64) -> CookiePlainText { + let issue_at: byteorder::I64 = + *zerocopy::FromBytes::ref_from(&issue_at.to_ne_bytes()).expect("it should be aligned"); + let fingerprint: byteorder::I64 = + *zerocopy::FromBytes::ref_from(&fingerprint.to_ne_bytes()).expect("it should be aligned"); + + let cookie = issue_at.get().wrapping_add(fingerprint.get()); + let cookie: byteorder::I64 = + *zerocopy::FromBytes::ref_from(&cookie.to_ne_bytes()).expect("it should be aligned"); + + *CipherArrayBlowfish::from_slice(cookie.as_bytes()) + } + + #[instrument()] + pub(super) fn disassemble(fingerprint: u64, cookie: CookiePlainText) -> f64 { + let fingerprint: byteorder::I64 = + *zerocopy::FromBytes::ref_from(&fingerprint.to_ne_bytes()).expect("it should be aligned"); + + // the array may be not aligned, so we read instead of reference. + let cookie: byteorder::I64 = + zerocopy::FromBytes::read_from(cookie.as_bytes()).expect("it should be the same size"); + + let issue_time_bytes = cookie.get().wrapping_sub(fingerprint.get()).to_ne_bytes(); + + let issue_time: byteorder::F64 = + *zerocopy::FromBytes::ref_from(&issue_time_bytes).expect("it should be aligned"); + + issue_time.get() + } + + #[instrument()] + pub(super) fn encode(mut cookie: CookiePlainText) -> CookieCipherText { + let cipher = Current::get_cipher_blowfish(); + + cipher.encrypt_block(&mut cookie); + + cookie + } + + #[instrument()] + pub(super) fn decode(mut cookie: CookieCipherText) -> CookiePlainText { + let cipher = Current::get_cipher_blowfish(); + + cipher.decrypt_block(&mut cookie); + + cookie + } +} + +#[cfg(test)] +mod tests { + + use super::*; + + #[test] + fn it_should_make_a_connection_cookie() { + let fingerprint = 1_000_000; + let issue_at = 1000.0; + let cookie = make(fingerprint, issue_at).unwrap().0.get(); + + // Expected connection ID derived through experimentation + assert_eq!(cookie.to_le_bytes(), [10, 130, 175, 211, 244, 253, 230, 210]); + } + + #[test] + fn it_should_create_same_cookie_for_same_input() { + let fingerprint = 1_000_000; + let issue_at = 1000.0; + let cookie1 = make(fingerprint, issue_at).unwrap(); + let cookie2 = make(fingerprint, issue_at).unwrap(); + + assert_eq!(cookie1, cookie2); + } + + #[test] + fn it_should_create_different_cookies_for_different_fingerprints() { + let fingerprint1 = 1_000_000; + let fingerprint2 = 2_000_000; + let issue_at = 1000.0; + let cookie1 = make(fingerprint1, issue_at).unwrap(); + let cookie2 = make(fingerprint2, issue_at).unwrap(); + + assert_ne!(cookie1, cookie2); + } + + #[test] + fn it_should_create_different_cookies_for_different_issue_times() { + let fingerprint = 1_000_000; + let issue_at1 = 1000.0; + let issue_at2 = 2000.0; + let cookie1 = make(fingerprint, issue_at1).unwrap(); + let cookie2 = make(fingerprint, issue_at2).unwrap(); + + assert_ne!(cookie1, cookie2); + } + + #[test] + fn it_should_validate_a_valid_cookie() { + let fingerprint = 1_000_000; + let issue_at = 1_000_000_000_f64; + let cookie = make(fingerprint, issue_at).unwrap(); + + let min = issue_at - 10.0; + let max = issue_at + 10.0; + + let result = check(&cookie, fingerprint, min..max).unwrap(); + + // we should have exactly the same bytes returned + assert_eq!(result.to_ne_bytes(), issue_at.to_ne_bytes()); + } + + #[test] + fn it_should_reject_an_expired_cookie() { + let fingerprint = 1_000_000; + let issue_at = 1_000_000_000_f64; + let cookie = make(fingerprint, issue_at).unwrap(); + + let min = issue_at + 10.0; + let max = issue_at + 20.0; + + let result = check(&cookie, fingerprint, min..max).unwrap_err(); + + match result { + ConnectionCookieError::ValueExpired { .. } => {} // Expected error + _ => panic!("Expected ConnectionIdExpired error"), + } + } + + #[test] + fn it_should_reject_a_cookie_from_the_future() { + let fingerprint = 1_000_000; + let issue_at = 1_000_000_000_f64; + + let cookie = make(fingerprint, issue_at).unwrap(); + + let min = issue_at - 20.0; + let max = issue_at - 10.0; + + let result = check(&cookie, fingerprint, min..max).unwrap_err(); + + match result { + ConnectionCookieError::ValueFromFuture { .. } => {} // Expected error + _ => panic!("Expected ConnectionIdFromFuture error"), + } + } +} diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs new file mode 100644 index 000000000..1d8b1d71c --- /dev/null +++ b/packages/udp-tracker-core/src/container.rs @@ -0,0 +1,123 @@ +use std::sync::Arc; + +use bittorrent_tracker_core::container::TrackerCoreContainer; +use tokio::sync::RwLock; +use torrust_tracker_configuration::{Core, UdpTracker}; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; + +use crate::event::bus::EventBus; +use crate::event::sender::Broadcaster; +use crate::services::announce::AnnounceService; +use crate::services::banning::BanService; +use crate::services::connect::ConnectService; +use crate::services::scrape::ScrapeService; +use crate::statistics::repository::Repository; +use crate::{event, services, statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; + +pub struct UdpTrackerCoreContainer { + pub udp_tracker_config: Arc, + + pub tracker_core_container: Arc, + + // `UdpTrackerCoreServices` + pub event_bus: Arc, + pub stats_event_sender: crate::event::sender::Sender, + pub stats_repository: Arc, + pub ban_service: Arc>, + pub connect_service: Arc, + pub announce_service: Arc, + pub scrape_service: Arc, +} + +impl UdpTrackerCoreContainer { + #[must_use] + pub fn initialize(core_config: &Arc, udp_tracker_config: &Arc) -> Arc { + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + core_config.tracker_usage_statistics.into(), + )); + + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + core_config, + &swarm_coordination_registry_container, + )); + + Self::initialize_from_tracker_core(&tracker_core_container, udp_tracker_config) + } + + #[must_use] + pub fn initialize_from_tracker_core( + tracker_core_container: &Arc, + udp_tracker_config: &Arc, + ) -> Arc { + let udp_tracker_core_services = UdpTrackerCoreServices::initialize_from(tracker_core_container); + + Self::initialize_from_services(tracker_core_container, &udp_tracker_core_services, udp_tracker_config) + } + + #[must_use] + pub fn initialize_from_services( + tracker_core_container: &Arc, + udp_tracker_core_services: &Arc, + udp_tracker_config: &Arc, + ) -> Arc { + Arc::new(Self { + udp_tracker_config: udp_tracker_config.clone(), + + tracker_core_container: tracker_core_container.clone(), + + // `UdpTrackerCoreServices` + event_bus: udp_tracker_core_services.event_bus.clone(), + stats_event_sender: udp_tracker_core_services.stats_event_sender.clone(), + stats_repository: udp_tracker_core_services.stats_repository.clone(), + ban_service: udp_tracker_core_services.ban_service.clone(), + connect_service: udp_tracker_core_services.connect_service.clone(), + announce_service: udp_tracker_core_services.announce_service.clone(), + scrape_service: udp_tracker_core_services.scrape_service.clone(), + }) + } +} + +pub struct UdpTrackerCoreServices { + pub event_bus: Arc, + pub stats_event_sender: crate::event::sender::Sender, + pub stats_repository: Arc, + pub ban_service: Arc>, + pub connect_service: Arc, + pub announce_service: Arc, + pub scrape_service: Arc, +} + +impl UdpTrackerCoreServices { + #[must_use] + pub fn initialize_from(tracker_core_container: &Arc) -> Arc { + let udp_core_broadcaster = Broadcaster::default(); + let udp_core_stats_repository = Arc::new(Repository::new()); + let event_bus = Arc::new(EventBus::new( + tracker_core_container.core_config.tracker_usage_statistics.into(), + udp_core_broadcaster.clone(), + )); + + let udp_core_stats_event_sender = event_bus.sender(); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender.clone())); + let announce_service = Arc::new(AnnounceService::new( + tracker_core_container.announce_handler.clone(), + tracker_core_container.whitelist_authorization.clone(), + udp_core_stats_event_sender.clone(), + )); + let scrape_service = Arc::new(ScrapeService::new( + tracker_core_container.scrape_handler.clone(), + udp_core_stats_event_sender.clone(), + )); + + Arc::new(Self { + event_bus, + stats_event_sender: udp_core_stats_event_sender, + stats_repository: udp_core_stats_repository, + ban_service, + connect_service, + announce_service, + scrape_service, + }) + } +} diff --git a/packages/udp-tracker-core/src/crypto/ephemeral_instance_keys.rs b/packages/udp-tracker-core/src/crypto/ephemeral_instance_keys.rs new file mode 100644 index 000000000..de40e4b1d --- /dev/null +++ b/packages/udp-tracker-core/src/crypto/ephemeral_instance_keys.rs @@ -0,0 +1,32 @@ +//! This module contains the ephemeral instance keys used by the application. +//! +//! They are ephemeral because they are generated at runtime when the +//! application starts and are not persisted anywhere. + +use blowfish::BlowfishLE; +use cipher::{BlockSizeUser, KeyInit}; +use generic_array::GenericArray; +use rand::rngs::ThreadRng; +use rand::RngExt; + +pub type Seed = [u8; 32]; +pub type CipherBlowfish = BlowfishLE; +pub type CipherArrayBlowfish = GenericArray::BlockSize>; + +lazy_static! { + /// The random static seed. + pub static ref RANDOM_SEED: Seed = { + let mut rng = ThreadRng::default(); + rng.random::() + }; + + /// The random cipher from the seed. + pub static ref RANDOM_CIPHER_BLOWFISH: CipherBlowfish = { + let mut rng = ThreadRng::default(); + let seed: Seed = rng.random(); + CipherBlowfish::new_from_slice(&seed).expect("it could not generate key") + }; + + /// The constant cipher for testing. + pub static ref ZEROED_TEST_CIPHER_BLOWFISH: CipherBlowfish = CipherBlowfish::new_from_slice(&[0u8; 32]).expect("it could not generate key"); +} diff --git a/packages/udp-tracker-core/src/crypto/keys.rs b/packages/udp-tracker-core/src/crypto/keys.rs new file mode 100644 index 000000000..bb813b9dc --- /dev/null +++ b/packages/udp-tracker-core/src/crypto/keys.rs @@ -0,0 +1,156 @@ +//! This module contains logic related to cryptographic keys. +//! +//! Specifically, it contains the logic for storing the seed and providing +//! it to other modules. +//! +//! It also provides the logic for the cipher for encryption and decryption. + +use cipher::{BlockDecrypt, BlockEncrypt}; + +use self::detail_cipher::CURRENT_CIPHER; +use self::detail_seed::CURRENT_SEED; +pub use crate::crypto::ephemeral_instance_keys::CipherArrayBlowfish; +use crate::crypto::ephemeral_instance_keys::{CipherBlowfish, Seed, RANDOM_CIPHER_BLOWFISH, RANDOM_SEED}; + +/// This trait is for structures that can keep and provide a seed. +pub trait Keeper { + type Seed: Sized + Default + AsMut<[u8]>; + type Cipher: BlockEncrypt + BlockDecrypt; + + /// It returns a reference to the seed that is keeping. + fn get_seed() -> &'static Self::Seed; + fn get_cipher_blowfish() -> &'static Self::Cipher; +} + +/// The keeper for the instance. When the application is running +/// in production, this will be the seed keeper that is used. +pub struct Instance; + +/// The keeper for the current execution. It's a facade at compilation +/// time that will either be the instance seed keeper (with a randomly +/// generated key for production) or the zeroed seed keeper. +pub struct Current; + +impl Keeper for Instance { + type Seed = Seed; + type Cipher = CipherBlowfish; + + fn get_seed() -> &'static Self::Seed { + &RANDOM_SEED + } + + fn get_cipher_blowfish() -> &'static Self::Cipher { + &RANDOM_CIPHER_BLOWFISH + } +} + +impl Keeper for Current { + type Seed = Seed; + type Cipher = CipherBlowfish; + + #[allow(clippy::needless_borrow)] + fn get_seed() -> &'static Self::Seed { + &CURRENT_SEED + } + + fn get_cipher_blowfish() -> &'static Self::Cipher { + &CURRENT_CIPHER + } +} + +#[cfg(test)] +mod tests { + + use super::detail_seed::ZEROED_TEST_SEED; + use super::{Current, Instance, Keeper}; + use crate::crypto::ephemeral_instance_keys::{CipherBlowfish, Seed, ZEROED_TEST_CIPHER_BLOWFISH}; + + pub struct ZeroedTest; + + impl Keeper for ZeroedTest { + type Seed = Seed; + type Cipher = CipherBlowfish; + + #[allow(clippy::needless_borrow)] + fn get_seed() -> &'static Self::Seed { + &ZEROED_TEST_SEED + } + + fn get_cipher_blowfish() -> &'static Self::Cipher { + &ZEROED_TEST_CIPHER_BLOWFISH + } + } + + #[test] + fn the_default_seed_and_the_zeroed_seed_should_be_the_same_when_testing() { + assert_eq!(Current::get_seed(), ZeroedTest::get_seed()); + } + + #[test] + fn the_default_seed_and_the_instance_seed_should_be_different_when_testing() { + assert_ne!(Current::get_seed(), Instance::get_seed()); + } +} + +mod detail_seed { + use crate::crypto::ephemeral_instance_keys::Seed; + + #[allow(dead_code)] + pub const ZEROED_TEST_SEED: Seed = [0u8; 32]; + + #[cfg(test)] + pub use ZEROED_TEST_SEED as CURRENT_SEED; + + #[cfg(not(test))] + pub use crate::crypto::ephemeral_instance_keys::RANDOM_SEED as CURRENT_SEED; + + #[cfg(test)] + mod tests { + use crate::crypto::ephemeral_instance_keys::RANDOM_SEED; + use crate::crypto::keys::detail_seed::ZEROED_TEST_SEED; + use crate::crypto::keys::CURRENT_SEED; + + #[test] + fn it_should_have_a_zero_test_seed() { + assert_eq!(ZEROED_TEST_SEED, [0u8; 32]); + } + + #[test] + fn it_should_default_to_zeroed_seed_when_testing() { + assert_eq!(CURRENT_SEED, ZEROED_TEST_SEED); + } + + #[test] + fn it_should_have_a_large_random_seed() { + assert!(u128::from_ne_bytes((*RANDOM_SEED)[..16].try_into().unwrap()) > u128::from(u64::MAX)); + assert!(u128::from_ne_bytes((*RANDOM_SEED)[16..].try_into().unwrap()) > u128::from(u64::MAX)); + } + } +} + +mod detail_cipher { + #[allow(unused_imports)] + #[cfg(not(test))] + pub use crate::crypto::ephemeral_instance_keys::RANDOM_CIPHER_BLOWFISH as CURRENT_CIPHER; + #[cfg(test)] + pub use crate::crypto::ephemeral_instance_keys::ZEROED_TEST_CIPHER_BLOWFISH as CURRENT_CIPHER; + + #[cfg(test)] + mod tests { + use cipher::BlockEncrypt; + + use crate::crypto::ephemeral_instance_keys::{CipherArrayBlowfish, ZEROED_TEST_CIPHER_BLOWFISH}; + use crate::crypto::keys::detail_cipher::CURRENT_CIPHER; + + #[test] + fn it_should_default_to_zeroed_seed_when_testing() { + let mut data: cipher::generic_array::GenericArray = CipherArrayBlowfish::from([0u8; 8]); + let mut data_2 = CipherArrayBlowfish::from([0u8; 8]); + + CURRENT_CIPHER.encrypt_block(&mut data); + ZEROED_TEST_CIPHER_BLOWFISH.encrypt_block(&mut data_2); + + assert_eq!(data, data_2); + } + } +} diff --git a/src/shared/crypto/mod.rs b/packages/udp-tracker-core/src/crypto/mod.rs similarity index 100% rename from src/shared/crypto/mod.rs rename to packages/udp-tracker-core/src/crypto/mod.rs diff --git a/packages/udp-tracker-core/src/event.rs b/packages/udp-tracker-core/src/event.rs new file mode 100644 index 000000000..761b809d8 --- /dev/null +++ b/packages/udp-tracker-core/src/event.rs @@ -0,0 +1,97 @@ +use std::net::SocketAddr; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_metrics::label::{LabelSet, LabelValue}; +use torrust_tracker_metrics::label_name; +use torrust_tracker_primitives::peer::PeerAnnouncement; +use torrust_tracker_primitives::service_binding::ServiceBinding; + +/// A UDP core event. +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum Event { + UdpConnect { + connection: ConnectionContext, + }, + UdpAnnounce { + connection: ConnectionContext, + info_hash: InfoHash, + announcement: PeerAnnouncement, + }, + UdpScrape { + connection: ConnectionContext, + }, +} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub struct ConnectionContext { + pub client_socket_addr: SocketAddr, + pub server_service_binding: ServiceBinding, +} + +impl ConnectionContext { + #[must_use] + pub fn new(client_socket_addr: SocketAddr, server_service_binding: ServiceBinding) -> Self { + Self { + client_socket_addr, + server_service_binding, + } + } + + #[must_use] + pub fn client_socket_addr(&self) -> SocketAddr { + self.client_socket_addr + } + + #[must_use] + pub fn server_socket_addr(&self) -> SocketAddr { + self.server_service_binding.bind_address() + } +} + +impl From for LabelSet { + fn from(connection_context: ConnectionContext) -> Self { + LabelSet::from([ + ( + label_name!("server_binding_protocol"), + LabelValue::new(&connection_context.server_service_binding.protocol().to_string()), + ), + ( + label_name!("server_binding_ip"), + LabelValue::new(&connection_context.server_service_binding.bind_address().ip().to_string()), + ), + ( + label_name!("server_binding_address_ip_type"), + LabelValue::new(&connection_context.server_service_binding.bind_address_ip_type().to_string()), + ), + ( + label_name!("server_binding_address_ip_family"), + LabelValue::new(&connection_context.server_service_binding.bind_address_ip_family().to_string()), + ), + ( + label_name!("server_binding_port"), + LabelValue::new(&connection_context.server_service_binding.bind_address().port().to_string()), + ), + ]) + } +} + +pub mod sender { + use std::sync::Arc; + + use super::Event; + + pub type Sender = Option>>; + pub type Broadcaster = torrust_tracker_events::broadcaster::Broadcaster; +} + +pub mod receiver { + use super::Event; + + pub type Receiver = Box>; +} + +pub mod bus { + use crate::event::Event; + + pub type EventBus = torrust_tracker_events::bus::EventBus; +} diff --git a/packages/udp-tracker-core/src/lib.rs b/packages/udp-tracker-core/src/lib.rs new file mode 100644 index 000000000..2c1943853 --- /dev/null +++ b/packages/udp-tracker-core/src/lib.rs @@ -0,0 +1,59 @@ +pub mod connection_cookie; +pub mod container; +pub mod crypto; +pub mod event; +pub mod services; +pub mod statistics; + +use torrust_tracker_clock::clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; + +use crypto::ephemeral_instance_keys; +use tracing::instrument; + +#[macro_use] +extern crate lazy_static; + +/// The maximum number of connection id errors per ip. Clients will be banned if +/// they exceed this limit. +pub const MAX_CONNECTION_ID_ERRORS_PER_IP: u32 = 10; + +pub const UDP_TRACKER_LOG_TARGET: &str = "UDP TRACKER"; + +/// It initializes the static values. +#[instrument(skip())] +pub fn initialize_static() { + // Initialize the Ephemeral Instance Random Seed + lazy_static::initialize(&ephemeral_instance_keys::RANDOM_SEED); + + // Initialize the Ephemeral Instance Random Cipher + lazy_static::initialize(&ephemeral_instance_keys::RANDOM_CIPHER_BLOWFISH); + + // Initialize the Zeroed Cipher + lazy_static::initialize(&ephemeral_instance_keys::ZEROED_TEST_CIPHER_BLOWFISH); +} + +#[cfg(test)] +pub(crate) mod tests { + use bittorrent_primitives::info_hash::InfoHash; + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } +} diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs new file mode 100644 index 000000000..a69e91d8a --- /dev/null +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -0,0 +1,161 @@ +//! The `announce` service. +//! +//! The service is responsible for handling the `announce` requests. +//! +//! It delegates the `announce` logic to the [`AnnounceHandler`] and it returns +//! the [`AnnounceData`]. +//! +//! It also sends an [`udp_tracker_core::statistics::event::Event`] +//! because events are specific for the HTTP tracker. +use std::net::SocketAddr; +use std::ops::Range; +use std::sync::Arc; + +use aquatic_udp_protocol::AnnounceRequest; +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; +use bittorrent_tracker_core::error::{AnnounceError, WhitelistError}; +use bittorrent_tracker_core::whitelist; +use bittorrent_udp_tracker_protocol::peer_builder; +use torrust_tracker_primitives::core::AnnounceData; +use torrust_tracker_primitives::peer::PeerAnnouncement; +use torrust_tracker_primitives::service_binding::ServiceBinding; + +use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; +use crate::event::{ConnectionContext, Event}; + +/// The `AnnounceService` is responsible for handling the `announce` requests. +/// +/// The service sends an statistics event that increments: +/// +/// - The number of UDP `announce` requests handled by the UDP tracker. +pub struct AnnounceService { + announce_handler: Arc, + whitelist_authorization: Arc, + opt_udp_core_stats_event_sender: crate::event::sender::Sender, +} + +impl AnnounceService { + #[must_use] + pub fn new( + announce_handler: Arc, + whitelist_authorization: Arc, + opt_udp_core_stats_event_sender: crate::event::sender::Sender, + ) -> Self { + Self { + announce_handler, + whitelist_authorization, + opt_udp_core_stats_event_sender, + } + } + + /// It handles the `Announce` request. + /// + /// # Errors + /// + /// It will return an error if: + /// + /// - The tracker is running in listed mode and the torrent is not in the + /// whitelist. + pub async fn handle_announce( + &self, + client_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, + request: &AnnounceRequest, + cookie_valid_range: Range, + ) -> Result { + Self::authenticate(client_socket_addr, request, cookie_valid_range)?; + + let info_hash = request.info_hash.into(); + + self.authorize(&info_hash).await?; + + let remote_client_ip = client_socket_addr.ip(); + + let mut peer = peer_builder::from_request(request, &remote_client_ip); + + let peers_wanted: PeersWanted = i32::from(request.peers_wanted.0).into(); + + let announce_data = self + .announce_handler + .handle_announcement(&info_hash, &mut peer, &remote_client_ip, &peers_wanted) + .await?; + + self.send_event(info_hash, peer, client_socket_addr, server_service_binding) + .await; + + Ok(announce_data) + } + + fn authenticate( + remote_addr: SocketAddr, + request: &AnnounceRequest, + cookie_valid_range: Range, + ) -> Result { + check( + &request.connection_id, + gen_remote_fingerprint(&remote_addr), + cookie_valid_range, + ) + } + + async fn authorize(&self, info_hash: &InfoHash) -> Result<(), WhitelistError> { + self.whitelist_authorization.authorize(info_hash).await + } + + async fn send_event( + &self, + info_hash: InfoHash, + announcement: PeerAnnouncement, + client_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, + ) { + if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { + let event = Event::UdpAnnounce { + connection: ConnectionContext::new(client_socket_addr, server_service_binding), + info_hash, + announcement, + }; + + tracing::debug!(target = crate::UDP_TRACKER_LOG_TARGET, "Sending UdpAnnounce event: {event:?}"); + + udp_stats_event_sender.send(event).await; + } + } +} + +/// Errors related to announce requests. +#[derive(thiserror::Error, Debug, Clone)] +pub enum UdpAnnounceError { + /// Error returned when there was an error with the connection cookie. + #[error("Connection cookie error: {source}")] + ConnectionCookieError { source: ConnectionCookieError }, + + /// Error returned when there was an error with the tracker core announce handler. + #[error("Tracker core announce error: {source}")] + TrackerCoreAnnounceError { source: AnnounceError }, + + /// Error returned when there was an error with the tracker core whitelist. + #[error("Tracker core whitelist error: {source}")] + TrackerCoreWhitelistError { source: WhitelistError }, +} + +impl From for UdpAnnounceError { + fn from(connection_cookie_error: ConnectionCookieError) -> Self { + Self::ConnectionCookieError { + source: connection_cookie_error, + } + } +} + +impl From for UdpAnnounceError { + fn from(announce_error: AnnounceError) -> Self { + Self::TrackerCoreAnnounceError { source: announce_error } + } +} + +impl From for UdpAnnounceError { + fn from(whitelist_error: WhitelistError) -> Self { + Self::TrackerCoreWhitelistError { source: whitelist_error } + } +} diff --git a/packages/udp-tracker-core/src/services/banning.rs b/packages/udp-tracker-core/src/services/banning.rs new file mode 100644 index 000000000..8f63dd804 --- /dev/null +++ b/packages/udp-tracker-core/src/services/banning.rs @@ -0,0 +1,150 @@ +//! Banning service for UDP tracker. +//! +//! It bans clients that send invalid connection id's. +//! +//! It uses two levels of filtering: +//! +//! 1. First, tt uses a Counting Bloom Filter to keep track of the number of +//! connection ID errors per ip. That means there can be false positives, but +//! not false negatives. 1 out of 100000 requests will be a false positive +//! and the client will be banned and not receive a response. +//! 2. Since we want to avoid false positives (banning a client that is not +//! sending invalid connection id's), we use a `HashMap` to keep track of the +//! exact number of connection ID errors per ip. +//! +//! This two level filtering is to avoid false positives. It has the advantage +//! of being fast by using a Counting Bloom Filter and not having false +//! negatives at the cost of increasing the memory usage. +use std::collections::HashMap; +use std::net::IpAddr; + +use bloom::{CountingBloomFilter, ASMS}; +use tokio::time::Instant; + +use crate::UDP_TRACKER_LOG_TARGET; + +pub struct BanService { + max_connection_id_errors_per_ip: u32, + fuzzy_error_counter: CountingBloomFilter, + accurate_error_counter: HashMap, + last_connection_id_errors_reset: Instant, +} + +impl BanService { + #[must_use] + pub fn new(max_connection_id_errors_per_ip: u32) -> Self { + Self { + max_connection_id_errors_per_ip, + fuzzy_error_counter: CountingBloomFilter::with_rate(4, 0.01, 100), + accurate_error_counter: HashMap::new(), + last_connection_id_errors_reset: tokio::time::Instant::now(), + } + } + + pub fn increase_counter(&mut self, ip: &IpAddr) { + self.fuzzy_error_counter.insert(&ip.to_string()); + *self.accurate_error_counter.entry(*ip).or_insert(0) += 1; + } + + #[must_use] + pub fn get_count(&self, ip: &IpAddr) -> Option { + self.accurate_error_counter.get(ip).copied() + } + + #[must_use] + pub fn get_banned_ips_total(&self) -> usize { + self.accurate_error_counter.len() + } + + #[must_use] + pub fn get_estimate_count(&self, ip: &IpAddr) -> u32 { + self.fuzzy_error_counter.estimate_count(&ip.to_string()) + } + + /// Returns true if the given ip address is banned. + #[must_use] + pub fn is_banned(&self, ip: &IpAddr) -> bool { + // First check if the ip is in the bloom filter (fast check) + if self.fuzzy_error_counter.estimate_count(&ip.to_string()) <= self.max_connection_id_errors_per_ip { + return false; + } + + // Check with the exact counter (to avoid false positives) + match self.get_count(ip) { + Some(count) => count > self.max_connection_id_errors_per_ip, + None => false, + } + } + + /// Resets the filters and updates the reset timestamp. + pub fn reset_bans(&mut self) { + self.fuzzy_error_counter.clear(); + + self.accurate_error_counter.clear(); + + self.last_connection_id_errors_reset = Instant::now(); + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp::run_udp_server::loop (connection id errors filter cleared)"); + } +} + +#[cfg(test)] +mod tests { + use std::net::IpAddr; + + use super::BanService; + + /// Sample service with one day ban duration. + fn ban_service(counter_limit: u32) -> BanService { + BanService::new(counter_limit) + } + + #[test] + fn it_should_increase_the_errors_counter_for_a_given_ip() { + let mut ban_service = ban_service(1); + + let ip: IpAddr = "127.0.0.2".parse().unwrap(); + + ban_service.increase_counter(&ip); + + assert_eq!(ban_service.get_count(&ip), Some(1)); + } + + #[test] + fn it_should_ban_ips_with_counters_exceeding_a_predefined_limit() { + let mut ban_service = ban_service(1); + + let ip: IpAddr = "127.0.0.2".parse().unwrap(); + + ban_service.increase_counter(&ip); // Counter = 1 + ban_service.increase_counter(&ip); // Counter = 2 + + println!("Counter: {}", ban_service.get_count(&ip).unwrap()); + + assert!(ban_service.is_banned(&ip)); + } + + #[test] + fn it_should_not_ban_ips_whose_counters_do_not_exceed_the_predefined_limit() { + let mut ban_service = ban_service(1); + + let ip: IpAddr = "127.0.0.2".parse().unwrap(); + + ban_service.increase_counter(&ip); + + assert!(!ban_service.is_banned(&ip)); + } + + #[test] + fn it_should_allow_resetting_all_the_counters() { + let mut ban_service = ban_service(1); + + let ip: IpAddr = "127.0.0.2".parse().unwrap(); + + ban_service.increase_counter(&ip); // Counter = 1 + + ban_service.reset_bans(); + + assert_eq!(ban_service.get_estimate_count(&ip), 0); + } +} diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs new file mode 100644 index 000000000..6ba36f274 --- /dev/null +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -0,0 +1,187 @@ +//! The `connect` service. +//! +//! The service is responsible for handling the `connect` requests. +use std::net::SocketAddr; + +use aquatic_udp_protocol::ConnectionId; +use torrust_tracker_primitives::service_binding::ServiceBinding; + +use crate::connection_cookie::{gen_remote_fingerprint, make}; +use crate::event::{ConnectionContext, Event}; + +/// The `ConnectService` is responsible for handling the `connect` requests. +/// +/// It is responsible for generating the connection cookie and sending the +/// appropriate statistics events. +pub struct ConnectService { + pub opt_udp_core_stats_event_sender: crate::event::sender::Sender, +} + +impl ConnectService { + #[must_use] + pub fn new(opt_udp_core_stats_event_sender: crate::event::sender::Sender) -> Self { + Self { + opt_udp_core_stats_event_sender, + } + } + + /// Handles a `connect` request. + /// + /// # Panics + /// + /// It will panic if there was an error making the connection cookie. + pub async fn handle_connect( + &self, + client_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, + cookie_issue_time: f64, + ) -> ConnectionId { + let connection_id = + make(gen_remote_fingerprint(&client_socket_addr), cookie_issue_time).expect("it should be a normal value"); + + if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { + udp_stats_event_sender + .send(Event::UdpConnect { + connection: ConnectionContext::new(client_socket_addr, server_service_binding), + }) + .await; + } + + connection_id + } +} + +#[cfg(test)] +mod tests { + + mod connect_request { + + use std::future; + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use mockall::predicate::eq; + use torrust_tracker_events::bus::SenderStatus; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::connection_cookie::make; + use crate::event::bus::EventBus; + use crate::event::sender::Broadcaster; + use crate::event::{ConnectionContext, Event}; + use crate::services::connect::ConnectService; + use crate::services::tests::{ + sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv4_socket_address, sample_ipv6_remote_addr, + sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpCoreStatsEventSender, + }; + + #[tokio::test] + async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let udp_core_broadcaster = Broadcaster::default(); + let event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); + let udp_core_stats_event_sender = event_bus.sender(); + + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + + let response = connect_service + .handle_connect(sample_ipv4_remote_addr(), server_service_binding, sample_issue_time()) + .await; + + assert_eq!( + response, + make(sample_ipv4_remote_addr_fingerprint(), sample_issue_time()).unwrap() + ); + } + + #[tokio::test] + async fn a_connect_response_should_contain_a_new_connection_id() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let udp_core_broadcaster = Broadcaster::default(); + let event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); + let udp_core_stats_event_sender = event_bus.sender(); + + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + + let response = connect_service + .handle_connect(sample_ipv4_remote_addr(), server_service_binding, sample_issue_time()) + .await; + + assert_eq!( + response, + make(sample_ipv4_remote_addr_fingerprint(), sample_issue_time()).unwrap(), + ); + } + + #[tokio::test] + async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { + let client_socket_addr = sample_ipv6_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let udp_core_broadcaster = Broadcaster::default(); + let event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); + let udp_core_stats_event_sender = event_bus.sender(); + + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + + let response = connect_service + .handle_connect(client_socket_addr, server_service_binding, sample_issue_time()) + .await; + + assert_eq!( + response, + make(sample_ipv6_remote_addr_fingerprint(), sample_issue_time()).unwrap(), + ); + } + + #[tokio::test] + async fn it_should_send_the_upd4_connect_event_when_a_client_tries_to_connect_using_a_ip4_socket_address() { + let client_socket_addr = sample_ipv4_socket_address(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let mut udp_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send() + .with(eq(Event::UdpConnect { + connection: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let opt_udp_stats_event_sender: crate::event::sender::Sender = Some(Arc::new(udp_stats_event_sender_mock)); + + let connect_service = Arc::new(ConnectService::new(opt_udp_stats_event_sender)); + + connect_service + .handle_connect(client_socket_addr, server_service_binding, sample_issue_time()) + .await; + } + + #[tokio::test] + async fn it_should_send_the_upd6_connect_event_when_a_client_tries_to_connect_using_a_ip6_socket_address() { + let client_socket_addr = sample_ipv6_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let mut udp_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send() + .with(eq(Event::UdpConnect { + connection: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let opt_udp_stats_event_sender: crate::event::sender::Sender = Some(Arc::new(udp_stats_event_sender_mock)); + + let connect_service = Arc::new(ConnectService::new(opt_udp_stats_event_sender)); + + connect_service + .handle_connect(client_socket_addr, server_service_binding, sample_issue_time()) + .await; + } + } +} diff --git a/packages/udp-tracker-core/src/services/mod.rs b/packages/udp-tracker-core/src/services/mod.rs new file mode 100644 index 000000000..56882e68f --- /dev/null +++ b/packages/udp-tracker-core/src/services/mod.rs @@ -0,0 +1,54 @@ +pub mod announce; +pub mod banning; +pub mod connect; +pub mod scrape; + +#[cfg(test)] +pub(crate) mod tests { + + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + + use futures::future::BoxFuture; + use mockall::mock; + use torrust_tracker_events::sender::SendError; + + use crate::connection_cookie::gen_remote_fingerprint; + use crate::event::Event; + + pub(crate) fn sample_ipv4_remote_addr() -> SocketAddr { + sample_ipv4_socket_address() + } + + pub(crate) fn sample_ipv4_remote_addr_fingerprint() -> u64 { + gen_remote_fingerprint(&sample_ipv4_socket_address()) + } + + pub(crate) fn sample_ipv6_remote_addr() -> SocketAddr { + sample_ipv6_socket_address() + } + + pub(crate) fn sample_ipv6_remote_addr_fingerprint() -> u64 { + gen_remote_fingerprint(&sample_ipv6_socket_address()) + } + + pub(crate) fn sample_ipv4_socket_address() -> SocketAddr { + SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080) + } + + fn sample_ipv6_socket_address() -> SocketAddr { + SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 8080) + } + + pub(crate) fn sample_issue_time() -> f64 { + 1_000_000_000_f64 + } + + mock! { + pub(crate) UdpCoreStatsEventSender {} + impl torrust_tracker_events::sender::Sender for UdpCoreStatsEventSender { + type Event = Event; + + fn send(&self, event: Event) -> BoxFuture<'static,Option > > > ; + } + } +} diff --git a/packages/udp-tracker-core/src/services/scrape.rs b/packages/udp-tracker-core/src/services/scrape.rs new file mode 100644 index 000000000..8551351fb --- /dev/null +++ b/packages/udp-tracker-core/src/services/scrape.rs @@ -0,0 +1,130 @@ +//! The `scrape` service. +//! +//! The service is responsible for handling the `scrape` requests. +//! +//! It delegates the `scrape` logic to the [`ScrapeHandler`] and it returns the +//! [`ScrapeData`]. +//! +//! It also sends an [`udp_tracker_core::statistics::event::Event`] +//! because events are specific for the UDP tracker. +use std::net::SocketAddr; +use std::ops::Range; +use std::sync::Arc; + +use aquatic_udp_protocol::ScrapeRequest; +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::error::{ScrapeError, WhitelistError}; +use bittorrent_tracker_core::scrape_handler::ScrapeHandler; +use torrust_tracker_primitives::core::ScrapeData; +use torrust_tracker_primitives::service_binding::ServiceBinding; + +use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; +use crate::event::{ConnectionContext, Event}; + +/// The `ScrapeService` is responsible for handling the `scrape` requests. +/// +/// The service sends an statistics event that increments: +/// +/// - The number of UDP `scrape` requests handled by the UDP tracker. +pub struct ScrapeService { + scrape_handler: Arc, + opt_udp_stats_event_sender: crate::event::sender::Sender, +} + +impl ScrapeService { + #[must_use] + pub fn new(scrape_handler: Arc, opt_udp_stats_event_sender: crate::event::sender::Sender) -> Self { + Self { + scrape_handler, + opt_udp_stats_event_sender, + } + } + + /// It handles the `Scrape` request. + /// + /// # Errors + /// + /// It will return an error if the tracker core scrape handler returns an error. + pub async fn handle_scrape( + &self, + client_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, + request: &ScrapeRequest, + cookie_valid_range: Range, + ) -> Result { + Self::authenticate(client_socket_addr, request, cookie_valid_range)?; + + let scrape_data = self + .scrape_handler + .handle_scrape(&Self::convert_from_aquatic(&request.info_hashes)) + .await?; + + self.send_event(client_socket_addr, server_service_binding).await; + + Ok(scrape_data) + } + + fn authenticate( + remote_addr: SocketAddr, + request: &ScrapeRequest, + cookie_valid_range: Range, + ) -> Result { + check( + &request.connection_id, + gen_remote_fingerprint(&remote_addr), + cookie_valid_range, + ) + } + + fn convert_from_aquatic(aquatic_infohashes: &[aquatic_udp_protocol::common::InfoHash]) -> Vec { + aquatic_infohashes.iter().map(|&x| x.into()).collect() + } + + async fn send_event(&self, client_socket_addr: SocketAddr, server_service_binding: ServiceBinding) { + if let Some(udp_stats_event_sender) = self.opt_udp_stats_event_sender.as_deref() { + let event = Event::UdpScrape { + connection: ConnectionContext::new(client_socket_addr, server_service_binding), + }; + + tracing::debug!(target = crate::UDP_TRACKER_LOG_TARGET, "Sending UdpScrape event: {event:?}"); + + udp_stats_event_sender.send(event).await; + } + } +} + +/// Errors related to scrape requests. +#[derive(thiserror::Error, Debug, Clone)] +pub enum UdpScrapeError { + /// Error returned when there was an error with the connection cookie. + #[error("Connection cookie error: {source}")] + ConnectionCookieError { source: ConnectionCookieError }, + + /// Error returned when there was an error with the tracker core scrape handler. + #[error("Tracker core scrape error: {source}")] + TrackerCoreScrapeError { source: ScrapeError }, + + /// Error returned when there was an error with the tracker core whitelist. + #[error("Tracker core whitelist error: {source}")] + TrackerCoreWhitelistError { source: WhitelistError }, +} + +impl From for UdpScrapeError { + fn from(connection_cookie_error: ConnectionCookieError) -> Self { + Self::ConnectionCookieError { + source: connection_cookie_error, + } + } +} + +impl From for UdpScrapeError { + fn from(scrape_error: ScrapeError) -> Self { + Self::TrackerCoreScrapeError { source: scrape_error } + } +} + +impl From for UdpScrapeError { + fn from(whitelist_error: WhitelistError) -> Self { + Self::TrackerCoreWhitelistError { source: whitelist_error } + } +} diff --git a/packages/udp-tracker-core/src/statistics/event/handler.rs b/packages/udp-tracker-core/src/statistics/event/handler.rs new file mode 100644 index 000000000..e5d2b87a7 --- /dev/null +++ b/packages/udp-tracker-core/src/statistics/event/handler.rs @@ -0,0 +1,222 @@ +use torrust_tracker_metrics::label::{LabelSet, LabelValue}; +use torrust_tracker_metrics::{label_name, metric_name}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::Event; +use crate::statistics::repository::Repository; +use crate::statistics::UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; + +/// # Panics +/// +/// This function panics if the IP version does not match the event type. +pub async fn handle_event(event: Event, stats_repository: &Repository, now: DurationSinceUnixEpoch) { + match event { + Event::UdpConnect { connection: context } => { + let mut label_set = LabelSet::from(context); + label_set.upsert(label_name!("request_kind"), LabelValue::new("connect")); + + match stats_repository + .increase_counter(&metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; + } + Event::UdpAnnounce { connection: context, .. } => { + let mut label_set = LabelSet::from(context); + label_set.upsert(label_name!("request_kind"), LabelValue::new("announce")); + + match stats_repository + .increase_counter(&metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; + } + Event::UdpScrape { connection: context } => { + let mut label_set = LabelSet::from(context); + label_set.upsert(label_name!("request_kind"), LabelValue::new("scrape")); + + match stats_repository + .increase_counter(&metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; + } + } + + tracing::debug!("stats: {:?}", stats_repository.get_stats().await); +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + + use torrust_tracker_clock::clock::Time; + use torrust_tracker_primitives::peer::PeerAnnouncement; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event}; + use crate::statistics::event::handler::handle_event; + use crate::statistics::repository::Repository; + use crate::tests::sample_info_hash; + use crate::CurrentClock; + + #[tokio::test] + async fn should_increase_the_udp4_connections_counter_when_it_receives_a_udp4_connect_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpConnect { + connection: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_connections_handled(), 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_announces_counter_when_it_receives_a_udp4_announce_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpAnnounce { + connection: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + info_hash: sample_info_hash(), + announcement: PeerAnnouncement::default(), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_announces_handled(), 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_scrapes_counter_when_it_receives_a_udp4_scrape_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpScrape { + connection: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_scrapes_handled(), 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_connections_counter_when_it_receives_a_udp6_connect_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpConnect { + connection: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_connections_handled(), 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_announces_counter_when_it_receives_a_udp6_announce_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpAnnounce { + connection: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + info_hash: sample_info_hash(), + announcement: PeerAnnouncement::default(), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_announces_handled(), 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_scrapes_counter_when_it_receives_a_udp6_scrape_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpScrape { + connection: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_scrapes_handled(), 1); + } +} diff --git a/packages/udp-tracker-core/src/statistics/event/listener.rs b/packages/udp-tracker-core/src/statistics/event/listener.rs new file mode 100644 index 000000000..b11bcce85 --- /dev/null +++ b/packages/udp-tracker-core/src/statistics/event/listener.rs @@ -0,0 +1,58 @@ +use std::sync::Arc; + +use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_events::receiver::RecvError; + +use super::handler::handle_event; +use crate::event::receiver::Receiver; +use crate::statistics::repository::Repository; +use crate::{CurrentClock, UDP_TRACKER_LOG_TARGET}; + +#[must_use] +pub fn run_event_listener( + receiver: Receiver, + cancellation_token: CancellationToken, + repository: &Arc, +) -> JoinHandle<()> { + let stats_repository = repository.clone(); + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker core event listener"); + + tokio::spawn(async move { + dispatch_events(receiver, cancellation_token, stats_repository).await; + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "UDP tracker core event listener finished"); + }) +} + +async fn dispatch_events(mut receiver: Receiver, cancellation_token: CancellationToken, stats_repository: Arc) { + loop { + tokio::select! { + biased; + + () = cancellation_token.cancelled() => { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Received cancellation request, shutting down UDP tracker core event listener."); + break; + } + + result = receiver.recv() => { + match result { + Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, + Err(e) => { + match e { + RecvError::Closed => { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp tracker core statistics receiver closed."); + break; + } + RecvError::Lagged(n) => { + tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp tracker core statistics receiver lagged by {} events.", n); + } + } + } + } + } + } + } +} diff --git a/packages/udp-tracker-core/src/statistics/event/mod.rs b/packages/udp-tracker-core/src/statistics/event/mod.rs new file mode 100644 index 000000000..dae683398 --- /dev/null +++ b/packages/udp-tracker-core/src/statistics/event/mod.rs @@ -0,0 +1,2 @@ +pub mod handler; +pub mod listener; diff --git a/packages/udp-tracker-core/src/statistics/metrics.rs b/packages/udp-tracker-core/src/statistics/metrics.rs new file mode 100644 index 000000000..98906a596 --- /dev/null +++ b/packages/udp-tracker-core/src/statistics/metrics.rs @@ -0,0 +1,124 @@ +use serde::Serialize; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::aggregate::sum::Sum; +use torrust_tracker_metrics::metric_collection::{Error, MetricCollection}; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::statistics::UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; + +#[derive(Debug, PartialEq, Default, Serialize)] +pub struct Metrics { + /// A collection of metrics. + pub metric_collection: MetricCollection, +} + +impl Metrics { + /// # Errors + /// + /// This function returns an error if the metric does not exist and it + /// cannot be created. + pub fn increase_counter( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.increment_counter(metric_name, labels, now) + } + + /// # Errors + /// + /// This function returns an error if the metric does not exist and it + /// cannot be created. + pub fn set_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.set_gauge(metric_name, labels, value, now) + } +} + +impl Metrics { + /// Total number of UDP (UDP tracker) connections from IPv4 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_connections_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "connect")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_announces_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "announce")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_scrapes_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_connections_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "connect")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_announces_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_scrapes_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "scrape")].into(), + ) + .unwrap_or_default() as u64 + } +} diff --git a/packages/udp-tracker-core/src/statistics/mod.rs b/packages/udp-tracker-core/src/statistics/mod.rs new file mode 100644 index 000000000..fec76069e --- /dev/null +++ b/packages/udp-tracker-core/src/statistics/mod.rs @@ -0,0 +1,24 @@ +pub mod event; +pub mod metrics; +pub mod repository; +pub mod services; + +use metrics::Metrics; +use torrust_tracker_metrics::metric::description::MetricDescription; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_metrics::unit::Unit; + +const UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL: &str = "udp_tracker_core_requests_received_total"; + +#[must_use] +pub fn describe_metrics() -> Metrics { + let mut metrics = Metrics::default(); + + metrics.metric_collection.describe_counter( + &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("Total number of UDP requests received")), + ); + + metrics +} diff --git a/packages/udp-tracker-core/src/statistics/repository.rs b/packages/udp-tracker-core/src/statistics/repository.rs new file mode 100644 index 000000000..ceee0e369 --- /dev/null +++ b/packages/udp-tracker-core/src/statistics/repository.rs @@ -0,0 +1,54 @@ +use std::sync::Arc; + +use tokio::sync::{RwLock, RwLockReadGuard}; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::Error; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::describe_metrics; +use super::metrics::Metrics; + +/// A repository for the tracker metrics. +#[derive(Clone)] +pub struct Repository { + pub stats: Arc>, +} + +impl Default for Repository { + fn default() -> Self { + Self::new() + } +} + +impl Repository { + #[must_use] + pub fn new() -> Self { + Self { + stats: Arc::new(RwLock::new(describe_metrics())), + } + } + + pub async fn get_stats(&self) -> RwLockReadGuard<'_, Metrics> { + self.stats.read().await + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increase the counter. + pub async fn increase_counter( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.increase_counter(metric_name, labels, now); + + drop(stats_lock); + + result + } +} diff --git a/packages/udp-tracker-core/src/statistics/services.rs b/packages/udp-tracker-core/src/statistics/services.rs new file mode 100644 index 000000000..18a80bad1 --- /dev/null +++ b/packages/udp-tracker-core/src/statistics/services.rs @@ -0,0 +1,105 @@ +//! Statistics services. +//! +//! It includes: +//! +//! - A [`factory`](crate::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. +//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::statistics::metrics::Metrics). +//! +//! Tracker metrics are collected using a Publisher-Subscribe pattern. +//! +//! The factory function builds two structs: +//! +//! - An event [`Sender`](crate::event::sender::Sender) +//! - An statistics [`Repository`] +//! +//! ```text +//! let (stats_event_sender, stats_repository) = factory(tracker_usage_statistics); +//! ``` +//! +//! The statistics repository is responsible for storing the metrics in memory. +//! The statistics event sender allows sending events related to metrics. +//! There is an event listener that is receiving all the events and processing them with an event handler. +//! Then, the event handler updates the metrics depending on the received event. +//! +//! For example, if you send the event [`Event::Udp4Connect`](crate::statistics::event::Event::Udp4Connect): +//! +//! ```text +//! let result = event_sender.send_event(Event::Udp4Connect).await; +//! ``` +//! +//! Eventually the counter for UDP connections from IPv4 peers will be increased. +//! +//! ```rust,no_run +//! pub struct Metrics { +//! // ... +//! pub udp4_connections_handled: u64, // This will be incremented +//! // ... +//! } +//! ``` +use std::sync::Arc; + +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; + +use crate::statistics::metrics::Metrics; +use crate::statistics::repository::Repository; + +/// All the metrics collected by the tracker. +#[derive(Debug, PartialEq)] +pub struct TrackerMetrics { + /// Domain level metrics. + /// + /// General metrics for all torrents (number of seeders, leechers, etcetera) + pub torrents_metrics: AggregateActiveSwarmMetadata, + + /// Application level metrics. Usage statistics/metrics. + /// + /// Metrics about how the tracker is been used (number of udp announce requests, etcetera) + pub protocol_metrics: Metrics, +} + +/// It returns all the [`TrackerMetrics`] +pub async fn get_metrics( + in_memory_torrent_repository: Arc, + stats_repository: Arc, +) -> TrackerMetrics { + let torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata().await; + let stats = stats_repository.get_stats().await; + + TrackerMetrics { + torrents_metrics, + protocol_metrics: Metrics { + metric_collection: stats.metric_collection.clone(), + }, + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::{self}; + use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; + + use crate::statistics::describe_metrics; + use crate::statistics::repository::Repository; + use crate::statistics::services::{get_metrics, TrackerMetrics}; + + #[tokio::test] + async fn the_statistics_service_should_return_the_tracker_metrics() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let repository = Arc::new(Repository::new()); + + let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), repository.clone()).await; + + assert_eq!( + tracker_metrics, + TrackerMetrics { + torrents_metrics: AggregateActiveSwarmMetadata::default(), + protocol_metrics: describe_metrics(), + } + ); + } +} diff --git a/packages/udp-tracker-server/Cargo.toml b/packages/udp-tracker-server/Cargo.toml new file mode 100644 index 000000000..dc66572d8 --- /dev/null +++ b/packages/udp-tracker-server/Cargo.toml @@ -0,0 +1,46 @@ +[package] +authors.workspace = true +description = "The Torrust Bittorrent UDP tracker." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = [ "axum", "bittorrent", "server", "torrust", "tracker", "udp" ] +license.workspace = true +name = "torrust-udp-tracker-server" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +bittorrent-primitives = "0.1.0" +bittorrent-tracker-client = { version = "3.0.0-develop", path = "../tracker-client" } +bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } +bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "../udp-tracker-core" } +derive_more = { version = "2", features = [ "as_ref", "constructor", "from" ] } +futures = "0" +futures-util = "0" +ringbuf = "0" +serde = "1.0.219" +thiserror = "2" +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } +tokio-util = "0.7.15" +torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } +torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } +tracing = "0" +url = { version = "2", features = [ "serde" ] } +uuid = { version = "1", features = [ "v4" ] } +zerocopy = "0.7" + +[dev-dependencies] +local-ip-address = "0" +mockall = "0" +rand = "0" +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } diff --git a/packages/udp-tracker-server/LICENSE b/packages/udp-tracker-server/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/udp-tracker-server/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/udp-tracker-server/README.md b/packages/udp-tracker-server/README.md new file mode 100644 index 000000000..bdf147104 --- /dev/null +++ b/packages/udp-tracker-server/README.md @@ -0,0 +1,11 @@ +# Torrust UDP Tracker + +The Torrust Bittorrent UDP tracker. + +## Documentation + +[Crate documentation](https://docs.rs/torrust-udp-tracker-server). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/udp-tracker-server/src/banning/event/handler.rs b/packages/udp-tracker-server/src/banning/event/handler.rs new file mode 100644 index 000000000..4876323a8 --- /dev/null +++ b/packages/udp-tracker-server/src/banning/event/handler.rs @@ -0,0 +1,47 @@ +use std::sync::Arc; + +use bittorrent_udp_tracker_core::services::banning::BanService; +use tokio::sync::RwLock; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::{ErrorKind, Event}; +use crate::statistics::repository::Repository; +use crate::statistics::UDP_TRACKER_SERVER_IPS_BANNED_TOTAL; + +pub async fn handle_event( + event: Event, + ban_service: &Arc>, + repository: &Repository, + now: DurationSinceUnixEpoch, +) { + if let Event::UdpError { + context, + kind: _, + error: ErrorKind::ConnectionCookie(_msg), + } = event + { + let mut ban_service = ban_service.write().await; + + ban_service.increase_counter(&context.client_socket_addr().ip()); + + update_metric_for_banned_ips_total(repository, ban_service.get_banned_ips_total(), now).await; + } +} + +#[allow(clippy::cast_precision_loss)] +async fn update_metric_for_banned_ips_total(repository: &Repository, ips_banned_total: usize, now: DurationSinceUnixEpoch) { + match repository + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), + &LabelSet::default(), + ips_banned_total as f64, + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + } +} diff --git a/packages/udp-tracker-server/src/banning/event/listener.rs b/packages/udp-tracker-server/src/banning/event/listener.rs new file mode 100644 index 000000000..0d579f912 --- /dev/null +++ b/packages/udp-tracker-server/src/banning/event/listener.rs @@ -0,0 +1,68 @@ +use std::sync::Arc; + +use bittorrent_udp_tracker_core::services::banning::BanService; +use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; +use tokio::sync::RwLock; +use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_events::receiver::RecvError; + +use super::handler::handle_event; +use crate::event::receiver::Receiver; +use crate::statistics::repository::Repository; +use crate::CurrentClock; + +#[must_use] +pub fn run_event_listener( + receiver: Receiver, + cancellation_token: CancellationToken, + ban_service: &Arc>, + repository: &Arc, +) -> JoinHandle<()> { + let ban_service_clone = ban_service.clone(); + let repository_clone = repository.clone(); + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker server event listener (banning)"); + + tokio::spawn(async move { + dispatch_events(receiver, cancellation_token, ban_service_clone, repository_clone).await; + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "UDP tracker server event listener (banning) finished"); + }) +} + +async fn dispatch_events( + mut receiver: Receiver, + cancellation_token: CancellationToken, + ban_service: Arc>, + repository: Arc, +) { + loop { + tokio::select! { + biased; + + () = cancellation_token.cancelled() => { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Received cancellation request, shutting down UDP tracker server event listener."); + break; + } + + result = receiver.recv() => { + match result { + Ok(event) => handle_event(event, &ban_service, &repository, CurrentClock::now()).await, + Err(e) => { + match e { + RecvError::Closed => { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp tracker server receiver (banning) closed."); + break; + } + RecvError::Lagged(n) => { + tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp tracker server receiver (banning) lagged by {} events.", n); + } + } + } + } + } + } + } +} diff --git a/packages/udp-tracker-server/src/banning/event/mod.rs b/packages/udp-tracker-server/src/banning/event/mod.rs new file mode 100644 index 000000000..dae683398 --- /dev/null +++ b/packages/udp-tracker-server/src/banning/event/mod.rs @@ -0,0 +1,2 @@ +pub mod handler; +pub mod listener; diff --git a/packages/udp-tracker-server/src/banning/mod.rs b/packages/udp-tracker-server/src/banning/mod.rs new file mode 100644 index 000000000..53f112654 --- /dev/null +++ b/packages/udp-tracker-server/src/banning/mod.rs @@ -0,0 +1 @@ +pub mod event; diff --git a/packages/udp-tracker-server/src/container.rs b/packages/udp-tracker-server/src/container.rs new file mode 100644 index 000000000..365db4ca7 --- /dev/null +++ b/packages/udp-tracker-server/src/container.rs @@ -0,0 +1,54 @@ +use std::sync::Arc; + +use torrust_tracker_configuration::Core; + +use crate::event::bus::EventBus; +use crate::event::sender::Broadcaster; +use crate::event::{self}; +use crate::statistics; +use crate::statistics::repository::Repository; + +pub struct UdpTrackerServerContainer { + pub event_bus: Arc, + pub stats_event_sender: crate::event::sender::Sender, + pub stats_repository: Arc, +} + +impl UdpTrackerServerContainer { + #[must_use] + pub fn initialize(core_config: &Arc) -> Arc { + let udp_tracker_server_services = UdpTrackerServerServices::initialize(core_config); + + Arc::new(Self { + event_bus: udp_tracker_server_services.event_bus.clone(), + stats_event_sender: udp_tracker_server_services.stats_event_sender.clone(), + stats_repository: udp_tracker_server_services.stats_repository.clone(), + }) + } +} + +pub struct UdpTrackerServerServices { + pub event_bus: Arc, + pub stats_event_sender: crate::event::sender::Sender, + pub stats_repository: Arc, +} + +impl UdpTrackerServerServices { + #[must_use] + pub fn initialize(core_config: &Arc) -> Arc { + let udp_server_broadcaster = Broadcaster::default(); + let udp_server_stats_repository = Arc::new(Repository::new()); + let udp_server_stats_event_bus = Arc::new(EventBus::new( + core_config.tracker_usage_statistics.into(), + udp_server_broadcaster.clone(), + )); + + let udp_server_stats_event_sender = udp_server_stats_event_bus.sender(); + + Arc::new(Self { + event_bus: udp_server_stats_event_bus.clone(), + stats_event_sender: udp_server_stats_event_sender.clone(), + stats_repository: udp_server_stats_repository.clone(), + }) + } +} diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs new file mode 100644 index 000000000..13e18ba9b --- /dev/null +++ b/packages/udp-tracker-server/src/environment.rs @@ -0,0 +1,237 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use bittorrent_tracker_core::container::TrackerCoreContainer; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; +use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; +use torrust_server_lib::registar::Registar; +use torrust_tracker_configuration::{logging, Configuration, DEFAULT_TIMEOUT}; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; + +use crate::container::UdpTrackerServerContainer; +use crate::server::spawner::Spawner; +use crate::server::states::{Running, Stopped}; +use crate::server::Server; + +pub type Started = Environment; + +pub struct Environment +where + S: std::fmt::Debug + std::fmt::Display, +{ + pub container: Arc, + pub registar: Registar, + pub server: Server, + pub udp_core_event_listener_job: Option>, + pub udp_server_stats_event_listener_job: Option>, + pub udp_server_banning_event_listener_job: Option>, + pub cancellation_token: CancellationToken, +} + +impl Environment { + #[allow(dead_code)] + #[must_use] + pub fn new(configuration: &Arc) -> Self { + initialize_global_services(configuration); + + let container = Arc::new(EnvContainer::initialize(configuration)); + + let bind_to = container.udp_tracker_core_container.udp_tracker_config.bind_address; + + let server = Server::new(Spawner::new(bind_to)); + + Self { + container, + registar: Registar::default(), + server, + udp_core_event_listener_job: None, + udp_server_stats_event_listener_job: None, + udp_server_banning_event_listener_job: None, + cancellation_token: CancellationToken::new(), + } + } + + /// Starts the test environment and return a running environment. + /// + /// # Panics + /// + /// Will panic if it cannot start the server. + #[allow(dead_code)] + pub async fn start(self) -> Environment { + let cookie_lifetime = self.container.udp_tracker_core_container.udp_tracker_config.cookie_lifetime; + + // Start the UDP tracker core event listener + let udp_core_event_listener_job = Some(bittorrent_udp_tracker_core::statistics::event::listener::run_event_listener( + self.container.udp_tracker_core_container.event_bus.receiver(), + self.cancellation_token.clone(), + &self.container.udp_tracker_core_container.stats_repository, + )); + + // Start the UDP tracker server event listener (statistics) + let udp_server_stats_event_listener_job = Some(crate::statistics::event::listener::run_event_listener( + self.container.udp_tracker_server_container.event_bus.receiver(), + self.cancellation_token.clone(), + &self.container.udp_tracker_server_container.stats_repository, + )); + + // Start the UDP tracker server event listener (banning) + let udp_server_banning_event_listener_job = Some(crate::banning::event::listener::run_event_listener( + self.container.udp_tracker_server_container.event_bus.receiver(), + self.cancellation_token.clone(), + &self.container.udp_tracker_core_container.ban_service, + &self.container.udp_tracker_server_container.stats_repository, + )); + + // Start the UDP tracker server + let server = self + .server + .start( + self.container.udp_tracker_core_container.clone(), + self.container.udp_tracker_server_container.clone(), + self.registar.give_form(), + cookie_lifetime, + ) + .await + .expect("Failed to start the UDP tracker server"); + + Environment { + container: self.container.clone(), + registar: self.registar.clone(), + server, + udp_core_event_listener_job, + udp_server_stats_event_listener_job, + udp_server_banning_event_listener_job, + cancellation_token: self.cancellation_token, + } + } +} + +impl Environment { + /// # Panics + /// + /// Will panic if it cannot start the server within the timeout. + pub async fn new(configuration: &Arc) -> Self { + tokio::time::timeout(DEFAULT_TIMEOUT, Environment::::new(configuration).start()) + .await + .expect("Failed to create a UDP tracker server running environment within the timeout") + } + + /// Stops the test environment and return a stopped environment. + /// + /// # Panics + /// + /// Will panic if it cannot stop the service within the timeout. + #[allow(dead_code)] + pub async fn stop(self) -> Environment { + // Stop the UDP tracker core event listener + if let Some(udp_core_event_listener_job) = self.udp_core_event_listener_job { + // todo: send a message to the event listener to stop and wait for + // it to finish + udp_core_event_listener_job.abort(); + } + + // Stop the UDP tracker server event listener (statistics) + if let Some(udp_server_stats_event_listener_job) = self.udp_server_stats_event_listener_job { + // todo: send a message to the event listener to stop and wait for + // it to finish + udp_server_stats_event_listener_job.abort(); + } + + // Stop the UDP tracker server event listener (banning) + if let Some(udp_server_banning_event_listener_job) = self.udp_server_banning_event_listener_job { + // todo: send a message to the event listener to stop and wait for + // it to finish + udp_server_banning_event_listener_job.abort(); + } + + // Stop the UDP tracker server + let server = tokio::time::timeout(DEFAULT_TIMEOUT, self.server.stop()) + .await + .expect("Failed to stop the UDP tracker server within the timeout") + .expect("Failed to stop the UDP tracker server"); + + Environment { + container: self.container, + registar: Registar::default(), + server, + udp_core_event_listener_job: None, + udp_server_stats_event_listener_job: None, + udp_server_banning_event_listener_job: None, + cancellation_token: self.cancellation_token, + } + } + + #[must_use] + pub fn bind_address(&self) -> SocketAddr { + self.server.state.local_addr + } +} + +pub struct EnvContainer { + pub tracker_core_container: Arc, + pub udp_tracker_core_container: Arc, + pub udp_tracker_server_container: Arc, +} + +impl EnvContainer { + /// # Panics + /// + /// Will panic if the configuration is missing the UDP tracker configuration. + #[must_use] + pub fn initialize(configuration: &Configuration) -> Self { + let core_config = Arc::new(configuration.core.clone()); + let udp_tracker_configurations = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); + let udp_tracker_config = Arc::new(udp_tracker_configurations[0].clone()); + + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + core_config.tracker_usage_statistics.into(), + )); + + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + &core_config, + &swarm_coordination_registry_container, + )); + + let udp_tracker_core_container = + UdpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, &udp_tracker_config); + + let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); + + Self { + tracker_core_container, + udp_tracker_core_container, + udp_tracker_server_container, + } + } +} + +fn initialize_global_services(configuration: &Configuration) { + initialize_static(); + logging::setup(&configuration.logging); +} + +fn initialize_static() { + torrust_tracker_clock::initialize_static(); + bittorrent_udp_tracker_core::initialize_static(); +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use tokio::time::sleep; + use torrust_tracker_test_helpers::{configuration, logging}; + + use crate::environment::Started; + + #[tokio::test] + async fn it_should_make_and_stop_udp_server() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + sleep(Duration::from_secs(1)).await; + env.stop().await; + sleep(Duration::from_secs(1)).await; + } +} diff --git a/packages/udp-tracker-server/src/error.rs b/packages/udp-tracker-server/src/error.rs new file mode 100644 index 000000000..d260ebfd4 --- /dev/null +++ b/packages/udp-tracker-server/src/error.rs @@ -0,0 +1,100 @@ +//! Error types for the UDP server. +use std::fmt::Display; +use std::panic::Location; + +use aquatic_udp_protocol::{ConnectionId, RequestParseError, TransactionId}; +use bittorrent_udp_tracker_core::services::announce::UdpAnnounceError; +use bittorrent_udp_tracker_core::services::scrape::UdpScrapeError; +use derive_more::derive::Display; +use thiserror::Error; + +#[derive(Display, Debug)] +#[display(":?")] +pub struct ConnectionCookie(pub ConnectionId); + +/// Error returned by the UDP server. +#[derive(Error, Debug, Clone)] +pub enum Error { + /// Error returned when the request is invalid. + #[error("error parsing request: {request_parse_error:?}")] + InvalidRequest { request_parse_error: SendableRequestParseError }, + + /// Error returned when the domain tracker returns an announce error. + #[error("tracker announce error: {source}")] + AnnounceFailed { source: UdpAnnounceError }, + + /// Error returned when the domain tracker returns an scrape error. + #[error("tracker scrape error: {source}")] + ScrapeFailed { source: UdpScrapeError }, + + /// Error returned from a third-party library (`aquatic_udp_protocol`). + #[error("internal server error: {message}, {location}")] + Internal { + location: &'static Location<'static>, + message: String, + }, + + /// Error returned when tracker requires authentication. + #[error("domain tracker requires authentication but is not supported in current UDP implementation. Location: {location}")] + AuthRequired { location: &'static Location<'static> }, +} + +impl From for Error { + fn from(request_parse_error: RequestParseError) -> Self { + Self::InvalidRequest { + request_parse_error: request_parse_error.into(), + } + } +} + +impl From for Error { + fn from(udp_announce_error: UdpAnnounceError) -> Self { + Self::AnnounceFailed { + source: udp_announce_error, + } + } +} + +impl From for Error { + fn from(udp_scrape_error: UdpScrapeError) -> Self { + Self::ScrapeFailed { + source: udp_scrape_error, + } + } +} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub struct SendableRequestParseError { + pub message: String, + pub opt_connection_id: Option, + pub opt_transaction_id: Option, +} + +impl Display for SendableRequestParseError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "SendableRequestParseError: message: {}, connection_id: {:?}, transaction_id: {:?}", + self.message, self.opt_connection_id, self.opt_transaction_id + ) + } +} + +impl From for SendableRequestParseError { + fn from(request_parse_error: RequestParseError) -> Self { + let (message, opt_connection_id, opt_transaction_id) = match request_parse_error { + RequestParseError::Sendable { + connection_id, + transaction_id, + err, + } => ((*err).to_string(), Some(connection_id), Some(transaction_id)), + RequestParseError::Unsendable { err } => (err.to_string(), None, None), + }; + + Self { + message, + opt_connection_id, + opt_transaction_id, + } + } +} diff --git a/packages/udp-tracker-server/src/event.rs b/packages/udp-tracker-server/src/event.rs new file mode 100644 index 000000000..a7634d58e --- /dev/null +++ b/packages/udp-tracker-server/src/event.rs @@ -0,0 +1,192 @@ +use std::fmt; +use std::net::SocketAddr; +use std::time::Duration; + +use aquatic_udp_protocol::AnnounceRequest; +use bittorrent_tracker_core::error::{AnnounceError, ScrapeError}; +use bittorrent_udp_tracker_core::services::announce::UdpAnnounceError; +use bittorrent_udp_tracker_core::services::scrape::UdpScrapeError; +use torrust_tracker_metrics::label::{LabelSet, LabelValue}; +use torrust_tracker_metrics::label_name; +use torrust_tracker_primitives::service_binding::ServiceBinding; + +use crate::error::Error; + +/// A UDP server event. +#[derive(Debug, Clone, PartialEq)] +pub enum Event { + UdpRequestReceived { + context: ConnectionContext, + }, + UdpRequestAborted { + context: ConnectionContext, + }, + UdpRequestBanned { + context: ConnectionContext, + }, + UdpRequestAccepted { + context: ConnectionContext, + kind: UdpRequestKind, + }, + UdpResponseSent { + context: ConnectionContext, + kind: UdpResponseKind, + req_processing_time: Duration, + }, + UdpError { + context: ConnectionContext, + kind: Option, + error: ErrorKind, + }, +} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum UdpRequestKind { + Connect, + Announce { announce_request: AnnounceRequest }, + Scrape, +} + +impl From for LabelValue { + fn from(kind: UdpRequestKind) -> Self { + match kind { + UdpRequestKind::Connect => LabelValue::new("connect"), + UdpRequestKind::Announce { .. } => LabelValue::new("announce"), + UdpRequestKind::Scrape => LabelValue::new("scrape"), + } + } +} + +impl fmt::Display for UdpRequestKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let proto_str = match self { + UdpRequestKind::Connect => "connect", + UdpRequestKind::Announce { .. } => "announce", + UdpRequestKind::Scrape => "scrape", + }; + write!(f, "{proto_str}") + } +} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum UdpResponseKind { + Ok { + req_kind: UdpRequestKind, + }, + + /// There was an error handling the request. The error contains the request + /// kind if the request was parsed successfully. + Error { + opt_req_kind: Option, + }, +} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub struct ConnectionContext { + client_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, +} + +impl ConnectionContext { + #[must_use] + pub fn new(client_socket_addr: SocketAddr, server_service_binding: ServiceBinding) -> Self { + Self { + client_socket_addr, + server_service_binding, + } + } + + #[must_use] + pub fn client_socket_addr(&self) -> SocketAddr { + self.client_socket_addr + } + + #[must_use] + pub fn server_socket_addr(&self) -> SocketAddr { + self.server_service_binding.bind_address() + } +} + +impl From for LabelSet { + fn from(connection_context: ConnectionContext) -> Self { + LabelSet::from([ + ( + label_name!("server_binding_protocol"), + LabelValue::new(&connection_context.server_service_binding.protocol().to_string()), + ), + ( + label_name!("server_binding_ip"), + LabelValue::new(&connection_context.server_service_binding.bind_address().ip().to_string()), + ), + ( + label_name!("server_binding_address_ip_type"), + LabelValue::new(&connection_context.server_service_binding.bind_address_ip_type().to_string()), + ), + ( + label_name!("server_binding_address_ip_family"), + LabelValue::new(&connection_context.server_service_binding.bind_address_ip_family().to_string()), + ), + ( + label_name!("server_binding_port"), + LabelValue::new(&connection_context.server_service_binding.bind_address().port().to_string()), + ), + ]) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub enum ErrorKind { + RequestParse(String), + ConnectionCookie(String), + Whitelist(String), + Database(String), + InternalServer(String), + BadRequest(String), + TrackerAuthentication(String), +} + +impl From for ErrorKind { + fn from(error: Error) -> Self { + match error { + Error::InvalidRequest { request_parse_error } => Self::RequestParse(request_parse_error.to_string()), + Error::AnnounceFailed { source } => match source { + UdpAnnounceError::ConnectionCookieError { source } => Self::ConnectionCookie(source.to_string()), + UdpAnnounceError::TrackerCoreAnnounceError { source } => match source { + AnnounceError::Whitelist(whitelist_error) => Self::Whitelist(whitelist_error.to_string()), + AnnounceError::Database(error) => Self::Database(error.to_string()), + }, + UdpAnnounceError::TrackerCoreWhitelistError { source } => Self::Whitelist(source.to_string()), + }, + Error::ScrapeFailed { source } => match source { + UdpScrapeError::ConnectionCookieError { source } => Self::ConnectionCookie(source.to_string()), + UdpScrapeError::TrackerCoreScrapeError { source } => match source { + ScrapeError::Whitelist(whitelist_error) => Self::Whitelist(whitelist_error.to_string()), + }, + UdpScrapeError::TrackerCoreWhitelistError { source } => Self::Whitelist(source.to_string()), + }, + Error::Internal { location: _, message } => Self::InternalServer(message.clone()), + Error::AuthRequired { location } => Self::TrackerAuthentication(location.to_string()), + } + } +} + +pub mod sender { + use std::sync::Arc; + + use super::Event; + + pub type Sender = Option>>; + pub type Broadcaster = torrust_tracker_events::broadcaster::Broadcaster; +} + +pub mod receiver { + use super::Event; + + pub type Receiver = Box>; +} + +pub mod bus { + use crate::event::Event; + + pub type EventBus = torrust_tracker_events::bus::EventBus; +} diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs new file mode 100644 index 000000000..ea19611ce --- /dev/null +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -0,0 +1,986 @@ +//! UDP tracker announce handler. +use std::net::{IpAddr, SocketAddr}; +use std::ops::Range; +use std::sync::Arc; + +use aquatic_udp_protocol::{ + AnnounceInterval, AnnounceRequest, AnnounceResponse, AnnounceResponseFixedData, Ipv4AddrBytes, Ipv6AddrBytes, NumberOfPeers, + Port, Response, ResponsePeer, TransactionId, +}; +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_udp_tracker_core::services::announce::AnnounceService; +use torrust_tracker_configuration::Core; +use torrust_tracker_primitives::core::AnnounceData; +use torrust_tracker_primitives::service_binding::ServiceBinding; +use tracing::{instrument, Level}; +use zerocopy::network_endian::I32; + +use crate::error::Error; +use crate::event::{ConnectionContext, Event, UdpRequestKind}; + +/// It handles the `Announce` request. +/// +/// # Errors +/// +/// If a error happens in the `handle_announce` function, it will just return the `ServerError`. +#[instrument(fields(transaction_id, connection_id, info_hash), skip(announce_service, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] +pub async fn handle_announce( + announce_service: &Arc, + client_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, + request: &AnnounceRequest, + core_config: &Arc, + opt_udp_server_stats_event_sender: &crate::event::sender::Sender, + cookie_valid_range: Range, +) -> Result { + tracing::Span::current() + .record("transaction_id", request.transaction_id.0.to_string()) + .record("connection_id", request.connection_id.0.to_string()) + .record("info_hash", InfoHash::from_bytes(&request.info_hash.0).to_hex_string()); + + tracing::trace!("handle announce"); + + if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { + udp_server_stats_event_sender + .send(Event::UdpRequestAccepted { + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + kind: UdpRequestKind::Announce { + announce_request: *request, + }, + }) + .await; + } + + let announce_data = announce_service + .handle_announce(client_socket_addr, server_service_binding, request, cookie_valid_range) + .await + .map_err(|e| { + ( + e.into(), + request.transaction_id, + UdpRequestKind::Announce { + announce_request: *request, + }, + ) + })?; + + Ok(build_response(client_socket_addr, request, core_config, &announce_data)) +} + +fn build_response( + remote_addr: SocketAddr, + request: &AnnounceRequest, + core_config: &Arc, + announce_data: &AnnounceData, +) -> Response { + #[allow(clippy::cast_possible_truncation)] + if remote_addr.is_ipv4() { + let announce_response = AnnounceResponse { + fixed: AnnounceResponseFixedData { + transaction_id: request.transaction_id, + announce_interval: AnnounceInterval(I32::new(i64::from(core_config.announce_policy.interval) as i32)), + leechers: NumberOfPeers(I32::new(i64::from(announce_data.stats.incomplete) as i32)), + seeders: NumberOfPeers(I32::new(i64::from(announce_data.stats.complete) as i32)), + }, + peers: announce_data + .peers + .iter() + .filter_map(|peer| { + if let IpAddr::V4(ip) = peer.peer_addr.ip() { + Some(ResponsePeer:: { + ip_address: ip.into(), + port: Port(peer.peer_addr.port().into()), + }) + } else { + None + } + }) + .collect(), + }; + + Response::from(announce_response) + } else { + let announce_response = AnnounceResponse { + fixed: AnnounceResponseFixedData { + transaction_id: request.transaction_id, + announce_interval: AnnounceInterval(I32::new(i64::from(core_config.announce_policy.interval) as i32)), + leechers: NumberOfPeers(I32::new(i64::from(announce_data.stats.incomplete) as i32)), + seeders: NumberOfPeers(I32::new(i64::from(announce_data.stats.complete) as i32)), + }, + peers: announce_data + .peers + .iter() + .filter_map(|peer| { + if let IpAddr::V6(ip) = peer.peer_addr.ip() { + Some(ResponsePeer:: { + ip_address: ip.into(), + port: Port(peer.peer_addr.port().into()), + }) + } else { + None + } + }) + .collect(), + }; + + Response::from(announce_response) + } +} + +#[cfg(test)] +pub(crate) mod tests { + + pub mod announce_request { + + use std::net::Ipv4Addr; + use std::num::NonZeroU16; + + use aquatic_udp_protocol::{ + AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectionId, NumberOfBytes, NumberOfPeers, + PeerId as AquaticPeerId, PeerKey, Port, TransactionId, + }; + use bittorrent_udp_tracker_core::connection_cookie::make; + + use crate::handlers::tests::{sample_ipv4_remote_addr_fingerprint, sample_issue_time}; + + pub struct AnnounceRequestBuilder { + request: AnnounceRequest, + } + + impl AnnounceRequestBuilder { + pub fn default() -> AnnounceRequestBuilder { + let client_ip = Ipv4Addr::new(126, 0, 0, 1); + let client_port = 8080; + let info_hash_aquatic = aquatic_udp_protocol::InfoHash([0u8; 20]); + + let default_request = AnnounceRequest { + connection_id: make(sample_ipv4_remote_addr_fingerprint(), sample_issue_time()).unwrap(), + action_placeholder: AnnounceActionPlaceholder::default(), + transaction_id: TransactionId(0i32.into()), + info_hash: info_hash_aquatic, + peer_id: AquaticPeerId([255u8; 20]), + bytes_downloaded: NumberOfBytes(0i64.into()), + bytes_uploaded: NumberOfBytes(0i64.into()), + bytes_left: NumberOfBytes(0i64.into()), + event: AnnounceEvent::Started.into(), + ip_address: client_ip.into(), + key: PeerKey::new(0i32), + peers_wanted: NumberOfPeers::new(1i32), + port: Port::new(NonZeroU16::new(client_port).expect("a non-zero client port")), + }; + AnnounceRequestBuilder { + request: default_request, + } + } + + pub fn with_connection_id(mut self, connection_id: ConnectionId) -> Self { + self.request.connection_id = connection_id; + self + } + + pub fn with_info_hash(mut self, info_hash: aquatic_udp_protocol::InfoHash) -> Self { + self.request.info_hash = info_hash; + self + } + + pub fn with_peer_id(mut self, peer_id: AquaticPeerId) -> Self { + self.request.peer_id = peer_id; + self + } + + pub fn with_ip_address(mut self, ip_address: Ipv4Addr) -> Self { + self.request.ip_address = ip_address.into(); + self + } + + pub fn with_port(mut self, port: u16) -> Self { + self.request.port = Port(port.into()); + self + } + + pub fn into(self) -> AnnounceRequest { + self.request + } + } + + mod using_ipv4 { + + use std::future; + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{ + AnnounceInterval, AnnounceResponse, AnnounceResponseFixedData, InfoHash as AquaticInfoHash, Ipv4AddrBytes, + Ipv6AddrBytes, NumberOfPeers, PeerId as AquaticPeerId, Response, ResponsePeer, + }; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; + use mockall::predicate::eq; + use torrust_tracker_events::bus::SenderStatus; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event, UdpRequestKind}; + use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::handlers::handle_announce; + use crate::handlers::tests::{ + initialize_core_tracker_services_for_default_tracker_configuration, + initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_socket_address, + sample_issue_time, CoreTrackerServices, CoreUdpTrackerServices, MockUdpServerStatsEventSender, + }; + + #[tokio::test] + async fn an_announced_peer_should_be_added_to_the_tracker() { + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); + + let client_ip = Ipv4Addr::new(126, 0, 0, 1); + let client_port = 8080; + let info_hash = AquaticInfoHash([0u8; 20]); + let peer_id = AquaticPeerId([255u8; 20]); + + let client_socket_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) + .with_info_hash(info_hash) + .with_peer_id(peer_id) + .with_ip_address(client_ip) + .with_port(client_port) + .into(); + + handle_announce( + &core_udp_tracker_services.announce_service, + client_socket_addr, + server_service_binding, + &request, + &core_tracker_services.core_config, + &server_udp_tracker_services.udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let peers = core_tracker_services + .in_memory_torrent_repository + .get_torrent_peers(&info_hash.0.into()) + .await; + + let expected_peer = PeerBuilder::default() + .with_peer_id(&peer_id) + .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip), client_port)) + .updated_on(peers[0].updated) + .into(); + + assert_eq!(peers[0], Arc::new(expected_peer)); + } + + #[tokio::test] + async fn the_announced_peer_should_not_be_included_in_the_response() { + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); + + let client_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) + .into(); + + let response = handle_announce( + &core_udp_tracker_services.announce_service, + client_socket_addr, + server_service_binding, + &request, + &core_tracker_services.core_config, + &server_udp_tracker_services.udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let empty_peer_vector: Vec> = vec![]; + assert_eq!( + response, + Response::from(AnnounceResponse { + fixed: AnnounceResponseFixedData { + transaction_id: request.transaction_id, + announce_interval: AnnounceInterval(120i32.into()), + leechers: NumberOfPeers(0i32.into()), + seeders: NumberOfPeers(1i32.into()), + }, + peers: empty_peer_vector + }) + ); + } + + #[tokio::test] + async fn the_tracker_should_always_use_the_remote_client_ip_but_not_the_port_in_the_udp_request_header_instead_of_the_peer_address_in_the_announce_request( + ) { + // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): + // "Do note that most trackers will only honor the IP address field under limited circumstances." + + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); + + let info_hash = AquaticInfoHash([0u8; 20]); + let peer_id = AquaticPeerId([255u8; 20]); + let client_port = 8080; + + let remote_client_ip = Ipv4Addr::new(126, 0, 0, 1); + let remote_client_port = 8081; + let peer_address = Ipv4Addr::new(126, 0, 0, 2); + + let client_socket_addr = SocketAddr::new(IpAddr::V4(remote_client_ip), remote_client_port); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) + .with_info_hash(info_hash) + .with_peer_id(peer_id) + .with_ip_address(peer_address) + .with_port(client_port) + .into(); + + handle_announce( + &core_udp_tracker_services.announce_service, + client_socket_addr, + server_service_binding, + &request, + &core_tracker_services.core_config, + &server_udp_tracker_services.udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let peers = core_tracker_services + .in_memory_torrent_repository + .get_torrent_peers(&info_hash.0.into()) + .await; + + assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V4(remote_client_ip), client_port)); + } + + async fn add_a_torrent_peer_using_ipv6(in_memory_torrent_repository: &Arc) { + let info_hash = AquaticInfoHash([0u8; 20]); + + let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); + let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); + let client_port = 8080; + let peer_id = AquaticPeerId([255u8; 20]); + + let peer_using_ipv6 = PeerBuilder::default() + .with_peer_id(&peer_id) + .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) + .into(); + + in_memory_torrent_repository + .handle_announcement(&info_hash.0.into(), &peer_using_ipv6, None) + .await; + } + + async fn announce_a_new_peer_using_ipv4( + core_tracker_services: Arc, + core_udp_tracker_services: Arc, + ) -> Response { + let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); + let event_bus = Arc::new(crate::event::bus::EventBus::new( + SenderStatus::Disabled, + udp_server_broadcaster.clone(), + )); + + let udp_server_stats_event_sender = event_bus.sender(); + + let client_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) + .into(); + + handle_announce( + &core_udp_tracker_services.announce_service, + client_socket_addr, + server_service_binding, + &request, + &core_tracker_services.core_config, + &udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap() + } + + #[tokio::test] + async fn when_the_announce_request_comes_from_a_client_using_ipv4_the_response_should_not_include_peers_using_ipv6() { + let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); + + add_a_torrent_peer_using_ipv6(&core_tracker_services.in_memory_torrent_repository).await; + + let response = + announce_a_new_peer_using_ipv4(Arc::new(core_tracker_services), Arc::new(core_udp_tracker_services)).await; + + // The response should not contain the peer using IPV6 + let peers: Option>> = match response { + Response::AnnounceIpv6(announce_response) => Some(announce_response.peers), + _ => None, + }; + let no_ipv6_peers = peers.is_none(); + assert!(no_ipv6_peers); + } + + #[tokio::test] + async fn should_send_the_upd4_announce_event() { + let client_socket_addr = sample_ipv4_socket_address(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + let announce_request = AnnounceRequestBuilder::default().into(); + + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); + udp_server_stats_event_sender_mock + .expect_send() + .with(eq(Event::UdpRequestAccepted { + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + kind: UdpRequestKind::Announce { announce_request }, + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let udp_server_stats_event_sender: crate::event::sender::Sender = + Some(Arc::new(udp_server_stats_event_sender_mock)); + + let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = + initialize_core_tracker_services_for_default_tracker_configuration(); + + handle_announce( + &core_udp_tracker_services.announce_service, + client_socket_addr, + server_service_binding, + &announce_request, + &core_tracker_services.core_config, + &udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + } + + mod from_a_loopback_ip { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; + use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::handlers::handle_announce; + use crate::handlers::tests::{ + initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_issue_time, + }; + + #[tokio::test] + async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration_if_defined() { + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); + + let client_ip = Ipv4Addr::LOCALHOST; + let client_port = 8080; + let info_hash = AquaticInfoHash([0u8; 20]); + let peer_id = AquaticPeerId([255u8; 20]); + + let client_socket_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) + .with_info_hash(info_hash) + .with_peer_id(peer_id) + .with_ip_address(client_ip) + .with_port(client_port) + .into(); + + handle_announce( + &core_udp_tracker_services.announce_service, + client_socket_addr, + server_service_binding, + &request, + &core_tracker_services.core_config, + &server_udp_tracker_services.udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let peers = core_tracker_services + .in_memory_torrent_repository + .get_torrent_peers(&info_hash.0.into()) + .await; + + let external_ip_in_tracker_configuration = core_tracker_services.core_config.net.external_ip.unwrap(); + + let expected_peer = PeerBuilder::default() + .with_peer_id(&peer_id) + .with_peer_address(SocketAddr::new(external_ip_in_tracker_configuration, client_port)) + .updated_on(peers[0].updated) + .into(); + + assert_eq!(peers[0], Arc::new(expected_peer)); + } + } + } + + mod using_ipv6 { + + use std::future; + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{ + AnnounceInterval, AnnounceResponse, AnnounceResponseFixedData, InfoHash as AquaticInfoHash, Ipv4AddrBytes, + Ipv6AddrBytes, NumberOfPeers, PeerId as AquaticPeerId, Response, ResponsePeer, + }; + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::whitelist; + use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; + use bittorrent_udp_tracker_core::event::bus::EventBus; + use bittorrent_udp_tracker_core::event::sender::Broadcaster; + use bittorrent_udp_tracker_core::services::announce::AnnounceService; + use mockall::predicate::eq; + use torrust_tracker_configuration::Core; + use torrust_tracker_events::bus::SenderStatus; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event, UdpRequestKind}; + use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::handlers::handle_announce; + use crate::handlers::tests::{ + initialize_core_tracker_services_for_default_tracker_configuration, + initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, + sample_issue_time, MockUdpServerStatsEventSender, + }; + + #[tokio::test] + async fn an_announced_peer_should_be_added_to_the_tracker() { + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); + + let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); + let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); + let client_port = 8080; + let info_hash = AquaticInfoHash([0u8; 20]); + let peer_id = AquaticPeerId([255u8; 20]); + + let client_socket_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); + let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) + .with_info_hash(info_hash) + .with_peer_id(peer_id) + .with_ip_address(client_ip_v4) + .with_port(client_port) + .into(); + + handle_announce( + &core_udp_tracker_services.announce_service, + client_socket_addr, + server_service_binding, + &request, + &core_tracker_services.core_config, + &server_udp_tracker_services.udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let peers = core_tracker_services + .in_memory_torrent_repository + .get_torrent_peers(&info_hash.0.into()) + .await; + + let expected_peer = PeerBuilder::default() + .with_peer_id(&peer_id) + .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) + .updated_on(peers[0].updated) + .into(); + + assert_eq!(peers[0], Arc::new(expected_peer)); + } + + #[tokio::test] + async fn the_announced_peer_should_not_be_included_in_the_response() { + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); + + let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); + let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); + + let client_socket_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), 8080); + let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) + .into(); + + let response = handle_announce( + &core_udp_tracker_services.announce_service, + client_socket_addr, + server_service_binding, + &request, + &core_tracker_services.core_config, + &server_udp_tracker_services.udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let empty_peer_vector: Vec> = vec![]; + assert_eq!( + response, + Response::from(AnnounceResponse { + fixed: AnnounceResponseFixedData { + transaction_id: request.transaction_id, + announce_interval: AnnounceInterval(120i32.into()), + leechers: NumberOfPeers(0i32.into()), + seeders: NumberOfPeers(1i32.into()), + }, + peers: empty_peer_vector + }) + ); + } + + #[tokio::test] + async fn the_tracker_should_always_use_the_remote_client_ip_but_not_the_port_in_the_udp_request_header_instead_of_the_peer_address_in_the_announce_request( + ) { + // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): + // "Do note that most trackers will only honor the IP address field under limited circumstances." + + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_service) = + initialize_core_tracker_services_for_public_tracker(); + + let info_hash = AquaticInfoHash([0u8; 20]); + let peer_id = AquaticPeerId([255u8; 20]); + let client_port = 8080; + + let remote_client_ip = "::100".parse().unwrap(); // IPV4 ::0.0.1.0 -> IPV6 = ::100 = ::ffff:0:100 = 0:0:0:0:0:ffff:0:0100 + let remote_client_port = 8081; + let peer_address = "126.0.0.1".parse().unwrap(); + + let client_socket_addr = SocketAddr::new(IpAddr::V6(remote_client_ip), remote_client_port); + let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) + .with_info_hash(info_hash) + .with_peer_id(peer_id) + .with_ip_address(peer_address) + .with_port(client_port) + .into(); + + handle_announce( + &core_udp_tracker_services.announce_service, + client_socket_addr, + server_service_binding, + &request, + &core_tracker_services.core_config, + &server_udp_tracker_service.udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let peers = core_tracker_services + .in_memory_torrent_repository + .get_torrent_peers(&info_hash.0.into()) + .await; + + // When using IPv6 the tracker converts the remote client ip into a IPv4 address + assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V6(remote_client_ip), client_port)); + } + + async fn add_a_torrent_peer_using_ipv4(in_memory_torrent_repository: &Arc) { + let info_hash = AquaticInfoHash([0u8; 20]); + + let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); + let client_port = 8080; + let peer_id = AquaticPeerId([255u8; 20]); + + let peer_using_ipv4 = PeerBuilder::default() + .with_peer_id(&peer_id) + .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip_v4), client_port)) + .into(); + + in_memory_torrent_repository + .handle_announcement(&info_hash.0.into(), &peer_using_ipv4, None) + .await; + } + + async fn announce_a_new_peer_using_ipv6( + core_config: Arc, + announce_handler: Arc, + whitelist_authorization: Arc, + ) -> Response { + let udp_core_broadcaster = Broadcaster::default(); + let core_event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); + let udp_core_stats_event_sender = core_event_bus.sender(); + + let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); + let server_event_bus = Arc::new(crate::event::bus::EventBus::new( + SenderStatus::Disabled, + udp_server_broadcaster.clone(), + )); + + let udp_server_stats_event_sender = server_event_bus.sender(); + + let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); + let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); + let client_port = 8080; + + let client_socket_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); + let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) + .into(); + + let announce_service = Arc::new(AnnounceService::new( + announce_handler.clone(), + whitelist_authorization.clone(), + udp_core_stats_event_sender.clone(), + )); + + handle_announce( + &announce_service, + client_socket_addr, + server_service_binding, + &request, + &core_config, + &udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap() + } + + #[tokio::test] + async fn when_the_announce_request_comes_from_a_client_using_ipv6_the_response_should_not_include_peers_using_ipv4() { + let (core_tracker_services, _core_udp_tracker_services, _server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); + + add_a_torrent_peer_using_ipv4(&core_tracker_services.in_memory_torrent_repository).await; + + let response = announce_a_new_peer_using_ipv6( + core_tracker_services.core_config.clone(), + core_tracker_services.announce_handler.clone(), + core_tracker_services.whitelist_authorization, + ) + .await; + + // The response should not contain the peer using IPV4 + let peers: Option>> = match response { + Response::AnnounceIpv4(announce_response) => Some(announce_response.peers), + _ => None, + }; + let no_ipv4_peers = peers.is_none(); + assert!(no_ipv4_peers); + } + + #[tokio::test] + async fn should_send_the_upd6_announce_event() { + let client_socket_addr = sample_ipv6_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let announce_request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) + .into(); + + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); + udp_server_stats_event_sender_mock + .expect_send() + .with(eq(Event::UdpRequestAccepted { + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + kind: UdpRequestKind::Announce { announce_request }, + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let udp_server_stats_event_sender: crate::event::sender::Sender = + Some(Arc::new(udp_server_stats_event_sender_mock)); + + let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = + initialize_core_tracker_services_for_default_tracker_configuration(); + + handle_announce( + &core_udp_tracker_services.announce_service, + client_socket_addr, + server_service_binding, + &announce_request, + &core_tracker_services.core_config, + &udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + } + + mod from_a_loopback_ip { + use std::future; + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::databases::setup::initialize_database; + use bittorrent_tracker_core::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; + use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; + use bittorrent_udp_tracker_core::services::announce::AnnounceService; + use bittorrent_udp_tracker_core::{self, event as core_event}; + use mockall::predicate::{self, eq}; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event, UdpRequestKind}; + use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::handlers::handle_announce; + use crate::handlers::tests::{ + sample_cookie_valid_range, sample_issue_time, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, + TrackerConfigurationBuilder, + }; + use crate::tests::{announce_events_match, sample_peer}; + + #[tokio::test] + async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { + let config = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); + + let loopback_ipv4 = Ipv4Addr::LOCALHOST; + let loopback_ipv6 = Ipv6Addr::LOCALHOST; + + let client_ip_v4 = loopback_ipv4; + let client_ip_v6 = loopback_ipv6; + let client_port = 8080; + + let info_hash = AquaticInfoHash([0u8; 20]); + let peer_id = AquaticPeerId([255u8; 20]); + let mut announcement = sample_peer(); + announcement.peer_id = peer_id; + announcement.peer_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x7e00, 1)), client_port); + + let client_socket_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); + let mut server_socket_addr = config.udp_trackers.clone().unwrap()[0].bind_address; + if server_socket_addr.port() == 0 { + // Port 0 cannot be use in service binding + server_socket_addr.set_port(6969); + } + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + let server_service_binding_clone = server_service_binding.clone(); + + let database = initialize_database(&config.core); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = + Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) + .with_info_hash(info_hash) + .with_peer_id(peer_id) + .with_ip_address(client_ip_v4) + .with_port(client_port) + .into(); + + let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); + udp_core_stats_event_sender_mock + .expect_send() + .with(predicate::function(move |event| { + let expected_event = core_event::Event::UdpAnnounce { + connection: core_event::ConnectionContext::new( + client_socket_addr, + server_service_binding.clone(), + ), + info_hash: info_hash.into(), + announcement, + }; + + announce_events_match(event, &expected_event) + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let udp_core_stats_event_sender: bittorrent_udp_tracker_core::event::sender::Sender = + Some(Arc::new(udp_core_stats_event_sender_mock)); + + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); + udp_server_stats_event_sender_mock + .expect_send() + .with(eq(Event::UdpRequestAccepted { + context: ConnectionContext::new(client_socket_addr, server_service_binding_clone.clone()), + kind: UdpRequestKind::Announce { + announce_request: request, + }, + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let udp_server_stats_event_sender: crate::event::sender::Sender = + Some(Arc::new(udp_server_stats_event_sender_mock)); + + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_downloads_metric_repository, + )); + + let core_config = Arc::new(config.core.clone()); + + let announce_service = Arc::new(AnnounceService::new( + announce_handler.clone(), + whitelist_authorization.clone(), + udp_core_stats_event_sender.clone(), + )); + + handle_announce( + &announce_service, + client_socket_addr, + server_service_binding_clone, + &request, + &core_config, + &udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()).await; + + let external_ip_in_tracker_configuration = core_config.net.external_ip.unwrap(); + + assert!(external_ip_in_tracker_configuration.is_ipv6()); + + // There's a special type of IPv6 addresses that provide compatibility with IPv4. + // The last 32 bits of these addresses represent an IPv4, and are represented like this: + // 1111:2222:3333:4444:5555:6666:1.2.3.4 + // + // ::127.0.0.1 is the IPV6 representation for the IPV4 address 127.0.0.1. + assert_eq!(Ok(peers[0].peer_addr.ip()), "::126.0.0.1".parse()); + } + } + } + } +} diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs new file mode 100644 index 000000000..961189945 --- /dev/null +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -0,0 +1,291 @@ +//! UDP tracker connect handler. +use std::net::SocketAddr; +use std::sync::Arc; + +use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, ConnectionId, Response}; +use bittorrent_udp_tracker_core::services::connect::ConnectService; +use torrust_tracker_primitives::service_binding::ServiceBinding; +use tracing::{instrument, Level}; + +use crate::event::{ConnectionContext, Event, UdpRequestKind}; + +/// It handles the `Connect` request. +#[instrument(fields(transaction_id), skip(connect_service, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] +pub async fn handle_connect( + client_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, + request: &ConnectRequest, + connect_service: &Arc, + opt_udp_server_stats_event_sender: &crate::event::sender::Sender, + cookie_issue_time: f64, +) -> Response { + tracing::Span::current().record("transaction_id", request.transaction_id.0.to_string()); + tracing::trace!("handle connect"); + + if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { + udp_server_stats_event_sender + .send(Event::UdpRequestAccepted { + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + kind: UdpRequestKind::Connect, + }) + .await; + } + + let connection_id = connect_service + .handle_connect(client_socket_addr, server_service_binding, cookie_issue_time) + .await; + + build_response(*request, connection_id) +} + +fn build_response(request: ConnectRequest, connection_id: ConnectionId) -> Response { + let response = ConnectResponse { + transaction_id: request.transaction_id, + connection_id, + }; + + Response::from(response) +} + +#[cfg(test)] +mod tests { + + mod connect_request { + + use std::future; + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response, TransactionId}; + use bittorrent_udp_tracker_core::connection_cookie::make; + use bittorrent_udp_tracker_core::event as core_event; + use bittorrent_udp_tracker_core::event::bus::EventBus; + use bittorrent_udp_tracker_core::event::sender::Broadcaster; + use bittorrent_udp_tracker_core::services::connect::ConnectService; + use mockall::predicate::eq; + use torrust_tracker_events::bus::SenderStatus; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event, UdpRequestKind}; + use crate::handlers::handle_connect; + use crate::handlers::tests::{ + sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv4_socket_address, sample_ipv6_remote_addr, + sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, + }; + + fn sample_connect_request() -> ConnectRequest { + ConnectRequest { + transaction_id: TransactionId(0i32.into()), + } + } + + #[tokio::test] + async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let udp_core_broadcaster = Broadcaster::default(); + let core_event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); + let udp_core_stats_event_sender = core_event_bus.sender(); + + let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); + let server_event_bus = Arc::new(crate::event::bus::EventBus::new( + SenderStatus::Disabled, + udp_server_broadcaster.clone(), + )); + + let udp_server_stats_event_sender = server_event_bus.sender(); + + let request = ConnectRequest { + transaction_id: TransactionId(0i32.into()), + }; + + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + + let response = handle_connect( + sample_ipv4_remote_addr(), + server_service_binding, + &request, + &connect_service, + &udp_server_stats_event_sender, + sample_issue_time(), + ) + .await; + + assert_eq!( + response, + Response::Connect(ConnectResponse { + connection_id: make(sample_ipv4_remote_addr_fingerprint(), sample_issue_time()).unwrap(), + transaction_id: request.transaction_id + }) + ); + } + + #[tokio::test] + async fn a_connect_response_should_contain_a_new_connection_id() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let udp_core_broadcaster = Broadcaster::default(); + let core_event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); + let udp_core_stats_event_sender = core_event_bus.sender(); + + let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); + let server_event_bus = Arc::new(crate::event::bus::EventBus::new( + SenderStatus::Disabled, + udp_server_broadcaster.clone(), + )); + + let udp_server_stats_event_sender = server_event_bus.sender(); + + let request = ConnectRequest { + transaction_id: TransactionId(0i32.into()), + }; + + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + + let response = handle_connect( + sample_ipv4_remote_addr(), + server_service_binding, + &request, + &connect_service, + &udp_server_stats_event_sender, + sample_issue_time(), + ) + .await; + + assert_eq!( + response, + Response::Connect(ConnectResponse { + connection_id: make(sample_ipv4_remote_addr_fingerprint(), sample_issue_time()).unwrap(), + transaction_id: request.transaction_id + }) + ); + } + + #[tokio::test] + async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let udp_core_broadcaster = Broadcaster::default(); + let core_event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); + + let udp_core_stats_event_sender = core_event_bus.sender(); + + let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); + let server_event_bus = Arc::new(crate::event::bus::EventBus::new( + SenderStatus::Disabled, + udp_server_broadcaster.clone(), + )); + + let udp_server_stats_event_sender = server_event_bus.sender(); + + let request = ConnectRequest { + transaction_id: TransactionId(0i32.into()), + }; + + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + + let response = handle_connect( + sample_ipv6_remote_addr(), + server_service_binding, + &request, + &connect_service, + &udp_server_stats_event_sender, + sample_issue_time(), + ) + .await; + + assert_eq!( + response, + Response::Connect(ConnectResponse { + connection_id: make(sample_ipv6_remote_addr_fingerprint(), sample_issue_time()).unwrap(), + transaction_id: request.transaction_id + }) + ); + } + + #[tokio::test] + async fn it_should_send_the_upd4_connect_event_when_a_client_tries_to_connect_using_a_ip4_socket_address() { + let client_socket_addr = sample_ipv4_socket_address(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); + udp_core_stats_event_sender_mock + .expect_send() + .with(eq(core_event::Event::UdpConnect { + connection: core_event::ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let udp_core_stats_event_sender: bittorrent_udp_tracker_core::event::sender::Sender = + Some(Arc::new(udp_core_stats_event_sender_mock)); + + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); + udp_server_stats_event_sender_mock + .expect_send() + .with(eq(Event::UdpRequestAccepted { + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + kind: UdpRequestKind::Connect, + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let udp_server_stats_event_sender: crate::event::sender::Sender = Some(Arc::new(udp_server_stats_event_sender_mock)); + + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + + handle_connect( + client_socket_addr, + server_service_binding, + &sample_connect_request(), + &connect_service, + &udp_server_stats_event_sender, + sample_issue_time(), + ) + .await; + } + + #[tokio::test] + async fn it_should_send_the_upd6_connect_event_when_a_client_tries_to_connect_using_a_ip6_socket_address() { + let client_socket_addr = sample_ipv6_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); + udp_core_stats_event_sender_mock + .expect_send() + .with(eq(core_event::Event::UdpConnect { + connection: core_event::ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let udp_core_stats_event_sender: bittorrent_udp_tracker_core::event::sender::Sender = + Some(Arc::new(udp_core_stats_event_sender_mock)); + + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); + udp_server_stats_event_sender_mock + .expect_send() + .with(eq(Event::UdpRequestAccepted { + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + kind: UdpRequestKind::Connect, + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let udp_server_stats_event_sender: crate::event::sender::Sender = Some(Arc::new(udp_server_stats_event_sender_mock)); + + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + + handle_connect( + client_socket_addr, + server_service_binding, + &sample_connect_request(), + &connect_service, + &udp_server_stats_event_sender, + sample_issue_time(), + ) + .await; + } + } +} diff --git a/packages/udp-tracker-server/src/handlers/error.rs b/packages/udp-tracker-server/src/handlers/error.rs new file mode 100644 index 000000000..7fb4141b2 --- /dev/null +++ b/packages/udp-tracker-server/src/handlers/error.rs @@ -0,0 +1,82 @@ +//! UDP tracker error handling. +use std::net::SocketAddr; +use std::ops::Range; + +use aquatic_udp_protocol::{ErrorResponse, Response, TransactionId}; +use bittorrent_udp_tracker_core::{self, UDP_TRACKER_LOG_TARGET}; +use torrust_tracker_primitives::service_binding::ServiceBinding; +use tracing::{instrument, Level}; +use uuid::Uuid; +use zerocopy::network_endian::I32; + +use crate::error::Error; +use crate::event::{ConnectionContext, Event, UdpRequestKind}; + +#[allow(clippy::too_many_arguments)] +#[instrument(fields(transaction_id), skip(opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] +pub async fn handle_error( + req_kind: Option, + client_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, + request_id: Uuid, + opt_udp_server_stats_event_sender: &crate::event::sender::Sender, + cookie_valid_range: Range, + error: &Error, + opt_transaction_id: Option, +) -> Response { + tracing::trace!("handle error"); + + let server_socket_addr = server_service_binding.bind_address(); + + log_error(error, client_socket_addr, server_socket_addr, opt_transaction_id, request_id); + + trigger_udp_error_event( + error, + client_socket_addr, + server_service_binding, + opt_udp_server_stats_event_sender, + req_kind, + ) + .await; + + Response::from(ErrorResponse { + transaction_id: opt_transaction_id.unwrap_or(TransactionId(I32::new(0))), + message: error.to_string().into(), + }) +} + +fn log_error( + error: &Error, + client_socket_addr: SocketAddr, + server_socket_addr: SocketAddr, + opt_transaction_id: Option, + request_id: Uuid, +) { + match opt_transaction_id { + Some(transaction_id) => { + let transaction_id = transaction_id.0.to_string(); + tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %error, %client_socket_addr, %server_socket_addr, %request_id, %transaction_id, "response error"); + } + None => { + tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %error, %client_socket_addr, %server_socket_addr, %request_id, "response error"); + } + } +} + +async fn trigger_udp_error_event( + error: &Error, + client_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, + opt_udp_server_stats_event_sender: &crate::event::sender::Sender, + req_kind: Option, +) { + if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { + udp_server_stats_event_sender + .send(Event::UdpError { + context: ConnectionContext::new(client_socket_addr, server_service_binding), + kind: req_kind, + error: error.clone().into(), + }) + .await; + } +} diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs new file mode 100644 index 000000000..add576a89 --- /dev/null +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -0,0 +1,397 @@ +//! Handlers for the UDP server. +pub mod announce; +pub mod connect; +pub mod error; +pub mod scrape; + +use std::net::SocketAddr; +use std::ops::Range; +use std::sync::Arc; +use std::time::Instant; + +use announce::handle_announce; +use aquatic_udp_protocol::{Request, Response, TransactionId}; +use bittorrent_tracker_core::MAX_SCRAPE_TORRENTS; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; +use connect::handle_connect; +use error::handle_error; +use scrape::handle_scrape; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_primitives::service_binding::ServiceBinding; +use tracing::{instrument, Level}; +use uuid::Uuid; + +use super::RawRequest; +use crate::container::UdpTrackerServerContainer; +use crate::error::Error; +use crate::event::UdpRequestKind; +use crate::CurrentClock; + +#[derive(Debug, Clone, PartialEq)] +pub struct CookieTimeValues { + pub(super) issue_time: f64, + pub(super) valid_range: Range, +} + +impl CookieTimeValues { + pub(super) fn new(cookie_lifetime: f64) -> Self { + let issue_time = CurrentClock::now().as_secs_f64(); + let expiry_time = issue_time - cookie_lifetime - 1.0; + let tolerance_max_time = issue_time + 1.0; + + Self { + issue_time, + valid_range: expiry_time..tolerance_max_time, + } + } +} + +/// It handles the incoming UDP packets. +/// +/// It's responsible for: +/// +/// - Parsing the incoming packet. +/// - Delegating the request to the correct handler depending on the request type. +/// +/// It will return an `Error` response if the request is invalid. +#[instrument(fields(request_id), skip(udp_request, udp_tracker_core_container, udp_tracker_server_container, cookie_time_values), ret(level = Level::TRACE))] +pub(crate) async fn handle_packet( + udp_request: RawRequest, + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, + server_service_binding: ServiceBinding, + cookie_time_values: CookieTimeValues, +) -> (Response, Option) { + let request_id = Uuid::new_v4(); + + tracing::Span::current().record("request_id", request_id.to_string()); + tracing::debug!("Handling Packets: {udp_request:?}"); + + let start_time = Instant::now(); + + let (response, opt_req_kind) = + match Request::parse_bytes(&udp_request.payload[..udp_request.payload.len()], MAX_SCRAPE_TORRENTS).map_err(Error::from) { + Ok(request) => match handle_request( + request, + udp_request.from, + server_service_binding.clone(), + udp_tracker_core_container.clone(), + udp_tracker_server_container.clone(), + cookie_time_values.clone(), + ) + .await + { + Ok((response, req_kid)) => return (response, Some(req_kid)), + Err((error, transaction_id, req_kind)) => { + let response = handle_error( + Some(req_kind.clone()), + udp_request.from, + server_service_binding, + request_id, + &udp_tracker_server_container.stats_event_sender, + cookie_time_values.valid_range.clone(), + &error, + Some(transaction_id), + ) + .await; + + (response, Some(req_kind)) + } + }, + Err(e) => { + // The request payload could not be parsed, so we handle it as an error. + + let opt_transaction_id = if let Error::InvalidRequest { request_parse_error } = e.clone() { + request_parse_error.opt_transaction_id + } else { + None + }; + + let response = handle_error( + None, + udp_request.from, + server_service_binding, + request_id, + &udp_tracker_server_container.stats_event_sender, + cookie_time_values.valid_range.clone(), + &e, + opt_transaction_id, + ) + .await; + + (response, None) + } + }; + + let latency = start_time.elapsed(); + tracing::trace!(?latency, "responded"); + + (response, opt_req_kind) +} + +/// It dispatches the request to the correct handler. +/// +/// # Errors +/// +/// If a error happens in the `handle_request` function, it will just return the `ServerError`. +#[instrument(skip( + request, + client_socket_addr, + server_service_binding, + udp_tracker_core_container, + udp_tracker_server_container, + cookie_time_values +))] +pub async fn handle_request( + request: Request, + client_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, + cookie_time_values: CookieTimeValues, +) -> Result<(Response, UdpRequestKind), (Error, TransactionId, UdpRequestKind)> { + tracing::trace!("handle request"); + + match request { + Request::Connect(connect_request) => Ok(( + handle_connect( + client_socket_addr, + server_service_binding, + &connect_request, + &udp_tracker_core_container.connect_service, + &udp_tracker_server_container.stats_event_sender, + cookie_time_values.issue_time, + ) + .await, + UdpRequestKind::Connect, + )), + Request::Announce(announce_request) => { + match handle_announce( + &udp_tracker_core_container.announce_service, + client_socket_addr, + server_service_binding, + &announce_request, + &udp_tracker_core_container.tracker_core_container.core_config, + &udp_tracker_server_container.stats_event_sender, + cookie_time_values.valid_range, + ) + .await + { + Ok(response) => Ok((response, UdpRequestKind::Announce { announce_request })), + Err(err) => Err(err), + } + } + Request::Scrape(scrape_request) => { + match handle_scrape( + &udp_tracker_core_container.scrape_service, + client_socket_addr, + server_service_binding, + &scrape_request, + &udp_tracker_server_container.stats_event_sender, + cookie_time_values.valid_range, + ) + .await + { + Ok(response) => Ok((response, UdpRequestKind::Scrape)), + Err(err) => Err(err), + } + } + } +} + +#[cfg(test)] +pub(crate) mod tests { + + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::ops::Range; + use std::sync::Arc; + + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::databases::setup::initialize_database; + use bittorrent_tracker_core::scrape_handler::ScrapeHandler; + use bittorrent_tracker_core::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::whitelist; + use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; + use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use bittorrent_udp_tracker_core::connection_cookie::gen_remote_fingerprint; + use bittorrent_udp_tracker_core::event::bus::EventBus; + use bittorrent_udp_tracker_core::event::sender::Broadcaster; + use bittorrent_udp_tracker_core::services::announce::AnnounceService; + use bittorrent_udp_tracker_core::services::scrape::ScrapeService; + use bittorrent_udp_tracker_core::{self, event as core_event}; + use futures::future::BoxFuture; + use mockall::mock; + use torrust_tracker_configuration::{Configuration, Core}; + use torrust_tracker_events::bus::SenderStatus; + use torrust_tracker_events::sender::SendError; + use torrust_tracker_test_helpers::configuration; + + use crate::event as server_event; + + pub(crate) struct CoreTrackerServices { + pub core_config: Arc, + pub announce_handler: Arc, + pub in_memory_torrent_repository: Arc, + pub in_memory_whitelist: Arc, + pub whitelist_authorization: Arc, + } + + pub(crate) struct CoreUdpTrackerServices { + pub announce_service: Arc, + pub scrape_service: Arc, + } + + pub(crate) struct ServerUdpTrackerServices { + pub udp_server_stats_event_sender: crate::event::sender::Sender, + } + + fn default_testing_tracker_configuration() -> Configuration { + configuration::ephemeral() + } + + pub(crate) fn initialize_core_tracker_services_for_default_tracker_configuration( + ) -> (CoreTrackerServices, CoreUdpTrackerServices, ServerUdpTrackerServices) { + initialize_core_tracker_services(&default_testing_tracker_configuration()) + } + + pub(crate) fn initialize_core_tracker_services_for_public_tracker( + ) -> (CoreTrackerServices, CoreUdpTrackerServices, ServerUdpTrackerServices) { + initialize_core_tracker_services(&configuration::ephemeral_public()) + } + + pub(crate) fn initialize_core_tracker_services_for_listed_tracker( + ) -> (CoreTrackerServices, CoreUdpTrackerServices, ServerUdpTrackerServices) { + initialize_core_tracker_services(&configuration::ephemeral_listed()) + } + + fn initialize_core_tracker_services( + config: &Configuration, + ) -> (CoreTrackerServices, CoreUdpTrackerServices, ServerUdpTrackerServices) { + let core_config = Arc::new(config.core.clone()); + let database = initialize_database(&config.core); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_downloads_metric_repository, + )); + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + let udp_core_broadcaster = Broadcaster::default(); + let core_event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); + let udp_core_stats_event_sender = core_event_bus.sender(); + + let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); + let server_event_bus = Arc::new(crate::event::bus::EventBus::new( + SenderStatus::Disabled, + udp_server_broadcaster.clone(), + )); + + let udp_server_stats_event_sender = server_event_bus.sender(); + + let announce_service = Arc::new(AnnounceService::new( + announce_handler.clone(), + whitelist_authorization.clone(), + udp_core_stats_event_sender.clone(), + )); + + let scrape_service = Arc::new(ScrapeService::new( + scrape_handler.clone(), + udp_core_stats_event_sender.clone(), + )); + + ( + CoreTrackerServices { + core_config, + announce_handler, + in_memory_torrent_repository, + in_memory_whitelist, + whitelist_authorization, + }, + CoreUdpTrackerServices { + announce_service, + scrape_service, + }, + ServerUdpTrackerServices { + udp_server_stats_event_sender, + }, + ) + } + + pub(crate) fn sample_ipv4_remote_addr() -> SocketAddr { + sample_ipv4_socket_address() + } + + pub(crate) fn sample_ipv4_remote_addr_fingerprint() -> u64 { + gen_remote_fingerprint(&sample_ipv4_socket_address()) + } + + pub(crate) fn sample_ipv6_remote_addr() -> SocketAddr { + sample_ipv6_socket_address() + } + + pub(crate) fn sample_ipv6_remote_addr_fingerprint() -> u64 { + gen_remote_fingerprint(&sample_ipv6_socket_address()) + } + + pub(crate) fn sample_ipv4_socket_address() -> SocketAddr { + SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080) + } + + fn sample_ipv6_socket_address() -> SocketAddr { + SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 8080) + } + + pub(crate) fn sample_issue_time() -> f64 { + 1_000_000_000_f64 + } + + pub(crate) fn sample_cookie_valid_range() -> Range { + sample_issue_time() - 10.0..sample_issue_time() + 10.0 + } + + pub(crate) struct TrackerConfigurationBuilder { + configuration: Configuration, + } + + impl TrackerConfigurationBuilder { + pub fn default() -> TrackerConfigurationBuilder { + let default_configuration = default_testing_tracker_configuration(); + TrackerConfigurationBuilder { + configuration: default_configuration, + } + } + + pub fn with_external_ip(mut self, external_ip: &str) -> Self { + self.configuration.core.net.external_ip = Some(external_ip.to_owned().parse().expect("valid IP address")); + self + } + + pub fn into(self) -> Configuration { + self.configuration + } + } + + mock! { + pub(crate) UdpCoreStatsEventSender {} + impl torrust_tracker_events::sender::Sender for UdpCoreStatsEventSender { + type Event = core_event::Event; + + fn send(&self, event: core_event::Event) -> BoxFuture<'static,Option > > > ; + } + } + + mock! { + pub(crate) UdpServerStatsEventSender {} + impl torrust_tracker_events::sender::Sender for UdpServerStatsEventSender { + type Event = server_event::Event; + + fn send(&self, event: server_event::Event) -> BoxFuture<'static,Option > > > ; + } + } +} diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs new file mode 100644 index 000000000..8bac05c1e --- /dev/null +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -0,0 +1,461 @@ +//! UDP tracker scrape handler. +use std::net::SocketAddr; +use std::ops::Range; +use std::sync::Arc; + +use aquatic_udp_protocol::{ + NumberOfDownloads, NumberOfPeers, Response, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, +}; +use bittorrent_udp_tracker_core::services::scrape::ScrapeService; +use bittorrent_udp_tracker_core::{self}; +use torrust_tracker_primitives::core::ScrapeData; +use torrust_tracker_primitives::service_binding::ServiceBinding; +use tracing::{instrument, Level}; +use zerocopy::network_endian::I32; + +use crate::error::Error; +use crate::event::{ConnectionContext, Event, UdpRequestKind}; + +/// It handles the `Scrape` request. +/// +/// # Errors +/// +/// This function does not ever return an error. +#[instrument(fields(transaction_id, connection_id), skip(scrape_service, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] +pub async fn handle_scrape( + scrape_service: &Arc, + client_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, + request: &ScrapeRequest, + opt_udp_server_stats_event_sender: &crate::event::sender::Sender, + cookie_valid_range: Range, +) -> Result { + tracing::Span::current() + .record("transaction_id", request.transaction_id.0.to_string()) + .record("connection_id", request.connection_id.0.to_string()); + + tracing::trace!("handle scrape"); + + if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { + udp_server_stats_event_sender + .send(Event::UdpRequestAccepted { + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + kind: UdpRequestKind::Scrape, + }) + .await; + } + + let scrape_data = scrape_service + .handle_scrape(client_socket_addr, server_service_binding, request, cookie_valid_range) + .await + .map_err(|e| (e.into(), request.transaction_id, UdpRequestKind::Scrape))?; + + Ok(build_response(request, &scrape_data)) +} + +fn build_response(request: &ScrapeRequest, scrape_data: &ScrapeData) -> Response { + let mut torrent_stats: Vec = Vec::new(); + + for file in &scrape_data.files { + let swarm_metadata = file.1; + + #[allow(clippy::cast_possible_truncation)] + let scrape_entry = { + TorrentScrapeStatistics { + seeders: NumberOfPeers(I32::new(i64::from(swarm_metadata.complete) as i32)), + completed: NumberOfDownloads(I32::new(i64::from(swarm_metadata.downloaded) as i32)), + leechers: NumberOfPeers(I32::new(i64::from(swarm_metadata.incomplete) as i32)), + } + }; + + torrent_stats.push(scrape_entry); + } + + let response = ScrapeResponse { + transaction_id: request.transaction_id, + torrent_stats, + }; + + Response::from(response) +} + +#[cfg(test)] +mod tests { + + mod scrape_request { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{ + InfoHash, NumberOfDownloads, NumberOfPeers, PeerId, Response, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, + TransactionId, + }; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; + use torrust_tracker_events::bus::SenderStatus; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::bus::EventBus; + use crate::event::sender::Broadcaster; + use crate::handlers::handle_scrape; + use crate::handlers::tests::{ + initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, + sample_issue_time, CoreTrackerServices, CoreUdpTrackerServices, + }; + + fn zeroed_torrent_statistics() -> TorrentScrapeStatistics { + TorrentScrapeStatistics { + seeders: NumberOfPeers(0.into()), + completed: NumberOfDownloads(0.into()), + leechers: NumberOfPeers(0.into()), + } + } + + #[tokio::test] + async fn should_return_no_stats_when_the_tracker_does_not_have_any_torrent() { + let (_core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); + + let client_socket_addr = sample_ipv4_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let info_hash = InfoHash([0u8; 20]); + let info_hashes = vec![info_hash]; + + let request = ScrapeRequest { + connection_id: make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap(), + transaction_id: TransactionId(0i32.into()), + info_hashes, + }; + + let response = handle_scrape( + &core_udp_tracker_services.scrape_service, + client_socket_addr, + server_service_binding, + &request, + &server_udp_tracker_services.udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let expected_torrent_stats = vec![zeroed_torrent_statistics()]; + + assert_eq!( + response, + Response::from(ScrapeResponse { + transaction_id: request.transaction_id, + torrent_stats: expected_torrent_stats + }) + ); + } + + async fn add_a_seeder( + in_memory_torrent_repository: Arc, + remote_addr: &SocketAddr, + info_hash: &InfoHash, + ) { + let peer_id = PeerId([255u8; 20]); + + let peer = PeerBuilder::default() + .with_peer_id(&peer_id) + .with_peer_address(*remote_addr) + .with_bytes_left_to_download(0) + .into(); + + in_memory_torrent_repository + .handle_announcement(&info_hash.0.into(), &peer, None) + .await; + } + + fn build_scrape_request(remote_addr: &SocketAddr, info_hash: &InfoHash) -> ScrapeRequest { + let info_hashes = vec![*info_hash]; + + ScrapeRequest { + connection_id: make(gen_remote_fingerprint(remote_addr), sample_issue_time()).unwrap(), + transaction_id: TransactionId::new(0i32), + info_hashes, + } + } + + async fn add_a_sample_seeder_and_scrape( + core_tracker_services: Arc, + core_udp_tracker_services: Arc, + ) -> Response { + let udp_server_broadcaster = Broadcaster::default(); + let event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_server_broadcaster.clone())); + + let udp_server_stats_event_sender = event_bus.sender(); + + let client_socket_addr = sample_ipv4_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let info_hash = InfoHash([0u8; 20]); + + add_a_seeder( + core_tracker_services.in_memory_torrent_repository.clone(), + &client_socket_addr, + &info_hash, + ) + .await; + + let request = build_scrape_request(&client_socket_addr, &info_hash); + + handle_scrape( + &core_udp_tracker_services.scrape_service, + client_socket_addr, + server_service_binding, + &request, + &udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap() + } + + fn match_scrape_response(response: Response) -> Option { + match response { + Response::Scrape(scrape_response) => Some(scrape_response), + _ => None, + } + } + + mod with_a_public_tracker { + use aquatic_udp_protocol::{NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; + + use crate::handlers::scrape::tests::scrape_request::{add_a_sample_seeder_and_scrape, match_scrape_response}; + use crate::handlers::tests::initialize_core_tracker_services_for_public_tracker; + + #[tokio::test] + async fn should_return_torrent_statistics_when_the_tracker_has_the_requested_torrent() { + let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); + + let torrent_stats = match_scrape_response( + add_a_sample_seeder_and_scrape(core_tracker_services.into(), core_udp_tracker_services.into()).await, + ); + + let expected_torrent_stats = vec![TorrentScrapeStatistics { + seeders: NumberOfPeers(1.into()), + completed: NumberOfDownloads(0.into()), + leechers: NumberOfPeers(0.into()), + }]; + + assert_eq!(torrent_stats.unwrap().torrent_stats, expected_torrent_stats); + } + } + + mod with_a_whitelisted_tracker { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use aquatic_udp_protocol::{InfoHash, NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::handlers::handle_scrape; + use crate::handlers::scrape::tests::scrape_request::{ + add_a_seeder, build_scrape_request, match_scrape_response, zeroed_torrent_statistics, + }; + use crate::handlers::tests::{ + initialize_core_tracker_services_for_listed_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, + }; + + #[tokio::test] + async fn should_return_the_torrent_statistics_when_the_requested_torrent_is_whitelisted() { + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + initialize_core_tracker_services_for_listed_tracker(); + + let client_socket_addr = sample_ipv4_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let info_hash = InfoHash([0u8; 20]); + + add_a_seeder( + core_tracker_services.in_memory_torrent_repository.clone(), + &client_socket_addr, + &info_hash, + ) + .await; + + core_tracker_services.in_memory_whitelist.add(&info_hash.0.into()).await; + + let request = build_scrape_request(&client_socket_addr, &info_hash); + + let torrent_stats = match_scrape_response( + handle_scrape( + &core_udp_tracker_services.scrape_service, + client_socket_addr, + server_service_binding, + &request, + &server_udp_tracker_services.udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(), + ) + .unwrap(); + + let expected_torrent_stats = vec![TorrentScrapeStatistics { + seeders: NumberOfPeers(1.into()), + completed: NumberOfDownloads(0.into()), + leechers: NumberOfPeers(0.into()), + }]; + + assert_eq!(torrent_stats.torrent_stats, expected_torrent_stats); + } + + #[tokio::test] + async fn should_return_zeroed_statistics_when_the_requested_torrent_is_not_whitelisted() { + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + initialize_core_tracker_services_for_listed_tracker(); + + let client_socket_addr = sample_ipv4_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let info_hash = InfoHash([0u8; 20]); + + add_a_seeder( + core_tracker_services.in_memory_torrent_repository.clone(), + &client_socket_addr, + &info_hash, + ) + .await; + + let request = build_scrape_request(&client_socket_addr, &info_hash); + + let torrent_stats = match_scrape_response( + handle_scrape( + &core_udp_tracker_services.scrape_service, + client_socket_addr, + server_service_binding, + &request, + &server_udp_tracker_services.udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(), + ) + .unwrap(); + + let expected_torrent_stats = vec![zeroed_torrent_statistics()]; + + assert_eq!(torrent_stats.torrent_stats, expected_torrent_stats); + } + } + + fn sample_scrape_request(remote_addr: &SocketAddr) -> ScrapeRequest { + let info_hash = InfoHash([0u8; 20]); + let info_hashes = vec![info_hash]; + + ScrapeRequest { + connection_id: make(gen_remote_fingerprint(remote_addr), sample_issue_time()).unwrap(), + transaction_id: TransactionId(0i32.into()), + info_hashes, + } + } + + mod using_ipv4 { + use std::future; + use std::net::{IpAddr, Ipv6Addr, SocketAddr}; + use std::sync::Arc; + + use mockall::predicate::eq; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use super::sample_scrape_request; + use crate::event::{ConnectionContext, Event, UdpRequestKind}; + use crate::handlers::handle_scrape; + use crate::handlers::tests::{ + initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, + sample_ipv4_remote_addr, MockUdpServerStatsEventSender, + }; + + #[tokio::test] + async fn should_send_the_upd4_scrape_event() { + let client_socket_addr = sample_ipv4_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); + udp_server_stats_event_sender_mock + .expect_send() + .with(eq(Event::UdpRequestAccepted { + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + kind: UdpRequestKind::Scrape, + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let udp_server_stats_event_sender: crate::event::sender::Sender = + Some(Arc::new(udp_server_stats_event_sender_mock)); + + let (_core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = + initialize_core_tracker_services_for_default_tracker_configuration(); + + handle_scrape( + &core_udp_tracker_services.scrape_service, + client_socket_addr, + server_service_binding, + &sample_scrape_request(&client_socket_addr), + &udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + } + } + + mod using_ipv6 { + use std::future; + use std::net::{IpAddr, Ipv6Addr, SocketAddr}; + use std::sync::Arc; + + use mockall::predicate::eq; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use super::sample_scrape_request; + use crate::event::{ConnectionContext, Event, UdpRequestKind}; + use crate::handlers::handle_scrape; + use crate::handlers::tests::{ + initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, + sample_ipv6_remote_addr, MockUdpServerStatsEventSender, + }; + + #[tokio::test] + async fn should_send_the_upd6_scrape_event() { + let client_socket_addr = sample_ipv6_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); + udp_server_stats_event_sender_mock + .expect_send() + .with(eq(Event::UdpRequestAccepted { + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + kind: UdpRequestKind::Scrape, + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let udp_server_stats_event_sender: crate::event::sender::Sender = + Some(Arc::new(udp_server_stats_event_sender_mock)); + + let (_core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = + initialize_core_tracker_services_for_default_tracker_configuration(); + + handle_scrape( + &core_udp_tracker_services.scrape_service, + client_socket_addr, + server_service_binding, + &sample_scrape_request(&client_socket_addr), + &udp_server_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + } + } + } +} diff --git a/src/servers/udp/mod.rs b/packages/udp-tracker-server/src/lib.rs similarity index 85% rename from src/servers/udp/mod.rs rename to packages/udp-tracker-server/src/lib.rs index edbfd77d2..58a3830e1 100644 --- a/src/servers/udp/mod.rs +++ b/packages/udp-tracker-server/src/lib.rs @@ -5,7 +5,7 @@ //! The UDP tracker is a simple UDP server that responds to these requests: //! //! - `Connect`: used to get a connection ID which must be provided on each -//! request in order to avoid spoofing the source address of the UDP packets. +//! request in order to avoid spoofing the source address of the UDP packets. //! - `Announce`: used to announce the presence of a peer to the tracker. //! - `Scrape`: used to get information about a torrent. //! @@ -22,10 +22,10 @@ //! for more information about the UDP tracker protocol. //! //! > **NOTICE**: [BEP-41](https://www.bittorrent.org/beps/bep_0041.html) is not -//! implemented yet. +//! > implemented yet. //! //! > **NOTICE**: we are using the [`aquatic_udp_protocol`](https://crates.io/crates/aquatic_udp_protocol) -//! crate so requests and responses are handled by it. +//! > crate so requests and responses are handled by it. //! //! > **NOTICE**: all values are send in network byte order ([big endian](https://en.wikipedia.org/wiki/Endianness)). //! @@ -52,8 +52,7 @@ //! is designed to be as simple as possible. It uses a single UDP port and //! supports only three types of requests: `Connect`, `Announce` and `Scrape`. //! -//! Request are parsed from UDP packets using the [`aquatic_udp_protocol`](https://crates.io/crates/aquatic_udp_protocol) -//! crate and then handled by the [`Tracker`](crate::tracker::Tracker) struct. +//! Request are parsed from UDP packets using the [`aquatic_udp_protocol`](https://crates.io/crates/aquatic_udp_protocol). //! And then the response is also build using the [`aquatic_udp_protocol`](https://crates.io/crates/aquatic_udp_protocol) //! and converted to a UDP packet. //! @@ -61,9 +60,6 @@ //! UDP packet -> Aquatic Struct Request -> [Torrust Struct Request] -> Tracker -> Aquatic Struct Response -> UDP packet //! ``` //! -//! For the `Announce` request there is a wrapper struct [`AnnounceWrapper`](crate::servers::udp::request::AnnounceWrapper). -//! It was added to add an extra field with the internal [`InfoHash`](crate::shared::bit_torrent::info_hash::InfoHash) struct. -//! //! ### Connect //! //! `Connect` requests are used to get a connection ID which must be provided on @@ -83,23 +79,23 @@ //! spoofing can be explained as follows: //! //! 1. No connection state: Unlike TCP, UDP is a connectionless protocol, -//! meaning that it does not establish a connection between two endpoints before -//! exchanging data. As a result, it is more susceptible to IP spoofing, where -//! an attacker sends packets with a forged source IP address, tricking the -//! receiver into believing that they are coming from a legitimate source. +//! meaning that it does not establish a connection between two endpoints before +//! exchanging data. As a result, it is more susceptible to IP spoofing, where +//! an attacker sends packets with a forged source IP address, tricking the +//! receiver into believing that they are coming from a legitimate source. //! //! 2. Mitigating IP spoofing: To mitigate IP spoofing in the UDP tracker -//! protocol, a connection ID is used. When a client wants to interact with a -//! tracker, it sends a "connect" request to the tracker, which, in turn, -//! responds with a unique connection ID. This connection ID must be included in -//! all subsequent requests from the client to the tracker. +//! protocol, a connection ID is used. When a client wants to interact with a +//! tracker, it sends a "connect" request to the tracker, which, in turn, +//! responds with a unique connection ID. This connection ID must be included in +//! all subsequent requests from the client to the tracker. //! //! 3. Validating requests: By requiring the connection ID, the tracker can -//! verify that the requests are coming from the same client that initially sent -//! the "connect" request. If an attacker attempts to spoof the client's IP -//! address, they would also need to know the valid connection ID to be accepted -//! by the tracker. This makes it significantly more challenging for an attacker -//! to spoof IP addresses and disrupt the P2P network. +//! verify that the requests are coming from the same client that initially sent +//! the "connect" request. If an attacker attempts to spoof the client's IP +//! address, they would also need to know the valid connection ID to be accepted +//! by the tracker. This makes it significantly more challenging for an attacker +//! to spoof IP addresses and disrupt the P2P network. //! //! There are different ways to generate a connection ID. The most common way is //! to generate a time bound secret. The secret is generated using a time based @@ -109,7 +105,7 @@ //! connection ID = hash(client IP + current time slot + secret seed) //! ``` //! -//! The BEP-15 recommends a two-minute time slot. Refer to [`connection_cookie`](crate::servers::udp::connection_cookie) +//! The BEP-15 recommends a two-minute time slot. Refer to [`connection_cookie`](bittorrent_udp_tracker_core::connection_cookie) //! for more information about the connection ID generation with this method. //! //! #### Connect Request @@ -161,9 +157,9 @@ //! 8 | [`i32`](std::i64) | `connection_id` | Generated by the tracker to authenticate the client. | `0xC5_58_7C_09_08_48_D8_37` | `-4226491872051668937` //! //! > **NOTICE**: the `connection_id` is used when further information is -//! exchanged with the tracker, to identify the client. This `connection_id` can -//! be reused for multiple requests, but if it's cached for too long, it will -//! not be valid anymore. +//! > exchanged with the tracker, to identify the client. This `connection_id` can +//! > be reused for multiple requests, but if it's cached for too long, it will +//! > not be valid anymore. //! //! > **NOTICE**: `Hex` column is a signed 2's complement. //! @@ -243,41 +239,41 @@ //! circumstances might include: //! //! 1. Network Address Translation (NAT): In cases where a peer is behind a NAT, -//! the private IP address of the peer is not directly routable over the -//! internet. The NAT device translates the private IP address to a public one -//! when sending packets to the tracker. The public IP address is what the -//! tracker sees as the source IP of the incoming request. However, if the peer -//! provides its private IP address in the announce request, the tracker can use -//! this information to facilitate communication between peers in the same -//! private network. +//! the private IP address of the peer is not directly routable over the +//! internet. The NAT device translates the private IP address to a public one +//! when sending packets to the tracker. The public IP address is what the +//! tracker sees as the source IP of the incoming request. However, if the peer +//! provides its private IP address in the announce request, the tracker can use +//! this information to facilitate communication between peers in the same +//! private network. //! //! 2. Proxy or VPN usage: If a peer uses a proxy or VPN service to connect to -//! the tracker, the source IP address seen by the tracker will be the one -//! assigned by the proxy or VPN server. In this case, if the peer provides its -//! actual IP address in the announce request, the tracker can use it to -//! establish a direct connection with other peers, bypassing the proxy or VPN -//! server. This might improve performance or help in cases where some peers -//! cannot connect to the proxy or VPN server. +//! the tracker, the source IP address seen by the tracker will be the one +//! assigned by the proxy or VPN server. In this case, if the peer provides its +//! actual IP address in the announce request, the tracker can use it to +//! establish a direct connection with other peers, bypassing the proxy or VPN +//! server. This might improve performance or help in cases where some peers +//! cannot connect to the proxy or VPN server. //! //! 3. Tracker is behind a NAT, firewall, proxy, VPN, or load balancer: In cases -//! where the tracker is behind a NAT, firewall, proxy, VPN, or load balancer, -//! the source IP address of the incoming request will be the public IP address -//! of the NAT, firewall, proxy, VPN, or load balancer. If the peer provides its -//! private IP address in the announce request, the tracker can use this -//! information to establish a direct connection with the peer. +//! where the tracker is behind a NAT, firewall, proxy, VPN, or load balancer, +//! the source IP address of the incoming request will be the public IP address +//! of the NAT, firewall, proxy, VPN, or load balancer. If the peer provides its +//! private IP address in the announce request, the tracker can use this +//! information to establish a direct connection with the peer. //! //! It's important to note that using the provided IP address can pose security //! risks, as malicious peers might spoof their IP addresses in the announce //! request to perform various types of attacks. //! //! > **NOTICE**: The current tracker behavior is to ignore the IP address -//! provided by the peer, and use the source IP address of the incoming request, -//! when the tracker is not running behind a proxy, and to use the right-most IP -//! address in the `X-Forwarded-For` header when the tracker is running behind a -//! proxy. +//! > provided by the peer, and use the source IP address of the incoming request, +//! > when the tracker is not running behind a proxy, and to use the right-most IP +//! > address in the `X-Forwarded-For` header when the tracker is running behind a +//! > proxy. //! //! > **NOTICE**: The tracker also changes the peer IP address to the tracker -//! external IP when the peer is using a loopback IP address. +//! > external IP when the peer is using a loopback IP address. //! //! **Sample announce request (UDP packet)** //! @@ -317,11 +313,11 @@ //! 101 | N bytes | | | | //! //! > **NOTICE**: bytes after offset 98 are part of the [BEP-41. UDP Tracker Protocol Extensions](https://www.bittorrent.org/beps/bep_0041.html). -//! There are three options defined for byte 98: `0x0` (`EndOfOptions`), `0x1` (`NOP`) and `0x2` (`URLData`). +//! > There are three options defined for byte 98: `0x0` (`EndOfOptions`), `0x1` (`NOP`) and `0x2` (`URLData`). //! //! > **NOTICE**: `num_want` is being ignored by the tracker. Refer to -//! [issue 262](https://github.com/torrust/torrust-tracker/issues/262) for more -//! information. +//! > [issue 262](https://github.com/torrust/torrust-tracker/issues/262) for more +//! > information. //! //! **Announce request (parsed struct)** //! @@ -342,10 +338,10 @@ //! `port` | [`Port`](aquatic_udp_protocol::common::Port) | `17548` //! //! > **NOTICE**: the `peers_wanted` field is the `num_want` field in the UDP -//! packet. +//! > packet. //! //! We are using a wrapper struct for the aquatic [`AnnounceRequest`](aquatic_udp_protocol::request::AnnounceRequest) -//! struct, because we have our internal [`InfoHash`](crate::shared::bit_torrent::info_hash::InfoHash) +//! struct, because we have our internal [`InfoHash`](bittorrent_primitives::info_hash::InfoHash) //! struct. //! //! ```text @@ -374,7 +370,7 @@ //! > **NOTICE**: `Hex` column is a signed 2's complement. //! //! > **NOTICE**: `IP address` should always be set to 0 when the peer is using -//! `IPv6`. +//! > `IPv6`. //! //! **Sample announce response (UDP packet)** //! @@ -413,7 +409,7 @@ //! ``` //! //! > **NOTICE**: there are 6 bytes per peer (4 bytes for the `IPv4` address and -//! 2 bytes for the TCP port). +//! > 2 bytes for the TCP port). //! //! UDP packet fields (`IPv4` peer list): //! @@ -433,7 +429,7 @@ //! ``` //! //! > **NOTICE**: there are 18 bytes per peer (16 bytes for the `IPv6` address and -//! 2 bytes for the TCP port). +//! > 2 bytes for the TCP port). //! //! UDP packet fields (`IPv6` peer list): //! @@ -446,7 +442,7 @@ //! > **NOTICE**: `Hex` column is a signed 2's complement. //! //! > **NOTICE**: the peer list does not include the peer that sent the announce -//! request. +//! > request. //! //! **Announce response (struct)** //! @@ -467,21 +463,21 @@ //! //! ### Scrape //! -//! The `scrape` request allows a peer to get [swarm metadata](crate::tracker::torrent::SwarmMetadata) +//! The `scrape` request allows a peer to get [swarm metadata](torrust_tracker_primitives::swarm_metadata::SwarmMetadata) //! for multiple torrents at the same time. //! -//! The response contains the [swarm metadata](crate::tracker::torrent::SwarmMetadata) +//! The response contains the [swarm metadata](torrust_tracker_primitives::swarm_metadata::SwarmMetadata) //! for that torrent: //! -//! - [complete](crate::tracker::torrent::SwarmMetadata::complete) -//! - [downloaded](crate::tracker::torrent::SwarmMetadata::downloaded) -//! - [incomplete](crate::tracker::torrent::SwarmMetadata::incomplete) +//! - [complete](torrust_tracker_primitives::swarm_metadata::SwarmMetadata::complete) +//! - [downloaded](torrust_tracker_primitives::swarm_metadata::SwarmMetadata::downloaded) +//! - [incomplete](torrust_tracker_primitives::swarm_metadata::SwarmMetadata::incomplete) //! //! > **NOTICE**: up to about 74 torrents can be scraped at once. A full scrape -//! can't be done with this protocol. This is a limitation of the UDP protocol. -//! Defined with a hardcoded const [`MAX_SCRAPE_TORRENTS`](crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS). -//! Refer to [issue 262](https://github.com/torrust/torrust-tracker/issues/262) -//! for more information about this limitation. +//! > can't be done with this protocol. This is a limitation of the UDP protocol. +//! > Defined with a hardcoded const [`MAX_SCRAPE_TORRENTS`](torrust_udp_tracker_server::MAX_SCRAPE_TORRENTS). +//! > Refer to [issue 262](https://github.com/torrust/torrust-tracker/issues/262) +//! > for more information about this limitation. //! //! #### Scrape Request //! @@ -638,12 +634,32 @@ //! documentation by [Arvid Norberg](https://github.com/arvidn) was very //! supportive in the development of this documentation. Some descriptions were //! taken from the [libtorrent](https://www.rasterbar.com/products/libtorrent/udp_tracker_protocol.html). -pub mod connection_cookie; +pub mod banning; +pub mod container; +pub mod environment; pub mod error; +pub mod event; pub mod handlers; -pub mod peer_builder; -pub mod request; pub mod server; +pub mod statistics; + +use std::net::SocketAddr; + +use torrust_tracker_clock::clock; + +/// The maximum number of bytes in a UDP packet. +pub const MAX_PACKET_SIZE: usize = 1496; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; /// Number of bytes. pub type Bytes = u64; @@ -653,8 +669,62 @@ pub type Port = u16; /// match requests and responses. pub type TransactionId = i64; -/// The maximum number of bytes in a UDP packet. -pub const MAX_PACKET_SIZE: usize = 1496; -/// A magic 64-bit integer constant defined in the protocol that is used to -/// identify the protocol. -pub const PROTOCOL_ID: i64 = 0x0417_2710_1980; +#[derive(Clone, Debug)] +pub struct RawRequest { + payload: Vec, + from: SocketAddr, +} + +#[cfg(test)] +pub(crate) mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use bittorrent_udp_tracker_core::event::Event; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + + pub fn sample_peer() -> peer::Peer { + peer::Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), + event: AnnounceEvent::Started, + } + } + + #[must_use] + pub fn announce_events_match(event: &Event, expected_event: &Event) -> bool { + match (event, expected_event) { + ( + Event::UdpAnnounce { + connection, + info_hash, + announcement, + }, + Event::UdpAnnounce { + connection: expected_connection, + info_hash: expected_info_hash, + announcement: expected_announcement, + }, + ) => { + *connection == *expected_connection + && *info_hash == *expected_info_hash + && announcement.peer_id == expected_announcement.peer_id + && announcement.peer_addr == expected_announcement.peer_addr + // Events can't be compared due to the `updated` field. + // The `announcement.uploaded` contains the current time + // when the test is executed. + // todo: mock time + //&& announcement.updated == expected_announcement.updated + && announcement.uploaded == expected_announcement.uploaded + && announcement.downloaded == expected_announcement.downloaded + && announcement.left == expected_announcement.left + && announcement.event == expected_announcement.event + } + _ => false, + } + } +} diff --git a/packages/udp-tracker-server/src/server/bound_socket.rs b/packages/udp-tracker-server/src/server/bound_socket.rs new file mode 100644 index 000000000..6b81545d2 --- /dev/null +++ b/packages/udp-tracker-server/src/server/bound_socket.rs @@ -0,0 +1,79 @@ +use std::fmt::Debug; +use std::net::SocketAddr; +use std::ops::Deref; + +use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; +use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; +use url::Url; + +/// Wrapper for Tokio [`UdpSocket`][`tokio::net::UdpSocket`] that is bound to a particular socket. +pub struct BoundSocket { + socket: tokio::net::UdpSocket, +} + +impl BoundSocket { + /// # Errors + /// + /// Will return an error if the socket can't be bound the the provided address. + pub async fn new(addr: SocketAddr) -> Result> { + let bind_addr = format!("udp://{addr}"); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, bind_addr, "UdpSocket::new (binding)"); + + let socket = tokio::net::UdpSocket::bind(addr).await; + + let socket = match socket { + Ok(socket) => socket, + Err(e) => Err(e)?, + }; + + let local_addr = format!("udp://{}", socket.local_addr()?); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "UdpSocket::new (bound)"); + + Ok(Self { socket }) + } + + /// # Panics + /// + /// Will panic if the socket can't get the address it was bound to. + #[must_use] + pub fn address(&self) -> SocketAddr { + self.socket.local_addr().expect("it should get local address") + } + + /// # Panics + /// + /// Will panic if the address the socket was bound to is not a valid address + /// to be used in a URL. + #[must_use] + pub fn url(&self) -> Url { + Url::parse(&format!("udp://{}", self.address())).expect("UDP socket address should be valid") + } + + /// # Panics + /// + /// It should never panic because the conversion to a [`ServiceBinding`] + /// is infallible. + #[must_use] + pub fn service_binding(&self) -> ServiceBinding { + ServiceBinding::new(Protocol::UDP, self.address()).expect("Conversion to ServiceBinding should not fail") + } +} + +impl Deref for BoundSocket { + type Target = tokio::net::UdpSocket; + + fn deref(&self) -> &Self::Target { + &self.socket + } +} + +impl Debug for BoundSocket { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let local_addr = match self.socket.local_addr() { + Ok(socket) => format!("Receiving From: {socket}"), + Err(err) => format!("Socket Broken: {err}"), + }; + + f.debug_struct("UdpSocket").field("addr", &local_addr).finish_non_exhaustive() + } +} diff --git a/packages/udp-tracker-server/src/server/launcher.rs b/packages/udp-tracker-server/src/server/launcher.rs new file mode 100644 index 000000000..4fd3a95d9 --- /dev/null +++ b/packages/udp-tracker-server/src/server/launcher.rs @@ -0,0 +1,253 @@ +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +use bittorrent_tracker_client::udp::client::check; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; +use bittorrent_udp_tracker_core::{self, UDP_TRACKER_LOG_TARGET}; +use derive_more::Constructor; +use futures_util::StreamExt; +use tokio::select; +use tokio::sync::oneshot; +use tokio::time::interval; +use torrust_server_lib::logging::STARTED_ON; +use torrust_server_lib::registar::ServiceHealthCheckJob; +use torrust_server_lib::signals::{shutdown_signal_with_message, Halted, Started}; +use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; +use tracing::instrument; + +use super::request_buffer::ActiveRequests; +use crate::container::UdpTrackerServerContainer; +use crate::event::{ConnectionContext, Event}; +use crate::server::bound_socket::BoundSocket; +use crate::server::processor::Processor; +use crate::server::receiver::Receiver; + +const IP_BANS_RESET_INTERVAL_IN_SECS: u64 = 3600 * 24; + +const TYPE_STRING: &str = "udp_tracker"; +/// A UDP server instance launcher. +#[derive(Constructor)] +pub struct Launcher; + +impl Launcher { + /// It starts the UDP server instance with graceful shutdown. + /// + /// # Panics + /// + /// It panics if unable to bind to udp socket, and get the address from the udp socket. + /// It panics if unable to send address of socket. + /// It panics if the udp server is loaded when the tracker is private. + #[instrument(skip(udp_tracker_core_container, udp_tracker_server_container, bind_to, tx_start, rx_halt))] + pub async fn run_with_graceful_shutdown( + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, + bind_to: SocketAddr, + cookie_lifetime: Duration, + tx_start: oneshot::Sender, + rx_halt: oneshot::Receiver, + ) { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting on: {bind_to}"); + + if udp_tracker_core_container.tracker_core_container.core_config.private { + tracing::error!("udp services cannot be used for private trackers"); + panic!("it should not use udp if using authentication"); + } + + let socket = tokio::time::timeout(Duration::from_secs(5), BoundSocket::new(bind_to)) + .await + .expect("it should bind to the socket within five seconds"); + + let bound_socket = match socket { + Ok(socket) => socket, + Err(e) => { + tracing::error!(target: UDP_TRACKER_LOG_TARGET, addr = %bind_to, err = %e, "Udp::run_with_graceful_shutdown panic! (error when building socket)" ); + panic!("could not bind to socket!"); + } + }; + + let service_binding = bound_socket.service_binding().clone(); + let address = bound_socket.address(); + let local_udp_url = bound_socket.url().to_string(); + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "{STARTED_ON}: {local_udp_url}"); + + let receiver = Receiver::new(bound_socket.into()); + + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (spawning main loop)"); + + let running = { + let local_addr = local_udp_url.clone(); + tokio::task::spawn(async move { + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_with_graceful_shutdown::task (listening...)"); + let () = Self::run_udp_server_main( + receiver, + udp_tracker_core_container, + udp_tracker_server_container, + cookie_lifetime, + ) + .await; + }) + }; + + tx_start + .send(Started { + service_binding, + address, + }) + .expect("the UDP Tracker service should not be dropped"); + + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (started)"); + + let stop = running.abort_handle(); + + let halt_task = tokio::task::spawn(shutdown_signal_with_message( + rx_halt, + format!("Halting UDP Service Bound to Socket: {address}"), + )); + + select! { + _ = running => { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (stopped)"); }, + _ = halt_task => { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (halting)"); } + } + stop.abort(); + + tokio::task::yield_now().await; // lets allow the other threads to complete. + } + + #[must_use] + #[instrument(skip(service_binding))] + pub fn check(service_binding: &ServiceBinding) -> ServiceHealthCheckJob { + let info = format!("checking the udp tracker health check at: {}", service_binding.bind_address()); + + let service_binding_clone = service_binding.clone(); + + let job = tokio::spawn(async move { check(&service_binding_clone).await }); + + ServiceHealthCheckJob::new(service_binding.clone(), info, TYPE_STRING.to_string(), job) + } + + #[instrument(skip(receiver, udp_tracker_core_container, udp_tracker_server_container))] + async fn run_udp_server_main( + mut receiver: Receiver, + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, + cookie_lifetime: Duration, + ) { + let active_requests = &mut ActiveRequests::default(); + + let server_socket_addr = receiver.bound_socket_address(); + + let server_service_binding = + ServiceBinding::new(Protocol::UDP, server_socket_addr).expect("Bound socket to service binding should not fail"); + + let local_addr = server_service_binding.clone().to_string(); + + let cookie_lifetime = cookie_lifetime.as_secs_f64(); + + let ban_cleaner = udp_tracker_core_container.ban_service.clone(); + + tokio::spawn(async move { + let mut cleaner_interval = interval(Duration::from_secs(IP_BANS_RESET_INTERVAL_IN_SECS)); + + cleaner_interval.tick().await; + + loop { + cleaner_interval.tick().await; + ban_cleaner.write().await.reset_bans(); + } + }); + + loop { + let server_service_binding = + ServiceBinding::new(Protocol::UDP, server_socket_addr).expect("Bound socket to service binding should not fail"); + + if let Some(req) = { + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server (wait for request)"); + receiver.next().await + } { + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop (in)"); + + let req = match req { + Ok(req) => req, + Err(e) => { + if e.kind() == std::io::ErrorKind::Interrupted { + tracing::warn!(target: UDP_TRACKER_LOG_TARGET, local_addr, err = %e, "Udp::run_udp_server::loop (interrupted)"); + return; + } + tracing::error!(target: UDP_TRACKER_LOG_TARGET, local_addr, err = %e, "Udp::run_udp_server::loop break: (got error)"); + break; + } + }; + + let client_socket_addr = req.from; + + if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.stats_event_sender.as_deref() { + udp_server_stats_event_sender + .send(Event::UdpRequestReceived { + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + }) + .await; + } + + if udp_tracker_core_container.ban_service.read().await.is_banned(&req.from.ip()) { + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop continue: (banned ip)"); + + if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.stats_event_sender.as_deref() { + udp_server_stats_event_sender + .send(Event::UdpRequestBanned { + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + }) + .await; + } + + continue; + } + + let processor = Processor::new( + receiver.socket.clone(), + udp_tracker_core_container.clone(), + udp_tracker_server_container.clone(), + cookie_lifetime, + ); + + /* We spawn the new task even if the active requests buffer is + full. This could seem counterintuitive because we are accepting + more request and consuming more memory even if the server is + already busy. However, we "force_push" the new tasks in the + buffer. That means, in the worst scenario we will abort a + running task to make place for the new task. + + Once concern could be to reach an starvation point were we are + only adding and removing tasks without given them the chance to + finish. However, the buffer is yielding before aborting one + tasks, giving it the chance to finish. */ + let abort_handle: tokio::task::AbortHandle = tokio::task::spawn(processor.process_request(req)).abort_handle(); + + if abort_handle.is_finished() { + continue; + } + + let old_request_aborted = active_requests.force_push(abort_handle, &local_addr).await; + + if old_request_aborted { + // Evicted task from active requests buffer was aborted. + + if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.stats_event_sender.as_deref() { + udp_server_stats_event_sender + .send(Event::UdpRequestAborted { + context: ConnectionContext::new(client_socket_addr, server_service_binding), + }) + .await; + } + } + } else { + tokio::task::yield_now().await; + + // the request iterator returned `None`. + tracing::error!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server breaking: (ran dry, should not happen in production!)"); + break; + } + } + } +} diff --git a/packages/udp-tracker-server/src/server/mod.rs b/packages/udp-tracker-server/src/server/mod.rs new file mode 100644 index 000000000..f70e28b27 --- /dev/null +++ b/packages/udp-tracker-server/src/server/mod.rs @@ -0,0 +1,227 @@ +//! Module to handle the UDP server instances. +use std::fmt::Debug; + +use derive_more::derive::Display; +use thiserror::Error; + +use super::RawRequest; + +pub mod bound_socket; +pub mod launcher; +pub mod processor; +pub mod receiver; +pub mod request_buffer; +pub mod spawner; +pub mod states; + +/// Error that can occur when starting or stopping the UDP server. +/// +/// Some errors triggered while starting the server are: +/// +/// - The server cannot bind to the given address. +/// - It cannot get the bound address. +/// +/// Some errors triggered while stopping the server are: +/// +/// - The [`Server`] cannot send the shutdown signal to the spawned UDP service thread. +#[derive(Debug, Error)] +pub enum UdpError { + #[error("Any error to do with the socket")] + FailedToBindSocket(std::io::Error), + + #[error("Any error to do with starting or stopping the sever")] + FailedToStartOrStopServer(String), +} + +/// A UDP server. +/// +/// It's an state machine. Configurations cannot be changed. This struct +/// represents concrete configuration and state. It allows to start and stop the +/// server but always keeping the same configuration. +/// +/// > **NOTICE**: if the configurations changes after running the server it will +/// > reset to the initial value after stopping the server. This struct is not +/// > intended to persist configurations between runs. +#[allow(clippy::module_name_repetitions)] +#[derive(Debug, Display)] +pub struct Server +where + S: std::fmt::Debug + std::fmt::Display, +{ + /// The state of the server: `running` or `stopped`. + pub state: S, +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::time::Duration; + + use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; + use torrust_server_lib::registar::Registar; + use torrust_tracker_configuration::{logging, Configuration}; + use torrust_tracker_test_helpers::configuration::ephemeral_public; + + use super::spawner::Spawner; + use super::Server; + use crate::container::UdpTrackerServerContainer; + + fn initialize_global_services(configuration: &Configuration) { + initialize_static(); + logging::setup(&configuration.logging); + } + + fn initialize_static() { + torrust_tracker_clock::initialize_static(); + bittorrent_udp_tracker_core::initialize_static(); + } + + #[tokio::test] + async fn it_should_be_able_to_start_and_stop() { + let cfg = Arc::new(ephemeral_public()); + let core_config = Arc::new(cfg.core.clone()); + let udp_tracker_config = Arc::new( + cfg.udp_trackers + .clone() + .expect("no UDP services array config provided") + .first() + .expect("no UDP test service config provided") + .clone(), + ); + + initialize_global_services(&cfg); + + let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); + let config = &udp_trackers[0]; + let bind_to = config.bind_address; + let register = &Registar::default(); + + let stopped = Server::new(Spawner::new(bind_to)); + + let udp_tracker_core_container = UdpTrackerCoreContainer::initialize(&core_config, &udp_tracker_config); + let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); + + let started = stopped + .start( + udp_tracker_core_container, + udp_tracker_server_container, + register.give_form(), + config.cookie_lifetime, + ) + .await + .expect("it should start the server"); + + let stopped = started.stop().await.expect("it should stop the server"); + + tokio::time::sleep(Duration::from_secs(1)).await; + + assert_eq!(stopped.state.spawner.bind_to, bind_to); + } + + #[tokio::test] + async fn it_should_be_able_to_start_and_stop_with_wait() { + let cfg = Arc::new(ephemeral_public()); + let core_config = Arc::new(cfg.core.clone()); + let udp_tracker_config = Arc::new( + cfg.udp_trackers + .clone() + .expect("no UDP services array config provided") + .first() + .expect("no UDP test service config provided") + .clone(), + ); + + initialize_global_services(&cfg); + + let bind_to = udp_tracker_config.bind_address; + let register = &Registar::default(); + + let stopped = Server::new(Spawner::new(bind_to)); + + let udp_tracker_core_container = UdpTrackerCoreContainer::initialize(&core_config, &udp_tracker_config); + let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); + + let started = stopped + .start( + udp_tracker_core_container, + udp_tracker_server_container, + register.give_form(), + udp_tracker_config.cookie_lifetime, + ) + .await + .expect("it should start the server"); + + tokio::time::sleep(Duration::from_secs(1)).await; + + let stopped = started.stop().await.expect("it should stop the server"); + + tokio::time::sleep(Duration::from_secs(1)).await; + + assert_eq!(stopped.state.spawner.bind_to, bind_to); + } +} + +/// Todo: submit test to tokio documentation. +#[cfg(test)] +mod test_tokio { + use std::sync::Arc; + use std::time::Duration; + + use tokio::sync::Barrier; + use tokio::task::JoinSet; + + #[tokio::test] + async fn test_barrier_with_aborted_tasks() { + // Create a barrier that requires 10 tasks to proceed. + let barrier = Arc::new(Barrier::new(10)); + let mut tasks = JoinSet::default(); + let mut handles = Vec::default(); + + // Set Barrier to 9/10. + for _ in 0..9 { + let c = barrier.clone(); + handles.push(tasks.spawn(async move { + c.wait().await; + })); + } + + // Abort two tasks: Barrier: 7/10. + for _ in 0..2 { + if let Some(handle) = handles.pop() { + handle.abort(); + } + } + + // Spawn a single task: Barrier 8/10. + let c = barrier.clone(); + handles.push(tasks.spawn(async move { + c.wait().await; + })); + + // give a chance fro the barrier to release. + tokio::time::sleep(Duration::from_millis(50)).await; + + // assert that the barrier isn't removed, i.e. 8, not 10. + for h in &handles { + assert!(!h.is_finished()); + } + + // Spawn two more tasks to trigger the barrier release: Barrier 10/10. + for _ in 0..2 { + let c = barrier.clone(); + handles.push(tasks.spawn(async move { + c.wait().await; + })); + } + + // give a chance fro the barrier to release. + tokio::time::sleep(Duration::from_millis(50)).await; + + // assert that the barrier has been triggered + for h in &handles { + assert!(h.is_finished()); + } + + tasks.shutdown().await; + } +} diff --git a/packages/udp-tracker-server/src/server/processor.rs b/packages/udp-tracker-server/src/server/processor.rs new file mode 100644 index 000000000..dd6ba633d --- /dev/null +++ b/packages/udp-tracker-server/src/server/processor.rs @@ -0,0 +1,144 @@ +use std::io::Cursor; +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +use aquatic_udp_protocol::Response; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; +use bittorrent_udp_tracker_core::{self}; +use tokio::time::Instant; +use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; +use tracing::{instrument, Level}; + +use super::bound_socket::BoundSocket; +use crate::container::UdpTrackerServerContainer; +use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; +use crate::handlers::CookieTimeValues; +use crate::{handlers, RawRequest}; + +pub struct Processor { + socket: Arc, + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, + cookie_lifetime: f64, + server_service_binding: ServiceBinding, +} + +impl Processor { + /// # Panics + /// + /// It will panic if a bound socket address port is 0. It should never + /// happen. + pub fn new( + socket: Arc, + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, + cookie_lifetime: f64, + ) -> Self { + let server_service_binding = + ServiceBinding::new(Protocol::UDP, socket.address()).expect("Bound socket port should't be 0"); + + Self { + socket, + udp_tracker_core_container, + udp_tracker_server_container, + cookie_lifetime, + server_service_binding, + } + } + + #[instrument(skip(self, request))] + pub async fn process_request(self, request: RawRequest) { + let client_socket_addr = request.from; + + let start_time = Instant::now(); + + let (response, opt_req_kind) = handlers::handle_packet( + request, + self.udp_tracker_core_container.clone(), + self.udp_tracker_server_container.clone(), + self.server_service_binding.clone(), + CookieTimeValues::new(self.cookie_lifetime), + ) + .await; + + let elapsed_time = start_time.elapsed(); + + self.send_response(client_socket_addr, response, opt_req_kind, elapsed_time) + .await; + } + + #[instrument(skip(self))] + async fn send_response( + self, + client_socket_addr: SocketAddr, + response: Response, + opt_req_kind: Option, + req_processing_time: Duration, + ) { + tracing::debug!("send response"); + + let response_type = match &response { + Response::Connect(_) => "Connect".to_string(), + Response::AnnounceIpv4(_) => "AnnounceIpv4".to_string(), + Response::AnnounceIpv6(_) => "AnnounceIpv6".to_string(), + Response::Scrape(_) => "Scrape".to_string(), + Response::Error(e) => format!("Error: {e:?}"), + }; + + let udp_response_kind = match &response { + Response::Error(_e) => event::UdpResponseKind::Error { opt_req_kind: None }, + _ => { + if let Some(req_kind) = opt_req_kind { + event::UdpResponseKind::Ok { req_kind } + } else { + // code-review: this case should never happen. + event::UdpResponseKind::Error { opt_req_kind } + } + } + }; + + let mut writer = Cursor::new(Vec::with_capacity(200)); + + match response.write_bytes(&mut writer) { + Ok(()) => { + let bytes_count = writer.get_ref().len(); + let payload = writer.get_ref(); + + let () = match self.send_packet(&client_socket_addr, payload).await { + Ok(sent_bytes) => { + if tracing::event_enabled!(Level::TRACE) { + tracing::debug!(%bytes_count, %sent_bytes, ?payload, "sent {response_type}"); + } else { + tracing::debug!(%bytes_count, %sent_bytes, "sent {response_type}"); + } + + if let Some(udp_server_stats_event_sender) = + self.udp_tracker_server_container.stats_event_sender.as_deref() + { + udp_server_stats_event_sender + .send(Event::UdpResponseSent { + context: ConnectionContext::new(client_socket_addr, self.server_service_binding), + kind: udp_response_kind, + req_processing_time, + }) + .await; + } + } + Err(error) => tracing::warn!(%bytes_count, %error, ?payload, "failed to send"), + }; + } + Err(e) => { + tracing::error!(%e, "error"); + } + } + } + + #[instrument(skip(self))] + async fn send_packet(&self, target: &SocketAddr, payload: &[u8]) -> std::io::Result { + tracing::trace!("send packet"); + + // doesn't matter if it reaches or not + self.socket.send_to(payload, target).await + } +} diff --git a/packages/udp-tracker-server/src/server/receiver.rs b/packages/udp-tracker-server/src/server/receiver.rs new file mode 100644 index 000000000..89fbed081 --- /dev/null +++ b/packages/udp-tracker-server/src/server/receiver.rs @@ -0,0 +1,54 @@ +use std::cell::RefCell; +use std::net::SocketAddr; +use std::pin::Pin; +use std::sync::Arc; +use std::task::{Context, Poll}; + +use futures::Stream; + +use super::bound_socket::BoundSocket; +use super::RawRequest; +use crate::MAX_PACKET_SIZE; + +pub struct Receiver { + pub socket: Arc, + data: RefCell<[u8; MAX_PACKET_SIZE]>, +} + +impl Receiver { + #[must_use] + pub fn new(bound_socket: Arc) -> Self { + Receiver { + socket: bound_socket, + data: RefCell::new([0; MAX_PACKET_SIZE]), + } + } + + pub fn bound_socket_address(&self) -> SocketAddr { + self.socket.address() + } +} + +impl Stream for Receiver { + type Item = std::io::Result; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let mut buf = *self.data.borrow_mut(); + let mut buf = tokio::io::ReadBuf::new(&mut buf); + + let Poll::Ready(ready) = self.socket.poll_recv_from(cx, &mut buf) else { + return Poll::Pending; + }; + + let res = match ready { + Ok(from) => { + let payload = buf.filled().to_vec(); + let request = RawRequest { payload, from }; + Some(Ok(request)) + } + Err(err) => Some(Err(err)), + }; + + Poll::Ready(res) + } +} diff --git a/packages/udp-tracker-server/src/server/request_buffer.rs b/packages/udp-tracker-server/src/server/request_buffer.rs new file mode 100644 index 000000000..6e420306e --- /dev/null +++ b/packages/udp-tracker-server/src/server/request_buffer.rs @@ -0,0 +1,146 @@ +use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; +use ringbuf::traits::{Consumer, Observer, Producer}; +use ringbuf::StaticRb; +use tokio::task::AbortHandle; + +/// A ring buffer for managing active UDP request abort handles. +/// +/// The `ActiveRequests` struct maintains a fixed-size ring buffer of abort +/// handles for UDP request processor tasks. It ensures that at most 50 requests +/// are handled concurrently, and provides mechanisms to handle buffer overflow +/// by removing finished or oldest unfinished tasks. +#[derive(Default)] +pub struct ActiveRequests { + rb: StaticRb, // The number of requests handled simultaneously. +} + +impl std::fmt::Debug for ActiveRequests { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let (left, right) = &self.rb.as_slices(); + let dbg = format!("capacity: {}, left: {left:?}, right: {right:?}", &self.rb.capacity()); + f.debug_struct("ActiveRequests").field("rb", &dbg).finish() + } +} + +impl Drop for ActiveRequests { + fn drop(&mut self) { + for h in self.rb.pop_iter() { + if !h.is_finished() { + h.abort(); + } + } + } +} + +impl ActiveRequests { + /// Inserts an abort handle for a UDP request processor task. + /// + /// If the buffer is full, this method attempts to make space by: + /// + /// 1. Removing finished tasks. + /// 2. Removing the oldest unfinished task if no finished tasks are found. + /// + /// Returns `true` if a task was removed, `false` otherwise. + /// + /// # Panics + /// + /// This method will panic if it cannot make space for adding a new handle. + /// + /// # Arguments + /// + /// * `abort_handle` - The `AbortHandle` for the UDP request processor task. + /// * `local_addr` - A string slice representing the local address for logging. + pub async fn force_push(&mut self, new_task: AbortHandle, local_addr: &str) -> bool { + // Attempt to add the new handle to the buffer. + match self.rb.try_push(new_task) { + Ok(()) => { + // Successfully added the task, no further action needed. + false + } + Err(new_task) => { + // Buffer is full, attempt to make space. + + let mut finished: u64 = 0; + let mut unfinished_task = None; + let mut old_task_aborted = false; + + for old_task in self.rb.pop_iter() { + // We found a finished tasks ... increase the counter and + // continue searching for more and ... + if old_task.is_finished() { + finished += 1; + continue; + } + + // The current removed tasks is not finished. + + // Give it a second chance to finish. + tokio::task::yield_now().await; + + // Recheck if it finished ... increase the counter and + // continue searching for more and ... + if old_task.is_finished() { + finished += 1; + continue; + } + + // At this point we found a "definitive" unfinished task. + + // Log unfinished task. + tracing::debug!( + target: UDP_TRACKER_LOG_TARGET, + local_addr, + removed_count = finished, + "Udp::run_udp_server::loop (got unfinished task)" + ); + + // If no finished tasks were found, abort the current + // unfinished task. + if finished == 0 { + // We make place aborting this task. + old_task.abort(); + old_task_aborted = true; + + tracing::warn!( + target: UDP_TRACKER_LOG_TARGET, + local_addr, + "Udp::run_udp_server::loop aborting request: (no finished tasks)" + ); + + break; + } + + // At this point we found at least one finished task, but the + // current one is not finished and it was removed from the + // buffer, so we need to re-insert in in the buffer. + + // Save the unfinished task for re-entry. + unfinished_task = Some(old_task); + } + + // After this point there can't be a race condition because only + // one thread owns the active buffer. There is no way for the + // buffer to be full again. That means the "expects" should + // never happen. + + // Reinsert the unfinished task if any. + if let Some(h) = unfinished_task { + self.rb.try_push(h).expect("it was previously inserted"); + } + + // Insert the new task. + // + // Notice that space has already been made for this new task in + // the buffer. One or many old task have already been finished + // or yielded, freeing space in the buffer. Or a single + // unfinished task has been aborted to make space for this new + // task. + if !new_task.is_finished() { + self.rb.try_push(new_task).expect("it should have space for this new task."); + } + + old_task_aborted + } + } + } +} diff --git a/packages/udp-tracker-server/src/server/spawner.rs b/packages/udp-tracker-server/src/server/spawner.rs new file mode 100644 index 000000000..46916f6ae --- /dev/null +++ b/packages/udp-tracker-server/src/server/spawner.rs @@ -0,0 +1,52 @@ +//! A thin wrapper for tokio spawn to launch the UDP server launcher as a new task. +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; +use derive_more::derive::Display; +use derive_more::Constructor; +use tokio::sync::oneshot; +use tokio::task::JoinHandle; +use torrust_server_lib::signals::{Halted, Started}; + +use super::launcher::Launcher; +use crate::container::UdpTrackerServerContainer; + +#[derive(Constructor, Copy, Clone, Debug, Display)] +#[display("(with socket): {bind_to}")] +pub struct Spawner { + pub bind_to: SocketAddr, +} + +impl Spawner { + /// It spawns a new task to run the UDP server instance. + /// + /// # Panics + /// + /// It would panic if unable to resolve the `local_addr` from the supplied ´socket´. + #[must_use] + pub fn spawn_launcher( + &self, + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, + cookie_lifetime: Duration, + tx_start: oneshot::Sender, + rx_halt: oneshot::Receiver, + ) -> JoinHandle { + let spawner = Self::new(self.bind_to); + + tokio::spawn(async move { + Launcher::run_with_graceful_shutdown( + udp_tracker_core_container, + udp_tracker_server_container, + spawner.bind_to, + cookie_lifetime, + tx_start, + rx_halt, + ) + .await; + spawner + }) + } +} diff --git a/packages/udp-tracker-server/src/server/states.rs b/packages/udp-tracker-server/src/server/states.rs new file mode 100644 index 000000000..4ad059095 --- /dev/null +++ b/packages/udp-tracker-server/src/server/states.rs @@ -0,0 +1,136 @@ +use std::fmt::Debug; +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; +use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; +use derive_more::derive::Display; +use derive_more::Constructor; +use tokio::task::JoinHandle; +use torrust_server_lib::registar::{ServiceRegistration, ServiceRegistrationForm}; +use torrust_server_lib::signals::{Halted, Started}; +use tracing::{instrument, Level}; + +use super::spawner::Spawner; +use super::{Server, UdpError}; +use crate::container::UdpTrackerServerContainer; +use crate::server::launcher::Launcher; + +/// A UDP server instance controller with no UDP instance running. +#[allow(clippy::module_name_repetitions)] +pub type StoppedUdpServer = Server; + +/// A UDP server instance controller with a running UDP instance. +#[allow(clippy::module_name_repetitions)] +pub type RunningUdpServer = Server; + +/// A stopped UDP server state. +#[derive(Debug, Display)] +#[display("Stopped: {spawner}")] +pub struct Stopped { + pub spawner: Spawner, +} + +/// A running UDP server state. +#[derive(Debug, Display, Constructor)] +#[display("Running (with local address): {local_addr}")] +pub struct Running { + /// The address where the server is bound. + pub local_addr: SocketAddr, + pub halt_task: tokio::sync::oneshot::Sender, + pub task: JoinHandle, +} + +impl Server { + /// Creates a new `UdpServer` instance in `stopped`state. + #[must_use] + pub fn new(spawner: Spawner) -> Self { + Self { + state: Stopped { spawner }, + } + } + + /// It starts the server and returns a `UdpServer` controller in `running` + /// state. + /// + /// # Errors + /// + /// Will return `Err` if UDP can't bind to given bind address. + /// + /// # Panics + /// + /// It panics if unable to receive the bound socket address from service. + #[instrument(skip(self, udp_tracker_core_container, udp_tracker_server_container, form), err, ret(Display, level = Level::INFO))] + pub async fn start( + self, + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, + form: ServiceRegistrationForm, + cookie_lifetime: Duration, + ) -> Result, std::io::Error> { + let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); + let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); + + assert!(!tx_halt.is_closed(), "Halt channel for UDP tracker should be open"); + + // May need to wrap in a task to about a tokio bug. + let task = self.state.spawner.spawn_launcher( + udp_tracker_core_container, + udp_tracker_server_container, + cookie_lifetime, + tx_start, + rx_halt, + ); + + let started = rx_start.await.expect("it should be able to start the service"); + + let service_binding = started.service_binding; + let local_addr = started.address; + + form.send(ServiceRegistration::new(service_binding, Launcher::check)) + .expect("it should be able to send service registration"); + + let running_udp_server: Server = Server { + state: Running { + local_addr, + halt_task: tx_halt, + task, + }, + }; + + let local_addr = format!("udp://{local_addr}"); + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "UdpServer::start (running)"); + + Ok(running_udp_server) + } +} + +impl Server { + /// It stops the server and returns a `UdpServer` controller in `stopped` + /// state. + /// + /// # Errors + /// + /// Will return `Err` if the oneshot channel to send the stop signal + /// has already been called once. + /// + /// # Panics + /// + /// It panics if unable to shutdown service. + #[instrument(skip(self), err, ret(Display, level = Level::INFO))] + pub async fn stop(self) -> Result, UdpError> { + self.state + .halt_task + .send(Halted::Normal) + .map_err(|e| UdpError::FailedToStartOrStopServer(e.to_string()))?; + + let launcher = self.state.task.await.expect("it should shutdown service"); + + let stopped_api_server: Server = Server { + state: Stopped { spawner: launcher }, + }; + + Ok(stopped_api_server) + } +} diff --git a/packages/udp-tracker-server/src/statistics/event/handler/error.rs b/packages/udp-tracker-server/src/statistics/event/handler/error.rs new file mode 100644 index 000000000..63e480ca5 --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/handler/error.rs @@ -0,0 +1,142 @@ +use aquatic_udp_protocol::PeerClient; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::{label_name, metric_name}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::{ConnectionContext, ErrorKind, UdpRequestKind}; +use crate::statistics::repository::Repository; +use crate::statistics::{UDP_TRACKER_SERVER_CONNECTION_ID_ERRORS_TOTAL, UDP_TRACKER_SERVER_ERRORS_TOTAL}; + +pub async fn handle_event( + connection_context: ConnectionContext, + opt_udp_request_kind: Option, + error_kind: ErrorKind, + repository: &Repository, + now: DurationSinceUnixEpoch, +) { + update_extendable_metrics(&connection_context, opt_udp_request_kind, error_kind, repository, now).await; +} + +async fn update_extendable_metrics( + connection_context: &ConnectionContext, + opt_udp_request_kind: Option, + error_kind: ErrorKind, + repository: &Repository, + now: DurationSinceUnixEpoch, +) { + update_all_errors_counter(connection_context, opt_udp_request_kind.clone(), repository, now).await; + update_connection_id_errors_counter(opt_udp_request_kind, error_kind, repository, now).await; +} + +async fn update_all_errors_counter( + connection_context: &ConnectionContext, + opt_udp_request_kind: Option, + repository: &Repository, + now: DurationSinceUnixEpoch, +) { + let mut label_set = LabelSet::from(connection_context.clone()); + + if let Some(kind) = opt_udp_request_kind.clone() { + label_set.upsert(label_name!("request_kind"), kind.to_string().into()); + } + + match repository + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), &label_set, now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + } +} + +async fn update_connection_id_errors_counter( + opt_udp_request_kind: Option, + error_kind: ErrorKind, + repository: &Repository, + now: DurationSinceUnixEpoch, +) { + if let ErrorKind::ConnectionCookie(_) = error_kind { + if let Some(UdpRequestKind::Announce { announce_request }) = opt_udp_request_kind { + let (client_software_name, client_software_version) = extract_name_and_version(&announce_request.peer_id.client()); + + let label_set = LabelSet::from([ + (label_name!("client_software_name"), client_software_name.into()), + (label_name!("client_software_version"), client_software_version.into()), + ]); + + match repository + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_CONNECTION_ID_ERRORS_TOTAL), &label_set, now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; + } + } +} + +fn extract_name_and_version(peer_client: &PeerClient) -> (String, String) { + match peer_client { + PeerClient::BitTorrent(compact_string) => ("BitTorrent".to_string(), compact_string.as_str().to_owned()), + PeerClient::Deluge(compact_string) => ("Deluge".to_string(), compact_string.as_str().to_owned()), + PeerClient::LibTorrentRakshasa(compact_string) => ("lt (rakshasa)".to_string(), compact_string.as_str().to_owned()), + PeerClient::LibTorrentRasterbar(compact_string) => ("lt (rasterbar)".to_string(), compact_string.as_str().to_owned()), + PeerClient::QBitTorrent(compact_string) => ("QBitTorrent".to_string(), compact_string.as_str().to_owned()), + PeerClient::Transmission(compact_string) => ("Transmission".to_string(), compact_string.as_str().to_owned()), + PeerClient::UTorrent(compact_string) => ("µTorrent".to_string(), compact_string.as_str().to_owned()), + PeerClient::UTorrentEmbedded(compact_string) => ("µTorrent Emb.".to_string(), compact_string.as_str().to_owned()), + PeerClient::UTorrentMac(compact_string) => ("µTorrent Mac".to_string(), compact_string.as_str().to_owned()), + PeerClient::UTorrentWeb(compact_string) => ("µTorrent Web".to_string(), compact_string.as_str().to_owned()), + PeerClient::Vuze(compact_string) => ("Vuze".to_string(), compact_string.as_str().to_owned()), + PeerClient::WebTorrent(compact_string) => ("WebTorrent".to_string(), compact_string.as_str().to_owned()), + PeerClient::WebTorrentDesktop(compact_string) => ("WebTorrent Desktop".to_string(), compact_string.as_str().to_owned()), + PeerClient::Mainline(compact_string) => ("Mainline".to_string(), compact_string.as_str().to_owned()), + PeerClient::OtherWithPrefixAndVersion { prefix, version } => { + (format!("Other ({})", prefix.as_str()), version.as_str().to_owned()) + } + PeerClient::OtherWithPrefix(compact_string) => (format!("Other ({compact_string})"), String::new()), + PeerClient::Other => ("Other".to_string(), String::new()), + _ => ("Unknown".to_string(), String::new()), + } +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use torrust_tracker_clock::clock::Time; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event}; + use crate::statistics::event::handler::error::ErrorKind; + use crate::statistics::event::handler::handle_event; + use crate::statistics::repository::Repository; + use crate::CurrentClock; + + #[tokio::test] + async fn should_increase_the_udp4_errors_counter_when_it_receives_a_udp4_error_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpError { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: None, + error: ErrorKind::RequestParse("Invalid request format".to_string()), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_errors_total(), 1); + } +} diff --git a/packages/udp-tracker-server/src/statistics/event/handler/mod.rs b/packages/udp-tracker-server/src/statistics/event/handler/mod.rs new file mode 100644 index 000000000..9e7f5cd47 --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/handler/mod.rs @@ -0,0 +1,40 @@ +mod error; +mod request_aborted; +mod request_accepted; +mod request_banned; +mod request_received; +mod response_sent; + +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::Event; +use crate::statistics::repository::Repository; + +pub async fn handle_event(event: Event, stats_repository: &Repository, now: DurationSinceUnixEpoch) { + match event { + Event::UdpRequestAborted { context } => { + request_aborted::handle_event(context, stats_repository, now).await; + } + Event::UdpRequestBanned { context } => { + request_banned::handle_event(context, stats_repository, now).await; + } + Event::UdpRequestReceived { context } => { + request_received::handle_event(context, stats_repository, now).await; + } + Event::UdpRequestAccepted { context, kind } => { + request_accepted::handle_event(context, kind, stats_repository, now).await; + } + Event::UdpResponseSent { + context, + kind, + req_processing_time, + } => { + response_sent::handle_event(context, kind, req_processing_time, stats_repository, now).await; + } + Event::UdpError { context, kind, error } => { + error::handle_event(context, kind, error, stats_repository, now).await; + } + } + + tracing::debug!("stats: {:?}", stats_repository.get_stats().await); +} diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs new file mode 100644 index 000000000..f340fe51a --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs @@ -0,0 +1,82 @@ +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::ConnectionContext; +use crate::statistics::repository::Repository; +use crate::statistics::UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL; + +pub async fn handle_event(context: ConnectionContext, stats_repository: &Repository, now: DurationSinceUnixEpoch) { + match stats_repository + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), + &LabelSet::from(context), + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use torrust_tracker_clock::clock::Time; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event}; + use crate::statistics::event::handler::handle_event; + use crate::statistics::repository::Repository; + use crate::CurrentClock; + + #[tokio::test] + async fn should_increase_the_number_of_aborted_requests_when_it_receives_a_udp_request_aborted_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpRequestAborted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp_requests_aborted_total(), 1); + } + + #[tokio::test] + async fn should_increase_the_udp_abort_counter_when_it_receives_a_udp_abort_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpRequestAborted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + let stats = stats_repository.get_stats().await; + assert_eq!(stats.udp_requests_aborted_total(), 1); + } +} diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs new file mode 100644 index 000000000..33971926e --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs @@ -0,0 +1,200 @@ +use torrust_tracker_metrics::label::{LabelSet, LabelValue}; +use torrust_tracker_metrics::{label_name, metric_name}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::{ConnectionContext, UdpRequestKind}; +use crate::statistics::repository::Repository; +use crate::statistics::UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL; + +pub async fn handle_event( + context: ConnectionContext, + kind: UdpRequestKind, + stats_repository: &Repository, + now: DurationSinceUnixEpoch, +) { + let mut label_set = LabelSet::from(context); + label_set.upsert(label_name!("request_kind"), LabelValue::new(&kind.to_string())); + match stats_repository + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &label_set, now) + .await + { + Ok(()) => { + tracing::debug!("Successfully increased the counter for UDP requests accepted: {}", label_set); + } + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + + use torrust_tracker_clock::clock::Time; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event}; + use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::statistics::event::handler::handle_event; + use crate::statistics::repository::Repository; + use crate::CurrentClock; + + #[tokio::test] + async fn should_increase_the_udp4_connect_requests_counter_when_it_receives_a_udp4_request_event_of_connect_kind() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpRequestAccepted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: crate::event::UdpRequestKind::Connect, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_connect_requests_accepted_total(), 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_announce_requests_counter_when_it_receives_a_udp4_request_event_of_announce_kind() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpRequestAccepted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: crate::event::UdpRequestKind::Announce { + announce_request: AnnounceRequestBuilder::default().into(), + }, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_announce_requests_accepted_total(), 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_scrape_requests_counter_when_it_receives_a_udp4_request_event_of_scrape_kind() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpRequestAccepted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: crate::event::UdpRequestKind::Scrape, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_scrape_requests_accepted_total(), 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_connect_requests_counter_when_it_receives_a_udp6_request_event_of_connect_kind() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpRequestAccepted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: crate::event::UdpRequestKind::Connect, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_connect_requests_accepted_total(), 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_announce_requests_counter_when_it_receives_a_udp6_request_event_of_announce_kind() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpRequestAccepted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: crate::event::UdpRequestKind::Announce { + announce_request: AnnounceRequestBuilder::default().into(), + }, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_announce_requests_accepted_total(), 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_scrape_requests_counter_when_it_receives_a_udp6_request_event_of_scrape_kind() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpRequestAccepted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: crate::event::UdpRequestKind::Scrape, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_scrape_requests_accepted_total(), 1); + } +} diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs new file mode 100644 index 000000000..10f6cad88 --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs @@ -0,0 +1,82 @@ +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::ConnectionContext; +use crate::statistics::repository::Repository; +use crate::statistics::UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL; + +pub async fn handle_event(context: ConnectionContext, stats_repository: &Repository, now: DurationSinceUnixEpoch) { + match stats_repository + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), + &LabelSet::from(context), + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use torrust_tracker_clock::clock::Time; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event}; + use crate::statistics::event::handler::handle_event; + use crate::statistics::repository::Repository; + use crate::CurrentClock; + + #[tokio::test] + async fn should_increase_the_number_of_banned_requests_when_it_receives_a_udp_request_banned_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpRequestBanned { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp_requests_banned_total(), 1); + } + + #[tokio::test] + async fn should_increase_the_udp_ban_counter_when_it_receives_a_udp_banned_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpRequestBanned { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + let stats = stats_repository.get_stats().await; + assert_eq!(stats.udp_requests_banned_total(), 1); + } +} diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs new file mode 100644 index 000000000..148b9d8da --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs @@ -0,0 +1,59 @@ +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::ConnectionContext; +use crate::statistics::repository::Repository; +use crate::statistics::UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL; + +pub async fn handle_event(context: ConnectionContext, stats_repository: &Repository, now: DurationSinceUnixEpoch) { + match stats_repository + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), + &LabelSet::from(context), + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use torrust_tracker_clock::clock::Time; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event}; + use crate::statistics::event::handler::handle_event; + use crate::statistics::repository::Repository; + use crate::CurrentClock; + + #[tokio::test] + async fn should_increase_the_number_of_incoming_requests_when_it_receives_a_udp4_incoming_request_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpRequestReceived { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_requests_received_total(), 1); + } +} diff --git a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs new file mode 100644 index 000000000..b1a046b5b --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs @@ -0,0 +1,141 @@ +use torrust_tracker_metrics::label::{LabelSet, LabelValue}; +use torrust_tracker_metrics::{label_name, metric_name}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::{ConnectionContext, UdpRequestKind, UdpResponseKind}; +use crate::statistics::repository::Repository; +use crate::statistics::UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL; + +pub async fn handle_event( + context: ConnectionContext, + kind: UdpResponseKind, + req_processing_time: std::time::Duration, + stats_repository: &Repository, + now: DurationSinceUnixEpoch, +) { + let (result_label_value, kind_label_value) = match kind { + UdpResponseKind::Ok { req_kind } => match req_kind { + UdpRequestKind::Connect => { + let mut label_set = LabelSet::from(context.clone()); + label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); + + let _new_avg = stats_repository + .recalculate_udp_avg_processing_time_ns(req_processing_time, &label_set, now) + .await; + + (LabelValue::new("ok"), UdpRequestKind::Connect.into()) + } + UdpRequestKind::Announce { announce_request } => { + let mut label_set = LabelSet::from(context.clone()); + label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); + + let _new_avg = stats_repository + .recalculate_udp_avg_processing_time_ns(req_processing_time, &label_set, now) + .await; + + (LabelValue::new("ok"), UdpRequestKind::Announce { announce_request }.into()) + } + UdpRequestKind::Scrape => { + let mut label_set = LabelSet::from(context.clone()); + label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); + + let _new_avg = stats_repository + .recalculate_udp_avg_processing_time_ns(req_processing_time, &label_set, now) + .await; + + (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Scrape.to_string())) + } + }, + UdpResponseKind::Error { opt_req_kind: _ } => (LabelValue::new("error"), LabelValue::ignore()), + }; + + // Increase the number of responses sent + let mut label_set = LabelSet::from(context); + if result_label_value == LabelValue::new("ok") { + label_set.upsert(label_name!("request_kind"), kind_label_value); + } + label_set.upsert(label_name!("result"), result_label_value); + match stats_repository + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), &label_set, now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + + use torrust_tracker_clock::clock::Time; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event}; + use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::statistics::event::handler::handle_event; + use crate::statistics::repository::Repository; + use crate::CurrentClock; + + #[tokio::test] + async fn should_increase_the_udp4_responses_counter_when_it_receives_a_udp4_response_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpResponseSent { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: crate::event::UdpResponseKind::Ok { + req_kind: crate::event::UdpRequestKind::Announce { + announce_request: AnnounceRequestBuilder::default().into(), + }, + }, + req_processing_time: std::time::Duration::from_secs(1), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_responses_sent_total(), 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_response_counter_when_it_receives_a_udp6_response_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::UdpResponseSent { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: crate::event::UdpResponseKind::Ok { + req_kind: crate::event::UdpRequestKind::Announce { + announce_request: AnnounceRequestBuilder::default().into(), + }, + }, + req_processing_time: std::time::Duration::from_secs(1), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_responses_sent_total(), 1); + } +} diff --git a/packages/udp-tracker-server/src/statistics/event/listener.rs b/packages/udp-tracker-server/src/statistics/event/listener.rs new file mode 100644 index 000000000..caaf5a2bc --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/listener.rs @@ -0,0 +1,59 @@ +use std::sync::Arc; + +use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; +use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_events::receiver::RecvError; + +use super::handler::handle_event; +use crate::event::receiver::Receiver; +use crate::statistics::repository::Repository; +use crate::CurrentClock; + +#[must_use] +pub fn run_event_listener( + receiver: Receiver, + cancellation_token: CancellationToken, + repository: &Arc, +) -> JoinHandle<()> { + let repository_clone = repository.clone(); + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker server event listener"); + + tokio::spawn(async move { + dispatch_events(receiver, cancellation_token, repository_clone).await; + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "UDP tracker server event listener finished"); + }) +} + +async fn dispatch_events(mut receiver: Receiver, cancellation_token: CancellationToken, stats_repository: Arc) { + loop { + tokio::select! { + biased; + + () = cancellation_token.cancelled() => { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Received cancellation request, shutting down UDP tracker server event listener."); + break; + } + + result = receiver.recv() => { + match result { + Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, + Err(e) => { + match e { + RecvError::Closed => { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp tracker server statistics receiver closed."); + break; + } + RecvError::Lagged(n) => { + tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp tracker server statistics receiver lagged by {} events.", n); + } + } + } + } + } + } + } +} diff --git a/packages/udp-tracker-server/src/statistics/event/mod.rs b/packages/udp-tracker-server/src/statistics/event/mod.rs new file mode 100644 index 000000000..dae683398 --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/mod.rs @@ -0,0 +1,2 @@ +pub mod handler; +pub mod listener; diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs new file mode 100644 index 000000000..e167dc5ae --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -0,0 +1,1315 @@ +use std::time::Duration; + +use serde::Serialize; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::aggregate::avg::Avg; +use torrust_tracker_metrics::metric_collection::aggregate::sum::Sum; +use torrust_tracker_metrics::metric_collection::{Error, MetricCollection}; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::statistics::{ + UDP_TRACKER_SERVER_ERRORS_TOTAL, UDP_TRACKER_SERVER_IPS_BANNED_TOTAL, + UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL, UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS, + UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL, + UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL, + UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL, +}; + +/// Metrics collected by the UDP tracker server. +#[derive(Debug, PartialEq, Default, Serialize)] +pub struct Metrics { + /// A collection of metrics. + pub metric_collection: MetricCollection, +} + +impl Metrics { + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn increase_counter( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.increment_counter(metric_name, labels, now) + } + + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn set_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.set_gauge(metric_name, labels, value, now) + } +} + +impl Metrics { + #[allow(clippy::cast_precision_loss)] + pub fn recalculate_udp_avg_processing_time_ns( + &mut self, + req_processing_time: Duration, + label_set: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> f64 { + self.increment_udp_processed_requests_total(label_set, now); + + let processed_requests_total = self.udp_processed_requests_total(label_set) as f64; + let previous_avg = self.udp_avg_processing_time_ns(label_set); + let req_processing_time = req_processing_time.as_nanos() as f64; + + // Moving average: https://en.wikipedia.org/wiki/Moving_average + let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / processed_requests_total; + + tracing::debug!( + "Recalculated UDP average processing time for labels {}: {} ns (previous: {} ns, req_processing_time: {} ns, request_processed_total: {})", + label_set, + new_avg, + previous_avg, + req_processing_time, + processed_requests_total + ); + + self.update_udp_avg_processing_time_ns(new_avg, label_set, now); + + new_avg + } + + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + fn udp_avg_processing_time_ns(&self, label_set: &LabelSet) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + label_set, + ) + .unwrap_or_default() as u64 + } + + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_request_accepted_total(&self, label_set: &LabelSet) -> u64 { + self.metric_collection + .sum(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), label_set) + .unwrap_or_default() as u64 + } + + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + fn udp_processed_requests_total(&self, label_set: &LabelSet) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL), + label_set, + ) + .unwrap_or_default() as u64 + } + + fn update_udp_avg_processing_time_ns(&mut self, new_avg: f64, label_set: &LabelSet, now: DurationSinceUnixEpoch) { + tracing::debug!( + "Updating average processing time metric to {} ns for label set {}", + new_avg, + label_set, + ); + + match self.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + label_set, + new_avg, + now, + ) { + Ok(()) => {} + Err(err) => tracing::error!("Failed to set gauge: {}", err), + } + } + + fn increment_udp_processed_requests_total(&mut self, label_set: &LabelSet, now: DurationSinceUnixEpoch) { + tracing::debug!("Incrementing processed requests total for label set {}", label_set,); + + match self.increase_counter( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL), + label_set, + now, + ) { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increment counter: {}", err), + } + } + + // UDP + /// Total number of UDP (UDP tracker) requests aborted. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_requests_aborted_total(&self) -> u64 { + self.metric_collection + .sum(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &LabelSet::empty()) + .unwrap_or_default() as u64 + } + + /// Total number of UDP (UDP tracker) requests banned. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_requests_banned_total(&self) -> u64 { + self.metric_collection + .sum(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), &LabelSet::empty()) + .unwrap_or_default() as u64 + } + + /// Total number of banned IPs. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_banned_ips_total(&self) -> u64 { + self.metric_collection + .sum(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &LabelSet::empty()) + .unwrap_or_default() as u64 + } + + /// Average processing time for UDP connect requests across all servers (in nanoseconds). + /// This calculates the average of all gauge samples for connect requests. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_avg_connect_processing_time_ns_averaged(&self) -> u64 { + self.metric_collection + .avg( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &[("request_kind", "connect")].into(), + ) + .unwrap_or(0.0) as u64 + } + + /// Average processing time for UDP announce requests across all servers (in nanoseconds). + /// This calculates the average of all gauge samples for announce requests. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_avg_announce_processing_time_ns_averaged(&self) -> u64 { + self.metric_collection + .avg( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &[("request_kind", "announce")].into(), + ) + .unwrap_or(0.0) as u64 + } + + /// Average processing time for UDP scrape requests across all servers (in nanoseconds). + /// This calculates the average of all gauge samples for scrape requests. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_avg_scrape_processing_time_ns_averaged(&self) -> u64 { + self.metric_collection + .avg( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &[("request_kind", "scrape")].into(), + ) + .unwrap_or(0.0) as u64 + } + + // UDPv4 + /// Total number of UDP (UDP tracker) requests from IPv4 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_requests_received_total(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of UDP (UDP tracker) connections from IPv4 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_connect_requests_accepted_total(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "connect")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_announce_requests_accepted_total(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "announce")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_scrape_requests_accepted_total(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of UDP (UDP tracker) responses from IPv4 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_responses_sent_total(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), + &[("server_binding_address_ip_family", "inet")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of UDP (UDP tracker) `error` requests from IPv4 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_errors_total(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), + &[("server_binding_address_ip_family", "inet")].into(), + ) + .unwrap_or_default() as u64 + } + + // UDPv6 + /// Total number of UDP (UDP tracker) requests from IPv6 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_requests_received_total(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet6")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_connect_requests_accepted_total(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "connect")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_announce_requests_accepted_total(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_scrape_requests_accepted_total(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "scrape")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of UDP (UDP tracker) responses from IPv6 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_responses_sent_total(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), + &[("server_binding_address_ip_family", "inet6")].into(), + ) + .unwrap_or_default() as u64 + } + + /// Total number of UDP (UDP tracker) `error` requests from IPv6 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_errors_total(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), + &[("server_binding_address_ip_family", "inet6")].into(), + ) + .unwrap_or_default() as u64 + } +} + +#[cfg(test)] +mod tests { + use torrust_tracker_clock::clock::Time; + use torrust_tracker_metrics::metric_name; + + use super::*; + use crate::statistics::{ + UDP_TRACKER_SERVER_ERRORS_TOTAL, UDP_TRACKER_SERVER_IPS_BANNED_TOTAL, + UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL, UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS, + UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL, + UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL, + UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL, + }; + use crate::CurrentClock; + + #[test] + fn it_should_implement_default() { + let metrics = Metrics::default(); + // MetricCollection starts with empty collections + assert_eq!(metrics, Metrics::default()); + } + + #[test] + fn it_should_implement_debug() { + let metrics = Metrics::default(); + let debug_string = format!("{metrics:?}"); + assert!(debug_string.contains("Metrics")); + assert!(debug_string.contains("metric_collection")); + } + + #[test] + fn it_should_implement_partial_eq() { + let metrics1 = Metrics::default(); + let metrics2 = Metrics::default(); + assert_eq!(metrics1, metrics2); + } + + #[test] + fn it_should_increase_counter_metric() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + let result = metrics.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &labels, now); + + assert!(result.is_ok()); + } + + #[test] + fn it_should_increase_counter_metric_with_labels() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet")]); + + let result = metrics.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &labels, now); + + assert!(result.is_ok()); + } + + #[test] + fn it_should_set_gauge_metric() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + let result = metrics.set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 42.0, now); + + assert!(result.is_ok()); + } + + #[test] + fn it_should_set_gauge_metric_with_labels() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("request_kind", "connect")]); + + let result = metrics.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels, + 1000.0, + now, + ); + + assert!(result.is_ok()); + } + + #[test] + fn it_should_return_zero_for_udp_processed_requests_total_when_no_data() { + let metrics = Metrics::default(); + let labels = LabelSet::from([("request_kind", "connect")]); + assert_eq!(metrics.udp_processed_requests_total(&labels), 0); + } + + #[test] + fn it_should_increment_processed_requests_total() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("request_kind", "connect")]); + + // Directly increment the counter using the public method + metrics + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL), + &labels, + now, + ) + .unwrap(); + + assert_eq!(metrics.udp_processed_requests_total(&labels), 1); + } + + mod udp_general_metrics { + use super::*; + + #[test] + fn it_should_return_zero_for_udp_requests_aborted_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp_requests_aborted_total(), 0); + } + + #[test] + fn it_should_return_sum_of_udp_requests_aborted() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &labels, now) + .unwrap(); + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &labels, now) + .unwrap(); + + assert_eq!(metrics.udp_requests_aborted_total(), 2); + } + + #[test] + fn it_should_return_zero_for_udp_requests_banned_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp_requests_banned_total(), 0); + } + + #[test] + fn it_should_return_sum_of_udp_requests_banned() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + for _ in 0..3 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp_requests_banned_total(), 3); + } + + #[test] + fn it_should_return_zero_for_udp_banned_ips_total_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp_banned_ips_total(), 0); + } + + #[test] + fn it_should_return_gauge_value_for_udp_banned_ips_total() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + metrics + .set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 10.0, now) + .unwrap(); + + assert_eq!(metrics.udp_banned_ips_total(), 10); + } + } + + mod udpv4_metrics { + use super::*; + + #[test] + fn it_should_return_zero_for_udp4_requests_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp4_requests_received_total(), 0); + } + + #[test] + fn it_should_return_sum_of_udp4_requests() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet")]); + + for _ in 0..5 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp4_requests_received_total(), 5); + } + + #[test] + fn it_should_return_zero_for_udp4_connections_handled_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp4_connect_requests_accepted_total(), 0); + } + + #[test] + fn it_should_return_sum_of_udp4_connections_handled() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "connect")]); + + for _ in 0..3 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp4_connect_requests_accepted_total(), 3); + } + + #[test] + fn it_should_return_zero_for_udp4_announces_handled_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp4_announce_requests_accepted_total(), 0); + } + + #[test] + fn it_should_return_sum_of_udp4_announces_handled() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "announce")]); + + for _ in 0..7 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp4_announce_requests_accepted_total(), 7); + } + + #[test] + fn it_should_return_zero_for_udp4_scrapes_handled_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp4_scrape_requests_accepted_total(), 0); + } + + #[test] + fn it_should_return_sum_of_udp4_scrapes_handled() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")]); + + for _ in 0..4 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp4_scrape_requests_accepted_total(), 4); + } + + #[test] + fn it_should_return_zero_for_udp4_responses_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp4_responses_sent_total(), 0); + } + + #[test] + fn it_should_return_sum_of_udp4_responses() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet")]); + + for _ in 0..6 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp4_responses_sent_total(), 6); + } + + #[test] + fn it_should_return_zero_for_udp4_errors_handled_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp4_errors_total(), 0); + } + + #[test] + fn it_should_return_sum_of_udp4_errors_handled() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet")]); + + for _ in 0..2 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp4_errors_total(), 2); + } + } + + mod udpv6_metrics { + use super::*; + + #[test] + fn it_should_return_zero_for_udp6_requests_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp6_requests_received_total(), 0); + } + + #[test] + fn it_should_return_sum_of_udp6_requests() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet6")]); + + for _ in 0..8 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp6_requests_received_total(), 8); + } + + #[test] + fn it_should_return_zero_for_udp6_connections_handled_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp6_connect_requests_accepted_total(), 0); + } + + #[test] + fn it_should_return_sum_of_udp6_connections_handled() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet6"), ("request_kind", "connect")]); + + for _ in 0..4 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp6_connect_requests_accepted_total(), 4); + } + + #[test] + fn it_should_return_zero_for_udp6_announces_handled_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp6_announce_requests_accepted_total(), 0); + } + + #[test] + fn it_should_return_sum_of_udp6_announces_handled() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")]); + + for _ in 0..9 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp6_announce_requests_accepted_total(), 9); + } + + #[test] + fn it_should_return_zero_for_udp6_scrapes_handled_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp6_scrape_requests_accepted_total(), 0); + } + + #[test] + fn it_should_return_sum_of_udp6_scrapes_handled() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet6"), ("request_kind", "scrape")]); + + for _ in 0..6 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp6_scrape_requests_accepted_total(), 6); + } + + #[test] + fn it_should_return_zero_for_udp6_responses_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp6_responses_sent_total(), 0); + } + + #[test] + fn it_should_return_sum_of_udp6_responses() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet6")]); + + for _ in 0..11 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp6_responses_sent_total(), 11); + } + + #[test] + fn it_should_return_zero_for_udp6_errors_handled_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp6_errors_total(), 0); + } + + #[test] + fn it_should_return_sum_of_udp6_errors_handled() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet6")]); + + for _ in 0..3 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp6_errors_total(), 3); + } + } + + mod combined_metrics { + use super::*; + + #[test] + fn it_should_distinguish_between_ipv4_and_ipv6_metrics() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + + let ipv4_labels = LabelSet::from([("server_binding_address_ip_family", "inet")]); + let ipv6_labels = LabelSet::from([("server_binding_address_ip_family", "inet6")]); + + // Add different counts for IPv4 and IPv6 + for _ in 0..3 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &ipv4_labels, now) + .unwrap(); + } + + for _ in 0..7 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &ipv6_labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp4_requests_received_total(), 3); + assert_eq!(metrics.udp6_requests_received_total(), 7); + } + + #[test] + fn it_should_distinguish_between_different_request_kinds() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + + let connect_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "connect")]); + let announce_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "announce")]); + let scrape_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")]); + + // Add different counts for different request kinds + for _ in 0..2 { + metrics + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &connect_labels, + now, + ) + .unwrap(); + } + + for _ in 0..5 { + metrics + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &announce_labels, + now, + ) + .unwrap(); + } + + for _ in 0..1 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &scrape_labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp4_connect_requests_accepted_total(), 2); + assert_eq!(metrics.udp4_announce_requests_accepted_total(), 5); + assert_eq!(metrics.udp4_scrape_requests_accepted_total(), 1); + } + + #[test] + fn it_should_handle_mixed_ipv4_and_ipv6_for_different_request_kinds() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + + let ipv4_connect_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "connect")]); + let ipv6_connect_labels = + LabelSet::from([("server_binding_address_ip_family", "inet6"), ("request_kind", "connect")]); + let ipv4_announce_labels = + LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "announce")]); + let ipv6_announce_labels = + LabelSet::from([("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")]); + + // Add mixed IPv4/IPv6 counts + for _ in 0..3 { + metrics + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &ipv4_connect_labels, + now, + ) + .unwrap(); + } + + for _ in 0..2 { + metrics + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &ipv6_connect_labels, + now, + ) + .unwrap(); + } + + for _ in 0..4 { + metrics + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &ipv4_announce_labels, + now, + ) + .unwrap(); + } + + for _ in 0..6 { + metrics + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &ipv6_announce_labels, + now, + ) + .unwrap(); + } + + assert_eq!(metrics.udp4_connect_requests_accepted_total(), 3); + assert_eq!(metrics.udp6_connect_requests_accepted_total(), 2); + assert_eq!(metrics.udp4_announce_requests_accepted_total(), 4); + assert_eq!(metrics.udp6_announce_requests_accepted_total(), 6); + } + } + + mod edge_cases { + use super::*; + + #[test] + fn it_should_handle_large_counter_values() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + // Add a large number of increments + for _ in 0..1000 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp_requests_aborted_total(), 1000); + } + + #[test] + fn it_should_handle_large_gauge_values() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + // Set a large gauge value + metrics + .set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 999_999.0, now) + .unwrap(); + + assert_eq!(metrics.udp_banned_ips_total(), 999_999); + } + + #[test] + fn it_should_handle_zero_gauge_values() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + metrics + .set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 0.0, now) + .unwrap(); + + assert_eq!(metrics.udp_banned_ips_total(), 0); + } + + #[test] + fn it_should_overwrite_gauge_values_when_set_multiple_times() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + // Set initial value + metrics + .set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 50.0, now) + .unwrap(); + + assert_eq!(metrics.udp_banned_ips_total(), 50); + + // Overwrite with new value + metrics + .set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 75.0, now) + .unwrap(); + + assert_eq!(metrics.udp_banned_ips_total(), 75); + } + + #[test] + fn it_should_handle_empty_label_sets() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let empty_labels = LabelSet::empty(); + + let result = metrics.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &empty_labels, now); + + assert!(result.is_ok()); + assert_eq!(metrics.udp_requests_aborted_total(), 1); + } + + #[test] + fn it_should_handle_multiple_labels_on_same_metric() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + + let labels1 = LabelSet::from([("server_binding_address_ip_family", "inet")]); + let labels2 = LabelSet::from([("server_binding_address_ip_family", "inet6")]); + + // Add to same metric with different labels + for _ in 0..3 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &labels1, now) + .unwrap(); + } + + for _ in 0..5 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &labels2, now) + .unwrap(); + } + + // Should return labeled sums correctly + assert_eq!(metrics.udp4_requests_received_total(), 3); + assert_eq!(metrics.udp6_requests_received_total(), 5); + } + } + + mod error_handling { + use super::*; + + #[test] + fn it_should_return_ok_result_for_valid_counter_operations() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + let result = metrics.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &labels, now); + + assert!(result.is_ok()); + } + + #[test] + fn it_should_return_ok_result_for_valid_gauge_operations() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + let result = metrics.set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 42.0, now); + + assert!(result.is_ok()); + } + + #[test] + fn it_should_handle_unknown_metric_names_gracefully() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + // This should still work as metrics are created on demand + let result = metrics.increase_counter(&metric_name!("unknown_metric"), &labels, now); + + assert!(result.is_ok()); + } + } + + mod averaged_processing_time_metrics { + use super::*; + + #[test] + fn it_should_return_zero_for_udp_avg_connect_processing_time_ns_averaged_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp_avg_connect_processing_time_ns_averaged(), 0); + } + + #[test] + fn it_should_return_averaged_value_for_udp_avg_connect_processing_time_ns_averaged() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels1 = LabelSet::from([("request_kind", "connect"), ("server_id", "server1")]); + let labels2 = LabelSet::from([("request_kind", "connect"), ("server_id", "server2")]); + + // Set different gauge values for connect requests from different servers + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels1, + 1000.0, + now, + ) + .unwrap(); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels2, + 2000.0, + now, + ) + .unwrap(); + + // Should return the average: (1000 + 2000) / 2 = 1500 + assert_eq!(metrics.udp_avg_connect_processing_time_ns_averaged(), 1500); + } + + #[test] + fn it_should_return_zero_for_udp_avg_announce_processing_time_ns_averaged_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp_avg_announce_processing_time_ns_averaged(), 0); + } + + #[test] + fn it_should_return_averaged_value_for_udp_avg_announce_processing_time_ns_averaged() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels1 = LabelSet::from([("request_kind", "announce"), ("server_id", "server1")]); + let labels2 = LabelSet::from([("request_kind", "announce"), ("server_id", "server2")]); + let labels3 = LabelSet::from([("request_kind", "announce"), ("server_id", "server3")]); + + // Set different gauge values for announce requests from different servers + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels1, + 1500.0, + now, + ) + .unwrap(); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels2, + 2500.0, + now, + ) + .unwrap(); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels3, + 3000.0, + now, + ) + .unwrap(); + + // Should return the average: (1500 + 2500 + 3000) / 3 = 2333 (truncated) + assert_eq!(metrics.udp_avg_announce_processing_time_ns_averaged(), 2333); + } + + #[test] + fn it_should_return_zero_for_udp_avg_scrape_processing_time_ns_averaged_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp_avg_scrape_processing_time_ns_averaged(), 0); + } + + #[test] + fn it_should_return_averaged_value_for_udp_avg_scrape_processing_time_ns_averaged() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels1 = LabelSet::from([("request_kind", "scrape"), ("server_id", "server1")]); + let labels2 = LabelSet::from([("request_kind", "scrape"), ("server_id", "server2")]); + + // Set different gauge values for scrape requests from different servers + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels1, + 500.0, + now, + ) + .unwrap(); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels2, + 1500.0, + now, + ) + .unwrap(); + + // Should return the average: (500 + 1500) / 2 = 1000 + assert_eq!(metrics.udp_avg_scrape_processing_time_ns_averaged(), 1000); + } + + #[test] + fn it_should_handle_fractional_averages_with_truncation() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels1 = LabelSet::from([("request_kind", "connect"), ("server_id", "server1")]); + let labels2 = LabelSet::from([("request_kind", "connect"), ("server_id", "server2")]); + let labels3 = LabelSet::from([("request_kind", "connect"), ("server_id", "server3")]); + + // Set values that will result in a fractional average + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels1, + 1000.0, + now, + ) + .unwrap(); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels2, + 1001.0, + now, + ) + .unwrap(); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels3, + 1001.0, + now, + ) + .unwrap(); + + // Should return the average: (1000 + 1001 + 1001) / 3 = 1000.666... → 1000 (truncated) + assert_eq!(metrics.udp_avg_connect_processing_time_ns_averaged(), 1000); + } + + #[test] + fn it_should_only_average_matching_request_kinds() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + + // Set values for different request kinds with the same server_id + let connect_labels = LabelSet::from([("request_kind", "connect"), ("server_id", "server1")]); + let announce_labels = LabelSet::from([("request_kind", "announce"), ("server_id", "server1")]); + let scrape_labels = LabelSet::from([("request_kind", "scrape"), ("server_id", "server1")]); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &connect_labels, + 1000.0, + now, + ) + .unwrap(); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &announce_labels, + 2000.0, + now, + ) + .unwrap(); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &scrape_labels, + 3000.0, + now, + ) + .unwrap(); + + // Each function should only return the value for its specific request kind + assert_eq!(metrics.udp_avg_connect_processing_time_ns_averaged(), 1000); + assert_eq!(metrics.udp_avg_announce_processing_time_ns_averaged(), 2000); + assert_eq!(metrics.udp_avg_scrape_processing_time_ns_averaged(), 3000); + } + + #[test] + fn it_should_handle_single_server_averaged_metrics() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("request_kind", "connect"), ("server_id", "single_server")]); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels, + 1234.0, + now, + ) + .unwrap(); + + // With only one server, the average should be the same as the single value + assert_eq!(metrics.udp_avg_connect_processing_time_ns_averaged(), 1234); + } + } +} diff --git a/packages/udp-tracker-server/src/statistics/mod.rs b/packages/udp-tracker-server/src/statistics/mod.rs new file mode 100644 index 000000000..6bd35b9a1 --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/mod.rs @@ -0,0 +1,90 @@ +pub mod event; +pub mod metrics; +pub mod repository; +pub mod services; + +use metrics::Metrics; +use torrust_tracker_metrics::metric::description::MetricDescription; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_metrics::unit::Unit; + +pub const UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL: &str = "udp_tracker_server_requests_aborted_total"; +pub const UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL: &str = "udp_tracker_server_requests_banned_total"; +pub const UDP_TRACKER_SERVER_IPS_BANNED_TOTAL: &str = "udp_tracker_server_ips_banned_total"; +pub const UDP_TRACKER_SERVER_CONNECTION_ID_ERRORS_TOTAL: &str = "udp_tracker_server_connection_id_errors_total"; +pub const UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL: &str = "udp_tracker_server_requests_received_total"; +pub const UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL: &str = "udp_tracker_server_requests_accepted_total"; +pub const UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL: &str = "udp_tracker_server_responses_sent_total"; +pub const UDP_TRACKER_SERVER_ERRORS_TOTAL: &str = "udp_tracker_server_errors_total"; +pub const UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS: &str = "udp_tracker_server_performance_avg_processing_time_ns"; +pub const UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL: &str = + "udp_tracker_server_performance_avg_processed_requests_total"; + +#[must_use] +pub fn describe_metrics() -> Metrics { + let mut metrics = Metrics::default(); + + metrics.metric_collection.describe_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("Total number of UDP requests aborted")), + ); + + metrics.metric_collection.describe_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("Total number of UDP requests banned")), + ); + + metrics.metric_collection.describe_gauge( + &metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("Total number of IPs banned from UDP requests")), + ); + + metrics.metric_collection.describe_counter( + &metric_name!(UDP_TRACKER_SERVER_CONNECTION_ID_ERRORS_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("Total number of requests with connection ID errors")), + ); + + metrics.metric_collection.describe_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("Total number of UDP requests received")), + ); + + metrics.metric_collection.describe_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("Total number of UDP requests accepted")), + ); + + metrics.metric_collection.describe_counter( + &metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("Total number of UDP responses sent")), + ); + + metrics.metric_collection.describe_counter( + &metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("Total number of errors processing UDP requests")), + ); + + metrics.metric_collection.describe_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + Some(Unit::Nanoseconds), + Some(MetricDescription::new("Average time to process a UDP request in nanoseconds")), + ); + + metrics.metric_collection.describe_counter( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new( + "Total number of UDP requests processed for the average performance metrics", + )), + ); + + metrics +} diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs new file mode 100644 index 000000000..c4c995b8a --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -0,0 +1,775 @@ +use std::sync::Arc; +use std::time::Duration; + +use tokio::sync::{RwLock, RwLockReadGuard}; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::Error; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::describe_metrics; +use super::metrics::Metrics; + +/// A repository for the tracker metrics. +#[derive(Clone)] +pub struct Repository { + pub stats: Arc>, +} + +impl Default for Repository { + fn default() -> Self { + Self::new() + } +} + +impl Repository { + #[must_use] + pub fn new() -> Self { + Self { + stats: Arc::new(RwLock::new(describe_metrics())), + } + } + + pub async fn get_stats(&self) -> RwLockReadGuard<'_, Metrics> { + self.stats.read().await + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increase the counter. + pub async fn increase_counter( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.increase_counter(metric_name, labels, now); + + drop(stats_lock); + + result + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increase the counter. + pub async fn set_gauge( + &self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.set_gauge(metric_name, labels, value, now); + + drop(stats_lock); + + result + } + + pub async fn recalculate_udp_avg_processing_time_ns( + &self, + req_processing_time: Duration, + label_set: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> f64 { + let mut stats_lock = self.stats.write().await; + + let new_avg = stats_lock.recalculate_udp_avg_processing_time_ns(req_processing_time, label_set, now); + + drop(stats_lock); + + new_avg + } +} + +#[cfg(test)] +mod tests { + use core::f64; + use std::time::Duration; + + use torrust_tracker_clock::clock::Time; + use torrust_tracker_metrics::metric_collection::aggregate::sum::Sum; + use torrust_tracker_metrics::metric_name; + + use super::*; + use crate::statistics::*; + use crate::CurrentClock; + + #[test] + fn it_should_implement_default() { + let repo = Repository::default(); + assert!(!std::ptr::eq(&repo.stats, &Repository::new().stats)); + } + + #[test] + fn it_should_be_cloneable() { + let repo = Repository::new(); + let cloned_repo = repo.clone(); + assert!(!std::ptr::eq(&repo.stats, &cloned_repo.stats)); + } + + #[tokio::test] + async fn it_should_be_initialized_with_described_metrics() { + let repo = Repository::new(); + let stats = repo.get_stats().await; + + // Check that the described metrics are present + assert!(stats + .metric_collection + .contains_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL))); + assert!(stats + .metric_collection + .contains_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL))); + assert!(stats + .metric_collection + .contains_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL))); + assert!(stats + .metric_collection + .contains_counter(&metric_name!(UDP_TRACKER_SERVER_CONNECTION_ID_ERRORS_TOTAL))); + assert!(stats + .metric_collection + .contains_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL))); + assert!(stats + .metric_collection + .contains_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL))); + assert!(stats + .metric_collection + .contains_counter(&metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL))); + assert!(stats + .metric_collection + .contains_counter(&metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL))); + assert!(stats + .metric_collection + .contains_gauge(&metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS))); + } + + #[tokio::test] + async fn it_should_return_a_read_guard_to_metrics() { + let repo = Repository::new(); + let stats = repo.get_stats().await; + + // Should be able to read metrics through the guard + assert_eq!(stats.udp_requests_aborted_total(), 0); + assert_eq!(stats.udp_requests_banned_total(), 0); + } + + #[tokio::test] + async fn it_should_allow_increasing_a_counter_metric_successfully() { + let repo = Repository::new(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + // Increase a counter metric + let result = repo + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &labels, now) + .await; + + assert!(result.is_ok()); + + // Verify the counter was incremented + let stats = repo.get_stats().await; + assert_eq!(stats.udp_requests_aborted_total(), 1); + } + + #[tokio::test] + async fn it_should_allow_increasing_a_counter_multiple_times() { + let repo = Repository::new(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + // Increase counter multiple times + for _ in 0..5 { + repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &labels, now) + .await + .unwrap(); + } + + // Verify the counter was incremented correctly + let stats = repo.get_stats().await; + assert_eq!(stats.udp_requests_aborted_total(), 5); + } + + #[tokio::test] + async fn it_should_allow_increasing_a_counter_with_different_labels() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + let labels_ipv4 = LabelSet::from([("server_binding_address_ip_family", "inet")]); + let labels_ipv6 = LabelSet::from([("server_binding_address_ip_family", "inet6")]); + + // Increase counters with different labels + repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &labels_ipv4, now) + .await + .unwrap(); + + repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &labels_ipv6, now) + .await + .unwrap(); + + // Verify both labeled metrics + let stats = repo.get_stats().await; + assert_eq!(stats.udp4_requests_received_total(), 1); + assert_eq!(stats.udp6_requests_received_total(), 1); + } + + #[tokio::test] + async fn it_should_set_a_gauge_metric_successfully() { + let repo = Repository::new(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + // Set a gauge metric + let result = repo + .set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 42.0, now) + .await; + + assert!(result.is_ok()); + + // Verify the gauge was set + let stats = repo.get_stats().await; + assert_eq!(stats.udp_banned_ips_total(), 42); + } + + #[tokio::test] + async fn it_should_overwrite_previous_value_when_setting_a_gauge_with_a_previous_value() { + let repo = Repository::new(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + // Set gauge to initial value + repo.set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 10.0, now) + .await + .unwrap(); + + // Overwrite with new value + repo.set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 25.0, now) + .await + .unwrap(); + + // Verify the gauge has the new value + let stats = repo.get_stats().await; + assert_eq!(stats.udp_banned_ips_total(), 25); + } + + #[tokio::test] + async fn it_should_allow_setting_a_gauge_with_different_labels() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + let labels_connect = LabelSet::from([("request_kind", "connect")]); + let labels_announce = LabelSet::from([("request_kind", "announce")]); + + // Set gauges with different labels + repo.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels_connect, + 1000.0, + now, + ) + .await + .unwrap(); + + repo.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels_announce, + 2000.0, + now, + ) + .await + .unwrap(); + + // Verify both labeled metrics + let stats = repo.get_stats().await; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp_avg_connect_processing_time_ns = stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &[("request_kind", "connect")].into(), + ) + .unwrap_or_default() as u64; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp_avg_announce_processing_time_ns = stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &[("request_kind", "announce")].into(), + ) + .unwrap_or_default() as u64; + + assert_eq!(udp_avg_connect_processing_time_ns, 1000); + assert_eq!(udp_avg_announce_processing_time_ns, 2000); + } + + #[tokio::test] + async fn it_should_recalculate_the_udp_average_connect_processing_time_in_nanoseconds_using_moving_average() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + // Set initial average to 1000ns + let connect_labels = LabelSet::from([("request_kind", "connect")]); + repo.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &connect_labels, + 1000.0, + now, + ) + .await + .unwrap(); + + // Calculate new average with processing time of 2000ns + // This will increment the processed requests counter from 0 to 1 + let processing_time = Duration::from_micros(2); + let new_avg = repo + .recalculate_udp_avg_processing_time_ns(processing_time, &connect_labels, now) + .await; + + // Moving average: previous_avg + (new_value - previous_avg) / processed_requests_total + // With processed_requests_total = 1 (incremented during the call): + // 1000 + (2000 - 1000) / 1 = 1000 + 1000 = 2000 + let expected_avg = 1000.0 + (2000.0 - 1000.0) / 1.0; + assert!( + (new_avg - expected_avg).abs() < 0.01, + "Expected {expected_avg}, got {new_avg}" + ); + } + + #[tokio::test] + async fn it_should_recalculate_the_udp_average_announce_processing_time_in_nanoseconds_using_moving_average() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + // Set initial average to 500ns + let announce_labels = LabelSet::from([("request_kind", "announce")]); + repo.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &announce_labels, + 500.0, + now, + ) + .await + .unwrap(); + + // Calculate new average with processing time of 1500ns + // This will increment the processed requests counter from 0 to 1 + let processing_time = Duration::from_nanos(1500); + let new_avg = repo + .recalculate_udp_avg_processing_time_ns(processing_time, &announce_labels, now) + .await; + + // Moving average: previous_avg + (new_value - previous_avg) / processed_requests_total + // With processed_requests_total = 1 (incremented during the call): + // 500 + (1500 - 500) / 1 = 500 + 1000 = 1500 + let expected_avg = 500.0 + (1500.0 - 500.0) / 1.0; + assert!( + (new_avg - expected_avg).abs() < 0.01, + "Expected {expected_avg}, got {new_avg}" + ); + } + + #[tokio::test] + async fn it_should_recalculate_the_udp_average_scrape_processing_time_in_nanoseconds_using_moving_average() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + // Set initial average to 800ns + let scrape_labels = LabelSet::from([("request_kind", "scrape")]); + repo.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &scrape_labels, + 800.0, + now, + ) + .await + .unwrap(); + + // Calculate new average with processing time of 1200ns + // This will increment the processed requests counter from 0 to 1 + let processing_time = Duration::from_nanos(1200); + let new_avg = repo + .recalculate_udp_avg_processing_time_ns(processing_time, &scrape_labels, now) + .await; + + // Moving average: previous_avg + (new_value - previous_avg) / processed_requests_total + // With processed_requests_total = 1 (incremented during the call): + // 800 + (1200 - 800) / 1 = 800 + 400 = 1200 + let expected_avg = 800.0 + (1200.0 - 800.0) / 1.0; + assert!( + (new_avg - expected_avg).abs() < 0.01, + "Expected {expected_avg}, got {new_avg}" + ); + } + + #[tokio::test] + async fn recalculate_average_methods_should_handle_zero_connections_gracefully() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + // Test with zero connections (should not panic, should handle division by zero) + let processing_time = Duration::from_micros(1); + + let connect_labels = LabelSet::from([("request_kind", "connect")]); + let connect_avg = repo + .recalculate_udp_avg_processing_time_ns(processing_time, &connect_labels, now) + .await; + + let announce_labels = LabelSet::from([("request_kind", "announce")]); + let announce_avg = repo + .recalculate_udp_avg_processing_time_ns(processing_time, &announce_labels, now) + .await; + + let scrape_labels = LabelSet::from([("request_kind", "scrape")]); + let scrape_avg = repo + .recalculate_udp_avg_processing_time_ns(processing_time, &scrape_labels, now) + .await; + + // With 0 total connections, the formula becomes 0 + (1000 - 0) / 0 + // This should handle the division by zero case gracefully + assert!((connect_avg - 1000.0).abs() < f64::EPSILON); + assert!((announce_avg - 1000.0).abs() < f64::EPSILON); + assert!((scrape_avg - 1000.0).abs() < f64::EPSILON); + } + + #[tokio::test] + async fn it_should_handle_concurrent_access() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + // Spawn multiple concurrent tasks + let mut handles = vec![]; + + for i in 0..10 { + let repo_clone = repo.clone(); + let handle = tokio::spawn(async move { + for _ in 0..5 { + repo_clone + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), + &LabelSet::empty(), + now, + ) + .await + .unwrap(); + } + i + }); + handles.push(handle); + } + + // Wait for all tasks to complete + for handle in handles { + handle.await.unwrap(); + } + + // Verify all increments were properly recorded + let stats = repo.get_stats().await; + assert_eq!(stats.udp_requests_aborted_total(), 50); // 10 tasks * 5 increments each + } + + #[tokio::test] + async fn it_should_handle_large_processing_times() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + // Set up a connection + let ipv4_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "connect")]); + repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &ipv4_labels, now) + .await + .unwrap(); + + // Test with very large processing time + let large_duration = Duration::from_secs(1); // 1 second = 1,000,000,000 ns + let connect_labels = LabelSet::from([("request_kind", "connect")]); + let new_avg = repo + .recalculate_udp_avg_processing_time_ns(large_duration, &connect_labels, now) + .await; + + // Should handle large numbers without overflow + assert!(new_avg > 0.0); + assert!(new_avg.is_finite()); + } + + #[tokio::test] + async fn it_should_maintain_consistency_across_operations() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + // Perform a series of operations + repo.increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), + &LabelSet::empty(), + now, + ) + .await + .unwrap(); + + repo.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), + &LabelSet::empty(), + 10.0, + now, + ) + .await + .unwrap(); + + repo.increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), + &LabelSet::empty(), + now, + ) + .await + .unwrap(); + + // Check final state + let stats = repo.get_stats().await; + assert_eq!(stats.udp_requests_aborted_total(), 1); + assert_eq!(stats.udp_banned_ips_total(), 10); + assert_eq!(stats.udp_requests_banned_total(), 1); + } + + #[tokio::test] + async fn it_should_handle_error_cases_gracefully() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + // Test with invalid metric name (this should still work as metrics are created dynamically) + let result = repo + .increase_counter(&metric_name!("non_existent_metric"), &LabelSet::empty(), now) + .await; + + // Should succeed as metrics are created on demand + assert!(result.is_ok()); + + // Test with NaN value for gauge + let result = repo + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), + &LabelSet::empty(), + f64::NAN, + now, + ) + .await; + + // Should handle NaN values + assert!(result.is_ok()); + } + + mod race_conditions { + + use core::f64; + use std::time::Duration; + + use tokio::task::JoinHandle; + use torrust_tracker_clock::clock::Time; + use torrust_tracker_metrics::metric_name; + + use super::*; + use crate::CurrentClock; + + #[tokio::test] + async fn it_should_handle_race_conditions_when_updating_udp_performance_metrics_in_parallel() { + const REQUESTS_PER_SERVER: usize = 100; + + // ** Set up test data and environment ** + + let repo = Repository::new(); + let now = CurrentClock::now(); + + let server1_labels = create_server_metric_labels("6868"); + let server2_labels = create_server_metric_labels("6969"); + + // ** Execute concurrent metric updates ** + + // Spawn concurrent tasks for server 1 with processing times [1000, 2000, 3000, 4000, 5000] ns + let server1_handles = spawn_server_tasks(&repo, &server1_labels, 1000, now, REQUESTS_PER_SERVER); + + // Spawn concurrent tasks for server 2 with processing times [2000, 3000, 4000, 5000, 6000] ns + let server2_handles = spawn_server_tasks(&repo, &server2_labels, 2000, now, REQUESTS_PER_SERVER); + + // Wait for both servers' results + let (server1_results, server2_results) = tokio::join!( + collect_concurrent_task_results(server1_handles), + collect_concurrent_task_results(server2_handles) + ); + + // ** Verify results and metrics ** + + // Verify correctness of concurrent operations + assert_server_results_are_valid(&server1_results, "Server 1", REQUESTS_PER_SERVER); + assert_server_results_are_valid(&server2_results, "Server 2", REQUESTS_PER_SERVER); + + let stats = repo.get_stats().await; + + // Verify each server's metrics individually + let server1_avg = assert_server_metrics_are_correct(&stats, &server1_labels, "Server 1", REQUESTS_PER_SERVER, 3000.0); + let server2_avg = assert_server_metrics_are_correct(&stats, &server2_labels, "Server 2", REQUESTS_PER_SERVER, 4000.0); + + // Verify relationship between servers + assert_server_metrics_relationship(server1_avg, server2_avg); + + // Verify each server's result consistency individually + assert_server_result_matches_stored_average(&server1_results, &stats, &server1_labels, "Server 1"); + assert_server_result_matches_stored_average(&server2_results, &stats, &server2_labels, "Server 2"); + + // Verify metric collection integrity + assert_metric_collection_integrity(&stats); + } + + // Test helper functions to hide implementation details + + fn create_server_metric_labels(port: &str) -> LabelSet { + LabelSet::from([ + ("request_kind", "connect"), + ("server_binding_address_ip_family", "inet"), + ("server_port", port), + ]) + } + + fn spawn_server_tasks( + repo: &Repository, + labels: &LabelSet, + base_processing_time_ns: usize, + now: DurationSinceUnixEpoch, + requests_per_server: usize, + ) -> Vec> { + let mut handles = vec![]; + + for i in 0..requests_per_server { + let repo_clone = repo.clone(); + let labels_clone = labels.clone(); + let handle = tokio::spawn(async move { + let processing_time_ns = base_processing_time_ns + (i % 5) * 1000; + let processing_time = Duration::from_nanos(processing_time_ns as u64); + repo_clone + .recalculate_udp_avg_processing_time_ns(processing_time, &labels_clone, now) + .await + }); + handles.push(handle); + } + + handles + } + + async fn collect_concurrent_task_results(handles: Vec>) -> Vec { + let mut server_results = Vec::new(); + + for handle in handles { + let result = handle.await.unwrap(); + server_results.push(result); + } + + server_results + } + + fn assert_server_results_are_valid(results: &[f64], server_name: &str, expected_count: usize) { + // Verify all tasks completed + assert_eq!( + results.len(), + expected_count, + "{server_name} should have {expected_count} results" + ); + + // Verify all results are valid numbers + for result in results { + assert!(result.is_finite(), "{server_name} result should be finite: {result}"); + assert!(*result > 0.0, "{server_name} result should be positive: {result}"); + } + } + + fn assert_server_metrics_are_correct( + stats: &Metrics, + labels: &LabelSet, + server_name: &str, + expected_request_count: usize, + expected_avg_ns: f64, + ) -> f64 { + // Verify request count + let processed_requests = get_processed_requests_count(stats, labels); + assert_eq!( + processed_requests, expected_request_count as u64, + "{server_name} should have processed {expected_request_count} requests" + ); + + // Verify average processing time is within expected range + let avg_processing_time = get_average_processing_time(stats, labels); + assert!( + (avg_processing_time - expected_avg_ns).abs() < 50.0, + "{server_name} average should be ~{expected_avg_ns}ns (±50ns), got {avg_processing_time}ns" + ); + + avg_processing_time + } + + fn assert_server_metrics_relationship(server1_avg: f64, server2_avg: f64) { + const MIN_DIFFERENCE_NS: f64 = 950.0; + + assert_averages_are_significantly_different(server1_avg, server2_avg, MIN_DIFFERENCE_NS); + assert_server_ordering_is_correct(server1_avg, server2_avg); + } + + fn assert_averages_are_significantly_different(avg1: f64, avg2: f64, min_difference: f64) { + let difference = (avg1 - avg2).abs(); + assert!( + difference > min_difference, + "Server averages should differ by more than {min_difference}ns, but difference was {difference}ns" + ); + } + + fn assert_server_ordering_is_correct(server1_avg: f64, server2_avg: f64) { + // Server 2 should have higher average since it has higher processing times [2000-6000] vs [1000-5000] + assert!( + server2_avg > server1_avg, + "Server 2 average ({server2_avg}ns) should be higher than Server 1 ({server1_avg}ns) due to higher processing time ranges" + ); + } + + fn assert_server_result_matches_stored_average(results: &[f64], stats: &Metrics, labels: &LabelSet, server_name: &str) { + let final_avg = get_average_processing_time(stats, labels); + let last_result = results.last().copied().unwrap(); + + assert!( + (last_result - final_avg).abs() <= f64::EPSILON, + "{server_name} last result ({last_result}) should match final average ({final_avg}) exactly" + ); + } + + fn assert_metric_collection_integrity(stats: &Metrics) { + assert!(stats + .metric_collection + .contains_gauge(&metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS))); + assert!(stats + .metric_collection + .contains_counter(&metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL))); + } + + fn get_processed_requests_count(stats: &Metrics, labels: &LabelSet) -> u64 { + stats + .metric_collection + .get_counter_value( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL), + labels, + ) + .unwrap() + .value() + } + + fn get_average_processing_time(stats: &Metrics, labels: &LabelSet) -> f64 { + stats + .metric_collection + .get_gauge_value(&metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), labels) + .unwrap() + .value() + } + } +} diff --git a/packages/udp-tracker-server/src/statistics/services.rs b/packages/udp-tracker-server/src/statistics/services.rs new file mode 100644 index 000000000..0eac01270 --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/services.rs @@ -0,0 +1,105 @@ +//! Statistics services. +//! +//! It includes: +//! +//! - A [`factory`](crate::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. +//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::statistics::metrics::Metrics). +//! +//! Tracker metrics are collected using a Publisher-Subscribe pattern. +//! +//! The factory function builds two structs: +//! +//! - An statistics event [`Sender`](crate::statistics::event::sender::Sender) +//! - An statistics [`Repository`] +//! +//! ```text +//! let (stats_event_sender, stats_repository) = factory(tracker_usage_statistics); +//! ``` +//! +//! The statistics repository is responsible for storing the metrics in memory. +//! The statistics event sender allows sending events related to metrics. +//! There is an event listener that is receiving all the events and processing them with an event handler. +//! Then, the event handler updates the metrics depending on the received event. +//! +//! For example, if you send the event [`Event::Udp4Connect`](crate::statistics::event::Event::Udp4Connect): +//! +//! ```text +//! let result = event_sender.send_event(Event::Udp4Connect).await; +//! ``` +//! +//! Eventually the counter for UDP connections from IPv4 peers will be increased. +//! +//! ```rust,no_run +//! pub struct Metrics { +//! // ... +//! pub udp4_connections_handled: u64, // This will be incremented +//! // ... +//! } +//! ``` +use std::sync::Arc; + +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; + +use crate::statistics::metrics::Metrics; +use crate::statistics::repository::Repository; + +/// All the metrics collected by the tracker. +#[derive(Debug, PartialEq)] +pub struct TrackerMetrics { + /// Domain level metrics. + /// + /// General metrics for all torrents (number of seeders, leechers, etcetera) + pub torrents_metrics: AggregateActiveSwarmMetadata, + + /// Application level metrics. Usage statistics/metrics. + /// + /// Metrics about how the tracker is been used (number of udp announce requests, etcetera) + pub protocol_metrics: Metrics, +} + +/// It returns all the [`TrackerMetrics`] +pub async fn get_metrics( + in_memory_torrent_repository: Arc, + stats_repository: Arc, +) -> TrackerMetrics { + let torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata().await; + let stats = stats_repository.get_stats().await; + + TrackerMetrics { + torrents_metrics, + protocol_metrics: Metrics { + metric_collection: stats.metric_collection.clone(), + }, + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::{self}; + use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; + + use crate::statistics::describe_metrics; + use crate::statistics::repository::Repository; + use crate::statistics::services::{get_metrics, TrackerMetrics}; + + #[tokio::test] + async fn the_statistics_service_should_return_the_tracker_metrics() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let stats_repository = Arc::new(Repository::new()); + + let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), stats_repository.clone()).await; + + assert_eq!( + tracker_metrics, + TrackerMetrics { + torrents_metrics: AggregateActiveSwarmMetadata::default(), + protocol_metrics: describe_metrics(), + } + ); + } +} diff --git a/packages/udp-tracker-server/tests/common/fixtures.rs b/packages/udp-tracker-server/tests/common/fixtures.rs new file mode 100644 index 000000000..f4066c67a --- /dev/null +++ b/packages/udp-tracker-server/tests/common/fixtures.rs @@ -0,0 +1,17 @@ +use aquatic_udp_protocol::TransactionId; +use bittorrent_primitives::info_hash::InfoHash; +use rand::prelude::*; + +/// Returns a random info hash. +pub fn random_info_hash() -> InfoHash { + let mut rng = rand::rng(); + let random_bytes: [u8; 20] = rng.random(); + + InfoHash::from_bytes(&random_bytes) +} + +/// Returns a random transaction id. +pub fn random_transaction_id() -> TransactionId { + let random_value = rand::rng().random(); + TransactionId::new(random_value) +} diff --git a/packages/udp-tracker-server/tests/common/mod.rs b/packages/udp-tracker-server/tests/common/mod.rs new file mode 100644 index 000000000..d327fd14f --- /dev/null +++ b/packages/udp-tracker-server/tests/common/mod.rs @@ -0,0 +1,2 @@ +pub mod fixtures; +pub mod udp; diff --git a/tests/common/udp.rs b/packages/udp-tracker-server/tests/common/udp.rs similarity index 100% rename from tests/common/udp.rs rename to packages/udp-tracker-server/tests/common/udp.rs diff --git a/packages/udp-tracker-server/tests/integration.rs b/packages/udp-tracker-server/tests/integration.rs new file mode 100644 index 000000000..70b3aeb89 --- /dev/null +++ b/packages/udp-tracker-server/tests/integration.rs @@ -0,0 +1,20 @@ +//! Integration tests. +//! +//! ```text +//! cargo test --test integration +//! ``` +mod common; +mod server; + +use torrust_tracker_clock::clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/tests/servers/udp/asserts.rs b/packages/udp-tracker-server/tests/server/asserts.rs similarity index 73% rename from tests/servers/udp/asserts.rs rename to packages/udp-tracker-server/tests/server/asserts.rs index bf8fb6728..37c848e06 100644 --- a/tests/servers/udp/asserts.rs +++ b/packages/udp-tracker-server/tests/server/asserts.rs @@ -1,9 +1,9 @@ use aquatic_udp_protocol::{Response, TransactionId}; -pub fn is_error_response(response: &Response, error_message: &str) -> bool { +pub fn get_error_response_message(response: &Response) -> Option { match response { - Response::Error(error_response) => error_response.message.starts_with(error_message), - _ => false, + Response::Error(error_response) => Some(error_response.message.to_string()), + _ => None, } } diff --git a/packages/udp-tracker-server/tests/server/contract.rs b/packages/udp-tracker-server/tests/server/contract.rs new file mode 100644 index 000000000..350f3b8eb --- /dev/null +++ b/packages/udp-tracker-server/tests/server/contract.rs @@ -0,0 +1,354 @@ +// UDP tracker documentation: +// +// BEP 15. UDP Tracker Protocol for BitTorrent +// https://www.bittorrent.org/beps/bep_0015.html + +use core::panic; + +use aquatic_udp_protocol::{ConnectRequest, ConnectionId, Response, TransactionId}; +use bittorrent_tracker_client::udp::client::UdpTrackerClient; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; +use torrust_tracker_test_helpers::{configuration, logging}; +use torrust_udp_tracker_server::MAX_PACKET_SIZE; + +use crate::server::asserts::get_error_response_message; + +fn empty_udp_request() -> [u8; MAX_PACKET_SIZE] { + [0; MAX_PACKET_SIZE] +} + +async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrackerClient) -> ConnectionId { + let connect_request = ConnectRequest { transaction_id }; + + match client.send(connect_request.into()).await { + Ok(_) => (), + Err(err) => panic!("{err}"), + } + + let response = match client.receive().await { + Ok(response) => response, + Err(err) => panic!("{err}"), + }; + + match response { + Response::Connect(connect_response) => connect_response.connection_id, + _ => panic!("error connecting to udp server {response:?}"), + } +} + +#[tokio::test] +async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_request() { + logging::setup(); + + let env = torrust_udp_tracker_server::environment::Started::new(&configuration::ephemeral().into()).await; + + let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { + Ok(udp_client) => udp_client, + Err(err) => panic!("{err}"), + }; + + match client.client.send(&empty_udp_request()).await { + Ok(_) => (), + Err(err) => panic!("{err}"), + } + + let response = match client.client.receive().await { + Ok(response) => response, + Err(err) => panic!("{err}"), + }; + + let response = Response::parse_bytes(&response, true).unwrap(); + + assert!(get_error_response_message(&response) + .unwrap() + .contains("Protocol identifier missing")); + + env.stop().await; +} + +mod receiving_a_connection_request { + use aquatic_udp_protocol::{ConnectRequest, TransactionId}; + use bittorrent_tracker_client::udp::client::UdpTrackerClient; + use torrust_tracker_configuration::DEFAULT_TIMEOUT; + use torrust_tracker_test_helpers::{configuration, logging}; + + use crate::server::asserts::is_connect_response; + + #[tokio::test] + async fn should_return_a_connect_response() { + logging::setup(); + + let env = torrust_udp_tracker_server::environment::Started::new(&configuration::ephemeral().into()).await; + + let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { + Ok(udp_tracker_client) => udp_tracker_client, + Err(err) => panic!("{err}"), + }; + + let connect_request = ConnectRequest { + transaction_id: TransactionId::new(123), + }; + + match client.send(connect_request.into()).await { + Ok(_) => (), + Err(err) => panic!("{err}"), + } + + let response = match client.receive().await { + Ok(response) => response, + Err(err) => panic!("{err}"), + }; + + assert!(is_connect_response(&response, TransactionId::new(123))); + + env.stop().await; + } +} + +mod receiving_an_announce_request { + use std::net::Ipv4Addr; + + use aquatic_udp_protocol::{ + AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectionId, InfoHash, NumberOfBytes, NumberOfPeers, PeerId, + PeerKey, Port, TransactionId, + }; + use bittorrent_tracker_client::udp::client::UdpTrackerClient; + use torrust_tracker_configuration::DEFAULT_TIMEOUT; + use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; + use torrust_tracker_test_helpers::{configuration, logging}; + + use crate::common::fixtures::{random_info_hash, random_transaction_id}; + use crate::server::asserts::is_ipv4_announce_response; + use crate::server::contract::send_connection_request; + + pub async fn assert_send_and_get_announce( + tx_id: TransactionId, + c_id: ConnectionId, + info_hash: bittorrent_primitives::info_hash::InfoHash, + client: &UdpTrackerClient, + ) { + let response = send_and_get_announce(tx_id, c_id, info_hash, client).await; + assert!(is_ipv4_announce_response(&response)); + } + + pub async fn send_and_get_announce( + tx_id: TransactionId, + c_id: ConnectionId, + info_hash: bittorrent_primitives::info_hash::InfoHash, + client: &UdpTrackerClient, + ) -> aquatic_udp_protocol::Response { + let announce_request = + build_sample_announce_request(tx_id, c_id, client.client.socket.local_addr().unwrap().port(), info_hash); + + match client.send(announce_request.into()).await { + Ok(_) => (), + Err(err) => panic!("{err}"), + } + + match client.receive().await { + Ok(response) => response, + Err(err) => panic!("{err}"), + } + } + + fn build_sample_announce_request( + tx_id: TransactionId, + c_id: ConnectionId, + port: u16, + info_hash: bittorrent_primitives::info_hash::InfoHash, + ) -> AnnounceRequest { + AnnounceRequest { + connection_id: ConnectionId(c_id.0), + action_placeholder: AnnounceActionPlaceholder::default(), + transaction_id: tx_id, + info_hash: InfoHash(info_hash.0), + peer_id: PeerId([255u8; 20]), + bytes_downloaded: NumberOfBytes(0i64.into()), + bytes_uploaded: NumberOfBytes(0i64.into()), + bytes_left: NumberOfBytes(0i64.into()), + event: AnnounceEvent::Started.into(), + ip_address: Ipv4Addr::UNSPECIFIED.into(), + key: PeerKey::new(0i32), + peers_wanted: NumberOfPeers(1i32.into()), + port: Port(port.into()), + } + } + + #[tokio::test] + async fn should_return_an_announce_response() { + logging::setup(); + + let env = torrust_udp_tracker_server::environment::Started::new(&configuration::ephemeral().into()).await; + + let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { + Ok(udp_tracker_client) => udp_tracker_client, + Err(err) => panic!("{err}"), + }; + + let tx_id = TransactionId::new(123); + + let c_id = send_connection_request(tx_id, &client).await; + + let info_hash = random_info_hash(); + + assert_send_and_get_announce(tx_id, c_id, info_hash, &client).await; + + env.stop().await; + } + + #[tokio::test] + async fn should_return_many_announce_response() { + logging::setup(); + + let env = torrust_udp_tracker_server::environment::Started::new(&configuration::ephemeral().into()).await; + + let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { + Ok(udp_tracker_client) => udp_tracker_client, + Err(err) => panic!("{err}"), + }; + + let tx_id = TransactionId::new(123); + + let c_id = send_connection_request(tx_id, &client).await; + + let info_hash = random_info_hash(); + + for x in 0..1000 { + tracing::info!("req no: {x}"); + assert_send_and_get_announce(tx_id, c_id, info_hash, &client).await; + } + + env.stop().await; + } + + #[tokio::test] + async fn should_ban_the_client_ip_if_it_sends_more_than_10_requests_with_a_cookie_value_not_normal() { + logging::setup(); + + let env = torrust_udp_tracker_server::environment::Started::new(&configuration::ephemeral().into()).await; + let ban_service = env.container.udp_tracker_core_container.ban_service.clone(); + + let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { + Ok(udp_tracker_client) => udp_tracker_client, + Err(err) => panic!("{err}"), + }; + + let udp_banned_ips_total_before = ban_service.read().await.get_banned_ips_total(); + + // The eleven first requests should be fine + + let invalid_connection_id = ConnectionId::new(0); // Zero is one of the not normal values. + + let info_hash = random_info_hash(); + + for x in 0..=10 { + tracing::info!("req no: {x}"); + + let tx_id = random_transaction_id(); + + send_and_get_announce(tx_id, invalid_connection_id, info_hash, &client).await; + + let transaction_id = tx_id.0.to_string(); + + assert!( + logs_contains_a_line_with(&["ERROR", "UDP TRACKER", &transaction_id]), + "Expected logs to contain: ERROR ... UDP TRACKER ... transaction_id={transaction_id}" + ); + } + + // The twelfth request should be banned (timeout error) + + let tx_id = random_transaction_id(); + + let announce_request = build_sample_announce_request( + tx_id, + invalid_connection_id, + client.client.socket.local_addr().unwrap().port(), + info_hash, + ); + + let udp_requests_banned_before = env + .container + .udp_tracker_server_container + .stats_repository + .get_stats() + .await + .udp_requests_banned_total(); + + // This should return a timeout error + match client.send(announce_request.into()).await { + Ok(_) => (), + Err(err) => panic!("{err}"), + } + + assert!(client.receive().await.is_err()); + + let udp_requests_banned_after = env + .container + .udp_tracker_server_container + .stats_repository + .get_stats() + .await + .udp_requests_banned_total(); + let udp_banned_ips_total_after = ban_service.read().await.get_banned_ips_total(); + + // UDP counter for banned requests should be increased by 1 + assert_eq!(udp_requests_banned_after, udp_requests_banned_before + 1); + + // UDP counter for banned IPs should be increased by 1 + assert_eq!(udp_banned_ips_total_after, udp_banned_ips_total_before + 1); + + env.stop().await; + } +} + +mod receiving_an_scrape_request { + use aquatic_udp_protocol::{ConnectionId, InfoHash, ScrapeRequest, TransactionId}; + use bittorrent_tracker_client::udp::client::UdpTrackerClient; + use torrust_tracker_configuration::DEFAULT_TIMEOUT; + use torrust_tracker_test_helpers::{configuration, logging}; + + use crate::server::asserts::is_scrape_response; + use crate::server::contract::send_connection_request; + + #[tokio::test] + async fn should_return_a_scrape_response() { + logging::setup(); + + let env = torrust_udp_tracker_server::environment::Started::new(&configuration::ephemeral().into()).await; + + let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { + Ok(udp_tracker_client) => udp_tracker_client, + Err(err) => panic!("{err}"), + }; + + let connection_id = send_connection_request(TransactionId::new(123), &client).await; + + // Send scrape request + + // Full scrapes are not allowed you need to pass an array of info hashes otherwise + // it will return "bad request" error with empty vector + + let empty_info_hash = vec![InfoHash([0u8; 20])]; + + let scrape_request = ScrapeRequest { + connection_id: ConnectionId(connection_id.0), + transaction_id: TransactionId::new(123i32), + info_hashes: empty_info_hash, + }; + + match client.send(scrape_request.into()).await { + Ok(_) => (), + Err(err) => panic!("{err}"), + } + + let response = match client.receive().await { + Ok(response) => response, + Err(err) => panic!("{err}"), + }; + + assert!(is_scrape_response(&response)); + + env.stop().await; + } +} diff --git a/packages/udp-tracker-server/tests/server/mod.rs b/packages/udp-tracker-server/tests/server/mod.rs new file mode 100644 index 000000000..e2db6b4ce --- /dev/null +++ b/packages/udp-tracker-server/tests/server/mod.rs @@ -0,0 +1,2 @@ +pub mod asserts; +pub mod contract; diff --git a/project-words.txt b/project-words.txt new file mode 100644 index 000000000..48c9565cc --- /dev/null +++ b/project-words.txt @@ -0,0 +1,252 @@ +Addrs +adduser +alekitto +appuser +Arvid +ASMS +asyn +autoclean +AUTOINCREMENT +automock +Avicora +Azureus +bdecode +bencode +bencoded +bencoding +beps +binascii +binstall +Bitflu +bools +Bragilevsky +bufs +buildid +Buildx +byteorder +callgrind +camino +canonicalize +canonicalized +certbot +chrono +Cinstrument +ciphertext +clippy +cloneable +codecov +codegen +completei +Condvar +connectionless +Containerfile +conv +curr +cvar +Cyberneering +dashmap +datagram +datetime +debuginfo +Deque +Dijke +distroless +dockerhub +downloadedi +dtolnay +elif +endianness +Eray +filesd +flamegraph +formatjson +Freebox +FrostegÃ¥rd +gecos +Gibibytes +Grcov +hasher +healthcheck +heaptrack +hexlify +hlocalhost +Hydranode +hyperthread +Icelake +iiiiiiiiiiiiiiiiiiiid +imdl +impls +incompletei +infohash +infohashes +infoschema +Intermodal +intervali +Joakim +kallsyms +Karatay +kcachegrind +kexec +keyout +Kibibytes +kptr +lcov +leecher +leechers +libsqlite +libtorrent +libz +LOGNAME +Lphant +matchmakes +Mebibytes +metainfo +middlewares +misresolved +mockall +multimap +myacicontext +ñaca +Naim +nanos +newkey +nextest +nocapture +nologin +nonroot +Norberg +numwant +nvCFlJCq7fz7Qx6KoKTDiMZvns8l5Kw7 +oneshot +ostr +Pando +peekable +peerlist +programatik +proot +proto +Quickstart +Radeon +Rakshasa +Rasterbar +realpath +reannounce +Registar +repr +reqs +reqwest +rerequests +ringbuf +ringsize +rngs +rosegment +routable +rstest +rusqlite +rustc +RUSTDOCFLAGS +RUSTFLAGS +rustfmt +Rustls +Ryzen +Seedable +serde +Shareaza +sharktorrent +SHLVL +skiplist +slowloris +socketaddr +sqllite +subsec +Swatinem +Swiftbit +taiki +tdyne +Tebibytes +tempfile +testcontainers +thiserror +tlsv +Torrentstorm +torrust +torrustracker +trackerid +Trackon +typenum +udpv +Unamed +underflows +Unsendable +untuple +uroot +Vagaa +valgrind +Vitaly +vmlinux +Vuze +Weidendorfer +Werror +whitespaces +Xacrimon +XBTT +Xdebug +Xeon +Xtorrent +Xunlei +xxxxxxxxxxxxxxxxxxxxd +yyyyyyyyyyyyyyyyyyyyd +zerocopy +Aideq +autoremove +CALLSITE +Dihc +Dmqcd +QJSF +Glrg +Irwe +Uninit +Unparker +eventfd +fastrand +fdbased +fdget +fput +iiiiiiiiiiiiiiiippe +iiiiiiiiiiiiiiiipp +iiiiiiiiiiiiiiip +iipp +iiiipp +jdbe +ksys +llist +mmap +mprotect +nonblocking +peersld +pkey +porti +prealloc +println +shellcheck +sockfd +subkey +sysmalloc +sysret +timespec +toki +torru +ttwu +uninit +unparked +unsync +vtable +wakelist +wakeup +actix +iterationsadd +josecelano +mysqladmin +setgroups +taplo +trixie diff --git a/rustfmt.toml b/rustfmt.toml index 3e878b271..76046e6f4 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,4 +1,3 @@ -max_width = 130 -imports_granularity = "Module" group_imports = "StdExternalCrate" - +imports_granularity = "Module" +max_width = 130 diff --git a/share/container/entry_script_sh b/share/container/entry_script_sh new file mode 100644 index 000000000..32cdfe33d --- /dev/null +++ b/share/container/entry_script_sh @@ -0,0 +1,82 @@ +#!/bin/sh +set -x + +to_lc() { echo "$1" | tr '[:upper:]' '[:lower:]'; } +clean() { echo "$1" | tr -d -c 'a-zA-Z0-9-' ; } +cmp_lc() { [ "$(to_lc "$(clean "$1")")" = "$(to_lc "$(clean "$2")")" ]; } + + +inst() { + if [ -n "$1" ] && [ -n "$2" ] && [ -e "$1" ] && [ ! -e "$2" ]; then + install -D -m 0640 -o torrust -g torrust "$1" "$2"; fi; } + + +# Add torrust user, based upon supplied user-id. +if [ -z "$USER_ID" ] && [ "$USER_ID" -lt 1000 ]; then + echo "ERROR: USER_ID is not set, or less than 1000" + exit 1 +fi + +adduser --disabled-password --shell "/bin/sh" --uid "$USER_ID" "torrust" + +# Configure Permissions for Torrust Folders +mkdir -p /var/lib/torrust/tracker/database/ /etc/torrust/tracker/ +chown -R "${USER_ID}":"${USER_ID}" /var/lib/torrust /var/log/torrust /etc/torrust +chmod -R 2770 /var/lib/torrust /var/log/torrust /etc/torrust + + +# Install the database and config: +if [ -n "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER" ]; then + if cmp_lc "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER" "sqlite3"; then + + # Select Sqlite3 empty database + default_database="/usr/share/torrust/default/database/tracker.sqlite3.db" + + # Select Sqlite3 default configuration + default_config="/usr/share/torrust/default/config/tracker.container.sqlite3.toml" + + elif cmp_lc "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER" "mysql"; then + + # (no database file needed for MySQL) + + # Select default MySQL configuration + default_config="/usr/share/torrust/default/config/tracker.container.mysql.toml" + + else + echo "Error: Unsupported Database Type: \"$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER\"." + echo "Please Note: Supported Database Types: \"sqlite3\", \"mysql\"." + exit 1 + fi +else + echo "Error: \"\$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER\" was not set!"; exit 1; +fi + +install_config="/etc/torrust/tracker/tracker.toml" +install_database="/var/lib/torrust/tracker/database/sqlite3.db" + +inst "$default_config" "$install_config" +inst "$default_database" "$install_database" + +# Make Minimal Message of the Day +if cmp_lc "$RUNTIME" "runtime"; then + printf '\n in runtime \n' >> /etc/motd; +elif cmp_lc "$RUNTIME" "debug"; then + printf '\n in debug mode \n' >> /etc/motd; +elif cmp_lc "$RUNTIME" "release"; then + printf '\n in release mode \n' >> /etc/motd; +else + echo "ERROR: running in unknown mode: \"$RUNTIME\""; exit 1 +fi + +if [ -e "/usr/share/torrust/container/message" ]; then + cat "/usr/share/torrust/container/message" >> /etc/motd; chmod 0644 /etc/motd +fi + +# Load message of the day from Profile +# shellcheck disable=SC2016 +echo '[ ! -z "$TERM" -a -r /etc/motd ] && cat /etc/motd' >> /etc/profile + +cd /home/torrust || exit 1 + +# Switch to torrust user +exec /bin/su-exec torrust "$@" diff --git a/share/container/message b/share/container/message new file mode 100644 index 000000000..6bfd6bfb8 --- /dev/null +++ b/share/container/message @@ -0,0 +1,4 @@ + +Lovely welcome to our Torrust Tracker Container! + +run 'torrust-tracker' to start tracker diff --git a/share/default/config/tracker.container.mysql.toml b/share/default/config/tracker.container.mysql.toml new file mode 100644 index 000000000..865ea224e --- /dev/null +++ b/share/default/config/tracker.container.mysql.toml @@ -0,0 +1,29 @@ +[metadata] +app = "torrust-tracker" +purpose = "configuration" +schema_version = "2.0.0" + +[logging] +threshold = "info" + +[core] +listed = false +private = false + +[core.database] +driver = "mysql" +path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" + +# Uncomment to enable services + +#[[udp_trackers]] +#bind_address = "0.0.0.0:6969" + +#[[http_trackers]] +#bind_address = "0.0.0.0:7070" + +#[http_api] +#bind_address = "0.0.0.0:1212" + +#[http_api.access_tokens] +#admin = "MyAccessToken" diff --git a/share/default/config/tracker.container.sqlite3.toml b/share/default/config/tracker.container.sqlite3.toml new file mode 100644 index 000000000..6c73cf54a --- /dev/null +++ b/share/default/config/tracker.container.sqlite3.toml @@ -0,0 +1,28 @@ +[metadata] +app = "torrust-tracker" +purpose = "configuration" +schema_version = "2.0.0" + +[logging] +threshold = "info" + +[core] +listed = false +private = false + +[core.database] +path = "/var/lib/torrust/tracker/database/sqlite3.db" + +# Uncomment to enable services + +#[[udp_trackers]] +#bind_address = "0.0.0.0:6969" + +#[[http_trackers]] +#bind_address = "0.0.0.0:7070" + +#[http_api] +#bind_address = "0.0.0.0:1212" + +#[http_api.access_tokens] +#admin = "MyAccessToken" diff --git a/share/default/config/tracker.development.sqlite3.toml b/share/default/config/tracker.development.sqlite3.toml new file mode 100644 index 000000000..17a73a1d2 --- /dev/null +++ b/share/default/config/tracker.development.sqlite3.toml @@ -0,0 +1,39 @@ +[metadata] +app = "torrust-tracker" +purpose = "configuration" +schema_version = "2.0.0" + +[logging] +threshold = "info" + +[core] +inactive_peer_cleanup_interval = 120 +listed = false +private = false + +[core.tracker_policy] +max_peer_timeout = 60 +persistent_torrent_completed_stat = true +remove_peerless_torrents = true + +[[udp_trackers]] +bind_address = "0.0.0.0:6868" +tracker_usage_statistics = true + +[[udp_trackers]] +bind_address = "0.0.0.0:6969" +tracker_usage_statistics = true + +[[http_trackers]] +bind_address = "0.0.0.0:7070" +tracker_usage_statistics = true + +[[http_trackers]] +bind_address = "0.0.0.0:7171" +tracker_usage_statistics = true + +[http_api] +bind_address = "0.0.0.0:1212" + +[http_api.access_tokens] +admin = "MyAccessToken" diff --git a/share/default/config/tracker.e2e.container.sqlite3.toml b/share/default/config/tracker.e2e.container.sqlite3.toml new file mode 100644 index 000000000..73c6df219 --- /dev/null +++ b/share/default/config/tracker.e2e.container.sqlite3.toml @@ -0,0 +1,30 @@ +[metadata] +app = "torrust-tracker" +purpose = "configuration" +schema_version = "2.0.0" + +[logging] +threshold = "info" + +[core] +listed = false +private = false + +[core.database] +path = "/var/lib/torrust/tracker/database/sqlite3.db" + +[[udp_trackers]] +bind_address = "0.0.0.0:6969" + +[[http_trackers]] +bind_address = "0.0.0.0:7070" + +[http_api] +bind_address = "0.0.0.0:1212" + +[http_api.access_tokens] +admin = "MyAccessToken" + +[health_check_api] +# Must be bound to wildcard IP to be accessible from outside the container +bind_address = "0.0.0.0:1313" diff --git a/share/default/config/tracker.udp.benchmarking.toml b/share/default/config/tracker.udp.benchmarking.toml new file mode 100644 index 000000000..8a898153a --- /dev/null +++ b/share/default/config/tracker.udp.benchmarking.toml @@ -0,0 +1,21 @@ +[metadata] +schema_version = "2.0.0" + +[logging] +threshold = "error" + +[core] +listed = false +private = false +tracker_usage_statistics = false + +[core.database] +driver = "sqlite3" +path = "./sqlite3.db" + +[core.tracker_policy] +persistent_torrent_completed_stat = false +remove_peerless_torrents = false + +[[udp_trackers]] +bind_address = "0.0.0.0:3000" diff --git a/share/default/config/tracker_checker.json b/share/default/config/tracker_checker.json new file mode 100644 index 000000000..7d1453bfd --- /dev/null +++ b/share/default/config/tracker_checker.json @@ -0,0 +1,11 @@ +{ + "udp_trackers": [ + "127.0.0.1:6969" + ], + "http_trackers": [ + "http://127.0.0.1:7070" + ], + "health_checks": [ + "http://127.0.0.1:1313/health_check" + ] +} \ No newline at end of file diff --git a/src/app.rs b/src/app.rs index 3fc790a23..2149a6d4c 100644 --- a/src/app.rs +++ b/src/app.rs @@ -11,7 +11,11 @@ //! - Loading data from the database when it's needed. //! - Starting some jobs depending on the configuration. //! -//! The started jobs may be: +//! Jobs executed always: +//! +//! - Health Check API +//! +//! Optional jobs: //! //! - Torrent cleaner: it removes inactive peers and (optionally) peerless torrents. //! - UDP trackers: the user can enable multiple UDP tracker on several ports. @@ -19,69 +23,274 @@ //! - Tracker REST API: the tracker API can be enabled/disabled. use std::sync::Arc; -use log::warn; -use tokio::task::JoinHandle; -use torrust_tracker_configuration::Configuration; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_configuration::{Configuration, HttpTracker, UdpTracker}; +use tracing::instrument; + +use crate::bootstrap::jobs::manager::JobManager; +use crate::bootstrap::jobs::{ + self, activity_metrics_updater, health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker, +}; +use crate::bootstrap::{self}; +use crate::container::AppContainer; +use crate::CurrentClock; + +pub async fn run() -> (Arc, JobManager) { + let (config, app_container) = bootstrap::app::setup(); -use crate::bootstrap::jobs::{http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; -use crate::servers::http::Version; -use crate::tracker; + let app_container = Arc::new(app_container); + let jobs = start(&config, &app_container).await; + + (app_container, jobs) +} + +/// Starts the tracker application. +/// /// # Panics /// -/// Will panic if the socket address for API can't be parsed. -pub async fn start(config: Arc, tracker: Arc) -> Vec> { - let mut jobs: Vec> = Vec::new(); - - // Load peer keys - if tracker.is_private() { - tracker - .load_keys_from_database() +/// Will panic if: +/// +/// - Can't retrieve tracker keys from database. +/// - Can't load whitelist from database. +#[instrument(skip(config, app_container))] +pub async fn start(config: &Configuration, app_container: &Arc) -> JobManager { + warn_if_no_services_enabled(config); + + load_data_from_database(config, app_container).await; + + start_jobs(config, app_container).await +} + +async fn load_data_from_database(config: &Configuration, app_container: &Arc) { + load_peer_keys(config, app_container).await; + load_whitelisted_torrents(config, app_container).await; + load_torrent_metrics(config, app_container).await; +} + +async fn start_jobs(config: &Configuration, app_container: &Arc) -> JobManager { + let mut job_manager = JobManager::new(); + + start_swarm_coordination_registry_event_listener(config, app_container, &mut job_manager); + start_tracker_core_event_listener(config, app_container, &mut job_manager); + start_http_core_event_listener(config, app_container, &mut job_manager); + start_udp_core_event_listener(config, app_container, &mut job_manager); + start_udp_server_stats_event_listener(config, app_container, &mut job_manager); + start_udp_server_banning_event_listener(app_container, &mut job_manager); + + start_the_udp_instances(config, app_container, &mut job_manager).await; + start_the_http_instances(config, app_container, &mut job_manager).await; + + start_torrent_cleanup(config, app_container, &mut job_manager); + start_peers_inactivity_update(config, app_container, &mut job_manager); + + start_the_http_api(config, app_container, &mut job_manager).await; + start_health_check_api(config, app_container, &mut job_manager).await; + + job_manager +} + +fn warn_if_no_services_enabled(config: &Configuration) { + if config.http_api.is_none() + && (config.udp_trackers.is_none() || config.udp_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) + && (config.http_trackers.is_none() || config.http_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) + { + tracing::warn!("No services enabled in configuration"); + } +} + +async fn load_peer_keys(config: &Configuration, app_container: &Arc) { + if config.core.private { + app_container + .tracker_core_container + .keys_handler + .load_peer_keys_from_database() .await .expect("Could not retrieve keys from database."); } +} - // Load whitelisted torrents - if tracker.is_whitelisted() { - tracker +async fn load_whitelisted_torrents(config: &Configuration, app_container: &Arc) { + if config.core.listed { + app_container + .tracker_core_container + .whitelist_manager .load_whitelist_from_database() .await .expect("Could not load whitelist from database."); } +} + +async fn load_torrent_metrics(config: &Configuration, app_container: &Arc) { + if config.core.tracker_policy.persistent_torrent_completed_stat { + bittorrent_tracker_core::statistics::persisted::load_persisted_metrics( + &app_container.tracker_core_container.stats_repository, + &app_container.tracker_core_container.db_downloads_metric_repository, + CurrentClock::now(), + ) + .await + .expect("Could not load persisted metrics from database."); + } +} - // Start the UDP blocks - for udp_tracker_config in &config.udp_trackers { - if !udp_tracker_config.enabled { - continue; +fn start_swarm_coordination_registry_event_listener( + config: &Configuration, + app_container: &Arc, + job_manager: &mut JobManager, +) { + job_manager.push_opt( + "swarm_coordination_registry_event_listener", + jobs::torrent_repository::start_event_listener(config, app_container, job_manager.new_cancellation_token()), + ); +} + +fn start_tracker_core_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { + job_manager.push_opt( + "tracker_core_event_listener", + jobs::tracker_core::start_event_listener(config, app_container, job_manager.new_cancellation_token()), + ); +} + +fn start_http_core_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { + job_manager.push_opt( + "http_core_event_listener", + jobs::http_tracker_core::start_event_listener(config, app_container, job_manager.new_cancellation_token()), + ); +} + +fn start_udp_core_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { + job_manager.push_opt( + "udp_core_event_listener", + jobs::udp_tracker_core::start_event_listener(config, app_container, job_manager.new_cancellation_token()), + ); +} + +fn start_udp_server_stats_event_listener( + config: &Configuration, + app_container: &Arc, + job_manager: &mut JobManager, +) { + job_manager.push_opt( + "udp_server_stats_event_listener", + jobs::udp_tracker_server::start_stats_event_listener(config, app_container, job_manager.new_cancellation_token()), + ); +} + +fn start_udp_server_banning_event_listener(app_container: &Arc, job_manager: &mut JobManager) { + job_manager.push( + "udp_server_banning_event_listener", + jobs::udp_tracker_server::start_banning_event_listener(app_container, job_manager.new_cancellation_token()), + ); +} + +async fn start_the_udp_instances(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { + if let Some(udp_trackers) = &config.udp_trackers { + for (idx, udp_tracker_config) in udp_trackers.iter().enumerate() { + if config.core.private { + tracing::warn!( + "Could not start UDP tracker on: {} while in private mode. UDP is not safe for private trackers!", + udp_tracker_config.bind_address + ); + } else { + start_udp_instance(idx, udp_tracker_config, app_container, job_manager).await; + } } + } else { + tracing::info!("No UDP blocks in configuration"); + } +} + +async fn start_udp_instance( + idx: usize, + udp_tracker_config: &UdpTracker, + app_container: &Arc, + job_manager: &mut JobManager, +) { + let udp_tracker_container = app_container + .udp_tracker_container(udp_tracker_config.bind_address) + .expect("Could not create UDP tracker container"); + let udp_tracker_server_container = app_container.udp_tracker_server_container(); - if tracker.is_private() { - warn!( - "Could not start UDP tracker on: {} while in {:?}. UDP is not safe for private trackers!", - udp_tracker_config.bind_address, config.mode - ); - } else { - jobs.push(udp_tracker::start_job(udp_tracker_config, tracker.clone())); + let handle = udp_tracker::start_job( + udp_tracker_container, + udp_tracker_server_container, + app_container.registar.give_form(), + ) + .await; + + job_manager.push(format!("udp_instance_{}_{}", idx, udp_tracker_config.bind_address), handle); +} + +async fn start_the_http_instances(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { + if let Some(http_trackers) = &config.http_trackers { + for (idx, http_tracker_config) in http_trackers.iter().enumerate() { + start_http_instance(idx, http_tracker_config, app_container, job_manager).await; } + } else { + tracing::info!("No HTTP blocks in configuration"); + } +} + +async fn start_http_instance( + idx: usize, + http_tracker_config: &HttpTracker, + app_container: &Arc, + job_manager: &mut JobManager, +) { + let http_tracker_container = app_container + .http_tracker_container(http_tracker_config.bind_address) + .expect("Could not create HTTP tracker container"); + + if let Some(handle) = http_tracker::start_job( + http_tracker_container, + app_container.registar.give_form(), + torrust_axum_http_tracker_server::Version::V1, + ) + .await + { + job_manager.push(format!("http_instance_{}_{}", idx, http_tracker_config.bind_address), handle); } +} - // Start the HTTP blocks - for http_tracker_config in &config.http_trackers { - if !http_tracker_config.enabled { - continue; +async fn start_the_http_api(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { + if let Some(http_api_config) = &config.http_api { + let http_api_config = Arc::new(http_api_config.clone()); + let http_api_container = app_container.tracker_http_api_container(&http_api_config); + + if let Some(job) = tracker_apis::start_job( + http_api_container, + app_container.registar.give_form(), + torrust_axum_rest_tracker_api_server::Version::V1, + ) + .await + { + job_manager.push("http_api", job); } - jobs.push(http_tracker::start_job(http_tracker_config, tracker.clone(), Version::V1).await); + } else { + tracing::info!("No API block in configuration"); } +} - // Start HTTP API - if config.http_api.enabled { - jobs.push(tracker_apis::start_job(&config.http_api, tracker.clone()).await); +fn start_torrent_cleanup(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { + if config.core.inactive_peer_cleanup_interval > 0 { + let handle = torrent_cleanup::start_job(&config.core, &app_container.tracker_core_container.torrents_manager); + + job_manager.push("torrent_cleanup", handle); } +} - // Remove torrents without peers, every interval - if config.inactive_peer_cleanup_interval > 0 { - jobs.push(torrent_cleanup::start_job(&config, &tracker)); +fn start_peers_inactivity_update(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { + if config.core.tracker_usage_statistics { + let handle = activity_metrics_updater::start_job(config, app_container); + + job_manager.push("peers_inactivity_update", handle); + } else { + tracing::info!("Peers inactivity update job is disabled."); } +} + +async fn start_health_check_api(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { + let handle = health_check_api::start_job(&config.health_check_api, app_container.registar.entries()).await; - jobs + job_manager.push("health_check_api", handle); } diff --git a/src/bin/e2e_tests_runner.rs b/src/bin/e2e_tests_runner.rs new file mode 100644 index 000000000..5787799dc --- /dev/null +++ b/src/bin/e2e_tests_runner.rs @@ -0,0 +1,6 @@ +//! Program to run E2E tests. +use torrust_tracker_lib::console::ci::e2e; + +fn main() -> anyhow::Result<()> { + e2e::runner::run() +} diff --git a/src/bin/http_health_check.rs b/src/bin/http_health_check.rs new file mode 100644 index 000000000..b7c6dfa41 --- /dev/null +++ b/src/bin/http_health_check.rs @@ -0,0 +1,42 @@ +//! Minimal `curl` or `wget` to be used for container health checks. +//! +//! It's convenient to avoid using third-party libraries because: +//! +//! - They are harder to maintain. +//! - They introduce new attack vectors. +use std::time::Duration; +use std::{env, process}; + +use reqwest::Client; + +#[tokio::main] +async fn main() { + let args: Vec = env::args().collect(); + if args.len() != 2 { + eprintln!("Usage: cargo run --bin http_health_check "); + eprintln!("Example: cargo run --bin http_health_check http://127.0.0.1:1313/health_check"); + std::process::exit(1); + } + + println!("Health check ..."); + + let url = &args[1].clone(); + + let client = Client::builder().timeout(Duration::from_secs(5)).build().unwrap(); + + match client.get(url).send().await { + Ok(response) => { + if response.status().is_success() { + println!("STATUS: {}", response.status()); + process::exit(0); + } else { + println!("Non-success status received."); + process::exit(1); + } + } + Err(err) => { + println!("ERROR: {err}"); + process::exit(1); + } + } +} diff --git a/src/bin/profiling.rs b/src/bin/profiling.rs new file mode 100644 index 000000000..aca6ab98d --- /dev/null +++ b/src/bin/profiling.rs @@ -0,0 +1,8 @@ +//! This binary is used for profiling with [valgrind](https://valgrind.org/) +//! and [kcachegrind](https://kcachegrind.github.io/). +use torrust_tracker_lib::console::profiling::run; + +#[tokio::main] +async fn main() { + run().await; +} diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index c0e688a0d..bcf000dfd 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -1,6 +1,6 @@ //! Setup for the main tracker application. //! -//! The [`setup`](bootstrap::app::setup) only builds the application and its dependencies but it does not start the application. +//! The [`setup`] only builds the application and its dependencies but it does not start the application. //! In fact, there is no such thing as the main application process. When the application starts, the only thing it does is //! starting a bunch of independent jobs. If you are looking for how things are started you should read [`app::start`](crate::app::start) //! function documentation. @@ -11,91 +11,68 @@ //! 2. Initialize static variables. //! 3. Initialize logging. //! 4. Initialize the domain tracker. -use std::env; -use std::sync::Arc; +use bittorrent_udp_tracker_core::crypto::keys::{self, Keeper as _}; +use torrust_tracker_configuration::validator::Validator; +use torrust_tracker_configuration::{logging, Configuration}; +use tracing::instrument; -use torrust_tracker_configuration::Configuration; +use super::config::initialize_configuration; +use crate::container::AppContainer; -use crate::bootstrap; -use crate::shared::clock::static_time; -use crate::shared::crypto::ephemeral_instance_keys; -use crate::tracker::services::tracker_factory; -use crate::tracker::Tracker; - -/// It loads the configuration from the environment and builds the main domain [`tracker`](crate::tracker::Tracker) struct. +/// It loads the configuration from the environment and builds app container. +/// +/// # Panics +/// +/// Setup can file if the configuration is invalid. #[must_use] -pub fn setup() -> (Arc, Arc) { - let configuration = Arc::new(initialize_configuration()); - let tracker = initialize_with_configuration(&configuration); +#[instrument(skip())] +pub fn setup() -> (Configuration, AppContainer) { + #[cfg(not(test))] + check_seed(); - (configuration, tracker) -} + let configuration = initialize_configuration(); -/// It initializes the application with the given configuration. -/// -/// The configuration may be obtained from the environment (via config file or env vars). -#[must_use] -pub fn initialize_with_configuration(configuration: &Arc) -> Arc { - initialize_static(); - initialize_logging(configuration); - Arc::new(initialize_tracker(configuration)) -} + if let Err(e) = configuration.validate() { + panic!("Configuration error: {e}"); + } -/// It initializes the application static values. -/// -/// These values are accessible throughout the entire application: -/// -/// - The time when the application started. -/// - An ephemeral instance random seed. This seed is used for encryption and it's changed when the main application process is restarted. -pub fn initialize_static() { - // Set the time of Torrust app starting - lazy_static::initialize(&static_time::TIME_AT_APP_START); + initialize_global_services(&configuration); - // Initialize the Ephemeral Instance Random Seed - lazy_static::initialize(&ephemeral_instance_keys::RANDOM_SEED); + tracing::info!("Configuration:\n{}", configuration.clone().mask_secrets().to_json()); + + let app_container = AppContainer::initialize(&configuration); + + (configuration, app_container) } -/// It loads the application configuration from the environment. -/// -/// There are two methods to inject the configuration: -/// -/// 1. By using a config file: `config.toml`. The file must be in the same folder where you are running the tracker. -/// 2. Environment variable: `TORRUST_TRACKER_CONFIG`. The variable contains the same contents as the `config.toml` file. -/// -/// Environment variable has priority over the config file. -/// -/// Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) for the configuration options. +/// checks if the seed is the instance seed in production. /// /// # Panics /// -/// Will panic if it can't load the configuration from either -/// `./config.toml` file or the env var `TORRUST_TRACKER_CONFIG`. -#[must_use] -fn initialize_configuration() -> Configuration { - const CONFIG_PATH: &str = "./config.toml"; - const CONFIG_ENV_VAR_NAME: &str = "TORRUST_TRACKER_CONFIG"; +/// It would panic if the seed is not the instance seed. +pub fn check_seed() { + let seed = keys::Current::get_seed(); + let instance = keys::Instance::get_seed(); - if env::var(CONFIG_ENV_VAR_NAME).is_ok() { - println!("Loading configuration from env var {CONFIG_ENV_VAR_NAME}"); - Configuration::load_from_env_var(CONFIG_ENV_VAR_NAME).unwrap() - } else { - println!("Loading configuration from config file {CONFIG_PATH}"); - Configuration::load_from_file(CONFIG_PATH).unwrap() - } + assert_eq!(seed, instance, "maybe using zeroed seed in production!?"); } -/// It builds the domain tracker -/// -/// The tracker is the domain layer service. It's the entrypoint to make requests to the domain layer. -/// It's used by other higher-level components like the UDP and HTTP trackers or the tracker API. -#[must_use] -pub fn initialize_tracker(config: &Arc) -> Tracker { - tracker_factory(config.clone()) +/// It initializes the global services. +#[instrument(skip())] +pub fn initialize_global_services(configuration: &Configuration) { + initialize_static(); + logging::setup(&configuration.logging); } -/// It initializes the log level, format and channel. +/// It initializes the application static values. /// -/// See [the logging setup](crate::bootstrap::logging::setup) for more info about logging. -pub fn initialize_logging(config: &Arc) { - bootstrap::logging::setup(config); +/// These values are accessible throughout the entire application: +/// +/// - The time when the application started. +/// - An ephemeral instance random seed. This seed is used for encryption and +/// it's changed when the main application process is restarted. +#[instrument(skip())] +pub fn initialize_static() { + torrust_tracker_clock::initialize_static(); + bittorrent_udp_tracker_core::initialize_static(); } diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs new file mode 100644 index 000000000..fb5afe403 --- /dev/null +++ b/src/bootstrap/config.rs @@ -0,0 +1,39 @@ +//! Initialize configuration from file or env var. +//! +//! All environment variables are prefixed with `TORRUST_TRACKER_`. + +use torrust_tracker_configuration::{Configuration, Info}; + +pub const DEFAULT_PATH_CONFIG: &str = "./share/default/config/tracker.development.sqlite3.toml"; + +/// It loads the application configuration from the environment. +/// +/// There are two methods to inject the configuration: +/// +/// 1. By using a config file: `tracker.toml`. +/// 2. Environment variable: `TORRUST_TRACKER_CONFIG_TOML`. The variable contains the same contents as the `tracker.toml` file. +/// +/// Environment variable has priority over the config file. +/// +/// Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) for the configuration options. +/// +/// # Panics +/// +/// Will panic if it can't load the configuration from either +/// `./tracker.toml` file or the env var `TORRUST_TRACKER_CONFIG_TOML`. +#[must_use] +pub fn initialize_configuration() -> Configuration { + let info = Info::new(DEFAULT_PATH_CONFIG.to_string()).expect("info to load configuration is not valid"); + Configuration::load(&info).expect("error loading configuration from sources") +} + +#[cfg(test)] +mod tests { + + #[test] + fn it_should_load_with_default_config() { + use crate::bootstrap::config::initialize_configuration; + + drop(initialize_configuration()); + } +} diff --git a/src/bootstrap/jobs/activity_metrics_updater.rs b/src/bootstrap/jobs/activity_metrics_updater.rs new file mode 100644 index 000000000..9bbdc3f9b --- /dev/null +++ b/src/bootstrap/jobs/activity_metrics_updater.rs @@ -0,0 +1,27 @@ +//! Job that runs a task on intervals to update peers' activity metrics. +use std::sync::Arc; +use std::time::Duration; + +use tokio::task::JoinHandle; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_configuration::Configuration; + +use crate::container::AppContainer; +use crate::CurrentClock; + +#[must_use] +pub fn start_job(config: &Configuration, app_container: &Arc) -> JoinHandle<()> { + torrust_tracker_swarm_coordination_registry::statistics::activity_metrics_updater::start_job( + &app_container.swarm_coordination_registry_container.swarms.clone(), + &app_container.swarm_coordination_registry_container.stats_repository.clone(), + peer_inactivity_cutoff_timestamp(config.core.tracker_policy.max_peer_timeout), + ) +} + +/// Returns the timestamp of the cutoff for inactive peers. +/// +/// Peers that has not been updated for more than `max_peer_timeout` seconds are +/// considered inactive. +fn peer_inactivity_cutoff_timestamp(max_peer_timeout: u32) -> Duration { + CurrentClock::now_sub(&Duration::from_secs(u64::from(max_peer_timeout))).unwrap_or_default() +} diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs new file mode 100644 index 000000000..7c529fadd --- /dev/null +++ b/src/bootstrap/jobs/health_check_api.rs @@ -0,0 +1,71 @@ +//! Health Check API job starter. +//! +//! The [`health_check_api::start_job`](crate::bootstrap::jobs::health_check_api::start_job) +//! function starts the Health Check REST API. +//! +//! The [`health_check_api::start_job`](crate::bootstrap::jobs::health_check_api::start_job) +//! function spawns a new asynchronous task, that tasks is the "**launcher**". +//! The "**launcher**" starts the actual server and sends a message back +//! to the main application. +//! +//! The "**launcher**" is an intermediary thread that decouples the Health Check +//! API server from the process that handles it. +//! +//! Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) +//! for the API configuration options. + +use tokio::sync::oneshot; +use tokio::task::JoinHandle; +use torrust_axum_health_check_api_server::{server, HEALTH_CHECK_API_LOG_TARGET}; +use torrust_server_lib::logging::STARTED_ON; +use torrust_server_lib::registar::ServiceRegistry; +use torrust_server_lib::signals::{Halted, Started}; +use torrust_tracker_configuration::HealthCheckApi; +use tracing::instrument; + +/// This function starts a new Health Check API server with the provided +/// configuration. +/// +/// The functions starts a new concurrent task that will run the API server. +/// This task will send a message to the main application process to notify +/// that the API server was successfully started. +/// +/// # Panics +/// +/// It would panic if unable to send the `ApiServerJobStarted` notice. +#[allow(clippy::async_yields_async)] +#[instrument(skip(config, register))] +pub async fn start_job(config: &HealthCheckApi, register: ServiceRegistry) -> JoinHandle<()> { + let bind_addr = config.bind_address; + + let (tx_start, rx_start) = oneshot::channel::(); + let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); + + let protocol = "http"; + + // Run the API server + let join_handle = tokio::spawn(async move { + tracing::info!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting on: {protocol}://{}", bind_addr); + + let handle = server::start(bind_addr, tx_start, rx_halt, register); + + if let Ok(()) = handle.await { + tracing::info!(target: HEALTH_CHECK_API_LOG_TARGET, "Stopped server running on: {protocol}://{}", bind_addr); + } + }); + + // Wait until the server sends the started message + match rx_start.await { + Ok(msg) => tracing::info!(target: HEALTH_CHECK_API_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", msg.address), + Err(e) => panic!("the Health Check API server was dropped: {e}"), + } + + // Wait until the server finishes + tokio::spawn(async move { + assert!(!tx_halt.is_closed(), "Halt channel for Health Check API should be open"); + + join_handle + .await + .expect("it should be able to join to the Health Check API server task"); + }) +} diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index ac0161640..013031395 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -3,92 +3,103 @@ //! The function [`http_tracker::start_job`](crate::bootstrap::jobs::http_tracker::start_job) starts a new HTTP tracker server. //! //! > **NOTICE**: the application can launch more than one HTTP tracker on different ports. -//! Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) for the configuration options. +//! > Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) for the configuration options. //! //! The [`http_tracker::start_job`](crate::bootstrap::jobs::http_tracker::start_job) function spawns a new asynchronous task, //! that tasks is the "**launcher**". The "**launcher**" starts the actual server and sends a message back to the main application. -//! The main application waits until receives the message [`ServerJobStarted`](crate::bootstrap::jobs::http_tracker::ServerJobStarted) from the "**launcher**". //! //! The "**launcher**" is an intermediary thread that decouples the HTTP servers from the process that handles it. The HTTP could be used independently in the future. //! In that case it would not need to notify a parent process. +use std::net::SocketAddr; use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; -use log::info; -use tokio::sync::oneshot; +use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use tokio::task::JoinHandle; -use torrust_tracker_configuration::HttpTracker; - -use crate::servers::http::v1::launcher; -use crate::servers::http::Version; -use crate::tracker; - -/// This is the message that the "**launcher**" spawned task sends to the main application process to notify that the HTTP server was successfully started. -/// -/// > **NOTICE**: it does not mean the HTTP server is ready to receive requests. It only means the new server started. It might take some time to the server to be ready to accept request. -#[derive(Debug)] -pub struct ServerJobStarted(); +use torrust_axum_http_tracker_server::server::{HttpServer, Launcher}; +use torrust_axum_http_tracker_server::Version; +use torrust_axum_server::tsl::make_rust_tls; +use torrust_server_lib::registar::ServiceRegistrationForm; +use tracing::instrument; /// It starts a new HTTP server with the provided configuration and version. /// /// Right now there is only one version but in the future we could support more than one HTTP tracker version at the same time. /// This feature allows supporting breaking changes on `BitTorrent` BEPs. -pub async fn start_job(config: &HttpTracker, tracker: Arc, version: Version) -> JoinHandle<()> { - match version { - Version::V1 => start_v1(config, tracker.clone()).await, - } -} - +/// /// # Panics /// /// It would panic if the `config::HttpTracker` struct would contain inappropriate values. -async fn start_v1(config: &HttpTracker, tracker: Arc) -> JoinHandle<()> { - let bind_addr = config - .bind_address - .parse::() - .expect("Tracker API bind_address invalid."); - let ssl_enabled = config.ssl_enabled; - let ssl_cert_path = config.ssl_cert_path.clone(); - let ssl_key_path = config.ssl_key_path.clone(); +#[instrument(skip(http_tracker_container, form))] +pub async fn start_job( + http_tracker_container: Arc, + form: ServiceRegistrationForm, + version: Version, +) -> Option> { + let socket = http_tracker_container.http_tracker_config.bind_address; + + let tls = make_rust_tls(&http_tracker_container.http_tracker_config.tsl_config) + .await + .map(|tls| tls.expect("it should have a valid http tracker tls configuration")); - let (tx, rx) = oneshot::channel::(); + match version { + Version::V1 => Some(start_v1(socket, tls, http_tracker_container, form).await), + } +} - // Run the API server - let join_handle = tokio::spawn(async move { - if !ssl_enabled { - info!("Starting Torrust HTTP tracker server on: http://{}", bind_addr); +#[allow(clippy::async_yields_async)] +#[instrument(skip(socket, tls, http_tracker_container, form))] +async fn start_v1( + socket: SocketAddr, + tls: Option, + http_tracker_container: Arc, + form: ServiceRegistrationForm, +) -> JoinHandle<()> { + let server = HttpServer::new(Launcher::new(socket, tls)) + .start(http_tracker_container, form) + .await + .expect("it should be able to start to the http tracker"); + + tokio::spawn(async move { + assert!( + !server.state.halt_task.is_closed(), + "Halt channel for HTTP tracker should be open" + ); + server + .state + .task + .await + .expect("it should be able to join to the http tracker task"); + }) +} - let handle = launcher::start(bind_addr, tracker); +#[cfg(test)] +mod tests { + use std::sync::Arc; - tx.send(ServerJobStarted()) - .expect("the HTTP tracker server should not be dropped"); + use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; + use torrust_axum_http_tracker_server::Version; + use torrust_server_lib::registar::Registar; + use torrust_tracker_test_helpers::configuration::ephemeral_public; - if let Ok(()) = handle.await { - info!("Torrust HTTP tracker server on http://{} stopped", bind_addr); - } - } else if ssl_enabled && ssl_cert_path.is_some() && ssl_key_path.is_some() { - info!("Starting Torrust HTTP tracker server on: https://{}", bind_addr); + use crate::bootstrap::app::initialize_global_services; + use crate::bootstrap::jobs::http_tracker::start_job; - let ssl_config = RustlsConfig::from_pem_file(ssl_cert_path.unwrap(), ssl_key_path.unwrap()) - .await - .unwrap(); + #[tokio::test] + async fn it_should_start_http_tracker() { + let cfg = Arc::new(ephemeral_public()); + let core_config = Arc::new(cfg.core.clone()); + let http_tracker = cfg.http_trackers.clone().expect("missing HTTP tracker configuration"); + let http_tracker_config = Arc::new(http_tracker[0].clone()); - let handle = launcher::start_tls(bind_addr, ssl_config, tracker); + initialize_global_services(&cfg); - tx.send(ServerJobStarted()) - .expect("the HTTP tracker server should not be dropped"); + let http_tracker_container = HttpTrackerCoreContainer::initialize(&core_config, &http_tracker_config); - if let Ok(()) = handle.await { - info!("Torrust HTTP tracker server on https://{} stopped", bind_addr); - } - } - }); + let version = Version::V1; - // Wait until the HTTP tracker server job is running - match rx.await { - Ok(_msg) => info!("Torrust HTTP tracker server started"), - Err(e) => panic!("the HTTP tracker server was dropped: {e}"), + start_job(http_tracker_container, Registar::default().give_form(), version) + .await + .expect("it should be able to join to the http tracker start-job"); } - - join_handle } diff --git a/src/bootstrap/jobs/http_tracker_core.rs b/src/bootstrap/jobs/http_tracker_core.rs new file mode 100644 index 000000000..ab71b9a0f --- /dev/null +++ b/src/bootstrap/jobs/http_tracker_core.rs @@ -0,0 +1,26 @@ +use std::sync::Arc; + +use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; +use torrust_tracker_configuration::Configuration; + +use crate::container::AppContainer; + +pub fn start_event_listener( + config: &Configuration, + app_container: &Arc, + cancellation_token: CancellationToken, +) -> Option> { + if config.core.tracker_usage_statistics { + let job = bittorrent_http_tracker_core::statistics::event::listener::run_event_listener( + app_container.http_tracker_core_services.event_bus.receiver(), + cancellation_token, + &app_container.http_tracker_core_services.stats_repository, + ); + + Some(job) + } else { + tracing::info!("HTTP tracker core event listener job is disabled."); + None + } +} diff --git a/src/bootstrap/jobs/manager.rs b/src/bootstrap/jobs/manager.rs new file mode 100644 index 000000000..565cd7b73 --- /dev/null +++ b/src/bootstrap/jobs/manager.rs @@ -0,0 +1,119 @@ +use std::time::Duration; + +use tokio::task::JoinHandle; +use tokio::time::timeout; +use tokio_util::sync::CancellationToken; +use tracing::{info, warn}; + +/// Represents a named background job. +#[derive(Debug)] +pub struct Job { + name: String, + handle: JoinHandle<()>, +} + +impl Job { + pub fn new>(name: N, handle: JoinHandle<()>) -> Self { + Self { + name: name.into(), + handle, + } + } +} + +/// Manages multiple background jobs. +#[derive(Debug, Default)] +pub struct JobManager { + jobs: Vec, + cancellation_token: CancellationToken, +} + +impl JobManager { + #[must_use] + pub fn new() -> Self { + Self { + jobs: Vec::new(), + cancellation_token: CancellationToken::new(), + } + } + + pub fn push>(&mut self, name: N, handle: JoinHandle<()>) { + self.jobs.push(Job::new(name, handle)); + } + + pub fn push_opt>(&mut self, name: N, handle: Option>) { + if let Some(handle) = handle { + self.push(name, handle); + } + } + + #[must_use] + pub fn new_cancellation_token(&self) -> CancellationToken { + self.cancellation_token.clone() + } + + /// Cancels all jobs using the shared cancellation token. + /// + /// Notice that this does not cancel the jobs immediately, but rather + /// signals them to stop. The jobs themselves must handle the cancellation + /// token appropriately. + /// + /// Notice jobs might be pushed into the manager without a cancellation + /// token, so this method will not cancel those jobs. Some tasks might + /// decide to listen for CTRL+c signal directly, or implement their own + /// cancellation logic. + pub fn cancel(&self) { + self.cancellation_token.cancel(); + } + + /// Waits sequentially for all jobs to complete, with a graceful timeout per + /// job. + pub async fn wait_for_all(mut self, grace_period: Duration) { + for job in self.jobs.drain(..) { + let name = job.name.clone(); + + info!(job = %name, "Waiting for job to finish (timeout of {} seconds) ...", grace_period.as_secs()); + + if let Ok(result) = timeout(grace_period, job.handle).await { + if let Err(e) = result { + warn!(job = %name, "Job return an error: {:?}", e); + } else { + info!(job = %name, "Job completed gracefully"); + } + } else { + warn!(job = %name, "Job did not complete in time"); + } + } + } +} + +#[cfg(test)] +mod tests { + use tokio::time::Duration; + + use super::*; + + #[tokio::test] + async fn it_should_wait_for_all_jobs_to_finish() { + let mut manager = JobManager::new(); + + manager.push("job1", tokio::spawn(async {})); + manager.push("job2", tokio::spawn(async {})); + + manager.wait_for_all(Duration::from_secs(1)).await; + } + + #[tokio::test] + async fn it_should_log_when_a_job_panics() { + let mut manager = JobManager::new(); + + manager.push( + "panic_job", + tokio::spawn(async { + panic!("expected panic"); + }), + ); + + manager.wait_for_all(Duration::from_secs(1)).await; + } +} diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index c519a9f4b..0e9c912af 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -6,7 +6,15 @@ //! 2. Launch all the application services as concurrent jobs. //! //! This modules contains all the functions needed to start those jobs. +pub mod activity_metrics_updater; +pub mod health_check_api; pub mod http_tracker; +pub mod http_tracker_core; +pub mod manager; pub mod torrent_cleanup; +pub mod torrent_repository; pub mod tracker_apis; +pub mod tracker_core; pub mod udp_tracker; +pub mod udp_tracker_core; +pub mod udp_tracker_server; diff --git a/src/bootstrap/jobs/torrent_cleanup.rs b/src/bootstrap/jobs/torrent_cleanup.rs index d48769139..8a3a71a44 100644 --- a/src/bootstrap/jobs/torrent_cleanup.rs +++ b/src/bootstrap/jobs/torrent_cleanup.rs @@ -12,12 +12,11 @@ use std::sync::Arc; +use bittorrent_tracker_core::torrent::manager::TorrentsManager; use chrono::Utc; -use log::info; use tokio::task::JoinHandle; -use torrust_tracker_configuration::Configuration; - -use crate::tracker; +use torrust_tracker_configuration::Core; +use tracing::instrument; /// It starts a jobs for cleaning up the torrent data in the tracker. /// @@ -25,9 +24,11 @@ use crate::tracker; /// /// Refer to [`torrust-tracker-configuration documentation`](https://docs.rs/torrust-tracker-configuration) for more info about that option. #[must_use] -pub fn start_job(config: &Arc, tracker: &Arc) -> JoinHandle<()> { - let weak_tracker = std::sync::Arc::downgrade(tracker); +#[instrument(skip(config, torrents_manager))] +pub fn start_job(config: &Core, torrents_manager: &Arc) -> JoinHandle<()> { + let weak_torrents_manager = std::sync::Arc::downgrade(torrents_manager); let interval = config.inactive_peer_cleanup_interval; + let interval_in_secs = interval; tokio::spawn(async move { let interval = std::time::Duration::from_secs(interval); @@ -37,15 +38,15 @@ pub fn start_job(config: &Arc, tracker: &Arc) - loop { tokio::select! { _ = tokio::signal::ctrl_c() => { - info!("Stopping torrent cleanup job.."); + tracing::info!("Stopping torrent cleanup job ..."); break; } _ = interval.tick() => { - if let Some(tracker) = weak_tracker.upgrade() { + if let Some(torrents_manager) = weak_torrents_manager.upgrade() { let start_time = Utc::now().time(); - info!("Cleaning up torrents.."); - tracker.cleanup_torrents().await; - info!("Cleaned up torrents in: {}ms", (Utc::now().time() - start_time).num_milliseconds()); + tracing::info!("Cleaning up torrents (executed every {} secs) ...", interval_in_secs); + torrents_manager.cleanup_torrents().await; + tracing::info!("Cleaned up torrents in: {} ms", (Utc::now().time() - start_time).num_milliseconds()); } else { break; } diff --git a/src/bootstrap/jobs/torrent_repository.rs b/src/bootstrap/jobs/torrent_repository.rs new file mode 100644 index 000000000..e49323735 --- /dev/null +++ b/src/bootstrap/jobs/torrent_repository.rs @@ -0,0 +1,26 @@ +use std::sync::Arc; + +use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; +use torrust_tracker_configuration::Configuration; + +use crate::container::AppContainer; + +pub fn start_event_listener( + config: &Configuration, + app_container: &Arc, + cancellation_token: CancellationToken, +) -> Option> { + if config.core.tracker_usage_statistics { + let job = torrust_tracker_swarm_coordination_registry::statistics::event::listener::run_event_listener( + app_container.swarm_coordination_registry_container.event_bus.receiver(), + cancellation_token, + &app_container.swarm_coordination_registry_container.stats_repository, + ); + + Some(job) + } else { + tracing::info!("Torrent repository package event listener job is disabled."); + None + } +} diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 9afe4ab24..9f3964c20 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -4,14 +4,14 @@ //! function starts a the HTTP tracker REST API. //! //! > **NOTICE**: that even thought there is only one job the API has different -//! versions. API consumers can choose which version to use. The API version is -//! part of the URL, for example: `http://localhost:1212/api/v1/stats`. +//! > versions. API consumers can choose which version to use. The API version is +//! > part of the URL, for example: `http://localhost:1212/api/v1/stats`. //! -//! The [`tracker_apis::start_job`](crate::bootstrap::jobs::tracker_apis::start_job) +//! The [`tracker_apis::start_job`](crate::bootstrap::jobs::tracker_apis::start_job) //! function spawns a new asynchronous task, that tasks is the "**launcher**". //! The "**launcher**" starts the actual server and sends a message back //! to the main application. The main application waits until receives -//! the message [`ApiServerJobStarted`](crate::bootstrap::jobs::tracker_apis::ApiServerJobStarted) +//! the message [`ApiServerJobStarted`] //! from the "**launcher**". //! //! The "**launcher**" is an intermediary thread that decouples the API server @@ -20,23 +20,25 @@ //! //! Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) //! for the API configuration options. +use std::net::SocketAddr; use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; -use log::info; -use tokio::sync::oneshot; use tokio::task::JoinHandle; -use torrust_tracker_configuration::HttpApi; - -use crate::servers::apis::server; -use crate::tracker; +use torrust_axum_rest_tracker_api_server::server::{ApiServer, Launcher}; +use torrust_axum_rest_tracker_api_server::Version; +use torrust_axum_server::tsl::make_rust_tls; +use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; +use torrust_server_lib::registar::ServiceRegistrationForm; +use torrust_tracker_configuration::AccessTokens; +use tracing::instrument; /// This is the message that the "launcher" spawned task sends to the main /// application process to notify the API server was successfully started. /// /// > **NOTICE**: it does not mean the API server is ready to receive requests. -/// It only means the new server started. It might take some time to the server -/// to be ready to accept request. +/// > It only means the new server started. It might take some time to the server +/// > to be ready to accept request. #[derive(Debug)] pub struct ApiServerJobStarted(); @@ -49,51 +51,82 @@ pub struct ApiServerJobStarted(); /// # Panics /// /// It would panic if unable to send the `ApiServerJobStarted` notice. -pub async fn start_job(config: &HttpApi, tracker: Arc) -> JoinHandle<()> { - let bind_addr = config - .bind_address - .parse::() - .expect("Tracker API bind_address invalid."); - let ssl_enabled = config.ssl_enabled; - let ssl_cert_path = config.ssl_cert_path.clone(); - let ssl_key_path = config.ssl_key_path.clone(); - - let (tx, rx) = oneshot::channel::(); - - // Run the API server - let join_handle = tokio::spawn(async move { - if !ssl_enabled { - info!("Starting Torrust APIs server on: http://{}", bind_addr); - - let handle = server::start(bind_addr, tracker); - - tx.send(ApiServerJobStarted()).expect("the API server should not be dropped"); - - if let Ok(()) = handle.await { - info!("Torrust APIs server on http://{} stopped", bind_addr); - } - } else if ssl_enabled && ssl_cert_path.is_some() && ssl_key_path.is_some() { - info!("Starting Torrust APIs server on: https://{}", bind_addr); - - let ssl_config = RustlsConfig::from_pem_file(ssl_cert_path.unwrap(), ssl_key_path.unwrap()) - .await - .unwrap(); - - let handle = server::start_tls(bind_addr, ssl_config, tracker); - - tx.send(ApiServerJobStarted()).expect("the API server should not be dropped"); - - if let Ok(()) = handle.await { - info!("Torrust APIs server on https://{} stopped", bind_addr); - } - } - }); - - // Wait until the APIs server job is running - match rx.await { - Ok(_msg) => info!("Torrust APIs server started"), - Err(e) => panic!("the API server was dropped: {e}"), +/// +/// +#[instrument(skip(http_api_container, form))] +pub async fn start_job( + http_api_container: Arc, + form: ServiceRegistrationForm, + version: Version, +) -> Option> { + let bind_to = http_api_container.http_api_config.bind_address; + + let tls = make_rust_tls(&http_api_container.http_api_config.tsl_config) + .await + .map(|tls| tls.expect("it should have a valid tracker api tls configuration")); + + let access_tokens = Arc::new(http_api_container.http_api_config.access_tokens.clone()); + + match version { + Version::V1 => Some(start_v1(bind_to, tls, http_api_container, form, access_tokens).await), } +} + +#[allow(clippy::async_yields_async)] +#[instrument(skip(socket, tls, http_api_container, form, access_tokens))] +async fn start_v1( + socket: SocketAddr, + tls: Option, + http_api_container: Arc, + form: ServiceRegistrationForm, + access_tokens: Arc, +) -> JoinHandle<()> { + let server = ApiServer::new(Launcher::new(socket, tls)) + .start(http_api_container, form, access_tokens) + .await + .expect("it should be able to start to the tracker api"); + + tokio::spawn(async move { + assert!(!server.state.halt_task.is_closed(), "Halt channel should be open"); + server.state.task.await.expect("failed to close service"); + }) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; - join_handle + use torrust_axum_rest_tracker_api_server::Version; + use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; + use torrust_server_lib::registar::Registar; + use torrust_tracker_test_helpers::configuration::ephemeral_public; + + use crate::bootstrap::app::initialize_global_services; + use crate::bootstrap::jobs::tracker_apis::start_job; + + #[tokio::test] + async fn it_should_start_http_tracker() { + let cfg = Arc::new(ephemeral_public()); + + let core_config = Arc::new(cfg.core.clone()); + + let http_tracker_config = cfg.http_trackers.clone().expect("missing HTTP tracker configuration"); + let http_tracker_config = Arc::new(http_tracker_config[0].clone()); + + let udp_tracker_configurations = cfg.udp_trackers.clone().expect("missing UDP tracker configuration"); + let udp_tracker_config = Arc::new(udp_tracker_configurations[0].clone()); + + let http_api_config = Arc::new(cfg.http_api.clone().expect("missing HTTP API configuration").clone()); + + initialize_global_services(&cfg); + + let http_api_container = + TrackerHttpApiCoreContainer::initialize(&core_config, &http_tracker_config, &udp_tracker_config, &http_api_config); + + let version = Version::V1; + + start_job(http_api_container, Registar::default().give_form(), version) + .await + .expect("it should be able to join to the tracker api start-job"); + } } diff --git a/src/bootstrap/jobs/tracker_core.rs b/src/bootstrap/jobs/tracker_core.rs new file mode 100644 index 000000000..d881f4cd2 --- /dev/null +++ b/src/bootstrap/jobs/tracker_core.rs @@ -0,0 +1,32 @@ +use std::sync::Arc; + +use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; +use torrust_tracker_configuration::Configuration; + +use crate::container::AppContainer; + +pub fn start_event_listener( + config: &Configuration, + app_container: &Arc, + cancellation_token: CancellationToken, +) -> Option> { + if config.core.tracker_usage_statistics || config.core.tracker_policy.persistent_torrent_completed_stat { + let job = bittorrent_tracker_core::statistics::event::listener::run_event_listener( + app_container.swarm_coordination_registry_container.event_bus.receiver(), + cancellation_token, + &app_container.tracker_core_container.stats_repository, + &app_container.tracker_core_container.db_downloads_metric_repository, + app_container + .tracker_core_container + .core_config + .tracker_policy + .persistent_torrent_completed_stat, + ); + + Some(job) + } else { + tracing::info!("Tracker core event listener job is disabled."); + None + } +} diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 76c465a8d..2723ad9ab 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -4,34 +4,64 @@ //! function starts a new UDP tracker server. //! //! > **NOTICE**: that the application can launch more than one UDP tracker -//! on different ports. Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) -//! for the configuration options. +//! > on different ports. Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) +//! > for the configuration options. use std::sync::Arc; -use log::{error, info, warn}; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; +use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use tokio::task::JoinHandle; -use torrust_tracker_configuration::UdpTracker; - -use crate::servers::udp::server::Udp; -use crate::tracker; +use torrust_server_lib::registar::ServiceRegistrationForm; +use torrust_udp_tracker_server::container::UdpTrackerServerContainer; +use torrust_udp_tracker_server::server::spawner::Spawner; +use torrust_udp_tracker_server::server::Server; +use tracing::instrument; /// It starts a new UDP server with the provided configuration. /// /// It spawns a new asynchronous task for the new UDP server. +/// +/// # Panics +/// +/// It will panic if the API binding address is not a valid socket. +/// It will panic if it is unable to start the UDP service. +/// It will panic if the task did not finish successfully. #[must_use] -pub fn start_job(config: &UdpTracker, tracker: Arc) -> JoinHandle<()> { - let bind_addr = config.bind_address.clone(); +#[allow(clippy::async_yields_async)] +#[instrument(skip(udp_tracker_core_container, udp_tracker_server_container, form))] +pub async fn start_job( + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, + form: ServiceRegistrationForm, +) -> JoinHandle<()> { + let bind_to = udp_tracker_core_container.udp_tracker_config.bind_address; + let cookie_lifetime = udp_tracker_core_container.udp_tracker_config.cookie_lifetime; + + let server = Server::new(Spawner::new(bind_to)) + .start( + udp_tracker_core_container, + udp_tracker_server_container, + form, + cookie_lifetime, + ) + .await + .expect("it should be able to start the udp tracker"); tokio::spawn(async move { - match Udp::new(&bind_addr).await { - Ok(udp_server) => { - info!("Starting UDP server on: udp://{}", bind_addr); - udp_server.start(tracker).await; - } - Err(e) => { - warn!("Could not start UDP tracker on: udp://{}", bind_addr); - error!("{}", e); - } - } + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, "Wait for launcher (UDP service) to finish ..."); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, "Is halt channel closed before waiting?: {}", server.state.halt_task.is_closed()); + + assert!( + !server.state.halt_task.is_closed(), + "Halt channel for UDP tracker should be open" + ); + + server + .state + .task + .await + .expect("it should be able to join to the udp tracker task"); + + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, "Is halt channel closed after finishing the server?: {}", server.state.halt_task.is_closed()); }) } diff --git a/src/bootstrap/jobs/udp_tracker_core.rs b/src/bootstrap/jobs/udp_tracker_core.rs new file mode 100644 index 000000000..dd7e8c165 --- /dev/null +++ b/src/bootstrap/jobs/udp_tracker_core.rs @@ -0,0 +1,25 @@ +use std::sync::Arc; + +use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; +use torrust_tracker_configuration::Configuration; + +use crate::container::AppContainer; + +pub fn start_event_listener( + config: &Configuration, + app_container: &Arc, + cancellation_token: CancellationToken, +) -> Option> { + if config.core.tracker_usage_statistics { + let job = bittorrent_udp_tracker_core::statistics::event::listener::run_event_listener( + app_container.udp_tracker_core_services.event_bus.receiver(), + cancellation_token, + &app_container.udp_tracker_core_services.stats_repository, + ); + Some(job) + } else { + tracing::info!("UDP tracker core event listener job is disabled."); + None + } +} diff --git a/src/bootstrap/jobs/udp_tracker_server.rs b/src/bootstrap/jobs/udp_tracker_server.rs new file mode 100644 index 000000000..fc6df9c16 --- /dev/null +++ b/src/bootstrap/jobs/udp_tracker_server.rs @@ -0,0 +1,35 @@ +use std::sync::Arc; + +use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; +use torrust_tracker_configuration::Configuration; + +use crate::container::AppContainer; + +pub fn start_stats_event_listener( + config: &Configuration, + app_container: &Arc, + cancellation_token: CancellationToken, +) -> Option> { + if config.core.tracker_usage_statistics { + let job = torrust_udp_tracker_server::statistics::event::listener::run_event_listener( + app_container.udp_tracker_server_container.event_bus.receiver(), + cancellation_token, + &app_container.udp_tracker_server_container.stats_repository, + ); + Some(job) + } else { + tracing::info!("UDP tracker server event listener job is disabled."); + None + } +} + +#[must_use] +pub fn start_banning_event_listener(app_container: &Arc, cancellation_token: CancellationToken) -> JoinHandle<()> { + torrust_udp_tracker_server::banning::event::listener::run_event_listener( + app_container.udp_tracker_server_container.event_bus.receiver(), + cancellation_token, + &app_container.udp_tracker_core_services.ban_service, + &app_container.udp_tracker_server_container.stats_repository, + ) +} diff --git a/src/bootstrap/logging.rs b/src/bootstrap/logging.rs deleted file mode 100644 index 97e26919d..000000000 --- a/src/bootstrap/logging.rs +++ /dev/null @@ -1,60 +0,0 @@ -//! Setup for the application logging. -//! -//! It redirects the log info to the standard output with the log level defined in the configuration. -//! -//! - `Off` -//! - `Error` -//! - `Warn` -//! - `Info` -//! - `Debug` -//! - `Trace` -//! -//! Refer to the [configuration crate documentation](https://docs.rs/torrust-tracker-configuration) to know how to change log settings. -use std::str::FromStr; -use std::sync::Once; - -use log::{info, LevelFilter}; -use torrust_tracker_configuration::Configuration; - -static INIT: Once = Once::new(); - -/// It redirects the log info to the standard output with the log level defined in the configuration -pub fn setup(cfg: &Configuration) { - let level = config_level_or_default(&cfg.log_level); - - if level == log::LevelFilter::Off { - return; - } - - INIT.call_once(|| { - stdout_config(level); - }); -} - -fn config_level_or_default(log_level: &Option) -> LevelFilter { - match log_level { - None => log::LevelFilter::Info, - Some(level) => LevelFilter::from_str(level).unwrap(), - } -} - -fn stdout_config(level: LevelFilter) { - if let Err(_err) = fern::Dispatch::new() - .format(|out, message, record| { - out.finish(format_args!( - "{} [{}][{}] {}", - chrono::Local::now().format("%+"), - record.target(), - record.level(), - message - )); - }) - .level(level) - .chain(std::io::stdout()) - .apply() - { - panic!("Failed to initialize logging.") - } - - info!("logging initialized."); -} diff --git a/src/bootstrap/mod.rs b/src/bootstrap/mod.rs index e39cf3adc..2f7909043 100644 --- a/src/bootstrap/mod.rs +++ b/src/bootstrap/mod.rs @@ -6,5 +6,5 @@ //! like cleaning torrents, and other jobs because they can be enabled/disabled depending on the configuration. //! For example, you can have more than one UDP and HTTP tracker, each server is executed like a independent job. pub mod app; +pub mod config; pub mod jobs; -pub mod logging; diff --git a/src/console/ci/e2e/docker.rs b/src/console/ci/e2e/docker.rs new file mode 100644 index 000000000..89d258d2c --- /dev/null +++ b/src/console/ci/e2e/docker.rs @@ -0,0 +1,234 @@ +//! Docker command wrapper. +use std::io; +use std::process::{Command, Output}; +use std::thread::sleep; +use std::time::{Duration, Instant}; + +/// Docker command wrapper. +pub struct Docker {} + +#[derive(Clone, Debug)] +pub struct RunningContainer { + pub image: String, + pub name: String, + pub output: Output, +} + +impl Drop for RunningContainer { + /// Ensures that the temporary container is stopped when the struct goes out + /// of scope. + fn drop(&mut self) { + tracing::info!("Dropping running container: {}", self.name); + if Docker::is_container_running(&self.name) { + let _unused = Docker::stop(self); + } + } +} + +/// `docker run` command options. +pub struct RunOptions { + pub env_vars: Vec<(String, String)>, + pub ports: Vec, +} + +impl Docker { + /// Builds a Docker image from a given Dockerfile. + /// + /// # Errors + /// + /// Will fail if the docker build command fails. + pub fn build(dockerfile: &str, tag: &str) -> io::Result<()> { + let status = Command::new("docker") + .args(["build", "-f", dockerfile, "-t", tag, "."]) + .status()?; + + if status.success() { + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::Other, + format!("Failed to build Docker image from dockerfile {dockerfile}"), + )) + } + } + + /// Runs a Docker container from a given image with multiple environment variables. + /// + /// # Arguments + /// + /// * `image` - The Docker image to run. + /// * `container` - The name for the Docker container. + /// * `env_vars` - A slice of tuples, each representing an environment variable as ("KEY", "value"). + /// + /// # Errors + /// + /// Will fail if the docker run command fails. + pub fn run(image: &str, container: &str, options: &RunOptions) -> io::Result { + let initial_args = vec![ + "run".to_string(), + "--detach".to_string(), + "--name".to_string(), + container.to_string(), + ]; + + // Add environment variables + let mut env_var_args: Vec = vec![]; + for (key, value) in &options.env_vars { + env_var_args.push("--env".to_string()); + env_var_args.push(format!("{key}={value}")); + } + + // Add port mappings + let mut port_args: Vec = vec![]; + for port in &options.ports { + port_args.push("--publish".to_string()); + port_args.push(port.clone()); + } + + let args = [initial_args, env_var_args, port_args, [image.to_string()].to_vec()].concat(); + + tracing::debug!("Docker run args: {:?}", args); + + let output = Command::new("docker").args(args).output()?; + + if output.status.success() { + Ok(RunningContainer { + image: image.to_owned(), + name: container.to_owned(), + output, + }) + } else { + Err(io::Error::new( + io::ErrorKind::Other, + format!("Failed to run Docker image {image}"), + )) + } + } + + /// Stops a Docker container. + /// + /// # Errors + /// + /// Will fail if the docker stop command fails. + pub fn stop(container: &RunningContainer) -> io::Result<()> { + let status = Command::new("docker").args(["stop", &container.name]).status()?; + + if status.success() { + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::Other, + format!("Failed to stop Docker container {}", container.name), + )) + } + } + + /// Removes a Docker container. + /// + /// # Errors + /// + /// Will fail if the docker rm command fails. + pub fn remove(container: &str) -> io::Result<()> { + let status = Command::new("docker").args(["rm", "-f", container]).status()?; + + if status.success() { + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::Other, + format!("Failed to remove Docker container {container}"), + )) + } + } + + /// Fetches logs from a Docker container. + /// + /// # Errors + /// + /// Will fail if the docker logs command fails. + pub fn logs(container: &str) -> io::Result { + let output = Command::new("docker").args(["logs", container]).output()?; + + if output.status.success() { + Ok(String::from_utf8_lossy(&output.stdout).to_string()) + } else { + Err(io::Error::new( + io::ErrorKind::Other, + format!("Failed to fetch logs from Docker container {container}"), + )) + } + } + + /// Checks if a Docker container is healthy. + #[must_use] + pub fn wait_until_is_healthy(name: &str, timeout: Duration) -> bool { + let start = Instant::now(); + + while start.elapsed() < timeout { + let Ok(output) = Command::new("docker") + .args(["ps", "-f", &format!("name={name}"), "--format", "{{.Status}}"]) + .output() + else { + return false; + }; + + let output_str = String::from_utf8_lossy(&output.stdout); + + tracing::info!("Waiting until container is healthy: {:?}", output_str); + + if output_str.contains("(healthy)") { + return true; + } + + sleep(Duration::from_secs(1)); + } + + false + } + + /// Checks if a Docker container is running. + /// + /// # Arguments + /// + /// * `container` - The name of the Docker container. + /// + /// # Returns + /// + /// `true` if the container is running, `false` otherwise. + #[must_use] + pub fn is_container_running(container: &str) -> bool { + match Command::new("docker") + .args(["ps", "-f", &format!("name={container}"), "--format", "{{.Names}}"]) + .output() + { + Ok(output) => { + let output_str = String::from_utf8_lossy(&output.stdout); + output_str.contains(container) + } + Err(_) => false, + } + } + + /// Checks if a Docker container exists. + /// + /// # Arguments + /// + /// * `container` - The name of the Docker container. + /// + /// # Returns + /// + /// `true` if the container exists, `false` otherwise. + #[must_use] + pub fn container_exist(container: &str) -> bool { + match Command::new("docker") + .args(["ps", "-a", "-f", &format!("name={container}"), "--format", "{{.Names}}"]) + .output() + { + Ok(output) => { + let output_str = String::from_utf8_lossy(&output.stdout); + output_str.contains(container) + } + Err(_) => false, + } + } +} diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs new file mode 100644 index 000000000..e8b6b3b8f --- /dev/null +++ b/src/console/ci/e2e/logs_parser.rs @@ -0,0 +1,178 @@ +//! Utilities to parse Torrust Tracker logs. +use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; +use regex::Regex; +use serde::{Deserialize, Serialize}; +use torrust_axum_health_check_api_server::HEALTH_CHECK_API_LOG_TARGET; +use torrust_axum_http_tracker_server::HTTP_TRACKER_LOG_TARGET; +use torrust_server_lib::logging::STARTED_ON; + +const INFO_THRESHOLD: &str = "INFO"; + +#[derive(Serialize, Deserialize, Debug, Default)] +pub struct RunningServices { + pub udp_trackers: Vec, + pub http_trackers: Vec, + pub health_checks: Vec, +} + +impl RunningServices { + /// It parses the tracker logs to extract the running services. + /// + /// For example, from this logs: + /// + /// ```text + /// Loading configuration from default configuration file: `./share/default/config/tracker.development.sqlite3.toml` ... + /// 2024-06-10T16:07:39.989540Z INFO torrust_tracker::bootstrap::logging: Logging initialized + /// 2024-06-10T16:07:39.990205Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6868 + /// 2024-06-10T16:07:39.990215Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6868 + /// 2024-06-10T16:07:39.990244Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6969 + /// 2024-06-10T16:07:39.990255Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969 + /// 2024-06-10T16:07:39.990261Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled + /// 2024-06-10T16:07:39.990303Z INFO HTTP TRACKER: Starting on: http://0.0.0.0:7070 + /// 2024-06-10T16:07:39.990439Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070 + /// 2024-06-10T16:07:39.990448Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled + /// 2024-06-10T16:07:39.990563Z INFO API: Starting on: http://127.0.0.1:1212 + /// 2024-06-10T16:07:39.990565Z INFO API: Started on: http://127.0.0.1:1212 + /// 2024-06-10T16:07:39.990577Z INFO HEALTH CHECK API: Starting on: http://127.0.0.1:1313 + /// 2024-06-10T16:07:39.990638Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 + /// ``` + /// + /// It would extract these services: + /// + /// ```json + /// { + /// "udp_trackers": [ + /// "127.0.0.1:6969" + /// ], + /// "http_trackers": [ + /// "http://127.0.0.1:7070" + /// ], + /// "health_checks": [ + /// "http://127.0.0.1:1313/health_check" + /// ] + /// } + /// ``` + /// + /// NOTICE: Using colors in the console output could affect this method + /// due to the hidden control chars. + /// + /// # Panics + /// + /// Will panic is the regular expression to parse the services can't be compiled. + #[must_use] + pub fn parse_from_logs(logs: &str) -> Self { + let mut udp_trackers: Vec = Vec::new(); + let mut http_trackers: Vec = Vec::new(); + let mut health_checks: Vec = Vec::new(); + + let udp_re = Regex::new(&format!("{STARTED_ON}: {}", r"udp://([0-9.]+:[0-9]+)")).unwrap(); + let http_re = Regex::new(&format!("{STARTED_ON}: {}", r"(https?://[0-9.]+:[0-9]+)")).unwrap(); // DevSkim: ignore DS137138 + let health_re = Regex::new(&format!("{STARTED_ON}: {}", r"(https?://[0-9.]+:[0-9]+)")).unwrap(); // DevSkim: ignore DS137138 + let ansi_escape_re = Regex::new(r"\x1b\[[0-9;]*m").unwrap(); + + for line in logs.lines() { + let clean_line = ansi_escape_re.replace_all(line, ""); + + if !line.contains(INFO_THRESHOLD) { + continue; + } + + if line.contains(UDP_TRACKER_LOG_TARGET) { + if let Some(captures) = udp_re.captures(&clean_line) { + let address = Self::replace_wildcard_ip_with_localhost(&captures[1]); + udp_trackers.push(address); + } + } else if line.contains(HTTP_TRACKER_LOG_TARGET) { + if let Some(captures) = http_re.captures(&clean_line) { + let address = Self::replace_wildcard_ip_with_localhost(&captures[1]); + http_trackers.push(address); + } + } else if line.contains(HEALTH_CHECK_API_LOG_TARGET) { + if let Some(captures) = health_re.captures(&clean_line) { + let address = format!("{}/health_check", Self::replace_wildcard_ip_with_localhost(&captures[1])); + health_checks.push(address); + } + } + } + + Self { + udp_trackers, + http_trackers, + health_checks, + } + } + + fn replace_wildcard_ip_with_localhost(address: &str) -> String { + address.replace("0.0.0.0", "127.0.0.1") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_should_parse_from_logs_with_valid_logs() { + let logs = r" + Loading configuration from default configuration file: `./share/default/config/tracker.development.sqlite3.toml` ... + 2024-06-10T16:07:39.989540Z INFO torrust_tracker::bootstrap::logging: Logging initialized + 2024-06-10T16:07:39.990244Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6969 + 2024-06-10T16:07:39.990255Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969 + 2024-06-10T16:07:39.990261Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled + 2024-06-10T16:07:39.990303Z INFO HTTP TRACKER: Starting on: http://0.0.0.0:7070 + 2024-06-10T16:07:39.990439Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070 + 2024-06-10T16:07:39.990448Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled + 2024-06-10T16:07:39.990563Z INFO API: Starting on: http://127.0.0.1:1212 + 2024-06-10T16:07:39.990565Z INFO API: Started on: http://127.0.0.1:1212 + 2024-06-10T16:07:39.990577Z INFO HEALTH CHECK API: Starting on: http://127.0.0.1:1313 + 2024-06-10T16:07:39.990638Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 + "; + + let running_services = RunningServices::parse_from_logs(logs); + + assert_eq!(running_services.udp_trackers, vec!["127.0.0.1:6969"]); + assert_eq!(running_services.http_trackers, vec!["http://127.0.0.1:7070"]); + assert_eq!(running_services.health_checks, vec!["http://127.0.0.1:1313/health_check"]); + } + + #[test] + fn it_should_support_colored_output() { + let logs = "\x1b[2m2024-06-14T14:40:13.028824Z\x1b[0m \x1b[33mINFO\x1b[0m \x1b[2mUDP TRACKER\x1b[0m: \x1b[37mStarted on: udp://0.0.0.0:6969\x1b[0m"; + + let running_services = RunningServices::parse_from_logs(logs); + + assert_eq!(running_services.udp_trackers, vec!["127.0.0.1:6969"]); + } + + #[test] + fn it_should_ignore_logs_with_no_matching_lines() { + let logs = "[Other Service][INFO] Started on: 0.0.0.0:7070"; + + let running_services = RunningServices::parse_from_logs(logs); + + assert!(running_services.udp_trackers.is_empty()); + assert!(running_services.http_trackers.is_empty()); + assert!(running_services.health_checks.is_empty()); + } + + #[test] + fn it_should_parse_multiple_services() { + let logs = " + 2024-06-10T16:07:39.990205Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6868 + 2024-06-10T16:07:39.990215Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6868 + + 2024-06-10T16:07:39.990244Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6969 + 2024-06-10T16:07:39.990255Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969 + "; + + let running_services = RunningServices::parse_from_logs(logs); + + assert_eq!(running_services.udp_trackers, vec!["127.0.0.1:6868", "127.0.0.1:6969"]); + } + + #[test] + fn it_should_replace_wildcard_ip_with_localhost() { + let address = "0.0.0.0:8080"; + assert_eq!(RunningServices::replace_wildcard_ip_with_localhost(address), "127.0.0.1:8080"); + } +} diff --git a/src/console/ci/e2e/mod.rs b/src/console/ci/e2e/mod.rs new file mode 100644 index 000000000..58a876cbe --- /dev/null +++ b/src/console/ci/e2e/mod.rs @@ -0,0 +1,6 @@ +//! E2E tests scripts. +pub mod docker; +pub mod logs_parser; +pub mod runner; +pub mod tracker_checker; +pub mod tracker_container; diff --git a/src/console/ci/e2e/runner.rs b/src/console/ci/e2e/runner.rs new file mode 100644 index 000000000..6275c144b --- /dev/null +++ b/src/console/ci/e2e/runner.rs @@ -0,0 +1,158 @@ +//! Program to run E2E tests. +//! +//! You can execute it with (passing a TOML config file path): +//! +//! ```text +//! cargo run --bin e2e_tests_runner -- --config-toml-path "./share/default/config/tracker.e2e.container.sqlite3.toml" +//! ``` +//! +//! Or: +//! +//! ```text +//! TORRUST_TRACKER_CONFIG_TOML_PATH="./share/default/config/tracker.e2e.container.sqlite3.toml" cargo run --bin e2e_tests_runner" +//! ``` +//! +//! You can execute it with (directly passing TOML config): +//! +//! ```text +//! TORRUST_TRACKER_CONFIG_TOML=$(cat "./share/default/config/tracker.e2e.container.sqlite3.toml") cargo run --bin e2e_tests_runner +//! ``` +use std::path::PathBuf; + +use anyhow::Context; +use clap::Parser; +use tracing::level_filters::LevelFilter; + +use super::tracker_container::TrackerContainer; +use crate::console::ci::e2e::docker::RunOptions; +use crate::console::ci::e2e::logs_parser::RunningServices; +use crate::console::ci::e2e::tracker_checker::{self}; + +/* code-review: + - We use always the same docker image name. Should we use a random image name (tag)? + - We use the name image name we use in other workflows `torrust-tracker:local`. + Should we use a different one like `torrust-tracker:e2e`? + - We remove the container after running tests but not the container image. + Should we remove the image too? +*/ + +const CONTAINER_IMAGE: &str = "torrust-tracker:local"; +const CONTAINER_NAME_PREFIX: &str = "tracker_"; + +#[derive(Parser, Debug)] +#[clap(author, version, about, long_about = None)] +struct Args { + /// Path to the JSON configuration file. + #[clap(short, long, env = "TORRUST_TRACKER_CONFIG_TOML_PATH")] + config_toml_path: Option, + + /// Direct configuration content in JSON. + #[clap(env = "TORRUST_TRACKER_CONFIG_TOML", hide_env_values = true)] + config_toml: Option, +} + +/// Script to run E2E tests. +/// +/// # Errors +/// +/// Will return an error if it can't load the tracker configuration from arguments. +/// +/// # Panics +/// +/// Will panic if it can't not perform any of the operations. +pub fn run() -> anyhow::Result<()> { + tracing_stdout_init(LevelFilter::INFO); + + let args = Args::parse(); + + let tracker_config = load_tracker_configuration(&args)?; + + tracing::info!("tracker config:\n{tracker_config}"); + + let mut tracker_container = TrackerContainer::new(CONTAINER_IMAGE, CONTAINER_NAME_PREFIX); + + tracker_container.build_image(); + + // code-review: if we want to use port 0 we don't know which ports we have to open. + // Besides, if we don't use port 0 we should get the port numbers from the tracker configuration. + // We could not use docker, but the intention was to create E2E tests including containerization. + let options = RunOptions { + env_vars: vec![("TORRUST_TRACKER_CONFIG_TOML".to_string(), tracker_config.clone())], + ports: vec![ + "6969:6969/udp".to_string(), + "7070:7070/tcp".to_string(), + "1212:1212/tcp".to_string(), + "1313:1313/tcp".to_string(), + ], + }; + + tracker_container.run(&options); + + let running_services = tracker_container.running_services(); + + tracing::info!( + "Running services:\n {}", + serde_json::to_string_pretty(&running_services).expect("running services to be serializable to JSON") + ); + + assert_there_is_at_least_one_service_per_type(&running_services); + + let tracker_checker_config = + serde_json::to_string_pretty(&running_services).expect("Running services should be serialized into JSON"); + + tracker_checker::run(&tracker_checker_config).expect("All tracker services should be running correctly"); + + // More E2E tests could be added here in the future. + // For example: `cargo test ...` for only E2E tests, using this shared test env. + + tracker_container.stop(); + + tracker_container.remove(); + + tracing::info!("Tracker container final state:\n{:#?}", tracker_container); + + Ok(()) +} + +fn tracing_stdout_init(filter: LevelFilter) { + tracing_subscriber::fmt().with_max_level(filter).init(); + tracing::info!("Logging initialized"); +} + +fn load_tracker_configuration(args: &Args) -> anyhow::Result { + match (args.config_toml_path.clone(), args.config_toml.clone()) { + (Some(config_path), _) => { + tracing::info!( + "Reading tracker configuration from file: {} ...", + config_path.to_string_lossy() + ); + load_config_from_file(&config_path) + } + (_, Some(config_content)) => { + tracing::info!("Reading tracker configuration from env var ..."); + Ok(config_content) + } + _ => Err(anyhow::anyhow!("No configuration provided")), + } +} + +fn load_config_from_file(path: &PathBuf) -> anyhow::Result { + let config = std::fs::read_to_string(path).with_context(|| format!("CSan't read config file {}", path.display()))?; + + Ok(config) +} + +fn assert_there_is_at_least_one_service_per_type(running_services: &RunningServices) { + assert!( + !running_services.udp_trackers.is_empty(), + "At least one UDP tracker should be enabled in E2E tests configuration" + ); + assert!( + !running_services.http_trackers.is_empty(), + "At least one HTTP tracker should be enabled in E2E tests configuration" + ); + assert!( + !running_services.health_checks.is_empty(), + "At least one Health Check should be enabled in E2E tests configuration" + ); +} diff --git a/src/console/ci/e2e/tracker_checker.rs b/src/console/ci/e2e/tracker_checker.rs new file mode 100644 index 000000000..a39e68c93 --- /dev/null +++ b/src/console/ci/e2e/tracker_checker.rs @@ -0,0 +1,25 @@ +use std::io; +use std::process::Command; + +/// Runs the Tracker Checker. +/// +/// # Errors +/// +/// Will return an error if the Tracker Checker fails. +pub fn run(config_content: &str) -> io::Result<()> { + tracing::info!( + "Running Tracker Checker: TORRUST_CHECKER_CONFIG=[config] cargo run -p torrust-tracker-client --bin tracker_checker" + ); + tracing::info!("Tracker Checker config:\n{config_content}"); + + let status = Command::new("cargo") + .env("TORRUST_CHECKER_CONFIG", config_content) + .args(["run", "-p", "torrust-tracker-client", "--bin", "tracker_checker"]) + .status()?; + + if status.success() { + Ok(()) + } else { + Err(io::Error::new(io::ErrorKind::Other, "Failed to run Tracker Checker")) + } +} diff --git a/src/console/ci/e2e/tracker_container.rs b/src/console/ci/e2e/tracker_container.rs new file mode 100644 index 000000000..1a7717a41 --- /dev/null +++ b/src/console/ci/e2e/tracker_container.rs @@ -0,0 +1,130 @@ +use std::time::Duration; + +use rand::distr::Alphanumeric; +use rand::RngExt; + +use super::docker::{RunOptions, RunningContainer}; +use super::logs_parser::RunningServices; +use crate::console::ci::e2e::docker::Docker; + +#[derive(Debug)] +pub struct TrackerContainer { + pub image: String, + pub name: String, + pub running: Option, +} + +impl Drop for TrackerContainer { + /// Ensures that the temporary container is removed when the + /// struct goes out of scope. + fn drop(&mut self) { + tracing::info!("Dropping tracker container: {}", self.name); + if Docker::container_exist(&self.name) { + let _unused = Docker::remove(&self.name); + } + } +} + +impl TrackerContainer { + #[must_use] + pub fn new(tag: &str, container_name_prefix: &str) -> Self { + Self { + image: tag.to_owned(), + name: Self::generate_random_container_name(container_name_prefix), + running: None, + } + } + + /// # Panics + /// + /// Will panic if it can't build the docker image. + pub fn build_image(&self) { + tracing::info!("Building tracker container image with tag: {} ...", self.image); + Docker::build("./Containerfile", &self.image).expect("A tracker local docker image should be built"); + } + + /// # Panics + /// + /// Will panic if it can't run the container. + pub fn run(&mut self, options: &RunOptions) { + tracing::info!("Running docker tracker image: {} ...", self.name); + + let container = Docker::run(&self.image, &self.name, options).expect("A tracker local docker image should be running"); + + tracing::info!("Waiting for the container {} to be healthy ...", self.name); + + let is_healthy = Docker::wait_until_is_healthy(&self.name, Duration::from_secs(10)); + + assert!(is_healthy, "Unhealthy tracker container: {}", &self.name); + + tracing::info!("Container {} is healthy ...", &self.name); + + self.running = Some(container); + + self.assert_there_are_no_panics_in_logs(); + } + + /// # Panics + /// + /// Will panic if it can't get the logs from the running container. + #[must_use] + pub fn running_services(&self) -> RunningServices { + let logs = Docker::logs(&self.name).expect("Logs should be captured from running container"); + + tracing::info!("Parsing running services from logs. Logs :\n{logs}"); + + RunningServices::parse_from_logs(&logs) + } + + /// # Panics + /// + /// Will panic if it can't stop the container. + pub fn stop(&mut self) { + match &self.running { + Some(container) => { + tracing::info!("Stopping docker tracker container: {} ...", self.name); + + Docker::stop(container).expect("Container should be stopped"); + + self.assert_there_are_no_panics_in_logs(); + } + None => { + if Docker::is_container_running(&self.name) { + tracing::error!("Tracker container {} was started manually", self.name); + } else { + tracing::info!("Docker tracker container is not running: {} ...", self.name); + } + } + } + + self.running = None; + } + + /// # Panics + /// + /// Will panic if it can't remove the container. + pub fn remove(&self) { + if let Some(_running_container) = &self.running { + tracing::error!("Can't remove running container: {} ...", self.name); + } else { + tracing::info!("Removing docker tracker container: {} ...", self.name); + Docker::remove(&self.name).expect("Container should be removed"); + } + } + + fn generate_random_container_name(prefix: &str) -> String { + let rand_string: String = rand::rng().sample_iter(&Alphanumeric).take(20).map(char::from).collect(); + + format!("{prefix}{rand_string}") + } + + fn assert_there_are_no_panics_in_logs(&self) { + let logs = Docker::logs(&self.name).expect("Logs should be captured from running container"); + + assert!( + !(logs.contains(" panicked at ") || logs.contains("RUST_BACKTRACE=1")), + "{}", + format!("Panics found is logs:\n{logs}") + ); + } +} diff --git a/src/console/ci/mod.rs b/src/console/ci/mod.rs new file mode 100644 index 000000000..6eac3e120 --- /dev/null +++ b/src/console/ci/mod.rs @@ -0,0 +1,2 @@ +//! Continuos integration scripts. +pub mod e2e; diff --git a/src/console/mod.rs b/src/console/mod.rs new file mode 100644 index 000000000..0e0da3fa2 --- /dev/null +++ b/src/console/mod.rs @@ -0,0 +1,3 @@ +//! Console apps. +pub mod ci; +pub mod profiling; diff --git a/src/console/profiling.rs b/src/console/profiling.rs new file mode 100644 index 000000000..df44f4009 --- /dev/null +++ b/src/console/profiling.rs @@ -0,0 +1,199 @@ +//! This binary is used for profiling with [valgrind](https://valgrind.org/) +//! and [kcachegrind](https://kcachegrind.github.io/). +//! +//! # Requirements +//! +//! [valgrind](https://valgrind.org/) and [kcachegrind](https://kcachegrind.github.io/). +//! +//! On Ubuntu you can install them with: +//! +//! ```text +//! sudo apt install valgrind kcachegrind +//! ``` +//! +//! > NOTICE: valgrind executes the program you wan to profile and waits until +//! > it ends. Since the tracker is a service and does not end the profiling +//! > binary accepts an arguments with the duration you want to run the tracker, +//! > so that it terminates automatically after that period of time. +//! +//! # Run profiling +//! +//! To run the profiling you have to: +//! +//! 1. Build and run the tracker for profiling. +//! 2. Run the aquatic UDP load test tool to start collecting data in the tracker. +//! +//! Build and run the tracker for profiling: +//! +//! ```text +//! RUSTFLAGS='-g' cargo build --release --bin profiling \ +//! && export TORRUST_TRACKER_CONFIG_TOML_PATH="./share/default/config/tracker.udp.benchmarking.toml" \ +//! && valgrind \ +//! --tool=callgrind \ +//! --callgrind-out-file=callgrind.out \ +//! --collect-jumps=yes \ +//! --simulate-cache=yes \ +//! ./target/release/profiling 60 +//! ``` +//! +//! The output should be something like: +//! +//! ```text +//! RUSTFLAGS='-g' cargo build --release --bin profiling \ +//! && export TORRUST_TRACKER_CONFIG_TOML_PATH="./share/default/config/tracker.udp.benchmarking.toml" \ +//! && valgrind \ +//! --tool=callgrind \ +//! --callgrind-out-file=callgrind.out \ +//! --collect-jumps=yes \ +//! --simulate-cache=yes \ +//! ./target/release/profiling 60 +//! +//! Compiling torrust-tracker v3.0.0-alpha.12-develop (/home/developer/Documents/git/committer/me/github/torrust/torrust-tracker) +//! Finished `release` profile [optimized + debuginfo] target(s) in 1m 15s +//! ==122801== Callgrind, a call-graph generating cache profiler +//! ==122801== Copyright (C) 2002-2017, and GNU GPL'd, by Josef Weidendorfer et al. +//! ==122801== Using Valgrind-3.19.0 and LibVEX; rerun with -h for copyright info +//! ==122801== Command: ./target/release/profiling 60 +//! ==122801== +//! --122801-- warning: L3 cache found, using its data for the LL simulation. +//! ==122801== For interactive control, run 'callgrind_control -h'. +//! Loading configuration file: `./share/default/config/tracker.udp.benchmarking.toml` ... +//! Torrust successfully shutdown. +//! ==122801== +//! ==122801== Events : Ir Dr Dw I1mr D1mr D1mw ILmr DLmr DLmw +//! ==122801== Collected : 1160654816 278135882 247755311 24453652 12650490 16315690 10932 2481624 4832145 +//! ==122801== +//! ==122801== I refs: 1,160,654,816 +//! ==122801== I1 misses: 24,453,652 +//! ==122801== LLi misses: 10,932 +//! ==122801== I1 miss rate: 2.11% +//! ==122801== LLi miss rate: 0.00% +//! ==122801== +//! ==122801== D refs: 525,891,193 (278,135,882 rd + 247,755,311 wr) +//! ==122801== D1 misses: 28,966,180 ( 12,650,490 rd + 16,315,690 wr) +//! ==122801== LLd misses: 7,313,769 ( 2,481,624 rd + 4,832,145 wr) +//! ==122801== D1 miss rate: 5.5% ( 4.5% + 6.6% ) +//! ==122801== LLd miss rate: 1.4% ( 0.9% + 2.0% ) +//! ==122801== +//! ==122801== LL refs: 53,419,832 ( 37,104,142 rd + 16,315,690 wr) +//! ==122801== LL misses: 7,324,701 ( 2,492,556 rd + 4,832,145 wr) +//! ==122801== LL miss rate: 0.4% ( 0.2% + 2.0% ) +//! ``` +//! +//! > NOTICE: We are using an specific tracker configuration for profiling that +//! > removes all features except the UDP tracker and sets the logging level to `error`. +//! +//! Build the aquatic UDP load test command: +//! +//! ```text +//! cd /tmp +//! git clone git@github.com:greatest-ape/aquatic.git +//! cd aquatic +//! cargo build --profile=release-debug -p aquatic_udp_load_test +//! ./target/release-debug/aquatic_udp_load_test -p > "load-test-config.toml" +//! ``` +//! +//! Modify the "load-test-config.toml" file to change the UDP tracker port from +//! `3000` to `6969`. +//! +//! Running the aquatic UDP load test command: +//! +//! ```text +//! ./target/release-debug/aquatic_udp_load_test -c "load-test-config.toml" +//! ``` +//! +//! The output should be something like this: +//! +//! ```text +//! Starting client with config: Config { +//! server_address: 127.0.0.1:6969, +//! log_level: Error, +//! workers: 1, +//! duration: 0, +//! summarize_last: 0, +//! extra_statistics: true, +//! network: NetworkConfig { +//! multiple_client_ipv4s: true, +//! sockets_per_worker: 4, +//! recv_buffer: 8000000, +//! }, +//! requests: RequestConfig { +//! number_of_torrents: 1000000, +//! number_of_peers: 2000000, +//! scrape_max_torrents: 10, +//! announce_peers_wanted: 30, +//! weight_connect: 50, +//! weight_announce: 50, +//! weight_scrape: 1, +//! peer_seeder_probability: 0.75, +//! }, +//! } +//! +//! Requests out: 45097.51/second +//! Responses in: 4212.70/second +//! - Connect responses: 2098.15 +//! - Announce responses: 2074.95 +//! - Scrape responses: 39.59 +//! - Error responses: 0.00 +//! Peers per announce response: 0.00 +//! Announce responses per info hash: +//! - p10: 1 +//! - p25: 1 +//! - p50: 1 +//! - p75: 2 +//! - p90: 3 +//! - p95: 4 +//! - p99: 6 +//! - p99.9: 8 +//! - p100: 10 +//! ``` +//! +//! After running the tracker for some seconds the tracker will automatically stop +//! and `valgrind`will write the file `callgrind.out` with the data. +//! +//! You can now analyze the collected data with: +//! +//! ```text +//! kcachegrind callgrind.out +//! ``` +use std::env; +use std::time::Duration; + +use tokio::time::sleep; + +use crate::app; + +pub async fn run() { + // Parse command line arguments + let args: Vec = env::args().collect(); + + // Ensure an argument for duration is provided + if args.len() != 2 { + eprintln!("Usage: {} ", args[0]); + return; + } + + // Parse duration argument + let Ok(duration_secs) = args[1].parse::() else { + eprintln!("Invalid duration provided"); + return; + }; + + let (_app_container, jobs) = app::run().await; + + // Run the tracker for a fixed duration + let run_duration = sleep(Duration::from_secs(duration_secs)); + + tokio::select! { + () = run_duration => { + tracing::info!("Torrust timed shutdown.."); + }, + _ = tokio::signal::ctrl_c() => { + tracing::info!("Torrust tracker shutting down via Ctrl+C ..."); + + jobs.wait_for_all(Duration::from_secs(10)).await; + } + } + + println!("Torrust successfully shutdown."); +} diff --git a/src/container.rs b/src/container.rs new file mode 100644 index 000000000..7112a54e8 --- /dev/null +++ b/src/container.rs @@ -0,0 +1,209 @@ +use std::collections::HashMap; +use std::net::SocketAddr; +use std::sync::Arc; + +use bittorrent_http_tracker_core::container::{HttpTrackerCoreContainer, HttpTrackerCoreServices}; +use bittorrent_tracker_core::container::TrackerCoreContainer; +use bittorrent_udp_tracker_core::container::{UdpTrackerCoreContainer, UdpTrackerCoreServices}; +use bittorrent_udp_tracker_core::{self}; +use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; +use torrust_server_lib::registar::Registar; +use torrust_tracker_configuration::{Configuration, HttpApi}; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; +use torrust_udp_tracker_server::container::UdpTrackerServerContainer; +use tracing::instrument; + +#[derive(thiserror::Error, Debug, Clone)] +pub enum Error { + #[error("There is not a HTTP tracker server instance bound to the socket address: {bind_address}")] + MissingHttpTrackerCoreContainer { bind_address: SocketAddr }, + + #[error("There is not a UDP tracker server instance bound to the socket address: {bind_address}")] + MissingUdpTrackerCoreContainer { bind_address: SocketAddr }, +} + +pub struct AppContainer { + // Configuration + pub http_api_config: Arc>, + + // Registar + pub registar: Arc, + + // Swarm Coordination Registry Container + pub swarm_coordination_registry_container: Arc, + + // Core + pub tracker_core_container: Arc, + + // HTTP + pub http_tracker_core_services: Arc, + pub http_tracker_instance_containers: Arc>>, + + // UDP + pub udp_tracker_core_services: Arc, + pub udp_tracker_server_container: Arc, + pub udp_tracker_instance_containers: Arc>>, +} + +impl AppContainer { + #[instrument(skip(configuration))] + pub fn initialize(configuration: &Configuration) -> AppContainer { + // Configuration + + let core_config = Arc::new(configuration.core.clone()); + + let http_api_config = Arc::new(configuration.http_api.clone()); + + // Registar + + let registar = Arc::new(Registar::default()); + + // Swarm Coordination Registry Container + + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + core_config.tracker_usage_statistics.into(), + )); + + // Core + + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + &core_config, + &swarm_coordination_registry_container, + )); + + // HTTP + + let http_tracker_core_services = HttpTrackerCoreServices::initialize_from(&tracker_core_container); + + let http_tracker_instance_containers = Self::initialize_http_tracker_instance_containers( + configuration, + &tracker_core_container, + &http_tracker_core_services, + ); + + // UDP + + let udp_tracker_core_services = UdpTrackerCoreServices::initialize_from(&tracker_core_container); + + let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); + + let udp_tracker_instance_containers = + Self::initialize_udp_tracker_instance_containers(configuration, &tracker_core_container, &udp_tracker_core_services); + + AppContainer { + // Configuration + http_api_config, + + // Registar + registar, + + // Swarm Coordination Registry Container + swarm_coordination_registry_container, + + // Core + tracker_core_container, + + // HTTP + http_tracker_core_services, + http_tracker_instance_containers, + + // UDP + udp_tracker_core_services, + udp_tracker_server_container, + udp_tracker_instance_containers, + } + } + + #[must_use] + pub fn udp_tracker_server_container(&self) -> Arc { + self.udp_tracker_server_container.clone() + } + + /// # Errors + /// + /// Return an error if there is no HTTP tracker server instance bound to the + /// socket address. + pub fn http_tracker_container(&self, bind_address: SocketAddr) -> Result, Error> { + match self.http_tracker_instance_containers.get(&bind_address) { + Some(http_tracker_container) => Ok(http_tracker_container.clone()), + None => Err(Error::MissingHttpTrackerCoreContainer { bind_address }), + } + } + + /// # Errors + /// + /// Return an error if there is no UDP tracker server instance bound to the + /// socket address. + pub fn udp_tracker_container(&self, bind_address: SocketAddr) -> Result, Error> { + match self.udp_tracker_instance_containers.get(&bind_address) { + Some(udp_tracker_container) => Ok(udp_tracker_container.clone()), + None => Err(Error::MissingUdpTrackerCoreContainer { bind_address }), + } + } + + #[must_use] + pub fn tracker_http_api_container(&self, http_api_config: &Arc) -> Arc { + TrackerHttpApiCoreContainer { + http_api_config: http_api_config.clone(), + + swarm_coordination_registry_container: self.swarm_coordination_registry_container.clone(), + + tracker_core_container: self.tracker_core_container.clone(), + + http_stats_repository: self.http_tracker_core_services.stats_repository.clone(), + + ban_service: self.udp_tracker_core_services.ban_service.clone(), + udp_core_stats_repository: self.udp_tracker_core_services.stats_repository.clone(), + udp_server_stats_repository: self.udp_tracker_server_container.stats_repository.clone(), + } + .into() + } + + #[must_use] + fn initialize_http_tracker_instance_containers( + configuration: &Configuration, + tracker_core_container: &Arc, + http_tracker_core_services: &Arc, + ) -> Arc>> { + let mut http_tracker_instance_containers = HashMap::new(); + + if let Some(http_trackers) = &configuration.http_trackers { + for http_tracker_config in http_trackers { + http_tracker_instance_containers.insert( + http_tracker_config.bind_address, + HttpTrackerCoreContainer::initialize_from_services( + tracker_core_container, + http_tracker_core_services, + &Arc::new(http_tracker_config.clone()), + ), + ); + } + } + + Arc::new(http_tracker_instance_containers) + } + + #[must_use] + fn initialize_udp_tracker_instance_containers( + configuration: &Configuration, + tracker_core_container: &Arc, + udp_tracker_core_services: &Arc, + ) -> Arc>> { + let mut udp_tracker_instance_containers = HashMap::new(); + + if let Some(udp_trackers) = &configuration.udp_trackers { + for udp_tracker_config in udp_trackers { + udp_tracker_instance_containers.insert( + udp_tracker_config.bind_address, + UdpTrackerCoreContainer::initialize_from_services( + tracker_core_container, + udp_tracker_core_services, + &Arc::new(udp_tracker_config.clone()), + ), + ); + } + } + + Arc::new(udp_tracker_instance_containers) + } +} diff --git a/src/lib.rs b/src/lib.rs index e219e59e3..b26960899 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -36,7 +36,7 @@ //! - [API](#api) //! - [HTTP Tracker](#http-tracker) //! - [UDP Tracker](#udp-tracker) -//! - [Components](#components) +//! - [Packages](#packages) //! - [Implemented BEPs](#implemented-beps) //! - [Contributing](#contributing) //! - [Documentation](#documentation) @@ -55,131 +55,178 @@ //! //! From the end-user perspective the Torrust Tracker exposes three different services. //! -//! - A REST [`API`](crate::servers::apis) -//! - One or more [`UDP`](crate::servers::udp) trackers -//! - One or more [`HTTP`](crate::servers::http) trackers +//! - A REST [`API`](torrust_axum_rest_tracker_api_server) +//! - One or more [`UDP`](torrust_udp_tracker_server) trackers +//! - One or more [`HTTP`](torrust_axum_http_tracker_server) trackers //! //! # Installation //! //! ## Minimum requirements //! //! - Rust Stable `1.68` -//! - You might have problems compiling with a machine with low resources. Or with low resources limits on docker containers. It has been tested with docker containers with 6 CPUs, 7.5 GM of memory and 2GB of swap. +//! - You might have problems compiling with a machine with low resources. +//! +//! It has been tested with: +//! +//! Docker containers with: +//! +//! - 6 CPUs +//! - 7.5G of ram +//! - 2GB of swap +//! +//! [VM](https://github.com/torrust/torrust-tracker/issues/321) with: +//! +//! - 1 core of Intel Xeon Processor (Icelake) +//! - 1G of ram +//! - 25G of disk +//! - Debian 11 +//! - no swap by default +//! +//! Adding swap may help with compilation. See issue [#321](https://github.com/torrust/torrust-tracker/issues/321). //! //! ## Prerequisites //! +//! The tracker has some system dependencies: +//! +//! Since we are using the `openssl` crate with the [vendored feature](https://docs.rs/openssl/latest/openssl/#vendored), +//! enabled, you will need to install the following dependencies: +//! +//! ```text +//! sudo apt-get install pkg-config libssl-dev make +//! ``` +//! +//! If you are using `SQLite3` as database driver, you will need to install the +//! following dependency: +//! +//! ```text +//! sudo apt-get install libsqlite3-dev +//! ``` +//! +//! > **NOTICE**: those are the commands for `Ubuntu`. If you are using a +//! > different OS, you will need to install the equivalent packages. Please +//! > refer to the documentation of your OS. +//! //! With the default configuration you will need to create the `storage` directory: //! //! ```text -//! storage/ -//! ├── database -//! │   └── data.db -//! └── ssl_certificates -//! ├── localhost.crt -//! └── localhost.key +//! ./storage/ +//! └── tracker +//! ├── etc +//! ├── lib +//! │   ├── database +//! │   │   └── sqlite3.db +//! │   └── tls +//! └── log //! ``` //! -//! The default configuration expects a directory `./storage/database` to be writable by the tracker process. +//! The default configuration expects a directory `./storage/tracker/lib/database` to be writable by the tracker process. //! -//! By default the tracker uses `SQLite` and the database file name `data.db`. +//! By default the tracker uses `SQLite` and the database file name `sqlite3.db`. //! -//! You only need the `ssl_certificates` directory in case you are setting up SSL for the HTTP tracker or the tracker API. -//! Visit [`HTTP`](crate::servers::http) or [`API`](crate::servers::apis) if you want to know how you can use HTTPS. +//! You only need the `tls` directory in case you are setting up SSL for the HTTP tracker or the tracker API. +//! Visit [`HTTP`](torrust_axum_http_tracker_server) or [`API`](torrust_axum_rest_tracker_api_server) if you want to know how you can use HTTPS. //! //! ## Install from sources //! +//! First, you need to create a folder to clone the repository. +//! +//! ```text +//! cd /tmp +//! mkdir torrust +//! ``` +//! //! ```text //! git clone https://github.com/torrust/torrust-tracker.git \ //! && cd torrust-tracker \ -//! && cargo build --release \ -//! && mkdir -p ./storage/database \ -//! && mkdir -p ./storage/ssl_certificates +//! && mkdir -p ./storage/tracker/etc \ +//! && mkdir -p ./storage/tracker/lib/database \ +//! && mkdir -p ./storage/tracker/lib/tls \ +//! && mkdir -p ./storage/tracker/log //! ``` //! -//! ## Run with docker -//! -//! You can run the tracker with a pre-built docker image: +//! To run the tracker we will have to use the command "cargo run" this will +//! compile and after being compiled it will start running the tracker. //! //! ```text -//! mkdir -p ./storage/database \ -//! && mkdir -p ./storage/ssl_certificates \ -//! && export TORRUST_TRACKER_USER_UID=1000 \ -//! && docker run -it \ -//! --user="$TORRUST_TRACKER_USER_UID" \ -//! --publish 6969:6969/udp \ -//! --publish 7070:7070/tcp \ -//! --publish 1212:1212/tcp \ -//! --volume "$(pwd)/storage":"/app/storage" \ -//! torrust/tracker:3.0.0-alpha.2 +//! cargo run --release //! ``` //! -//! For more information about using docker visit the [tracker docker documentation](https://github.com/torrust/torrust-tracker/tree/develop/docker). +//! ## Run with docker +//! +//! You can run the tracker with a pre-built docker image. Please refer to the +//! [tracker docker documentation](https://github.com/torrust/torrust-tracker/blob/develop/docs/containers.md). //! //! # Configuration //! -//! In order to run the tracker you need to provide the configuration. If you run the tracker without providing the configuration, -//! the tracker will generate the default configuration the first time you run it. It will generate a `config.toml` file with -//! in the root directory. +//! In order to run the tracker you need to provide the configuration. If you +//! run the tracker without providing the configuration, the tracker will +//! generate the default configuration the first time you run it. It will +//! generate a `tracker.toml` file with in the root directory. //! //! The default configuration is: //! //! ```toml -//! log_level = "info" -//! mode = "public" -//! db_driver = "Sqlite3" -//! db_path = "./storage/database/data.db" -//! announce_interval = 120 -//! min_announce_interval = 120 -//! max_peer_timeout = 900 -//! on_reverse_proxy = false -//! external_ip = "0.0.0.0" -//! tracker_usage_statistics = true -//! persistent_torrent_completed_stat = false +//! [logging] +//! threshold = "info" +//! +//! [core] //! inactive_peer_cleanup_interval = 600 -//! remove_peerless_torrents = true +//! listed = false +//! private = false +//! tracker_usage_statistics = true //! -//! [[udp_trackers]] -//! enabled = false -//! bind_address = "0.0.0.0:6969" +//! [core.announce_policy] +//! interval = 120 +//! interval_min = 120 //! -//! [[http_trackers]] -//! enabled = false -//! bind_address = "0.0.0.0:7070" -//! ssl_enabled = false -//! ssl_cert_path = "" -//! ssl_key_path = "" +//! [core.database] +//! driver = "sqlite3" +//! path = "./storage/tracker/lib/database/sqlite3.db" //! -//! [http_api] -//! enabled = true -//! bind_address = "127.0.0.1:1212" -//! ssl_enabled = false -//! ssl_cert_path = "" -//! ssl_key_path = "" +//! [core.net] +//! external_ip = "0.0.0.0" +//! on_reverse_proxy = false //! -//! [http_api.access_tokens] -//! admin = "MyAccessToken" -//! ``` +//! [core.tracker_policy] +//! max_peer_timeout = 900 +//! persistent_torrent_completed_stat = false +//! remove_peerless_torrents = true +//! +//! [health_check_api] +//! bind_address = "127.0.0.1:1313" +//!``` //! -//! The default configuration includes one disabled UDP server, one disabled HTTP server and the enabled API. +//! The default configuration includes one disabled UDP server, one disabled +//! HTTP server and the enabled API. //! -//! For more information about each service and options you can visit the documentation for the [torrust-tracker-configuration crate](https://docs.rs/torrust-tracker-configuration). +//! For more information about each service and options you can visit the +//! documentation for the [torrust-tracker-configuration crate](https://docs.rs/torrust-tracker-configuration). //! -//! Alternatively to the `config.toml` file you can use one environment variable `TORRUST_TRACKER_CONFIG` to pass the configuration to the tracker: +//! Alternatively to the `tracker.toml` file you can use one environment +//! variable `TORRUST_TRACKER_CONFIG_TOML` to pass the configuration to the tracker: //! //! ```text -//! TORRUST_TRACKER_CONFIG=$(cat config.toml) -//! cargo run +//! TORRUST_TRACKER_CONFIG_TOML=$(cat ./share/default/config/tracker.development.sqlite3.toml) ./target/release/torrust-tracker //! ``` //! -//! In the previous example you are just setting the env var with the contents of the `config.toml` file. +//! In the previous example you are just setting the env var with the contents +//! of the `tracker.toml` file. //! -//! The env var contains the same data as the `config.toml`. It's particularly useful in you are [running the tracker with docker](https://github.com/torrust/torrust-tracker/tree/develop/docker). +//! The env var contains the same data as the `tracker.toml`. It's particularly +//! useful in you are [running the tracker with docker](https://github.com/torrust/torrust-tracker/blob/develop/docs/containers.md). //! -//! > NOTE: The `TORRUST_TRACKER_CONFIG` env var has priority over the `config.toml` file. +//! > NOTICE: The `TORRUST_TRACKER_CONFIG_TOML` env var has priority over the `tracker.toml` file. +//! +//! By default, if you don’t specify any `tracker.toml` file, the application +//! will use `./share/default/config/tracker.development.sqlite3.toml`. +//! +//! > IMPORTANT: Every time you change the configuration you need to restart the +//! > service. //! //! # Usage //! -//! Running the tracker with the default configuration and enabling the UDP and HTTP trackers will expose the services on these URLs: +//! Running the tracker with the default configuration and enabling the UDP and +//! HTTP trackers will expose the services on these URLs: //! //! - REST API: //! - UDP tracker: @@ -191,11 +238,10 @@ //! //! ```toml //! [http_api] -//! enabled = true //! bind_address = "127.0.0.1:1212" -//! ssl_enabled = false -//! ssl_cert_path = "" -//! ssl_key_path = "" +//! +//! [http_api.access_tokens] +//! admin = "MyAccessToken" //! ``` //! //! By default it's enabled on port `1212`. You also need to add access tokens in the configuration: @@ -233,7 +279,7 @@ //! } //! ``` //! -//! Refer to the [`API`](crate::servers::apis) documentation for more information about the [`API`](crate::servers::apis) endpoints. +//! Refer to the [`API`](torrust_axum_rest_tracker_api_server) documentation for more information about the [`API`](torrust_axum_rest_tracker_api_server) endpoints. //! //! ## HTTP tracker //! @@ -251,11 +297,10 @@ //! //! ```toml //! [[http_trackers]] -//! enabled = true //! bind_address = "0.0.0.0:7070" //! ``` //! -//! Refer to the [`HTTP`](crate::servers::http) documentation for more information about the [`HTTP`](crate::servers::http) tracker. +//! Refer to the [`HTTP`](torrust_axum_http_tracker_server) documentation for more information about the [`HTTP`](torrust_axum_http_tracker_server) tracker. //! //! ### Announce //! @@ -313,7 +358,7 @@ //! //! If the tracker is running in `private` or `private_listed` mode you will need to provide a valid authentication key. //! -//! Right now the only way to add new keys is via the REST [`API`](crate::servers::apis). The endpoint `POST /api/vi/key/:duration_in_seconds` +//! Right now the only way to add new keys is via the REST [`API`](torrust_axum_rest_tracker_api_server). The endpoint `POST /api/vi/key/:duration_in_seconds` //! will return an expiring key that will be valid for `duration_in_seconds` seconds. //! //! Using `curl` you can create a 2-minute valid auth key: @@ -333,7 +378,7 @@ //! ``` //! //! You can also use the Torrust Tracker together with the [Torrust Index](https://github.com/torrust/torrust-index). If that's the case, -//! the Index will create the keys by using the tracker [API](crate::servers::apis). +//! the Index will create the keys by using the tracker [API](torrust_axum_rest_tracker_api_server). //! //! ## UDP tracker //! @@ -346,26 +391,18 @@ //! //! ```toml //! [[udp_trackers]] -//! enabled = true //! bind_address = "0.0.0.0:6969" //! ``` //! -//! Refer to the [`UDP`](crate::servers::udp) documentation for more information about the [`UDP`](crate::servers::udp) tracker. +//! Refer to the [`UDP`](torrust_udp_tracker_server) documentation for more information about the [`UDP`](torrust_udp_tracker_server) tracker. //! //! If you want to know more about the UDP tracker protocol: //! //! - [BEP 15. UDP Tracker Protocol for `BitTorrent`](https://www.bittorrent.org/beps/bep_0015.html) //! -//! # Components -//! -//! Torrust Tracker has four main components: -//! -//! - The core [`tracker`](crate::tracker) -//! - The tracker REST [`API`](crate::servers::apis) -//! - The [`UDP`](crate::servers::udp) tracker -//! - The [`HTTP`](crate::servers::http) tracker +//! # Packages //! -//! ![Torrust Tracker Components](https://raw.githubusercontent.com/torrust/torrust-tracker/main/docs/media/torrust-tracker-components.png) +//! ![Torrust Tracker Layers with Main Packages](https://raw.githubusercontent.com/torrust/torrust-tracker/main/docs/media/packages/torrust-tracker-layers-with-packages.png) //! //! ## Core tracker //! @@ -378,7 +415,7 @@ //! - Statistics //! - Persistence //! -//! See [`tracker`](crate::tracker) for more details on the [`tracker`](crate::tracker) module. +//! See [`core`] for more details on the [`core`] module. //! //! ## Tracker API //! @@ -389,7 +426,7 @@ //! - Torrents: to get peers for a torrent //! - Whitelist: to handle the torrent whitelist when the tracker runs on `listed` or `private_listed` mode //! -//! See [`API`](crate::servers::apis) for more details on the REST API. +//! See [`API`](torrust_axum_rest_tracker_api_server) for more details on the REST API. //! //! ## UDP tracker //! @@ -401,13 +438,13 @@ //! - [Wikipedia: UDP tracker](https://en.wikipedia.org/wiki/UDP_tracker) //! - [BEP 15: UDP Tracker Protocol for `BitTorrent`](https://www.bittorrent.org/beps/bep_0015.html) //! -//! See [`UDP`](crate::servers::udp) for more details on the UDP tracker. +//! See [`UDP`](torrust_udp_tracker_server) for more details on the UDP tracker. //! //! ## HTTP tracker //! //! HTTP tracker was the original tracker specification defined on the [BEP 3]((https://www.bittorrent.org/beps/bep_0003.html)). //! -//! See [`HTTP`](crate::servers::http) for more details on the HTTP tracker. +//! See [`HTTP`](torrust_axum_http_tracker_server) for more details on the HTTP tracker. //! //! You can find more information about UDP tracker on: //! @@ -442,11 +479,21 @@ //! //! In addition to the production code documentation you can find a lot of //! examples on the integration and unit tests. + +use torrust_tracker_clock::clock; + pub mod app; pub mod bootstrap; -pub mod servers; -pub mod shared; -pub mod tracker; +pub mod console; +pub mod container; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; -#[macro_use] -extern crate lazy_static; +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/src/main.rs b/src/main.rs index 87c0fc367..7012ecaa7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,20 +1,20 @@ -use log::info; -use torrust_tracker::{app, bootstrap}; +use std::time::Duration; + +use torrust_tracker_lib::app; #[tokio::main] async fn main() { - let (config, tracker) = bootstrap::app::setup(); - - let jobs = app::start(config.clone(), tracker.clone()).await; + let (_app_container, jobs) = app::run().await; - // handle the signals tokio::select! { _ = tokio::signal::ctrl_c() => { - info!("Torrust shutting down.."); + tracing::info!("Torrust tracker shutting down ..."); + + jobs.cancel(); + + jobs.wait_for_all(Duration::from_secs(10)).await; - // Await for all jobs to shutdown - futures::future::join_all(jobs).await; - info!("Torrust successfully shutdown."); + tracing::info!("Torrust tracker successfully shutdown."); } } } diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs deleted file mode 100644 index a4c4642c7..000000000 --- a/src/servers/apis/routes.rs +++ /dev/null @@ -1,28 +0,0 @@ -//! API routes. -//! -//! It loads all the API routes for all API versions and adds the authentication -//! middleware to them. -//! -//! All the API routes have the `/api` prefix and the version number as the -//! first path segment. For example: `/api/v1/torrents`. -use std::sync::Arc; - -use axum::{middleware, Router}; - -use super::v1; -use crate::tracker::Tracker; - -/// Add all API routes to the router. -#[allow(clippy::needless_pass_by_value)] -pub fn router(tracker: Arc) -> Router { - let router = Router::new(); - - let prefix = "/api"; - - let router = v1::routes::add(prefix, router, tracker.clone()); - - router.layer(middleware::from_fn_with_state( - tracker.config.clone(), - v1::middlewares::auth::auth, - )) -} diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs deleted file mode 100644 index 1e24e6655..000000000 --- a/src/servers/apis/server.rs +++ /dev/null @@ -1,296 +0,0 @@ -//! Logic to run the HTTP API server. -//! -//! It contains two main structs: `ApiServer` and `Launcher`, -//! and two main functions: `start` and `start_tls`. -//! -//! The `ApiServer` struct is responsible for: -//! - Starting and stopping the server. -//! - Storing the configuration. -//! -//! `ApiServer` relies on a launcher to start the actual server. -/// -/// 1. `ApiServer::start` -> spawns new asynchronous task. -/// 2. `Launcher::start` -> starts the server on the spawned task. -/// -/// The `Launcher` struct is responsible for: -/// -/// - Knowing how to start the server with graceful shutdown. -/// -/// For the time being the `ApiServer` and `Launcher` are only used in tests -/// where we need to start and stop the server multiple times. In production -/// code and the main application uses the `start` and `start_tls` functions -/// to start the servers directly since we do not need to control the server -/// when it's running. In the future we might need to control the server, -/// for example, to restart it to apply new configuration changes, to remotely -/// shutdown the server, etc. -use std::net::SocketAddr; -use std::str::FromStr; -use std::sync::Arc; - -use axum_server::tls_rustls::RustlsConfig; -use axum_server::Handle; -use futures::future::BoxFuture; -use futures::Future; -use log::info; - -use super::routes::router; -use crate::servers::signals::shutdown_signal; -use crate::tracker::Tracker; - -/// Errors that can occur when starting or stopping the API server. -#[derive(Debug)] -pub enum Error { - Error(String), -} - -/// An alias for the `ApiServer` struct with the `Stopped` state. -#[allow(clippy::module_name_repetitions)] -pub type StoppedApiServer = ApiServer; - -/// An alias for the `ApiServer` struct with the `Running` state. -#[allow(clippy::module_name_repetitions)] -pub type RunningApiServer = ApiServer; - -/// A struct responsible for starting and stopping an API server with a -/// specific configuration and keeping track of the started server. -/// -/// It's a state machine that can be in one of two -/// states: `Stopped` or `Running`. -#[allow(clippy::module_name_repetitions)] -pub struct ApiServer { - pub cfg: torrust_tracker_configuration::HttpApi, - pub state: S, -} - -/// The `Stopped` state of the `ApiServer` struct. -pub struct Stopped; - -/// The `Running` state of the `ApiServer` struct. -pub struct Running { - pub bind_addr: SocketAddr, - task_killer: tokio::sync::oneshot::Sender, - task: tokio::task::JoinHandle<()>, -} - -impl ApiServer { - #[must_use] - pub fn new(cfg: torrust_tracker_configuration::HttpApi) -> Self { - Self { cfg, state: Stopped {} } - } - - /// Starts the API server with the given configuration. - /// - /// # Errors - /// - /// It would return an error if no `SocketAddr` is returned after launching the server. - pub async fn start(self, tracker: Arc) -> Result, Error> { - let (shutdown_sender, shutdown_receiver) = tokio::sync::oneshot::channel::(); - let (addr_sender, addr_receiver) = tokio::sync::oneshot::channel::(); - - let configuration = self.cfg.clone(); - - let task = tokio::spawn(async move { - let (bind_addr, server) = Launcher::start(&configuration, tracker, shutdown_signal(shutdown_receiver)); - - addr_sender.send(bind_addr).expect("Could not return SocketAddr."); - - server.await; - }); - - let bind_address = addr_receiver - .await - .map_err(|_| Error::Error("Could not receive bind_address.".to_string()))?; - - Ok(ApiServer { - cfg: self.cfg, - state: Running { - bind_addr: bind_address, - task_killer: shutdown_sender, - task, - }, - }) - } -} - -impl ApiServer { - /// Stops the API server. - /// - /// # Errors - /// - /// It would return an error if the channel for the task killer signal was closed. - pub async fn stop(self) -> Result, Error> { - self.state - .task_killer - .send(0) - .map_err(|_| Error::Error("Task killer channel was closed.".to_string()))?; - - let _: Result<(), tokio::task::JoinError> = self.state.task.await; - - Ok(ApiServer { - cfg: self.cfg, - state: Stopped {}, - }) - } -} - -/// A struct responsible for starting the API server. -struct Launcher; - -impl Launcher { - /// Starts the API server with graceful shutdown. - /// - /// If TLS is enabled in the configuration, it will start the server with - /// TLS. See [`torrust-tracker-configuration`](torrust_tracker_configuration) - /// for more information about configuration. - pub fn start( - cfg: &torrust_tracker_configuration::HttpApi, - tracker: Arc, - shutdown_signal: F, - ) -> (SocketAddr, BoxFuture<'static, ()>) - where - F: Future + Send + 'static, - { - let addr = SocketAddr::from_str(&cfg.bind_address).expect("bind_address is not a valid SocketAddr."); - let tcp_listener = std::net::TcpListener::bind(addr).expect("Could not bind tcp_listener to address."); - let bind_addr = tcp_listener - .local_addr() - .expect("Could not get local_addr from tcp_listener."); - - if let (true, Some(ssl_cert_path), Some(ssl_key_path)) = (&cfg.ssl_enabled, &cfg.ssl_cert_path, &cfg.ssl_key_path) { - let server = Self::start_tls_with_graceful_shutdown( - tcp_listener, - (ssl_cert_path.to_string(), ssl_key_path.to_string()), - tracker, - shutdown_signal, - ); - - (bind_addr, server) - } else { - let server = Self::start_with_graceful_shutdown(tcp_listener, tracker, shutdown_signal); - - (bind_addr, server) - } - } - - /// Starts the API server with graceful shutdown. - pub fn start_with_graceful_shutdown( - tcp_listener: std::net::TcpListener, - tracker: Arc, - shutdown_signal: F, - ) -> BoxFuture<'static, ()> - where - F: Future + Send + 'static, - { - let app = router(tracker); - - Box::pin(async { - axum::Server::from_tcp(tcp_listener) - .expect("Could not bind to tcp listener.") - .serve(app.into_make_service_with_connect_info::()) - .with_graceful_shutdown(shutdown_signal) - .await - .expect("Axum server crashed."); - }) - } - - /// Starts the API server with graceful shutdown and TLS. - pub fn start_tls_with_graceful_shutdown( - tcp_listener: std::net::TcpListener, - (ssl_cert_path, ssl_key_path): (String, String), - tracker: Arc, - shutdown_signal: F, - ) -> BoxFuture<'static, ()> - where - F: Future + Send + 'static, - { - let app = router(tracker); - - let handle = Handle::new(); - - let cloned_handle = handle.clone(); - - tokio::task::spawn_local(async move { - shutdown_signal.await; - cloned_handle.shutdown(); - }); - - Box::pin(async { - let tls_config = RustlsConfig::from_pem_file(ssl_cert_path, ssl_key_path) - .await - .expect("Could not read tls cert."); - - axum_server::from_tcp_rustls(tcp_listener, tls_config) - .handle(handle) - .serve(app.into_make_service_with_connect_info::()) - .await - .expect("Axum server crashed."); - }) - } -} - -/// Starts the API server with graceful shutdown on the current thread. -pub fn start(socket_addr: SocketAddr, tracker: Arc) -> impl Future> { - let app = router(tracker); - - let server = axum::Server::bind(&socket_addr).serve(app.into_make_service()); - - server.with_graceful_shutdown(async move { - tokio::signal::ctrl_c().await.expect("Failed to listen to shutdown signal."); - info!("Stopping Torrust APIs server on http://{} ...", socket_addr); - }) -} - -/// Starts the API server with graceful shutdown and TLS on the current thread. -pub fn start_tls( - socket_addr: SocketAddr, - ssl_config: RustlsConfig, - tracker: Arc, -) -> impl Future> { - let app = router(tracker); - - let handle = Handle::new(); - let shutdown_handle = handle.clone(); - - tokio::spawn(async move { - tokio::signal::ctrl_c().await.expect("Failed to listen to shutdown signal."); - info!("Stopping Torrust APIs server on https://{} ...", socket_addr); - shutdown_handle.shutdown(); - }); - - axum_server::bind_rustls(socket_addr, ssl_config) - .handle(handle) - .serve(app.into_make_service()) -} - -#[cfg(test)] -mod tests { - use std::sync::Arc; - - use torrust_tracker_configuration::Configuration; - use torrust_tracker_test_helpers::configuration; - - use crate::servers::apis::server::ApiServer; - use crate::tracker; - use crate::tracker::statistics; - - fn tracker_configuration() -> Arc { - Arc::new(configuration::ephemeral()) - } - - #[tokio::test] - async fn it_should_be_able_to_start_from_stopped_state_and_then_stop_again() { - let cfg = tracker_configuration(); - - let tracker = Arc::new(tracker::Tracker::new(cfg.clone(), None, statistics::Repo::new()).unwrap()); - - let stopped_api_server = ApiServer::new(cfg.http_api.clone()); - - let running_api_server_result = stopped_api_server.start(tracker).await; - - assert!(running_api_server_result.is_ok()); - - let running_api_server = running_api_server_result.unwrap(); - - assert!(running_api_server.stop().await.is_ok()); - } -} diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/src/servers/apis/v1/context/auth_key/handlers.rs deleted file mode 100644 index 57d55d4c0..000000000 --- a/src/servers/apis/v1/context/auth_key/handlers.rs +++ /dev/null @@ -1,96 +0,0 @@ -//! API handlers for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context. -use std::str::FromStr; -use std::sync::Arc; -use std::time::Duration; - -use axum::extract::{Path, State}; -use axum::response::Response; -use serde::Deserialize; - -use super::responses::{ - auth_key_response, failed_to_delete_key_response, failed_to_generate_key_response, failed_to_reload_keys_response, -}; -use crate::servers::apis::v1::context::auth_key::resources::AuthKey; -use crate::servers::apis::v1::responses::{invalid_auth_key_param_response, ok_response}; -use crate::tracker::auth::Key; -use crate::tracker::Tracker; - -/// It handles the request to generate a new authentication key. -/// -/// It returns two types of responses: -/// -/// - `200` with an json [`AuthKey`](crate::servers::apis::v1::context::auth_key::resources::AuthKey) -/// resource. If the key was generated successfully. -/// - `500` with serialized error in debug format. If the key couldn't be -/// generated. -/// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#generate-a-new-authentication-key) -/// for more information about this endpoint. -pub async fn generate_auth_key_handler(State(tracker): State>, Path(seconds_valid_or_key): Path) -> Response { - let seconds_valid = seconds_valid_or_key; - match tracker.generate_auth_key(Duration::from_secs(seconds_valid)).await { - Ok(auth_key) => auth_key_response(&AuthKey::from(auth_key)), - Err(e) => failed_to_generate_key_response(e), - } -} - -/// A container for the `key` parameter extracted from the URL PATH. -/// -/// It does not perform any validation, it just stores the value. -/// -/// In the current API version, the `key` parameter can be either a valid key -/// like `xqD6NWH9TcKrOCwDmqcdH5hF5RrbL0A6` or the number of seconds the -/// key will be valid, for example two minutes `120`. -/// -/// For example, the `key` is used in the following requests: -/// -/// - `POST /api/v1/key/120`. It will generate a new key valid for two minutes. -/// - `DELETE /api/v1/key/xqD6NWH9TcKrOCwDmqcdH5hF5RrbL0A6`. It will delete the -/// key `xqD6NWH9TcKrOCwDmqcdH5hF5RrbL0A6`. -/// -/// > **NOTICE**: this may change in the future, in the [API v2](https://github.com/torrust/torrust-tracker/issues/144). -#[derive(Deserialize)] -pub struct KeyParam(String); - -/// It handles the request to delete an authentication key. -/// -/// It returns two types of responses: -/// -/// - `200` with an json [`ActionStatus::Ok`](crate::servers::apis::v1::responses::ActionStatus::Ok) -/// response. If the key was deleted successfully. -/// - `500` with serialized error in debug format. If the key couldn't be -/// deleted. -/// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#delete-an-authentication-key) -/// for more information about this endpoint. -pub async fn delete_auth_key_handler( - State(tracker): State>, - Path(seconds_valid_or_key): Path, -) -> Response { - match Key::from_str(&seconds_valid_or_key.0) { - Err(_) => invalid_auth_key_param_response(&seconds_valid_or_key.0), - Ok(key) => match tracker.remove_auth_key(&key).await { - Ok(_) => ok_response(), - Err(e) => failed_to_delete_key_response(e), - }, - } -} - -/// It handles the request to reload the authentication keys from the database -/// into memory. -/// -/// It returns two types of responses: -/// -/// - `200` with an json [`ActionStatus::Ok`](crate::servers::apis::v1::responses::ActionStatus::Ok) -/// response. If the keys were successfully reloaded. -/// - `500` with serialized error in debug format. If the they couldn't be -/// reloaded. -/// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#reload-authentication-keys) -/// for more information about this endpoint. -pub async fn reload_keys_handler(State(tracker): State>) -> Response { - match tracker.load_keys_from_database().await { - Ok(_) => ok_response(), - Err(e) => failed_to_reload_keys_response(e), - } -} diff --git a/src/servers/apis/v1/context/auth_key/resources.rs b/src/servers/apis/v1/context/auth_key/resources.rs deleted file mode 100644 index 3eeafbda0..000000000 --- a/src/servers/apis/v1/context/auth_key/resources.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! API resources for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context. -use std::convert::From; - -use serde::{Deserialize, Serialize}; - -use crate::shared::clock::convert_from_iso_8601_to_timestamp; -use crate::tracker::auth::{self, Key}; - -/// A resource that represents an authentication key. -#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] -pub struct AuthKey { - /// The authentication key. - pub key: String, - /// The timestamp when the key will expire. - #[deprecated(since = "3.0.0", note = "please use `expiry_time` instead")] - pub valid_until: u64, // todo: remove when the torrust-index-backend starts using the `expiry_time` attribute. - /// The ISO 8601 timestamp when the key will expire. - pub expiry_time: String, -} - -impl From for auth::ExpiringKey { - fn from(auth_key_resource: AuthKey) -> Self { - auth::ExpiringKey { - key: auth_key_resource.key.parse::().unwrap(), - valid_until: convert_from_iso_8601_to_timestamp(&auth_key_resource.expiry_time), - } - } -} - -impl From for AuthKey { - fn from(auth_key: auth::ExpiringKey) -> Self { - AuthKey { - key: auth_key.key.to_string(), - valid_until: auth_key.valid_until.as_secs(), - expiry_time: auth_key.expiry_time().to_string(), - } - } -} - -#[cfg(test)] -mod tests { - use std::time::Duration; - - use super::AuthKey; - use crate::shared::clock::{Current, TimeNow}; - use crate::tracker::auth::{self, Key}; - - struct TestTime { - pub timestamp: u64, - pub iso_8601_v1: String, - pub iso_8601_v2: String, - } - - fn one_hour_after_unix_epoch() -> TestTime { - let timestamp = 60_u64; - let iso_8601_v1 = "1970-01-01T00:01:00.000Z".to_string(); - let iso_8601_v2 = "1970-01-01 00:01:00 UTC".to_string(); - TestTime { - timestamp, - iso_8601_v1, - iso_8601_v2, - } - } - - #[test] - fn it_should_be_convertible_into_an_auth_key() { - let auth_key_resource = AuthKey { - key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".to_string(), // cspell:disable-line - valid_until: one_hour_after_unix_epoch().timestamp, - expiry_time: one_hour_after_unix_epoch().iso_8601_v1, - }; - - assert_eq!( - auth::ExpiringKey::from(auth_key_resource), - auth::ExpiringKey { - key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".parse::().unwrap(), // cspell:disable-line - valid_until: Current::add(&Duration::new(one_hour_after_unix_epoch().timestamp, 0)).unwrap() - } - ); - } - - #[test] - fn it_should_be_convertible_from_an_auth_key() { - let auth_key = auth::ExpiringKey { - key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".parse::().unwrap(), // cspell:disable-line - valid_until: Current::add(&Duration::new(one_hour_after_unix_epoch().timestamp, 0)).unwrap(), - }; - - assert_eq!( - AuthKey::from(auth_key), - AuthKey { - key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".to_string(), // cspell:disable-line - valid_until: one_hour_after_unix_epoch().timestamp, - expiry_time: one_hour_after_unix_epoch().iso_8601_v2, - } - ); - } - - #[test] - fn it_should_be_convertible_into_json() { - assert_eq!( - serde_json::to_string(&AuthKey { - key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".to_string(), // cspell:disable-line - valid_until: one_hour_after_unix_epoch().timestamp, - expiry_time: one_hour_after_unix_epoch().iso_8601_v1, - }) - .unwrap(), - "{\"key\":\"IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM\",\"valid_until\":60,\"expiry_time\":\"1970-01-01T00:01:00.000Z\"}" // cspell:disable-line - ); - } -} diff --git a/src/servers/apis/v1/context/auth_key/routes.rs b/src/servers/apis/v1/context/auth_key/routes.rs deleted file mode 100644 index 76c634e21..000000000 --- a/src/servers/apis/v1/context/auth_key/routes.rs +++ /dev/null @@ -1,34 +0,0 @@ -//! API routes for the [`auth_key`](crate::servers::apis::v1::context::auth_key) -//! API context. -//! -//! - `POST /key/:seconds_valid` -//! - `DELETE /key/:key` -//! - `GET /keys/reload` -//! -//! Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key). -use std::sync::Arc; - -use axum::routing::{get, post}; -use axum::Router; - -use super::handlers::{delete_auth_key_handler, generate_auth_key_handler, reload_keys_handler}; -use crate::tracker::Tracker; - -/// It adds the routes to the router for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context. -pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { - // Keys - router - .route( - // code-review: Axum does not allow two routes with the same path but different path variable name. - // In the new major API version, `seconds_valid` should be a POST form field so that we will have two paths: - // POST /key - // DELETE /key/:key - &format!("{prefix}/key/:seconds_valid_or_key"), - post(generate_auth_key_handler) - .with_state(tracker.clone()) - .delete(delete_auth_key_handler) - .with_state(tracker.clone()), - ) - // Keys command - .route(&format!("{prefix}/keys/reload"), get(reload_keys_handler).with_state(tracker)) -} diff --git a/src/servers/apis/v1/context/stats/handlers.rs b/src/servers/apis/v1/context/stats/handlers.rs deleted file mode 100644 index dfb983f77..000000000 --- a/src/servers/apis/v1/context/stats/handlers.rs +++ /dev/null @@ -1,21 +0,0 @@ -//! API handlers for the [`stats`](crate::servers::apis::v1::context::stats) -//! API context. -use std::sync::Arc; - -use axum::extract::State; -use axum::response::Json; - -use super::resources::Stats; -use super::responses::stats_response; -use crate::tracker::services::statistics::get_metrics; -use crate::tracker::Tracker; - -/// It handles the request to get the tracker statistics. -/// -/// It returns a `200` response with a json [`Stats`](crate::servers::apis::v1::context::stats::resources::Stats) -/// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::stats#get-tracker-statistics) -/// for more information about this endpoint. -pub async fn get_stats_handler(State(tracker): State>) -> Json { - stats_response(get_metrics(tracker.clone()).await) -} diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs deleted file mode 100644 index 355a1e448..000000000 --- a/src/servers/apis/v1/context/stats/resources.rs +++ /dev/null @@ -1,124 +0,0 @@ -//! API resources for the [`stats`](crate::servers::apis::v1::context::stats) -//! API context. -use serde::{Deserialize, Serialize}; - -use crate::tracker::services::statistics::TrackerMetrics; - -/// It contains all the statistics generated by the tracker. -#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] -pub struct Stats { - // Torrent metrics - /// Total number of torrents. - pub torrents: u64, - /// Total number of seeders for all torrents. - pub seeders: u64, - /// Total number of peers that have ever completed downloading for all torrents. - pub completed: u64, - /// Total number of leechers for all torrents. - pub leechers: u64, - - // Protocol metrics - /// Total number of TCP (HTTP tracker) connections from IPv4 peers. - /// Since the HTTP tracker spec does not require a handshake, this metric - /// increases for every HTTP request. - pub tcp4_connections_handled: u64, - /// Total number of TCP (HTTP tracker) `announce` requests from IPv4 peers. - pub tcp4_announces_handled: u64, - /// Total number of TCP (HTTP tracker) `scrape` requests from IPv4 peers. - pub tcp4_scrapes_handled: u64, - /// Total number of TCP (HTTP tracker) connections from IPv6 peers. - pub tcp6_connections_handled: u64, - /// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers. - pub tcp6_announces_handled: u64, - /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. - pub tcp6_scrapes_handled: u64, - /// Total number of UDP (UDP tracker) connections from IPv4 peers. - pub udp4_connections_handled: u64, - /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. - pub udp4_announces_handled: u64, - /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. - pub udp4_scrapes_handled: u64, - /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. - pub udp6_connections_handled: u64, - /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. - pub udp6_announces_handled: u64, - /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. - pub udp6_scrapes_handled: u64, -} - -impl From for Stats { - fn from(metrics: TrackerMetrics) -> Self { - Self { - torrents: metrics.torrents_metrics.torrents, - seeders: metrics.torrents_metrics.seeders, - completed: metrics.torrents_metrics.completed, - leechers: metrics.torrents_metrics.leechers, - tcp4_connections_handled: metrics.protocol_metrics.tcp4_connections_handled, - tcp4_announces_handled: metrics.protocol_metrics.tcp4_announces_handled, - tcp4_scrapes_handled: metrics.protocol_metrics.tcp4_scrapes_handled, - tcp6_connections_handled: metrics.protocol_metrics.tcp6_connections_handled, - tcp6_announces_handled: metrics.protocol_metrics.tcp6_announces_handled, - tcp6_scrapes_handled: metrics.protocol_metrics.tcp6_scrapes_handled, - udp4_connections_handled: metrics.protocol_metrics.udp4_connections_handled, - udp4_announces_handled: metrics.protocol_metrics.udp4_announces_handled, - udp4_scrapes_handled: metrics.protocol_metrics.udp4_scrapes_handled, - udp6_connections_handled: metrics.protocol_metrics.udp6_connections_handled, - udp6_announces_handled: metrics.protocol_metrics.udp6_announces_handled, - udp6_scrapes_handled: metrics.protocol_metrics.udp6_scrapes_handled, - } - } -} - -#[cfg(test)] -mod tests { - use super::Stats; - use crate::tracker::services::statistics::TrackerMetrics; - use crate::tracker::statistics::Metrics; - use crate::tracker::TorrentsMetrics; - - #[test] - fn stats_resource_should_be_converted_from_tracker_metrics() { - assert_eq!( - Stats::from(TrackerMetrics { - torrents_metrics: TorrentsMetrics { - seeders: 1, - completed: 2, - leechers: 3, - torrents: 4 - }, - protocol_metrics: Metrics { - tcp4_connections_handled: 5, - tcp4_announces_handled: 6, - tcp4_scrapes_handled: 7, - tcp6_connections_handled: 8, - tcp6_announces_handled: 9, - tcp6_scrapes_handled: 10, - udp4_connections_handled: 11, - udp4_announces_handled: 12, - udp4_scrapes_handled: 13, - udp6_connections_handled: 14, - udp6_announces_handled: 15, - udp6_scrapes_handled: 16 - } - }), - Stats { - torrents: 4, - seeders: 1, - completed: 2, - leechers: 3, - tcp4_connections_handled: 5, - tcp4_announces_handled: 6, - tcp4_scrapes_handled: 7, - tcp6_connections_handled: 8, - tcp6_announces_handled: 9, - tcp6_scrapes_handled: 10, - udp4_connections_handled: 11, - udp4_announces_handled: 12, - udp4_scrapes_handled: 13, - udp6_connections_handled: 14, - udp6_announces_handled: 15, - udp6_scrapes_handled: 16 - } - ); - } -} diff --git a/src/servers/apis/v1/context/stats/responses.rs b/src/servers/apis/v1/context/stats/responses.rs deleted file mode 100644 index a4dad77e4..000000000 --- a/src/servers/apis/v1/context/stats/responses.rs +++ /dev/null @@ -1,11 +0,0 @@ -//! API responses for the [`stats`](crate::servers::apis::v1::context::stats) -//! API context. -use axum::response::Json; - -use super::resources::Stats; -use crate::tracker::services::statistics::TrackerMetrics; - -/// `200` response that contains the [`Stats`](crate::servers::apis::v1::context::stats::resources::Stats) resource as json. -pub fn stats_response(tracker_metrics: TrackerMetrics) -> Json { - Json(Stats::from(tracker_metrics)) -} diff --git a/src/servers/apis/v1/context/stats/routes.rs b/src/servers/apis/v1/context/stats/routes.rs deleted file mode 100644 index 9198562dd..000000000 --- a/src/servers/apis/v1/context/stats/routes.rs +++ /dev/null @@ -1,17 +0,0 @@ -//! API routes for the [`stats`](crate::servers::apis::v1::context::stats) API context. -//! -//! - `GET /stats` -//! -//! Refer to the [API endpoint documentation](crate::servers::apis::v1::context::stats). -use std::sync::Arc; - -use axum::routing::get; -use axum::Router; - -use super::handlers::get_stats_handler; -use crate::tracker::Tracker; - -/// It adds the routes to the router for the [`stats`](crate::servers::apis::v1::context::stats) API context. -pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { - router.route(&format!("{prefix}/stats"), get(get_stats_handler).with_state(tracker)) -} diff --git a/src/servers/apis/v1/context/torrent/handlers.rs b/src/servers/apis/v1/context/torrent/handlers.rs deleted file mode 100644 index 002d4356e..000000000 --- a/src/servers/apis/v1/context/torrent/handlers.rs +++ /dev/null @@ -1,86 +0,0 @@ -//! API handlers for the [`torrent`](crate::servers::apis::v1::context::torrent) -//! API context. -use std::fmt; -use std::str::FromStr; -use std::sync::Arc; - -use axum::extract::{Path, Query, State}; -use axum::response::{IntoResponse, Json, Response}; -use log::debug; -use serde::{de, Deserialize, Deserializer}; - -use super::resources::torrent::ListItem; -use super::responses::{torrent_info_response, torrent_list_response, torrent_not_known_response}; -use crate::servers::apis::v1::responses::invalid_info_hash_param_response; -use crate::servers::apis::InfoHashParam; -use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::services::torrent::{get_torrent_info, get_torrents, Pagination}; -use crate::tracker::Tracker; - -/// It handles the request to get the torrent data. -/// -/// It returns: -/// -/// - `200` response with a json [`Torrent`](crate::servers::apis::v1::context::torrent::resources::torrent::Torrent). -/// - `500` with serialized error in debug format if the torrent is not known. -/// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::torrent#get-a-torrent) -/// for more information about this endpoint. -pub async fn get_torrent_handler(State(tracker): State>, Path(info_hash): Path) -> Response { - match InfoHash::from_str(&info_hash.0) { - Err(_) => invalid_info_hash_param_response(&info_hash.0), - Ok(info_hash) => match get_torrent_info(tracker.clone(), &info_hash).await { - Some(info) => torrent_info_response(info).into_response(), - None => torrent_not_known_response(), - }, - } -} - -/// A container for the optional URL query pagination parameters: -/// `offset` and `limit`. -#[derive(Deserialize, Debug)] -pub struct PaginationParams { - /// The offset of the first page to return. Starts at 0. - #[serde(default, deserialize_with = "empty_string_as_none")] - pub offset: Option, - /// The maximum number of items to return per page - #[serde(default, deserialize_with = "empty_string_as_none")] - pub limit: Option, -} - -/// It handles the request to get a list of torrents. -/// -/// It returns a `200` response with a json array with -/// [`ListItem`](crate::servers::apis::v1::context::torrent::resources::torrent::ListItem) -/// resources. -/// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::torrent#list-torrents) -/// for more information about this endpoint. -pub async fn get_torrents_handler( - State(tracker): State>, - pagination: Query, -) -> Json> { - debug!("pagination: {:?}", pagination); - - torrent_list_response( - &get_torrents( - tracker.clone(), - &Pagination::new_with_options(pagination.0.offset, pagination.0.limit), - ) - .await, - ) -} - -/// Serde deserialization decorator to map empty Strings to None, -fn empty_string_as_none<'de, D, T>(de: D) -> Result, D::Error> -where - D: Deserializer<'de>, - T: FromStr, - T::Err: fmt::Display, -{ - let opt = Option::::deserialize(de)?; - match opt.as_deref() { - None | Some("") => Ok(None), - Some(s) => FromStr::from_str(s).map_err(de::Error::custom).map(Some), - } -} diff --git a/src/servers/apis/v1/context/torrent/resources/mod.rs b/src/servers/apis/v1/context/torrent/resources/mod.rs deleted file mode 100644 index a6dbff726..000000000 --- a/src/servers/apis/v1/context/torrent/resources/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -//! API resources for the [`torrent`](crate::servers::apis::v1::context::torrent) -//! API context. -pub mod peer; -pub mod torrent; diff --git a/src/servers/apis/v1/context/torrent/routes.rs b/src/servers/apis/v1/context/torrent/routes.rs deleted file mode 100644 index 18295f2a2..000000000 --- a/src/servers/apis/v1/context/torrent/routes.rs +++ /dev/null @@ -1,24 +0,0 @@ -//! API routes for the [`torrent`](crate::servers::apis::v1::context::torrent) API context. -//! -//! - `GET /torrent/:info_hash` -//! - `GET /torrents` -//! -//! Refer to the [API endpoint documentation](crate::servers::apis::v1::context::torrent). -use std::sync::Arc; - -use axum::routing::get; -use axum::Router; - -use super::handlers::{get_torrent_handler, get_torrents_handler}; -use crate::tracker::Tracker; - -/// It adds the routes to the router for the [`torrent`](crate::servers::apis::v1::context::torrent) API context. -pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { - // Torrents - router - .route( - &format!("{prefix}/torrent/:info_hash"), - get(get_torrent_handler).with_state(tracker.clone()), - ) - .route(&format!("{prefix}/torrents"), get(get_torrents_handler).with_state(tracker)) -} diff --git a/src/servers/apis/v1/context/whitelist/routes.rs b/src/servers/apis/v1/context/whitelist/routes.rs deleted file mode 100644 index 65d511341..000000000 --- a/src/servers/apis/v1/context/whitelist/routes.rs +++ /dev/null @@ -1,32 +0,0 @@ -//! API routes for the [`whitelist`](crate::servers::apis::v1::context::whitelist) API context. -//! -//! - `POST /whitelist/:info_hash` -//! - `DELETE /whitelist/:info_hash` -//! - `GET /whitelist/reload` -//! -//! Refer to the [API endpoint documentation](crate::servers::apis::v1::context::torrent). -use std::sync::Arc; - -use axum::routing::{delete, get, post}; -use axum::Router; - -use super::handlers::{add_torrent_to_whitelist_handler, reload_whitelist_handler, remove_torrent_from_whitelist_handler}; -use crate::tracker::Tracker; - -/// It adds the routes to the router for the [`whitelist`](crate::servers::apis::v1::context::whitelist) API context. -pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { - let prefix = format!("{prefix}/whitelist"); - - router - // Whitelisted torrents - .route( - &format!("{prefix}/:info_hash"), - post(add_torrent_to_whitelist_handler).with_state(tracker.clone()), - ) - .route( - &format!("{prefix}/:info_hash"), - delete(remove_torrent_from_whitelist_handler).with_state(tracker.clone()), - ) - // Whitelist commands - .route(&format!("{prefix}/reload"), get(reload_whitelist_handler).with_state(tracker)) -} diff --git a/src/servers/apis/v1/middlewares/auth.rs b/src/servers/apis/v1/middlewares/auth.rs deleted file mode 100644 index 608a1b7d2..000000000 --- a/src/servers/apis/v1/middlewares/auth.rs +++ /dev/null @@ -1,91 +0,0 @@ -//! Authentication middleware for the API. -//! -//! It uses a "token" GET param to authenticate the user. URLs must be of the -//! form: -//! -//! `http://:/api/v1/?token=`. -//! -//! > **NOTICE**: the token can be at any position in the URL, not just at the -//! > beginning or at the end. -//! -//! The token must be one of the `access_tokens` in the tracker -//! [HTTP API configuration](torrust_tracker_configuration::HttpApi). -//! -//! The configuration file `config.toml` contains a list of tokens: -//! -//! ```toml -//! [http_api.access_tokens] -//! admin = "MyAccessToken" -//! ``` -//! -//! All the tokes have the same permissions, so it is not possible to have -//! different permissions for different tokens. The label is only used to -//! identify the token. -use std::sync::Arc; - -use axum::extract::{Query, State}; -use axum::http::Request; -use axum::middleware::Next; -use axum::response::{IntoResponse, Response}; -use serde::Deserialize; -use torrust_tracker_configuration::{Configuration, HttpApi}; - -use crate::servers::apis::v1::responses::unhandled_rejection_response; - -/// Container for the `token` extracted from the query params. -#[derive(Deserialize, Debug)] -pub struct QueryParams { - pub token: Option, -} - -/// Middleware for authentication using a "token" GET param. -/// The token must be one of the tokens in the tracker [HTTP API configuration](torrust_tracker_configuration::HttpApi). -pub async fn auth( - State(config): State>, - Query(params): Query, - request: Request, - next: Next, -) -> Response -where - B: Send, -{ - let Some(token) = params.token else { return AuthError::Unauthorized.into_response() }; - - if !authenticate(&token, &config.http_api) { - return AuthError::TokenNotValid.into_response(); - } - - next.run(request).await -} - -enum AuthError { - /// Missing token for authentication. - Unauthorized, - /// Token was provided but it is not valid. - TokenNotValid, -} - -impl IntoResponse for AuthError { - fn into_response(self) -> Response { - match self { - AuthError::Unauthorized => unauthorized_response(), - AuthError::TokenNotValid => token_not_valid_response(), - } - } -} - -fn authenticate(token: &str, http_api_config: &HttpApi) -> bool { - http_api_config.contains_token(token) -} - -/// `500` error response returned when the token is missing. -#[must_use] -pub fn unauthorized_response() -> Response { - unhandled_rejection_response("unauthorized".to_string()) -} - -/// `500` error response when the provided token is not valid. -#[must_use] -pub fn token_not_valid_response() -> Response { - unhandled_rejection_response("token not valid".to_string()) -} diff --git a/src/servers/apis/v1/routes.rs b/src/servers/apis/v1/routes.rs deleted file mode 100644 index 74778ca14..000000000 --- a/src/servers/apis/v1/routes.rs +++ /dev/null @@ -1,16 +0,0 @@ -//! Route initialization for the v1 API. -use std::sync::Arc; - -use axum::Router; - -use super::context::{auth_key, stats, torrent, whitelist}; -use crate::tracker::Tracker; - -/// Add the routes for the v1 API. -pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { - let v1_prefix = format!("{prefix}/v1"); - let router = auth_key::routes::add(&v1_prefix, router, tracker.clone()); - let router = stats::routes::add(&v1_prefix, router, tracker.clone()); - let router = whitelist::routes::add(&v1_prefix, router, tracker.clone()); - torrent::routes::add(&v1_prefix, router, tracker) -} diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs deleted file mode 100644 index 6a46b81df..000000000 --- a/src/servers/http/server.rs +++ /dev/null @@ -1,160 +0,0 @@ -//! Module to handle the HTTP server instances. -use std::future::Future; -use std::net::SocketAddr; -use std::sync::Arc; - -use futures::future::BoxFuture; - -use crate::servers::signals::shutdown_signal; -use crate::tracker::Tracker; - -/// Trait to be implemented by a HTTP server launcher for the tracker. -/// -/// A launcher is responsible for starting the server and returning the -/// `SocketAddr` it is bound to. -#[allow(clippy::module_name_repetitions)] -pub trait HttpServerLauncher: Sync + Send { - fn new() -> Self; - - fn start_with_graceful_shutdown( - &self, - cfg: torrust_tracker_configuration::HttpTracker, - tracker: Arc, - shutdown_signal: F, - ) -> (SocketAddr, BoxFuture<'static, ()>) - where - F: Future + Send + 'static; -} - -/// Error that can occur when starting or stopping the HTTP server. -/// -/// Some errors triggered while starting the server are: -/// -/// - The spawned server cannot send its `SocketAddr` back to the main thread. -/// - The launcher cannot receive the `SocketAddr` from the spawned server. -/// -/// Some errors triggered while stopping the server are: -/// -/// - The channel to send the shutdown signal to the server is closed. -/// - The task to shutdown the server on the spawned server failed to execute to -/// completion. -#[derive(Debug)] -pub enum Error { - /// Any kind of error starting or stopping the server. - Error(String), // todo: refactor to use thiserror and add more variants for specific errors. -} - -/// A HTTP server instance controller with no HTTP instance running. -#[allow(clippy::module_name_repetitions)] -pub type StoppedHttpServer = HttpServer>; - -/// A HTTP server instance controller with a running HTTP instance. -#[allow(clippy::module_name_repetitions)] -pub type RunningHttpServer = HttpServer>; - -/// A HTTP server instance controller. -/// -/// It's responsible for: -/// -/// - Keeping the initial configuration of the server. -/// - Starting and stopping the server. -/// - Keeping the state of the server: `running` or `stopped`. -/// -/// It's an state machine. Configurations cannot be changed. This struct -/// represents concrete configuration and state. It allows to start and stop the -/// server but always keeping the same configuration. -/// -/// > **NOTICE**: if the configurations changes after running the server it will -/// reset to the initial value after stopping the server. This struct is not -/// intended to persist configurations between runs. -#[allow(clippy::module_name_repetitions)] -pub struct HttpServer { - /// The configuration of the server that will be used every time the server - /// is started. - pub cfg: torrust_tracker_configuration::HttpTracker, - /// The state of the server: `running` or `stopped`. - pub state: S, -} - -/// A stopped HTTP server state. -pub struct Stopped { - launcher: I, -} - -/// A running HTTP server state. -pub struct Running { - /// The address where the server is bound. - pub bind_addr: SocketAddr, - task_killer: tokio::sync::oneshot::Sender, - task: tokio::task::JoinHandle, -} - -impl HttpServer> { - /// It creates a new `HttpServer` controller in `stopped` state. - pub fn new(cfg: torrust_tracker_configuration::HttpTracker, launcher: I) -> Self { - Self { - cfg, - state: Stopped { launcher }, - } - } - - /// It starts the server and returns a `HttpServer` controller in `running` - /// state. - /// - /// # Errors - /// - /// It would return an error if no `SocketAddr` is returned after launching the server. - pub async fn start(self, tracker: Arc) -> Result>, Error> { - let (shutdown_sender, shutdown_receiver) = tokio::sync::oneshot::channel::(); - let (addr_sender, addr_receiver) = tokio::sync::oneshot::channel::(); - - let configuration = self.cfg.clone(); - let launcher = self.state.launcher; - - let task = tokio::spawn(async move { - let (bind_addr, server) = - launcher.start_with_graceful_shutdown(configuration, tracker, shutdown_signal(shutdown_receiver)); - - addr_sender.send(bind_addr).expect("Could not return SocketAddr."); - - server.await; - - launcher - }); - - let bind_address = addr_receiver - .await - .map_err(|_| Error::Error("Could not receive bind_address.".to_string()))?; - - Ok(HttpServer { - cfg: self.cfg, - state: Running { - bind_addr: bind_address, - task_killer: shutdown_sender, - task, - }, - }) - } -} - -impl HttpServer> { - /// It stops the server and returns a `HttpServer` controller in `stopped` - /// state. - /// - /// # Errors - /// - /// It would return an error if the channel for the task killer signal was closed. - pub async fn stop(self) -> Result>, Error> { - self.state - .task_killer - .send(0) - .map_err(|_| Error::Error("Task killer channel was closed.".to_string()))?; - - let launcher = self.state.task.await.map_err(|e| Error::Error(e.to_string()))?; - - Ok(HttpServer { - cfg: self.cfg, - state: Stopped { launcher }, - }) - } -} diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs deleted file mode 100644 index 5b26b3758..000000000 --- a/src/servers/http/v1/handlers/announce.rs +++ /dev/null @@ -1,339 +0,0 @@ -//! Axum [`handlers`](axum#handlers) for the `announce` requests. -//! -//! Refer to [HTTP server](crate::servers::http) for more information about the -//! `announce` request. -//! -//! The handlers perform the authentication and authorization of the request, -//! and resolve the client IP address. -use std::net::{IpAddr, SocketAddr}; -use std::panic::Location; -use std::sync::Arc; - -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; -use axum::extract::State; -use axum::response::{IntoResponse, Response}; -use log::debug; - -use crate::servers::http::v1::extractors::announce_request::ExtractRequest; -use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; -use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; -use crate::servers::http::v1::handlers::common::auth; -use crate::servers::http::v1::requests::announce::{Announce, Compact, Event}; -use crate::servers::http::v1::responses::{self, announce}; -use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; -use crate::servers::http::v1::services::{self, peer_ip_resolver}; -use crate::shared::clock::{Current, Time}; -use crate::tracker::auth::Key; -use crate::tracker::peer::Peer; -use crate::tracker::{AnnounceData, Tracker}; - -/// It handles the `announce` request when the HTTP tracker does not require -/// authentication (no PATH `key` parameter required). -#[allow(clippy::unused_async)] -pub async fn handle_without_key( - State(tracker): State>, - ExtractRequest(announce_request): ExtractRequest, - ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, -) -> Response { - debug!("http announce request: {:#?}", announce_request); - - handle(&tracker, &announce_request, &client_ip_sources, None).await -} - -/// It handles the `announce` request when the HTTP tracker requires -/// authentication (PATH `key` parameter required). -#[allow(clippy::unused_async)] -pub async fn handle_with_key( - State(tracker): State>, - ExtractRequest(announce_request): ExtractRequest, - ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, - ExtractKey(key): ExtractKey, -) -> Response { - debug!("http announce request: {:#?}", announce_request); - - handle(&tracker, &announce_request, &client_ip_sources, Some(key)).await -} - -/// It handles the `announce` request. -/// -/// Internal implementation that handles both the `authenticated` and -/// `unauthenticated` modes. -async fn handle( - tracker: &Arc, - announce_request: &Announce, - client_ip_sources: &ClientIpSources, - maybe_key: Option, -) -> Response { - let announce_data = match handle_announce(tracker, announce_request, client_ip_sources, maybe_key).await { - Ok(announce_data) => announce_data, - Err(error) => return error.into_response(), - }; - build_response(announce_request, announce_data) -} - -/* code-review: authentication, authorization and peer IP resolution could be moved - from the handler (Axum) layer into the app layer `services::announce::invoke`. - That would make the handler even simpler and the code more reusable and decoupled from Axum. - See https://github.com/torrust/torrust-tracker/discussions/240. -*/ - -async fn handle_announce( - tracker: &Arc, - announce_request: &Announce, - client_ip_sources: &ClientIpSources, - maybe_key: Option, -) -> Result { - // Authentication - if tracker.requires_authentication() { - match maybe_key { - Some(key) => match tracker.authenticate(&key).await { - Ok(_) => (), - Err(error) => return Err(responses::error::Error::from(error)), - }, - None => { - return Err(responses::error::Error::from(auth::Error::MissingAuthKey { - location: Location::caller(), - })) - } - } - } - - // Authorization - match tracker.authorize(&announce_request.info_hash).await { - Ok(_) => (), - Err(error) => return Err(responses::error::Error::from(error)), - } - - let peer_ip = match peer_ip_resolver::invoke(tracker.config.on_reverse_proxy, client_ip_sources) { - Ok(peer_ip) => peer_ip, - Err(error) => return Err(responses::error::Error::from(error)), - }; - - let mut peer = peer_from_request(announce_request, &peer_ip); - - let announce_data = services::announce::invoke(tracker.clone(), announce_request.info_hash, &mut peer).await; - - Ok(announce_data) -} - -fn build_response(announce_request: &Announce, announce_data: AnnounceData) -> Response { - match &announce_request.compact { - Some(compact) => match compact { - Compact::Accepted => announce::Compact::from(announce_data).into_response(), - Compact::NotAccepted => announce::NonCompact::from(announce_data).into_response(), - }, - // Default response format non compact - None => announce::NonCompact::from(announce_data).into_response(), - } -} - -/// It builds a `Peer` from the announce request. -/// -/// It ignores the peer address in the announce request params. -#[must_use] -fn peer_from_request(announce_request: &Announce, peer_ip: &IpAddr) -> Peer { - Peer { - peer_id: announce_request.peer_id, - peer_addr: SocketAddr::new(*peer_ip, announce_request.port), - updated: Current::now(), - uploaded: NumberOfBytes(announce_request.uploaded.unwrap_or(0)), - downloaded: NumberOfBytes(announce_request.downloaded.unwrap_or(0)), - left: NumberOfBytes(announce_request.left.unwrap_or(0)), - event: map_to_aquatic_event(&announce_request.event), - } -} - -fn map_to_aquatic_event(event: &Option) -> AnnounceEvent { - match event { - Some(event) => match &event { - Event::Started => aquatic_udp_protocol::AnnounceEvent::Started, - Event::Stopped => aquatic_udp_protocol::AnnounceEvent::Stopped, - Event::Completed => aquatic_udp_protocol::AnnounceEvent::Completed, - }, - None => aquatic_udp_protocol::AnnounceEvent::None, - } -} - -#[cfg(test)] -mod tests { - - use torrust_tracker_test_helpers::configuration; - - use crate::servers::http::v1::requests::announce::Announce; - use crate::servers::http::v1::responses; - use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::tracker::services::tracker_factory; - use crate::tracker::{peer, Tracker}; - - fn private_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_private().into()) - } - - fn whitelisted_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_whitelisted().into()) - } - - fn tracker_on_reverse_proxy() -> Tracker { - tracker_factory(configuration::ephemeral_with_reverse_proxy().into()) - } - - fn tracker_not_on_reverse_proxy() -> Tracker { - tracker_factory(configuration::ephemeral_without_reverse_proxy().into()) - } - - fn sample_announce_request() -> Announce { - Announce { - info_hash: "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), - peer_id: "-qB00000000000000001".parse::().unwrap(), - port: 17548, - downloaded: None, - uploaded: None, - left: None, - event: None, - compact: None, - } - } - - fn sample_client_ip_sources() -> ClientIpSources { - ClientIpSources { - right_most_x_forwarded_for: None, - connection_info_ip: None, - } - } - - fn assert_error_response(error: &responses::error::Error, error_message: &str) { - assert!( - error.failure_reason.contains(error_message), - "Error response does not contain message: '{error_message}'. Error: {error:?}" - ); - } - - mod with_tracker_in_private_mode { - - use std::str::FromStr; - use std::sync::Arc; - - use super::{private_tracker, sample_announce_request, sample_client_ip_sources}; - use crate::servers::http::v1::handlers::announce::handle_announce; - use crate::servers::http::v1::handlers::announce::tests::assert_error_response; - use crate::tracker::auth; - - #[tokio::test] - async fn it_should_fail_when_the_authentication_key_is_missing() { - let tracker = Arc::new(private_tracker()); - - let maybe_key = None; - - let response = handle_announce(&tracker, &sample_announce_request(), &sample_client_ip_sources(), maybe_key) - .await - .unwrap_err(); - - assert_error_response( - &response, - "Authentication error: Missing authentication key param for private tracker", - ); - } - - #[tokio::test] - async fn it_should_fail_when_the_authentication_key_is_invalid() { - let tracker = Arc::new(private_tracker()); - - let unregistered_key = auth::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); - - let maybe_key = Some(unregistered_key); - - let response = handle_announce(&tracker, &sample_announce_request(), &sample_client_ip_sources(), maybe_key) - .await - .unwrap_err(); - - assert_error_response(&response, "Authentication error: Failed to read key"); - } - } - - mod with_tracker_in_listed_mode { - - use std::sync::Arc; - - use super::{sample_announce_request, sample_client_ip_sources, whitelisted_tracker}; - use crate::servers::http::v1::handlers::announce::handle_announce; - use crate::servers::http::v1::handlers::announce::tests::assert_error_response; - - #[tokio::test] - async fn it_should_fail_when_the_announced_torrent_is_not_whitelisted() { - let tracker = Arc::new(whitelisted_tracker()); - - let announce_request = sample_announce_request(); - - let response = handle_announce(&tracker, &announce_request, &sample_client_ip_sources(), None) - .await - .unwrap_err(); - - assert_error_response( - &response, - &format!( - "Tracker error: The torrent: {}, is not whitelisted", - announce_request.info_hash - ), - ); - } - } - - mod with_tracker_on_reverse_proxy { - - use std::sync::Arc; - - use super::{sample_announce_request, tracker_on_reverse_proxy}; - use crate::servers::http::v1::handlers::announce::handle_announce; - use crate::servers::http::v1::handlers::announce::tests::assert_error_response; - use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; - - #[tokio::test] - async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let tracker = Arc::new(tracker_on_reverse_proxy()); - - let client_ip_sources = ClientIpSources { - right_most_x_forwarded_for: None, - connection_info_ip: None, - }; - - let response = handle_announce(&tracker, &sample_announce_request(), &client_ip_sources, None) - .await - .unwrap_err(); - - assert_error_response( - &response, - "Error resolving peer IP: missing or invalid the right most X-Forwarded-For IP", - ); - } - } - - mod with_tracker_not_on_reverse_proxy { - - use std::sync::Arc; - - use super::{sample_announce_request, tracker_not_on_reverse_proxy}; - use crate::servers::http::v1::handlers::announce::handle_announce; - use crate::servers::http::v1::handlers::announce::tests::assert_error_response; - use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; - - #[tokio::test] - async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let tracker = Arc::new(tracker_not_on_reverse_proxy()); - - let client_ip_sources = ClientIpSources { - right_most_x_forwarded_for: None, - connection_info_ip: None, - }; - - let response = handle_announce(&tracker, &sample_announce_request(), &client_ip_sources, None) - .await - .unwrap_err(); - - assert_error_response( - &response, - "Error resolving peer IP: cannot get the client IP from the connection info", - ); - } - } -} diff --git a/src/servers/http/v1/handlers/common/auth.rs b/src/servers/http/v1/handlers/common/auth.rs deleted file mode 100644 index f41635d69..000000000 --- a/src/servers/http/v1/handlers/common/auth.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! HTTP server authentication error and conversion to -//! [`responses::error::Error`](crate::servers::http::v1::responses::error::Error) -//! response. -use std::panic::Location; - -use thiserror::Error; - -use crate::servers::http::v1::responses; -use crate::tracker::auth; - -/// Authentication error. -/// -/// When the tracker is private, the authentication key is required in the URL -/// path. These are the possible errors that can occur when extracting the key -/// from the URL path. -#[derive(Debug, Error)] -pub enum Error { - #[error("Missing authentication key param for private tracker. Error in {location}")] - MissingAuthKey { location: &'static Location<'static> }, - #[error("Invalid format for authentication key param. Error in {location}")] - InvalidKeyFormat { location: &'static Location<'static> }, - #[error("Cannot extract authentication key param from URL path. Error in {location}")] - CannotExtractKeyParam { location: &'static Location<'static> }, -} - -impl From for responses::error::Error { - fn from(err: Error) -> Self { - responses::error::Error { - failure_reason: format!("Authentication error: {err}"), - } - } -} - -impl From for responses::error::Error { - fn from(err: auth::Error) -> Self { - responses::error::Error { - failure_reason: format!("Authentication error: {err}"), - } - } -} diff --git a/src/servers/http/v1/handlers/common/mod.rs b/src/servers/http/v1/handlers/common/mod.rs deleted file mode 100644 index 30eaf37b7..000000000 --- a/src/servers/http/v1/handlers/common/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -//! Common logic for HTTP handlers. -pub mod auth; -pub mod peer_ip; diff --git a/src/servers/http/v1/handlers/common/peer_ip.rs b/src/servers/http/v1/handlers/common/peer_ip.rs deleted file mode 100644 index d65efbc79..000000000 --- a/src/servers/http/v1/handlers/common/peer_ip.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! Logic to convert peer IP resolution errors into responses. -//! -//! The HTTP tracker may fail to resolve the peer IP address. This module -//! contains the logic to convert those -//! [`PeerIpResolutionError`](crate::servers::http::v1::services::peer_ip_resolver::PeerIpResolutionError) -//! errors into responses. -use crate::servers::http::v1::responses; -use crate::servers::http::v1::services::peer_ip_resolver::PeerIpResolutionError; - -impl From for responses::error::Error { - fn from(err: PeerIpResolutionError) -> Self { - responses::error::Error { - failure_reason: format!("Error resolving peer IP: {err}"), - } - } -} - -#[cfg(test)] -mod tests { - use std::panic::Location; - - use crate::servers::http::v1::responses; - use crate::servers::http::v1::services::peer_ip_resolver::PeerIpResolutionError; - - fn assert_error_response(error: &responses::error::Error, error_message: &str) { - assert!( - error.failure_reason.contains(error_message), - "Error response does not contain message: '{error_message}'. Error: {error:?}" - ); - } - - #[test] - fn it_should_map_a_peer_ip_resolution_error_into_an_error_response() { - let response = responses::error::Error::from(PeerIpResolutionError::MissingRightMostXForwardedForIp { - location: Location::caller(), - }); - - assert_error_response(&response, "Error resolving peer IP"); - } -} diff --git a/src/servers/http/v1/handlers/mod.rs b/src/servers/http/v1/handlers/mod.rs deleted file mode 100644 index d78dee7d5..000000000 --- a/src/servers/http/v1/handlers/mod.rs +++ /dev/null @@ -1,18 +0,0 @@ -//! Axum [`handlers`](axum#handlers) for the HTTP server. -//! -//! Refer to the generic [HTTP server documentation](crate::servers::http) for -//! more information about the HTTP tracker. -use super::responses; -use crate::tracker::error::Error; - -pub mod announce; -pub mod common; -pub mod scrape; - -impl From for responses::error::Error { - fn from(err: Error) -> Self { - responses::error::Error { - failure_reason: format!("Tracker error: {err}"), - } - } -} diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs deleted file mode 100644 index b8c1cbea1..000000000 --- a/src/servers/http/v1/handlers/scrape.rs +++ /dev/null @@ -1,280 +0,0 @@ -//! Axum [`handlers`](axum#handlers) for the `announce` requests. -//! -//! Refer to [HTTP server](crate::servers::http) for more information about the -//! `scrape` request. -//! -//! The handlers perform the authentication and authorization of the request, -//! and resolve the client IP address. -use std::sync::Arc; - -use axum::extract::State; -use axum::response::{IntoResponse, Response}; -use log::debug; - -use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; -use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; -use crate::servers::http::v1::extractors::scrape_request::ExtractRequest; -use crate::servers::http::v1::requests::scrape::Scrape; -use crate::servers::http::v1::services::peer_ip_resolver::{self, ClientIpSources}; -use crate::servers::http::v1::{responses, services}; -use crate::tracker::auth::Key; -use crate::tracker::{ScrapeData, Tracker}; - -/// It handles the `scrape` request when the HTTP tracker is configured -/// to run in `public` mode. -#[allow(clippy::unused_async)] -pub async fn handle_without_key( - State(tracker): State>, - ExtractRequest(scrape_request): ExtractRequest, - ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, -) -> Response { - debug!("http scrape request: {:#?}", &scrape_request); - - handle(&tracker, &scrape_request, &client_ip_sources, None).await -} - -/// It handles the `scrape` request when the HTTP tracker is configured -/// to run in `private` or `private_listed` mode. -/// -/// In this case, the authentication `key` parameter is required. -#[allow(clippy::unused_async)] -pub async fn handle_with_key( - State(tracker): State>, - ExtractRequest(scrape_request): ExtractRequest, - ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, - ExtractKey(key): ExtractKey, -) -> Response { - debug!("http scrape request: {:#?}", &scrape_request); - - handle(&tracker, &scrape_request, &client_ip_sources, Some(key)).await -} - -async fn handle( - tracker: &Arc, - scrape_request: &Scrape, - client_ip_sources: &ClientIpSources, - maybe_key: Option, -) -> Response { - let scrape_data = match handle_scrape(tracker, scrape_request, client_ip_sources, maybe_key).await { - Ok(scrape_data) => scrape_data, - Err(error) => return error.into_response(), - }; - build_response(scrape_data) -} - -/* code-review: authentication, authorization and peer IP resolution could be moved - from the handler (Axum) layer into the app layer `services::announce::invoke`. - That would make the handler even simpler and the code more reusable and decoupled from Axum. - See https://github.com/torrust/torrust-tracker/discussions/240. -*/ - -async fn handle_scrape( - tracker: &Arc, - scrape_request: &Scrape, - client_ip_sources: &ClientIpSources, - maybe_key: Option, -) -> Result { - // Authentication - let return_real_scrape_data = if tracker.requires_authentication() { - match maybe_key { - Some(key) => match tracker.authenticate(&key).await { - Ok(_) => true, - Err(_error) => false, - }, - None => false, - } - } else { - true - }; - - // Authorization for scrape requests is handled at the `Tracker` level - // for each torrent. - - let peer_ip = match peer_ip_resolver::invoke(tracker.config.on_reverse_proxy, client_ip_sources) { - Ok(peer_ip) => peer_ip, - Err(error) => return Err(responses::error::Error::from(error)), - }; - - if return_real_scrape_data { - Ok(services::scrape::invoke(tracker, &scrape_request.info_hashes, &peer_ip).await) - } else { - Ok(services::scrape::fake(tracker, &scrape_request.info_hashes, &peer_ip).await) - } -} - -fn build_response(scrape_data: ScrapeData) -> Response { - responses::scrape::Bencoded::from(scrape_data).into_response() -} - -#[cfg(test)] -mod tests { - use std::net::IpAddr; - use std::str::FromStr; - - use torrust_tracker_test_helpers::configuration; - - use crate::servers::http::v1::requests::scrape::Scrape; - use crate::servers::http::v1::responses; - use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::tracker::services::tracker_factory; - use crate::tracker::Tracker; - - fn private_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_private().into()) - } - - fn whitelisted_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_whitelisted().into()) - } - - fn tracker_on_reverse_proxy() -> Tracker { - tracker_factory(configuration::ephemeral_with_reverse_proxy().into()) - } - - fn tracker_not_on_reverse_proxy() -> Tracker { - tracker_factory(configuration::ephemeral_without_reverse_proxy().into()) - } - - fn sample_scrape_request() -> Scrape { - Scrape { - info_hashes: vec!["3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap()], - } - } - - fn sample_client_ip_sources() -> ClientIpSources { - ClientIpSources { - right_most_x_forwarded_for: Some(IpAddr::from_str("203.0.113.195").unwrap()), - connection_info_ip: Some(IpAddr::from_str("203.0.113.196").unwrap()), - } - } - - fn assert_error_response(error: &responses::error::Error, error_message: &str) { - assert!( - error.failure_reason.contains(error_message), - "Error response does not contain message: '{error_message}'. Error: {error:?}" - ); - } - - mod with_tracker_in_private_mode { - use std::str::FromStr; - use std::sync::Arc; - - use super::{private_tracker, sample_client_ip_sources, sample_scrape_request}; - use crate::servers::http::v1::handlers::scrape::handle_scrape; - use crate::tracker::{auth, ScrapeData}; - - #[tokio::test] - async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_missing() { - let tracker = Arc::new(private_tracker()); - - let scrape_request = sample_scrape_request(); - let maybe_key = None; - - let scrape_data = handle_scrape(&tracker, &scrape_request, &sample_client_ip_sources(), maybe_key) - .await - .unwrap(); - - let expected_scrape_data = ScrapeData::zeroed(&scrape_request.info_hashes); - - assert_eq!(scrape_data, expected_scrape_data); - } - - #[tokio::test] - async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_invalid() { - let tracker = Arc::new(private_tracker()); - - let scrape_request = sample_scrape_request(); - let unregistered_key = auth::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); - let maybe_key = Some(unregistered_key); - - let scrape_data = handle_scrape(&tracker, &scrape_request, &sample_client_ip_sources(), maybe_key) - .await - .unwrap(); - - let expected_scrape_data = ScrapeData::zeroed(&scrape_request.info_hashes); - - assert_eq!(scrape_data, expected_scrape_data); - } - } - - mod with_tracker_in_listed_mode { - - use std::sync::Arc; - - use super::{sample_client_ip_sources, sample_scrape_request, whitelisted_tracker}; - use crate::servers::http::v1::handlers::scrape::handle_scrape; - use crate::tracker::ScrapeData; - - #[tokio::test] - async fn it_should_return_zeroed_swarm_metadata_when_the_torrent_is_not_whitelisted() { - let tracker = Arc::new(whitelisted_tracker()); - - let scrape_request = sample_scrape_request(); - - let scrape_data = handle_scrape(&tracker, &scrape_request, &sample_client_ip_sources(), None) - .await - .unwrap(); - - let expected_scrape_data = ScrapeData::zeroed(&scrape_request.info_hashes); - - assert_eq!(scrape_data, expected_scrape_data); - } - } - - mod with_tracker_on_reverse_proxy { - use std::sync::Arc; - - use super::{sample_scrape_request, tracker_on_reverse_proxy}; - use crate::servers::http::v1::handlers::scrape::handle_scrape; - use crate::servers::http::v1::handlers::scrape::tests::assert_error_response; - use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; - - #[tokio::test] - async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let tracker = Arc::new(tracker_on_reverse_proxy()); - - let client_ip_sources = ClientIpSources { - right_most_x_forwarded_for: None, - connection_info_ip: None, - }; - - let response = handle_scrape(&tracker, &sample_scrape_request(), &client_ip_sources, None) - .await - .unwrap_err(); - - assert_error_response( - &response, - "Error resolving peer IP: missing or invalid the right most X-Forwarded-For IP", - ); - } - } - - mod with_tracker_not_on_reverse_proxy { - use std::sync::Arc; - - use super::{sample_scrape_request, tracker_not_on_reverse_proxy}; - use crate::servers::http::v1::handlers::scrape::handle_scrape; - use crate::servers::http::v1::handlers::scrape::tests::assert_error_response; - use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; - - #[tokio::test] - async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let tracker = Arc::new(tracker_not_on_reverse_proxy()); - - let client_ip_sources = ClientIpSources { - right_most_x_forwarded_for: None, - connection_info_ip: None, - }; - - let response = handle_scrape(&tracker, &sample_scrape_request(), &client_ip_sources, None) - .await - .unwrap_err(); - - assert_error_response( - &response, - "Error resolving peer IP: cannot get the client IP from the connection info", - ); - } - } -} diff --git a/src/servers/http/v1/launcher.rs b/src/servers/http/v1/launcher.rs deleted file mode 100644 index 96dd1baac..000000000 --- a/src/servers/http/v1/launcher.rs +++ /dev/null @@ -1,147 +0,0 @@ -//! Logic to start new HTTP server instances. -use std::future::Future; -use std::net::SocketAddr; -use std::str::FromStr; -use std::sync::Arc; - -use async_trait::async_trait; -use axum_server::tls_rustls::RustlsConfig; -use axum_server::Handle; -use futures::future::BoxFuture; -use log::info; - -use super::routes::router; -use crate::servers::http::server::HttpServerLauncher; -use crate::tracker::Tracker; - -#[derive(Debug)] -pub enum Error { - Error(String), -} - -pub struct Launcher; - -impl Launcher { - pub fn start_from_tcp_listener_with_graceful_shutdown( - tcp_listener: std::net::TcpListener, - tracker: Arc, - shutdown_signal: F, - ) -> BoxFuture<'static, ()> - where - F: Future + Send + 'static, - { - let app = router(tracker); - - Box::pin(async { - axum::Server::from_tcp(tcp_listener) - .expect("Could not bind to tcp listener.") - .serve(app.into_make_service_with_connect_info::()) - .with_graceful_shutdown(shutdown_signal) - .await - .expect("Axum server crashed."); - }) - } - - pub fn start_tls_from_tcp_listener_with_graceful_shutdown( - tcp_listener: std::net::TcpListener, - (ssl_cert_path, ssl_key_path): (String, String), - tracker: Arc, - shutdown_signal: F, - ) -> BoxFuture<'static, ()> - where - F: Future + Send + 'static, - { - let app = router(tracker); - - let handle = Handle::new(); - - let cloned_handle = handle.clone(); - - tokio::task::spawn_local(async move { - shutdown_signal.await; - cloned_handle.shutdown(); - }); - - Box::pin(async { - let tls_config = RustlsConfig::from_pem_file(ssl_cert_path, ssl_key_path) - .await - .expect("Could not read tls cert."); - - axum_server::from_tcp_rustls(tcp_listener, tls_config) - .handle(handle) - .serve(app.into_make_service_with_connect_info::()) - .await - .expect("Axum server crashed."); - }) - } -} - -#[async_trait] -impl HttpServerLauncher for Launcher { - fn new() -> Self { - Self {} - } - - fn start_with_graceful_shutdown( - &self, - cfg: torrust_tracker_configuration::HttpTracker, - tracker: Arc, - shutdown_signal: F, - ) -> (SocketAddr, BoxFuture<'static, ()>) - where - F: Future + Send + 'static, - { - let addr = SocketAddr::from_str(&cfg.bind_address).expect("bind_address is not a valid SocketAddr."); - let tcp_listener = std::net::TcpListener::bind(addr).expect("Could not bind tcp_listener to address."); - let bind_addr = tcp_listener - .local_addr() - .expect("Could not get local_addr from tcp_listener."); - - if let (true, Some(ssl_cert_path), Some(ssl_key_path)) = (cfg.ssl_enabled, &cfg.ssl_cert_path, &cfg.ssl_key_path) { - let server = Self::start_tls_from_tcp_listener_with_graceful_shutdown( - tcp_listener, - (ssl_cert_path.to_string(), ssl_key_path.to_string()), - tracker, - shutdown_signal, - ); - - (bind_addr, server) - } else { - let server = Self::start_from_tcp_listener_with_graceful_shutdown(tcp_listener, tracker, shutdown_signal); - - (bind_addr, server) - } - } -} - -pub fn start(socket_addr: std::net::SocketAddr, tracker: Arc) -> impl Future> { - let app = router(tracker); - - let server = axum::Server::bind(&socket_addr).serve(app.into_make_service_with_connect_info::()); - - server.with_graceful_shutdown(async move { - tokio::signal::ctrl_c().await.expect("Failed to listen to shutdown signal."); - info!("Stopping Torrust HTTP tracker server on http://{} ...", socket_addr); - }) -} - -pub fn start_tls( - socket_addr: std::net::SocketAddr, - ssl_config: RustlsConfig, - tracker: Arc, -) -> impl Future> { - let app = router(tracker); - - let handle = Handle::new(); - let shutdown_handle = handle.clone(); - - tokio::spawn(async move { - tokio::signal::ctrl_c().await.expect("Failed to listen to shutdown signal."); - info!("Stopping Torrust HTTP tracker server on https://{} ...", socket_addr); - shutdown_handle.shutdown(); - }); - - axum_server::bind_rustls(socket_addr, ssl_config) - .handle(handle) - .serve(app.into_make_service_with_connect_info::()) -} diff --git a/src/servers/http/v1/mod.rs b/src/servers/http/v1/mod.rs deleted file mode 100644 index 464a7ee14..000000000 --- a/src/servers/http/v1/mod.rs +++ /dev/null @@ -1,12 +0,0 @@ -//! HTTP server implementation for the `v1` API. -//! -//! Refer to the generic [HTTP server documentation](crate::servers::http) for -//! more information about the endpoints and their usage. -pub mod extractors; -pub mod handlers; -pub mod launcher; -pub mod query; -pub mod requests; -pub mod responses; -pub mod routes; -pub mod services; diff --git a/src/servers/http/v1/requests/mod.rs b/src/servers/http/v1/requests/mod.rs deleted file mode 100644 index ee34ca72a..000000000 --- a/src/servers/http/v1/requests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -//! HTTP requests for the HTTP tracker. -//! -//! Refer to the generic [HTTP server documentation](crate::servers::http) for -//! more information about the HTTP tracker. -pub mod announce; -pub mod scrape; diff --git a/src/servers/http/v1/responses/announce.rs b/src/servers/http/v1/responses/announce.rs deleted file mode 100644 index 8fbe5df35..000000000 --- a/src/servers/http/v1/responses/announce.rs +++ /dev/null @@ -1,508 +0,0 @@ -//! `Announce` response for the HTTP tracker [`announce`](crate::servers::http::v1::requests::announce::Announce) request. -//! -//! Data structures and logic to build the `announce` response. -use std::io::Write; -use std::net::IpAddr; -use std::panic::Location; - -use axum::http::StatusCode; -use axum::response::{IntoResponse, Response}; -use bip_bencode::{ben_bytes, ben_int, ben_list, ben_map, BMutAccess, BencodeMut}; -use serde::{self, Deserialize, Serialize}; -use thiserror::Error; - -use crate::servers::http::v1::responses; -use crate::tracker::{self, AnnounceData}; - -/// Normal (non compact) `announce` response. -/// -/// It's a bencoded dictionary. -/// -/// ```rust -/// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -/// use torrust_tracker::servers::http::v1::responses::announce::{NonCompact, Peer}; -/// -/// let response = NonCompact { -/// interval: 111, -/// interval_min: 222, -/// complete: 333, -/// incomplete: 444, -/// peers: vec![ -/// // IPV4 -/// Peer { -/// peer_id: *b"-qB00000000000000001", -/// ip: IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), // 105.105.105.105 -/// port: 0x7070, // 28784 -/// }, -/// // IPV6 -/// Peer { -/// peer_id: *b"-qB00000000000000002", -/// ip: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), -/// port: 0x7070, // 28784 -/// }, -/// ], -/// }; -/// -/// let bytes = response.body(); -/// -/// // The expected bencoded response. -/// let expected_bytes = b"d8:completei333e10:incompletei444e8:intervali111e12:min intervali222e5:peersld2:ip15:105.105.105.1057:peer id20:-qB000000000000000014:porti28784eed2:ip39:6969:6969:6969:6969:6969:6969:6969:69697:peer id20:-qB000000000000000024:porti28784eeee"; -/// -/// assert_eq!( -/// String::from_utf8(bytes).unwrap(), -/// String::from_utf8(expected_bytes.to_vec()).unwrap() -/// ); -/// ``` -/// -/// Refer to [BEP 03: The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -/// for more information. -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct NonCompact { - /// Interval in seconds that the client should wait between sending regular - /// announce requests to the tracker. - /// - /// It's a **recommended** wait time between announcements. - /// - /// This is the standard amount of time that clients should wait between - /// sending consecutive announcements to the tracker. This value is set by - /// the tracker and is typically provided in the tracker's response to a - /// client's initial request. It serves as a guideline for clients to know - /// how often they should contact the tracker for updates on the peer list, - /// while ensuring that the tracker is not overwhelmed with requests. - pub interval: u32, - /// Minimum announce interval. Clients must not reannounce more frequently - /// than this. - /// - /// It establishes the shortest allowed wait time. - /// - /// This is an optional parameter in the protocol that the tracker may - /// provide in its response. It sets a lower limit on the frequency at which - /// clients are allowed to send announcements. Clients should respect this - /// value to prevent sending too many requests in a short period, which - /// could lead to excessive load on the tracker or even getting banned by - /// the tracker for not adhering to the rules. - #[serde(rename = "min interval")] - pub interval_min: u32, - /// Number of peers with the entire file, i.e. seeders. - pub complete: u32, - /// Number of non-seeder peers, aka "leechers". - pub incomplete: u32, - /// A list of peers. The value is a list of dictionaries. - pub peers: Vec, -} - -/// Peer information in the [`NonCompact`](crate::servers::http::v1::responses::announce::NonCompact) -/// response. -/// -/// ```rust -/// use std::net::{IpAddr, Ipv4Addr}; -/// use torrust_tracker::servers::http::v1::responses::announce::{NonCompact, Peer}; -/// -/// let peer = Peer { -/// peer_id: *b"-qB00000000000000001", -/// ip: IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), // 105.105.105.105 -/// port: 0x7070, // 28784 -/// }; -/// ``` -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct Peer { - /// The peer's ID. - pub peer_id: [u8; 20], - /// The peer's IP address. - pub ip: IpAddr, - /// The peer's port number. - pub port: u16, -} - -impl Peer { - #[must_use] - pub fn ben_map(&self) -> BencodeMut { - ben_map! { - "peer id" => ben_bytes!(self.peer_id.clone().to_vec()), - "ip" => ben_bytes!(self.ip.to_string()), - "port" => ben_int!(i64::from(self.port)) - } - } -} - -impl From for Peer { - fn from(peer: tracker::peer::Peer) -> Self { - Peer { - peer_id: peer.peer_id.to_bytes(), - ip: peer.peer_addr.ip(), - port: peer.peer_addr.port(), - } - } -} - -impl NonCompact { - /// Returns the bencoded body of the non-compact response. - /// - /// # Panics - /// - /// Will return an error if it can't access the bencode as a mutable `BListAccess`. - #[must_use] - pub fn body(&self) -> Vec { - let mut peers_list = ben_list!(); - let peers_list_mut = peers_list.list_mut().unwrap(); - for peer in &self.peers { - peers_list_mut.push(peer.ben_map()); - } - - (ben_map! { - "complete" => ben_int!(i64::from(self.complete)), - "incomplete" => ben_int!(i64::from(self.incomplete)), - "interval" => ben_int!(i64::from(self.interval)), - "min interval" => ben_int!(i64::from(self.interval_min)), - "peers" => peers_list.clone() - }) - .encode() - } -} - -impl IntoResponse for NonCompact { - fn into_response(self) -> Response { - (StatusCode::OK, self.body()).into_response() - } -} - -impl From for NonCompact { - fn from(domain_announce_response: AnnounceData) -> Self { - let peers: Vec = domain_announce_response.peers.iter().map(|peer| Peer::from(*peer)).collect(); - - Self { - interval: domain_announce_response.interval, - interval_min: domain_announce_response.interval_min, - complete: domain_announce_response.swarm_stats.seeders, - incomplete: domain_announce_response.swarm_stats.leechers, - peers, - } - } -} - -/// Compact `announce` response. -/// -/// _"To reduce the size of tracker responses and to reduce memory and -/// computational requirements in trackers, trackers may return peers as a -/// packed string rather than as a bencoded list."_ -/// -/// ```rust -/// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -/// use torrust_tracker::servers::http::v1::responses::announce::{Compact, CompactPeer}; -/// -/// let response = Compact { -/// interval: 111, -/// interval_min: 222, -/// complete: 333, -/// incomplete: 444, -/// peers: vec![ -/// // IPV4 -/// CompactPeer { -/// ip: IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), // 105.105.105.105 -/// port: 0x7070, // 28784 -/// }, -/// // IPV6 -/// CompactPeer { -/// ip: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), -/// port: 0x7070, // 28784 -/// }, -/// ], -/// }; -/// -/// let bytes = response.body().unwrap(); -/// -/// // The expected bencoded response. -/// let expected_bytes = -/// // cspell:disable-next-line -/// b"d8:completei333e10:incompletei444e8:intervali111e12:min intervali222e5:peers6:iiiipp6:peers618:iiiiiiiiiiiiiiiippe"; -/// -/// assert_eq!( -/// String::from_utf8(bytes).unwrap(), -/// String::from_utf8(expected_bytes.to_vec()).unwrap() -/// ); -/// ``` -/// -/// Refer to the official BEPs for more information: -/// -/// - [BEP 23: Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) -/// - [BEP 07: IPv6 Tracker Extension](https://www.bittorrent.org/beps/bep_0007.html) -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct Compact { - /// Interval in seconds that the client should wait between sending regular - /// announce requests to the tracker. - /// - /// It's a **recommended** wait time between announcements. - /// - /// This is the standard amount of time that clients should wait between - /// sending consecutive announcements to the tracker. This value is set by - /// the tracker and is typically provided in the tracker's response to a - /// client's initial request. It serves as a guideline for clients to know - /// how often they should contact the tracker for updates on the peer list, - /// while ensuring that the tracker is not overwhelmed with requests. - pub interval: u32, - /// Minimum announce interval. Clients must not reannounce more frequently - /// than this. - /// - /// It establishes the shortest allowed wait time. - /// - /// This is an optional parameter in the protocol that the tracker may - /// provide in its response. It sets a lower limit on the frequency at which - /// clients are allowed to send announcements. Clients should respect this - /// value to prevent sending too many requests in a short period, which - /// could lead to excessive load on the tracker or even getting banned by - /// the tracker for not adhering to the rules. - #[serde(rename = "min interval")] - pub interval_min: u32, - /// Number of seeders, aka "completed". - pub complete: u32, - /// Number of non-seeder peers, aka "incomplete". - pub incomplete: u32, - /// Compact peer list. - pub peers: Vec, -} - -/// Compact peer. It's used in the [`Compact`](crate::servers::http::v1::responses::announce::Compact) -/// response. -/// -/// _"To reduce the size of tracker responses and to reduce memory and -/// computational requirements in trackers, trackers may return peers as a -/// packed string rather than as a bencoded list."_ -/// -/// A part from reducing the size of the response, this format does not contain -/// the peer's ID. -/// -/// ```rust -/// use std::net::{IpAddr, Ipv4Addr}; -/// use torrust_tracker::servers::http::v1::responses::announce::CompactPeer; -/// -/// let compact_peer = CompactPeer { -/// ip: IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), // 105.105.105.105 -/// port: 0x7070 // 28784 -/// }; -/// ``` -/// -/// Refer to [BEP 23: Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) -/// for more information. -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct CompactPeer { - /// The peer's IP address. - pub ip: IpAddr, - /// The peer's port number. - pub port: u16, -} - -impl CompactPeer { - /// Returns the compact peer as a byte vector. - /// - /// # Errors - /// - /// Will return `Err` if internally interrupted. - pub fn bytes(&self) -> Result, Box> { - let mut bytes: Vec = Vec::new(); - match self.ip { - IpAddr::V4(ip) => { - bytes.write_all(&u32::from(ip).to_be_bytes())?; - } - IpAddr::V6(ip) => { - bytes.write_all(&u128::from(ip).to_be_bytes())?; - } - } - bytes.write_all(&self.port.to_be_bytes())?; - Ok(bytes) - } -} - -impl From for CompactPeer { - fn from(peer: tracker::peer::Peer) -> Self { - CompactPeer { - ip: peer.peer_addr.ip(), - port: peer.peer_addr.port(), - } - } -} - -impl Compact { - /// Returns the bencoded compact response as a byte vector. - /// - /// # Errors - /// - /// Will return `Err` if internally interrupted. - pub fn body(&self) -> Result, Box> { - let bytes = (ben_map! { - "complete" => ben_int!(i64::from(self.complete)), - "incomplete" => ben_int!(i64::from(self.incomplete)), - "interval" => ben_int!(i64::from(self.interval)), - "min interval" => ben_int!(i64::from(self.interval_min)), - "peers" => ben_bytes!(self.peers_v4_bytes()?), - "peers6" => ben_bytes!(self.peers_v6_bytes()?) - }) - .encode(); - - Ok(bytes) - } - - fn peers_v4_bytes(&self) -> Result, Box> { - let mut bytes: Vec = Vec::new(); - for compact_peer in &self.peers { - match compact_peer.ip { - IpAddr::V4(_ip) => { - let peer_bytes = compact_peer.bytes()?; - bytes.write_all(&peer_bytes)?; - } - IpAddr::V6(_) => {} - } - } - Ok(bytes) - } - - fn peers_v6_bytes(&self) -> Result, Box> { - let mut bytes: Vec = Vec::new(); - for compact_peer in &self.peers { - match compact_peer.ip { - IpAddr::V6(_ip) => { - let peer_bytes = compact_peer.bytes()?; - bytes.write_all(&peer_bytes)?; - } - IpAddr::V4(_) => {} - } - } - Ok(bytes) - } -} - -/// `Compact` response serialization error. -#[derive(Error, Debug)] -pub enum CompactSerializationError { - #[error("cannot write bytes: {inner_error} in {location}")] - CannotWriteBytes { - location: &'static Location<'static>, - inner_error: String, - }, -} - -impl From for responses::error::Error { - fn from(err: CompactSerializationError) -> Self { - responses::error::Error { - failure_reason: format!("{err}"), - } - } -} - -impl IntoResponse for Compact { - fn into_response(self) -> Response { - match self.body() { - Ok(bytes) => (StatusCode::OK, bytes).into_response(), - Err(err) => responses::error::Error::from(CompactSerializationError::CannotWriteBytes { - location: Location::caller(), - inner_error: format!("{err}"), - }) - .into_response(), - } - } -} - -impl From for Compact { - fn from(domain_announce_response: AnnounceData) -> Self { - let peers: Vec = domain_announce_response - .peers - .iter() - .map(|peer| CompactPeer::from(*peer)) - .collect(); - - Self { - interval: domain_announce_response.interval, - interval_min: domain_announce_response.interval_min, - complete: domain_announce_response.swarm_stats.seeders, - incomplete: domain_announce_response.swarm_stats.leechers, - peers, - } - } -} - -#[cfg(test)] -mod tests { - - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; - - use super::{NonCompact, Peer}; - use crate::servers::http::v1::responses::announce::{Compact, CompactPeer}; - - // Some ascii values used in tests: - // - // +-----------------+ - // | Dec | Hex | Chr | - // +-----------------+ - // | 105 | 69 | i | - // | 112 | 70 | p | - // +-----------------+ - // - // IP addresses and port numbers used in tests are chosen so that their bencoded representation - // is also a valid string which makes asserts more readable. - - #[test] - fn non_compact_announce_response_can_be_bencoded() { - let response = NonCompact { - interval: 111, - interval_min: 222, - complete: 333, - incomplete: 444, - peers: vec![ - // IPV4 - Peer { - peer_id: *b"-qB00000000000000001", - ip: IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), // 105.105.105.105 - port: 0x7070, // 28784 - }, - // IPV6 - Peer { - peer_id: *b"-qB00000000000000002", - ip: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), - port: 0x7070, // 28784 - }, - ], - }; - - let bytes = response.body(); - - // cspell:disable-next-line - let expected_bytes = b"d8:completei333e10:incompletei444e8:intervali111e12:min intervali222e5:peersld2:ip15:105.105.105.1057:peer id20:-qB000000000000000014:porti28784eed2:ip39:6969:6969:6969:6969:6969:6969:6969:69697:peer id20:-qB000000000000000024:porti28784eeee"; - - assert_eq!( - String::from_utf8(bytes).unwrap(), - String::from_utf8(expected_bytes.to_vec()).unwrap() - ); - } - - #[test] - fn compact_announce_response_can_be_bencoded() { - let response = Compact { - interval: 111, - interval_min: 222, - complete: 333, - incomplete: 444, - peers: vec![ - // IPV4 - CompactPeer { - ip: IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), // 105.105.105.105 - port: 0x7070, // 28784 - }, - // IPV6 - CompactPeer { - ip: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), - port: 0x7070, // 28784 - }, - ], - }; - - let bytes = response.body().unwrap(); - - let expected_bytes = - // cspell:disable-next-line - b"d8:completei333e10:incompletei444e8:intervali111e12:min intervali222e5:peers6:iiiipp6:peers618:iiiiiiiiiiiiiiiippe"; - - assert_eq!( - String::from_utf8(bytes).unwrap(), - String::from_utf8(expected_bytes.to_vec()).unwrap() - ); - } -} diff --git a/src/servers/http/v1/responses/error.rs b/src/servers/http/v1/responses/error.rs deleted file mode 100644 index 606ead3b2..000000000 --- a/src/servers/http/v1/responses/error.rs +++ /dev/null @@ -1,69 +0,0 @@ -//! `Error` response for the [`HTTP tracker`](crate::servers::http). -//! -//! Data structures and logic to build the error responses. -//! -//! From the [BEP 03. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html): -//! -//! _"Tracker responses are bencoded dictionaries. If a tracker response has a -//! key failure reason, then that maps to a human readable string which explains -//! why the query failed, and no other keys are required."_ -//! -//! > **NOTICE**: error responses are bencoded and always have a `200 OK` status -//! code. The official `BitTorrent` specification does not specify the status -//! code. -use axum::http::StatusCode; -use axum::response::{IntoResponse, Response}; -use serde::{self, Serialize}; - -/// `Error` response for the [`HTTP tracker`](crate::servers::http). -#[derive(Serialize, Debug, PartialEq)] -pub struct Error { - /// Human readable string which explains why the request failed. - #[serde(rename = "failure reason")] - pub failure_reason: String, -} - -impl Error { - /// Returns the bencoded representation of the `Error` struct. - /// - /// ```rust - /// use torrust_tracker::servers::http::v1::responses::error::Error; - /// - /// let err = Error { - /// failure_reason: "error message".to_owned(), - /// }; - /// - /// // cspell:disable-next-line - /// assert_eq!(err.write(), "d14:failure reason13:error messagee"); - /// ``` - /// - /// # Panics - /// - /// It would panic if the `Error` struct contained an inappropriate field - /// type. - #[must_use] - pub fn write(&self) -> String { - serde_bencode::to_string(&self).unwrap() - } -} - -impl IntoResponse for Error { - fn into_response(self) -> Response { - (StatusCode::OK, self.write()).into_response() - } -} - -#[cfg(test)] -mod tests { - - use super::Error; - - #[test] - fn http_tracker_errors_can_be_bencoded() { - let err = Error { - failure_reason: "error message".to_owned(), - }; - - assert_eq!(err.write(), "d14:failure reason13:error messagee"); // cspell:disable-line - } -} diff --git a/src/servers/http/v1/responses/mod.rs b/src/servers/http/v1/responses/mod.rs deleted file mode 100644 index 3c6632fed..000000000 --- a/src/servers/http/v1/responses/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! HTTP responses for the HTTP tracker. -//! -//! Refer to the generic [HTTP server documentation](crate::servers::http) for -//! more information about the HTTP tracker. -pub mod announce; -pub mod error; -pub mod scrape; diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs deleted file mode 100644 index 86bdf480f..000000000 --- a/src/servers/http/v1/routes.rs +++ /dev/null @@ -1,26 +0,0 @@ -//! HTTP server routes for version `v1`. -use std::sync::Arc; - -use axum::routing::get; -use axum::Router; -use axum_client_ip::SecureClientIpSource; - -use super::handlers::{announce, scrape}; -use crate::tracker::Tracker; - -/// It adds the routes to the router. -/// -/// > **NOTICE**: it's added a layer to get the client IP from the connection -/// info. The tracker could use the connection info to get the client IP. -#[allow(clippy::needless_pass_by_value)] -pub fn router(tracker: Arc) -> Router { - Router::new() - // Announce request - .route("/announce", get(announce::handle_without_key).with_state(tracker.clone())) - .route("/announce/:key", get(announce::handle_with_key).with_state(tracker.clone())) - // Scrape request - .route("/scrape", get(scrape::handle_without_key).with_state(tracker.clone())) - .route("/scrape/:key", get(scrape::handle_with_key).with_state(tracker)) - // Add extension to get the client IP from the connection info - .layer(SecureClientIpSource::ConnectInfo.into_extension()) -} diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs deleted file mode 100644 index 4c1b262ba..000000000 --- a/src/servers/http/v1/services/announce.rs +++ /dev/null @@ -1,216 +0,0 @@ -//! The `announce` service. -//! -//! The service is responsible for handling the `announce` requests. -//! -//! It delegates the `announce` logic to the [`Tracker`](crate::tracker::Tracker::announce) -//! and it returns the [`AnnounceData`](crate::tracker::AnnounceData) returned -//! by the [`Tracker`](crate::tracker::Tracker). -//! -//! It also sends an [`statistics::Event`](crate::tracker::statistics::Event) -//! because events are specific for the HTTP tracker. -use std::net::IpAddr; -use std::sync::Arc; - -use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::peer::Peer; -use crate::tracker::{statistics, AnnounceData, Tracker}; - -/// The HTTP tracker `announce` service. -/// -/// The service sends an statistics event that increments: -/// -/// - The number of TCP connections handled by the HTTP tracker. -/// - The number of TCP `announce` requests handled by the HTTP tracker. -/// -/// > **NOTICE**: as the HTTP tracker does not requires a connection request -/// like the UDP tracker, the number of TCP connections is incremented for -/// each `announce` request. -pub async fn invoke(tracker: Arc, info_hash: InfoHash, peer: &mut Peer) -> AnnounceData { - let original_peer_ip = peer.peer_addr.ip(); - - // The tracker could change the original peer ip - let announce_data = tracker.announce(&info_hash, peer, &original_peer_ip).await; - - match original_peer_ip { - IpAddr::V4(_) => { - tracker.send_stats_event(statistics::Event::Tcp4Announce).await; - } - IpAddr::V6(_) => { - tracker.send_stats_event(statistics::Event::Tcp6Announce).await; - } - } - - announce_data -} - -#[cfg(test)] -mod tests { - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; - use torrust_tracker_test_helpers::configuration; - - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::shared::clock::DurationSinceUnixEpoch; - use crate::tracker::services::tracker_factory; - use crate::tracker::{peer, Tracker}; - - fn public_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_public().into()) - } - - fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() - } - - fn sample_peer_using_ipv4() -> peer::Peer { - sample_peer() - } - - fn sample_peer_using_ipv6() -> peer::Peer { - let mut peer = sample_peer(); - peer.peer_addr = SocketAddr::new( - IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), - 8080, - ); - peer - } - - fn sample_peer() -> peer::Peer { - peer::Peer { - peer_id: peer::Id(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), - event: AnnounceEvent::Started, - } - } - - mod with_tracker_in_any_mode { - use std::future; - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - use std::sync::Arc; - - use mockall::predicate::eq; - use torrust_tracker_test_helpers::configuration; - - use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; - use crate::servers::http::v1::services::announce::invoke; - use crate::servers::http::v1::services::announce::tests::{public_tracker, sample_info_hash, sample_peer}; - use crate::tracker::peer::Peer; - use crate::tracker::torrent::SwarmStats; - use crate::tracker::{statistics, AnnounceData, Tracker}; - - #[tokio::test] - async fn it_should_return_the_announce_data() { - let tracker = Arc::new(public_tracker()); - - let mut peer = sample_peer(); - - let announce_data = invoke(tracker.clone(), sample_info_hash(), &mut peer).await; - - let expected_announce_data = AnnounceData { - peers: vec![], - swarm_stats: SwarmStats { - completed: 0, - seeders: 1, - leechers: 0, - }, - interval: tracker.config.announce_interval, - interval_min: tracker.config.min_announce_interval, - }; - - assert_eq!(announce_data, expected_announce_data); - } - - #[tokio::test] - async fn it_should_send_the_tcp_4_announce_event_when_the_peer_uses_ipv4() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::Event::Tcp4Announce)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); - - let tracker = Arc::new( - Tracker::new( - Arc::new(configuration::ephemeral()), - Some(stats_event_sender), - statistics::Repo::new(), - ) - .unwrap(), - ); - - let mut peer = sample_peer_using_ipv4(); - - let _announce_data = invoke(tracker, sample_info_hash(), &mut peer).await; - } - - fn tracker_with_an_ipv6_external_ip(stats_event_sender: Box) -> Tracker { - let mut configuration = configuration::ephemeral(); - configuration.external_ip = - Some(IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)).to_string()); - - Tracker::new(Arc::new(configuration), Some(stats_event_sender), statistics::Repo::new()).unwrap() - } - - fn peer_with_the_ipv4_loopback_ip() -> Peer { - let loopback_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); - let mut peer = sample_peer(); - peer.peer_addr = SocketAddr::new(loopback_ip, 8080); - peer - } - - #[tokio::test] - async fn it_should_send_the_tcp_4_announce_event_when_the_peer_uses_ipv4_even_if_the_tracker_changes_the_peer_ip_to_ipv6() - { - // Tracker changes the peer IP to the tracker external IP when the peer is using the loopback IP. - - // Assert that the event sent is a TCP4 event - let mut stats_event_sender_mock = statistics::MockEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::Event::Tcp4Announce)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); - - let mut peer = peer_with_the_ipv4_loopback_ip(); - - let _announce_data = invoke( - tracker_with_an_ipv6_external_ip(stats_event_sender).into(), - sample_info_hash(), - &mut peer, - ) - .await; - } - - #[tokio::test] - async fn it_should_send_the_tcp_6_announce_event_when_the_peer_uses_ipv6_even_if_the_tracker_changes_the_peer_ip_to_ipv4() - { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::Event::Tcp6Announce)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); - - let tracker = Arc::new( - Tracker::new( - Arc::new(configuration::ephemeral()), - Some(stats_event_sender), - statistics::Repo::new(), - ) - .unwrap(), - ); - - let mut peer = sample_peer_using_ipv6(); - - let _announce_data = invoke(tracker, sample_info_hash(), &mut peer).await; - } - } -} diff --git a/src/servers/http/v1/services/peer_ip_resolver.rs b/src/servers/http/v1/services/peer_ip_resolver.rs deleted file mode 100644 index b8987bb4d..000000000 --- a/src/servers/http/v1/services/peer_ip_resolver.rs +++ /dev/null @@ -1,218 +0,0 @@ -//! This service resolves the peer IP from the request. -//! -//! The peer IP is used to identify the peer in the tracker. It's the peer IP -//! that is used in the `announce` responses (peer list). And it's also used to -//! send statistics events. -//! -//! Given this request chain: -//! -//! ```text -//! client <-> http proxy 1 <-> http proxy 2 <-> server -//! ip: 126.0.0.1 ip: 126.0.0.2 ip: 126.0.0.3 ip: 126.0.0.4 -//! X-Forwarded-For: 126.0.0.1 X-Forwarded-For: 126.0.0.1,126.0.0.2 -//! ``` -//! -//! This service returns two options for the peer IP: -//! -//! ```text -//! right_most_x_forwarded_for = 126.0.0.2 -//! connection_info_ip = 126.0.0.3 -//! ``` -//! -//! Depending on the tracker configuration. -use std::net::IpAddr; -use std::panic::Location; - -use serde::{Deserialize, Serialize}; -use thiserror::Error; - -/// This struct contains the sources from which the peer IP can be obtained. -#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)] -pub struct ClientIpSources { - /// The right most IP from the `X-Forwarded-For` HTTP header. - pub right_most_x_forwarded_for: Option, - /// The IP from the connection info. - pub connection_info_ip: Option, -} - -/// The error that can occur when resolving the peer IP. -#[derive(Error, Debug)] -pub enum PeerIpResolutionError { - /// The peer IP cannot be obtained because the tracker is configured as a - /// reverse proxy but the `X-Forwarded-For` HTTP header is missing or - /// invalid. - #[error( - "missing or invalid the right most X-Forwarded-For IP (mandatory on reverse proxy tracker configuration) in {location}" - )] - MissingRightMostXForwardedForIp { location: &'static Location<'static> }, - /// The peer IP cannot be obtained because the tracker is not configured as - /// a reverse proxy but the connection info was not provided to the Axum - /// framework via a route extension. - #[error("cannot get the client IP from the connection info in {location}")] - MissingClientIp { location: &'static Location<'static> }, -} - -/// Resolves the peer IP from the request. -/// -/// Given the sources from which the peer IP can be obtained, this function -/// resolves the peer IP according to the tracker configuration. -/// -/// With the tracker running on reverse proxy mode: -/// -/// ```rust -/// use std::net::IpAddr; -/// use std::str::FromStr; -/// -/// use torrust_tracker::servers::http::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; -/// -/// let on_reverse_proxy = true; -/// -/// let ip = invoke( -/// on_reverse_proxy, -/// &ClientIpSources { -/// right_most_x_forwarded_for: Some(IpAddr::from_str("203.0.113.195").unwrap()), -/// connection_info_ip: None, -/// }, -/// ) -/// .unwrap(); -/// -/// assert_eq!(ip, IpAddr::from_str("203.0.113.195").unwrap()); -/// ``` -/// -/// With the tracker non running on reverse proxy mode: -/// -/// ```rust -/// use std::net::IpAddr; -/// use std::str::FromStr; -/// -/// use torrust_tracker::servers::http::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; -/// -/// let on_reverse_proxy = false; -/// -/// let ip = invoke( -/// on_reverse_proxy, -/// &ClientIpSources { -/// right_most_x_forwarded_for: None, -/// connection_info_ip: Some(IpAddr::from_str("203.0.113.195").unwrap()), -/// }, -/// ) -/// .unwrap(); -/// -/// assert_eq!(ip, IpAddr::from_str("203.0.113.195").unwrap()); -/// ``` -/// -/// # Errors -/// -/// Will return an error if the peer IP cannot be obtained according to the configuration. -/// For example, if the IP is extracted from an HTTP header which is missing in the request. -pub fn invoke(on_reverse_proxy: bool, client_ip_sources: &ClientIpSources) -> Result { - if on_reverse_proxy { - resolve_peer_ip_on_reverse_proxy(client_ip_sources) - } else { - resolve_peer_ip_without_reverse_proxy(client_ip_sources) - } -} - -fn resolve_peer_ip_without_reverse_proxy(remote_client_ip: &ClientIpSources) -> Result { - if let Some(ip) = remote_client_ip.connection_info_ip { - Ok(ip) - } else { - Err(PeerIpResolutionError::MissingClientIp { - location: Location::caller(), - }) - } -} - -fn resolve_peer_ip_on_reverse_proxy(remote_client_ip: &ClientIpSources) -> Result { - if let Some(ip) = remote_client_ip.right_most_x_forwarded_for { - Ok(ip) - } else { - Err(PeerIpResolutionError::MissingRightMostXForwardedForIp { - location: Location::caller(), - }) - } -} - -#[cfg(test)] -mod tests { - use super::invoke; - - mod working_without_reverse_proxy { - use std::net::IpAddr; - use std::str::FromStr; - - use super::invoke; - use crate::servers::http::v1::services::peer_ip_resolver::{ClientIpSources, PeerIpResolutionError}; - - #[test] - fn it_should_get_the_peer_ip_from_the_connection_info() { - let on_reverse_proxy = false; - - let ip = invoke( - on_reverse_proxy, - &ClientIpSources { - right_most_x_forwarded_for: None, - connection_info_ip: Some(IpAddr::from_str("203.0.113.195").unwrap()), - }, - ) - .unwrap(); - - assert_eq!(ip, IpAddr::from_str("203.0.113.195").unwrap()); - } - - #[test] - fn it_should_return_an_error_if_it_cannot_get_the_peer_ip_from_the_connection_info() { - let on_reverse_proxy = false; - - let error = invoke( - on_reverse_proxy, - &ClientIpSources { - right_most_x_forwarded_for: None, - connection_info_ip: None, - }, - ) - .unwrap_err(); - - assert!(matches!(error, PeerIpResolutionError::MissingClientIp { .. })); - } - } - - mod working_on_reverse_proxy { - use std::net::IpAddr; - use std::str::FromStr; - - use crate::servers::http::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; - - #[test] - fn it_should_get_the_peer_ip_from_the_right_most_ip_in_the_x_forwarded_for_header() { - let on_reverse_proxy = true; - - let ip = invoke( - on_reverse_proxy, - &ClientIpSources { - right_most_x_forwarded_for: Some(IpAddr::from_str("203.0.113.195").unwrap()), - connection_info_ip: None, - }, - ) - .unwrap(); - - assert_eq!(ip, IpAddr::from_str("203.0.113.195").unwrap()); - } - - #[test] - fn it_should_return_an_error_if_it_cannot_get_the_right_most_ip_from_the_x_forwarded_for_header() { - let on_reverse_proxy = true; - - let error = invoke( - on_reverse_proxy, - &ClientIpSources { - right_most_x_forwarded_for: None, - connection_info_ip: None, - }, - ) - .unwrap_err(); - - assert!(matches!(error, PeerIpResolutionError::MissingRightMostXForwardedForIp { .. })); - } - } -} diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs deleted file mode 100644 index 240680ca3..000000000 --- a/src/servers/http/v1/services/scrape.rs +++ /dev/null @@ -1,269 +0,0 @@ -//! The `scrape` service. -//! -//! The service is responsible for handling the `scrape` requests. -//! -//! It delegates the `scrape` logic to the [`Tracker`](crate::tracker::Tracker::scrape) -//! and it returns the [`ScrapeData`](crate::tracker::ScrapeData) returned -//! by the [`Tracker`](crate::tracker::Tracker). -//! -//! It also sends an [`statistics::Event`](crate::tracker::statistics::Event) -//! because events are specific for the HTTP tracker. -use std::net::IpAddr; -use std::sync::Arc; - -use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::{statistics, ScrapeData, Tracker}; - -/// The HTTP tracker `scrape` service. -/// -/// The service sends an statistics event that increments: -/// -/// - The number of TCP connections handled by the HTTP tracker. -/// - The number of TCP `scrape` requests handled by the HTTP tracker. -/// -/// > **NOTICE**: as the HTTP tracker does not requires a connection request -/// like the UDP tracker, the number of TCP connections is incremented for -/// each `scrape` request. -pub async fn invoke(tracker: &Arc, info_hashes: &Vec, original_peer_ip: &IpAddr) -> ScrapeData { - let scrape_data = tracker.scrape(info_hashes).await; - - send_scrape_event(original_peer_ip, tracker).await; - - scrape_data -} - -/// The HTTP tracker fake `scrape` service. It returns zeroed stats. -/// -/// When the peer is not authenticated and the tracker is running in `private` mode, -/// the tracker returns empty stats for all the torrents. -/// -/// > **NOTICE**: tracker statistics are not updated in this case. -pub async fn fake(tracker: &Arc, info_hashes: &Vec, original_peer_ip: &IpAddr) -> ScrapeData { - send_scrape_event(original_peer_ip, tracker).await; - - ScrapeData::zeroed(info_hashes) -} - -async fn send_scrape_event(original_peer_ip: &IpAddr, tracker: &Arc) { - match original_peer_ip { - IpAddr::V4(_) => { - tracker.send_stats_event(statistics::Event::Tcp4Scrape).await; - } - IpAddr::V6(_) => { - tracker.send_stats_event(statistics::Event::Tcp6Scrape).await; - } - } -} - -#[cfg(test)] -mod tests { - - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; - use torrust_tracker_test_helpers::configuration; - - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::shared::clock::DurationSinceUnixEpoch; - use crate::tracker::services::tracker_factory; - use crate::tracker::{peer, Tracker}; - - fn public_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_public().into()) - } - - fn sample_info_hashes() -> Vec { - vec![sample_info_hash()] - } - - fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() - } - - fn sample_peer() -> peer::Peer { - peer::Peer { - peer_id: peer::Id(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), - event: AnnounceEvent::Started, - } - } - - mod with_real_data { - - use std::future; - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; - use std::sync::Arc; - - use mockall::predicate::eq; - use torrust_tracker_test_helpers::configuration; - - use crate::servers::http::v1::services::scrape::invoke; - use crate::servers::http::v1::services::scrape::tests::{ - public_tracker, sample_info_hash, sample_info_hashes, sample_peer, - }; - use crate::tracker::torrent::SwarmMetadata; - use crate::tracker::{statistics, ScrapeData, Tracker}; - - #[tokio::test] - async fn it_should_return_the_scrape_data_for_a_torrent() { - let tracker = Arc::new(public_tracker()); - - let info_hash = sample_info_hash(); - let info_hashes = vec![info_hash]; - - // Announce a new peer to force scrape data to contain not zeroed data - let mut peer = sample_peer(); - let original_peer_ip = peer.ip(); - tracker.announce(&info_hash, &mut peer, &original_peer_ip).await; - - let scrape_data = invoke(&tracker, &info_hashes, &original_peer_ip).await; - - let mut expected_scrape_data = ScrapeData::empty(); - expected_scrape_data.add_file( - &info_hash, - SwarmMetadata { - complete: 1, - downloaded: 0, - incomplete: 0, - }, - ); - - assert_eq!(scrape_data, expected_scrape_data); - } - - #[tokio::test] - async fn it_should_send_the_tcp_4_scrape_event_when_the_peer_uses_ipv4() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::Event::Tcp4Scrape)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); - - let tracker = Arc::new( - Tracker::new( - Arc::new(configuration::ephemeral()), - Some(stats_event_sender), - statistics::Repo::new(), - ) - .unwrap(), - ); - - let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); - - invoke(&tracker, &sample_info_hashes(), &peer_ip).await; - } - - #[tokio::test] - async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::Event::Tcp6Scrape)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); - - let tracker = Arc::new( - Tracker::new( - Arc::new(configuration::ephemeral()), - Some(stats_event_sender), - statistics::Repo::new(), - ) - .unwrap(), - ); - - let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); - - invoke(&tracker, &sample_info_hashes(), &peer_ip).await; - } - } - - mod with_zeroed_data { - - use std::future; - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; - use std::sync::Arc; - - use mockall::predicate::eq; - use torrust_tracker_test_helpers::configuration; - - use crate::servers::http::v1::services::scrape::fake; - use crate::servers::http::v1::services::scrape::tests::{ - public_tracker, sample_info_hash, sample_info_hashes, sample_peer, - }; - use crate::tracker::{statistics, ScrapeData, Tracker}; - - #[tokio::test] - async fn it_should_always_return_the_zeroed_scrape_data_for_a_torrent() { - let tracker = Arc::new(public_tracker()); - - let info_hash = sample_info_hash(); - let info_hashes = vec![info_hash]; - - // Announce a new peer to force scrape data to contain not zeroed data - let mut peer = sample_peer(); - let original_peer_ip = peer.ip(); - tracker.announce(&info_hash, &mut peer, &original_peer_ip).await; - - let scrape_data = fake(&tracker, &info_hashes, &original_peer_ip).await; - - let expected_scrape_data = ScrapeData::zeroed(&info_hashes); - - assert_eq!(scrape_data, expected_scrape_data); - } - - #[tokio::test] - async fn it_should_send_the_tcp_4_scrape_event_when_the_peer_uses_ipv4() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::Event::Tcp4Scrape)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); - - let tracker = Arc::new( - Tracker::new( - Arc::new(configuration::ephemeral()), - Some(stats_event_sender), - statistics::Repo::new(), - ) - .unwrap(), - ); - - let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); - - fake(&tracker, &sample_info_hashes(), &peer_ip).await; - } - - #[tokio::test] - async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::Event::Tcp6Scrape)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); - - let tracker = Arc::new( - Tracker::new( - Arc::new(configuration::ephemeral()), - Some(stats_event_sender), - statistics::Repo::new(), - ) - .unwrap(), - ); - - let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); - - fake(&tracker, &sample_info_hashes(), &peer_ip).await; - } - } -} diff --git a/src/servers/mod.rs b/src/servers/mod.rs deleted file mode 100644 index 38b4b70cd..000000000 --- a/src/servers/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -//! Servers. Services that can be started and stopped. -pub mod apis; -pub mod http; -pub mod signals; -pub mod udp; diff --git a/src/servers/signals.rs b/src/servers/signals.rs deleted file mode 100644 index f0312b886..000000000 --- a/src/servers/signals.rs +++ /dev/null @@ -1,42 +0,0 @@ -//! This module contains functions to handle signals. -use log::info; - -/// Resolves on `ctrl_c` or the `terminate` signal. -pub async fn global_shutdown_signal() { - let ctrl_c = async { - tokio::signal::ctrl_c().await.expect("failed to install Ctrl+C handler"); - }; - - #[cfg(unix)] - let terminate = async { - tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) - .expect("failed to install signal handler") - .recv() - .await; - }; - - #[cfg(not(unix))] - let terminate = std::future::pending::<()>(); - - tokio::select! { - _ = ctrl_c => {}, - _ = terminate => {} - } -} - -/// Resolves when the `stop_receiver` or the `global_shutdown_signal()` resolves. -pub async fn shutdown_signal(stop_receiver: tokio::sync::oneshot::Receiver) { - let stop = async { stop_receiver.await.expect("Failed to install stop signal.") }; - - tokio::select! { - _ = stop => {}, - _ = global_shutdown_signal() => {} - } -} - -/// Same as `shutdown_signal()`, but shows a message when it resolves. -pub async fn shutdown_signal_with_message(stop_receiver: tokio::sync::oneshot::Receiver, message: String) { - shutdown_signal(stop_receiver).await; - - info!("{message}"); -} diff --git a/src/servers/udp/connection_cookie.rs b/src/servers/udp/connection_cookie.rs deleted file mode 100644 index a389388a7..000000000 --- a/src/servers/udp/connection_cookie.rs +++ /dev/null @@ -1,327 +0,0 @@ -//! Logic for generating and verifying connection IDs. -//! -//! The UDP tracker requires the client to connect to the server before it can -//! send any data. The server responds with a random 64-bit integer that the -//! client must use to identify itself. -//! -//! This connection ID is used to avoid spoofing attacks. The client must send -//! the connection ID in all requests to the server. The server will ignore any -//! requests that do not contain the correct connection ID. -//! -//! The simplest way to implement this would be to generate a random number when -//! the client connects and store it in a hash table. However, this would -//! require the server to store a large number of connection IDs, which would be -//! a waste of memory. Instead, the server generates a connection ID based on -//! the client's IP address and the current time. This allows the server to -//! verify the connection ID without storing it. -//! -//! This module implements this method of generating connection IDs. It's the -//! most common way to generate connection IDs. The connection ID is generated -//! using a time based algorithm and it is valid for a certain amount of time -//! (usually two minutes). The connection ID is generated using the following: -//! -//! ```text -//! connection ID = hash(client IP + current time slot + secret seed) -//! ``` -//! -//! Time slots are two minute intervals since the Unix epoch. The secret seed is -//! a random number that is generated when the server starts. And the client IP -//! is used in order generate a unique connection ID for each client. -//! -//! The BEP-15 recommends a two-minute time slot. -//! -//! ```text -//! Timestamp (seconds from Unix epoch): -//! |------------|------------|------------|------------| -//! 0 120 240 360 480 -//! Time slots (two-minutes time extents from Unix epoch): -//! |------------|------------|------------|------------| -//! 0 1 2 3 4 -//! Peer connections: -//! Peer A |-------------------------| -//! Peer B |-------------------------| -//! Peer C |------------------| -//! Peer A connects at timestamp 120 slot 1 -> connection ID will be valid from timestamp 120 to 360 -//! Peer B connects at timestamp 240 slot 2 -> connection ID will be valid from timestamp 240 to 480 -//! Peer C connects at timestamp 180 slot 1 -> connection ID will be valid from timestamp 180 to 360 -//! ``` -//! > **NOTICE**: connection ID is always the same for a given peer -//! (socket address) and time slot. -//! -//! > **NOTICE**: connection ID will be valid for two time extents, **not two -//! minutes**. It'll be valid for the the current time extent and the next one. -//! -//! Refer to [`Connect`](crate::servers::udp#connect) for more information about -//! the connection process. -//! -//! ## Advantages -//! -//! - It consumes less memory than storing a hash table of connection IDs. -//! - It's easy to implement. -//! - It's fast. -//! -//! ## Disadvantages -//! -//! - It's not very flexible. The connection ID is only valid for a certain -//! amount of time. -//! - It's not very accurate. The connection ID is valid for more than two -//! minutes. -use std::net::SocketAddr; -use std::panic::Location; - -use aquatic_udp_protocol::ConnectionId; - -use super::error::Error; -use crate::shared::clock::time_extent::{Extent, TimeExtent}; - -pub type Cookie = [u8; 8]; - -pub type SinceUnixEpochTimeExtent = TimeExtent; - -pub const COOKIE_LIFETIME: TimeExtent = TimeExtent::from_sec(2, &60); - -/// Converts a connection ID into a connection cookie. -#[must_use] -pub fn from_connection_id(connection_id: &ConnectionId) -> Cookie { - connection_id.0.to_le_bytes() -} - -/// Converts a connection cookie into a connection ID. -#[must_use] -pub fn into_connection_id(connection_cookie: &Cookie) -> ConnectionId { - ConnectionId(i64::from_le_bytes(*connection_cookie)) -} - -/// Generates a new connection cookie. -#[must_use] -pub fn make(remote_address: &SocketAddr) -> Cookie { - let time_extent = cookie_builder::get_last_time_extent(); - - //println!("remote_address: {remote_address:?}, time_extent: {time_extent:?}, cookie: {cookie:?}"); - cookie_builder::build(remote_address, &time_extent) -} - -/// Checks if the supplied `connection_cookie` is valid. -/// -/// # Panics -/// -/// It would panic if the `COOKIE_LIFETIME` constant would be an unreasonably large number. -/// -/// # Errors -/// -/// Will return a `ServerError::InvalidConnectionId` if the supplied `connection_cookie` fails to verify. -pub fn check(remote_address: &SocketAddr, connection_cookie: &Cookie) -> Result { - // we loop backwards testing each time_extent until we find one that matches. - // (or the lifetime of time_extents is exhausted) - for offset in 0..=COOKIE_LIFETIME.amount { - let checking_time_extent = cookie_builder::get_last_time_extent().decrease(offset).unwrap(); - - let checking_cookie = cookie_builder::build(remote_address, &checking_time_extent); - //println!("remote_address: {remote_address:?}, time_extent: {checking_time_extent:?}, cookie: {checking_cookie:?}"); - - if *connection_cookie == checking_cookie { - return Ok(checking_time_extent); - } - } - Err(Error::InvalidConnectionId { - location: Location::caller(), - }) -} - -mod cookie_builder { - use std::collections::hash_map::DefaultHasher; - use std::hash::{Hash, Hasher}; - use std::net::SocketAddr; - - use super::{Cookie, SinceUnixEpochTimeExtent, COOKIE_LIFETIME}; - use crate::shared::clock::time_extent::{DefaultTimeExtentMaker, Extent, Make, TimeExtent}; - use crate::shared::crypto::keys::seeds::{Current, Keeper}; - - pub(super) fn get_last_time_extent() -> SinceUnixEpochTimeExtent { - DefaultTimeExtentMaker::now(&COOKIE_LIFETIME.increment) - .unwrap() - .unwrap() - .increase(COOKIE_LIFETIME.amount) - .unwrap() - } - - pub(super) fn build(remote_address: &SocketAddr, time_extent: &TimeExtent) -> Cookie { - let seed = Current::get_seed(); - - let mut hasher = DefaultHasher::new(); - - remote_address.hash(&mut hasher); - time_extent.hash(&mut hasher); - seed.hash(&mut hasher); - - hasher.finish().to_le_bytes() - } -} - -#[cfg(test)] -mod tests { - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - - use super::cookie_builder::{self}; - use crate::servers::udp::connection_cookie::{check, make, Cookie, COOKIE_LIFETIME}; - use crate::shared::clock::time_extent::{self, Extent}; - use crate::shared::clock::{Stopped, StoppedTime}; - - // #![feature(const_socketaddr)] - // const REMOTE_ADDRESS_IPV4_ZERO: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - - #[test] - fn it_should_make_a_connection_cookie() { - // Note: This constant may need to be updated in the future as the hash is not guaranteed to to be stable between versions. - const ID_COOKIE: Cookie = [23, 204, 198, 29, 48, 180, 62, 19]; - - let cookie = make(&SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0)); - - assert_eq!(cookie, ID_COOKIE); - } - - #[test] - fn it_should_make_the_same_connection_cookie_for_the_same_input_data() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - let time_extent_zero = time_extent::ZERO; - - let cookie = cookie_builder::build(&remote_address, &time_extent_zero); - let cookie_2 = cookie_builder::build(&remote_address, &time_extent_zero); - - println!("remote_address: {remote_address:?}, time_extent: {time_extent_zero:?}, cookie: {cookie:?}"); - println!("remote_address: {remote_address:?}, time_extent: {time_extent_zero:?}, cookie: {cookie_2:?}"); - - //remote_address: 127.0.0.1:8080, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [212, 9, 204, 223, 176, 190, 150, 153] - //remote_address: 127.0.0.1:8080, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [212, 9, 204, 223, 176, 190, 150, 153] - - assert_eq!(cookie, cookie_2); - } - - #[test] - fn it_should_make_the_different_connection_cookie_for_different_ip() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - let remote_address_2 = SocketAddr::new(IpAddr::V4(Ipv4Addr::BROADCAST), 0); - let time_extent_zero = time_extent::ZERO; - - let cookie = cookie_builder::build(&remote_address, &time_extent_zero); - let cookie_2 = cookie_builder::build(&remote_address_2, &time_extent_zero); - - println!("remote_address: {remote_address:?}, time_extent: {time_extent_zero:?}, cookie: {cookie:?}"); - println!("remote_address: {remote_address_2:?}, time_extent: {time_extent_zero:?}, cookie: {cookie_2:?}"); - - //remote_address: 0.0.0.0:0, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [151, 130, 30, 157, 190, 41, 179, 135] - //remote_address: 255.255.255.255:0, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [217, 87, 239, 178, 182, 126, 66, 166] - - assert_ne!(cookie, cookie_2); - } - - #[test] - fn it_should_make_the_different_connection_cookie_for_different_ip_version() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - let remote_address_2 = SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0); - let time_extent_zero = time_extent::ZERO; - - let cookie = cookie_builder::build(&remote_address, &time_extent_zero); - let cookie_2 = cookie_builder::build(&remote_address_2, &time_extent_zero); - - println!("remote_address: {remote_address:?}, time_extent: {time_extent_zero:?}, cookie: {cookie:?}"); - println!("remote_address: {remote_address_2:?}, time_extent: {time_extent_zero:?}, cookie: {cookie_2:?}"); - - //remote_address: 0.0.0.0:0, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [151, 130, 30, 157, 190, 41, 179, 135] - //remote_address: [::]:0, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [99, 119, 230, 177, 20, 220, 163, 187] - - assert_ne!(cookie, cookie_2); - } - - #[test] - fn it_should_make_the_different_connection_cookie_for_different_socket() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - let remote_address_2 = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 1); - let time_extent_zero = time_extent::ZERO; - - let cookie = cookie_builder::build(&remote_address, &time_extent_zero); - let cookie_2 = cookie_builder::build(&remote_address_2, &time_extent_zero); - - println!("remote_address: {remote_address:?}, time_extent: {time_extent_zero:?}, cookie: {cookie:?}"); - println!("remote_address: {remote_address_2:?}, time_extent: {time_extent_zero:?}, cookie: {cookie_2:?}"); - - //remote_address: 0.0.0.0:0, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [151, 130, 30, 157, 190, 41, 179, 135] - //remote_address: 0.0.0.0:1, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [38, 8, 0, 102, 92, 170, 220, 11] - - assert_ne!(cookie, cookie_2); - } - - #[test] - fn it_should_make_the_different_connection_cookie_for_different_time_extents() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - let time_extent_zero = time_extent::ZERO; - let time_extent_max = time_extent::MAX; - - let cookie = cookie_builder::build(&remote_address, &time_extent_zero); - let cookie_2 = cookie_builder::build(&remote_address, &time_extent_max); - - println!("remote_address: {remote_address:?}, time_extent: {time_extent_zero:?}, cookie: {cookie:?}"); - println!("remote_address: {remote_address:?}, time_extent: {time_extent_max:?}, cookie: {cookie_2:?}"); - - //remote_address: 0.0.0.0:0, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [151, 130, 30, 157, 190, 41, 179, 135] - //remote_address: 0.0.0.0:0, time_extent: TimeExtent { increment: 18446744073709551615.999999999s, amount: 18446744073709551615 }, cookie: [87, 111, 109, 125, 182, 206, 3, 201] - - assert_ne!(cookie, cookie_2); - } - - #[test] - fn it_should_make_different_cookies_for_the_next_time_extent() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - - let cookie = make(&remote_address); - - Stopped::local_add(&COOKIE_LIFETIME.increment).unwrap(); - - let cookie_next = make(&remote_address); - - assert_ne!(cookie, cookie_next); - } - - #[test] - fn it_should_be_valid_for_this_time_extent() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - - let cookie = make(&remote_address); - - check(&remote_address, &cookie).unwrap(); - } - - #[test] - fn it_should_be_valid_for_the_next_time_extent() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - - let cookie = make(&remote_address); - - Stopped::local_add(&COOKIE_LIFETIME.increment).unwrap(); - - check(&remote_address, &cookie).unwrap(); - } - - #[test] - fn it_should_be_valid_for_the_last_time_extent() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - - let cookie = make(&remote_address); - - Stopped::local_set(&COOKIE_LIFETIME.total().unwrap().unwrap()); - - check(&remote_address, &cookie).unwrap(); - } - - #[test] - #[should_panic] - fn it_should_be_not_valid_after_their_last_time_extent() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - - let cookie = make(&remote_address); - - Stopped::local_set(&COOKIE_LIFETIME.total_next().unwrap().unwrap()); - - check(&remote_address, &cookie).unwrap(); - } -} diff --git a/src/servers/udp/error.rs b/src/servers/udp/error.rs deleted file mode 100644 index ce59cd015..000000000 --- a/src/servers/udp/error.rs +++ /dev/null @@ -1,32 +0,0 @@ -//! Error types for the UDP server. -use std::panic::Location; - -use thiserror::Error; -use torrust_tracker_located_error::LocatedError; - -/// Error returned by the UDP server. -#[derive(Error, Debug)] -pub enum Error { - /// Error returned when the domain tracker returns an error. - #[error("tracker server error: {source}")] - TrackerError { - source: LocatedError<'static, dyn std::error::Error + Send + Sync>, - }, - - /// Error returned from a third-party library (aquatic_udp_protocol). - #[error("internal server error: {message}, {location}")] - InternalServer { - location: &'static Location<'static>, - message: String, - }, - - /// Error returned when the connection id could not be verified. - #[error("connection id could not be verified")] - InvalidConnectionId { location: &'static Location<'static> }, - - /// Error returned when the request is invalid. - #[error("bad request: {source}")] - BadRequest { - source: LocatedError<'static, dyn std::error::Error + Send + Sync>, - }, -} diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs deleted file mode 100644 index e94e0292f..000000000 --- a/src/servers/udp/handlers.rs +++ /dev/null @@ -1,1295 +0,0 @@ -//! Handlers for the UDP server. -use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; -use std::panic::Location; -use std::sync::Arc; - -use aquatic_udp_protocol::{ - AnnounceInterval, AnnounceRequest, AnnounceResponse, ConnectRequest, ConnectResponse, ErrorResponse, NumberOfDownloads, - NumberOfPeers, Port, Request, Response, ResponsePeer, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, -}; -use log::debug; - -use super::connection_cookie::{check, from_connection_id, into_connection_id, make}; -use crate::servers::udp::error::Error; -use crate::servers::udp::peer_builder; -use crate::servers::udp::request::AnnounceWrapper; -use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; -use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::{statistics, Tracker}; - -/// It handles the incoming UDP packets. -/// -/// It's responsible for: -/// -/// - Parsing the incoming packet. -/// - Delegating the request to the correct handler depending on the request -/// type. -/// -/// It will return an `Error` response if the request is invalid. -pub async fn handle_packet(remote_addr: SocketAddr, payload: Vec, tracker: &Tracker) -> Response { - match Request::from_bytes(&payload[..payload.len()], MAX_SCRAPE_TORRENTS).map_err(|e| Error::InternalServer { - message: format!("{e:?}"), - location: Location::caller(), - }) { - Ok(request) => { - let transaction_id = match &request { - Request::Connect(connect_request) => connect_request.transaction_id, - Request::Announce(announce_request) => announce_request.transaction_id, - Request::Scrape(scrape_request) => scrape_request.transaction_id, - }; - - match handle_request(request, remote_addr, tracker).await { - Ok(response) => response, - Err(e) => handle_error(&e, transaction_id), - } - } - // bad request - Err(e) => handle_error( - &Error::BadRequest { - source: (Arc::new(e) as Arc).into(), - }, - TransactionId(0), - ), - } -} - -/// It dispatches the request to the correct handler. -/// -/// # Errors -/// -/// If a error happens in the `handle_request` function, it will just return the `ServerError`. -pub async fn handle_request(request: Request, remote_addr: SocketAddr, tracker: &Tracker) -> Result { - match request { - Request::Connect(connect_request) => handle_connect(remote_addr, &connect_request, tracker).await, - Request::Announce(announce_request) => handle_announce(remote_addr, &announce_request, tracker).await, - Request::Scrape(scrape_request) => handle_scrape(remote_addr, &scrape_request, tracker).await, - } -} - -/// It handles the `Connect` request. Refer to [`Connect`](crate::servers::udp#connect) -/// request for more information. -/// -/// # Errors -/// -/// This function does not ever return an error. -pub async fn handle_connect(remote_addr: SocketAddr, request: &ConnectRequest, tracker: &Tracker) -> Result { - debug!("udp connect request: {:#?}", request); - - let connection_cookie = make(&remote_addr); - let connection_id = into_connection_id(&connection_cookie); - - let response = ConnectResponse { - transaction_id: request.transaction_id, - connection_id, - }; - - debug!("udp connect response: {:#?}", response); - - // send stats event - match remote_addr { - SocketAddr::V4(_) => { - tracker.send_stats_event(statistics::Event::Udp4Connect).await; - } - SocketAddr::V6(_) => { - tracker.send_stats_event(statistics::Event::Udp6Connect).await; - } - } - - Ok(Response::from(response)) -} - -/// It authenticates the request. It returns an error if the peer is not allowed -/// to make the request. -/// -/// # Errors -/// -/// Will return `Error` if unable to `authenticate_request`. -pub async fn authenticate(info_hash: &InfoHash, tracker: &Tracker) -> Result<(), Error> { - tracker - .authenticate_request(info_hash, &None) - .await - .map_err(|e| Error::TrackerError { - source: (Arc::new(e) as Arc).into(), - }) -} - -/// It handles the `Announce` request. Refer to [`Announce`](crate::servers::udp#announce) -/// request for more information. -/// -/// # Errors -/// -/// If a error happens in the `handle_announce` function, it will just return the `ServerError`. -pub async fn handle_announce( - remote_addr: SocketAddr, - announce_request: &AnnounceRequest, - tracker: &Tracker, -) -> Result { - debug!("udp announce request: {:#?}", announce_request); - - check(&remote_addr, &from_connection_id(&announce_request.connection_id))?; - - let wrapped_announce_request = AnnounceWrapper::new(announce_request); - - let info_hash = wrapped_announce_request.info_hash; - let remote_client_ip = remote_addr.ip(); - - authenticate(&info_hash, tracker).await?; - - let mut peer = peer_builder::from_request(&wrapped_announce_request, &remote_client_ip); - - let response = tracker.announce(&info_hash, &mut peer, &remote_client_ip).await; - - match remote_client_ip { - IpAddr::V4(_) => { - tracker.send_stats_event(statistics::Event::Udp4Announce).await; - } - IpAddr::V6(_) => { - tracker.send_stats_event(statistics::Event::Udp6Announce).await; - } - } - - #[allow(clippy::cast_possible_truncation)] - if remote_addr.is_ipv4() { - let announce_response = AnnounceResponse { - transaction_id: wrapped_announce_request.announce_request.transaction_id, - announce_interval: AnnounceInterval(i64::from(tracker.config.announce_interval) as i32), - leechers: NumberOfPeers(i64::from(response.swarm_stats.leechers) as i32), - seeders: NumberOfPeers(i64::from(response.swarm_stats.seeders) as i32), - peers: response - .peers - .iter() - .filter_map(|peer| { - if let IpAddr::V4(ip) = peer.peer_addr.ip() { - Some(ResponsePeer:: { - ip_address: ip, - port: Port(peer.peer_addr.port()), - }) - } else { - None - } - }) - .collect(), - }; - - debug!("udp announce response: {:#?}", announce_response); - - Ok(Response::from(announce_response)) - } else { - let announce_response = AnnounceResponse { - transaction_id: wrapped_announce_request.announce_request.transaction_id, - announce_interval: AnnounceInterval(i64::from(tracker.config.announce_interval) as i32), - leechers: NumberOfPeers(i64::from(response.swarm_stats.leechers) as i32), - seeders: NumberOfPeers(i64::from(response.swarm_stats.seeders) as i32), - peers: response - .peers - .iter() - .filter_map(|peer| { - if let IpAddr::V6(ip) = peer.peer_addr.ip() { - Some(ResponsePeer:: { - ip_address: ip, - port: Port(peer.peer_addr.port()), - }) - } else { - None - } - }) - .collect(), - }; - - debug!("udp announce response: {:#?}", announce_response); - - Ok(Response::from(announce_response)) - } -} - -/// It handles the `Scrape` request. Refer to [`Scrape`](crate::servers::udp#scrape) -/// request for more information. -/// -/// # Errors -/// -/// This function does not ever return an error. -pub async fn handle_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tracker: &Tracker) -> Result { - debug!("udp scrape request: {:#?}", request); - - // Convert from aquatic infohashes - let mut info_hashes = vec![]; - for info_hash in &request.info_hashes { - info_hashes.push(InfoHash(info_hash.0)); - } - - let scrape_data = tracker.scrape(&info_hashes).await; - - let mut torrent_stats: Vec = Vec::new(); - - for file in &scrape_data.files { - let info_hash = file.0; - let swarm_metadata = file.1; - - let scrape_entry = if tracker.authenticate_request(info_hash, &None).await.is_ok() { - #[allow(clippy::cast_possible_truncation)] - TorrentScrapeStatistics { - seeders: NumberOfPeers(i64::from(swarm_metadata.complete) as i32), - completed: NumberOfDownloads(i64::from(swarm_metadata.downloaded) as i32), - leechers: NumberOfPeers(i64::from(swarm_metadata.incomplete) as i32), - } - } else { - TorrentScrapeStatistics { - seeders: NumberOfPeers(0), - completed: NumberOfDownloads(0), - leechers: NumberOfPeers(0), - } - }; - - torrent_stats.push(scrape_entry); - } - - // send stats event - match remote_addr { - SocketAddr::V4(_) => { - tracker.send_stats_event(statistics::Event::Udp4Scrape).await; - } - SocketAddr::V6(_) => { - tracker.send_stats_event(statistics::Event::Udp6Scrape).await; - } - } - - let response = ScrapeResponse { - transaction_id: request.transaction_id, - torrent_stats, - }; - - debug!("udp scrape response: {:#?}", response); - - Ok(Response::from(response)) -} - -fn handle_error(e: &Error, transaction_id: TransactionId) -> Response { - let message = e.to_string(); - Response::from(ErrorResponse { - transaction_id, - message: message.into(), - }) -} - -#[cfg(test)] -mod tests { - - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - use std::sync::Arc; - - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; - use torrust_tracker_configuration::Configuration; - use torrust_tracker_test_helpers::configuration; - - use crate::shared::clock::{Current, Time}; - use crate::tracker::services::tracker_factory; - use crate::tracker::{peer, Tracker}; - - fn tracker_configuration() -> Arc { - Arc::new(default_testing_tracker_configuration()) - } - - fn default_testing_tracker_configuration() -> Configuration { - configuration::ephemeral() - } - - fn public_tracker() -> Arc { - initialized_tracker(configuration::ephemeral_mode_public().into()) - } - - fn private_tracker() -> Arc { - initialized_tracker(configuration::ephemeral_mode_private().into()) - } - - fn whitelisted_tracker() -> Arc { - initialized_tracker(configuration::ephemeral_mode_whitelisted().into()) - } - - fn initialized_tracker(configuration: Arc) -> Arc { - tracker_factory(configuration).into() - } - - fn sample_ipv4_remote_addr() -> SocketAddr { - sample_ipv4_socket_address() - } - - fn sample_ipv6_remote_addr() -> SocketAddr { - sample_ipv6_socket_address() - } - - fn sample_ipv4_socket_address() -> SocketAddr { - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) - } - - fn sample_ipv6_socket_address() -> SocketAddr { - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) - } - - struct TorrentPeerBuilder { - peer: peer::Peer, - } - - impl TorrentPeerBuilder { - pub fn default() -> TorrentPeerBuilder { - let default_peer = peer::Peer { - peer_id: peer::Id([255u8; 20]), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: Current::now(), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), - event: AnnounceEvent::Started, - }; - TorrentPeerBuilder { peer: default_peer } - } - - pub fn with_peer_id(mut self, peer_id: peer::Id) -> Self { - self.peer.peer_id = peer_id; - self - } - - pub fn with_peer_addr(mut self, peer_addr: SocketAddr) -> Self { - self.peer.peer_addr = peer_addr; - self - } - - pub fn with_bytes_left(mut self, left: i64) -> Self { - self.peer.left = NumberOfBytes(left); - self - } - - pub fn into(self) -> peer::Peer { - self.peer - } - } - - struct TrackerConfigurationBuilder { - configuration: Configuration, - } - - impl TrackerConfigurationBuilder { - pub fn default() -> TrackerConfigurationBuilder { - let default_configuration = default_testing_tracker_configuration(); - TrackerConfigurationBuilder { - configuration: default_configuration, - } - } - - pub fn with_external_ip(mut self, external_ip: &str) -> Self { - self.configuration.external_ip = Some(external_ip.to_owned()); - self - } - - pub fn into(self) -> Configuration { - self.configuration - } - } - - mod connect_request { - - use std::future; - use std::sync::Arc; - - use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response, TransactionId}; - use mockall::predicate::eq; - - use super::{sample_ipv4_socket_address, sample_ipv6_remote_addr, tracker_configuration}; - use crate::servers::udp::connection_cookie::{into_connection_id, make}; - use crate::servers::udp::handlers::handle_connect; - use crate::servers::udp::handlers::tests::{public_tracker, sample_ipv4_remote_addr}; - use crate::tracker::{self, statistics}; - - fn sample_connect_request() -> ConnectRequest { - ConnectRequest { - transaction_id: TransactionId(0i32), - } - } - - #[tokio::test] - async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { - let request = ConnectRequest { - transaction_id: TransactionId(0i32), - }; - - let response = handle_connect(sample_ipv4_remote_addr(), &request, &public_tracker()) - .await - .unwrap(); - - assert_eq!( - response, - Response::Connect(ConnectResponse { - connection_id: into_connection_id(&make(&sample_ipv4_remote_addr())), - transaction_id: request.transaction_id - }) - ); - } - - #[tokio::test] - async fn a_connect_response_should_contain_a_new_connection_id() { - let request = ConnectRequest { - transaction_id: TransactionId(0i32), - }; - - let response = handle_connect(sample_ipv4_remote_addr(), &request, &public_tracker()) - .await - .unwrap(); - - assert_eq!( - response, - Response::Connect(ConnectResponse { - connection_id: into_connection_id(&make(&sample_ipv4_remote_addr())), - transaction_id: request.transaction_id - }) - ); - } - - #[tokio::test] - async fn it_should_send_the_upd4_connect_event_when_a_client_tries_to_connect_using_a_ip4_socket_address() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::Event::Udp4Connect)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); - - let client_socket_address = sample_ipv4_socket_address(); - - let torrent_tracker = Arc::new( - tracker::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), - ); - handle_connect(client_socket_address, &sample_connect_request(), &torrent_tracker) - .await - .unwrap(); - } - - #[tokio::test] - async fn it_should_send_the_upd6_connect_event_when_a_client_tries_to_connect_using_a_ip6_socket_address() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::Event::Udp6Connect)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); - - let torrent_tracker = Arc::new( - tracker::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), - ); - handle_connect(sample_ipv6_remote_addr(), &sample_connect_request(), &torrent_tracker) - .await - .unwrap(); - } - } - - mod announce_request { - - use std::net::Ipv4Addr; - - use aquatic_udp_protocol::{ - AnnounceEvent, AnnounceRequest, ConnectionId, NumberOfBytes, NumberOfPeers, PeerId as AquaticPeerId, PeerKey, Port, - TransactionId, - }; - - use crate::servers::udp::connection_cookie::{into_connection_id, make}; - use crate::servers::udp::handlers::tests::sample_ipv4_remote_addr; - - struct AnnounceRequestBuilder { - request: AnnounceRequest, - } - - impl AnnounceRequestBuilder { - pub fn default() -> AnnounceRequestBuilder { - let client_ip = Ipv4Addr::new(126, 0, 0, 1); - let client_port = 8080; - let info_hash_aquatic = aquatic_udp_protocol::InfoHash([0u8; 20]); - - let default_request = AnnounceRequest { - connection_id: into_connection_id(&make(&sample_ipv4_remote_addr())), - transaction_id: TransactionId(0i32), - info_hash: info_hash_aquatic, - peer_id: AquaticPeerId([255u8; 20]), - bytes_downloaded: NumberOfBytes(0i64), - bytes_uploaded: NumberOfBytes(0i64), - bytes_left: NumberOfBytes(0i64), - event: AnnounceEvent::Started, - ip_address: Some(client_ip), - key: PeerKey(0u32), - peers_wanted: NumberOfPeers(1i32), - port: Port(client_port), - }; - AnnounceRequestBuilder { - request: default_request, - } - } - - pub fn with_connection_id(mut self, connection_id: ConnectionId) -> Self { - self.request.connection_id = connection_id; - self - } - - pub fn with_info_hash(mut self, info_hash: aquatic_udp_protocol::InfoHash) -> Self { - self.request.info_hash = info_hash; - self - } - - pub fn with_peer_id(mut self, peer_id: AquaticPeerId) -> Self { - self.request.peer_id = peer_id; - self - } - - pub fn with_ip_address(mut self, ip_address: Ipv4Addr) -> Self { - self.request.ip_address = Some(ip_address); - self - } - - pub fn with_port(mut self, port: u16) -> Self { - self.request.port = Port(port); - self - } - - pub fn into(self) -> AnnounceRequest { - self.request - } - } - - mod using_ipv4 { - - use std::future; - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - use std::sync::Arc; - - use aquatic_udp_protocol::{ - AnnounceInterval, AnnounceResponse, InfoHash as AquaticInfoHash, NumberOfPeers, PeerId as AquaticPeerId, - Response, ResponsePeer, - }; - use mockall::predicate::eq; - - use crate::servers::udp::connection_cookie::{into_connection_id, make}; - use crate::servers::udp::handlers::handle_announce; - use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; - use crate::servers::udp::handlers::tests::{ - public_tracker, sample_ipv4_socket_address, tracker_configuration, TorrentPeerBuilder, - }; - use crate::tracker::{self, peer, statistics}; - - #[tokio::test] - async fn an_announced_peer_should_be_added_to_the_tracker() { - let tracker = public_tracker(); - - let client_ip = Ipv4Addr::new(126, 0, 0, 1); - let client_port = 8080; - let info_hash = AquaticInfoHash([0u8; 20]); - let peer_id = AquaticPeerId([255u8; 20]); - - let remote_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); - - let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) - .with_info_hash(info_hash) - .with_peer_id(peer_id) - .with_ip_address(client_ip) - .with_port(client_port) - .into(); - - handle_announce(remote_addr, &request, &tracker).await.unwrap(); - - let peers = tracker.get_all_torrent_peers(&info_hash.0.into()).await; - - let expected_peer = TorrentPeerBuilder::default() - .with_peer_id(peer::Id(peer_id.0)) - .with_peer_addr(SocketAddr::new(IpAddr::V4(client_ip), client_port)) - .into(); - - assert_eq!(peers[0], expected_peer); - } - - #[tokio::test] - async fn the_announced_peer_should_not_be_included_in_the_response() { - let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); - - let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) - .into(); - - let response = handle_announce(remote_addr, &request, &public_tracker()).await.unwrap(); - - let empty_peer_vector: Vec> = vec![]; - assert_eq!( - response, - Response::from(AnnounceResponse { - transaction_id: request.transaction_id, - announce_interval: AnnounceInterval(120i32), - leechers: NumberOfPeers(0i32), - seeders: NumberOfPeers(1i32), - peers: empty_peer_vector - }) - ); - } - - #[tokio::test] - async fn the_tracker_should_always_use_the_remote_client_ip_but_not_the_port_in_the_udp_request_header_instead_of_the_peer_address_in_the_announce_request( - ) { - // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): - // "Do note that most trackers will only honor the IP address field under limited circumstances." - - let tracker = public_tracker(); - - let info_hash = AquaticInfoHash([0u8; 20]); - let peer_id = AquaticPeerId([255u8; 20]); - let client_port = 8080; - - let remote_client_ip = Ipv4Addr::new(126, 0, 0, 1); - let remote_client_port = 8081; - let peer_address = Ipv4Addr::new(126, 0, 0, 2); - - let remote_addr = SocketAddr::new(IpAddr::V4(remote_client_ip), remote_client_port); - - let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) - .with_info_hash(info_hash) - .with_peer_id(peer_id) - .with_ip_address(peer_address) - .with_port(client_port) - .into(); - - handle_announce(remote_addr, &request, &tracker).await.unwrap(); - - let peers = tracker.get_all_torrent_peers(&info_hash.0.into()).await; - - assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V4(remote_client_ip), client_port)); - } - - async fn add_a_torrent_peer_using_ipv6(tracker: Arc) { - let info_hash = AquaticInfoHash([0u8; 20]); - - let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); - let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); - let client_port = 8080; - let peer_id = AquaticPeerId([255u8; 20]); - - let peer_using_ipv6 = TorrentPeerBuilder::default() - .with_peer_id(peer::Id(peer_id.0)) - .with_peer_addr(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) - .into(); - - tracker - .update_torrent_with_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv6) - .await; - } - - async fn announce_a_new_peer_using_ipv4(tracker: Arc) -> Response { - let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); - let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) - .into(); - - handle_announce(remote_addr, &request, &tracker).await.unwrap() - } - - #[tokio::test] - async fn when_the_announce_request_comes_from_a_client_using_ipv4_the_response_should_not_include_peers_using_ipv6() { - let tracker = public_tracker(); - - add_a_torrent_peer_using_ipv6(tracker.clone()).await; - - let response = announce_a_new_peer_using_ipv4(tracker.clone()).await; - - // The response should not contain the peer using IPV6 - let peers: Option>> = match response { - Response::AnnounceIpv6(announce_response) => Some(announce_response.peers), - _ => None, - }; - let no_ipv6_peers = peers.is_none(); - assert!(no_ipv6_peers); - } - - #[tokio::test] - async fn should_send_the_upd4_announce_event() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::Event::Udp4Announce)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); - - let tracker = Arc::new( - tracker::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), - ); - - handle_announce( - sample_ipv4_socket_address(), - &AnnounceRequestBuilder::default().into(), - &tracker, - ) - .await - .unwrap(); - } - - mod from_a_loopback_ip { - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - - use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; - - use crate::servers::udp::connection_cookie::{into_connection_id, make}; - use crate::servers::udp::handlers::handle_announce; - use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; - use crate::servers::udp::handlers::tests::{public_tracker, TorrentPeerBuilder}; - use crate::tracker::peer; - - #[tokio::test] - async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration_if_defined() { - let tracker = public_tracker(); - - let client_ip = Ipv4Addr::new(127, 0, 0, 1); - let client_port = 8080; - let info_hash = AquaticInfoHash([0u8; 20]); - let peer_id = AquaticPeerId([255u8; 20]); - - let remote_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); - - let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) - .with_info_hash(info_hash) - .with_peer_id(peer_id) - .with_ip_address(client_ip) - .with_port(client_port) - .into(); - - handle_announce(remote_addr, &request, &tracker).await.unwrap(); - - let peers = tracker.get_all_torrent_peers(&info_hash.0.into()).await; - - let external_ip_in_tracker_configuration = - tracker.config.external_ip.clone().unwrap().parse::().unwrap(); - - let expected_peer = TorrentPeerBuilder::default() - .with_peer_id(peer::Id(peer_id.0)) - .with_peer_addr(SocketAddr::new(IpAddr::V4(external_ip_in_tracker_configuration), client_port)) - .into(); - - assert_eq!(peers[0], expected_peer); - } - } - } - - mod using_ipv6 { - - use std::future; - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - use std::sync::Arc; - - use aquatic_udp_protocol::{ - AnnounceInterval, AnnounceResponse, InfoHash as AquaticInfoHash, NumberOfPeers, PeerId as AquaticPeerId, - Response, ResponsePeer, - }; - use mockall::predicate::eq; - - use crate::servers::udp::connection_cookie::{into_connection_id, make}; - use crate::servers::udp::handlers::handle_announce; - use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; - use crate::servers::udp::handlers::tests::{ - public_tracker, sample_ipv6_remote_addr, tracker_configuration, TorrentPeerBuilder, - }; - use crate::tracker::{self, peer, statistics}; - - #[tokio::test] - async fn an_announced_peer_should_be_added_to_the_tracker() { - let tracker = public_tracker(); - - let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); - let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); - let client_port = 8080; - let info_hash = AquaticInfoHash([0u8; 20]); - let peer_id = AquaticPeerId([255u8; 20]); - - let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); - - let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) - .with_info_hash(info_hash) - .with_peer_id(peer_id) - .with_ip_address(client_ip_v4) - .with_port(client_port) - .into(); - - handle_announce(remote_addr, &request, &tracker).await.unwrap(); - - let peers = tracker.get_all_torrent_peers(&info_hash.0.into()).await; - - let expected_peer = TorrentPeerBuilder::default() - .with_peer_id(peer::Id(peer_id.0)) - .with_peer_addr(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) - .into(); - - assert_eq!(peers[0], expected_peer); - } - - #[tokio::test] - async fn the_announced_peer_should_not_be_included_in_the_response() { - let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); - let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); - - let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), 8080); - - let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) - .into(); - - let response = handle_announce(remote_addr, &request, &public_tracker()).await.unwrap(); - - let empty_peer_vector: Vec> = vec![]; - assert_eq!( - response, - Response::from(AnnounceResponse { - transaction_id: request.transaction_id, - announce_interval: AnnounceInterval(120i32), - leechers: NumberOfPeers(0i32), - seeders: NumberOfPeers(1i32), - peers: empty_peer_vector - }) - ); - } - - #[tokio::test] - async fn the_tracker_should_always_use_the_remote_client_ip_but_not_the_port_in_the_udp_request_header_instead_of_the_peer_address_in_the_announce_request( - ) { - // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): - // "Do note that most trackers will only honor the IP address field under limited circumstances." - - let tracker = public_tracker(); - - let info_hash = AquaticInfoHash([0u8; 20]); - let peer_id = AquaticPeerId([255u8; 20]); - let client_port = 8080; - - let remote_client_ip = "::100".parse().unwrap(); // IPV4 ::0.0.1.0 -> IPV6 = ::100 = ::ffff:0:100 = 0:0:0:0:0:ffff:0:0100 - let remote_client_port = 8081; - let peer_address = "126.0.0.1".parse().unwrap(); - - let remote_addr = SocketAddr::new(IpAddr::V6(remote_client_ip), remote_client_port); - - let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) - .with_info_hash(info_hash) - .with_peer_id(peer_id) - .with_ip_address(peer_address) - .with_port(client_port) - .into(); - - handle_announce(remote_addr, &request, &tracker).await.unwrap(); - - let peers = tracker.get_all_torrent_peers(&info_hash.0.into()).await; - - // When using IPv6 the tracker converts the remote client ip into a IPv4 address - assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V6(remote_client_ip), client_port)); - } - - async fn add_a_torrent_peer_using_ipv4(tracker: Arc) { - let info_hash = AquaticInfoHash([0u8; 20]); - - let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); - let client_port = 8080; - let peer_id = AquaticPeerId([255u8; 20]); - - let peer_using_ipv4 = TorrentPeerBuilder::default() - .with_peer_id(peer::Id(peer_id.0)) - .with_peer_addr(SocketAddr::new(IpAddr::V4(client_ip_v4), client_port)) - .into(); - - tracker - .update_torrent_with_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv4) - .await; - } - - async fn announce_a_new_peer_using_ipv6(tracker: Arc) -> Response { - let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); - let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); - let client_port = 8080; - let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); - let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) - .into(); - - handle_announce(remote_addr, &request, &tracker).await.unwrap() - } - - #[tokio::test] - async fn when_the_announce_request_comes_from_a_client_using_ipv6_the_response_should_not_include_peers_using_ipv4() { - let tracker = public_tracker(); - - add_a_torrent_peer_using_ipv4(tracker.clone()).await; - - let response = announce_a_new_peer_using_ipv6(tracker.clone()).await; - - // The response should not contain the peer using IPV4 - let peers: Option>> = match response { - Response::AnnounceIpv4(announce_response) => Some(announce_response.peers), - _ => None, - }; - let no_ipv4_peers = peers.is_none(); - assert!(no_ipv4_peers); - } - - #[tokio::test] - async fn should_send_the_upd6_announce_event() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::Event::Udp6Announce)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); - - let tracker = Arc::new( - tracker::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), - ); - - let remote_addr = sample_ipv6_remote_addr(); - - let announce_request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) - .into(); - - handle_announce(remote_addr, &announce_request, &tracker).await.unwrap(); - } - - mod from_a_loopback_ip { - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - use std::sync::Arc; - - use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; - - use crate::servers::udp::connection_cookie::{into_connection_id, make}; - use crate::servers::udp::handlers::handle_announce; - use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; - use crate::servers::udp::handlers::tests::TrackerConfigurationBuilder; - use crate::tracker; - use crate::tracker::statistics::Keeper; - - #[tokio::test] - async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { - let configuration = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); - let (stats_event_sender, stats_repository) = Keeper::new_active_instance(); - let tracker = - Arc::new(tracker::Tracker::new(configuration, Some(stats_event_sender), stats_repository).unwrap()); - - let loopback_ipv4 = Ipv4Addr::new(127, 0, 0, 1); - let loopback_ipv6 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); - - let client_ip_v4 = loopback_ipv4; - let client_ip_v6 = loopback_ipv6; - let client_port = 8080; - - let info_hash = AquaticInfoHash([0u8; 20]); - let peer_id = AquaticPeerId([255u8; 20]); - - let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); - - let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) - .with_info_hash(info_hash) - .with_peer_id(peer_id) - .with_ip_address(client_ip_v4) - .with_port(client_port) - .into(); - - handle_announce(remote_addr, &request, &tracker).await.unwrap(); - - let peers = tracker.get_all_torrent_peers(&info_hash.0.into()).await; - - let _external_ip_in_tracker_configuration = - tracker.config.external_ip.clone().unwrap().parse::().unwrap(); - - // There's a special type of IPv6 addresses that provide compatibility with IPv4. - // The last 32 bits of these addresses represent an IPv4, and are represented like this: - // 1111:2222:3333:4444:5555:6666:1.2.3.4 - // - // ::127.0.0.1 is the IPV6 representation for the IPV4 address 127.0.0.1. - assert_eq!(Ok(peers[0].peer_addr.ip()), "::126.0.0.1".parse()); - } - } - } - } - - mod scrape_request { - use std::net::SocketAddr; - use std::sync::Arc; - - use aquatic_udp_protocol::{ - InfoHash, NumberOfDownloads, NumberOfPeers, Response, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, - TransactionId, - }; - - use super::TorrentPeerBuilder; - use crate::servers::udp::connection_cookie::{into_connection_id, make}; - use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::tests::{public_tracker, sample_ipv4_remote_addr}; - use crate::tracker::{self, peer}; - - fn zeroed_torrent_statistics() -> TorrentScrapeStatistics { - TorrentScrapeStatistics { - seeders: NumberOfPeers(0), - completed: NumberOfDownloads(0), - leechers: NumberOfPeers(0), - } - } - - #[tokio::test] - async fn should_return_no_stats_when_the_tracker_does_not_have_any_torrent() { - let remote_addr = sample_ipv4_remote_addr(); - - let info_hash = InfoHash([0u8; 20]); - let info_hashes = vec![info_hash]; - - let request = ScrapeRequest { - connection_id: into_connection_id(&make(&remote_addr)), - transaction_id: TransactionId(0i32), - info_hashes, - }; - - let response = handle_scrape(remote_addr, &request, &public_tracker()).await.unwrap(); - - let expected_torrent_stats = vec![zeroed_torrent_statistics()]; - - assert_eq!( - response, - Response::from(ScrapeResponse { - transaction_id: request.transaction_id, - torrent_stats: expected_torrent_stats - }) - ); - } - - async fn add_a_seeder(tracker: Arc, remote_addr: &SocketAddr, info_hash: &InfoHash) { - let peer_id = peer::Id([255u8; 20]); - - let peer = TorrentPeerBuilder::default() - .with_peer_id(peer::Id(peer_id.0)) - .with_peer_addr(*remote_addr) - .with_bytes_left(0) - .into(); - - tracker - .update_torrent_with_peer_and_get_stats(&info_hash.0.into(), &peer) - .await; - } - - fn build_scrape_request(remote_addr: &SocketAddr, info_hash: &InfoHash) -> ScrapeRequest { - let info_hashes = vec![*info_hash]; - - ScrapeRequest { - connection_id: into_connection_id(&make(remote_addr)), - transaction_id: TransactionId(0i32), - info_hashes, - } - } - - async fn add_a_sample_seeder_and_scrape(tracker: Arc) -> Response { - let remote_addr = sample_ipv4_remote_addr(); - let info_hash = InfoHash([0u8; 20]); - - add_a_seeder(tracker.clone(), &remote_addr, &info_hash).await; - - let request = build_scrape_request(&remote_addr, &info_hash); - - handle_scrape(remote_addr, &request, &tracker).await.unwrap() - } - - fn match_scrape_response(response: Response) -> Option { - match response { - Response::Scrape(scrape_response) => Some(scrape_response), - _ => None, - } - } - - mod with_a_public_tracker { - use aquatic_udp_protocol::{NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; - - use crate::servers::udp::handlers::tests::public_tracker; - use crate::servers::udp::handlers::tests::scrape_request::{add_a_sample_seeder_and_scrape, match_scrape_response}; - - #[tokio::test] - async fn should_return_torrent_statistics_when_the_tracker_has_the_requested_torrent() { - let tracker = public_tracker(); - - let torrent_stats = match_scrape_response(add_a_sample_seeder_and_scrape(tracker.clone()).await); - - let expected_torrent_stats = vec![TorrentScrapeStatistics { - seeders: NumberOfPeers(1), - completed: NumberOfDownloads(0), - leechers: NumberOfPeers(0), - }]; - - assert_eq!(torrent_stats.unwrap().torrent_stats, expected_torrent_stats); - } - } - - mod with_a_private_tracker { - - use aquatic_udp_protocol::InfoHash; - - use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::tests::scrape_request::{ - add_a_sample_seeder_and_scrape, build_scrape_request, match_scrape_response, zeroed_torrent_statistics, - }; - use crate::servers::udp::handlers::tests::{private_tracker, sample_ipv4_remote_addr}; - - #[tokio::test] - async fn should_return_zeroed_statistics_when_the_tracker_does_not_have_the_requested_torrent() { - let tracker = private_tracker(); - - let remote_addr = sample_ipv4_remote_addr(); - let non_existing_info_hash = InfoHash([0u8; 20]); - - let request = build_scrape_request(&remote_addr, &non_existing_info_hash); - - let torrent_stats = match_scrape_response(handle_scrape(remote_addr, &request, &tracker).await.unwrap()).unwrap(); - - let expected_torrent_stats = vec![zeroed_torrent_statistics()]; - - assert_eq!(torrent_stats.torrent_stats, expected_torrent_stats); - } - - #[tokio::test] - async fn should_return_zeroed_statistics_when_the_tracker_has_the_requested_torrent_because_authenticated_requests_are_not_supported_in_udp_tracker( - ) { - let tracker = private_tracker(); - - let torrent_stats = match_scrape_response(add_a_sample_seeder_and_scrape(tracker.clone()).await).unwrap(); - - let expected_torrent_stats = vec![zeroed_torrent_statistics()]; - - assert_eq!(torrent_stats.torrent_stats, expected_torrent_stats); - } - } - - mod with_a_whitelisted_tracker { - use aquatic_udp_protocol::{InfoHash, NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; - - use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::tests::scrape_request::{ - add_a_seeder, build_scrape_request, match_scrape_response, zeroed_torrent_statistics, - }; - use crate::servers::udp::handlers::tests::{sample_ipv4_remote_addr, whitelisted_tracker}; - - #[tokio::test] - async fn should_return_the_torrent_statistics_when_the_requested_torrent_is_whitelisted() { - let tracker = whitelisted_tracker(); - - let remote_addr = sample_ipv4_remote_addr(); - let info_hash = InfoHash([0u8; 20]); - - add_a_seeder(tracker.clone(), &remote_addr, &info_hash).await; - - tracker.add_torrent_to_memory_whitelist(&info_hash.0.into()).await; - - let request = build_scrape_request(&remote_addr, &info_hash); - - let torrent_stats = match_scrape_response(handle_scrape(remote_addr, &request, &tracker).await.unwrap()).unwrap(); - - let expected_torrent_stats = vec![TorrentScrapeStatistics { - seeders: NumberOfPeers(1), - completed: NumberOfDownloads(0), - leechers: NumberOfPeers(0), - }]; - - assert_eq!(torrent_stats.torrent_stats, expected_torrent_stats); - } - - #[tokio::test] - async fn should_return_zeroed_statistics_when_the_requested_torrent_is_not_whitelisted() { - let tracker = whitelisted_tracker(); - - let remote_addr = sample_ipv4_remote_addr(); - let info_hash = InfoHash([0u8; 20]); - - add_a_seeder(tracker.clone(), &remote_addr, &info_hash).await; - - let request = build_scrape_request(&remote_addr, &info_hash); - - let torrent_stats = match_scrape_response(handle_scrape(remote_addr, &request, &tracker).await.unwrap()).unwrap(); - - let expected_torrent_stats = vec![zeroed_torrent_statistics()]; - - assert_eq!(torrent_stats.torrent_stats, expected_torrent_stats); - } - } - - fn sample_scrape_request(remote_addr: &SocketAddr) -> ScrapeRequest { - let info_hash = InfoHash([0u8; 20]); - let info_hashes = vec![info_hash]; - - ScrapeRequest { - connection_id: into_connection_id(&make(remote_addr)), - transaction_id: TransactionId(0i32), - info_hashes, - } - } - - mod using_ipv4 { - use std::future; - use std::sync::Arc; - - use mockall::predicate::eq; - - use super::sample_scrape_request; - use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::tests::{sample_ipv4_remote_addr, tracker_configuration}; - use crate::tracker::{self, statistics}; - - #[tokio::test] - async fn should_send_the_upd4_scrape_event() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::Event::Udp4Scrape)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); - - let remote_addr = sample_ipv4_remote_addr(); - let tracker = Arc::new( - tracker::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), - ); - - handle_scrape(remote_addr, &sample_scrape_request(&remote_addr), &tracker) - .await - .unwrap(); - } - } - - mod using_ipv6 { - use std::future; - use std::sync::Arc; - - use mockall::predicate::eq; - - use super::sample_scrape_request; - use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::tests::{sample_ipv6_remote_addr, tracker_configuration}; - use crate::tracker::{self, statistics}; - - #[tokio::test] - async fn should_send_the_upd6_scrape_event() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::Event::Udp6Scrape)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); - - let remote_addr = sample_ipv6_remote_addr(); - let tracker = Arc::new( - tracker::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), - ); - - handle_scrape(remote_addr, &sample_scrape_request(&remote_addr), &tracker) - .await - .unwrap(); - } - } - } -} diff --git a/src/servers/udp/peer_builder.rs b/src/servers/udp/peer_builder.rs deleted file mode 100644 index ac62a7ecd..000000000 --- a/src/servers/udp/peer_builder.rs +++ /dev/null @@ -1,27 +0,0 @@ -//! Logic to extract the peer info from the announce request. -use std::net::{IpAddr, SocketAddr}; - -use super::request::AnnounceWrapper; -use crate::shared::clock::{Current, Time}; -use crate::tracker::peer::{Id, Peer}; - -/// Extracts the [`Peer`](crate::tracker::peer::Peer) info from the -/// announce request. -/// -/// # Arguments -/// -/// * `announce_wrapper` - The announce request to extract the peer info from. -/// * `peer_ip` - The real IP address of the peer, not the one in the announce -/// request. -#[must_use] -pub fn from_request(announce_wrapper: &AnnounceWrapper, peer_ip: &IpAddr) -> Peer { - Peer { - peer_id: Id(announce_wrapper.announce_request.peer_id.0), - peer_addr: SocketAddr::new(*peer_ip, announce_wrapper.announce_request.port.0), - updated: Current::now(), - uploaded: announce_wrapper.announce_request.bytes_uploaded, - downloaded: announce_wrapper.announce_request.bytes_downloaded, - left: announce_wrapper.announce_request.bytes_left, - event: announce_wrapper.announce_request.event, - } -} diff --git a/src/servers/udp/request.rs b/src/servers/udp/request.rs deleted file mode 100644 index 0afa02806..000000000 --- a/src/servers/udp/request.rs +++ /dev/null @@ -1,29 +0,0 @@ -//! UDP request types. -//! -//! Torrust Tracker uses the [`aquatic_udp_protocol`](https://crates.io/crates/aquatic_udp_protocol) -//! crate to parse and serialize UDP requests. -//! -//! Some of the type in this module are wrappers around the types in the -//! `aquatic_udp_protocol` crate. -use aquatic_udp_protocol::AnnounceRequest; - -use crate::shared::bit_torrent::info_hash::InfoHash; - -/// Wrapper around [`AnnounceRequest`](aquatic_udp_protocol::request::AnnounceRequest). -pub struct AnnounceWrapper { - /// [`AnnounceRequest`](aquatic_udp_protocol::request::AnnounceRequest) to wrap. - pub announce_request: AnnounceRequest, - /// Info hash of the torrent. - pub info_hash: InfoHash, -} - -impl AnnounceWrapper { - /// Creates a new [`AnnounceWrapper`] from an [`AnnounceRequest`]. - #[must_use] - pub fn new(announce_request: &AnnounceRequest) -> Self { - AnnounceWrapper { - announce_request: announce_request.clone(), - info_hash: InfoHash(announce_request.info_hash.0), - } - } -} diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs deleted file mode 100644 index 6b4b18831..000000000 --- a/src/servers/udp/server.rs +++ /dev/null @@ -1,270 +0,0 @@ -//! Module to handle the UDP server instances. -//! -//! There are two main types in this module: -//! -//! - [`UdpServer`](crate::servers::udp::server::UdpServer): a controller to -//! start and stop the server. -//! - [`Udp`](crate::servers::udp::server::Udp): the server launcher. -//! -//! The `UdpServer` is an state machine for a given configuration. This struct -//! represents concrete configuration and state. It allows to start and -//! stop the server but always keeping the same configuration. -//! -//! The `Udp` is the server launcher. It's responsible for launching the UDP -//! but without keeping any state. -//! -//! For the time being, the `UdpServer` is only used for testing purposes, -//! because we want to be able to start and stop the server multiple times, and -//! we want to know the bound address and the current state of the server. -//! In production, the `Udp` launcher is used directly. -use std::future::Future; -use std::io::Cursor; -use std::net::SocketAddr; -use std::sync::Arc; - -use aquatic_udp_protocol::Response; -use futures::pin_mut; -use log::{debug, error, info}; -use tokio::net::UdpSocket; -use tokio::task::JoinHandle; - -use crate::servers::signals::shutdown_signal; -use crate::servers::udp::handlers::handle_packet; -use crate::servers::udp::MAX_PACKET_SIZE; -use crate::tracker::Tracker; - -/// Error that can occur when starting or stopping the UDP server. -/// -/// Some errors triggered while starting the server are: -/// -/// - The server cannot bind to the given address. -/// - It cannot get the bound address. -/// -/// Some errors triggered while stopping the server are: -/// -/// - The [`UdpServer`](crate::servers::udp::server::UdpServer) cannot send the -/// shutdown signal to the spawned UDP service thread. -#[derive(Debug)] -pub enum Error { - /// Any kind of error starting or stopping the server. - Error(String), // todo: refactor to use thiserror and add more variants for specific errors. -} - -/// A UDP server instance controller with no UDP instance running. -#[allow(clippy::module_name_repetitions)] -pub type StoppedUdpServer = UdpServer; - -/// A UDP server instance controller with a running UDP instance. -#[allow(clippy::module_name_repetitions)] -pub type RunningUdpServer = UdpServer; - -/// A UDP server instance controller. -/// -/// It's responsible for: -/// -/// - Keeping the initial configuration of the server. -/// - Starting and stopping the server. -/// - Keeping the state of the server: `running` or `stopped`. -/// -/// It's an state machine. Configurations cannot be changed. This struct -/// represents concrete configuration and state. It allows to start and stop the -/// server but always keeping the same configuration. -/// -/// > **NOTICE**: if the configurations changes after running the server it will -/// reset to the initial value after stopping the server. This struct is not -/// intended to persist configurations between runs. -#[allow(clippy::module_name_repetitions)] -pub struct UdpServer { - /// The configuration of the server that will be used every time the server - /// is started. - pub cfg: torrust_tracker_configuration::UdpTracker, - /// The state of the server: `running` or `stopped`. - pub state: S, -} - -/// A stopped UDP server state. -pub struct Stopped; - -/// A running UDP server state. -pub struct Running { - /// The address where the server is bound. - pub bind_address: SocketAddr, - stop_job_sender: tokio::sync::oneshot::Sender, - job: JoinHandle<()>, -} - -impl UdpServer { - /// Creates a new `UdpServer` instance in `stopped`state. - #[must_use] - pub fn new(cfg: torrust_tracker_configuration::UdpTracker) -> Self { - Self { cfg, state: Stopped {} } - } - - /// It starts the server and returns a `UdpServer` controller in `running` - /// state. - /// - /// # Errors - /// - /// Will return `Err` if UDP can't bind to given bind address. - pub async fn start(self, tracker: Arc) -> Result, Error> { - let udp = Udp::new(&self.cfg.bind_address) - .await - .map_err(|e| Error::Error(e.to_string()))?; - - let bind_address = udp.socket.local_addr().map_err(|e| Error::Error(e.to_string()))?; - - let (sender, receiver) = tokio::sync::oneshot::channel::(); - - let job = tokio::spawn(async move { - udp.start_with_graceful_shutdown(tracker, shutdown_signal(receiver)).await; - }); - - let running_udp_server: UdpServer = UdpServer { - cfg: self.cfg, - state: Running { - bind_address, - stop_job_sender: sender, - job, - }, - }; - - Ok(running_udp_server) - } -} - -impl UdpServer { - /// It stops the server and returns a `UdpServer` controller in `stopped` - /// state. - /// - /// # Errors - /// - /// Will return `Err` if the oneshot channel to send the stop signal - /// has already been called once. - pub async fn stop(self) -> Result, Error> { - self.state.stop_job_sender.send(1).map_err(|e| Error::Error(e.to_string()))?; - - let _: Result<(), tokio::task::JoinError> = self.state.job.await; - - let stopped_api_server: UdpServer = UdpServer { - cfg: self.cfg, - state: Stopped {}, - }; - - Ok(stopped_api_server) - } -} - -/// A UDP server instance launcher. -pub struct Udp { - socket: Arc, -} - -impl Udp { - /// Creates a new `Udp` instance. - /// - /// # Errors - /// - /// Will return `Err` unable to bind to the supplied `bind_address`. - pub async fn new(bind_address: &str) -> tokio::io::Result { - let socket = UdpSocket::bind(bind_address).await?; - - Ok(Udp { - socket: Arc::new(socket), - }) - } - - /// It starts the UDP server instance. - /// - /// # Panics - /// - /// It would panic if unable to resolve the `local_addr` from the supplied ´socket´. - pub async fn start(&self, tracker: Arc) { - loop { - let mut data = [0; MAX_PACKET_SIZE]; - let socket = self.socket.clone(); - - tokio::select! { - _ = tokio::signal::ctrl_c() => { - info!("Stopping UDP server: {}..", socket.local_addr().unwrap()); - break; - } - Ok((valid_bytes, remote_addr)) = socket.recv_from(&mut data) => { - let payload = data[..valid_bytes].to_vec(); - - info!("Received {} bytes", payload.len()); - debug!("From: {}", &remote_addr); - debug!("Payload: {:?}", payload); - - let response = handle_packet(remote_addr, payload, &tracker).await; - - Udp::send_response(socket, remote_addr, response).await; - } - } - } - } - - /// It starts the UDP server instance with graceful shutdown. - /// - /// # Panics - /// - /// It would panic if unable to resolve the `local_addr` from the supplied ´socket´. - async fn start_with_graceful_shutdown(&self, tracker: Arc, shutdown_signal: F) - where - F: Future, - { - // Pin the future so that it doesn't move to the first loop iteration. - pin_mut!(shutdown_signal); - - loop { - let mut data = [0; MAX_PACKET_SIZE]; - let socket = self.socket.clone(); - - tokio::select! { - _ = &mut shutdown_signal => { - info!("Stopping UDP server: {}..", self.socket.local_addr().unwrap()); - break; - } - Ok((valid_bytes, remote_addr)) = socket.recv_from(&mut data) => { - let payload = data[..valid_bytes].to_vec(); - - info!("Received {} bytes", payload.len()); - debug!("From: {}", &remote_addr); - debug!("Payload: {:?}", payload); - - let response = handle_packet(remote_addr, payload, &tracker).await; - - Udp::send_response(socket, remote_addr, response).await; - } - } - } - } - - async fn send_response(socket: Arc, remote_addr: SocketAddr, response: Response) { - let buffer = vec![0u8; MAX_PACKET_SIZE]; - let mut cursor = Cursor::new(buffer); - - match response.write(&mut cursor) { - Ok(_) => { - #[allow(clippy::cast_possible_truncation)] - let position = cursor.position() as usize; - let inner = cursor.get_ref(); - - info!("Sending {} bytes ...", &inner[..position].len()); - debug!("To: {:?}", &remote_addr); - debug!("Payload: {:?}", &inner[..position]); - - Udp::send_packet(socket, &remote_addr, &inner[..position]).await; - - info!("{} bytes sent", &inner[..position].len()); - } - Err(_) => { - error!("could not write response to bytes."); - } - } - } - - async fn send_packet(socket: Arc, remote_addr: &SocketAddr, payload: &[u8]) { - // doesn't matter if it reaches or not - drop(socket.send_to(payload, remote_addr).await); - } -} diff --git a/src/shared/bit_torrent/common.rs b/src/shared/bit_torrent/common.rs deleted file mode 100644 index fd52e098c..000000000 --- a/src/shared/bit_torrent/common.rs +++ /dev/null @@ -1,56 +0,0 @@ -//! `BitTorrent` protocol primitive types -//! -//! [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; -use serde::{Deserialize, Serialize}; - -/// The maximum number of torrents that can be returned in an `scrape` response. -/// It's also the maximum number of peers returned in an `announce` response. -/// -/// The [BEP 15. UDP Tracker Protocol for `BitTorrent`](https://www.bittorrent.org/beps/bep_0015.html) -/// defines this limit: -/// -/// "Up to about 74 torrents can be scraped at once. A full scrape can't be done -/// with this protocol." -/// -/// The [BEP 48. Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) -/// does not specifically mention this limit, but the limit is being used for -/// both the UDP and HTTP trackers since it's applied at the domain level. -pub const MAX_SCRAPE_TORRENTS: u8 = 74; - -/// HTTP tracker authentication key length. -/// -/// See function to [`generate`](crate::tracker::auth::generate) the -/// [`ExpiringKeys`](crate::tracker::auth::ExpiringKey) for more information. -pub const AUTH_KEY_LENGTH: usize = 32; - -#[repr(u32)] -#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)] -enum Actions { - // todo: it seems this enum is not used anywhere. Values match the ones in - // aquatic_udp_protocol::request::Request::from_bytes. - Connect = 0, - Announce = 1, - Scrape = 2, - Error = 3, -} - -/// Announce events. Described on the -/// [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -#[derive(Serialize, Deserialize)] -#[serde(remote = "AnnounceEvent")] -pub enum AnnounceEventDef { - /// The peer has started downloading the torrent. - Started, - /// The peer has ceased downloading the torrent. - Stopped, - /// The peer has completed downloading the torrent. - Completed, - /// This is one of the announcements done at regular intervals. - None, -} - -/// Number of bytes downloaded, uploaded or pending to download (left) by the peer. -#[derive(Serialize, Deserialize)] -#[serde(remote = "NumberOfBytes")] -pub struct NumberOfBytesDef(pub i64); diff --git a/src/shared/bit_torrent/info_hash.rs b/src/shared/bit_torrent/info_hash.rs deleted file mode 100644 index 7392c791d..000000000 --- a/src/shared/bit_torrent/info_hash.rs +++ /dev/null @@ -1,419 +0,0 @@ -//! A `BitTorrent` `InfoHash`. It's a unique identifier for a `BitTorrent` torrent. -//! -//! "The 20-byte sha1 hash of the bencoded form of the info value -//! from the metainfo file." -//! -//! See [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -//! for the official specification. -//! -//! This modules provides a type that can be used to represent infohashes. -//! -//! > **NOTICE**: It only supports Info Hash v1. -//! -//! Typically infohashes are represented as hex strings, but internally they are -//! a 20-byte array. -//! -//! # Calculating the info-hash of a torrent file -//! -//! A sample torrent: -//! -//! - Torrent file: `mandelbrot_2048x2048_infohash_v1.png.torrent` -//! - File: `mandelbrot_2048x2048.png` -//! - Info Hash v1: `5452869be36f9f3350ccee6b4544e7e76caaadab` -//! - Sha1 hash of the info dictionary: `5452869BE36F9F3350CCEE6B4544E7E76CAAADAB` -//! -//! A torrent file is a binary file encoded with [Bencode encoding](https://en.wikipedia.org/wiki/Bencode): -//! -//! ```text -//! 0000000: 6431 303a 6372 6561 7465 6420 6279 3138 d10:created by18 -//! 0000010: 3a71 4269 7474 6f72 7265 6e74 2076 342e :qBittorrent v4. -//! 0000020: 342e 3131 333a 6372 6561 7469 6f6e 2064 4.113:creation d -//! 0000030: 6174 6569 3136 3739 3637 3436 3238 6534 atei1679674628e4 -//! 0000040: 3a69 6e66 6f64 363a 6c65 6e67 7468 6931 :infod6:lengthi1 -//! 0000050: 3732 3230 3465 343a 6e61 6d65 3234 3a6d 72204e4:name24:m -//! 0000060: 616e 6465 6c62 726f 745f 3230 3438 7832 andelbrot_2048x2 -//! 0000070: 3034 382e 706e 6731 323a 7069 6563 6520 048.png12:piece -//! 0000080: 6c65 6e67 7468 6931 3633 3834 6536 3a70 lengthi16384e6:p -//! 0000090: 6965 6365 7332 3230 3a7d 9171 0d9d 4dba ieces220:}.q..M. -//! 00000a0: 889b 5420 54d5 2672 8d5a 863f e121 df77 ..T T.&r.Z.?.!.w -//! 00000b0: c7f7 bb6c 7796 2166 2538 c5d9 cdab 8b08 ...lw.!f%8...... -//! 00000c0: ef8c 249b b2f5 c4cd 2adf 0bc0 0cf0 addf ..$.....*....... -//! 00000d0: 7290 e5b6 414c 236c 479b 8e9f 46aa 0c0d r...AL#lG...F... -//! 00000e0: 8ed1 97ff ee68 8b5f 34a3 87d7 71c5 a6f9 .....h._4...q... -//! 00000f0: 8e2e a631 7cbd f0f9 e223 f9cc 80af 5400 ...1|....#....T. -//! 0000100: 04f9 8569 1c77 89c1 764e d6aa bf61 a6c2 ...i.w..vN...a.. -//! 0000110: 8099 abb6 5f60 2f40 a825 be32 a33d 9d07 ...._`/@.%.2.=.. -//! 0000120: 0c79 6898 d49d 6349 af20 5866 266f 986b .yh...cI. Xf&o.k -//! 0000130: 6d32 34cd 7d08 155e 1ad0 0009 57ab 303b m24.}..^....W.0; -//! 0000140: 2060 c1dc 1287 d6f3 e745 4f70 6709 3631 `.......EOpg.61 -//! 0000150: 55f2 20f6 6ca5 156f 2c89 9569 1653 817d U. .l..o,..i.S.} -//! 0000160: 31f1 b6bd 3742 cc11 0bb2 fc2b 49a5 85b6 1...7B.....+I... -//! 0000170: fc76 7444 9365 65 .vtD.ee -//! ``` -//! -//! You can generate that output with the command: -//! -//! ```text -//! xxd mandelbrot_2048x2048_infohash_v1.png.torrent -//! ``` -//! -//! And you can show only the bytes (hexadecimal): -//! -//! ```text -//! 6431303a6372656174656420627931383a71426974746f7272656e742076 -//! 342e342e3131333a6372656174696f6e2064617465693136373936373436 -//! 323865343a696e666f64363a6c656e6774686931373232303465343a6e61 -//! 6d6532343a6d616e64656c62726f745f3230343878323034382e706e6731 -//! 323a7069656365206c656e67746869313633383465363a70696563657332 -//! 32303a7d91710d9d4dba889b542054d526728d5a863fe121df77c7f7bb6c -//! 779621662538c5d9cdab8b08ef8c249bb2f5c4cd2adf0bc00cf0addf7290 -//! e5b6414c236c479b8e9f46aa0c0d8ed197ffee688b5f34a387d771c5a6f9 -//! 8e2ea6317cbdf0f9e223f9cc80af540004f985691c7789c1764ed6aabf61 -//! a6c28099abb65f602f40a825be32a33d9d070c796898d49d6349af205866 -//! 266f986b6d3234cd7d08155e1ad0000957ab303b2060c1dc1287d6f3e745 -//! 4f706709363155f220f66ca5156f2c8995691653817d31f1b6bd3742cc11 -//! 0bb2fc2b49a585b6fc767444936565 -//! ``` -//! -//! You can generate that output with the command: -//! -//! ```text -//! `xxd -ps mandelbrot_2048x2048_infohash_v1.png.torrent`. -//! ``` -//! -//! The same data can be represented in a JSON format: -//! -//! ```json -//! { -//! "created by": "qBittorrent v4.4.1", -//! "creation date": 1679674628, -//! "info": { -//! "length": 172204, -//! "name": "mandelbrot_2048x2048.png", -//! "piece length": 16384, -//! "pieces": "7D 91 71 0D 9D 4D BA 88 9B 54 20 54 D5 26 72 8D 5A 86 3F E1 21 DF 77 C7 F7 BB 6C 77 96 21 66 25 38 C5 D9 CD AB 8B 08 EF 8C 24 9B B2 F5 C4 CD 2A DF 0B C0 0C F0 AD DF 72 90 E5 B6 41 4C 23 6C 47 9B 8E 9F 46 AA 0C 0D 8E D1 97 FF EE 68 8B 5F 34 A3 87 D7 71 C5 A6 F9 8E 2E A6 31 7C BD F0 F9 E2 23 F9 CC 80 AF 54 00 04 F9 85 69 1C 77 89 C1 76 4E D6 AA BF 61 A6 C2 80 99 AB B6 5F 60 2F 40 A8 25 BE 32 A3 3D 9D 07 0C 79 68 98 D4 9D 63 49 AF 20 58 66 26 6F 98 6B 6D 32 34 CD 7D 08 15 5E 1A D0 00 09 57 AB 30 3B 20 60 C1 DC 12 87 D6 F3 E7 45 4F 70 67 09 36 31 55 F2 20 F6 6C A5 15 6F 2C 89 95 69 16 53 81 7D 31 F1 B6 BD 37 42 CC 11 0B B2 FC 2B 49 A5 85 B6 FC 76 74 44 93" -//! } -//! } -//! ``` -//! -//! The JSON object was generated with: -//! -//! As you can see, there is a `info` attribute: -//! -//! ```json -//! { -//! "length": 172204, -//! "name": "mandelbrot_2048x2048.png", -//! "piece length": 16384, -//! "pieces": "7D 91 71 0D 9D 4D BA 88 9B 54 20 54 D5 26 72 8D 5A 86 3F E1 21 DF 77 C7 F7 BB 6C 77 96 21 66 25 38 C5 D9 CD AB 8B 08 EF 8C 24 9B B2 F5 C4 CD 2A DF 0B C0 0C F0 AD DF 72 90 E5 B6 41 4C 23 6C 47 9B 8E 9F 46 AA 0C 0D 8E D1 97 FF EE 68 8B 5F 34 A3 87 D7 71 C5 A6 F9 8E 2E A6 31 7C BD F0 F9 E2 23 F9 CC 80 AF 54 00 04 F9 85 69 1C 77 89 C1 76 4E D6 AA BF 61 A6 C2 80 99 AB B6 5F 60 2F 40 A8 25 BE 32 A3 3D 9D 07 0C 79 68 98 D4 9D 63 49 AF 20 58 66 26 6F 98 6B 6D 32 34 CD 7D 08 15 5E 1A D0 00 09 57 AB 30 3B 20 60 C1 DC 12 87 D6 F3 E7 45 4F 70 67 09 36 31 55 F2 20 F6 6C A5 15 6F 2C 89 95 69 16 53 81 7D 31 F1 B6 BD 37 42 CC 11 0B B2 FC 2B 49 A5 85 B6 FC 76 74 44 93" -//! } -//! ``` -//! -//! The infohash is the [SHA1](https://en.wikipedia.org/wiki/SHA-1) hash -//! of the `info` attribute. That is, the SHA1 hash of: -//! -//! ```text -//! 64363a6c656e6774686931373232303465343a6e61 -//! d6532343a6d616e64656c62726f745f3230343878323034382e706e6731 -//! 23a7069656365206c656e67746869313633383465363a70696563657332 -//! 2303a7d91710d9d4dba889b542054d526728d5a863fe121df77c7f7bb6c -//! 79621662538c5d9cdab8b08ef8c249bb2f5c4cd2adf0bc00cf0addf7290 -//! 5b6414c236c479b8e9f46aa0c0d8ed197ffee688b5f34a387d771c5a6f9 -//! e2ea6317cbdf0f9e223f9cc80af540004f985691c7789c1764ed6aabf61 -//! 6c28099abb65f602f40a825be32a33d9d070c796898d49d6349af205866 -//! 66f986b6d3234cd7d08155e1ad0000957ab303b2060c1dc1287d6f3e745 -//! f706709363155f220f66ca5156f2c8995691653817d31f1b6bd3742cc11 -//! bb2fc2b49a585b6fc7674449365 -//! ``` -//! -//! You can hash that byte string with -//! -//! The result is a 20-char string: `5452869BE36F9F3350CCEE6B4544E7E76CAAADAB` -use std::panic::Location; - -use thiserror::Error; - -/// `BitTorrent` Info Hash v1 -#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)] -pub struct InfoHash(pub [u8; 20]); - -const INFO_HASH_BYTES_LEN: usize = 20; - -impl InfoHash { - /// Create a new `InfoHash` from a byte slice. - /// - /// # Panics - /// - /// Will panic if byte slice does not contains the exact amount of bytes need for the `InfoHash`. - #[must_use] - pub fn from_bytes(bytes: &[u8]) -> Self { - assert_eq!(bytes.len(), INFO_HASH_BYTES_LEN); - let mut ret = Self([0u8; INFO_HASH_BYTES_LEN]); - ret.0.clone_from_slice(bytes); - ret - } - - /// Returns the `InfoHash` internal byte array. - #[must_use] - pub fn bytes(&self) -> [u8; 20] { - self.0 - } - - /// Returns the `InfoHash` as a hex string. - #[must_use] - pub fn to_hex_string(&self) -> String { - self.to_string() - } -} - -impl std::fmt::Display for InfoHash { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - let mut chars = [0u8; 40]; - binascii::bin2hex(&self.0, &mut chars).expect("failed to hexlify"); - write!(f, "{}", std::str::from_utf8(&chars).unwrap()) - } -} - -impl std::str::FromStr for InfoHash { - type Err = binascii::ConvertError; - - fn from_str(s: &str) -> Result { - let mut i = Self([0u8; 20]); - if s.len() != 40 { - return Err(binascii::ConvertError::InvalidInputLength); - } - binascii::hex2bin(s.as_bytes(), &mut i.0)?; - Ok(i) - } -} - -impl Ord for InfoHash { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.0.cmp(&other.0) - } -} - -impl std::cmp::PartialOrd for InfoHash { - fn partial_cmp(&self, other: &InfoHash) -> Option { - self.0.partial_cmp(&other.0) - } -} - -impl std::convert::From<&[u8]> for InfoHash { - fn from(data: &[u8]) -> InfoHash { - assert_eq!(data.len(), 20); - let mut ret = InfoHash([0u8; 20]); - ret.0.clone_from_slice(data); - ret - } -} - -impl std::convert::From<[u8; 20]> for InfoHash { - fn from(val: [u8; 20]) -> Self { - InfoHash(val) - } -} - -/// Errors that can occur when converting from a `Vec` to an `InfoHash`. -#[derive(Error, Debug)] -pub enum ConversionError { - /// Not enough bytes for infohash. An infohash is 20 bytes. - #[error("not enough bytes for infohash: {message} {location}")] - NotEnoughBytes { - location: &'static Location<'static>, - message: String, - }, - /// Too many bytes for infohash. An infohash is 20 bytes. - #[error("too many bytes for infohash: {message} {location}")] - TooManyBytes { - location: &'static Location<'static>, - message: String, - }, -} - -impl TryFrom> for InfoHash { - type Error = ConversionError; - - fn try_from(bytes: Vec) -> Result { - if bytes.len() < INFO_HASH_BYTES_LEN { - return Err(ConversionError::NotEnoughBytes { - location: Location::caller(), - message: format! {"got {} bytes, expected {}", bytes.len(), INFO_HASH_BYTES_LEN}, - }); - } - if bytes.len() > INFO_HASH_BYTES_LEN { - return Err(ConversionError::TooManyBytes { - location: Location::caller(), - message: format! {"got {} bytes, expected {}", bytes.len(), INFO_HASH_BYTES_LEN}, - }); - } - Ok(Self::from_bytes(&bytes)) - } -} - -impl serde::ser::Serialize for InfoHash { - fn serialize(&self, serializer: S) -> Result { - let mut buffer = [0u8; 40]; - let bytes_out = binascii::bin2hex(&self.0, &mut buffer).ok().unwrap(); - let str_out = std::str::from_utf8(bytes_out).unwrap(); - serializer.serialize_str(str_out) - } -} - -impl<'de> serde::de::Deserialize<'de> for InfoHash { - fn deserialize>(des: D) -> Result { - des.deserialize_str(InfoHashVisitor) - } -} - -struct InfoHashVisitor; - -impl<'v> serde::de::Visitor<'v> for InfoHashVisitor { - type Value = InfoHash; - - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(formatter, "a 40 character long hash") - } - - fn visit_str(self, v: &str) -> Result { - if v.len() != 40 { - return Err(serde::de::Error::invalid_value( - serde::de::Unexpected::Str(v), - &"a 40 character long string", - )); - } - - let mut res = InfoHash([0u8; 20]); - - if binascii::hex2bin(v.as_bytes(), &mut res.0).is_err() { - return Err(serde::de::Error::invalid_value( - serde::de::Unexpected::Str(v), - &"a hexadecimal string", - )); - }; - Ok(res) - } -} - -#[cfg(test)] -mod tests { - - use std::str::FromStr; - - use serde::{Deserialize, Serialize}; - use serde_json::json; - - use super::InfoHash; - - #[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)] - struct ContainingInfoHash { - pub info_hash: InfoHash, - } - - #[test] - fn an_info_hash_can_be_created_from_a_valid_40_utf8_char_string_representing_an_hexadecimal_value() { - let info_hash = InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"); - assert!(info_hash.is_ok()); - } - - #[test] - fn an_info_hash_can_not_be_created_from_a_utf8_string_representing_a_not_valid_hexadecimal_value() { - let info_hash = InfoHash::from_str("GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG"); - assert!(info_hash.is_err()); - } - - #[test] - fn an_info_hash_can_only_be_created_from_a_40_utf8_char_string() { - let info_hash = InfoHash::from_str(&"F".repeat(39)); - assert!(info_hash.is_err()); - - let info_hash = InfoHash::from_str(&"F".repeat(41)); - assert!(info_hash.is_err()); - } - - #[test] - fn an_info_hash_should_by_displayed_like_a_40_utf8_lowercased_char_hex_string() { - let info_hash = InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap(); - - let output = format!("{info_hash}"); - - assert_eq!(output, "ffffffffffffffffffffffffffffffffffffffff"); - } - - #[test] - fn an_info_hash_should_return_its_a_40_utf8_lowercased_char_hex_representations_as_string() { - let info_hash = InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap(); - - assert_eq!(info_hash.to_hex_string(), "ffffffffffffffffffffffffffffffffffffffff"); - } - - #[test] - fn an_info_hash_can_be_created_from_a_valid_20_byte_array_slice() { - let info_hash: InfoHash = [255u8; 20].as_slice().into(); - - assert_eq!( - info_hash, - InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap() - ); - } - - #[test] - fn an_info_hash_can_be_created_from_a_valid_20_byte_array() { - let info_hash: InfoHash = [255u8; 20].into(); - - assert_eq!( - info_hash, - InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap() - ); - } - - #[test] - fn an_info_hash_can_be_created_from_a_byte_vector() { - let info_hash: InfoHash = [255u8; 20].to_vec().try_into().unwrap(); - - assert_eq!( - info_hash, - InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap() - ); - } - - #[test] - fn it_should_fail_trying_to_create_an_info_hash_from_a_byte_vector_with_less_than_20_bytes() { - assert!(InfoHash::try_from([255u8; 19].to_vec()).is_err()); - } - - #[test] - fn it_should_fail_trying_to_create_an_info_hash_from_a_byte_vector_with_more_than_20_bytes() { - assert!(InfoHash::try_from([255u8; 21].to_vec()).is_err()); - } - - #[test] - fn an_info_hash_can_be_serialized() { - let s = ContainingInfoHash { - info_hash: InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap(), - }; - - let json_serialized_value = serde_json::to_string(&s).unwrap(); - - assert_eq!( - json_serialized_value, - r#"{"info_hash":"ffffffffffffffffffffffffffffffffffffffff"}"# - ); - } - - #[test] - fn an_info_hash_can_be_deserialized() { - let json = json!({ - "info_hash": "ffffffffffffffffffffffffffffffffffffffff", - }); - - let s: ContainingInfoHash = serde_json::from_value(json).unwrap(); - - assert_eq!( - s, - ContainingInfoHash { - info_hash: InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap() - } - ); - } -} diff --git a/src/shared/bit_torrent/mod.rs b/src/shared/bit_torrent/mod.rs deleted file mode 100644 index eba90b4ab..000000000 --- a/src/shared/bit_torrent/mod.rs +++ /dev/null @@ -1,71 +0,0 @@ -//! Common code for the `BitTorrent` protocol. -//! -//! # Glossary -//! -//! - [Announce](#announce) -//! - [Info Hash](#info-hash) -//! - [Leecher](#leechers) -//! - [Peer ID](#peer-id) -//! - [Peer List](#peer-list) -//! - [Peer](#peer) -//! - [Scrape](#scrape) -//! - [Seeders](#seeders) -//! - [Swarm](#swarm) -//! - [Tracker](#tracker) -//! -//! Glossary of `BitTorrent` terms. -//! -//! # Announce -//! -//! A request to the tracker to announce the presence of a peer. -//! -//! ## Info Hash -//! -//! A unique identifier for a torrent. -//! -//! ## Leecher -//! -//! Peers that are only downloading data. -//! -//! ## Peer ID -//! -//! A unique identifier for a peer. -//! -//! ## Peer List -//! -//! A list of peers that are downloading a torrent. -//! -//! ## Peer -//! -//! A client that is downloading or uploading a torrent. -//! -//! ## Scrape -//! -//! A request to the tracker to get information about a torrent. -//! -//! ## Seeder -//! -//! Peers that are only uploading data. -//! -//! ## Swarm -//! -//! A group of peers that are downloading the same torrent. -//! -//! ## Tracker -//! -//! A server that keeps track of peers that are downloading a torrent. -//! -//! # Links -//! -//! Description | Link -//! ---|--- -//! `BitTorrent.org`. A forum for developers to exchange ideas about the direction of the `BitTorrent` protocol | -//! Wikipedia entry for Glossary of `BitTorrent` term | -//! `BitTorrent` Specification Wiki | -//! Vuze Wiki. A `BitTorrent` client implementation | -//! `libtorrent`. Complete C++ bittorrent implementation| -//! UDP Tracker Protocol docs by `libtorrent` | -//! Percent Encoding spec | -//!Bencode & bdecode in your browser | -pub mod common; -pub mod info_hash; diff --git a/src/shared/clock/mod.rs b/src/shared/clock/mod.rs deleted file mode 100644 index 7a5290f49..000000000 --- a/src/shared/clock/mod.rs +++ /dev/null @@ -1,398 +0,0 @@ -//! Time related functions and types. -//! -//! It's usually a good idea to control where the time comes from -//! in an application so that it can be mocked for testing and it can be -//! controlled in production so we get the intended behavior without -//! relying on the specific time zone for the underlying system. -//! -//! Clocks use the type `DurationSinceUnixEpoch` which is a -//! `std::time::Duration` since the Unix Epoch (timestamp). -//! -//! ```text -//! Local time: lun 2023-03-27 16:12:00 WEST -//! Universal time: lun 2023-03-27 15:12:00 UTC -//! Time zone: Atlantic/Canary (WEST, +0100) -//! Timestamp: 1679929914 -//! Duration: 1679929914.10167426 -//! ``` -//! -//! > **NOTICE**: internally the `Duration` is stores it's main unit as seconds in a `u64` and it will -//! overflow in 584.9 billion years. -//! -//! > **NOTICE**: the timestamp does not depend on the time zone. That gives you -//! the ability to use the clock regardless of the underlying system time zone -//! configuration. See [Unix time Wikipedia entry](https://en.wikipedia.org/wiki/Unix_time). -pub mod static_time; -pub mod time_extent; -pub mod utils; - -use std::num::IntErrorKind; -use std::str::FromStr; -use std::time::Duration; - -use chrono::{DateTime, NaiveDateTime, Utc}; - -/// Duration since the Unix Epoch. -pub type DurationSinceUnixEpoch = Duration; - -/// Clock types. -#[derive(Debug)] -pub enum Type { - /// Clock that returns the current time. - WorkingClock, - /// Clock that returns always the same fixed time. - StoppedClock, -} - -/// A generic structure that represents a clock. -/// -/// It can be either the working clock (production) or the stopped clock -/// (testing). It implements the `Time` trait, which gives you the current time. -#[derive(Debug)] -pub struct Clock; - -/// The working clock. It returns the current time. -pub type Working = Clock<{ Type::WorkingClock as usize }>; -/// The stopped clock. It returns always the same fixed time. -pub type Stopped = Clock<{ Type::StoppedClock as usize }>; - -/// The current clock. Defined at compilation time. -/// It can be either the working clock (production) or the stopped clock (testing). -#[cfg(not(test))] -pub type Current = Working; - -/// The current clock. Defined at compilation time. -/// It can be either the working clock (production) or the stopped clock (testing). -#[cfg(test)] -pub type Current = Stopped; - -/// Trait for types that can be used as a timestamp clock. -pub trait Time: Sized { - fn now() -> DurationSinceUnixEpoch; -} - -/// Trait for types that can be manipulate the current time in order to -/// get time in the future or in the past after or before a duration of time. -pub trait TimeNow: Time { - #[must_use] - fn add(add_time: &Duration) -> Option { - Self::now().checked_add(*add_time) - } - #[must_use] - fn sub(sub_time: &Duration) -> Option { - Self::now().checked_sub(*sub_time) - } -} - -/// It converts a string in ISO 8601 format to a timestamp. -/// For example, the string `1970-01-01T00:00:00.000Z` which is the Unix Epoch -/// will be converted to a timestamp of 0: `DurationSinceUnixEpoch::ZERO`. -/// -/// # Panics -/// -/// Will panic if the input time cannot be converted to `DateTime::`, internally using the `i64` type. -/// (this will naturally happen in 292.5 billion years) -#[must_use] -pub fn convert_from_iso_8601_to_timestamp(iso_8601: &str) -> DurationSinceUnixEpoch { - convert_from_datetime_utc_to_timestamp(&DateTime::::from_str(iso_8601).unwrap()) -} - -/// It converts a `DateTime::` to a timestamp. -/// For example, the `DateTime::` of the Unix Epoch will be converted to a -/// timestamp of 0: `DurationSinceUnixEpoch::ZERO`. -/// -/// # Panics -/// -/// Will panic if the input time overflows the `u64` type. -/// (this will naturally happen in 584.9 billion years) -#[must_use] -pub fn convert_from_datetime_utc_to_timestamp(datetime_utc: &DateTime) -> DurationSinceUnixEpoch { - DurationSinceUnixEpoch::from_secs(u64::try_from(datetime_utc.timestamp()).expect("Overflow of u64 seconds, very future!")) -} - -/// It converts a timestamp to a `DateTime::`. -/// For example, the timestamp of 0: `DurationSinceUnixEpoch::ZERO` will be -/// converted to the `DateTime::` of the Unix Epoch. -/// -/// # Panics -/// -/// Will panic if the input time overflows the `u64` seconds overflows the `i64` type. -/// (this will naturally happen in 292.5 billion years) -#[must_use] -pub fn convert_from_timestamp_to_datetime_utc(duration: DurationSinceUnixEpoch) -> DateTime { - DateTime::::from_utc( - NaiveDateTime::from_timestamp_opt( - i64::try_from(duration.as_secs()).expect("Overflow of i64 seconds, very future!"), - duration.subsec_nanos(), - ) - .unwrap(), - Utc, - ) -} - -#[cfg(test)] -mod tests { - use std::any::TypeId; - - use crate::shared::clock::{Current, Stopped, Time, Working}; - - #[test] - fn it_should_be_the_stopped_clock_as_default_when_testing() { - // We are testing, so we should default to the fixed time. - assert_eq!(TypeId::of::(), TypeId::of::()); - assert_eq!(Stopped::now(), Current::now()); - } - - #[test] - fn it_should_have_different_times() { - assert_ne!(TypeId::of::(), TypeId::of::()); - assert_ne!(Stopped::now(), Working::now()); - } - - mod timestamp { - use chrono::{DateTime, NaiveDateTime, Utc}; - - use crate::shared::clock::{ - convert_from_datetime_utc_to_timestamp, convert_from_iso_8601_to_timestamp, convert_from_timestamp_to_datetime_utc, - DurationSinceUnixEpoch, - }; - - #[test] - fn should_be_converted_to_datetime_utc() { - let timestamp = DurationSinceUnixEpoch::ZERO; - assert_eq!( - convert_from_timestamp_to_datetime_utc(timestamp), - DateTime::::from_utc(NaiveDateTime::from_timestamp_opt(0, 0).unwrap(), Utc) - ); - } - - #[test] - fn should_be_converted_from_datetime_utc() { - let datetime = DateTime::::from_utc(NaiveDateTime::from_timestamp_opt(0, 0).unwrap(), Utc); - assert_eq!( - convert_from_datetime_utc_to_timestamp(&datetime), - DurationSinceUnixEpoch::ZERO - ); - } - - #[test] - fn should_be_converted_from_datetime_utc_in_iso_8601() { - let iso_8601 = "1970-01-01T00:00:00.000Z".to_string(); - assert_eq!(convert_from_iso_8601_to_timestamp(&iso_8601), DurationSinceUnixEpoch::ZERO); - } - } -} - -mod working_clock { - use std::time::SystemTime; - - use super::{DurationSinceUnixEpoch, Time, TimeNow, Working}; - - impl Time for Working { - fn now() -> DurationSinceUnixEpoch { - SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap() - } - } - - impl TimeNow for Working {} -} - -/// Trait for types that can be used as a timestamp clock stopped -/// at a given time. -pub trait StoppedTime: TimeNow { - /// It sets the clock to a given time. - fn local_set(unix_time: &DurationSinceUnixEpoch); - - /// It sets the clock to the Unix Epoch. - fn local_set_to_unix_epoch() { - Self::local_set(&DurationSinceUnixEpoch::ZERO); - } - - /// It sets the clock to the time the application started. - fn local_set_to_app_start_time(); - - /// It sets the clock to the current system time. - fn local_set_to_system_time_now(); - - /// It adds a `Duration` to the clock. - /// - /// # Errors - /// - /// Will return `IntErrorKind` if `duration` would overflow the internal `Duration`. - fn local_add(duration: &Duration) -> Result<(), IntErrorKind>; - - /// It subtracts a `Duration` from the clock. - /// # Errors - /// - /// Will return `IntErrorKind` if `duration` would underflow the internal `Duration`. - fn local_sub(duration: &Duration) -> Result<(), IntErrorKind>; - - /// It resets the clock to default fixed time that is application start time (or the unix epoch when testing). - fn local_reset(); -} - -mod stopped_clock { - use std::num::IntErrorKind; - use std::time::Duration; - - use super::{DurationSinceUnixEpoch, Stopped, StoppedTime, Time, TimeNow}; - - impl Time for Stopped { - fn now() -> DurationSinceUnixEpoch { - detail::FIXED_TIME.with(|time| { - return *time.borrow(); - }) - } - } - - impl TimeNow for Stopped {} - - impl StoppedTime for Stopped { - fn local_set(unix_time: &DurationSinceUnixEpoch) { - detail::FIXED_TIME.with(|time| { - *time.borrow_mut() = *unix_time; - }); - } - - fn local_set_to_app_start_time() { - Self::local_set(&detail::get_app_start_time()); - } - - fn local_set_to_system_time_now() { - Self::local_set(&detail::get_app_start_time()); - } - - fn local_add(duration: &Duration) -> Result<(), IntErrorKind> { - detail::FIXED_TIME.with(|time| { - let time_borrowed = *time.borrow(); - *time.borrow_mut() = match time_borrowed.checked_add(*duration) { - Some(time) => time, - None => { - return Err(IntErrorKind::PosOverflow); - } - }; - Ok(()) - }) - } - - fn local_sub(duration: &Duration) -> Result<(), IntErrorKind> { - detail::FIXED_TIME.with(|time| { - let time_borrowed = *time.borrow(); - *time.borrow_mut() = match time_borrowed.checked_sub(*duration) { - Some(time) => time, - None => { - return Err(IntErrorKind::NegOverflow); - } - }; - Ok(()) - }) - } - - fn local_reset() { - Self::local_set(&detail::get_default_fixed_time()); - } - } - - #[cfg(test)] - mod tests { - use std::thread; - use std::time::Duration; - - use crate::shared::clock::{DurationSinceUnixEpoch, Stopped, StoppedTime, Time, TimeNow, Working}; - - #[test] - fn it_should_default_to_zero_when_testing() { - assert_eq!(Stopped::now(), DurationSinceUnixEpoch::ZERO); - } - - #[test] - fn it_should_possible_to_set_the_time() { - // Check we start with ZERO. - assert_eq!(Stopped::now(), Duration::ZERO); - - // Set to Current Time and Check - let timestamp = Working::now(); - Stopped::local_set(×tamp); - assert_eq!(Stopped::now(), timestamp); - - // Elapse the Current Time and Check - Stopped::local_add(×tamp).unwrap(); - assert_eq!(Stopped::now(), timestamp + timestamp); - - // Reset to ZERO and Check - Stopped::local_reset(); - assert_eq!(Stopped::now(), Duration::ZERO); - } - - #[test] - fn it_should_default_to_zero_on_thread_exit() { - assert_eq!(Stopped::now(), Duration::ZERO); - let after5 = Working::add(&Duration::from_secs(5)).unwrap(); - Stopped::local_set(&after5); - assert_eq!(Stopped::now(), after5); - - let t = thread::spawn(move || { - // each thread starts out with the initial value of ZERO - assert_eq!(Stopped::now(), Duration::ZERO); - - // and gets set to the current time. - let timestamp = Working::now(); - Stopped::local_set(×tamp); - assert_eq!(Stopped::now(), timestamp); - }); - - // wait for the thread to complete and bail out on panic - t.join().unwrap(); - - // we retain our original value of current time + 5sec despite the child thread - assert_eq!(Stopped::now(), after5); - - // Reset to ZERO and Check - Stopped::local_reset(); - assert_eq!(Stopped::now(), Duration::ZERO); - } - } - - mod detail { - use std::cell::RefCell; - use std::time::SystemTime; - - use crate::shared::clock::{static_time, DurationSinceUnixEpoch}; - - pub fn get_app_start_time() -> DurationSinceUnixEpoch { - (*static_time::TIME_AT_APP_START) - .duration_since(SystemTime::UNIX_EPOCH) - .unwrap() - } - - #[cfg(not(test))] - pub fn get_default_fixed_time() -> DurationSinceUnixEpoch { - get_app_start_time() - } - - #[cfg(test)] - pub fn get_default_fixed_time() -> DurationSinceUnixEpoch { - DurationSinceUnixEpoch::ZERO - } - - thread_local!(pub static FIXED_TIME: RefCell = RefCell::new(get_default_fixed_time())); - - #[cfg(test)] - mod tests { - use std::time::Duration; - - use crate::shared::clock::stopped_clock::detail::{get_app_start_time, get_default_fixed_time}; - - #[test] - fn it_should_get_the_zero_start_time_when_testing() { - assert_eq!(get_default_fixed_time(), Duration::ZERO); - } - - #[test] - fn it_should_get_app_start_time() { - const TIME_AT_WRITING_THIS_TEST: Duration = Duration::new(1_662_983_731, 22312); - assert!(get_app_start_time() > TIME_AT_WRITING_THIS_TEST); - } - } - } -} diff --git a/src/shared/clock/time_extent.rs b/src/shared/clock/time_extent.rs deleted file mode 100644 index 2f9e003be..000000000 --- a/src/shared/clock/time_extent.rs +++ /dev/null @@ -1,659 +0,0 @@ -//! It includes functionality to handle time extents. -//! -//! Time extents are used to represent a duration of time which contains -//! N times intervals of the same duration. -//! -//! Given a duration of: 60 seconds. -//! -//! ```text -//! |------------------------------------------------------------| -//! ``` -//! -//! If we define a **base** duration of `10` seconds, we would have `6` intervals. -//! -//! ```text -//! |----------|----------|----------|----------|----------|----------| -//! ^--- 10 seconds -//! ``` -//! -//! Then, You can represent half of the duration (`30` seconds) as: -//! -//! ```text -//! |----------|----------|----------|----------|----------|----------| -//! ^--- 30 seconds -//! ``` -//! -//! `3` times (**multiplier**) the **base** interval (3*10 = 30 seconds): -//! -//! ```text -//! |----------|----------|----------|----------|----------|----------| -//! ^--- 30 seconds (3 units of 10 seconds) -//! ``` -//! -//! Time extents are a way to measure time duration using only one unit of time -//! (**base** duration) repeated `N` times (**multiplier**). -//! -//! Time extents are not clocks in a sense that they do not have a start time. -//! They are not synchronized with the real time. In order to measure time, -//! you need to define a start time for the intervals. -//! -//! For example, we could measure time is "lustrums" (5 years) since the start -//! of the 21st century. The time extent would contains a base 5-year duration -//! and the multiplier. The current "lustrum" (2023) would be 5th one if we -//! start counting "lustrums" at 1. -//! -//! ```text -//! Lustrum 1: 2000-2004 -//! Lustrum 2: 2005-2009 -//! Lustrum 3: 2010-2014 -//! Lustrum 4: 2015-2019 -//! Lustrum 5: 2020-2024 -//! ``` -//! -//! More practically time extents are used to represent number of time intervals -//! since the Unix Epoch. Each interval is typically an amount of seconds. -//! It's specially useful to check expiring dates. For example, you can have an -//! authentication token that expires after 120 seconds. If you divide the -//! current timestamp by 120 you get the number of 2-minute intervals since the -//! Unix Epoch, you can hash that value with a secret key and send it to a -//! client. The client can authenticate by sending the hashed value back to the -//! server. The server can build the same hash and compare it with the one sent -//! by the client. The hash would be the same during the 2-minute interval, but -//! it would change after that. This method is one of the methods used by UDP -//! trackers to generate and verify a connection ID, which a a token sent to -//! the client to identify the connection. -use std::num::{IntErrorKind, TryFromIntError}; -use std::time::Duration; - -use super::{Stopped, TimeNow, Type, Working}; - -/// This trait defines the operations that can be performed on a `TimeExtent`. -pub trait Extent: Sized + Default { - type Base; - type Multiplier; - type Product; - - /// It creates a new `TimeExtent`. - fn new(unit: &Self::Base, count: &Self::Multiplier) -> Self; - - /// It increases the `TimeExtent` by a multiplier. - /// - /// # Errors - /// - /// Will return `IntErrorKind` if `add` would overflow the internal `Duration`. - fn increase(&self, add: Self::Multiplier) -> Result; - - /// It decreases the `TimeExtent` by a multiplier. - /// - /// # Errors - /// - /// Will return `IntErrorKind` if `sub` would underflow the internal `Duration`. - fn decrease(&self, sub: Self::Multiplier) -> Result; - - /// It returns the total `Duration` of the `TimeExtent`. - fn total(&self) -> Option>; - - /// It returns the total `Duration` of the `TimeExtent` plus one increment. - fn total_next(&self) -> Option>; -} - -/// The `TimeExtent` base `Duration`, which is the duration of a single interval. -pub type Base = Duration; -/// The `TimeExtent` `Multiplier`, which is the number of `Base` duration intervals. -pub type Multiplier = u64; -/// The `TimeExtent` product, which is the total duration of the `TimeExtent`. -pub type Product = Base; - -/// A `TimeExtent` is a duration of time which contains N times intervals -/// of the same duration. -#[derive(Debug, Default, Hash, PartialEq, Eq)] -pub struct TimeExtent { - pub increment: Base, - pub amount: Multiplier, -} - -/// A zero time extent. It's the additive identity for a `TimeExtent`. -pub const ZERO: TimeExtent = TimeExtent { - increment: Base::ZERO, - amount: Multiplier::MIN, -}; - -/// The maximum value for a `TimeExtent`. -pub const MAX: TimeExtent = TimeExtent { - increment: Base::MAX, - amount: Multiplier::MAX, -}; - -impl TimeExtent { - #[must_use] - pub const fn from_sec(seconds: u64, amount: &Multiplier) -> Self { - Self { - increment: Base::from_secs(seconds), - amount: *amount, - } - } -} - -fn checked_duration_from_nanos(time: u128) -> Result { - const NANOS_PER_SEC: u32 = 1_000_000_000; - - let secs = time.div_euclid(u128::from(NANOS_PER_SEC)); - let nanos = time.rem_euclid(u128::from(NANOS_PER_SEC)); - - assert!(nanos < u128::from(NANOS_PER_SEC)); - - match u64::try_from(secs) { - Err(error) => Err(error), - Ok(secs) => Ok(Duration::new(secs, nanos.try_into().unwrap())), - } -} - -impl Extent for TimeExtent { - type Base = Base; - type Multiplier = Multiplier; - type Product = Product; - - fn new(increment: &Self::Base, amount: &Self::Multiplier) -> Self { - Self { - increment: *increment, - amount: *amount, - } - } - - fn increase(&self, add: Self::Multiplier) -> Result { - match self.amount.checked_add(add) { - None => Err(IntErrorKind::PosOverflow), - Some(amount) => Ok(Self { - increment: self.increment, - amount, - }), - } - } - - fn decrease(&self, sub: Self::Multiplier) -> Result { - match self.amount.checked_sub(sub) { - None => Err(IntErrorKind::NegOverflow), - Some(amount) => Ok(Self { - increment: self.increment, - amount, - }), - } - } - - fn total(&self) -> Option> { - self.increment - .as_nanos() - .checked_mul(u128::from(self.amount)) - .map(checked_duration_from_nanos) - } - - fn total_next(&self) -> Option> { - self.increment - .as_nanos() - .checked_mul(u128::from(self.amount) + 1) - .map(checked_duration_from_nanos) - } -} - -/// A `TimeExtent` maker. It's a clock base on time extents. -/// It gives you the time in time extents. -pub trait Make: Sized -where - Clock: TimeNow, -{ - /// It gives you the current time extent (with a certain increment) for - /// the current time. It gets the current timestamp front he `Clock`. - /// - /// For example: - /// - /// - If the base increment is `1` second, it will return a time extent - /// whose duration is `1 second` and whose multiplier is the the number - /// of seconds since the Unix Epoch (time extent). - /// - If the base increment is `1` minute, it will return a time extent - /// whose duration is `60 seconds` and whose multiplier is the number of - /// minutes since the Unix Epoch (time extent). - #[must_use] - fn now(increment: &Base) -> Option> { - Clock::now() - .as_nanos() - .checked_div((*increment).as_nanos()) - .map(|amount| match Multiplier::try_from(amount) { - Err(error) => Err(error), - Ok(amount) => Ok(TimeExtent::new(increment, &amount)), - }) - } - - /// Same as [`now`](crate::shared::clock::time_extent::Make::now), but it - /// will add an extra duration to the current time before calculating the - /// time extent. It gives you a time extent for a time in the future. - #[must_use] - fn now_after(increment: &Base, add_time: &Duration) -> Option> { - match Clock::add(add_time) { - None => None, - Some(time) => time - .as_nanos() - .checked_div(increment.as_nanos()) - .map(|amount| match Multiplier::try_from(amount) { - Err(error) => Err(error), - Ok(amount) => Ok(TimeExtent::new(increment, &amount)), - }), - } - } - - /// Same as [`now`](crate::shared::clock::time_extent::Make::now), but it - /// will subtract a duration to the current time before calculating the - /// time extent. It gives you a time extent for a time in the past. - #[must_use] - fn now_before(increment: &Base, sub_time: &Duration) -> Option> { - match Clock::sub(sub_time) { - None => None, - Some(time) => time - .as_nanos() - .checked_div(increment.as_nanos()) - .map(|amount| match Multiplier::try_from(amount) { - Err(error) => Err(error), - Ok(amount) => Ok(TimeExtent::new(increment, &amount)), - }), - } - } -} - -/// A `TimeExtent` maker which makes `TimeExtents`. -/// -/// It's a clock which measures time in `TimeExtents`. -#[derive(Debug)] -pub struct Maker {} - -/// A `TimeExtent` maker which makes `TimeExtents` from the `Working` clock. -pub type WorkingTimeExtentMaker = Maker<{ Type::WorkingClock as usize }>; - -/// A `TimeExtent` maker which makes `TimeExtents` from the `Stopped` clock. -pub type StoppedTimeExtentMaker = Maker<{ Type::StoppedClock as usize }>; - -impl Make for WorkingTimeExtentMaker {} -impl Make for StoppedTimeExtentMaker {} - -/// The default `TimeExtent` maker. It is `WorkingTimeExtentMaker` in production -/// and `StoppedTimeExtentMaker` in tests. -#[cfg(not(test))] -pub type DefaultTimeExtentMaker = WorkingTimeExtentMaker; - -/// The default `TimeExtent` maker. It is `WorkingTimeExtentMaker` in production -/// and `StoppedTimeExtentMaker` in tests. -#[cfg(test)] -pub type DefaultTimeExtentMaker = StoppedTimeExtentMaker; - -#[cfg(test)] -mod test { - - use crate::shared::clock::time_extent::{ - checked_duration_from_nanos, Base, DefaultTimeExtentMaker, Extent, Make, Multiplier, Product, TimeExtent, MAX, ZERO, - }; - use crate::shared::clock::{Current, DurationSinceUnixEpoch, StoppedTime}; - - const TIME_EXTENT_VAL: TimeExtent = TimeExtent::from_sec(2, &239_812_388_723); - - mod fn_checked_duration_from_nanos { - use std::time::Duration; - - use super::*; - - const NANOS_PER_SEC: u32 = 1_000_000_000; - - #[test] - fn it_should_give_zero_for_zero_input() { - assert_eq!(checked_duration_from_nanos(0).unwrap(), Duration::ZERO); - } - - #[test] - fn it_should_be_the_same_as_duration_implementation_for_u64_numbers() { - assert_eq!( - checked_duration_from_nanos(1_232_143_214_343_432).unwrap(), - Duration::from_nanos(1_232_143_214_343_432) - ); - assert_eq!( - checked_duration_from_nanos(u128::from(u64::MAX)).unwrap(), - Duration::from_nanos(u64::MAX) - ); - } - - #[test] - fn it_should_work_for_some_numbers_larger_than_u64() { - assert_eq!( - checked_duration_from_nanos(u128::from(TIME_EXTENT_VAL.amount) * u128::from(NANOS_PER_SEC)).unwrap(), - Duration::from_secs(TIME_EXTENT_VAL.amount) - ); - } - - #[test] - fn it_should_fail_for_numbers_that_are_too_large() { - assert_eq!( - checked_duration_from_nanos(u128::MAX).unwrap_err(), - u64::try_from(u128::MAX).unwrap_err() - ); - } - } - - mod time_extent { - use super::*; - - mod fn_default { - - use super::*; - - #[test] - fn it_should_default_initialize_to_zero() { - assert_eq!(TimeExtent::default(), ZERO); - } - } - - mod fn_from_sec { - use super::*; - - #[test] - fn it_should_make_empty_for_zero() { - assert_eq!(TimeExtent::from_sec(u64::MIN, &Multiplier::MIN), ZERO); - } - #[test] - fn it_should_make_from_seconds() { - assert_eq!( - TimeExtent::from_sec(TIME_EXTENT_VAL.increment.as_secs(), &TIME_EXTENT_VAL.amount), - TIME_EXTENT_VAL - ); - } - } - - mod fn_new { - use super::*; - - #[test] - fn it_should_make_empty_for_zero() { - assert_eq!(TimeExtent::new(&Base::ZERO, &Multiplier::MIN), ZERO); - } - - #[test] - fn it_should_make_new() { - assert_eq!( - TimeExtent::new(&Base::from_millis(2), &TIME_EXTENT_VAL.amount), - TimeExtent { - increment: Base::from_millis(2), - amount: TIME_EXTENT_VAL.amount - } - ); - } - } - - mod fn_increase { - use std::num::IntErrorKind; - - use super::*; - - #[test] - fn it_should_not_increase_for_zero() { - assert_eq!(ZERO.increase(0).unwrap(), ZERO); - } - - #[test] - fn it_should_increase() { - assert_eq!( - TIME_EXTENT_VAL.increase(50).unwrap(), - TimeExtent { - increment: TIME_EXTENT_VAL.increment, - amount: TIME_EXTENT_VAL.amount + 50, - } - ); - } - - #[test] - fn it_should_fail_when_attempting_to_increase_beyond_bounds() { - assert_eq!(TIME_EXTENT_VAL.increase(u64::MAX), Err(IntErrorKind::PosOverflow)); - } - } - - mod fn_decrease { - use std::num::IntErrorKind; - - use super::*; - - #[test] - fn it_should_not_decrease_for_zero() { - assert_eq!(ZERO.decrease(0).unwrap(), ZERO); - } - - #[test] - fn it_should_decrease() { - assert_eq!( - TIME_EXTENT_VAL.decrease(50).unwrap(), - TimeExtent { - increment: TIME_EXTENT_VAL.increment, - amount: TIME_EXTENT_VAL.amount - 50, - } - ); - } - - #[test] - fn it_should_fail_when_attempting_to_decrease_beyond_bounds() { - assert_eq!(TIME_EXTENT_VAL.decrease(u64::MAX), Err(IntErrorKind::NegOverflow)); - } - } - - mod fn_total { - use super::*; - - #[test] - fn it_should_be_zero_for_zero() { - assert_eq!(ZERO.total().unwrap().unwrap(), Product::ZERO); - } - - #[test] - fn it_should_give_a_total() { - assert_eq!( - TIME_EXTENT_VAL.total().unwrap().unwrap(), - Product::from_secs(TIME_EXTENT_VAL.increment.as_secs() * TIME_EXTENT_VAL.amount) - ); - - assert_eq!( - TimeExtent::new(&Base::from_millis(2), &(TIME_EXTENT_VAL.amount * 1000)) - .total() - .unwrap() - .unwrap(), - Product::from_secs(TIME_EXTENT_VAL.increment.as_secs() * TIME_EXTENT_VAL.amount) - ); - - assert_eq!( - TimeExtent::new(&Base::from_secs(1), &(u64::MAX)).total().unwrap().unwrap(), - Product::from_secs(u64::MAX) - ); - } - - #[test] - fn it_should_fail_when_too_large() { - assert_eq!(MAX.total(), None); - } - - #[test] - fn it_should_fail_when_product_is_too_large() { - let time_extent = TimeExtent { - increment: MAX.increment, - amount: 2, - }; - assert_eq!( - time_extent.total().unwrap().unwrap_err(), - u64::try_from(u128::MAX).unwrap_err() - ); - } - } - - mod fn_total_next { - use super::*; - - #[test] - fn it_should_be_zero_for_zero() { - assert_eq!(ZERO.total_next().unwrap().unwrap(), Product::ZERO); - } - - #[test] - fn it_should_give_a_total() { - assert_eq!( - TIME_EXTENT_VAL.total_next().unwrap().unwrap(), - Product::from_secs(TIME_EXTENT_VAL.increment.as_secs() * (TIME_EXTENT_VAL.amount + 1)) - ); - - assert_eq!( - TimeExtent::new(&Base::from_millis(2), &(TIME_EXTENT_VAL.amount * 1000)) - .total_next() - .unwrap() - .unwrap(), - Product::new( - TIME_EXTENT_VAL.increment.as_secs() * (TIME_EXTENT_VAL.amount), - Base::from_millis(2).as_nanos().try_into().unwrap() - ) - ); - - assert_eq!( - TimeExtent::new(&Base::from_secs(1), &(u64::MAX - 1)) - .total_next() - .unwrap() - .unwrap(), - Product::from_secs(u64::MAX) - ); - } - - #[test] - fn it_should_fail_when_too_large() { - assert_eq!(MAX.total_next(), None); - } - - #[test] - fn it_should_fail_when_product_is_too_large() { - let time_extent = TimeExtent { - increment: MAX.increment, - amount: 2, - }; - assert_eq!( - time_extent.total_next().unwrap().unwrap_err(), - u64::try_from(u128::MAX).unwrap_err() - ); - } - } - } - - mod make_time_extent { - use super::*; - - mod fn_now { - use super::*; - - #[test] - fn it_should_give_a_time_extent() { - assert_eq!( - DefaultTimeExtentMaker::now(&TIME_EXTENT_VAL.increment).unwrap().unwrap(), - TimeExtent { - increment: TIME_EXTENT_VAL.increment, - amount: 0 - } - ); - - Current::local_set(&DurationSinceUnixEpoch::from_secs(TIME_EXTENT_VAL.amount * 2)); - - assert_eq!( - DefaultTimeExtentMaker::now(&TIME_EXTENT_VAL.increment).unwrap().unwrap(), - TIME_EXTENT_VAL - ); - } - - #[test] - fn it_should_fail_for_zero() { - assert_eq!(DefaultTimeExtentMaker::now(&Base::ZERO), None); - } - - #[test] - fn it_should_fail_if_amount_exceeds_bounds() { - Current::local_set(&DurationSinceUnixEpoch::MAX); - assert_eq!( - DefaultTimeExtentMaker::now(&Base::from_millis(1)).unwrap().unwrap_err(), - u64::try_from(u128::MAX).unwrap_err() - ); - } - } - - mod fn_now_after { - use std::time::Duration; - - use super::*; - - #[test] - fn it_should_give_a_time_extent() { - assert_eq!( - DefaultTimeExtentMaker::now_after( - &TIME_EXTENT_VAL.increment, - &Duration::from_secs(TIME_EXTENT_VAL.amount * 2) - ) - .unwrap() - .unwrap(), - TIME_EXTENT_VAL - ); - } - - #[test] - fn it_should_fail_for_zero() { - assert_eq!(DefaultTimeExtentMaker::now_after(&Base::ZERO, &Duration::ZERO), None); - - Current::local_set(&DurationSinceUnixEpoch::MAX); - assert_eq!(DefaultTimeExtentMaker::now_after(&Base::ZERO, &Duration::MAX), None); - } - - #[test] - fn it_should_fail_if_amount_exceeds_bounds() { - Current::local_set(&DurationSinceUnixEpoch::MAX); - assert_eq!( - DefaultTimeExtentMaker::now_after(&Base::from_millis(1), &Duration::ZERO) - .unwrap() - .unwrap_err(), - u64::try_from(u128::MAX).unwrap_err() - ); - } - } - mod fn_now_before { - use std::time::Duration; - - use super::*; - - #[test] - fn it_should_give_a_time_extent() { - Current::local_set(&DurationSinceUnixEpoch::MAX); - - assert_eq!( - DefaultTimeExtentMaker::now_before( - &Base::from_secs(u64::from(u32::MAX)), - &Duration::from_secs(u64::from(u32::MAX)) - ) - .unwrap() - .unwrap(), - TimeExtent { - increment: Base::from_secs(u64::from(u32::MAX)), - amount: 4_294_967_296 - } - ); - } - - #[test] - fn it_should_fail_for_zero() { - assert_eq!(DefaultTimeExtentMaker::now_before(&Base::ZERO, &Duration::ZERO), None); - - assert_eq!(DefaultTimeExtentMaker::now_before(&Base::ZERO, &Duration::MAX), None); - } - - #[test] - fn it_should_fail_if_amount_exceeds_bounds() { - Current::local_set(&DurationSinceUnixEpoch::MAX); - assert_eq!( - DefaultTimeExtentMaker::now_before(&Base::from_millis(1), &Duration::ZERO) - .unwrap() - .unwrap_err(), - u64::try_from(u128::MAX).unwrap_err() - ); - } - } - } -} diff --git a/src/shared/clock/utils.rs b/src/shared/clock/utils.rs deleted file mode 100644 index 94d88d288..000000000 --- a/src/shared/clock/utils.rs +++ /dev/null @@ -1,11 +0,0 @@ -//! It contains helper functions related to time. -use super::DurationSinceUnixEpoch; - -/// Serializes a `DurationSinceUnixEpoch` as a Unix timestamp in milliseconds. -/// # Errors -/// -/// Will return `serde::Serializer::Error` if unable to serialize the `unix_time_value`. -pub fn ser_unix_time_value(unix_time_value: &DurationSinceUnixEpoch, ser: S) -> Result { - #[allow(clippy::cast_possible_truncation)] - ser.serialize_u64(unix_time_value.as_millis() as u64) -} diff --git a/src/shared/crypto/ephemeral_instance_keys.rs b/src/shared/crypto/ephemeral_instance_keys.rs deleted file mode 100644 index 44283365a..000000000 --- a/src/shared/crypto/ephemeral_instance_keys.rs +++ /dev/null @@ -1,13 +0,0 @@ -//! This module contains the ephemeral instance keys used by the application. -//! -//! They are ephemeral because they are generated at runtime when the -//! application starts and are not persisted anywhere. -use rand::rngs::ThreadRng; -use rand::Rng; - -pub type Seed = [u8; 32]; - -lazy_static! { - /// The random static seed. - pub static ref RANDOM_SEED: Seed = Rng::gen(&mut ThreadRng::default()); -} diff --git a/src/shared/crypto/keys.rs b/src/shared/crypto/keys.rs deleted file mode 100644 index 92e180996..000000000 --- a/src/shared/crypto/keys.rs +++ /dev/null @@ -1,112 +0,0 @@ -//! This module contains logic related to cryptographic keys. -pub mod seeds { - //! This module contains logic related to cryptographic seeds. - //! - //! Specifically, it contains the logic for storing the seed and providing - //! it to other modules. - //! - //! A **seed** is a pseudo-random number that is used as a secret key for - //! cryptographic operations. - use self::detail::CURRENT_SEED; - use crate::shared::crypto::ephemeral_instance_keys::{Seed, RANDOM_SEED}; - - /// This trait is for structures that can keep and provide a seed. - pub trait Keeper { - type Seed: Sized + Default + AsMut<[u8]>; - - /// It returns a reference to the seed that is keeping. - fn get_seed() -> &'static Self::Seed; - } - - /// The seed keeper for the instance. When the application is running - /// in production, this will be the seed keeper that is used. - pub struct Instance; - - /// The seed keeper for the current execution. It's a facade at compilation - /// time that will either be the instance seed keeper (with a randomly - /// generated key for production) or the zeroed seed keeper. - pub struct Current; - - impl Keeper for Instance { - type Seed = Seed; - - fn get_seed() -> &'static Self::Seed { - &RANDOM_SEED - } - } - - impl Keeper for Current { - type Seed = Seed; - - #[allow(clippy::needless_borrow)] - fn get_seed() -> &'static Self::Seed { - &CURRENT_SEED - } - } - - #[cfg(test)] - mod tests { - use super::detail::ZEROED_TEST_SEED; - use super::{Current, Instance, Keeper}; - use crate::shared::crypto::ephemeral_instance_keys::Seed; - - pub struct ZeroedTestSeed; - - impl Keeper for ZeroedTestSeed { - type Seed = Seed; - - #[allow(clippy::needless_borrow)] - fn get_seed() -> &'static Self::Seed { - &ZEROED_TEST_SEED - } - } - - #[test] - fn the_default_seed_and_the_zeroed_seed_should_be_the_same_when_testing() { - assert_eq!(Current::get_seed(), ZeroedTestSeed::get_seed()); - } - - #[test] - fn the_default_seed_and_the_instance_seed_should_be_different_when_testing() { - assert_ne!(Current::get_seed(), Instance::get_seed()); - } - } - - mod detail { - use crate::shared::crypto::ephemeral_instance_keys::Seed; - - #[allow(dead_code)] - pub const ZEROED_TEST_SEED: &Seed = &[0u8; 32]; - - #[cfg(test)] - pub use ZEROED_TEST_SEED as CURRENT_SEED; - - #[cfg(not(test))] - pub use crate::shared::crypto::ephemeral_instance_keys::RANDOM_SEED as CURRENT_SEED; - - #[cfg(test)] - mod tests { - use std::convert::TryInto; - - use crate::shared::crypto::ephemeral_instance_keys::RANDOM_SEED; - use crate::shared::crypto::keys::seeds::detail::ZEROED_TEST_SEED; - use crate::shared::crypto::keys::seeds::CURRENT_SEED; - - #[test] - fn it_should_have_a_zero_test_seed() { - assert_eq!(*ZEROED_TEST_SEED, [0u8; 32]); - } - - #[test] - fn it_should_default_to_zeroed_seed_when_testing() { - assert_eq!(*CURRENT_SEED, *ZEROED_TEST_SEED); - } - - #[test] - fn it_should_have_a_large_random_seed() { - assert!(u128::from_ne_bytes((*RANDOM_SEED)[..16].try_into().unwrap()) > u128::from(u64::MAX)); - assert!(u128::from_ne_bytes((*RANDOM_SEED)[16..].try_into().unwrap()) > u128::from(u64::MAX)); - } - } - } -} diff --git a/src/shared/mod.rs b/src/shared/mod.rs deleted file mode 100644 index f016ba913..000000000 --- a/src/shared/mod.rs +++ /dev/null @@ -1,8 +0,0 @@ -//! Modules with generic logic used by several modules. -//! -//! - [`bit_torrent`]: `BitTorrent` protocol related logic. -//! - [`clock`]: Times services. -//! - [`crypto`]: Encryption related logic. -pub mod bit_torrent; -pub mod clock; -pub mod crypto; diff --git a/src/tracker/auth.rs b/src/tracker/auth.rs deleted file mode 100644 index 466187af5..000000000 --- a/src/tracker/auth.rs +++ /dev/null @@ -1,266 +0,0 @@ -//! Tracker authentication services and structs. -//! -//! This module contains functions to handle tracker keys. -//! Tracker keys are tokens used to authenticate the tracker clients when the tracker runs -//! in `private` or `private_listed` modes. -//! -//! There are services to [`generate`](crate::tracker::auth::generate) and [`verify`](crate::tracker::auth::verify) authentication keys. -//! -//! Authentication keys are used only by [`HTTP`](crate::servers::http) trackers. All keys have an expiration time, that means -//! they are only valid during a period of time. After that time the expiring key will no longer be valid. -//! -//! Keys are stored in this struct: -//! -//! ```rust,no_run -//! use torrust_tracker::tracker::auth::Key; -//! use torrust_tracker::shared::clock::DurationSinceUnixEpoch; -//! -//! pub struct ExpiringKey { -//! /// Random 32-char string. For example: `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ` -//! pub key: Key, -//! /// Timestamp, the key will be no longer valid after this timestamp -//! pub valid_until: DurationSinceUnixEpoch, -//! } -//! ``` -//! -//! You can generate a new key valid for `9999` seconds and `0` nanoseconds from the current time with the following: -//! -//! ```rust,no_run -//! use torrust_tracker::tracker::auth; -//! use std::time::Duration; -//! -//! let expiring_key = auth::generate(Duration::new(9999, 0)); -//! -//! // And you can later verify it with: -//! -//! assert!(auth::verify(&expiring_key).is_ok()); -//! ``` - -use std::panic::Location; -use std::str::FromStr; -use std::sync::Arc; -use std::time::Duration; - -use derive_more::Display; -use log::debug; -use rand::distributions::Alphanumeric; -use rand::{thread_rng, Rng}; -use serde::{Deserialize, Serialize}; -use thiserror::Error; -use torrust_tracker_located_error::LocatedError; - -use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; -use crate::shared::clock::{convert_from_timestamp_to_datetime_utc, Current, DurationSinceUnixEpoch, Time, TimeNow}; - -#[must_use] -/// It generates a new random 32-char authentication [`ExpiringKey`](crate::tracker::auth::ExpiringKey) -/// -/// # Panics -/// -/// It would panic if the `lifetime: Duration` + Duration is more than `Duration::MAX`. -pub fn generate(lifetime: Duration) -> ExpiringKey { - let random_id: String = thread_rng() - .sample_iter(&Alphanumeric) - .take(AUTH_KEY_LENGTH) - .map(char::from) - .collect(); - - debug!("Generated key: {}, valid for: {:?} seconds", random_id, lifetime); - - ExpiringKey { - key: random_id.parse::().unwrap(), - valid_until: Current::add(&lifetime).unwrap(), - } -} - -/// It verifies an [`ExpiringKey`](crate::tracker::auth::ExpiringKey). It checks if the expiration date has passed. -/// -/// # Errors -/// -/// Will return `Error::KeyExpired` if `auth_key.valid_until` is past the `current_time`. -/// -/// Will return `Error::KeyInvalid` if `auth_key.valid_until` is past the `None`. -pub fn verify(auth_key: &ExpiringKey) -> Result<(), Error> { - let current_time: DurationSinceUnixEpoch = Current::now(); - - if auth_key.valid_until < current_time { - Err(Error::KeyExpired { - location: Location::caller(), - }) - } else { - Ok(()) - } -} - -/// An authentication key which has an expiration time. -/// After that time is will automatically become invalid. -#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] -pub struct ExpiringKey { - /// Random 32-char string. For example: `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ` - pub key: Key, - /// Timestamp, the key will be no longer valid after this timestamp - pub valid_until: DurationSinceUnixEpoch, -} - -impl std::fmt::Display for ExpiringKey { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "key: `{}`, valid until `{}`", self.key, self.expiry_time()) - } -} - -impl ExpiringKey { - #[must_use] - pub fn key(&self) -> Key { - self.key.clone() - } - - /// It returns the expiry time. For example, for the starting time for Unix Epoch - /// (timestamp 0) it will return a `DateTime` whose string representation is - /// `1970-01-01 00:00:00 UTC`. - /// - /// # Panics - /// - /// Will panic when the key timestamp overflows the internal i64 type. - /// (this will naturally happen in 292.5 billion years) - #[must_use] - pub fn expiry_time(&self) -> chrono::DateTime { - convert_from_timestamp_to_datetime_utc(self.valid_until) - } -} - -/// A randomly generated token used for authentication. -/// -/// It contains lower and uppercase letters and numbers. -/// It's a 32-char string. -#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Display, Hash)] -pub struct Key(String); - -/// Error returned when a key cannot be parsed from a string. -/// -/// ```rust,no_run -/// use torrust_tracker::tracker::auth::Key; -/// use std::str::FromStr; -/// -/// let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; -/// let key = Key::from_str(key_string); -/// -/// assert!(key.is_ok()); -/// assert_eq!(key.unwrap().to_string(), key_string); -/// ``` -/// -/// If the string does not contains a valid key, the parser function will return this error. -#[derive(Debug, PartialEq, Eq)] -pub struct ParseKeyError; - -impl FromStr for Key { - type Err = ParseKeyError; - - fn from_str(s: &str) -> Result { - if s.len() != AUTH_KEY_LENGTH { - return Err(ParseKeyError); - } - - Ok(Self(s.to_string())) - } -} - -/// Verification error. Error returned when an [`ExpiringKey`](crate::tracker::auth::ExpiringKey) cannot be verified with the [`verify(...)`](crate::tracker::auth::verify) function. -/// -#[derive(Debug, Error)] -#[allow(dead_code)] -pub enum Error { - #[error("Key could not be verified: {source}")] - KeyVerificationError { - source: LocatedError<'static, dyn std::error::Error + Send + Sync>, - }, - #[error("Failed to read key: {key}, {location}")] - UnableToReadKey { - location: &'static Location<'static>, - key: Box, - }, - #[error("Key has expired, {location}")] - KeyExpired { location: &'static Location<'static> }, -} - -impl From for Error { - fn from(e: r2d2_sqlite::rusqlite::Error) -> Self { - Error::KeyVerificationError { - source: (Arc::new(e) as Arc).into(), - } - } -} - -#[cfg(test)] -mod tests { - - mod key { - use std::str::FromStr; - - use crate::tracker::auth::Key; - - #[test] - fn should_be_parsed_from_an_string() { - let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; - let key = Key::from_str(key_string); - - assert!(key.is_ok()); - assert_eq!(key.unwrap().to_string(), key_string); - } - } - - mod expiring_auth_key { - use std::str::FromStr; - use std::time::Duration; - - use crate::shared::clock::{Current, StoppedTime}; - use crate::tracker::auth; - - #[test] - fn should_be_parsed_from_an_string() { - let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; - let auth_key = auth::Key::from_str(key_string); - - assert!(auth_key.is_ok()); - assert_eq!(auth_key.unwrap().to_string(), key_string); - } - - #[test] - fn should_be_displayed() { - // Set the time to the current time. - Current::local_set_to_unix_epoch(); - - let expiring_key = auth::generate(Duration::from_secs(0)); - - assert_eq!( - expiring_key.to_string(), - format!("key: `{}`, valid until `1970-01-01 00:00:00 UTC`", expiring_key.key) // cspell:disable-line - ); - } - - #[test] - fn should_be_generated_with_a_expiration_time() { - let expiring_key = auth::generate(Duration::new(9999, 0)); - - assert!(auth::verify(&expiring_key).is_ok()); - } - - #[test] - fn should_be_generate_and_verified() { - // Set the time to the current time. - Current::local_set_to_system_time_now(); - - // Make key that is valid for 19 seconds. - let expiring_key = auth::generate(Duration::from_secs(19)); - - // Mock the time has passed 10 sec. - Current::local_add(&Duration::from_secs(10)).unwrap(); - - assert!(auth::verify(&expiring_key).is_ok()); - - // Mock the time has passed another 10 sec. - Current::local_add(&Duration::from_secs(10)).unwrap(); - - assert!(auth::verify(&expiring_key).is_err()); - } - } -} diff --git a/src/tracker/databases/driver.rs b/src/tracker/databases/driver.rs deleted file mode 100644 index 7115bae8e..000000000 --- a/src/tracker/databases/driver.rs +++ /dev/null @@ -1,53 +0,0 @@ -//! Database driver factory. -//! -//! See [`databases::driver::build`](crate::tracker::databases::driver::build) -//! function for more information. -use torrust_tracker_primitives::DatabaseDriver; - -use super::error::Error; -use super::mysql::Mysql; -use super::sqlite::Sqlite; -use super::{Builder, Database}; - -/// It builds a new database driver. -/// -/// Example for `SQLite3`: -/// -/// ```rust,no_run -/// use torrust_tracker::tracker::databases; -/// use torrust_tracker_primitives::DatabaseDriver; -/// -/// let db_driver = DatabaseDriver::Sqlite3; -/// let db_path = "./storage/database/data.db".to_string(); -/// let database = databases::driver::build(&db_driver, &db_path); -/// ``` -/// -/// Example for `MySQL`: -/// -/// ```rust,no_run -/// use torrust_tracker::tracker::databases; -/// use torrust_tracker_primitives::DatabaseDriver; -/// -/// let db_driver = DatabaseDriver::MySQL; -/// let db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker".to_string(); -/// let database = databases::driver::build(&db_driver, &db_path); -/// ``` -/// -/// Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) -/// for more information about the database configuration. -/// -/// > **WARNING**: The driver instantiation runs database migrations. -/// -/// # Errors -/// -/// This function will return an error if unable to connect to the database. -pub fn build(driver: &DatabaseDriver, db_path: &str) -> Result, Error> { - let database = match driver { - DatabaseDriver::Sqlite3 => Builder::::build(db_path), - DatabaseDriver::MySQL => Builder::::build(db_path), - }?; - - database.create_database_tables().expect("Could not create database tables."); - - Ok(database) -} diff --git a/src/tracker/databases/error.rs b/src/tracker/databases/error.rs deleted file mode 100644 index d89ec05de..000000000 --- a/src/tracker/databases/error.rs +++ /dev/null @@ -1,103 +0,0 @@ -//! Database errors. -//! -//! This module contains the [Database errors](crate::tracker::databases::error::Error). -use std::panic::Location; -use std::sync::Arc; - -use r2d2_mysql::mysql::UrlError; -use torrust_tracker_located_error::{Located, LocatedError}; -use torrust_tracker_primitives::DatabaseDriver; - -#[derive(thiserror::Error, Debug, Clone)] -pub enum Error { - /// The query unexpectedly returned nothing. - #[error("The {driver} query unexpectedly returned nothing: {source}")] - QueryReturnedNoRows { - source: LocatedError<'static, dyn std::error::Error + Send + Sync>, - driver: DatabaseDriver, - }, - - /// The query was malformed. - #[error("The {driver} query was malformed: {source}")] - InvalidQuery { - source: LocatedError<'static, dyn std::error::Error + Send + Sync>, - driver: DatabaseDriver, - }, - - /// Unable to insert a record into the database - #[error("Unable to insert record into {driver} database, {location}")] - InsertFailed { - location: &'static Location<'static>, - driver: DatabaseDriver, - }, - - /// Unable to delete a record into the database - #[error("Failed to remove record from {driver} database, error-code: {error_code}, {location}")] - DeleteFailed { - location: &'static Location<'static>, - error_code: usize, - driver: DatabaseDriver, - }, - - /// Unable to connect to the database - #[error("Failed to connect to {driver} database: {source}")] - ConnectionError { - source: LocatedError<'static, UrlError>, - driver: DatabaseDriver, - }, - - /// Unable to create a connection pool - #[error("Failed to create r2d2 {driver} connection pool: {source}")] - ConnectionPool { - source: LocatedError<'static, r2d2::Error>, - driver: DatabaseDriver, - }, -} - -impl From for Error { - #[track_caller] - fn from(err: r2d2_sqlite::rusqlite::Error) -> Self { - match err { - r2d2_sqlite::rusqlite::Error::QueryReturnedNoRows => Error::QueryReturnedNoRows { - source: (Arc::new(err) as Arc).into(), - driver: DatabaseDriver::Sqlite3, - }, - _ => Error::InvalidQuery { - source: (Arc::new(err) as Arc).into(), - driver: DatabaseDriver::Sqlite3, - }, - } - } -} - -impl From for Error { - #[track_caller] - fn from(err: r2d2_mysql::mysql::Error) -> Self { - let e: Arc = Arc::new(err); - Error::InvalidQuery { - source: e.into(), - driver: DatabaseDriver::MySQL, - } - } -} - -impl From for Error { - #[track_caller] - fn from(err: UrlError) -> Self { - Self::ConnectionError { - source: Located(err).into(), - driver: DatabaseDriver::MySQL, - } - } -} - -impl From<(r2d2::Error, DatabaseDriver)> for Error { - #[track_caller] - fn from(e: (r2d2::Error, DatabaseDriver)) -> Self { - let (err, driver) = e; - Self::ConnectionPool { - source: Located(err).into(), - driver, - } - } -} diff --git a/src/tracker/databases/mod.rs b/src/tracker/databases/mod.rs deleted file mode 100644 index 3b02415df..000000000 --- a/src/tracker/databases/mod.rs +++ /dev/null @@ -1,230 +0,0 @@ -//! The persistence module. -//! -//! Persistence is currently implemented with one [`Database`](crate::tracker::databases::Database) trait. -//! -//! There are two implementations of the trait (two drivers): -//! -//! - [`Mysql`](crate::tracker::databases::mysql::Mysql) -//! - [`Sqlite`](crate::tracker::databases::sqlite::Sqlite) -//! -//! > **NOTICE**: There are no database migrations. If there are any changes, -//! we will implemented them or provide a script to migrate to the new schema. -//! -//! The persistent objects are: -//! -//! - [Torrent metrics](#torrent-metrics) -//! - [Torrent whitelist](torrent-whitelist) -//! - [Authentication keys](authentication-keys) -//! -//! # Torrent metrics -//! -//! Field | Sample data | Description -//! ---|---|--- -//! `id` | 1 | Autoincrement id -//! `info_hash` | `c1277613db1d28709b034a017ab2cae4be07ae10` | `BitTorrent` infohash V1 -//! `completed` | 20 | The number of peers that have ever completed downloading the torrent associated to this entry. See [`Entry`](crate::tracker::torrent::Entry) for more information. -//! -//! > **NOTICE**: The peer list for a torrent is not persisted. Since peer have to re-announce themselves on intervals, the data is be -//! regenerated again after some minutes. -//! -//! # Torrent whitelist -//! -//! Field | Sample data | Description -//! ---|---|--- -//! `id` | 1 | Autoincrement id -//! `info_hash` | `c1277613db1d28709b034a017ab2cae4be07ae10` | `BitTorrent` infohash V1 -//! -//! # Authentication keys -//! -//! Field | Sample data | Description -//! ---|---|--- -//! `id` | 1 | Autoincrement id -//! `key` | `IrweYtVuQPGbG9Jzx1DihcPmJGGpVy82` | Token -//! `valid_until` | 1672419840 | Timestamp for the expiring date -//! -//! > **NOTICE**: All keys must have an expiration date. -pub mod driver; -pub mod error; -pub mod mysql; -pub mod sqlite; - -use std::marker::PhantomData; - -use async_trait::async_trait; - -use self::error::Error; -use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::auth::{self, Key}; - -pub(self) struct Builder -where - T: Database, -{ - phantom: PhantomData, -} - -impl Builder -where - T: Database + 'static, -{ - /// . - /// - /// # Errors - /// - /// Will return `r2d2::Error` if `db_path` is not able to create a database. - pub(self) fn build(db_path: &str) -> Result, Error> { - Ok(Box::new(T::new(db_path)?)) - } -} - -/// The persistence trait. It contains all the methods to interact with the database. -#[async_trait] -pub trait Database: Sync + Send { - /// It instantiates a new database driver. - /// - /// # Errors - /// - /// Will return `r2d2::Error` if `db_path` is not able to create a database. - fn new(db_path: &str) -> Result - where - Self: std::marker::Sized; - - // Schema - - /// It generates the database tables. SQL queries are hardcoded in the trait - /// implementation. - /// - /// # Context: Schema - /// - /// # Errors - /// - /// Will return `Error` if unable to create own tables. - fn create_database_tables(&self) -> Result<(), Error>; - - /// It drops the database tables. - /// - /// # Context: Schema - /// - /// # Errors - /// - /// Will return `Err` if unable to drop tables. - fn drop_database_tables(&self) -> Result<(), Error>; - - // Torrent Metrics - - /// It loads the torrent metrics data from the database. - /// - /// It returns an array of tuples with the torrent - /// [`InfoHash`](crate::shared::bit_torrent::info_hash::InfoHash) and the - /// [`completed`](crate::tracker::torrent::Entry::completed) counter - /// which is the number of times the torrent has been downloaded. - /// See [`Entry::completed`](crate::tracker::torrent::Entry::completed). - /// - /// # Context: Torrent Metrics - /// - /// # Errors - /// - /// Will return `Err` if unable to load. - async fn load_persistent_torrents(&self) -> Result, Error>; - - /// It saves the torrent metrics data into the database. - /// - /// # Context: Torrent Metrics - /// - /// # Errors - /// - /// Will return `Err` if unable to save. - async fn save_persistent_torrent(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error>; - - // Whitelist - - /// It loads the whitelisted torrents from the database. - /// - /// # Context: Whitelist - /// - /// # Errors - /// - /// Will return `Err` if unable to load. - async fn load_whitelist(&self) -> Result, Error>; - - /// It checks if the torrent is whitelisted. - /// - /// It returns `Some(InfoHash)` if the torrent is whitelisted, `None` otherwise. - /// - /// # Context: Whitelist - /// - /// # Errors - /// - /// Will return `Err` if unable to load. - async fn get_info_hash_from_whitelist(&self, info_hash: &InfoHash) -> Result, Error>; - - /// It adds the torrent to the whitelist. - /// - /// # Context: Whitelist - /// - /// # Errors - /// - /// Will return `Err` if unable to save. - async fn add_info_hash_to_whitelist(&self, info_hash: InfoHash) -> Result; - - /// It checks if the torrent is whitelisted. - /// - /// # Context: Whitelist - /// - /// # Errors - /// - /// Will return `Err` if unable to load. - async fn is_info_hash_whitelisted(&self, info_hash: &InfoHash) -> Result { - Ok(self.get_info_hash_from_whitelist(info_hash).await?.is_some()) - } - - /// It removes the torrent from the whitelist. - /// - /// # Context: Whitelist - /// - /// # Errors - /// - /// Will return `Err` if unable to save. - async fn remove_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result; - - // Authentication keys - - /// It loads the expiring authentication keys from the database. - /// - /// # Context: Authentication Keys - /// - /// # Errors - /// - /// Will return `Err` if unable to load. - async fn load_keys(&self) -> Result, Error>; - - /// It gets an expiring authentication key from the database. - /// - /// It returns `Some(ExpiringKey)` if a [`ExpiringKey`](crate::tracker::auth::ExpiringKey) - /// with the input [`Key`](crate::tracker::auth::Key) exists, `None` otherwise. - /// - /// # Context: Authentication Keys - /// - /// # Errors - /// - /// Will return `Err` if unable to load. - async fn get_key_from_keys(&self, key: &Key) -> Result, Error>; - - /// It adds an expiring authentication key to the database. - /// - /// # Context: Authentication Keys - /// - /// # Errors - /// - /// Will return `Err` if unable to save. - async fn add_key_to_keys(&self, auth_key: &auth::ExpiringKey) -> Result; - - /// It removes an expiring authentication key from the database. - /// - /// # Context: Authentication Keys - /// - /// # Errors - /// - /// Will return `Err` if unable to load. - async fn remove_key_from_keys(&self, key: &Key) -> Result; -} diff --git a/src/tracker/databases/mysql.rs b/src/tracker/databases/mysql.rs deleted file mode 100644 index 4419666ab..000000000 --- a/src/tracker/databases/mysql.rs +++ /dev/null @@ -1,240 +0,0 @@ -//! The `MySQL` database driver. -use std::str::FromStr; -use std::time::Duration; - -use async_trait::async_trait; -use log::debug; -use r2d2::Pool; -use r2d2_mysql::mysql::prelude::Queryable; -use r2d2_mysql::mysql::{params, Opts, OptsBuilder}; -use r2d2_mysql::MySqlConnectionManager; -use torrust_tracker_primitives::DatabaseDriver; - -use super::{Database, Error}; -use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; -use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::auth::{self, Key}; - -const DRIVER: DatabaseDriver = DatabaseDriver::MySQL; - -pub struct Mysql { - pool: Pool, -} - -#[async_trait] -impl Database for Mysql { - /// It instantiates a new `MySQL` database driver. - /// - /// Refer to [`databases::Database::new`](crate::tracker::databases::Database::new). - /// - /// # Errors - /// - /// Will return `r2d2::Error` if `db_path` is not able to create `MySQL` database. - fn new(db_path: &str) -> Result { - let opts = Opts::from_url(db_path)?; - let builder = OptsBuilder::from_opts(opts); - let manager = MySqlConnectionManager::new(builder); - let pool = r2d2::Pool::builder().build(manager).map_err(|e| (e, DRIVER))?; - - Ok(Self { pool }) - } - - /// Refer to [`databases::Database::create_database_tables`](crate::tracker::databases::Database::create_database_tables). - fn create_database_tables(&self) -> Result<(), Error> { - let create_whitelist_table = " - CREATE TABLE IF NOT EXISTS whitelist ( - id integer PRIMARY KEY AUTO_INCREMENT, - info_hash VARCHAR(40) NOT NULL UNIQUE - );" - .to_string(); - - let create_torrents_table = " - CREATE TABLE IF NOT EXISTS torrents ( - id integer PRIMARY KEY AUTO_INCREMENT, - info_hash VARCHAR(40) NOT NULL UNIQUE, - completed INTEGER DEFAULT 0 NOT NULL - );" - .to_string(); - - let create_keys_table = format!( - " - CREATE TABLE IF NOT EXISTS `keys` ( - `id` INT NOT NULL AUTO_INCREMENT, - `key` VARCHAR({}) NOT NULL, - `valid_until` INT(10) NOT NULL, - PRIMARY KEY (`id`), - UNIQUE (`key`) - );", - i8::try_from(AUTH_KEY_LENGTH).expect("auth::Auth Key Length Should fit within a i8!") - ); - - let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - conn.query_drop(&create_torrents_table) - .expect("Could not create torrents table."); - conn.query_drop(&create_keys_table).expect("Could not create keys table."); - conn.query_drop(&create_whitelist_table) - .expect("Could not create whitelist table."); - - Ok(()) - } - - /// Refer to [`databases::Database::drop_database_tables`](crate::tracker::databases::Database::drop_database_tables). - fn drop_database_tables(&self) -> Result<(), Error> { - let drop_whitelist_table = " - DROP TABLE `whitelist`;" - .to_string(); - - let drop_torrents_table = " - DROP TABLE `torrents`;" - .to_string(); - - let drop_keys_table = " - DROP TABLE `keys`;" - .to_string(); - - let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - conn.query_drop(&drop_whitelist_table) - .expect("Could not drop `whitelist` table."); - conn.query_drop(&drop_torrents_table) - .expect("Could not drop `torrents` table."); - conn.query_drop(&drop_keys_table).expect("Could not drop `keys` table."); - - Ok(()) - } - - /// Refer to [`databases::Database::load_persistent_torrents`](crate::tracker::databases::Database::load_persistent_torrents). - async fn load_persistent_torrents(&self) -> Result, Error> { - let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let torrents = conn.query_map( - "SELECT info_hash, completed FROM torrents", - |(info_hash_string, completed): (String, u32)| { - let info_hash = InfoHash::from_str(&info_hash_string).unwrap(); - (info_hash, completed) - }, - )?; - - Ok(torrents) - } - - /// Refer to [`databases::Database::load_keys`](crate::tracker::databases::Database::load_keys). - async fn load_keys(&self) -> Result, Error> { - let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let keys = conn.query_map( - "SELECT `key`, valid_until FROM `keys`", - |(key, valid_until): (String, i64)| auth::ExpiringKey { - key: key.parse::().unwrap(), - valid_until: Duration::from_secs(valid_until.unsigned_abs()), - }, - )?; - - Ok(keys) - } - - /// Refer to [`databases::Database::load_whitelist`](crate::tracker::databases::Database::load_whitelist). - async fn load_whitelist(&self) -> Result, Error> { - let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let info_hashes = conn.query_map("SELECT info_hash FROM whitelist", |info_hash: String| { - InfoHash::from_str(&info_hash).unwrap() - })?; - - Ok(info_hashes) - } - - /// Refer to [`databases::Database::save_persistent_torrent`](crate::tracker::databases::Database::save_persistent_torrent). - async fn save_persistent_torrent(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { - const COMMAND : &str = "INSERT INTO torrents (info_hash, completed) VALUES (:info_hash_str, :completed) ON DUPLICATE KEY UPDATE completed = VALUES(completed)"; - - let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let info_hash_str = info_hash.to_string(); - - debug!("{}", info_hash_str); - - Ok(conn.exec_drop(COMMAND, params! { info_hash_str, completed })?) - } - - /// Refer to [`databases::Database::get_info_hash_from_whitelist`](crate::tracker::databases::Database::get_info_hash_from_whitelist). - async fn get_info_hash_from_whitelist(&self, info_hash: &InfoHash) -> Result, Error> { - let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let select = conn.exec_first::( - "SELECT info_hash FROM whitelist WHERE info_hash = :info_hash", - params! { "info_hash" => info_hash.to_hex_string() }, - )?; - - let info_hash = select.map(|f| InfoHash::from_str(&f).expect("Failed to decode InfoHash String from DB!")); - - Ok(info_hash) - } - - /// Refer to [`databases::Database::add_info_hash_to_whitelist`](crate::tracker::databases::Database::add_info_hash_to_whitelist). - async fn add_info_hash_to_whitelist(&self, info_hash: InfoHash) -> Result { - let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let info_hash_str = info_hash.to_string(); - - conn.exec_drop( - "INSERT INTO whitelist (info_hash) VALUES (:info_hash_str)", - params! { info_hash_str }, - )?; - - Ok(1) - } - - /// Refer to [`databases::Database::remove_info_hash_from_whitelist`](crate::tracker::databases::Database::remove_info_hash_from_whitelist). - async fn remove_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result { - let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let info_hash = info_hash.to_string(); - - conn.exec_drop("DELETE FROM whitelist WHERE info_hash = :info_hash", params! { info_hash })?; - - Ok(1) - } - - /// Refer to [`databases::Database::get_key_from_keys`](crate::tracker::databases::Database::get_key_from_keys). - async fn get_key_from_keys(&self, key: &Key) -> Result, Error> { - let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let query = conn.exec_first::<(String, i64), _, _>( - "SELECT `key`, valid_until FROM `keys` WHERE `key` = :key", - params! { "key" => key.to_string() }, - ); - - let key = query?; - - Ok(key.map(|(key, expiry)| auth::ExpiringKey { - key: key.parse::().unwrap(), - valid_until: Duration::from_secs(expiry.unsigned_abs()), - })) - } - - /// Refer to [`databases::Database::add_key_to_keys`](crate::tracker::databases::Database::add_key_to_keys). - async fn add_key_to_keys(&self, auth_key: &auth::ExpiringKey) -> Result { - let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let key = auth_key.key.to_string(); - let valid_until = auth_key.valid_until.as_secs().to_string(); - - conn.exec_drop( - "INSERT INTO `keys` (`key`, valid_until) VALUES (:key, :valid_until)", - params! { key, valid_until }, - )?; - - Ok(1) - } - - /// Refer to [`databases::Database::remove_key_from_keys`](crate::tracker::databases::Database::remove_key_from_keys). - async fn remove_key_from_keys(&self, key: &Key) -> Result { - let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - conn.exec_drop("DELETE FROM `keys` WHERE key = :key", params! { "key" => key.to_string() })?; - - Ok(1) - } -} diff --git a/src/tracker/databases/sqlite.rs b/src/tracker/databases/sqlite.rs deleted file mode 100644 index 1968ee049..000000000 --- a/src/tracker/databases/sqlite.rs +++ /dev/null @@ -1,273 +0,0 @@ -//! The `SQLite3` database driver. -use std::panic::Location; -use std::str::FromStr; - -use async_trait::async_trait; -use r2d2::Pool; -use r2d2_sqlite::SqliteConnectionManager; -use torrust_tracker_primitives::DatabaseDriver; - -use super::{Database, Error}; -use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::shared::clock::DurationSinceUnixEpoch; -use crate::tracker::auth::{self, Key}; - -const DRIVER: DatabaseDriver = DatabaseDriver::Sqlite3; - -pub struct Sqlite { - pool: Pool, -} - -#[async_trait] -impl Database for Sqlite { - /// It instantiates a new `SQLite3` database driver. - /// - /// Refer to [`databases::Database::new`](crate::tracker::databases::Database::new). - /// - /// # Errors - /// - /// Will return `r2d2::Error` if `db_path` is not able to create `SqLite` database. - fn new(db_path: &str) -> Result { - let cm = SqliteConnectionManager::file(db_path); - Pool::new(cm).map_or_else(|err| Err((err, DatabaseDriver::Sqlite3).into()), |pool| Ok(Sqlite { pool })) - } - - /// Refer to [`databases::Database::create_database_tables`](crate::tracker::databases::Database::create_database_tables). - fn create_database_tables(&self) -> Result<(), Error> { - let create_whitelist_table = " - CREATE TABLE IF NOT EXISTS whitelist ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - info_hash TEXT NOT NULL UNIQUE - );" - .to_string(); - - let create_torrents_table = " - CREATE TABLE IF NOT EXISTS torrents ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - info_hash TEXT NOT NULL UNIQUE, - completed INTEGER DEFAULT 0 NOT NULL - );" - .to_string(); - - let create_keys_table = " - CREATE TABLE IF NOT EXISTS keys ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - key TEXT NOT NULL UNIQUE, - valid_until INTEGER NOT NULL - );" - .to_string(); - - let conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - conn.execute(&create_whitelist_table, [])?; - conn.execute(&create_keys_table, [])?; - conn.execute(&create_torrents_table, [])?; - - Ok(()) - } - - /// Refer to [`databases::Database::drop_database_tables`](crate::tracker::databases::Database::drop_database_tables). - fn drop_database_tables(&self) -> Result<(), Error> { - let drop_whitelist_table = " - DROP TABLE whitelist;" - .to_string(); - - let drop_torrents_table = " - DROP TABLE torrents;" - .to_string(); - - let drop_keys_table = " - DROP TABLE keys;" - .to_string(); - - let conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - conn.execute(&drop_whitelist_table, []) - .and_then(|_| conn.execute(&drop_torrents_table, [])) - .and_then(|_| conn.execute(&drop_keys_table, []))?; - - Ok(()) - } - - /// Refer to [`databases::Database::load_persistent_torrents`](crate::tracker::databases::Database::load_persistent_torrents). - async fn load_persistent_torrents(&self) -> Result, Error> { - let conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let mut stmt = conn.prepare("SELECT info_hash, completed FROM torrents")?; - - let torrent_iter = stmt.query_map([], |row| { - let info_hash_string: String = row.get(0)?; - let info_hash = InfoHash::from_str(&info_hash_string).unwrap(); - let completed: u32 = row.get(1)?; - Ok((info_hash, completed)) - })?; - - //torrent_iter?; - //let torrent_iter = torrent_iter.unwrap(); - - let torrents: Vec<(InfoHash, u32)> = torrent_iter.filter_map(std::result::Result::ok).collect(); - - Ok(torrents) - } - - /// Refer to [`databases::Database::load_keys`](crate::tracker::databases::Database::load_keys). - async fn load_keys(&self) -> Result, Error> { - let conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let mut stmt = conn.prepare("SELECT key, valid_until FROM keys")?; - - let keys_iter = stmt.query_map([], |row| { - let key: String = row.get(0)?; - let valid_until: i64 = row.get(1)?; - - Ok(auth::ExpiringKey { - key: key.parse::().unwrap(), - valid_until: DurationSinceUnixEpoch::from_secs(valid_until.unsigned_abs()), - }) - })?; - - let keys: Vec = keys_iter.filter_map(std::result::Result::ok).collect(); - - Ok(keys) - } - - /// Refer to [`databases::Database::load_whitelist`](crate::tracker::databases::Database::load_whitelist). - async fn load_whitelist(&self) -> Result, Error> { - let conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let mut stmt = conn.prepare("SELECT info_hash FROM whitelist")?; - - let info_hash_iter = stmt.query_map([], |row| { - let info_hash: String = row.get(0)?; - - Ok(InfoHash::from_str(&info_hash).unwrap()) - })?; - - let info_hashes: Vec = info_hash_iter.filter_map(std::result::Result::ok).collect(); - - Ok(info_hashes) - } - - /// Refer to [`databases::Database::save_persistent_torrent`](crate::tracker::databases::Database::save_persistent_torrent). - async fn save_persistent_torrent(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { - let conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let insert = conn.execute( - "INSERT INTO torrents (info_hash, completed) VALUES (?1, ?2) ON CONFLICT(info_hash) DO UPDATE SET completed = ?2", - [info_hash.to_string(), completed.to_string()], - )?; - - if insert == 0 { - Err(Error::InsertFailed { - location: Location::caller(), - driver: DRIVER, - }) - } else { - Ok(()) - } - } - - /// Refer to [`databases::Database::get_info_hash_from_whitelist`](crate::tracker::databases::Database::get_info_hash_from_whitelist). - async fn get_info_hash_from_whitelist(&self, info_hash: &InfoHash) -> Result, Error> { - let conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let mut stmt = conn.prepare("SELECT info_hash FROM whitelist WHERE info_hash = ?")?; - - let mut rows = stmt.query([info_hash.to_hex_string()])?; - - let query = rows.next()?; - - Ok(query.map(|f| InfoHash::from_str(&f.get_unwrap::<_, String>(0)).unwrap())) - } - - /// Refer to [`databases::Database::add_info_hash_to_whitelist`](crate::tracker::databases::Database::add_info_hash_to_whitelist). - async fn add_info_hash_to_whitelist(&self, info_hash: InfoHash) -> Result { - let conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let insert = conn.execute("INSERT INTO whitelist (info_hash) VALUES (?)", [info_hash.to_string()])?; - - if insert == 0 { - Err(Error::InsertFailed { - location: Location::caller(), - driver: DRIVER, - }) - } else { - Ok(insert) - } - } - - /// Refer to [`databases::Database::remove_info_hash_from_whitelist`](crate::tracker::databases::Database::remove_info_hash_from_whitelist). - async fn remove_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result { - let conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let deleted = conn.execute("DELETE FROM whitelist WHERE info_hash = ?", [info_hash.to_string()])?; - - if deleted == 1 { - // should only remove a single record. - Ok(deleted) - } else { - Err(Error::DeleteFailed { - location: Location::caller(), - error_code: deleted, - driver: DRIVER, - }) - } - } - - /// Refer to [`databases::Database::get_key_from_keys`](crate::tracker::databases::Database::get_key_from_keys). - async fn get_key_from_keys(&self, key: &Key) -> Result, Error> { - let conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let mut stmt = conn.prepare("SELECT key, valid_until FROM keys WHERE key = ?")?; - - let mut rows = stmt.query([key.to_string()])?; - - let key = rows.next()?; - - Ok(key.map(|f| { - let expiry: i64 = f.get(1).unwrap(); - let key: String = f.get(0).unwrap(); - auth::ExpiringKey { - key: key.parse::().unwrap(), - valid_until: DurationSinceUnixEpoch::from_secs(expiry.unsigned_abs()), - } - })) - } - - /// Refer to [`databases::Database::add_key_to_keys`](crate::tracker::databases::Database::add_key_to_keys). - async fn add_key_to_keys(&self, auth_key: &auth::ExpiringKey) -> Result { - let conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let insert = conn.execute( - "INSERT INTO keys (key, valid_until) VALUES (?1, ?2)", - [auth_key.key.to_string(), auth_key.valid_until.as_secs().to_string()], - )?; - - if insert == 0 { - Err(Error::InsertFailed { - location: Location::caller(), - driver: DRIVER, - }) - } else { - Ok(insert) - } - } - - /// Refer to [`databases::Database::remove_key_from_keys`](crate::tracker::databases::Database::remove_key_from_keys). - async fn remove_key_from_keys(&self, key: &Key) -> Result { - let conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let deleted = conn.execute("DELETE FROM keys WHERE key = ?", [key.to_string()])?; - - if deleted == 1 { - // should only remove a single record. - Ok(deleted) - } else { - Err(Error::DeleteFailed { - location: Location::caller(), - error_code: deleted, - driver: DRIVER, - }) - } - } -} diff --git a/src/tracker/error.rs b/src/tracker/error.rs deleted file mode 100644 index f1e622673..000000000 --- a/src/tracker/error.rs +++ /dev/null @@ -1,31 +0,0 @@ -//! Error returned by the core `Tracker`. -//! -//! Error | Context | Description -//! ---|---|--- -//! `PeerKeyNotValid` | Authentication | The supplied key is not valid. It may not be registered or expired. -//! `PeerNotAuthenticated` | Authentication | The peer did not provide the authentication key. -//! `TorrentNotWhitelisted` | Authorization | The action cannot be perform on a not-whitelisted torrent (it only applies for trackers running in `listed` or `private_listed` modes). -//! -use std::panic::Location; - -use torrust_tracker_located_error::LocatedError; - -/// Authentication or authorization error returned by the core `Tracker` -#[derive(thiserror::Error, Debug, Clone)] -pub enum Error { - // Authentication errors - #[error("The supplied key: {key:?}, is not valid: {source}")] - PeerKeyNotValid { - key: super::auth::Key, - source: LocatedError<'static, dyn std::error::Error + Send + Sync>, - }, - #[error("The peer is not authenticated, {location}")] - PeerNotAuthenticated { location: &'static Location<'static> }, - - // Authorization errors - #[error("The torrent: {info_hash}, is not whitelisted, {location}")] - TorrentNotWhitelisted { - info_hash: crate::shared::bit_torrent::info_hash::InfoHash, - location: &'static Location<'static>, - }, -} diff --git a/src/tracker/mod.rs b/src/tracker/mod.rs deleted file mode 100644 index 0d3263988..000000000 --- a/src/tracker/mod.rs +++ /dev/null @@ -1,1805 +0,0 @@ -//! The core `tracker` module contains the generic `BitTorrent` tracker logic which is independent of the delivery layer. -//! -//! It contains the tracker services and their dependencies. It's a domain layer which does not -//! specify how the end user should connect to the `Tracker`. -//! -//! Typically this module is intended to be used by higher modules like: -//! -//! - A UDP tracker -//! - A HTTP tracker -//! - A tracker REST API -//! -//! ```text -//! Delivery layer Domain layer -//! -//! HTTP tracker | -//! UDP tracker |> Core tracker -//! Tracker REST API | -//! ``` -//! -//! # Table of contents -//! -//! - [Tracker](#tracker) -//! - [Announce request](#announce-request) -//! - [Scrape request](#scrape-request) -//! - [Torrents](#torrents) -//! - [Peers](#peers) -//! - [Configuration](#configuration) -//! - [Services](#services) -//! - [Authentication](#authentication) -//! - [Statistics](#statistics) -//! - [Persistence](#persistence) -//! -//! # Tracker -//! -//! The `Tracker` is the main struct in this module. `The` tracker has some groups of responsibilities: -//! -//! - **Core tracker**: it handles the information about torrents and peers. -//! - **Authentication**: it handles authentication keys which are used by HTTP trackers. -//! - **Authorization**: it handles the permission to perform requests. -//! - **Whitelist**: when the tracker runs in `listed` or `private_listed` mode all operations are restricted to whitelisted torrents. -//! - **Statistics**: it keeps and serves the tracker statistics. -//! -//! Refer to [torrust-tracker-configuration](https://docs.rs/torrust-tracker-configuration) crate docs to get more information about the tracker settings. -//! -//! ## Announce request -//! -//! Handling `announce` requests is the most important task for a `BitTorrent` tracker. -//! -//! A `BitTorrent` swarm is a network of peers that are all trying to download the same torrent. -//! When a peer wants to find other peers it announces itself to the swarm via the tracker. -//! The peer sends its data to the tracker so that the tracker can add it to the swarm. -//! The tracker responds to the peer with the list of other peers in the swarm so that -//! the peer can contact them to start downloading pieces of the file from them. -//! -//! Once you have instantiated the `Tracker` you can `announce` a new [`peer`](crate::tracker::peer::Peer) with: -//! -//! ```rust,no_run -//! use torrust_tracker::tracker::peer; -//! use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -//! use torrust_tracker::shared::clock::DurationSinceUnixEpoch; -//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; -//! use std::net::SocketAddr; -//! use std::net::IpAddr; -//! use std::net::Ipv4Addr; -//! use std::str::FromStr; -//! -//! -//! let info_hash = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(); -//! -//! let peer = peer::Peer { -//! peer_id: peer::Id(*b"-qB00000000000000001"), -//! peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), -//! updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), -//! uploaded: NumberOfBytes(0), -//! downloaded: NumberOfBytes(0), -//! left: NumberOfBytes(0), -//! event: AnnounceEvent::Completed, -//! }; -//! -//! let peer_ip = IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()); -//! ``` -//! -//! ```text -//! let announce_data = tracker.announce(&info_hash, &mut peer, &peer_ip).await; -//! ``` -//! -//! The `Tracker` returns the list of peers for the torrent with the infohash `3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0`, -//! filtering out the peer that is making the `announce` request. -//! -//! > **NOTICE**: that the peer argument is mutable because the `Tracker` can change the peer IP if the peer is using a loopback IP. -//! -//! The `peer_ip` argument is the resolved peer ip. It's a common practice that trackers ignore the peer ip in the `announce` request params, -//! and resolve the peer ip using the IP of the client making the request. As the tracker is a domain service, the peer IP must be provided -//! for the `Tracker` user, which is usually a higher component with access the the request metadata, for example, connection data, proxy headers, -//! etcetera. -//! -//! The returned struct is: -//! -//! ```rust,no_run -//! use torrust_tracker::tracker::peer::Peer; -//! -//! pub struct AnnounceData { -//! pub peers: Vec, -//! pub swarm_stats: SwarmStats, -//! pub interval: u32, // Option `announce_interval` from core tracker configuration -//! pub interval_min: u32, // Option `min_announce_interval` from core tracker configuration -//! } -//! -//! pub struct SwarmStats { -//! pub completed: u32, // The number of peers that have ever completed downloading -//! pub seeders: u32, // The number of active peers that have completed downloading (seeders) -//! pub leechers: u32, // The number of active peers that have not completed downloading (leechers) -//! } -//! -//! // Core tracker configuration -//! pub struct Configuration { -//! // ... -//! pub announce_interval: u32, // Interval in seconds that the client should wait between sending regular announce requests to the tracker -//! pub min_announce_interval: u32, // Minimum announce interval. Clients must not reannounce more frequently than this -//! // ... -//! } -//! ``` -//! -//! Refer to `BitTorrent` BEPs and other sites for more information about the `announce` request: -//! -//! - [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -//! - [BEP 23. Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) -//! - [Vuze docs](https://wiki.vuze.com/w/Announce) -//! -//! ## Scrape request -//! -//! The `scrape` request allows clients to query metadata about the swarm in bulk. -//! -//! An `scrape` request includes a list of infohashes whose swarm metadata you want to collect. -//! -//! The returned struct is: -//! -//! ```rust,no_run -//! use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -//! use std::collections::HashMap; -//! -//! pub struct ScrapeData { -//! pub files: HashMap, -//! } -//! -//! pub struct SwarmMetadata { -//! pub complete: u32, // The number of active peers that have completed downloading (seeders) -//! pub downloaded: u32, // The number of peers that have ever completed downloading -//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers) -//! } -//! ``` -//! -//! The JSON representation of a sample `scrape` response would be like the following: -//! -//! ```json -//! { -//! 'files': { -//! 'xxxxxxxxxxxxxxxxxxxx': {'complete': 11, 'downloaded': 13772, 'incomplete': 19}, -//! 'yyyyyyyyyyyyyyyyyyyy': {'complete': 21, 'downloaded': 206, 'incomplete': 20} -//! } -//! } -//! ``` -//! -//! `xxxxxxxxxxxxxxxxxxxx` and `yyyyyyyyyyyyyyyyyyyy` are 20-byte infohash arrays. -//! There are two data structures for infohashes: byte arrays and hex strings: -//! -//! ```rust,no_run -//! use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -//! use std::str::FromStr; -//! -//! let info_hash: InfoHash = [255u8; 20].into(); -//! -//! assert_eq!( -//! info_hash, -//! InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap() -//! ); -//! ``` -//! Refer to `BitTorrent` BEPs and other sites for more information about the `scrape` request: -//! -//! - [BEP 48. Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) -//! - [BEP 15. UDP Tracker Protocol for `BitTorrent`. Scrape section](https://www.bittorrent.org/beps/bep_0015.html) -//! - [Vuze docs](https://wiki.vuze.com/w/Scrape) -//! -//! ## Torrents -//! -//! The [`torrent`](crate::tracker::torrent) module contains all the data structures stored by the `Tracker` except for peers. -//! -//! We can represent the data stored in memory internally by the `Tracker` with this JSON object: -//! -//! ```json -//! { -//! "c1277613db1d28709b034a017ab2cae4be07ae10": { -//! "completed": 0, -//! "peers": { -//! "-qB00000000000000001": { -//! "peer_id": "-qB00000000000000001", -//! "peer_addr": "2.137.87.41:1754", -//! "updated": 1672419840, -//! "uploaded": 120, -//! "downloaded": 60, -//! "left": 60, -//! "event": "started" -//! }, -//! "-qB00000000000000002": { -//! "peer_id": "-qB00000000000000002", -//! "peer_addr": "23.17.287.141:2345", -//! "updated": 1679415984, -//! "uploaded": 80, -//! "downloaded": 20, -//! "left": 40, -//! "event": "started" -//! } -//! } -//! } -//! } -//! ``` -//! -//! The `Tracker` maintains an indexed-by-info-hash list of torrents. For each torrent, it stores a torrent `Entry`. -//! The torrent entry has two attributes: -//! -//! - `completed`: which is hte number of peers that have completed downloading the torrent file/s. As they have completed downloading, -//! they have a full version of the torrent data, and they can provide the full data to other peers. That's why they are also known as "seeders". -//! - `peers`: an indexed and orderer list of peer for the torrent. Each peer contains the data received from the peer in the `announce` request. -//! -//! The [`torrent`](crate::tracker::torrent) module not only contains the original data obtained from peer via `announce` requests, it also contains -//! aggregate data that can be derived from the original data. For example: -//! -//! ```rust,no_run -//! pub struct SwarmMetadata { -//! pub complete: u32, // The number of active peers that have completed downloading (seeders) -//! pub downloaded: u32, // The number of peers that have ever completed downloading -//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers) -//! } -//! -//! pub struct SwarmStats { -//! pub completed: u32, // The number of peers that have ever completed downloading -//! pub seeders: u32, // The number of active peers that have completed downloading (seeders) -//! pub leechers: u32, // The number of active peers that have not completed downloading (leechers) -//! } -//! ``` -//! -//! > **NOTICE**: that `complete` or `completed` peers are the peers that have completed downloading, but only the active ones are considered "seeders". -//! -//! `SwarmStats` struct follows name conventions for `scrape` responses. See [BEP 48](https://www.bittorrent.org/beps/bep_0048.html), while `SwarmStats` -//! is used for the rest of cases. -//! -//! Refer to [`torrent`](crate::tracker::torrent) module for more details about these data structures. -//! -//! ## Peers -//! -//! A `Peer` is the struct used by the `Tracker` to keep peers data: -//! -//! ```rust,no_run -//! use torrust_tracker::tracker::peer::Id; -//! use std::net::SocketAddr; -//! use torrust_tracker::shared::clock::DurationSinceUnixEpoch; -//! use aquatic_udp_protocol::NumberOfBytes; -//! use aquatic_udp_protocol::AnnounceEvent; -//! -//! pub struct Peer { -//! pub peer_id: Id, // The peer ID -//! pub peer_addr: SocketAddr, // Peer socket address -//! pub updated: DurationSinceUnixEpoch, // Last time (timestamp) when the peer was updated -//! pub uploaded: NumberOfBytes, // Number of bytes the peer has uploaded so far -//! pub downloaded: NumberOfBytes, // Number of bytes the peer has downloaded so far -//! pub left: NumberOfBytes, // The number of bytes this peer still has to download -//! pub event: AnnounceEvent, // The event the peer has announced: `started`, `completed`, `stopped` -//! } -//! ``` -//! -//! Notice that most of the attributes are obtained from the `announce` request. -//! For example, an HTTP announce request would contain the following `GET` parameters: -//! -//! -//! -//! The `Tracker` keeps an in-memory ordered data structure with all the torrents and a list of peers for each torrent, together with some swarm metrics. -//! -//! We can represent the data stored in memory with this JSON object: -//! -//! ```json -//! { -//! "c1277613db1d28709b034a017ab2cae4be07ae10": { -//! "completed": 0, -//! "peers": { -//! "-qB00000000000000001": { -//! "peer_id": "-qB00000000000000001", -//! "peer_addr": "2.137.87.41:1754", -//! "updated": 1672419840, -//! "uploaded": 120, -//! "downloaded": 60, -//! "left": 60, -//! "event": "started" -//! }, -//! "-qB00000000000000002": { -//! "peer_id": "-qB00000000000000002", -//! "peer_addr": "23.17.287.141:2345", -//! "updated": 1679415984, -//! "uploaded": 80, -//! "downloaded": 20, -//! "left": 40, -//! "event": "started" -//! } -//! } -//! } -//! } -//! ``` -//! -//! That JSON object does not exist, it's only a representation of the `Tracker` torrents data. -//! -//! `c1277613db1d28709b034a017ab2cae4be07ae10` is the torrent infohash and `completed` contains the number of peers -//! that have a full version of the torrent data, also known as seeders. -//! -//! Refer to [`peer`](crate::tracker::peer) module for more information about peers. -//! -//! # Configuration -//! -//! You can control the behavior of this module with the module settings: -//! -//! ```toml -//! log_level = "debug" -//! mode = "public" -//! db_driver = "Sqlite3" -//! db_path = "./storage/database/data.db" -//! announce_interval = 120 -//! min_announce_interval = 120 -//! max_peer_timeout = 900 -//! on_reverse_proxy = false -//! external_ip = "2.137.87.41" -//! tracker_usage_statistics = true -//! persistent_torrent_completed_stat = true -//! inactive_peer_cleanup_interval = 600 -//! remove_peerless_torrents = false -//! ``` -//! -//! Refer to the [`configuration` module documentation](https://docs.rs/torrust-tracker-configuration) to get more information about all options. -//! -//! # Services -//! -//! Services are domain services on top of the core tracker. Right now there are two types of service: -//! -//! - For statistics -//! - For torrents -//! -//! Services usually format the data inside the tracker to make it easier to consume by other parts. -//! They also decouple the internal data structure, used by the tracker, from the way we deliver that data to the consumers. -//! The internal data structure is designed for performance or low memory consumption. And it should be changed -//! without affecting the external consumers. -//! -//! Services can include extra features like pagination, for example. -//! -//! Refer to [`services`](crate::tracker::services) module for more information about services. -//! -//! # Authentication -//! -//! One of the core `Tracker` responsibilities is to create and keep authentication keys. Auth keys are used by HTTP trackers -//! when the tracker is running in `private` or `private_listed` mode. -//! -//! HTTP tracker's clients need to obtain an auth key before starting requesting the tracker. Once the get one they have to include -//! a `PATH` param with the key in all the HTTP requests. For example, when a peer wants to `announce` itself it has to use the -//! HTTP tracker endpoint `GET /announce/:key`. -//! -//! The common way to obtain the keys is by using the tracker API directly or via other applications like the [Torrust Index](https://github.com/torrust/torrust-index). -//! -//! To learn more about tracker authentication, refer to the following modules : -//! -//! - [`auth`](crate::tracker::auth) module. -//! - [`tracker`](crate::tracker) module. -//! - [`http`](crate::servers::http) module. -//! -//! # Statistics -//! -//! The `Tracker` keeps metrics for some events: -//! -//! ```rust,no_run -//! pub struct Metrics { -//! // IP version 4 -//! -//! // HTTP tracker -//! pub tcp4_connections_handled: u64, -//! pub tcp4_announces_handled: u64, -//! pub tcp4_scrapes_handled: u64, -//! -//! // UDP tracker -//! pub udp4_connections_handled: u64, -//! pub udp4_announces_handled: u64, -//! pub udp4_scrapes_handled: u64, -//! -//! // IP version 6 -//! -//! // HTTP tracker -//! pub tcp6_connections_handled: u64, -//! pub tcp6_announces_handled: u64, -//! pub tcp6_scrapes_handled: u64, -//! -//! // UDP tracker -//! pub udp6_connections_handled: u64, -//! pub udp6_announces_handled: u64, -//! pub udp6_scrapes_handled: u64, -//! } -//! ``` -//! -//! The metrics maintained by the `Tracker` are: -//! -//! - `connections_handled`: number of connections handled by the tracker -//! - `announces_handled`: number of `announce` requests handled by the tracker -//! - `scrapes_handled`: number of `scrape` handled requests by the tracker -//! -//! > **NOTICE**: as the HTTP tracker does not have an specific `connection` request like the UDP tracker, `connections_handled` are -//! increased on every `announce` and `scrape` requests. -//! -//! The tracker exposes an event sender API that allows the tracker users to send events. When a higher application service handles a -//! `connection` , `announce` or `scrape` requests, it notifies the `Tracker` by sending statistics events. -//! -//! For example, the HTTP tracker would send an event like the following when it handles an `announce` request received from a peer using IP version 4. -//! -//! ```text -//! tracker.send_stats_event(statistics::Event::Tcp4Announce).await -//! ``` -//! -//! Refer to [`statistics`](crate::tracker::statistics) module for more information about statistics. -//! -//! # Persistence -//! -//! Right now the `Tracker` is responsible for storing and load data into and -//! from the database, when persistence is enabled. -//! -//! There are three types of persistent object: -//! -//! - Authentication keys (only expiring keys) -//! - Torrent whitelist -//! - Torrent metrics -//! -//! Refer to [`databases`](crate::tracker::databases) module for more information about persistence. -pub mod auth; -pub mod databases; -pub mod error; -pub mod peer; -pub mod services; -pub mod statistics; -pub mod torrent; - -use std::collections::btree_map::Entry; -use std::collections::{BTreeMap, HashMap}; -use std::net::IpAddr; -use std::panic::Location; -use std::sync::Arc; -use std::time::Duration; - -use tokio::sync::mpsc::error::SendError; -use tokio::sync::{RwLock, RwLockReadGuard}; -use torrust_tracker_configuration::Configuration; -use torrust_tracker_primitives::TrackerMode; - -use self::auth::Key; -use self::error::Error; -use self::peer::Peer; -use self::torrent::{SwarmMetadata, SwarmStats}; -use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::databases::Database; - -/// The domain layer tracker service. -/// -/// Its main responsibility is to handle the `announce` and `scrape` requests. -/// But it's also a container for the `Tracker` configuration, persistence, -/// authentication and other services. -/// -/// > **NOTICE**: the `Tracker` is not responsible for handling the network layer. -/// Typically, the `Tracker` is used by a higher application service that handles -/// the network layer. -pub struct Tracker { - /// `Tracker` configuration. See [`torrust-tracker-configuration`](torrust_tracker_configuration) - pub config: Arc, - /// A database driver implementation: [`Sqlite3`](crate::tracker::databases::sqlite) - /// or [`MySQL`](crate::tracker::databases::mysql) - pub database: Box, - mode: TrackerMode, - keys: RwLock>, - whitelist: RwLock>, - torrents: RwLock>, - stats_event_sender: Option>, - stats_repository: statistics::Repo, -} - -/// Structure that holds general `Tracker` torrents metrics. -/// -/// Metrics are aggregate values for all torrents. -#[derive(Debug, PartialEq, Default)] -pub struct TorrentsMetrics { - /// Total number of seeders for all torrents - pub seeders: u64, - /// Total number of peers that have ever completed downloading for all torrents. - pub completed: u64, - /// Total number of leechers for all torrents. - pub leechers: u64, - /// Total number of torrents. - pub torrents: u64, -} - -/// Structure that holds the data returned by the `announce` request. -#[derive(Debug, PartialEq, Default)] -pub struct AnnounceData { - /// The list of peers that are downloading the same torrent. - /// It excludes the peer that made the request. - pub peers: Vec, - /// Swarm statistics - pub swarm_stats: SwarmStats, - /// The interval in seconds that the client should wait between sending - /// regular requests to the tracker. - /// Refer to [`announce_interval`](torrust_tracker_configuration::Configuration::announce_interval). - pub interval: u32, - /// The minimum announce interval in seconds that the client should wait. - /// Refer to [`min_announce_interval`](torrust_tracker_configuration::Configuration::min_announce_interval). - pub interval_min: u32, -} - -/// Structure that holds the data returned by the `scrape` request. -#[derive(Debug, PartialEq, Default)] -pub struct ScrapeData { - /// A map of infohashes and swarm metadata for each torrent. - pub files: HashMap, -} - -impl ScrapeData { - /// Creates a new empty `ScrapeData` with no files (torrents). - #[must_use] - pub fn empty() -> Self { - let files: HashMap = HashMap::new(); - Self { files } - } - - /// Creates a new `ScrapeData` with zeroed metadata for each torrent. - #[must_use] - pub fn zeroed(info_hashes: &Vec) -> Self { - let mut scrape_data = Self::empty(); - - for info_hash in info_hashes { - scrape_data.add_file(info_hash, SwarmMetadata::zeroed()); - } - - scrape_data - } - - /// Adds a torrent to the `ScrapeData`. - pub fn add_file(&mut self, info_hash: &InfoHash, swarm_metadata: SwarmMetadata) { - self.files.insert(*info_hash, swarm_metadata); - } - - /// Adds a torrent to the `ScrapeData` with zeroed metadata. - pub fn add_file_with_zeroed_metadata(&mut self, info_hash: &InfoHash) { - self.files.insert(*info_hash, SwarmMetadata::zeroed()); - } -} - -impl Tracker { - /// `Tracker` constructor. - /// - /// # Errors - /// - /// Will return a `databases::error::Error` if unable to connect to database. The `Tracker` is responsible for the persistence. - pub fn new( - config: Arc, - stats_event_sender: Option>, - stats_repository: statistics::Repo, - ) -> Result { - let database = databases::driver::build(&config.db_driver, &config.db_path)?; - - let mode = config.mode; - - Ok(Tracker { - config, - mode, - keys: RwLock::new(std::collections::HashMap::new()), - whitelist: RwLock::new(std::collections::HashSet::new()), - torrents: RwLock::new(std::collections::BTreeMap::new()), - stats_event_sender, - stats_repository, - database, - }) - } - - /// Returns `true` is the tracker is in public mode. - pub fn is_public(&self) -> bool { - self.mode == TrackerMode::Public - } - - /// Returns `true` is the tracker is in private mode. - pub fn is_private(&self) -> bool { - self.mode == TrackerMode::Private || self.mode == TrackerMode::PrivateListed - } - - /// Returns `true` is the tracker is in whitelisted mode. - pub fn is_whitelisted(&self) -> bool { - self.mode == TrackerMode::Listed || self.mode == TrackerMode::PrivateListed - } - - /// Returns `true` if the tracker requires authentication. - pub fn requires_authentication(&self) -> bool { - self.is_private() - } - - /// It handles an announce request. - /// - /// # Context: Tracker - /// - /// BEP 03: [The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html). - pub async fn announce(&self, info_hash: &InfoHash, peer: &mut Peer, remote_client_ip: &IpAddr) -> AnnounceData { - // code-review: maybe instead of mutating the peer we could just return - // a tuple with the new peer and the announce data: (Peer, AnnounceData). - // It could even be a different struct: `StoredPeer` or `PublicPeer`. - - // code-review: in the `scrape` function we perform an authorization check. - // We check if the torrent is whitelisted. Should we also check authorization here? - // I think so because the `Tracker` has the responsibility for checking authentication and authorization. - // The `Tracker` has delegated that responsibility to the handlers - // (because we want to return a friendly error response) but that does not mean we should - // double-check authorization at this domain level too. - // I would propose to return a `Result` here. - // Besides, regarding authentication the `Tracker` is also responsible for authentication but - // we are actually handling authentication at the handlers level. So I would extract that - // responsibility into another authentication service. - - peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.get_ext_ip())); - - let swarm_stats = self.update_torrent_with_peer_and_get_stats(info_hash, peer).await; - - let peers = self.get_peers_for_peer(info_hash, peer).await; - - AnnounceData { - peers, - swarm_stats, - interval: self.config.announce_interval, - interval_min: self.config.min_announce_interval, - } - } - - /// It handles a scrape request. - /// - /// # Context: Tracker - /// - /// BEP 48: [Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html). - pub async fn scrape(&self, info_hashes: &Vec) -> ScrapeData { - let mut scrape_data = ScrapeData::empty(); - - for info_hash in info_hashes { - let swarm_metadata = match self.authorize(info_hash).await { - Ok(_) => self.get_swarm_metadata(info_hash).await, - Err(_) => SwarmMetadata::zeroed(), - }; - scrape_data.add_file(info_hash, swarm_metadata); - } - - scrape_data - } - - /// It returns the data for a `scrape` response. - async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { - let torrents = self.get_torrents().await; - match torrents.get(info_hash) { - Some(torrent_entry) => torrent_entry.get_swarm_metadata(), - None => SwarmMetadata::default(), - } - } - - /// It loads the torrents from database into memory. It only loads the torrent entry list with the number of seeders for each torrent. - /// Peers data is not persisted. - /// - /// # Context: Tracker - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to load the list of `persistent_torrents` from the database. - pub async fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { - let persistent_torrents = self.database.load_persistent_torrents().await?; - - let mut torrents = self.torrents.write().await; - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if torrents.contains_key(&info_hash) { - continue; - } - - let torrent_entry = torrent::Entry { - peers: BTreeMap::default(), - completed, - }; - - torrents.insert(info_hash, torrent_entry); - } - - Ok(()) - } - - async fn get_peers_for_peer(&self, info_hash: &InfoHash, peer: &Peer) -> Vec { - let read_lock = self.torrents.read().await; - - match read_lock.get(info_hash) { - None => vec![], - Some(entry) => entry.get_peers_for_peer(peer).into_iter().copied().collect(), - } - } - - /// # Context: Tracker - /// - /// Get all torrent peers for a given torrent - pub async fn get_all_torrent_peers(&self, info_hash: &InfoHash) -> Vec { - let read_lock = self.torrents.read().await; - - match read_lock.get(info_hash) { - None => vec![], - Some(entry) => entry.get_all_peers().into_iter().copied().collect(), - } - } - - /// It updates the torrent entry in memory, it also stores in the database - /// the torrent info data which is persistent, and finally return the data - /// needed for a `announce` request response. - /// - /// # Context: Tracker - pub async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> torrent::SwarmStats { - // code-review: consider splitting the function in two (command and query segregation). - // `update_torrent_with_peer` and `get_stats` - - let mut torrents = self.torrents.write().await; - - let torrent_entry = match torrents.entry(*info_hash) { - Entry::Vacant(vacant) => vacant.insert(torrent::Entry::new()), - Entry::Occupied(entry) => entry.into_mut(), - }; - - let stats_updated = torrent_entry.update_peer(peer); - - // todo: move this action to a separate worker - if self.config.persistent_torrent_completed_stat && stats_updated { - let _: Result<(), databases::error::Error> = self - .database - .save_persistent_torrent(info_hash, torrent_entry.completed) - .await; - } - - let (seeders, completed, leechers) = torrent_entry.get_stats(); - - torrent::SwarmStats { - completed, - seeders, - leechers, - } - } - - pub async fn get_torrents(&self) -> RwLockReadGuard<'_, BTreeMap> { - self.torrents.read().await - } - - /// It calculates and returns the general `Tracker` - /// [`TorrentsMetrics`](crate::tracker::TorrentsMetrics) - /// - /// # Context: Tracker - pub async fn get_torrents_metrics(&self) -> TorrentsMetrics { - let mut torrents_metrics = TorrentsMetrics { - seeders: 0, - completed: 0, - leechers: 0, - torrents: 0, - }; - - let db = self.get_torrents().await; - - db.values().for_each(|torrent_entry| { - let (seeders, completed, leechers) = torrent_entry.get_stats(); - torrents_metrics.seeders += u64::from(seeders); - torrents_metrics.completed += u64::from(completed); - torrents_metrics.leechers += u64::from(leechers); - torrents_metrics.torrents += 1; - }); - - torrents_metrics - } - - /// Remove inactive peers and (optionally) peerless torrents - /// - /// # Context: Tracker - pub async fn cleanup_torrents(&self) { - let mut torrents_lock = self.torrents.write().await; - - // If we don't need to remove torrents we will use the faster iter - if self.config.remove_peerless_torrents { - torrents_lock.retain(|_, torrent_entry| { - torrent_entry.remove_inactive_peers(self.config.max_peer_timeout); - - if self.config.persistent_torrent_completed_stat { - torrent_entry.completed > 0 || !torrent_entry.peers.is_empty() - } else { - !torrent_entry.peers.is_empty() - } - }); - } else { - for (_, torrent_entry) in torrents_lock.iter_mut() { - torrent_entry.remove_inactive_peers(self.config.max_peer_timeout); - } - } - } - - /// It authenticates the peer `key` against the `Tracker` authentication - /// key list. - /// - /// # Errors - /// - /// Will return an error if the the authentication key cannot be verified. - /// - /// # Context: Authentication - pub async fn authenticate(&self, key: &Key) -> Result<(), auth::Error> { - if self.is_private() { - self.verify_auth_key(key).await - } else { - Ok(()) - } - } - - /// It generates a new expiring authentication key. - /// `lifetime` param is the duration in seconds for the new key. - /// The key will be no longer valid after `lifetime` seconds. - /// Authentication keys are used by HTTP trackers. - /// - /// # Context: Authentication - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to add the `auth_key` to the database. - pub async fn generate_auth_key(&self, lifetime: Duration) -> Result { - let auth_key = auth::generate(lifetime); - self.database.add_key_to_keys(&auth_key).await?; - self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); - Ok(auth_key) - } - - /// It removes an authentication key. - /// - /// # Context: Authentication - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to remove the `key` to the database. - /// - /// # Panics - /// - /// Will panic if key cannot be converted into a valid `Key`. - pub async fn remove_auth_key(&self, key: &Key) -> Result<(), databases::error::Error> { - self.database.remove_key_from_keys(key).await?; - self.keys.write().await.remove(key); - Ok(()) - } - - /// It verifies an authentication key. - /// - /// # Context: Authentication - /// - /// # Errors - /// - /// Will return a `key::Error` if unable to get any `auth_key`. - pub async fn verify_auth_key(&self, key: &Key) -> Result<(), auth::Error> { - // code-review: this function is public only because it's used in a test. - // We should change the test and make it private. - match self.keys.read().await.get(key) { - None => Err(auth::Error::UnableToReadKey { - location: Location::caller(), - key: Box::new(key.clone()), - }), - Some(key) => auth::verify(key), - } - } - - /// The `Tracker` stores the authentication keys in memory and in the database. - /// In case you need to restart the `Tracker` you can load the keys from the database - /// into memory with this function. Keys are automatically stored in the database when they - /// are generated. - /// - /// # Context: Authentication - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to `load_keys` from the database. - pub async fn load_keys_from_database(&self) -> Result<(), databases::error::Error> { - let keys_from_database = self.database.load_keys().await?; - let mut keys = self.keys.write().await; - - keys.clear(); - - for key in keys_from_database { - keys.insert(key.key.clone(), key); - } - - Ok(()) - } - - /// It authenticates and authorizes a UDP tracker request. - /// - /// # Context: Authentication and Authorization - /// - /// # Errors - /// - /// Will return a `torrent::Error::PeerKeyNotValid` if the `key` is not valid. - /// - /// Will return a `torrent::Error::PeerNotAuthenticated` if the `key` is `None`. - /// - /// Will return a `torrent::Error::TorrentNotWhitelisted` if the the Tracker is in listed mode and the `info_hash` is not whitelisted. - #[deprecated(since = "3.0.0", note = "please use `authenticate` and `authorize` instead")] - pub async fn authenticate_request(&self, info_hash: &InfoHash, key: &Option) -> Result<(), Error> { - // todo: this is a deprecated method. - // We're splitting authentication and authorization responsibilities. - // Use `authenticate` and `authorize` instead. - - // Authentication - - // no authentication needed in public mode - if self.is_public() { - return Ok(()); - } - - // check if auth_key is set and valid - if self.is_private() { - match key { - Some(key) => { - if let Err(e) = self.verify_auth_key(key).await { - return Err(Error::PeerKeyNotValid { - key: key.clone(), - source: (Arc::new(e) as Arc).into(), - }); - } - } - None => { - return Err(Error::PeerNotAuthenticated { - location: Location::caller(), - }); - } - } - } - - // Authorization - - // check if info_hash is whitelisted - if self.is_whitelisted() && !self.is_info_hash_whitelisted(info_hash).await { - return Err(Error::TorrentNotWhitelisted { - info_hash: *info_hash, - location: Location::caller(), - }); - } - - Ok(()) - } - - /// Right now, there is only authorization when the `Tracker` runs in - /// `listed` or `private_listed` modes. - /// - /// # Context: Authorization - /// - /// # Errors - /// - /// Will return an error if the tracker is running in `listed` mode - /// and the infohash is not whitelisted. - pub async fn authorize(&self, info_hash: &InfoHash) -> Result<(), Error> { - if !self.is_whitelisted() { - return Ok(()); - } - - if self.is_info_hash_whitelisted(info_hash).await { - return Ok(()); - } - - return Err(Error::TorrentNotWhitelisted { - info_hash: *info_hash, - location: Location::caller(), - }); - } - - /// It adds a torrent to the whitelist. - /// Adding torrents is not relevant to public trackers. - /// - /// # Context: Whitelist - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to add the `info_hash` into the whitelist database. - pub async fn add_torrent_to_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.add_torrent_to_database_whitelist(info_hash).await?; - self.add_torrent_to_memory_whitelist(info_hash).await; - Ok(()) - } - - /// It adds a torrent to the whitelist if it has not been whitelisted previously - async fn add_torrent_to_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - let is_whitelisted = self.database.is_info_hash_whitelisted(info_hash).await?; - - if is_whitelisted { - return Ok(()); - } - - self.database.add_info_hash_to_whitelist(*info_hash).await?; - - Ok(()) - } - - pub async fn add_torrent_to_memory_whitelist(&self, info_hash: &InfoHash) -> bool { - self.whitelist.write().await.insert(*info_hash) - } - - /// It removes a torrent from the whitelist. - /// Removing torrents is not relevant to public trackers. - /// - /// # Context: Whitelist - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. - pub async fn remove_torrent_from_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.remove_torrent_from_database_whitelist(info_hash).await?; - self.remove_torrent_from_memory_whitelist(info_hash).await; - Ok(()) - } - - /// It removes a torrent from the whitelist in the database. - /// - /// # Context: Whitelist - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. - pub async fn remove_torrent_from_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - let is_whitelisted = self.database.is_info_hash_whitelisted(info_hash).await?; - - if !is_whitelisted { - return Ok(()); - } - - self.database.remove_info_hash_from_whitelist(*info_hash).await?; - - Ok(()) - } - - /// It removes a torrent from the whitelist in memory. - /// - /// # Context: Whitelist - pub async fn remove_torrent_from_memory_whitelist(&self, info_hash: &InfoHash) -> bool { - self.whitelist.write().await.remove(info_hash) - } - - /// It checks if a torrent is whitelisted. - /// - /// # Context: Whitelist - pub async fn is_info_hash_whitelisted(&self, info_hash: &InfoHash) -> bool { - self.whitelist.read().await.contains(info_hash) - } - - /// It loads the whitelist from the database. - /// - /// # Context: Whitelist - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. - pub async fn load_whitelist_from_database(&self) -> Result<(), databases::error::Error> { - let whitelisted_torrents_from_database = self.database.load_whitelist().await?; - let mut whitelist = self.whitelist.write().await; - - whitelist.clear(); - - for info_hash in whitelisted_torrents_from_database { - let _: bool = whitelist.insert(info_hash); - } - - Ok(()) - } - - /// It return the `Tracker` [`statistics::Metrics`]. - /// - /// # Context: Statistics - pub async fn get_stats(&self) -> RwLockReadGuard<'_, statistics::Metrics> { - self.stats_repository.get_stats().await - } - - /// It allows to send a statistic events which eventually will be used to update [`statistics::Metrics`]. - /// - /// # Context: Statistics - pub async fn send_stats_event(&self, event: statistics::Event) -> Option>> { - match &self.stats_event_sender { - None => None, - Some(stats_event_sender) => stats_event_sender.send_event(event).await, - } - } -} - -#[must_use] -fn assign_ip_address_to_peer(remote_client_ip: &IpAddr, tracker_external_ip: Option) -> IpAddr { - if let Some(host_ip) = tracker_external_ip.filter(|_| remote_client_ip.is_loopback()) { - host_ip - } else { - *remote_client_ip - } -} - -#[cfg(test)] -mod tests { - - mod the_tracker { - - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::str::FromStr; - use std::sync::Arc; - - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; - use torrust_tracker_test_helpers::configuration; - - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::shared::clock::DurationSinceUnixEpoch; - use crate::tracker::peer::{self, Peer}; - use crate::tracker::services::tracker_factory; - use crate::tracker::{TorrentsMetrics, Tracker}; - - fn public_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_public().into()) - } - - fn private_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_private().into()) - } - - fn whitelisted_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_whitelisted().into()) - } - - pub fn tracker_persisting_torrents_in_database() -> Tracker { - let mut configuration = configuration::ephemeral(); - configuration.persistent_torrent_completed_stat = true; - tracker_factory(Arc::new(configuration)) - } - - fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() - } - - // The client peer IP - fn peer_ip() -> IpAddr { - IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) - } - - /// Sample peer whose state is not relevant for the tests - fn sample_peer() -> Peer { - complete_peer() - } - - /// Sample peer when for tests that need more than one peer - fn sample_peer_1() -> Peer { - Peer { - peer_id: peer::Id(*b"-qB00000000000000001"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), - event: AnnounceEvent::Completed, - } - } - - /// Sample peer when for tests that need more than one peer - fn sample_peer_2() -> Peer { - Peer { - peer_id: peer::Id(*b"-qB00000000000000002"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)), 8082), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), - event: AnnounceEvent::Completed, - } - } - - fn seeder() -> Peer { - complete_peer() - } - - fn leecher() -> Peer { - incomplete_peer() - } - - fn started_peer() -> Peer { - incomplete_peer() - } - - fn completed_peer() -> Peer { - complete_peer() - } - - /// A peer that counts as `complete` is swarm metadata - /// IMPORTANT!: it only counts if the it has been announce at least once before - /// announcing the `AnnounceEvent::Completed` event. - fn complete_peer() -> Peer { - Peer { - peer_id: peer::Id(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), // No bytes left to download - event: AnnounceEvent::Completed, - } - } - - /// A peer that counts as `incomplete` is swarm metadata - fn incomplete_peer() -> Peer { - Peer { - peer_id: peer::Id(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(1000), // Still bytes to download - event: AnnounceEvent::Started, - } - } - - #[tokio::test] - async fn should_collect_torrent_metrics() { - let tracker = public_tracker(); - - let torrents_metrics = tracker.get_torrents_metrics().await; - - assert_eq!( - torrents_metrics, - TorrentsMetrics { - seeders: 0, - completed: 0, - leechers: 0, - torrents: 0 - } - ); - } - - #[tokio::test] - async fn it_should_return_all_the_peers_for_a_given_torrent() { - let tracker = public_tracker(); - - let info_hash = sample_info_hash(); - let peer = sample_peer(); - - tracker.update_torrent_with_peer_and_get_stats(&info_hash, &peer).await; - - let peers = tracker.get_all_torrent_peers(&info_hash).await; - - assert_eq!(peers, vec![peer]); - } - - #[tokio::test] - async fn it_should_return_all_the_peers_for_a_given_torrent_excluding_a_given_peer() { - let tracker = public_tracker(); - - let info_hash = sample_info_hash(); - let peer = sample_peer(); - - tracker.update_torrent_with_peer_and_get_stats(&info_hash, &peer).await; - - let peers = tracker.get_peers_for_peer(&info_hash, &peer).await; - - assert_eq!(peers, vec![]); - } - - #[tokio::test] - async fn it_should_return_the_torrent_metrics() { - let tracker = public_tracker(); - - tracker - .update_torrent_with_peer_and_get_stats(&sample_info_hash(), &leecher()) - .await; - - let torrent_metrics = tracker.get_torrents_metrics().await; - - assert_eq!( - torrent_metrics, - TorrentsMetrics { - seeders: 0, - completed: 0, - leechers: 1, - torrents: 1, - } - ); - } - - mod for_all_config_modes { - - mod handling_an_announce_request { - - use crate::tracker::tests::the_tracker::{ - peer_ip, public_tracker, sample_info_hash, sample_peer, sample_peer_1, sample_peer_2, - }; - - mod should_assign_the_ip_to_the_peer { - - use std::net::{IpAddr, Ipv4Addr}; - - use crate::tracker::assign_ip_address_to_peer; - - #[test] - fn using_the_source_ip_instead_of_the_ip_in_the_announce_request() { - let remote_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)); - - let peer_ip = assign_ip_address_to_peer(&remote_ip, None); - - assert_eq!(peer_ip, remote_ip); - } - - mod and_when_the_client_ip_is_a_ipv4_loopback_ip { - - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; - use std::str::FromStr; - - use crate::tracker::assign_ip_address_to_peer; - - #[test] - fn it_should_use_the_loopback_ip_if_the_tracker_does_not_have_the_external_ip_configuration() { - let remote_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); - - let peer_ip = assign_ip_address_to_peer(&remote_ip, None); - - assert_eq!(peer_ip, remote_ip); - } - - #[test] - fn it_should_use_the_external_tracker_ip_in_tracker_configuration_if_it_is_defined() { - let remote_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); - - let tracker_external_ip = IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()); - - let peer_ip = assign_ip_address_to_peer(&remote_ip, Some(tracker_external_ip)); - - assert_eq!(peer_ip, tracker_external_ip); - } - - #[test] - fn it_should_use_the_external_ip_in_the_tracker_configuration_if_it_is_defined_even_if_the_external_ip_is_an_ipv6_ip( - ) { - let remote_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); - - let tracker_external_ip = - IpAddr::V6(Ipv6Addr::from_str("2345:0425:2CA1:0000:0000:0567:5673:23b5").unwrap()); - - let peer_ip = assign_ip_address_to_peer(&remote_ip, Some(tracker_external_ip)); - - assert_eq!(peer_ip, tracker_external_ip); - } - } - - mod and_when_client_ip_is_a_ipv6_loopback_ip { - - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; - use std::str::FromStr; - - use crate::tracker::assign_ip_address_to_peer; - - #[test] - fn it_should_use_the_loopback_ip_if_the_tracker_does_not_have_the_external_ip_configuration() { - let remote_ip = IpAddr::V6(Ipv6Addr::LOCALHOST); - - let peer_ip = assign_ip_address_to_peer(&remote_ip, None); - - assert_eq!(peer_ip, remote_ip); - } - - #[test] - fn it_should_use_the_external_ip_in_tracker_configuration_if_it_is_defined() { - let remote_ip = IpAddr::V6(Ipv6Addr::LOCALHOST); - - let tracker_external_ip = - IpAddr::V6(Ipv6Addr::from_str("2345:0425:2CA1:0000:0000:0567:5673:23b5").unwrap()); - - let peer_ip = assign_ip_address_to_peer(&remote_ip, Some(tracker_external_ip)); - - assert_eq!(peer_ip, tracker_external_ip); - } - - #[test] - fn it_should_use_the_external_ip_in_the_tracker_configuration_if_it_is_defined_even_if_the_external_ip_is_an_ipv4_ip( - ) { - let remote_ip = IpAddr::V6(Ipv6Addr::LOCALHOST); - - let tracker_external_ip = IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()); - - let peer_ip = assign_ip_address_to_peer(&remote_ip, Some(tracker_external_ip)); - - assert_eq!(peer_ip, tracker_external_ip); - } - } - } - - #[tokio::test] - async fn it_should_return_the_announce_data_with_an_empty_peer_list_when_it_is_the_first_announced_peer() { - let tracker = public_tracker(); - - let mut peer = sample_peer(); - - let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()).await; - - assert_eq!(announce_data.peers, vec![]); - } - - #[tokio::test] - async fn it_should_return_the_announce_data_with_the_previously_announced_peers() { - let tracker = public_tracker(); - - let mut previously_announced_peer = sample_peer_1(); - tracker - .announce(&sample_info_hash(), &mut previously_announced_peer, &peer_ip()) - .await; - - let mut peer = sample_peer_2(); - let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()).await; - - assert_eq!(announce_data.peers, vec![previously_announced_peer]); - } - - mod it_should_update_the_swarm_stats_for_the_torrent { - - use crate::tracker::tests::the_tracker::{ - completed_peer, leecher, peer_ip, public_tracker, sample_info_hash, seeder, started_peer, - }; - - #[tokio::test] - async fn when_the_peer_is_a_seeder() { - let tracker = public_tracker(); - - let mut peer = seeder(); - - let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()).await; - - assert_eq!(announce_data.swarm_stats.seeders, 1); - } - - #[tokio::test] - async fn when_the_peer_is_a_leecher() { - let tracker = public_tracker(); - - let mut peer = leecher(); - - let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()).await; - - assert_eq!(announce_data.swarm_stats.leechers, 1); - } - - #[tokio::test] - async fn when_a_previously_announced_started_peer_has_completed_downloading() { - let tracker = public_tracker(); - - // We have to announce with "started" event because peer does not count if peer was not previously known - let mut started_peer = started_peer(); - tracker.announce(&sample_info_hash(), &mut started_peer, &peer_ip()).await; - - let mut completed_peer = completed_peer(); - let announce_data = tracker.announce(&sample_info_hash(), &mut completed_peer, &peer_ip()).await; - - assert_eq!(announce_data.swarm_stats.completed, 1); - } - } - } - - mod handling_a_scrape_request { - - use std::net::{IpAddr, Ipv4Addr}; - - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::tracker::tests::the_tracker::{complete_peer, incomplete_peer, public_tracker}; - use crate::tracker::{ScrapeData, SwarmMetadata}; - - #[tokio::test] - async fn it_should_return_a_zeroed_swarm_metadata_for_the_requested_file_if_the_tracker_does_not_have_that_torrent( - ) { - let tracker = public_tracker(); - - let info_hashes = vec!["3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap()]; - - let scrape_data = tracker.scrape(&info_hashes).await; - - let mut expected_scrape_data = ScrapeData::empty(); - - expected_scrape_data.add_file_with_zeroed_metadata(&info_hashes[0]); - - assert_eq!(scrape_data, expected_scrape_data); - } - - #[tokio::test] - async fn it_should_return_the_swarm_metadata_for_the_requested_file_if_the_tracker_has_that_torrent() { - let tracker = public_tracker(); - - let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); - - // Announce a "complete" peer for the torrent - let mut complete_peer = complete_peer(); - tracker - .announce(&info_hash, &mut complete_peer, &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 10))) - .await; - - // Announce an "incomplete" peer for the torrent - let mut incomplete_peer = incomplete_peer(); - tracker - .announce(&info_hash, &mut incomplete_peer, &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 11))) - .await; - - // Scrape - let scrape_data = tracker.scrape(&vec![info_hash]).await; - - // The expected swarm metadata for the file - let mut expected_scrape_data = ScrapeData::empty(); - expected_scrape_data.add_file( - &info_hash, - SwarmMetadata { - complete: 0, // the "complete" peer does not count because it was not previously known - downloaded: 0, - incomplete: 1, // the "incomplete" peer we have just announced - }, - ); - - assert_eq!(scrape_data, expected_scrape_data); - } - - #[tokio::test] - async fn it_should_allow_scraping_for_multiple_torrents() { - let tracker = public_tracker(); - - let info_hashes = vec![ - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), - "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1".parse::().unwrap(), - ]; - - let scrape_data = tracker.scrape(&info_hashes).await; - - let mut expected_scrape_data = ScrapeData::empty(); - expected_scrape_data.add_file_with_zeroed_metadata(&info_hashes[0]); - expected_scrape_data.add_file_with_zeroed_metadata(&info_hashes[1]); - - assert_eq!(scrape_data, expected_scrape_data); - } - } - } - - mod configured_as_whitelisted { - - mod handling_authorization { - use crate::tracker::tests::the_tracker::{sample_info_hash, whitelisted_tracker}; - - #[tokio::test] - async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { - let tracker = whitelisted_tracker(); - - let info_hash = sample_info_hash(); - - let result = tracker.add_torrent_to_whitelist(&info_hash).await; - assert!(result.is_ok()); - - let result = tracker.authorize(&info_hash).await; - assert!(result.is_ok()); - } - - #[tokio::test] - async fn it_should_not_authorize_the_announce_and_scrape_actions_on_not_whitelisted_torrents() { - let tracker = whitelisted_tracker(); - - let info_hash = sample_info_hash(); - - let result = tracker.authorize(&info_hash).await; - assert!(result.is_err()); - } - } - - mod handling_the_torrent_whitelist { - use crate::tracker::tests::the_tracker::{sample_info_hash, whitelisted_tracker}; - - #[tokio::test] - async fn it_should_add_a_torrent_to_the_whitelist() { - let tracker = whitelisted_tracker(); - - let info_hash = sample_info_hash(); - - tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); - - assert!(tracker.is_info_hash_whitelisted(&info_hash).await); - } - - #[tokio::test] - async fn it_should_remove_a_torrent_from_the_whitelist() { - let tracker = whitelisted_tracker(); - - let info_hash = sample_info_hash(); - - tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); - - tracker.remove_torrent_from_whitelist(&info_hash).await.unwrap(); - - assert!(!tracker.is_info_hash_whitelisted(&info_hash).await); - } - - mod persistence { - use crate::tracker::tests::the_tracker::{sample_info_hash, whitelisted_tracker}; - - #[tokio::test] - async fn it_should_load_the_whitelist_from_the_database() { - let tracker = whitelisted_tracker(); - - let info_hash = sample_info_hash(); - - tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); - - // Remove torrent from the in-memory whitelist - tracker.whitelist.write().await.remove(&info_hash); - assert!(!tracker.is_info_hash_whitelisted(&info_hash).await); - - tracker.load_whitelist_from_database().await.unwrap(); - - assert!(tracker.is_info_hash_whitelisted(&info_hash).await); - } - } - } - - mod handling_an_announce_request {} - - mod handling_an_scrape_request { - - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::tracker::tests::the_tracker::{ - complete_peer, incomplete_peer, peer_ip, sample_info_hash, whitelisted_tracker, - }; - use crate::tracker::torrent::SwarmMetadata; - use crate::tracker::ScrapeData; - - #[test] - fn it_should_be_able_to_build_a_zeroed_scrape_data_for_a_list_of_info_hashes() { - // Zeroed scrape data is used when the authentication for the scrape request fails. - - let sample_info_hash = sample_info_hash(); - - let mut expected_scrape_data = ScrapeData::empty(); - expected_scrape_data.add_file_with_zeroed_metadata(&sample_info_hash); - - assert_eq!(ScrapeData::zeroed(&vec![sample_info_hash]), expected_scrape_data); - } - - #[tokio::test] - async fn it_should_return_the_zeroed_swarm_metadata_for_the_requested_file_if_it_is_not_whitelisted() { - let tracker = whitelisted_tracker(); - - let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); - - let mut peer = incomplete_peer(); - tracker.announce(&info_hash, &mut peer, &peer_ip()).await; - - // Announce twice to force non zeroed swarm metadata - let mut peer = complete_peer(); - tracker.announce(&info_hash, &mut peer, &peer_ip()).await; - - let scrape_data = tracker.scrape(&vec![info_hash]).await; - - // The expected zeroed swarm metadata for the file - let mut expected_scrape_data = ScrapeData::empty(); - expected_scrape_data.add_file(&info_hash, SwarmMetadata::zeroed()); - - assert_eq!(scrape_data, expected_scrape_data); - } - } - } - - mod configured_as_private { - - mod handling_authentication { - use std::str::FromStr; - use std::time::Duration; - - use crate::tracker::auth; - use crate::tracker::tests::the_tracker::private_tracker; - - #[tokio::test] - async fn it_should_generate_the_expiring_authentication_keys() { - let tracker = private_tracker(); - - let key = tracker.generate_auth_key(Duration::from_secs(100)).await.unwrap(); - - assert_eq!(key.valid_until, Duration::from_secs(100)); - } - - #[tokio::test] - async fn it_should_authenticate_a_peer_by_using_a_key() { - let tracker = private_tracker(); - - let expiring_key = tracker.generate_auth_key(Duration::from_secs(100)).await.unwrap(); - - let result = tracker.authenticate(&expiring_key.key()).await; - - assert!(result.is_ok()); - } - - #[tokio::test] - async fn it_should_fail_authenticating_a_peer_when_it_uses_an_unregistered_key() { - let tracker = private_tracker(); - - let unregistered_key = auth::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); - - let result = tracker.authenticate(&unregistered_key).await; - - assert!(result.is_err()); - } - - #[tokio::test] - async fn it_should_verify_a_valid_authentication_key() { - // todo: this should not be tested directly because - // `verify_auth_key` should be a private method. - let tracker = private_tracker(); - - let expiring_key = tracker.generate_auth_key(Duration::from_secs(100)).await.unwrap(); - - assert!(tracker.verify_auth_key(&expiring_key.key()).await.is_ok()); - } - - #[tokio::test] - async fn it_should_fail_verifying_an_unregistered_authentication_key() { - let tracker = private_tracker(); - - let unregistered_key = auth::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); - - assert!(tracker.verify_auth_key(&unregistered_key).await.is_err()); - } - - #[tokio::test] - async fn it_should_remove_an_authentication_key() { - let tracker = private_tracker(); - - let expiring_key = tracker.generate_auth_key(Duration::from_secs(100)).await.unwrap(); - - let result = tracker.remove_auth_key(&expiring_key.key()).await; - - assert!(result.is_ok()); - assert!(tracker.verify_auth_key(&expiring_key.key()).await.is_err()); - } - - #[tokio::test] - async fn it_should_load_authentication_keys_from_the_database() { - let tracker = private_tracker(); - - let expiring_key = tracker.generate_auth_key(Duration::from_secs(100)).await.unwrap(); - - // Remove the newly generated key in memory - tracker.keys.write().await.remove(&expiring_key.key()); - - let result = tracker.load_keys_from_database().await; - - assert!(result.is_ok()); - assert!(tracker.verify_auth_key(&expiring_key.key()).await.is_ok()); - } - } - - mod handling_an_announce_request {} - - mod handling_an_scrape_request {} - } - - mod configured_as_private_and_whitelisted { - - mod handling_an_announce_request {} - - mod handling_an_scrape_request {} - } - - mod handling_torrent_persistence { - use aquatic_udp_protocol::AnnounceEvent; - - use crate::tracker::tests::the_tracker::{sample_info_hash, sample_peer, tracker_persisting_torrents_in_database}; - - #[tokio::test] - async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { - let tracker = tracker_persisting_torrents_in_database(); - - let info_hash = sample_info_hash(); - - let mut peer = sample_peer(); - - peer.event = AnnounceEvent::Started; - let swarm_stats = tracker.update_torrent_with_peer_and_get_stats(&info_hash, &peer).await; - assert_eq!(swarm_stats.completed, 0); - - peer.event = AnnounceEvent::Completed; - let swarm_stats = tracker.update_torrent_with_peer_and_get_stats(&info_hash, &peer).await; - assert_eq!(swarm_stats.completed, 1); - - // Remove the newly updated torrent from memory - tracker.torrents.write().await.remove(&info_hash); - - tracker.load_torrents_from_database().await.unwrap(); - - let torrents = tracker.get_torrents().await; - assert!(torrents.contains_key(&info_hash)); - - let torrent_entry = torrents.get(&info_hash).unwrap(); - - // It persists the number of completed peers. - assert_eq!(torrent_entry.completed, 1); - - // It does not persist the peers - assert!(torrent_entry.peers.is_empty()); - } - } - } -} diff --git a/src/tracker/peer.rs b/src/tracker/peer.rs deleted file mode 100644 index 76747fea2..000000000 --- a/src/tracker/peer.rs +++ /dev/null @@ -1,505 +0,0 @@ -//! Peer struct used by the core `Tracker`. -//! -//! A sample peer: -//! -//! ```rust,no_run -//! use torrust_tracker::tracker::peer; -//! use std::net::SocketAddr; -//! use std::net::IpAddr; -//! use std::net::Ipv4Addr; -//! use torrust_tracker::shared::clock::DurationSinceUnixEpoch; -//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; -//! -//! peer::Peer { -//! peer_id: peer::Id(*b"-qB00000000000000000"), -//! peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), -//! updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), -//! uploaded: NumberOfBytes(0), -//! downloaded: NumberOfBytes(0), -//! left: NumberOfBytes(0), -//! event: AnnounceEvent::Started, -//! }; -//! ``` -use std::net::{IpAddr, SocketAddr}; -use std::panic::Location; - -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; -use serde; -use serde::Serialize; -use thiserror::Error; - -use crate::shared::bit_torrent::common::{AnnounceEventDef, NumberOfBytesDef}; -use crate::shared::clock::utils::ser_unix_time_value; -use crate::shared::clock::DurationSinceUnixEpoch; - -/// IP version used by the peer to connect to the tracker: IPv4 or IPv6 -#[derive(PartialEq, Eq, Debug)] -pub enum IPVersion { - /// - IPv4, - /// - IPv6, -} - -/// Peer struct used by the core `Tracker`. -/// -/// A sample peer: -/// -/// ```rust,no_run -/// use torrust_tracker::tracker::peer; -/// use std::net::SocketAddr; -/// use std::net::IpAddr; -/// use std::net::Ipv4Addr; -/// use torrust_tracker::shared::clock::DurationSinceUnixEpoch; -/// use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; -/// -/// peer::Peer { -/// peer_id: peer::Id(*b"-qB00000000000000000"), -/// peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), -/// updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), -/// uploaded: NumberOfBytes(0), -/// downloaded: NumberOfBytes(0), -/// left: NumberOfBytes(0), -/// event: AnnounceEvent::Started, -/// }; -/// ``` -#[derive(PartialEq, Eq, Debug, Clone, Serialize, Copy)] -pub struct Peer { - /// ID used by the downloader peer - pub peer_id: Id, - /// The IP and port this peer is listening on - pub peer_addr: SocketAddr, - /// The last time the the tracker receive an announce request from this peer (timestamp) - #[serde(serialize_with = "ser_unix_time_value")] - pub updated: DurationSinceUnixEpoch, - /// The total amount of bytes uploaded by this peer so far - #[serde(with = "NumberOfBytesDef")] - pub uploaded: NumberOfBytes, - /// The total amount of bytes downloaded by this peer so far - #[serde(with = "NumberOfBytesDef")] - pub downloaded: NumberOfBytes, - /// The number of bytes this peer still has to download - #[serde(with = "NumberOfBytesDef")] - pub left: NumberOfBytes, - /// This is an optional key which maps to started, completed, or stopped (or empty, which is the same as not being present). - #[serde(with = "AnnounceEventDef")] - pub event: AnnounceEvent, -} - -impl Peer { - #[must_use] - pub fn is_seeder(&self) -> bool { - self.left.0 <= 0 && self.event != AnnounceEvent::Stopped - } - - pub fn ip(&mut self) -> IpAddr { - self.peer_addr.ip() - } - - pub fn change_ip(&mut self, new_ip: &IpAddr) { - self.peer_addr = SocketAddr::new(*new_ip, self.peer_addr.port()); - } - - /// The IP version used by the peer: IPV4 or IPV6 - #[must_use] - pub fn ip_version(&self) -> IPVersion { - if self.peer_addr.is_ipv4() { - return IPVersion::IPv4; - } - IPVersion::IPv6 - } -} - -/// Peer ID. A 20-byte array. -/// -/// A string of length 20 which this downloader uses as its id. -/// Each downloader generates its own id at random at the start of a new download. -/// -/// A sample peer ID: -/// -/// ```rust,no_run -/// use torrust_tracker::tracker::peer; -/// -/// let peer_id = peer::Id(*b"-qB00000000000000000"); -/// ``` -#[derive(PartialEq, Eq, Hash, Clone, Debug, PartialOrd, Ord, Copy)] -pub struct Id(pub [u8; 20]); - -const PEER_ID_BYTES_LEN: usize = 20; - -/// Error returned when trying to convert an invalid peer id from another type. -/// -/// Usually because the source format does not contain 20 bytes. -#[derive(Error, Debug)] -pub enum IdConversionError { - #[error("not enough bytes for peer id: {message} {location}")] - NotEnoughBytes { - location: &'static Location<'static>, - message: String, - }, - #[error("too many bytes for peer id: {message} {location}")] - TooManyBytes { - location: &'static Location<'static>, - message: String, - }, -} - -impl Id { - /// # Panics - /// - /// Will panic if byte slice does not contains the exact amount of bytes need for the `Id`. - #[must_use] - pub fn from_bytes(bytes: &[u8]) -> Self { - assert_eq!(bytes.len(), PEER_ID_BYTES_LEN); - let mut ret = Self([0u8; PEER_ID_BYTES_LEN]); - ret.0.clone_from_slice(bytes); - ret - } - - #[must_use] - pub fn to_bytes(&self) -> [u8; 20] { - self.0 - } -} - -impl From<[u8; 20]> for Id { - fn from(bytes: [u8; 20]) -> Self { - Id(bytes) - } -} - -impl TryFrom> for Id { - type Error = IdConversionError; - - fn try_from(bytes: Vec) -> Result { - if bytes.len() < PEER_ID_BYTES_LEN { - return Err(IdConversionError::NotEnoughBytes { - location: Location::caller(), - message: format! {"got {} bytes, expected {}", bytes.len(), PEER_ID_BYTES_LEN}, - }); - } - if bytes.len() > PEER_ID_BYTES_LEN { - return Err(IdConversionError::TooManyBytes { - location: Location::caller(), - message: format! {"got {} bytes, expected {}", bytes.len(), PEER_ID_BYTES_LEN}, - }); - } - Ok(Self::from_bytes(&bytes)) - } -} - -impl std::str::FromStr for Id { - type Err = IdConversionError; - - fn from_str(s: &str) -> Result { - Self::try_from(s.as_bytes().to_vec()) - } -} - -impl std::fmt::Display for Id { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self.to_hex_string() { - Some(hex) => write!(f, "{hex}"), - None => write!(f, ""), - } - } -} - -impl Id { - #[must_use] - /// Converts to hex string. - /// - /// For the Id `-qB00000000000000000` it returns `2d71423030303030303030303030303030303030` - /// - /// For example: - /// - ///```text - /// Bytes = Hex - /// -qB00000000000000000 = 2d71423030303030303030303030303030303030 - /// -qB00000000000000000 = 2d 71 42 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 - /// - /// ------------- - /// |Char | Hex | - /// ------------- - /// | - | 2D | - /// | q | 71 | - /// | B | 42 | - /// | 0 | 30 | - /// ------------- - /// ``` - /// - /// Return `None` is some of the bytes are invalid UTF8 values. - /// - /// # Panics - /// - /// It will panic if the `binascii::bin2hex` from a too-small output buffer. - pub fn to_hex_string(&self) -> Option { - let buff_size = self.0.len() * 2; - let mut tmp: Vec = vec![0; buff_size]; - - binascii::bin2hex(&self.0, &mut tmp).unwrap(); - - match std::str::from_utf8(&tmp) { - Ok(hex) => Some(format!("0x{hex}")), - Err(_) => None, - } - } - - #[must_use] - pub fn get_client_name(&self) -> Option<&'static str> { - if self.0[0] == b'M' { - return Some("BitTorrent"); - } - if self.0[0] == b'-' { - let name = match &self.0[1..3] { - b"AG" | b"A~" => "Ares", - b"AR" => "Arctic", - b"AV" => "Avicora", - b"AX" => "BitPump", - b"AZ" => "Azureus", - b"BB" => "BitBuddy", - b"BC" => "BitComet", - b"BF" => "Bitflu", - b"BG" => "BTG (uses Rasterbar libtorrent)", - b"BR" => "BitRocket", - b"BS" => "BTSlave", - b"BX" => "~Bittorrent X", - b"CD" => "Enhanced CTorrent", - b"CT" => "CTorrent", - b"DE" => "DelugeTorrent", - b"DP" => "Propagate Data Client", - b"EB" => "EBit", - b"ES" => "electric sheep", - b"FT" => "FoxTorrent", - b"FW" => "FrostWire", - b"FX" => "Freebox BitTorrent", - b"GS" => "GSTorrent", - b"HL" => "Halite", - b"HN" => "Hydranode", - b"KG" => "KGet", - b"KT" => "KTorrent", - b"LH" => "LH-ABC", - b"LP" => "Lphant", - b"LT" => "libtorrent", - b"lt" => "libTorrent", - b"LW" => "LimeWire", - b"MO" => "MonoTorrent", - b"MP" => "MooPolice", - b"MR" => "Miro", - b"MT" => "MoonlightTorrent", - b"NX" => "Net Transport", - b"PD" => "Pando", - b"qB" => "qBittorrent", - b"QD" => "QQDownload", - b"QT" => "Qt 4 Torrent example", - b"RT" => "Retriever", - b"S~" => "Shareaza alpha/beta", - b"SB" => "~Swiftbit", - b"SS" => "SwarmScope", - b"ST" => "SymTorrent", - b"st" => "sharktorrent", - b"SZ" => "Shareaza", - b"TN" => "TorrentDotNET", - b"TR" => "Transmission", - b"TS" => "Torrentstorm", - b"TT" => "TuoTu", - b"UL" => "uLeecher!", - b"UT" => "µTorrent", - b"UW" => "µTorrent Web", - b"VG" => "Vagaa", - b"WD" => "WebTorrent Desktop", - b"WT" => "BitLet", - b"WW" => "WebTorrent", - b"WY" => "FireTorrent", - b"XL" => "Xunlei", - b"XT" => "XanTorrent", - b"XX" => "Xtorrent", - b"ZT" => "ZipTorrent", - _ => return None, - }; - Some(name) - } else { - None - } - } -} - -impl Serialize for Id { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - #[derive(Serialize)] - struct PeerIdInfo<'a> { - id: Option, - client: Option<&'a str>, - } - - let obj = PeerIdInfo { - id: self.to_hex_string(), - client: self.get_client_name(), - }; - obj.serialize(serializer) - } -} - -#[cfg(test)] -mod test { - - mod torrent_peer_id { - use crate::tracker::peer; - - #[test] - fn should_be_instantiated_from_a_byte_slice() { - let id = peer::Id::from_bytes(&[ - 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, - ]); - - let expected_id = peer::Id([ - 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, - ]); - - assert_eq!(id, expected_id); - } - - #[test] - #[should_panic] - fn should_fail_trying_to_instantiate_from_a_byte_slice_with_less_than_20_bytes() { - let less_than_20_bytes = [0; 19]; - let _: peer::Id = peer::Id::from_bytes(&less_than_20_bytes); - } - - #[test] - #[should_panic] - fn should_fail_trying_to_instantiate_from_a_byte_slice_with_more_than_20_bytes() { - let more_than_20_bytes = [0; 21]; - let _: peer::Id = peer::Id::from_bytes(&more_than_20_bytes); - } - - #[test] - fn should_be_instantiated_from_a_string() { - let id = "-qB00000000000000001".parse::().unwrap(); - - let expected_id = peer::Id([ - 45, 113, 66, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 49, - ]); - - assert_eq!(id, expected_id); - } - - #[test] - fn should_be_converted_from_a_20_byte_array() { - let id = peer::Id::from([ - 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, - ]); - - let expected_id = peer::Id([ - 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, - ]); - - assert_eq!(id, expected_id); - } - - #[test] - fn should_be_converted_from_a_byte_vector() { - let id = peer::Id::try_from( - [ - 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, - ] - .to_vec(), - ) - .unwrap(); - - let expected_id = peer::Id([ - 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, - ]); - - assert_eq!(id, expected_id); - } - - #[test] - #[should_panic] - fn should_fail_trying_to_convert_from_a_byte_vector_with_less_than_20_bytes() { - let _: peer::Id = peer::Id::try_from([0; 19].to_vec()).unwrap(); - } - - #[test] - #[should_panic] - fn should_fail_trying_to_convert_from_a_byte_vector_with_more_than_20_bytes() { - let _: peer::Id = peer::Id::try_from([0; 21].to_vec()).unwrap(); - } - - #[test] - fn should_be_converted_to_hex_string() { - let id = peer::Id(*b"-qB00000000000000000"); - assert_eq!(id.to_hex_string().unwrap(), "0x2d71423030303030303030303030303030303030"); - - let id = peer::Id([ - 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, - ]); - assert_eq!(id.to_hex_string().unwrap(), "0x009f9296009f9296009f9296009f9296009f9296"); - } - - #[test] - fn should_be_converted_into_string_type_using_the_hex_string_format() { - let id = peer::Id(*b"-qB00000000000000000"); - assert_eq!(id.to_string(), "0x2d71423030303030303030303030303030303030"); - - let id = peer::Id([ - 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, - ]); - assert_eq!(id.to_string(), "0x009f9296009f9296009f9296009f9296009f9296"); - } - - #[test] - fn should_return_the_inner_bytes() { - assert_eq!(peer::Id(*b"-qB00000000000000000").to_bytes(), *b"-qB00000000000000000"); - } - } - - mod torrent_peer { - - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; - use serde_json::Value; - - use crate::shared::clock::{Current, Time}; - use crate::tracker::peer::{self, Peer}; - - #[test] - fn it_should_be_serializable() { - let torrent_peer = Peer { - peer_id: peer::Id(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: Current::now(), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), - event: AnnounceEvent::Started, - }; - - let raw_json = serde_json::to_string(&torrent_peer).unwrap(); - - let expected_raw_json = r#" - { - "peer_id": { - "id": "0x2d71423030303030303030303030303030303030", - "client": "qBittorrent" - }, - "peer_addr":"126.0.0.1:8080", - "updated":0, - "uploaded":0, - "downloaded":0, - "left":0, - "event":"Started" - } - "#; - - assert_eq!( - serde_json::from_str::(&raw_json).unwrap(), - serde_json::from_str::(expected_raw_json).unwrap() - ); - } - } -} diff --git a/src/tracker/services/mod.rs b/src/tracker/services/mod.rs deleted file mode 100644 index deb07a439..000000000 --- a/src/tracker/services/mod.rs +++ /dev/null @@ -1,33 +0,0 @@ -//! Tracker domain services. Core and statistics services. -//! -//! There are two types of service: -//! -//! - [Core tracker services](crate::tracker::services::torrent): related to the tracker main functionalities like getting info about torrents. -//! - [Services for statistics](crate::tracker::services::statistics): related to tracker metrics. Aggregate data about the tracker server. -pub mod statistics; -pub mod torrent; - -use std::sync::Arc; - -use torrust_tracker_configuration::Configuration; - -use crate::tracker::Tracker; - -/// It returns a new tracker building its dependencies. -/// -/// # Panics -/// -/// Will panic if tracker cannot be instantiated. -#[must_use] -pub fn tracker_factory(config: Arc) -> Tracker { - // Initialize statistics - let (stats_event_sender, stats_repository) = statistics::setup::factory(config.tracker_usage_statistics); - - // Initialize Torrust tracker - match Tracker::new(config, stats_event_sender, stats_repository) { - Ok(tracker) => tracker, - Err(error) => { - panic!("{}", error) - } - } -} diff --git a/src/tracker/services/statistics/mod.rs b/src/tracker/services/statistics/mod.rs deleted file mode 100644 index 3761e38de..000000000 --- a/src/tracker/services/statistics/mod.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! Statistics services. -//! -//! It includes: -//! -//! - A [`factory`](crate::tracker::services::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. -//! - A [`get_metrics`](crate::tracker::services::statistics::get_metrics) service to get the [`tracker metrics`](crate::tracker::statistics::Metrics). -//! -//! Tracker metrics are collected using a Publisher-Subscribe pattern. -//! -//! The factory function builds two structs: -//! -//! - An statistics [`EventSender`](crate::tracker::statistics::EventSender) -//! - An statistics [`Repo`](crate::tracker::statistics::Repo) -//! -//! ```text -//! let (stats_event_sender, stats_repository) = factory(tracker_usage_statistics); -//! ``` -//! -//! The statistics repository is responsible for storing the metrics in memory. -//! The statistics event sender allows sending events related to metrics. -//! There is an event listener that is receiving all the events and processing them with an event handler. -//! Then, the event handler updates the metrics depending on the received event. -//! -//! For example, if you send the event [`Event::Udp4Connect`](crate::tracker::statistics::Event::Udp4Connect): -//! -//! ```text -//! let result = event_sender.send_event(Event::Udp4Connect).await; -//! ``` -//! -//! Eventually the counter for UDP connections from IPv4 peers will be increased. -//! -//! ```rust,no_run -//! pub struct Metrics { -//! // ... -//! pub udp4_connections_handled: u64, // This will be incremented -//! // ... -//! } -//! ``` -pub mod setup; - -use std::sync::Arc; - -use crate::tracker::statistics::Metrics; -use crate::tracker::{TorrentsMetrics, Tracker}; - -/// All the metrics collected by the tracker. -#[derive(Debug, PartialEq)] -pub struct TrackerMetrics { - /// Domain level metrics. - /// - /// General metrics for all torrents (number of seeders, leechers, etcetera) - pub torrents_metrics: TorrentsMetrics, - - /// Application level metrics. Usage statistics/metrics. - /// - /// Metrics about how the tracker is been used (number of udp announce requests, number of http scrape requests, etcetera) - pub protocol_metrics: Metrics, -} - -/// It returns all the [`TrackerMetrics`](crate::tracker::services::statistics::TrackerMetrics) -pub async fn get_metrics(tracker: Arc) -> TrackerMetrics { - let torrents_metrics = tracker.get_torrents_metrics().await; - let stats = tracker.get_stats().await; - - TrackerMetrics { - torrents_metrics, - protocol_metrics: Metrics { - tcp4_connections_handled: stats.tcp4_connections_handled, - tcp4_announces_handled: stats.tcp4_announces_handled, - tcp4_scrapes_handled: stats.tcp4_scrapes_handled, - tcp6_connections_handled: stats.tcp6_connections_handled, - tcp6_announces_handled: stats.tcp6_announces_handled, - tcp6_scrapes_handled: stats.tcp6_scrapes_handled, - udp4_connections_handled: stats.udp4_connections_handled, - udp4_announces_handled: stats.udp4_announces_handled, - udp4_scrapes_handled: stats.udp4_scrapes_handled, - udp6_connections_handled: stats.udp6_connections_handled, - udp6_announces_handled: stats.udp6_announces_handled, - udp6_scrapes_handled: stats.udp6_scrapes_handled, - }, - } -} - -#[cfg(test)] -mod tests { - use std::sync::Arc; - - use torrust_tracker_configuration::Configuration; - use torrust_tracker_test_helpers::configuration; - - use crate::tracker; - use crate::tracker::services::statistics::{get_metrics, TrackerMetrics}; - use crate::tracker::services::tracker_factory; - - pub fn tracker_configuration() -> Arc { - Arc::new(configuration::ephemeral()) - } - - #[tokio::test] - async fn the_statistics_service_should_return_the_tracker_metrics() { - let tracker = Arc::new(tracker_factory(tracker_configuration())); - - let tracker_metrics = get_metrics(tracker.clone()).await; - - assert_eq!( - tracker_metrics, - TrackerMetrics { - torrents_metrics: tracker::TorrentsMetrics::default(), - protocol_metrics: tracker::statistics::Metrics::default(), - } - ); - } -} diff --git a/src/tracker/services/statistics/setup.rs b/src/tracker/services/statistics/setup.rs deleted file mode 100644 index b8d325ab4..000000000 --- a/src/tracker/services/statistics/setup.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! Setup for the tracker statistics. -//! -//! The [`factory`](crate::tracker::services::statistics::setup::factory) function builds the structs needed for handling the tracker metrics. -use crate::tracker::statistics; - -/// It builds the structs needed for handling the tracker metrics. -/// -/// It returns: -/// -/// - An statistics [`EventSender`](crate::tracker::statistics::EventSender) that allows you to send events related to statistics. -/// - An statistics [`Repo`](crate::tracker::statistics::Repo) which is an in-memory repository for the tracker metrics. -/// -/// When the input argument `tracker_usage_statistics`is false the setup does not run the event listeners, consequently the statistics -/// events are sent are received but not dispatched to the handler. -#[must_use] -pub fn factory(tracker_usage_statistics: bool) -> (Option>, statistics::Repo) { - let mut stats_event_sender = None; - - let mut stats_tracker = statistics::Keeper::new(); - - if tracker_usage_statistics { - stats_event_sender = Some(stats_tracker.run_event_listener()); - } - - (stats_event_sender, stats_tracker.repository) -} - -#[cfg(test)] -mod test { - use super::factory; - - #[tokio::test] - async fn should_not_send_any_event_when_statistics_are_disabled() { - let tracker_usage_statistics = false; - - let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics); - - assert!(stats_event_sender.is_none()); - } - - #[tokio::test] - async fn should_send_events_when_statistics_are_enabled() { - let tracker_usage_statistics = true; - - let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics); - - assert!(stats_event_sender.is_some()); - } -} diff --git a/src/tracker/services/torrent.rs b/src/tracker/services/torrent.rs deleted file mode 100644 index 3610d930c..000000000 --- a/src/tracker/services/torrent.rs +++ /dev/null @@ -1,358 +0,0 @@ -//! Core tracker domain services. -//! -//! There are two services: -//! -//! - [`get_torrent_info`](crate::tracker::services::torrent::get_torrent_info): it returns all the data about one torrent. -//! - [`get_torrents`](crate::tracker::services::torrent::get_torrents): it returns data about some torrent in bulk excluding the peer list. -use std::sync::Arc; - -use serde::Deserialize; - -use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::peer::Peer; -use crate::tracker::Tracker; - -/// It contains all the information the tracker has about a torrent -#[derive(Debug, PartialEq)] -pub struct Info { - /// The infohash of the torrent this data is related to - pub info_hash: InfoHash, - /// The total number of seeders for this torrent. Peer that actively serving a full copy of the torrent data - pub seeders: u64, - /// The total number of peers that have ever complete downloading this torrent - pub completed: u64, - /// The total number of leechers for this torrent. Peers that actively downloading this torrent - pub leechers: u64, - /// The swarm: the list of peers that are actively trying to download or serving this torrent - pub peers: Option>, -} - -/// It contains only part of the information the tracker has about a torrent -/// -/// It contains the same data as [Info](crate::tracker::services::torrent::Info) but without the list of peers in the swarm. -#[derive(Debug, PartialEq, Clone)] -pub struct BasicInfo { - /// The infohash of the torrent this data is related to - pub info_hash: InfoHash, - /// The total number of seeders for this torrent. Peer that actively serving a full copy of the torrent data - pub seeders: u64, - /// The total number of peers that have ever complete downloading this torrent - pub completed: u64, - /// The total number of leechers for this torrent. Peers that actively downloading this torrent - pub leechers: u64, -} - -/// A struct to keep information about the page when results are being paginated -#[derive(Deserialize)] -pub struct Pagination { - /// The page number, starting at 0 - pub offset: u32, - /// Page size. The number of results per page - pub limit: u32, -} - -impl Pagination { - #[must_use] - pub fn new(offset: u32, limit: u32) -> Self { - Self { offset, limit } - } - - #[must_use] - pub fn new_with_options(offset_option: Option, limit_option: Option) -> Self { - let offset = match offset_option { - Some(offset) => offset, - None => Pagination::default_offset(), - }; - let limit = match limit_option { - Some(offset) => offset, - None => Pagination::default_limit(), - }; - - Self { offset, limit } - } - - #[must_use] - pub fn default_offset() -> u32 { - 0 - } - - #[must_use] - pub fn default_limit() -> u32 { - 4000 - } -} - -impl Default for Pagination { - fn default() -> Self { - Self { - offset: Self::default_offset(), - limit: Self::default_limit(), - } - } -} - -/// It returns all the information the tracker has about one torrent in a [Info](crate::tracker::services::torrent::Info) struct. -pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Option { - let db = tracker.get_torrents().await; - - let torrent_entry_option = db.get(info_hash); - - let Some(torrent_entry) = torrent_entry_option else { - return None; - }; - - let (seeders, completed, leechers) = torrent_entry.get_stats(); - - let peers = torrent_entry.get_all_peers(); - - let peers = Some(peers.iter().map(|peer| (**peer)).collect()); - - Some(Info { - info_hash: *info_hash, - seeders: u64::from(seeders), - completed: u64::from(completed), - leechers: u64::from(leechers), - peers, - }) -} - -/// It returns all the information the tracker has about multiple torrents in a [`BasicInfo`](crate::tracker::services::torrent::BasicInfo) struct, excluding the peer list. -pub async fn get_torrents(tracker: Arc, pagination: &Pagination) -> Vec { - let db = tracker.get_torrents().await; - - db.iter() - .map(|(info_hash, torrent_entry)| { - let (seeders, completed, leechers) = torrent_entry.get_stats(); - BasicInfo { - info_hash: *info_hash, - seeders: u64::from(seeders), - completed: u64::from(completed), - leechers: u64::from(leechers), - } - }) - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .collect() -} - -#[cfg(test)] -mod tests { - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; - - use crate::shared::clock::DurationSinceUnixEpoch; - use crate::tracker::peer; - - fn sample_peer() -> peer::Peer { - peer::Peer { - peer_id: peer::Id(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), - event: AnnounceEvent::Started, - } - } - - mod getting_a_torrent_info { - - use std::str::FromStr; - use std::sync::Arc; - - use torrust_tracker_configuration::Configuration; - use torrust_tracker_test_helpers::configuration; - - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::tracker::services::torrent::tests::sample_peer; - use crate::tracker::services::torrent::{get_torrent_info, Info}; - use crate::tracker::services::tracker_factory; - - pub fn tracker_configuration() -> Arc { - Arc::new(configuration::ephemeral()) - } - - #[tokio::test] - async fn should_return_none_if_the_tracker_does_not_have_the_torrent() { - let tracker = Arc::new(tracker_factory(tracker_configuration())); - - let torrent_info = get_torrent_info( - tracker.clone(), - &InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(), - ) - .await; - - assert!(torrent_info.is_none()); - } - - #[tokio::test] - async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { - let tracker = Arc::new(tracker_factory(tracker_configuration())); - - let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - let info_hash = InfoHash::from_str(&hash).unwrap(); - tracker - .update_torrent_with_peer_and_get_stats(&info_hash, &sample_peer()) - .await; - - let torrent_info = get_torrent_info(tracker.clone(), &info_hash).await.unwrap(); - - assert_eq!( - torrent_info, - Info { - info_hash: InfoHash::from_str(&hash).unwrap(), - seeders: 1, - completed: 0, - leechers: 0, - peers: Some(vec![sample_peer()]), - } - ); - } - } - - mod searching_for_torrents { - - use std::str::FromStr; - use std::sync::Arc; - - use torrust_tracker_configuration::Configuration; - use torrust_tracker_test_helpers::configuration; - - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::tracker::services::torrent::tests::sample_peer; - use crate::tracker::services::torrent::{get_torrents, BasicInfo, Pagination}; - use crate::tracker::services::tracker_factory; - - pub fn tracker_configuration() -> Arc { - Arc::new(configuration::ephemeral()) - } - - #[tokio::test] - async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { - let tracker = Arc::new(tracker_factory(tracker_configuration())); - - let torrents = get_torrents(tracker.clone(), &Pagination::default()).await; - - assert_eq!(torrents, vec![]); - } - - #[tokio::test] - async fn should_return_a_summarized_info_for_all_torrents() { - let tracker = Arc::new(tracker_factory(tracker_configuration())); - - let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - let info_hash = InfoHash::from_str(&hash).unwrap(); - - tracker - .update_torrent_with_peer_and_get_stats(&info_hash, &sample_peer()) - .await; - - let torrents = get_torrents(tracker.clone(), &Pagination::default()).await; - - assert_eq!( - torrents, - vec![BasicInfo { - info_hash: InfoHash::from_str(&hash).unwrap(), - seeders: 1, - completed: 0, - leechers: 0, - }] - ); - } - - #[tokio::test] - async fn should_allow_limiting_the_number_of_torrents_in_the_result() { - let tracker = Arc::new(tracker_factory(tracker_configuration())); - - let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - let info_hash1 = InfoHash::from_str(&hash1).unwrap(); - let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); - let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - - tracker - .update_torrent_with_peer_and_get_stats(&info_hash1, &sample_peer()) - .await; - tracker - .update_torrent_with_peer_and_get_stats(&info_hash2, &sample_peer()) - .await; - - let offset = 0; - let limit = 1; - - let torrents = get_torrents(tracker.clone(), &Pagination::new(offset, limit)).await; - - assert_eq!(torrents.len(), 1); - } - - #[tokio::test] - async fn should_allow_using_pagination_in_the_result() { - let tracker = Arc::new(tracker_factory(tracker_configuration())); - - let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - let info_hash1 = InfoHash::from_str(&hash1).unwrap(); - let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); - let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - - tracker - .update_torrent_with_peer_and_get_stats(&info_hash1, &sample_peer()) - .await; - tracker - .update_torrent_with_peer_and_get_stats(&info_hash2, &sample_peer()) - .await; - - let offset = 1; - let limit = 4000; - - let torrents = get_torrents(tracker.clone(), &Pagination::new(offset, limit)).await; - - assert_eq!(torrents.len(), 1); - assert_eq!( - torrents, - vec![BasicInfo { - info_hash: InfoHash::from_str(&hash1).unwrap(), - seeders: 1, - completed: 0, - leechers: 0, - }] - ); - } - - #[tokio::test] - async fn should_return_torrents_ordered_by_info_hash() { - let tracker = Arc::new(tracker_factory(tracker_configuration())); - - let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - let info_hash1 = InfoHash::from_str(&hash1).unwrap(); - tracker - .update_torrent_with_peer_and_get_stats(&info_hash1, &sample_peer()) - .await; - - let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); - let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - tracker - .update_torrent_with_peer_and_get_stats(&info_hash2, &sample_peer()) - .await; - - let torrents = get_torrents(tracker.clone(), &Pagination::default()).await; - - assert_eq!( - torrents, - vec![ - BasicInfo { - info_hash: InfoHash::from_str(&hash2).unwrap(), - seeders: 1, - completed: 0, - leechers: 0, - }, - BasicInfo { - info_hash: InfoHash::from_str(&hash1).unwrap(), - seeders: 1, - completed: 0, - leechers: 0, - } - ] - ); - } - } -} diff --git a/src/tracker/statistics.rs b/src/tracker/statistics.rs deleted file mode 100644 index 85cc4f255..000000000 --- a/src/tracker/statistics.rs +++ /dev/null @@ -1,490 +0,0 @@ -//! Structs to collect and keep tracker metrics. -//! -//! The tracker collects metrics such as: -//! -//! - Number of connections handled -//! - Number of `announce` requests handled -//! - Number of `scrape` request handled -//! -//! These metrics are collected for each connection type: UDP and HTTP and -//! also for each IP version used by the peers: IPv4 and IPv6. -//! -//! > Notice: that UDP tracker have an specific `connection` request. For the HTTP metrics the counter counts one connection for each `announce` or `scrape` request. -//! -//! The data is collected by using an `event-sender -> event listener` model. -//! -//! The tracker uses an [`statistics::EventSender`](crate::tracker::statistics::EventSender) instance to send an event. -//! The [`statistics::Keeper`](crate::tracker::statistics::Keeper) listens to new events and uses the [`statistics::Repo`](crate::tracker::statistics::Repo) to upgrade and store metrics. -//! -//! See the [`statistics::Event`](crate::tracker::statistics::Event) enum to check which events are available. -use std::sync::Arc; - -use async_trait::async_trait; -use log::debug; -#[cfg(test)] -use mockall::{automock, predicate::str}; -use tokio::sync::mpsc::error::SendError; -use tokio::sync::{mpsc, RwLock, RwLockReadGuard}; - -const CHANNEL_BUFFER_SIZE: usize = 65_535; - -/// An statistics event. It is used to collect tracker metrics. -/// -/// - `Tcp` prefix means the event was triggered by the HTTP tracker -/// - `Udp` prefix means the event was triggered by the UDP tracker -/// - `4` or `6` prefixes means the IP version used by the peer -/// - Finally the event suffix is the type of request: `announce`, `scrape` or `connection` -/// -/// > NOTE: HTTP trackers do not use `connection` requests. -#[derive(Debug, PartialEq, Eq)] -pub enum Event { - // code-review: consider one single event for request type with data: Event::Announce { scheme: HTTPorUDP, ip_version: V4orV6 } - // Attributes are enums too. - Tcp4Announce, - Tcp4Scrape, - Tcp6Announce, - Tcp6Scrape, - Udp4Connect, - Udp4Announce, - Udp4Scrape, - Udp6Connect, - Udp6Announce, - Udp6Scrape, -} - -/// Metrics collected by the tracker. -/// -/// - Number of connections handled -/// - Number of `announce` requests handled -/// - Number of `scrape` request handled -/// -/// These metrics are collected for each connection type: UDP and HTTP -/// and also for each IP version used by the peers: IPv4 and IPv6. -#[derive(Debug, PartialEq, Default)] -pub struct Metrics { - /// Total number of TCP (HTTP tracker) connections from IPv4 peers. - /// Since the HTTP tracker spec does not require a handshake, this metric - /// increases for every HTTP request. - pub tcp4_connections_handled: u64, - /// Total number of TCP (HTTP tracker) `announce` requests from IPv4 peers. - pub tcp4_announces_handled: u64, - /// Total number of TCP (HTTP tracker) `scrape` requests from IPv4 peers. - pub tcp4_scrapes_handled: u64, - /// Total number of TCP (HTTP tracker) connections from IPv6 peers. - pub tcp6_connections_handled: u64, - /// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers. - pub tcp6_announces_handled: u64, - /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. - pub tcp6_scrapes_handled: u64, - /// Total number of UDP (UDP tracker) connections from IPv4 peers. - pub udp4_connections_handled: u64, - /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. - pub udp4_announces_handled: u64, - /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. - pub udp4_scrapes_handled: u64, - /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. - pub udp6_connections_handled: u64, - /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. - pub udp6_announces_handled: u64, - /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. - pub udp6_scrapes_handled: u64, -} - -/// The service responsible for keeping tracker metrics (listening to statistics events and handle them). -/// -/// It actively listen to new statistics events. When it receives a new event -/// it accordingly increases the counters. -pub struct Keeper { - pub repository: Repo, -} - -impl Default for Keeper { - fn default() -> Self { - Self::new() - } -} - -impl Keeper { - #[must_use] - pub fn new() -> Self { - Self { repository: Repo::new() } - } - - #[must_use] - pub fn new_active_instance() -> (Box, Repo) { - let mut stats_tracker = Self::new(); - - let stats_event_sender = stats_tracker.run_event_listener(); - - (stats_event_sender, stats_tracker.repository) - } - - pub fn run_event_listener(&mut self) -> Box { - let (sender, receiver) = mpsc::channel::(CHANNEL_BUFFER_SIZE); - - let stats_repository = self.repository.clone(); - - tokio::spawn(async move { event_listener(receiver, stats_repository).await }); - - Box::new(Sender { sender }) - } -} - -async fn event_listener(mut receiver: mpsc::Receiver, stats_repository: Repo) { - while let Some(event) = receiver.recv().await { - event_handler(event, &stats_repository).await; - } -} - -async fn event_handler(event: Event, stats_repository: &Repo) { - match event { - // TCP4 - Event::Tcp4Announce => { - stats_repository.increase_tcp4_announces().await; - stats_repository.increase_tcp4_connections().await; - } - Event::Tcp4Scrape => { - stats_repository.increase_tcp4_scrapes().await; - stats_repository.increase_tcp4_connections().await; - } - - // TCP6 - Event::Tcp6Announce => { - stats_repository.increase_tcp6_announces().await; - stats_repository.increase_tcp6_connections().await; - } - Event::Tcp6Scrape => { - stats_repository.increase_tcp6_scrapes().await; - stats_repository.increase_tcp6_connections().await; - } - - // UDP4 - Event::Udp4Connect => { - stats_repository.increase_udp4_connections().await; - } - Event::Udp4Announce => { - stats_repository.increase_udp4_announces().await; - } - Event::Udp4Scrape => { - stats_repository.increase_udp4_scrapes().await; - } - - // UDP6 - Event::Udp6Connect => { - stats_repository.increase_udp6_connections().await; - } - Event::Udp6Announce => { - stats_repository.increase_udp6_announces().await; - } - Event::Udp6Scrape => { - stats_repository.increase_udp6_scrapes().await; - } - } - - debug!("stats: {:?}", stats_repository.get_stats().await); -} - -/// A trait to allow sending statistics events -#[async_trait] -#[cfg_attr(test, automock)] -pub trait EventSender: Sync + Send { - async fn send_event(&self, event: Event) -> Option>>; -} - -/// An [`statistics::EventSender`](crate::tracker::statistics::EventSender) implementation. -/// -/// It uses a channel sender to send the statistic events. The channel is created by a -/// [`statistics::Keeper`](crate::tracker::statistics::Keeper) -pub struct Sender { - sender: mpsc::Sender, -} - -#[async_trait] -impl EventSender for Sender { - async fn send_event(&self, event: Event) -> Option>> { - Some(self.sender.send(event).await) - } -} - -/// A repository for the tracker metrics. -#[derive(Clone)] -pub struct Repo { - pub stats: Arc>, -} - -impl Default for Repo { - fn default() -> Self { - Self::new() - } -} - -impl Repo { - #[must_use] - pub fn new() -> Self { - Self { - stats: Arc::new(RwLock::new(Metrics::default())), - } - } - - pub async fn get_stats(&self) -> RwLockReadGuard<'_, Metrics> { - self.stats.read().await - } - - pub async fn increase_tcp4_announces(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp4_announces_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp4_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp4_connections_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp4_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp4_scrapes_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp6_announces(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp6_announces_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp6_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp6_connections_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp6_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp6_scrapes_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_connections_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_announces(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_announces_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_scrapes_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_connections_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_announces(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_announces_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_scrapes_handled += 1; - drop(stats_lock); - } -} - -#[cfg(test)] -mod tests { - - mod stats_tracker { - use crate::tracker::statistics::{Event, Keeper, Metrics}; - - #[tokio::test] - async fn should_contain_the_tracker_statistics() { - let stats_tracker = Keeper::new(); - - let stats = stats_tracker.repository.get_stats().await; - - assert_eq!(stats.tcp4_announces_handled, Metrics::default().tcp4_announces_handled); - } - - #[tokio::test] - async fn should_create_an_event_sender_to_send_statistical_events() { - let mut stats_tracker = Keeper::new(); - - let event_sender = stats_tracker.run_event_listener(); - - let result = event_sender.send_event(Event::Udp4Connect).await; - - assert!(result.is_some()); - } - } - - mod event_handler { - use crate::tracker::statistics::{event_handler, Event, Repo}; - - #[tokio::test] - async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Tcp4Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp4_announces_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp4_connections_counter_when_it_receives_a_tcp4_announce_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Tcp4Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp4_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp4_scrapes_counter_when_it_receives_a_tcp4_scrape_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Tcp4Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp4_scrapes_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp4_connections_counter_when_it_receives_a_tcp4_scrape_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Tcp4Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp4_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp6_announces_counter_when_it_receives_a_tcp6_announce_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Tcp6Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp6_announces_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp6_connections_counter_when_it_receives_a_tcp6_announce_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Tcp6Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp6_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp6_scrapes_counter_when_it_receives_a_tcp6_scrape_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Tcp6Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp6_scrapes_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp6_connections_counter_when_it_receives_a_tcp6_scrape_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Tcp6Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp6_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp4_connections_counter_when_it_receives_a_udp4_connect_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Udp4Connect, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp4_announces_counter_when_it_receives_a_udp4_announce_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Udp4Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_announces_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp4_scrapes_counter_when_it_receives_a_udp4_scrape_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Udp4Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_scrapes_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp6_connections_counter_when_it_receives_a_udp6_connect_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Udp6Connect, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp6_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp6_announces_counter_when_it_receives_a_udp6_announce_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Udp6Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp6_announces_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp6_scrapes_counter_when_it_receives_a_udp6_scrape_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Udp6Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp6_scrapes_handled, 1); - } - } -} diff --git a/src/tracker/torrent.rs b/src/tracker/torrent.rs deleted file mode 100644 index 4f7e28b6b..000000000 --- a/src/tracker/torrent.rs +++ /dev/null @@ -1,476 +0,0 @@ -//! Structs to store the swarm data. -//! -//! There are to main data structures: -//! -//! - A torrent [`Entry`](crate::tracker::torrent::Entry): it contains all the information stored by the tracker for one torrent. -//! - The [`SwarmMetadata`](crate::tracker::torrent::SwarmMetadata): it contains aggregate information that can me derived from the torrent entries. -//! -//! A "swarm" is a network of peers that are trying to download the same torrent. -//! -//! The torrent entry contains the "swarm" data, which is basically the list of peers in the swarm. -//! That's the most valuable information the peer want to get from the tracker, because it allows them to -//! start downloading torrent from those peers. -//! -//! > **NOTICE**: that both swarm data (torrent entries) and swarm metadata (aggregate counters) are related to only one torrent. -//! -//! The "swarm metadata" contains aggregate data derived from the torrent entries. There two types of data: -//! -//! - For **active peers**: metrics related to the current active peers in the swarm. -//! - **Historical data**: since the tracker started running. -//! -//! The tracker collects metrics for: -//! -//! - The number of peers that have completed downloading the torrent since the tracker started collecting metrics. -//! - The number of peers that have completed downloading the torrent and are still active, that means they are actively participating in the network, -//! by announcing themselves periodically to the tracker. Since they have completed downloading they have a full copy of the torrent data. Peers with a -//! full copy of the data are called "seeders". -//! - The number of peers that have NOT completed downloading the torrent and are still active, that means they are actively participating in the network. -//! Peer that don not have a full copy of the torrent data are called "leechers". -//! -//! > **NOTICE**: that both [`SwarmMetadata`](crate::tracker::torrent::SwarmMetadata) and [`SwarmStats`](crate::tracker::torrent::SwarmStats) contain the same information. [`SwarmMetadata`](crate::tracker::torrent::SwarmMetadata) is using the names used on [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html). -use std::time::Duration; - -use aquatic_udp_protocol::AnnounceEvent; -use serde::{Deserialize, Serialize}; - -use super::peer::{self, Peer}; -use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; -use crate::shared::clock::{Current, TimeNow}; - -/// A data structure containing all the information about a torrent in the tracker. -/// -/// This is the tracker entry for a given torrent and contains the swarm data, -/// that's the list of all the peers trying to download the same torrent. -/// The tracker keeps one entry like this for every torrent. -#[derive(Serialize, Deserialize, Clone, Debug)] -pub struct Entry { - /// The swarm: a network of peers that are all trying to download the torrent associated to this entry - #[serde(skip)] - pub peers: std::collections::BTreeMap, - /// The number of peers that have ever completed downloading the torrent associated to this entry - pub completed: u32, -} - -/// Swarm statistics for one torrent. -/// Swarm metadata dictionary in the scrape response. -/// -/// See [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) -#[derive(Debug, PartialEq, Default)] -pub struct SwarmMetadata { - /// The number of peers that have ever completed downloading - pub downloaded: u32, - /// The number of active peers that have completed downloading (seeders) - pub complete: u32, - /// The number of active peers that have not completed downloading (leechers) - pub incomplete: u32, -} - -impl SwarmMetadata { - #[must_use] - pub fn zeroed() -> Self { - Self::default() - } -} - -/// Swarm statistics for one torrent. -/// -/// See [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) -#[derive(Debug, PartialEq, Default)] -pub struct SwarmStats { - /// The number of peers that have ever completed downloading - pub completed: u32, - /// The number of active peers that have completed downloading (seeders) - pub seeders: u32, - /// The number of active peers that have not completed downloading (leechers) - pub leechers: u32, -} - -impl Entry { - #[must_use] - pub fn new() -> Entry { - Entry { - peers: std::collections::BTreeMap::new(), - completed: 0, - } - } - - /// It updates a peer and returns true if the number of complete downloads have increased. - /// - /// The number of peers that have complete downloading is synchronously updated when peers are updated. - /// That's the total torrent downloads counter. - pub fn update_peer(&mut self, peer: &peer::Peer) -> bool { - let mut did_torrent_stats_change: bool = false; - - match peer.event { - AnnounceEvent::Stopped => { - let _: Option = self.peers.remove(&peer.peer_id); - } - AnnounceEvent::Completed => { - let peer_old = self.peers.insert(peer.peer_id, *peer); - // Don't count if peer was not previously known - if peer_old.is_some() { - self.completed += 1; - did_torrent_stats_change = true; - } - } - _ => { - let _: Option = self.peers.insert(peer.peer_id, *peer); - } - } - - did_torrent_stats_change - } - - /// Get all swarm peers, limiting the result to the maximum number of scrape - /// torrents. - #[must_use] - pub fn get_all_peers(&self) -> Vec<&peer::Peer> { - self.peers.values().take(MAX_SCRAPE_TORRENTS as usize).collect() - } - - /// It returns the list of peers for a given peer client, limiting the - /// result to the maximum number of scrape torrents. - /// - /// It filters out the input peer, typically because we want to return this - /// list of peers to that client peer. - #[must_use] - pub fn get_peers_for_peer(&self, client: &Peer) -> Vec<&peer::Peer> { - self.peers - .values() - // Take peers which are not the client peer - .filter(|peer| peer.peer_addr != client.peer_addr) - // Limit the number of peers on the result - .take(MAX_SCRAPE_TORRENTS as usize) - .collect() - } - - /// It returns the swarm metadata (statistics) as a tuple: - /// - /// `(seeders, completed, leechers)` - #[allow(clippy::cast_possible_truncation)] - #[must_use] - pub fn get_stats(&self) -> (u32, u32, u32) { - let seeders: u32 = self.peers.values().filter(|peer| peer.is_seeder()).count() as u32; - let leechers: u32 = self.peers.len() as u32 - seeders; - (seeders, self.completed, leechers) - } - - /// It returns the swarm metadata (statistics) as an struct - #[must_use] - pub fn get_swarm_metadata(&self) -> SwarmMetadata { - // code-review: consider using always this function instead of `get_stats`. - let (seeders, completed, leechers) = self.get_stats(); - SwarmMetadata { - complete: seeders, - downloaded: completed, - incomplete: leechers, - } - } - - /// It removes peer from the swarm that have not been updated for more than `max_peer_timeout` seconds - pub fn remove_inactive_peers(&mut self, max_peer_timeout: u32) { - let current_cutoff = Current::sub(&Duration::from_secs(u64::from(max_peer_timeout))).unwrap_or_default(); - self.peers.retain(|_, peer| peer.updated > current_cutoff); - } -} - -impl Default for Entry { - fn default() -> Self { - Self::new() - } -} - -#[cfg(test)] -mod tests { - - mod torrent_entry { - - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::ops::Sub; - use std::time::Duration; - - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; - - use crate::shared::clock::{Current, DurationSinceUnixEpoch, Stopped, StoppedTime, Time, Working}; - use crate::tracker::peer; - use crate::tracker::torrent::Entry; - - struct TorrentPeerBuilder { - peer: peer::Peer, - } - - impl TorrentPeerBuilder { - pub fn default() -> TorrentPeerBuilder { - let default_peer = peer::Peer { - peer_id: peer::Id([0u8; 20]), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), - updated: Current::now(), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), - event: AnnounceEvent::Started, - }; - TorrentPeerBuilder { peer: default_peer } - } - - pub fn with_event_completed(mut self) -> Self { - self.peer.event = AnnounceEvent::Completed; - self - } - - pub fn with_peer_address(mut self, peer_addr: SocketAddr) -> Self { - self.peer.peer_addr = peer_addr; - self - } - - pub fn with_peer_id(mut self, peer_id: peer::Id) -> Self { - self.peer.peer_id = peer_id; - self - } - - pub fn with_number_of_bytes_left(mut self, left: i64) -> Self { - self.peer.left = NumberOfBytes(left); - self - } - - pub fn updated_at(mut self, updated: DurationSinceUnixEpoch) -> Self { - self.peer.updated = updated; - self - } - - pub fn into(self) -> peer::Peer { - self.peer - } - } - - /// A torrent seeder is a peer with 0 bytes left to download which - /// has not announced it has stopped - fn a_torrent_seeder() -> peer::Peer { - TorrentPeerBuilder::default() - .with_number_of_bytes_left(0) - .with_event_completed() - .into() - } - - /// A torrent leecher is a peer that is not a seeder. - /// Leecher: left > 0 OR event = Stopped - fn a_torrent_leecher() -> peer::Peer { - TorrentPeerBuilder::default() - .with_number_of_bytes_left(1) - .with_event_completed() - .into() - } - - #[test] - fn the_default_torrent_entry_should_contain_an_empty_list_of_peers() { - let torrent_entry = Entry::new(); - - assert_eq!(torrent_entry.get_all_peers().len(), 0); - } - - #[test] - fn a_new_peer_can_be_added_to_a_torrent_entry() { - let mut torrent_entry = Entry::new(); - let torrent_peer = TorrentPeerBuilder::default().into(); - - torrent_entry.update_peer(&torrent_peer); // Add the peer - - assert_eq!(*torrent_entry.get_all_peers()[0], torrent_peer); - assert_eq!(torrent_entry.get_all_peers().len(), 1); - } - - #[test] - fn a_torrent_entry_should_contain_the_list_of_peers_that_were_added_to_the_torrent() { - let mut torrent_entry = Entry::new(); - let torrent_peer = TorrentPeerBuilder::default().into(); - - torrent_entry.update_peer(&torrent_peer); // Add the peer - - assert_eq!(torrent_entry.get_all_peers(), vec![&torrent_peer]); - } - - #[test] - fn a_peer_can_be_updated_in_a_torrent_entry() { - let mut torrent_entry = Entry::new(); - let mut torrent_peer = TorrentPeerBuilder::default().into(); - torrent_entry.update_peer(&torrent_peer); // Add the peer - - torrent_peer.event = AnnounceEvent::Completed; // Update the peer - torrent_entry.update_peer(&torrent_peer); // Update the peer in the torrent entry - - assert_eq!(torrent_entry.get_all_peers()[0].event, AnnounceEvent::Completed); - } - - #[test] - fn a_peer_should_be_removed_from_a_torrent_entry_when_the_peer_announces_it_has_stopped() { - let mut torrent_entry = Entry::new(); - let mut torrent_peer = TorrentPeerBuilder::default().into(); - torrent_entry.update_peer(&torrent_peer); // Add the peer - - torrent_peer.event = AnnounceEvent::Stopped; // Update the peer - torrent_entry.update_peer(&torrent_peer); // Update the peer in the torrent entry - - assert_eq!(torrent_entry.get_all_peers().len(), 0); - } - - #[test] - fn torrent_stats_change_when_a_previously_known_peer_announces_it_has_completed_the_torrent() { - let mut torrent_entry = Entry::new(); - let mut torrent_peer = TorrentPeerBuilder::default().into(); - - torrent_entry.update_peer(&torrent_peer); // Add the peer - - torrent_peer.event = AnnounceEvent::Completed; // Update the peer - let stats_have_changed = torrent_entry.update_peer(&torrent_peer); // Update the peer in the torrent entry - - assert!(stats_have_changed); - } - - #[test] - fn torrent_stats_should_not_change_when_a_peer_announces_it_has_completed_the_torrent_if_it_is_the_first_announce_from_the_peer( - ) { - let mut torrent_entry = Entry::new(); - let torrent_peer_announcing_complete_event = TorrentPeerBuilder::default().with_event_completed().into(); - - // Add a peer that did not exist before in the entry - let torrent_stats_have_not_changed = !torrent_entry.update_peer(&torrent_peer_announcing_complete_event); - - assert!(torrent_stats_have_not_changed); - } - - #[test] - fn a_torrent_entry_should_return_the_list_of_peers_for_a_given_peer_filtering_out_the_client_that_is_making_the_request() - { - let mut torrent_entry = Entry::new(); - let peer_socket_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); - let torrent_peer = TorrentPeerBuilder::default().with_peer_address(peer_socket_address).into(); - torrent_entry.update_peer(&torrent_peer); // Add peer - - // Get peers excluding the one we have just added - let peers = torrent_entry.get_peers_for_peer(&torrent_peer); - - assert_eq!(peers.len(), 0); - } - - #[test] - fn two_peers_with_the_same_ip_but_different_port_should_be_considered_different_peers() { - let mut torrent_entry = Entry::new(); - - let peer_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); - - // Add peer 1 - let torrent_peer_1 = TorrentPeerBuilder::default() - .with_peer_address(SocketAddr::new(peer_ip, 8080)) - .into(); - torrent_entry.update_peer(&torrent_peer_1); - - // Add peer 2 - let torrent_peer_2 = TorrentPeerBuilder::default() - .with_peer_address(SocketAddr::new(peer_ip, 8081)) - .into(); - torrent_entry.update_peer(&torrent_peer_2); - - // Get peers for peer 1 - let peers = torrent_entry.get_peers_for_peer(&torrent_peer_1); - - // The peer 2 using the same IP but different port should be included - assert_eq!(peers[0].peer_addr.ip(), Ipv4Addr::new(127, 0, 0, 1)); - assert_eq!(peers[0].peer_addr.port(), 8081); - } - - fn peer_id_from_i32(number: i32) -> peer::Id { - let peer_id = number.to_le_bytes(); - peer::Id([ - 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, peer_id[0], peer_id[1], - peer_id[2], peer_id[3], - ]) - } - - #[test] - fn the_tracker_should_limit_the_list_of_peers_to_74_when_clients_scrape_torrents() { - let mut torrent_entry = Entry::new(); - - // We add one more peer than the scrape limit - for peer_number in 1..=74 + 1 { - let torrent_peer = TorrentPeerBuilder::default() - .with_peer_id(peer_id_from_i32(peer_number)) - .into(); - torrent_entry.update_peer(&torrent_peer); - } - - let peers = torrent_entry.get_all_peers(); - - assert_eq!(peers.len(), 74); - } - - #[test] - fn torrent_stats_should_have_the_number_of_seeders_for_a_torrent() { - let mut torrent_entry = Entry::new(); - let torrent_seeder = a_torrent_seeder(); - - torrent_entry.update_peer(&torrent_seeder); // Add seeder - - assert_eq!(torrent_entry.get_stats().0, 1); - } - - #[test] - fn torrent_stats_should_have_the_number_of_leechers_for_a_torrent() { - let mut torrent_entry = Entry::new(); - let torrent_leecher = a_torrent_leecher(); - - torrent_entry.update_peer(&torrent_leecher); // Add leecher - - assert_eq!(torrent_entry.get_stats().2, 1); - } - - #[test] - fn torrent_stats_should_have_the_number_of_peers_that_having_announced_at_least_two_events_the_latest_one_is_the_completed_event( - ) { - let mut torrent_entry = Entry::new(); - let mut torrent_peer = TorrentPeerBuilder::default().into(); - torrent_entry.update_peer(&torrent_peer); // Add the peer - - // Announce "Completed" torrent download event. - torrent_peer.event = AnnounceEvent::Completed; - torrent_entry.update_peer(&torrent_peer); // Update the peer - - let number_of_previously_known_peers_with_completed_torrent = torrent_entry.get_stats().1; - - assert_eq!(number_of_previously_known_peers_with_completed_torrent, 1); - } - - #[test] - fn torrent_stats_should_not_include_a_peer_in_the_completed_counter_if_the_peer_has_announced_only_one_event() { - let mut torrent_entry = Entry::new(); - let torrent_peer_announcing_complete_event = TorrentPeerBuilder::default().with_event_completed().into(); - - // Announce "Completed" torrent download event. - // It's the first event announced from this peer. - torrent_entry.update_peer(&torrent_peer_announcing_complete_event); // Add the peer - - let number_of_peers_with_completed_torrent = torrent_entry.get_stats().1; - - assert_eq!(number_of_peers_with_completed_torrent, 0); - } - - #[test] - fn a_torrent_entry_should_remove_a_peer_not_updated_after_a_timeout_in_seconds() { - let mut torrent_entry = Entry::new(); - - let timeout = 120u32; - - let now = Working::now(); - Stopped::local_set(&now); - - let timeout_seconds_before_now = now.sub(Duration::from_secs(u64::from(timeout))); - let inactive_peer = TorrentPeerBuilder::default() - .updated_at(timeout_seconds_before_now.sub(Duration::from_secs(1))) - .into(); - torrent_entry.update_peer(&inactive_peer); // Add the peer - - torrent_entry.remove_inactive_peers(timeout); - - assert_eq!(torrent_entry.peers.len(), 0); - } - } -} diff --git a/tests/README.md b/tests/README.md deleted file mode 100644 index 04860056c..000000000 --- a/tests/README.md +++ /dev/null @@ -1,9 +0,0 @@ -### Running Benchmarks - -#### HTTP(S) Announce Peer + Torrent -For this benchmark we use the tool [wrk](https://github.com/wg/wrk). - -To run the benchmark using wrk, execute the following example script (change the url to your own tracker url): - - wrk -c200 -t1 -d10s -s ./wrk_benchmark_announce.lua --latency http://tracker.dutchbits.nl - diff --git a/tests/common/app.rs b/tests/common/app.rs deleted file mode 100644 index ee3fba064..000000000 --- a/tests/common/app.rs +++ /dev/null @@ -1,8 +0,0 @@ -use std::sync::Arc; - -use torrust_tracker::bootstrap; -use torrust_tracker::tracker::Tracker; - -pub fn setup_with_configuration(configuration: &Arc) -> Arc { - bootstrap::app::initialize_with_configuration(configuration) -} diff --git a/tests/common/fixtures.rs b/tests/common/fixtures.rs deleted file mode 100644 index 7062c8376..000000000 --- a/tests/common/fixtures.rs +++ /dev/null @@ -1,78 +0,0 @@ -use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; -use torrust_tracker::shared::clock::DurationSinceUnixEpoch; -use torrust_tracker::tracker::peer::{self, Id, Peer}; - -pub struct PeerBuilder { - peer: Peer, -} - -impl PeerBuilder { - #[allow(dead_code)] - pub fn default() -> PeerBuilder { - Self { - peer: default_peer_for_testing(), - } - } - - #[allow(dead_code)] - pub fn with_peer_id(mut self, peer_id: &Id) -> Self { - self.peer.peer_id = *peer_id; - self - } - - #[allow(dead_code)] - pub fn with_peer_addr(mut self, peer_addr: &SocketAddr) -> Self { - self.peer.peer_addr = *peer_addr; - self - } - - #[allow(dead_code)] - pub fn with_bytes_pending_to_download(mut self, left: i64) -> Self { - self.peer.left = NumberOfBytes(left); - self - } - - #[allow(dead_code)] - pub fn with_no_bytes_pending_to_download(mut self) -> Self { - self.peer.left = NumberOfBytes(0); - self - } - - #[allow(dead_code)] - pub fn build(self) -> Peer { - self.into() - } - - #[allow(dead_code)] - pub fn into(self) -> Peer { - self.peer - } -} - -#[allow(dead_code)] -fn default_peer_for_testing() -> Peer { - Peer { - peer_id: peer::Id(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), - event: AnnounceEvent::Started, - } -} - -#[allow(dead_code)] -pub fn invalid_info_hashes() -> Vec { - [ - "0".to_string(), - "-1".to_string(), - "1.1".to_string(), - "INVALID INFOHASH".to_string(), - "9c38422213e30bff212b30c360d26f9a0213642".to_string(), // 39-char length instead of 40 - "9c38422213e30bff212b30c360d26f9a0213642&".to_string(), // Invalid char - ] - .to_vec() -} diff --git a/tests/integration.rs b/tests/integration.rs index 5d66d9074..92289c415 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -1,7 +1,23 @@ -//! Integration tests. +//! Scaffolding for integration tests. +//! +//! Integration tests are used to test the interaction between multiple modules, +//! multiple running trackers, etc. Tests for one specific module should be in +//! the corresponding package. //! //! ```text //! cargo test --test integration //! ``` -mod common; mod servers; + +use torrust_tracker_clock::clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/tests/servers/api/connection_info.rs b/tests/servers/api/connection_info.rs deleted file mode 100644 index 35314a2fd..000000000 --- a/tests/servers/api/connection_info.rs +++ /dev/null @@ -1,29 +0,0 @@ -pub fn connection_with_invalid_token(bind_address: &str) -> ConnectionInfo { - ConnectionInfo::authenticated(bind_address, "invalid token") -} - -pub fn connection_with_no_token(bind_address: &str) -> ConnectionInfo { - ConnectionInfo::anonymous(bind_address) -} - -#[derive(Clone)] -pub struct ConnectionInfo { - pub bind_address: String, - pub api_token: Option, -} - -impl ConnectionInfo { - pub fn authenticated(bind_address: &str, api_token: &str) -> Self { - Self { - bind_address: bind_address.to_string(), - api_token: Some(api_token.to_string()), - } - } - - pub fn anonymous(bind_address: &str) -> Self { - Self { - bind_address: bind_address.to_string(), - api_token: None, - } - } -} diff --git a/tests/servers/api/contract/mod.rs b/tests/servers/api/contract/mod.rs new file mode 100644 index 000000000..9d34677fc --- /dev/null +++ b/tests/servers/api/contract/mod.rs @@ -0,0 +1 @@ +pub mod stats; diff --git a/tests/servers/api/contract/stats/mod.rs b/tests/servers/api/contract/stats/mod.rs new file mode 100644 index 000000000..d50bc58a5 --- /dev/null +++ b/tests/servers/api/contract/stats/mod.rs @@ -0,0 +1,94 @@ +use std::env; +use std::str::FromStr as _; + +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_client::http::client::requests::announce::QueryBuilder; +use bittorrent_tracker_client::http::client::Client as HttpTrackerClient; +use reqwest::Url; +use serde::Deserialize; +use tokio::time::Duration; +use torrust_rest_tracker_api_client::connection_info::{ConnectionInfo, Origin}; +use torrust_rest_tracker_api_client::v1::client::Client as TrackerApiClient; +use torrust_tracker_lib::app; + +#[tokio::test] +async fn the_stats_api_endpoint_should_return_the_global_stats() { + // Logging must be OFF otherwise your will get the following error: + // `Unable to install global subscriber: SetGlobalDefaultError("a global default trace dispatcher has already been set")` + // That's because we can't initialize the logger twice. + // You can enable it if you run only this test. + let config_with_two_http_trackers = r#" + [metadata] + app = "torrust-tracker" + purpose = "configuration" + schema_version = "2.0.0" + + [logging] + threshold = "off" + + [core] + listed = false + private = false + + [core.database] + driver = "sqlite3" + path = "./integration_tests_sqlite3.db" + + [[http_trackers]] + bind_address = "0.0.0.0:7272" + tracker_usage_statistics = true + + [[http_trackers]] + bind_address = "0.0.0.0:7373" + tracker_usage_statistics = true + + [http_api] + bind_address = "0.0.0.0:1414" + + [http_api.access_tokens] + admin = "MyAccessToken" + "#; + + env::set_var("TORRUST_TRACKER_CONFIG_TOML", config_with_two_http_trackers); + + let (_app_container, _jobs) = app::run().await; + + announce_to_tracker("http://127.0.0.1:7272").await; + announce_to_tracker("http://127.0.0.1:7373").await; + + let global_stats = get_tracker_statistics("http://127.0.0.1:1414", "MyAccessToken").await; + + assert_eq!(global_stats.tcp4_announces_handled, 2); +} + +/// Make a sample announce request to the tracker. +async fn announce_to_tracker(tracker_url: &str) { + let response = HttpTrackerClient::new(Url::parse(tracker_url).unwrap(), Duration::from_secs(1)) + .unwrap() + .announce( + &QueryBuilder::with_default_values() + .with_info_hash(&InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap()) // DevSkim: ignore DS173237 + .query(), + ) + .await; + + assert!(response.is_ok()); +} + +/// Global statistics with only metrics relevant to the test. +#[derive(Deserialize)] +struct PartialGlobalStatistics { + tcp4_announces_handled: u64, +} + +async fn get_tracker_statistics(aip_url: &str, token: &str) -> PartialGlobalStatistics { + let response = TrackerApiClient::new(ConnectionInfo::authenticated(Origin::new(aip_url).unwrap(), token)) + .unwrap() + .get_tracker_statistics(None) + .await; + + response + .json::() + .await + .expect("Failed to parse JSON response") +} diff --git a/tests/servers/api/mod.rs b/tests/servers/api/mod.rs index 7022da9b4..2943dbb50 100644 --- a/tests/servers/api/mod.rs +++ b/tests/servers/api/mod.rs @@ -1,14 +1 @@ -use std::sync::Arc; - -use torrust_tracker::tracker::Tracker; - -pub mod connection_info; -pub mod test_environment; -pub mod v1; - -/// It forces a database error by dropping all tables. -/// That makes any query fail. -/// code-review: alternatively we could inject a database mock in the future. -pub fn force_database_error(tracker: &Arc) { - tracker.database.drop_database_tables().unwrap(); -} +pub mod contract; diff --git a/tests/servers/api/test_environment.rs b/tests/servers/api/test_environment.rs deleted file mode 100644 index dbb23dcfa..000000000 --- a/tests/servers/api/test_environment.rs +++ /dev/null @@ -1,105 +0,0 @@ -use std::sync::Arc; - -use torrust_tracker::servers::apis::server::{ApiServer, RunningApiServer, StoppedApiServer}; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -use torrust_tracker::tracker::peer::Peer; -use torrust_tracker::tracker::Tracker; - -use super::connection_info::ConnectionInfo; -use crate::common::app::setup_with_configuration; - -#[allow(clippy::module_name_repetitions, dead_code)] -pub type StoppedTestEnvironment = TestEnvironment; -#[allow(clippy::module_name_repetitions)] -pub type RunningTestEnvironment = TestEnvironment; - -pub struct TestEnvironment { - pub cfg: Arc, - pub tracker: Arc, - pub state: S, -} - -#[allow(dead_code)] -pub struct Stopped { - api_server: StoppedApiServer, -} - -pub struct Running { - api_server: RunningApiServer, -} - -impl TestEnvironment { - /// Add a torrent to the tracker - pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &Peer) { - self.tracker.update_torrent_with_peer_and_get_stats(info_hash, peer).await; - } -} - -impl TestEnvironment { - pub fn new_stopped(cfg: torrust_tracker_configuration::Configuration) -> Self { - let cfg = Arc::new(cfg); - - let tracker = setup_with_configuration(&cfg); - - let api_server = api_server(cfg.http_api.clone()); - - Self { - cfg, - tracker, - state: Stopped { api_server }, - } - } - - pub async fn start(self) -> TestEnvironment { - TestEnvironment { - cfg: self.cfg, - tracker: self.tracker.clone(), - state: Running { - api_server: self.state.api_server.start(self.tracker).await.unwrap(), - }, - } - } - - pub fn config_mut(&mut self) -> &mut torrust_tracker_configuration::HttpApi { - &mut self.state.api_server.cfg - } -} - -impl TestEnvironment { - pub async fn new_running(cfg: torrust_tracker_configuration::Configuration) -> Self { - let test_env = StoppedTestEnvironment::new_stopped(cfg); - - test_env.start().await - } - - pub async fn stop(self) -> TestEnvironment { - TestEnvironment { - cfg: self.cfg, - tracker: self.tracker, - state: Stopped { - api_server: self.state.api_server.stop().await.unwrap(), - }, - } - } - - pub fn get_connection_info(&self) -> ConnectionInfo { - ConnectionInfo { - bind_address: self.state.api_server.state.bind_addr.to_string(), - api_token: self.state.api_server.cfg.access_tokens.get("admin").cloned(), - } - } -} - -#[allow(clippy::module_name_repetitions)] -pub fn stopped_test_environment(cfg: torrust_tracker_configuration::Configuration) -> StoppedTestEnvironment { - TestEnvironment::new_stopped(cfg) -} - -#[allow(clippy::module_name_repetitions)] -pub async fn running_test_environment(cfg: torrust_tracker_configuration::Configuration) -> RunningTestEnvironment { - TestEnvironment::new_running(cfg).await -} - -pub fn api_server(cfg: torrust_tracker_configuration::HttpApi) -> StoppedApiServer { - ApiServer::new(cfg) -} diff --git a/tests/servers/api/v1/client.rs b/tests/servers/api/v1/client.rs deleted file mode 100644 index 2b6db2e77..000000000 --- a/tests/servers/api/v1/client.rs +++ /dev/null @@ -1,116 +0,0 @@ -use reqwest::Response; - -use crate::common::http::{Query, QueryParam, ReqwestQuery}; -use crate::servers::api::connection_info::ConnectionInfo; - -/// API Client -pub struct Client { - connection_info: ConnectionInfo, - base_path: String, -} - -impl Client { - pub fn new(connection_info: ConnectionInfo) -> Self { - Self { - connection_info, - base_path: "/api/v1/".to_string(), - } - } - - pub async fn generate_auth_key(&self, seconds_valid: i32) -> Response { - self.post(&format!("key/{}", &seconds_valid)).await - } - - pub async fn delete_auth_key(&self, key: &str) -> Response { - self.delete(&format!("key/{}", &key)).await - } - - pub async fn reload_keys(&self) -> Response { - self.get("keys/reload", Query::default()).await - } - - pub async fn whitelist_a_torrent(&self, info_hash: &str) -> Response { - self.post(&format!("whitelist/{}", &info_hash)).await - } - - pub async fn remove_torrent_from_whitelist(&self, info_hash: &str) -> Response { - self.delete(&format!("whitelist/{}", &info_hash)).await - } - - pub async fn reload_whitelist(&self) -> Response { - self.get("whitelist/reload", Query::default()).await - } - - pub async fn get_torrent(&self, info_hash: &str) -> Response { - self.get(&format!("torrent/{}", &info_hash), Query::default()).await - } - - pub async fn get_torrents(&self, params: Query) -> Response { - self.get("torrents", params).await - } - - pub async fn get_tracker_statistics(&self) -> Response { - self.get("stats", Query::default()).await - } - - pub async fn get(&self, path: &str, params: Query) -> Response { - let mut query: Query = params; - - if let Some(token) = &self.connection_info.api_token { - query.add_param(QueryParam::new("token", token)); - }; - - self.get_request_with_query(path, query).await - } - - pub async fn post(&self, path: &str) -> Response { - reqwest::Client::new() - .post(self.base_url(path).clone()) - .query(&ReqwestQuery::from(self.query_with_token())) - .send() - .await - .unwrap() - } - - async fn delete(&self, path: &str) -> Response { - reqwest::Client::new() - .delete(self.base_url(path).clone()) - .query(&ReqwestQuery::from(self.query_with_token())) - .send() - .await - .unwrap() - } - - pub async fn get_request_with_query(&self, path: &str, params: Query) -> Response { - get(&self.base_url(path), Some(params)).await - } - - pub async fn get_request(&self, path: &str) -> Response { - get(&self.base_url(path), None).await - } - - fn query_with_token(&self) -> Query { - match &self.connection_info.api_token { - Some(token) => Query::params([QueryParam::new("token", token)].to_vec()), - None => Query::default(), - } - } - - fn base_url(&self, path: &str) -> String { - format!("http://{}{}{path}", &self.connection_info.bind_address, &self.base_path) - } -} - -async fn get(path: &str, query: Option) -> Response { - match query { - Some(params) => reqwest::Client::builder() - .build() - .unwrap() - .get(path) - .query(&ReqwestQuery::from(params)) - .send() - .await - .unwrap(), - None => reqwest::Client::builder().build().unwrap().get(path).send().await.unwrap(), - } -} diff --git a/tests/servers/api/v1/contract/authentication.rs b/tests/servers/api/v1/contract/authentication.rs deleted file mode 100644 index fb8de1810..000000000 --- a/tests/servers/api/v1/contract/authentication.rs +++ /dev/null @@ -1,83 +0,0 @@ -use torrust_tracker_test_helpers::configuration; - -use crate::common::http::{Query, QueryParam}; -use crate::servers::api::test_environment::running_test_environment; -use crate::servers::api::v1::asserts::{assert_token_not_valid, assert_unauthorized}; -use crate::servers::api::v1::client::Client; - -#[tokio::test] -async fn should_authenticate_requests_by_using_a_token_query_param() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let token = test_env.get_connection_info().api_token.unwrap(); - - let response = Client::new(test_env.get_connection_info()) - .get_request_with_query("stats", Query::params([QueryParam::new("token", &token)].to_vec())) - .await; - - assert_eq!(response.status(), 200); - - test_env.stop().await; -} - -#[tokio::test] -async fn should_not_authenticate_requests_when_the_token_is_missing() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let response = Client::new(test_env.get_connection_info()) - .get_request_with_query("stats", Query::default()) - .await; - - assert_unauthorized(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_not_authenticate_requests_when_the_token_is_empty() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let response = Client::new(test_env.get_connection_info()) - .get_request_with_query("stats", Query::params([QueryParam::new("token", "")].to_vec())) - .await; - - assert_token_not_valid(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_not_authenticate_requests_when_the_token_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let response = Client::new(test_env.get_connection_info()) - .get_request_with_query("stats", Query::params([QueryParam::new("token", "INVALID TOKEN")].to_vec())) - .await; - - assert_token_not_valid(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_allow_the_token_query_param_to_be_at_any_position_in_the_url_query() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let token = test_env.get_connection_info().api_token.unwrap(); - - // At the beginning of the query component - let response = Client::new(test_env.get_connection_info()) - .get_request(&format!("torrents?token={token}&limit=1")) - .await; - - assert_eq!(response.status(), 200); - - // At the end of the query component - let response = Client::new(test_env.get_connection_info()) - .get_request(&format!("torrents?limit=1&token={token}")) - .await; - - assert_eq!(response.status(), 200); - - test_env.stop().await; -} diff --git a/tests/servers/api/v1/contract/configuration.rs b/tests/servers/api/v1/contract/configuration.rs deleted file mode 100644 index e4b608607..000000000 --- a/tests/servers/api/v1/contract/configuration.rs +++ /dev/null @@ -1,17 +0,0 @@ -use torrust_tracker_test_helpers::configuration; - -use crate::servers::api::test_environment::stopped_test_environment; - -#[tokio::test] -#[should_panic] -async fn should_fail_with_ssl_enabled_and_bad_ssl_config() { - let mut test_env = stopped_test_environment(configuration::ephemeral()); - - let cfg = test_env.config_mut(); - - cfg.ssl_enabled = true; - cfg.ssl_key_path = Some("bad key path".to_string()); - cfg.ssl_cert_path = Some("bad cert path".to_string()); - - test_env.start().await; -} diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs deleted file mode 100644 index a99272e84..000000000 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ /dev/null @@ -1,265 +0,0 @@ -use std::time::Duration; - -use torrust_tracker::tracker::auth::Key; -use torrust_tracker_test_helpers::configuration; - -use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; -use crate::servers::api::force_database_error; -use crate::servers::api::test_environment::running_test_environment; -use crate::servers::api::v1::asserts::{ - assert_auth_key_utf8, assert_failed_to_delete_key, assert_failed_to_generate_key, assert_failed_to_reload_keys, - assert_invalid_auth_key_param, assert_invalid_key_duration_param, assert_ok, assert_token_not_valid, assert_unauthorized, -}; -use crate::servers::api::v1::client::Client; - -#[tokio::test] -async fn should_allow_generating_a_new_auth_key() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let seconds_valid = 60; - - let response = Client::new(test_env.get_connection_info()) - .generate_auth_key(seconds_valid) - .await; - - let auth_key_resource = assert_auth_key_utf8(response).await; - - // Verify the key with the tracker - assert!(test_env - .tracker - .verify_auth_key(&auth_key_resource.key.parse::().unwrap()) - .await - .is_ok()); - - test_env.stop().await; -} - -#[tokio::test] -async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let seconds_valid = 60; - - let response = Client::new(connection_with_invalid_token( - test_env.get_connection_info().bind_address.as_str(), - )) - .generate_auth_key(seconds_valid) - .await; - - assert_token_not_valid(response).await; - - let response = Client::new(connection_with_no_token(test_env.get_connection_info().bind_address.as_str())) - .generate_auth_key(seconds_valid) - .await; - - assert_unauthorized(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let invalid_key_durations = [ - // "", it returns 404 - // " ", it returns 404 - "-1", "text", - ]; - - for invalid_key_duration in invalid_key_durations { - let response = Client::new(test_env.get_connection_info()) - .post(&format!("key/{invalid_key_duration}")) - .await; - - assert_invalid_key_duration_param(response, invalid_key_duration).await; - } - - test_env.stop().await; -} - -#[tokio::test] -async fn should_fail_when_the_auth_key_cannot_be_generated() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - force_database_error(&test_env.tracker); - - let seconds_valid = 60; - let response = Client::new(test_env.get_connection_info()) - .generate_auth_key(seconds_valid) - .await; - - assert_failed_to_generate_key(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_allow_deleting_an_auth_key() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let seconds_valid = 60; - let auth_key = test_env - .tracker - .generate_auth_key(Duration::from_secs(seconds_valid)) - .await - .unwrap(); - - let response = Client::new(test_env.get_connection_info()) - .delete_auth_key(&auth_key.key.to_string()) - .await; - - assert_ok(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_fail_deleting_an_auth_key_when_the_key_id_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let invalid_auth_keys = [ - // "", it returns a 404 - // " ", it returns a 404 - "0", - "-1", - "INVALID AUTH KEY ID", - "IrweYtVuQPGbG9Jzx1DihcPmJGGpVy8", // 32 char key cspell:disable-line - "IrweYtVuQPGbG9Jzx1DihcPmJGGpVy8zs", // 34 char key cspell:disable-line - ]; - - for invalid_auth_key in &invalid_auth_keys { - let response = Client::new(test_env.get_connection_info()) - .delete_auth_key(invalid_auth_key) - .await; - - assert_invalid_auth_key_param(response, invalid_auth_key).await; - } - - test_env.stop().await; -} - -#[tokio::test] -async fn should_fail_when_the_auth_key_cannot_be_deleted() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let seconds_valid = 60; - let auth_key = test_env - .tracker - .generate_auth_key(Duration::from_secs(seconds_valid)) - .await - .unwrap(); - - force_database_error(&test_env.tracker); - - let response = Client::new(test_env.get_connection_info()) - .delete_auth_key(&auth_key.key.to_string()) - .await; - - assert_failed_to_delete_key(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let seconds_valid = 60; - - // Generate new auth key - let auth_key = test_env - .tracker - .generate_auth_key(Duration::from_secs(seconds_valid)) - .await - .unwrap(); - - let response = Client::new(connection_with_invalid_token( - test_env.get_connection_info().bind_address.as_str(), - )) - .delete_auth_key(&auth_key.key.to_string()) - .await; - - assert_token_not_valid(response).await; - - // Generate new auth key - let auth_key = test_env - .tracker - .generate_auth_key(Duration::from_secs(seconds_valid)) - .await - .unwrap(); - - let response = Client::new(connection_with_no_token(test_env.get_connection_info().bind_address.as_str())) - .delete_auth_key(&auth_key.key.to_string()) - .await; - - assert_unauthorized(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_allow_reloading_keys() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let seconds_valid = 60; - test_env - .tracker - .generate_auth_key(Duration::from_secs(seconds_valid)) - .await - .unwrap(); - - let response = Client::new(test_env.get_connection_info()).reload_keys().await; - - assert_ok(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_fail_when_keys_cannot_be_reloaded() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let seconds_valid = 60; - test_env - .tracker - .generate_auth_key(Duration::from_secs(seconds_valid)) - .await - .unwrap(); - - force_database_error(&test_env.tracker); - - let response = Client::new(test_env.get_connection_info()).reload_keys().await; - - assert_failed_to_reload_keys(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_not_allow_reloading_keys_for_unauthenticated_users() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let seconds_valid = 60; - test_env - .tracker - .generate_auth_key(Duration::from_secs(seconds_valid)) - .await - .unwrap(); - - let response = Client::new(connection_with_invalid_token( - test_env.get_connection_info().bind_address.as_str(), - )) - .reload_keys() - .await; - - assert_token_not_valid(response).await; - - let response = Client::new(connection_with_no_token(test_env.get_connection_info().bind_address.as_str())) - .reload_keys() - .await; - - assert_unauthorized(response).await; - - test_env.stop().await; -} diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs deleted file mode 100644 index 45f7e604a..000000000 --- a/tests/servers/api/v1/contract/context/stats.rs +++ /dev/null @@ -1,71 +0,0 @@ -use std::str::FromStr; - -use torrust_tracker::servers::apis::v1::context::stats::resources::Stats; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -use torrust_tracker_test_helpers::configuration; - -use crate::common::fixtures::PeerBuilder; -use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; -use crate::servers::api::test_environment::running_test_environment; -use crate::servers::api::v1::asserts::{assert_stats, assert_token_not_valid, assert_unauthorized}; -use crate::servers::api::v1::client::Client; - -#[tokio::test] -async fn should_allow_getting_tracker_statistics() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - test_env - .add_torrent_peer( - &InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(), - &PeerBuilder::default().into(), - ) - .await; - - let response = Client::new(test_env.get_connection_info()).get_tracker_statistics().await; - - assert_stats( - response, - Stats { - torrents: 1, - seeders: 1, - completed: 0, - leechers: 0, - tcp4_connections_handled: 0, - tcp4_announces_handled: 0, - tcp4_scrapes_handled: 0, - tcp6_connections_handled: 0, - tcp6_announces_handled: 0, - tcp6_scrapes_handled: 0, - udp4_connections_handled: 0, - udp4_announces_handled: 0, - udp4_scrapes_handled: 0, - udp6_connections_handled: 0, - udp6_announces_handled: 0, - udp6_scrapes_handled: 0, - }, - ) - .await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_not_allow_getting_tracker_statistics_for_unauthenticated_users() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let response = Client::new(connection_with_invalid_token( - test_env.get_connection_info().bind_address.as_str(), - )) - .get_tracker_statistics() - .await; - - assert_token_not_valid(response).await; - - let response = Client::new(connection_with_no_token(test_env.get_connection_info().bind_address.as_str())) - .get_tracker_statistics() - .await; - - assert_unauthorized(response).await; - - test_env.stop().await; -} diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs deleted file mode 100644 index ab497787f..000000000 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ /dev/null @@ -1,251 +0,0 @@ -use std::str::FromStr; - -use torrust_tracker::servers::apis::v1::context::torrent::resources::peer::Peer; -use torrust_tracker::servers::apis::v1::context::torrent::resources::torrent::{self, Torrent}; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -use torrust_tracker_test_helpers::configuration; - -use crate::common::fixtures::PeerBuilder; -use crate::common::http::{Query, QueryParam}; -use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; -use crate::servers::api::test_environment::running_test_environment; -use crate::servers::api::v1::asserts::{ - assert_bad_request, assert_invalid_infohash_param, assert_not_found, assert_token_not_valid, assert_torrent_info, - assert_torrent_list, assert_torrent_not_known, assert_unauthorized, -}; -use crate::servers::api::v1::client::Client; -use crate::servers::api::v1::contract::fixtures::{ - invalid_infohashes_returning_bad_request, invalid_infohashes_returning_not_found, -}; - -#[tokio::test] -async fn should_allow_getting_torrents() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); - - test_env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()).await; - - let response = Client::new(test_env.get_connection_info()).get_torrents(Query::empty()).await; - - assert_torrent_list( - response, - vec![torrent::ListItem { - info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), - seeders: 1, - completed: 0, - leechers: 0, - peers: None, // Torrent list does not include the peer list for each torrent - }], - ) - .await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_allow_limiting_the_torrents_in_the_result() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - // torrents are ordered alphabetically by infohashes - let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); - let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); - - test_env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()).await; - test_env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()).await; - - let response = Client::new(test_env.get_connection_info()) - .get_torrents(Query::params([QueryParam::new("limit", "1")].to_vec())) - .await; - - assert_torrent_list( - response, - vec![torrent::ListItem { - info_hash: "0b3aea4adc213ce32295be85d3883a63bca25446".to_string(), - seeders: 1, - completed: 0, - leechers: 0, - peers: None, // Torrent list does not include the peer list for each torrent - }], - ) - .await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_allow_the_torrents_result_pagination() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - // torrents are ordered alphabetically by infohashes - let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); - let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); - - test_env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()).await; - test_env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()).await; - - let response = Client::new(test_env.get_connection_info()) - .get_torrents(Query::params([QueryParam::new("offset", "1")].to_vec())) - .await; - - assert_torrent_list( - response, - vec![torrent::ListItem { - info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), - seeders: 1, - completed: 0, - leechers: 0, - peers: None, // Torrent list does not include the peer list for each torrent - }], - ) - .await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_fail_getting_torrents_when_the_offset_query_parameter_cannot_be_parsed() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let invalid_offsets = [" ", "-1", "1.1", "INVALID OFFSET"]; - - for invalid_offset in &invalid_offsets { - let response = Client::new(test_env.get_connection_info()) - .get_torrents(Query::params([QueryParam::new("offset", invalid_offset)].to_vec())) - .await; - - assert_bad_request(response, "Failed to deserialize query string: invalid digit found in string").await; - } - - test_env.stop().await; -} - -#[tokio::test] -async fn should_fail_getting_torrents_when_the_limit_query_parameter_cannot_be_parsed() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let invalid_limits = [" ", "-1", "1.1", "INVALID LIMIT"]; - - for invalid_limit in &invalid_limits { - let response = Client::new(test_env.get_connection_info()) - .get_torrents(Query::params([QueryParam::new("limit", invalid_limit)].to_vec())) - .await; - - assert_bad_request(response, "Failed to deserialize query string: invalid digit found in string").await; - } - - test_env.stop().await; -} - -#[tokio::test] -async fn should_not_allow_getting_torrents_for_unauthenticated_users() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let response = Client::new(connection_with_invalid_token( - test_env.get_connection_info().bind_address.as_str(), - )) - .get_torrents(Query::empty()) - .await; - - assert_token_not_valid(response).await; - - let response = Client::new(connection_with_no_token(test_env.get_connection_info().bind_address.as_str())) - .get_torrents(Query::default()) - .await; - - assert_unauthorized(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_allow_getting_a_torrent_info() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); - - let peer = PeerBuilder::default().into(); - - test_env.add_torrent_peer(&info_hash, &peer).await; - - let response = Client::new(test_env.get_connection_info()) - .get_torrent(&info_hash.to_string()) - .await; - - assert_torrent_info( - response, - Torrent { - info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), - seeders: 1, - completed: 0, - leechers: 0, - peers: Some(vec![Peer::from(peer)]), - }, - ) - .await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_fail_while_getting_a_torrent_info_when_the_torrent_does_not_exist() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); - - let response = Client::new(test_env.get_connection_info()) - .get_torrent(&info_hash.to_string()) - .await; - - assert_torrent_not_known(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_fail_getting_a_torrent_info_when_the_provided_infohash_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - for invalid_infohash in &invalid_infohashes_returning_bad_request() { - let response = Client::new(test_env.get_connection_info()) - .get_torrent(invalid_infohash) - .await; - - assert_invalid_infohash_param(response, invalid_infohash).await; - } - - for invalid_infohash in &invalid_infohashes_returning_not_found() { - let response = Client::new(test_env.get_connection_info()) - .get_torrent(invalid_infohash) - .await; - - assert_not_found(response).await; - } - - test_env.stop().await; -} - -#[tokio::test] -async fn should_not_allow_getting_a_torrent_info_for_unauthenticated_users() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); - - test_env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()).await; - - let response = Client::new(connection_with_invalid_token( - test_env.get_connection_info().bind_address.as_str(), - )) - .get_torrent(&info_hash.to_string()) - .await; - - assert_token_not_valid(response).await; - - let response = Client::new(connection_with_no_token(test_env.get_connection_info().bind_address.as_str())) - .get_torrent(&info_hash.to_string()) - .await; - - assert_unauthorized(response).await; - - test_env.stop().await; -} diff --git a/tests/servers/api/v1/contract/context/whitelist.rs b/tests/servers/api/v1/contract/context/whitelist.rs deleted file mode 100644 index 60ab4c901..000000000 --- a/tests/servers/api/v1/contract/context/whitelist.rs +++ /dev/null @@ -1,260 +0,0 @@ -use std::str::FromStr; - -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -use torrust_tracker_test_helpers::configuration; - -use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; -use crate::servers::api::force_database_error; -use crate::servers::api::test_environment::running_test_environment; -use crate::servers::api::v1::asserts::{ - assert_failed_to_reload_whitelist, assert_failed_to_remove_torrent_from_whitelist, assert_failed_to_whitelist_torrent, - assert_invalid_infohash_param, assert_not_found, assert_ok, assert_token_not_valid, assert_unauthorized, -}; -use crate::servers::api::v1::client::Client; -use crate::servers::api::v1::contract::fixtures::{ - invalid_infohashes_returning_bad_request, invalid_infohashes_returning_not_found, -}; - -#[tokio::test] -async fn should_allow_whitelisting_a_torrent() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - - let response = Client::new(test_env.get_connection_info()) - .whitelist_a_torrent(&info_hash) - .await; - - assert_ok(response).await; - assert!( - test_env - .tracker - .is_info_hash_whitelisted(&InfoHash::from_str(&info_hash).unwrap()) - .await - ); - - test_env.stop().await; -} - -#[tokio::test] -async fn should_allow_whitelisting_a_torrent_that_has_been_already_whitelisted() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - - let api_client = Client::new(test_env.get_connection_info()); - - let response = api_client.whitelist_a_torrent(&info_hash).await; - assert_ok(response).await; - - let response = api_client.whitelist_a_torrent(&info_hash).await; - assert_ok(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_not_allow_whitelisting_a_torrent_for_unauthenticated_users() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - - let response = Client::new(connection_with_invalid_token( - test_env.get_connection_info().bind_address.as_str(), - )) - .whitelist_a_torrent(&info_hash) - .await; - - assert_token_not_valid(response).await; - - let response = Client::new(connection_with_no_token(test_env.get_connection_info().bind_address.as_str())) - .whitelist_a_torrent(&info_hash) - .await; - - assert_unauthorized(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_fail_when_the_torrent_cannot_be_whitelisted() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - - force_database_error(&test_env.tracker); - - let response = Client::new(test_env.get_connection_info()) - .whitelist_a_torrent(&info_hash) - .await; - - assert_failed_to_whitelist_torrent(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_fail_whitelisting_a_torrent_when_the_provided_infohash_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - for invalid_infohash in &invalid_infohashes_returning_bad_request() { - let response = Client::new(test_env.get_connection_info()) - .whitelist_a_torrent(invalid_infohash) - .await; - - assert_invalid_infohash_param(response, invalid_infohash).await; - } - - for invalid_infohash in &invalid_infohashes_returning_not_found() { - let response = Client::new(test_env.get_connection_info()) - .whitelist_a_torrent(invalid_infohash) - .await; - - assert_not_found(response).await; - } - - test_env.stop().await; -} - -#[tokio::test] -async fn should_allow_removing_a_torrent_from_the_whitelist() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - let info_hash = InfoHash::from_str(&hash).unwrap(); - test_env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); - - let response = Client::new(test_env.get_connection_info()) - .remove_torrent_from_whitelist(&hash) - .await; - - assert_ok(response).await; - assert!(!test_env.tracker.is_info_hash_whitelisted(&info_hash).await); - - test_env.stop().await; -} - -#[tokio::test] -async fn should_not_fail_trying_to_remove_a_non_whitelisted_torrent_from_the_whitelist() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let non_whitelisted_torrent_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - - let response = Client::new(test_env.get_connection_info()) - .remove_torrent_from_whitelist(&non_whitelisted_torrent_hash) - .await; - - assert_ok(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_fail_removing_a_torrent_from_the_whitelist_when_the_provided_infohash_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - for invalid_infohash in &invalid_infohashes_returning_bad_request() { - let response = Client::new(test_env.get_connection_info()) - .remove_torrent_from_whitelist(invalid_infohash) - .await; - - assert_invalid_infohash_param(response, invalid_infohash).await; - } - - for invalid_infohash in &invalid_infohashes_returning_not_found() { - let response = Client::new(test_env.get_connection_info()) - .remove_torrent_from_whitelist(invalid_infohash) - .await; - - assert_not_found(response).await; - } - - test_env.stop().await; -} - -#[tokio::test] -async fn should_fail_when_the_torrent_cannot_be_removed_from_the_whitelist() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - let info_hash = InfoHash::from_str(&hash).unwrap(); - test_env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); - - force_database_error(&test_env.tracker); - - let response = Client::new(test_env.get_connection_info()) - .remove_torrent_from_whitelist(&hash) - .await; - - assert_failed_to_remove_torrent_from_whitelist(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthenticated_users() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - let info_hash = InfoHash::from_str(&hash).unwrap(); - - test_env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); - let response = Client::new(connection_with_invalid_token( - test_env.get_connection_info().bind_address.as_str(), - )) - .remove_torrent_from_whitelist(&hash) - .await; - - assert_token_not_valid(response).await; - - test_env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); - let response = Client::new(connection_with_no_token(test_env.get_connection_info().bind_address.as_str())) - .remove_torrent_from_whitelist(&hash) - .await; - - assert_unauthorized(response).await; - - test_env.stop().await; -} - -#[tokio::test] -async fn should_allow_reload_the_whitelist_from_the_database() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - let info_hash = InfoHash::from_str(&hash).unwrap(); - test_env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); - - let response = Client::new(test_env.get_connection_info()).reload_whitelist().await; - - assert_ok(response).await; - /* todo: this assert fails because the whitelist has not been reloaded yet. - We could add a new endpoint GET /api/whitelist/:info_hash to check if a torrent - is whitelisted and use that endpoint to check if the torrent is still there after reloading. - assert!( - !(test_env - .tracker - .is_info_hash_whitelisted(&InfoHash::from_str(&info_hash).unwrap()) - .await) - ); - */ - - test_env.stop().await; -} - -#[tokio::test] -async fn should_fail_when_the_whitelist_cannot_be_reloaded_from_the_database() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - let info_hash = InfoHash::from_str(&hash).unwrap(); - test_env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); - - force_database_error(&test_env.tracker); - - let response = Client::new(test_env.get_connection_info()).reload_whitelist().await; - - assert_failed_to_reload_whitelist(response).await; - - test_env.stop().await; -} diff --git a/tests/servers/http/connection_info.rs b/tests/servers/http/connection_info.rs deleted file mode 100644 index 5736271fd..000000000 --- a/tests/servers/http/connection_info.rs +++ /dev/null @@ -1,16 +0,0 @@ -use torrust_tracker::tracker::auth::Key; - -#[derive(Clone, Debug)] -pub struct ConnectionInfo { - pub bind_address: String, - pub key: Option, -} - -impl ConnectionInfo { - pub fn anonymous(bind_address: &str) -> Self { - Self { - bind_address: bind_address.to_string(), - key: None, - } - } -} diff --git a/tests/servers/http/test_environment.rs b/tests/servers/http/test_environment.rs deleted file mode 100644 index 8d0aaba02..000000000 --- a/tests/servers/http/test_environment.rs +++ /dev/null @@ -1,120 +0,0 @@ -use std::sync::Arc; - -use torrust_tracker::servers::http::server::{HttpServer, HttpServerLauncher, RunningHttpServer, StoppedHttpServer}; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -use torrust_tracker::tracker::peer::Peer; -use torrust_tracker::tracker::Tracker; - -use crate::common::app::setup_with_configuration; - -#[allow(clippy::module_name_repetitions, dead_code)] -pub type StoppedTestEnvironment = TestEnvironment>; -#[allow(clippy::module_name_repetitions)] -pub type RunningTestEnvironment = TestEnvironment>; - -pub struct TestEnvironment { - pub cfg: Arc, - pub tracker: Arc, - pub state: S, -} - -#[allow(dead_code)] -pub struct Stopped { - http_server: StoppedHttpServer, -} - -pub struct Running { - http_server: RunningHttpServer, -} - -impl TestEnvironment { - /// Add a torrent to the tracker - pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &Peer) { - self.tracker.update_torrent_with_peer_and_get_stats(info_hash, peer).await; - } -} - -impl TestEnvironment> { - #[allow(dead_code)] - pub fn new_stopped(cfg: torrust_tracker_configuration::Configuration) -> Self { - let cfg = Arc::new(cfg); - - let tracker = setup_with_configuration(&cfg); - - let http_server = http_server(cfg.http_trackers[0].clone()); - - Self { - cfg, - tracker, - state: Stopped { http_server }, - } - } - - #[allow(dead_code)] - pub async fn start(self) -> TestEnvironment> { - TestEnvironment { - cfg: self.cfg, - tracker: self.tracker.clone(), - state: Running { - http_server: self.state.http_server.start(self.tracker).await.unwrap(), - }, - } - } - - #[allow(dead_code)] - pub fn config(&self) -> &torrust_tracker_configuration::HttpTracker { - &self.state.http_server.cfg - } - - #[allow(dead_code)] - pub fn config_mut(&mut self) -> &mut torrust_tracker_configuration::HttpTracker { - &mut self.state.http_server.cfg - } -} - -impl TestEnvironment> { - pub async fn new_running(cfg: torrust_tracker_configuration::Configuration) -> Self { - let test_env = StoppedTestEnvironment::new_stopped(cfg); - - test_env.start().await - } - - pub async fn stop(self) -> TestEnvironment> { - TestEnvironment { - cfg: self.cfg, - tracker: self.tracker, - state: Stopped { - http_server: self.state.http_server.stop().await.unwrap(), - }, - } - } - - pub fn bind_address(&self) -> &std::net::SocketAddr { - &self.state.http_server.state.bind_addr - } - - #[allow(dead_code)] - pub fn config(&self) -> &torrust_tracker_configuration::HttpTracker { - &self.state.http_server.cfg - } -} - -#[allow(clippy::module_name_repetitions, dead_code)] -pub fn stopped_test_environment( - cfg: torrust_tracker_configuration::Configuration, -) -> StoppedTestEnvironment { - TestEnvironment::new_stopped(cfg) -} - -#[allow(clippy::module_name_repetitions)] -pub async fn running_test_environment( - cfg: torrust_tracker_configuration::Configuration, -) -> RunningTestEnvironment { - TestEnvironment::new_running(cfg).await -} - -pub fn http_server(cfg: torrust_tracker_configuration::HttpTracker) -> StoppedHttpServer { - let http_server = I::new(); - - HttpServer::new(cfg, http_server) -} diff --git a/tests/servers/mod.rs b/tests/servers/mod.rs index c19f72020..e5fdf85ee 100644 --- a/tests/servers/mod.rs +++ b/tests/servers/mod.rs @@ -1,5 +1 @@ -extern crate rand; - -mod api; -mod http; -mod udp; +pub mod api; diff --git a/tests/servers/udp/client.rs b/tests/servers/udp/client.rs deleted file mode 100644 index 75467055e..000000000 --- a/tests/servers/udp/client.rs +++ /dev/null @@ -1,84 +0,0 @@ -use std::io::Cursor; -use std::sync::Arc; - -use aquatic_udp_protocol::{Request, Response}; -use tokio::net::UdpSocket; -use torrust_tracker::servers::udp::MAX_PACKET_SIZE; - -use crate::servers::udp::source_address; - -#[allow(clippy::module_name_repetitions)] -pub struct UdpClient { - pub socket: Arc, -} - -impl UdpClient { - pub async fn bind(local_address: &str) -> Self { - let socket = UdpSocket::bind(local_address).await.unwrap(); - Self { - socket: Arc::new(socket), - } - } - - pub async fn connect(&self, remote_address: &str) { - self.socket.connect(remote_address).await.unwrap(); - } - - pub async fn send(&self, bytes: &[u8]) -> usize { - self.socket.writable().await.unwrap(); - self.socket.send(bytes).await.unwrap() - } - - pub async fn receive(&self, bytes: &mut [u8]) -> usize { - self.socket.readable().await.unwrap(); - self.socket.recv(bytes).await.unwrap() - } -} - -/// Creates a new `UdpClient` connected to a Udp server -pub async fn new_udp_client_connected(remote_address: &str) -> UdpClient { - let port = 0; // Let OS choose an unused port. - let client = UdpClient::bind(&source_address(port)).await; - client.connect(remote_address).await; - client -} - -#[allow(clippy::module_name_repetitions)] -pub struct UdpTrackerClient { - pub udp_client: UdpClient, -} - -impl UdpTrackerClient { - pub async fn send(&self, request: Request) -> usize { - // Write request into a buffer - let request_buffer = vec![0u8; MAX_PACKET_SIZE]; - let mut cursor = Cursor::new(request_buffer); - - let request_data = match request.write(&mut cursor) { - Ok(_) => { - #[allow(clippy::cast_possible_truncation)] - let position = cursor.position() as usize; - let inner_request_buffer = cursor.get_ref(); - // Return slice which contains written request data - &inner_request_buffer[..position] - } - Err(e) => panic!("could not write request to bytes: {e}."), - }; - - self.udp_client.send(request_data).await - } - - pub async fn receive(&self) -> Response { - let mut response_buffer = [0u8; MAX_PACKET_SIZE]; - - let payload_size = self.udp_client.receive(&mut response_buffer).await; - - Response::from_bytes(&response_buffer[..payload_size], true).unwrap() - } -} - -/// Creates a new `UdpTrackerClient` connected to a Udp Tracker server -pub async fn new_udp_tracker_client_connected(remote_address: &str) -> UdpTrackerClient { - let udp_client = new_udp_client_connected(remote_address).await; - UdpTrackerClient { udp_client } -} diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs deleted file mode 100644 index 3187d9871..000000000 --- a/tests/servers/udp/contract.rs +++ /dev/null @@ -1,160 +0,0 @@ -// UDP tracker documentation: -// -// BEP 15. UDP Tracker Protocol for BitTorrent -// https://www.bittorrent.org/beps/bep_0015.html - -use core::panic; - -use aquatic_udp_protocol::{ConnectRequest, ConnectionId, Response, TransactionId}; -use torrust_tracker::servers::udp::MAX_PACKET_SIZE; -use torrust_tracker_test_helpers::configuration; - -use crate::servers::udp::asserts::is_error_response; -use crate::servers::udp::client::{new_udp_client_connected, UdpTrackerClient}; -use crate::servers::udp::test_environment::running_test_environment; - -fn empty_udp_request() -> [u8; MAX_PACKET_SIZE] { - [0; MAX_PACKET_SIZE] -} - -fn empty_buffer() -> [u8; MAX_PACKET_SIZE] { - [0; MAX_PACKET_SIZE] -} - -async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrackerClient) -> ConnectionId { - let connect_request = ConnectRequest { transaction_id }; - - client.send(connect_request.into()).await; - - let response = client.receive().await; - - match response { - Response::Connect(connect_response) => connect_response.connection_id, - _ => panic!("error connecting to udp server {:?}", response), - } -} - -#[tokio::test] -async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_request() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let client = new_udp_client_connected(&test_env.bind_address().to_string()).await; - - client.send(&empty_udp_request()).await; - - let mut buffer = empty_buffer(); - client.receive(&mut buffer).await; - let response = Response::from_bytes(&buffer, true).unwrap(); - - assert!(is_error_response(&response, "bad request")); -} - -mod receiving_a_connection_request { - use aquatic_udp_protocol::{ConnectRequest, TransactionId}; - use torrust_tracker_test_helpers::configuration; - - use crate::servers::udp::asserts::is_connect_response; - use crate::servers::udp::client::new_udp_tracker_client_connected; - use crate::servers::udp::test_environment::running_test_environment; - - #[tokio::test] - async fn should_return_a_connect_response() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let client = new_udp_tracker_client_connected(&test_env.bind_address().to_string()).await; - - let connect_request = ConnectRequest { - transaction_id: TransactionId(123), - }; - - client.send(connect_request.into()).await; - - let response = client.receive().await; - - assert!(is_connect_response(&response, TransactionId(123))); - } -} - -mod receiving_an_announce_request { - use std::net::Ipv4Addr; - - use aquatic_udp_protocol::{ - AnnounceEvent, AnnounceRequest, ConnectionId, InfoHash, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, - TransactionId, - }; - use torrust_tracker_test_helpers::configuration; - - use crate::servers::udp::asserts::is_ipv4_announce_response; - use crate::servers::udp::client::new_udp_tracker_client_connected; - use crate::servers::udp::contract::send_connection_request; - use crate::servers::udp::test_environment::running_test_environment; - - #[tokio::test] - async fn should_return_an_announce_response() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let client = new_udp_tracker_client_connected(&test_env.bind_address().to_string()).await; - - let connection_id = send_connection_request(TransactionId(123), &client).await; - - // Send announce request - - let announce_request = AnnounceRequest { - connection_id: ConnectionId(connection_id.0), - transaction_id: TransactionId(123i32), - info_hash: InfoHash([0u8; 20]), - peer_id: PeerId([255u8; 20]), - bytes_downloaded: NumberOfBytes(0i64), - bytes_uploaded: NumberOfBytes(0i64), - bytes_left: NumberOfBytes(0i64), - event: AnnounceEvent::Started, - ip_address: Some(Ipv4Addr::new(0, 0, 0, 0)), - key: PeerKey(0u32), - peers_wanted: NumberOfPeers(1i32), - port: Port(client.udp_client.socket.local_addr().unwrap().port()), - }; - - client.send(announce_request.into()).await; - - let response = client.receive().await; - - assert!(is_ipv4_announce_response(&response)); - } -} - -mod receiving_an_scrape_request { - use aquatic_udp_protocol::{ConnectionId, InfoHash, ScrapeRequest, TransactionId}; - use torrust_tracker_test_helpers::configuration; - - use crate::servers::udp::asserts::is_scrape_response; - use crate::servers::udp::client::new_udp_tracker_client_connected; - use crate::servers::udp::contract::send_connection_request; - use crate::servers::udp::test_environment::running_test_environment; - - #[tokio::test] - async fn should_return_a_scrape_response() { - let test_env = running_test_environment(configuration::ephemeral()).await; - - let client = new_udp_tracker_client_connected(&test_env.bind_address().to_string()).await; - - let connection_id = send_connection_request(TransactionId(123), &client).await; - - // Send scrape request - - // Full scrapes are not allowed you need to pass an array of info hashes otherwise - // it will return "bad request" error with empty vector - let info_hashes = vec![InfoHash([0u8; 20])]; - - let scrape_request = ScrapeRequest { - connection_id: ConnectionId(connection_id.0), - transaction_id: TransactionId(123i32), - info_hashes, - }; - - client.send(scrape_request.into()).await; - - let response = client.receive().await; - - assert!(is_scrape_response(&response)); - } -} diff --git a/tests/servers/udp/mod.rs b/tests/servers/udp/mod.rs deleted file mode 100644 index d39c37153..000000000 --- a/tests/servers/udp/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub mod asserts; -pub mod client; -pub mod contract; -pub mod test_environment; - -/// Generates the source address for the UDP client -fn source_address(port: u16) -> String { - format!("127.0.0.1:{port}") -} diff --git a/tests/servers/udp/test_environment.rs b/tests/servers/udp/test_environment.rs deleted file mode 100644 index 15266d881..000000000 --- a/tests/servers/udp/test_environment.rs +++ /dev/null @@ -1,100 +0,0 @@ -use std::net::SocketAddr; -use std::sync::Arc; - -use torrust_tracker::servers::udp::server::{RunningUdpServer, StoppedUdpServer, UdpServer}; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -use torrust_tracker::tracker::peer::Peer; -use torrust_tracker::tracker::Tracker; - -use crate::common::app::setup_with_configuration; - -#[allow(clippy::module_name_repetitions, dead_code)] -pub type StoppedTestEnvironment = TestEnvironment; -#[allow(clippy::module_name_repetitions)] -pub type RunningTestEnvironment = TestEnvironment; - -pub struct TestEnvironment { - pub cfg: Arc, - pub tracker: Arc, - pub state: S, -} - -#[allow(dead_code)] -pub struct Stopped { - udp_server: StoppedUdpServer, -} - -pub struct Running { - udp_server: RunningUdpServer, -} - -impl TestEnvironment { - /// Add a torrent to the tracker - #[allow(dead_code)] - pub async fn add_torrent(&self, info_hash: &InfoHash, peer: &Peer) { - self.tracker.update_torrent_with_peer_and_get_stats(info_hash, peer).await; - } -} - -impl TestEnvironment { - #[allow(dead_code)] - pub fn new_stopped(cfg: torrust_tracker_configuration::Configuration) -> Self { - let cfg = Arc::new(cfg); - - let tracker = setup_with_configuration(&cfg); - - let udp_server = udp_server(cfg.udp_trackers[0].clone()); - - Self { - cfg, - tracker, - state: Stopped { udp_server }, - } - } - - #[allow(dead_code)] - pub async fn start(self) -> TestEnvironment { - TestEnvironment { - cfg: self.cfg, - tracker: self.tracker.clone(), - state: Running { - udp_server: self.state.udp_server.start(self.tracker).await.unwrap(), - }, - } - } -} - -impl TestEnvironment { - pub async fn new_running(cfg: torrust_tracker_configuration::Configuration) -> Self { - StoppedTestEnvironment::new_stopped(cfg).start().await - } - - #[allow(dead_code)] - pub async fn stop(self) -> TestEnvironment { - TestEnvironment { - cfg: self.cfg, - tracker: self.tracker, - state: Stopped { - udp_server: self.state.udp_server.stop().await.unwrap(), - }, - } - } - - pub fn bind_address(&self) -> SocketAddr { - self.state.udp_server.state.bind_address - } -} - -#[allow(clippy::module_name_repetitions, dead_code)] -pub fn stopped_test_environment(cfg: torrust_tracker_configuration::Configuration) -> StoppedTestEnvironment { - TestEnvironment::new_stopped(cfg) -} - -#[allow(clippy::module_name_repetitions)] -pub async fn running_test_environment(cfg: torrust_tracker_configuration::Configuration) -> RunningTestEnvironment { - TestEnvironment::new_running(cfg).await -} - -pub fn udp_server(cfg: torrust_tracker_configuration::UdpTracker) -> StoppedUdpServer { - UdpServer::new(cfg) -} diff --git a/tests/wrk_benchmark_announce.lua b/tests/wrk_benchmark_announce.lua deleted file mode 100644 index c182f8e68..000000000 --- a/tests/wrk_benchmark_announce.lua +++ /dev/null @@ -1,53 +0,0 @@ --- else the randomness would be the same every run -math.randomseed(os.time()) - -local charset = "0123456789ABCDEF" - -function hexToChar(hex) - local n = tonumber(hex, 16) - local f = string.char(n) - return f -end - -function hexStringToCharString(hex) - local ret = {} - local r - for i = 0, 19 do - local x = i * 2 - r = hex:sub(x+1, x+2) - local f = hexToChar(r) - table.insert(ret, f) - end - return table.concat(ret) -end - -function urlEncode(str) - str = string.gsub (str, "([^0-9a-zA-Z !'()*._~-])", -- locale independent - function (c) return string.format ("%%%02X", string.byte(c)) end) - str = string.gsub (str, " ", "+") - return str -end - -function genHexString(length) - local ret = {} - local r - for i = 1, length do - r = math.random(1, #charset) - table.insert(ret, charset:sub(r, r)) - end - return table.concat(ret) -end - -function randomInfoHash() - local hexString = genHexString(40) - local str = hexStringToCharString(hexString) - return urlEncode(str) -end - --- the request function that will run at each request -request = function() - path = "/announce?info_hash=" .. randomInfoHash() .. "&peer_id=-lt0D80-a%D4%10%19%99%A6yh%9A%E1%CD%96&port=54434&uploaded=885&downloaded=0&left=0&corrupt=0&key=A78381BD&numwant=200&compact=1&no_peer_id=1&supportcrypto=1&redundant=0" - headers = {} - headers["X-Forwarded-For"] = "1.1.1.1" - return wrk.format("GET", path, headers) -end