Skip to content

feat(http-protocol): consolidate duplicate HTTP types into http-protocol - #1974

Merged
josecelano merged 14 commits into
torrust:developfrom
josecelano:1965-1669-si-34-consolidate-duplicate-http-types
Jul 15, 2026
Merged

josecelano merged 14 commits into
torrust:developfrom
josecelano:1965-1669-si-34-consolidate-duplicate-http-types

Conversation

@josecelano

@josecelano josecelano commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

Description

Eliminates duplicate HTTP request/response type definitions across the workspace by consolidating them into packages/http-protocol.

Changes

  • New modules in http-protocol:

    • announce_builder / scrape_builder — Query builder types for constructing announce/scrape URLs
    • announce_deserialization / scrape_deserialization — Response deserialization types
    • percent_encode_byte_array — Moved to percent_encoding module
  • Deleted duplicate types from packages/tracker-client/src/http/client/ (6 files) and packages/axum-http-server/tests/server/ (5 files)

  • Consumers updated to import from http-protocol crate:

    • tracker-client (library)
    • axum-http-server (integration tests)
    • console/tracker-client (console tools)
    • Root crate integration tests
  • Dependencies: Added http-protocol to tracker-client, console/tracker-client, and root crate. Removed unused percent-encoding and serde_repr dev-dependencies from axum-http-server.

Design Decisions

  • Builder types added alongside existing parsers (iteration 1; unification can be evaluated later)
  • Uses domain types (InfoHash/PeerId) instead of raw ByteArray20
  • Uses full Event enum (Started/Stopped/Completed/Empty) from http-protocol
  • Error response type consolidated into http-protocol

Verification

  • linter all passes
  • cargo test --workspace passes
  • cargo clippy -- -D warnings passes
  • Pre-push checks pass (nightly fmt, nightly check, docs, stable tests)

Part of #1965

Add announce/scrape builder types and response deserialization types
to the http-protocol crate. Remove duplicate type definitions from
axum-http-server tests and tracker-client, updating all consumers to
import from http-protocol.

- Add announce_builder and scrape_builder modules to http-protocol
- Add announce_deserialization and scrape_deserialization modules
- Add percent_encode_byte_array to http-protocol percent_encoding module
- Add http-protocol dependency to tracker-client, console, and root crate
- Delete duplicate types from axum-http-server tests and tracker-client
- Update all imports across the workspace to use http-protocol types
- Remove unused dev-dependencies (percent-encoding, serde_repr)

Verification: linter all passes, cargo test --workspace passes,
cargo clippy -- -D warnings passes.
Copilot AI review requested due to automatic review settings July 13, 2026 11:15
@josecelano josecelano self-assigned this Jul 13, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR reduces maintenance overhead by moving duplicated HTTP tracker request/response builder and deserialization types into the canonical packages/http-protocol crate, then updating workspace consumers (tracker client, console client, and axum-http-server integration tests) to import from that single source of truth.

Changes:

  • Added new request builder modules (announce_builder, scrape_builder) and response deserialization modules (announce_deserialization, scrape_deserialization) to torrust-tracker-http-protocol.
  • Deleted duplicated request/response types from tracker-client and axum-http-server test helpers and updated call sites to import from http-protocol.
  • Updated workspace dependencies to add torrust-tracker-http-protocol where needed and remove now-unused crates.

Reviewed changes

Copilot reviewed 35 out of 36 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
tests/servers/api/contract/stats/mod.rs Switches stats contract tests to use http-protocol announce query builder.
packages/tracker-client/src/http/mod.rs Removes local HTTP helper/types now owned by http-protocol.
packages/tracker-client/src/http/client/mod.rs Updates tracker-client HTTP client to accept http-protocol request builder types.
packages/tracker-client/src/http/client/requests/mod.rs Converts requests module into docs-only placeholder (intended re-export point).
packages/tracker-client/src/http/client/responses/mod.rs Converts responses module into docs-only placeholder (intended re-export point).
packages/tracker-client/src/http/client/responses/error.rs Removes duplicated error response type.
packages/tracker-client/Cargo.toml Adds torrust-tracker-http-protocol dependency; removes no-longer-needed crates.
packages/http-protocol/src/v1/requests/mod.rs Registers new request builder modules.
packages/http-protocol/src/v1/requests/announce_builder.rs Introduces consolidated announce query builder using domain InfoHash/PeerId.
packages/http-protocol/src/v1/requests/scrape_builder.rs Introduces consolidated scrape query builder using domain InfoHash.
packages/http-protocol/src/v1/responses/mod.rs Registers new response deserialization modules.
packages/http-protocol/src/v1/responses/announce_deserialization.rs Adds announce response deserialization types for client/test usage.
packages/http-protocol/src/v1/responses/scrape_deserialization.rs Adds scrape response deserialization + builders using InfoHash map keys.
packages/http-protocol/src/v1/responses/error.rs Extends error response type to support deserialization.
packages/http-protocol/src/percent_encoding.rs Adds percent_encode_byte_array helper to shared percent-encoding utilities.
packages/http-protocol/Cargo.toml Adds hex, serde_bytes, and cargo-machete ignore metadata.
packages/axum-http-server/tests/server/mod.rs Removes duplicated byte-array/infohash helpers from test support module.
packages/axum-http-server/tests/server/client.rs Updates test HTTP client to accept http-protocol request builder types.
packages/axum-http-server/tests/server/asserts.rs Updates test assertions to use http-protocol response deserialization types.
packages/axum-http-server/tests/server/v1/contract.rs Replaces local request/response test helper types with http-protocol imports.
packages/axum-http-server/tests/server/requests/mod.rs Converts requests module into docs-only placeholder (intended re-export point).
packages/axum-http-server/tests/server/requests/announce.rs Removes duplicated announce request builder types from tests.
packages/axum-http-server/tests/server/requests/scrape.rs Removes duplicated scrape request builder types from tests.
packages/axum-http-server/tests/server/responses/mod.rs Converts responses module into docs-only placeholder (intended re-export point).
packages/axum-http-server/tests/server/responses/announce.rs Removes duplicated announce response types from tests.
packages/axum-http-server/tests/server/responses/scrape.rs Removes duplicated scrape response types from tests.
packages/axum-http-server/tests/server/responses/error.rs Removes duplicated error response type from tests.
packages/axum-http-server/Cargo.toml Removes now-unused dev-dependencies (percent-encoding, serde_repr).
console/tracker-client/src/console/clients/unified/http.rs Updates console unified HTTP client code to use http-protocol types.
console/tracker-client/src/console/clients/http/mod.rs Switches scrape parse error import to http-protocol.
console/tracker-client/src/console/clients/http/app.rs Updates console HTTP commands to use http-protocol builders/deserializers.
console/tracker-client/src/console/clients/checker/checks/http.rs Updates checker flow to use http-protocol request/response types.
console/tracker-client/Cargo.toml Adds torrust-tracker-http-protocol dependency.
docs/issues/open/1965-1669-si-34-consolidate-duplicate-http-types/ISSUE.md Records design decisions and progress updates for the consolidation effort.
Cargo.toml Adds torrust-tracker-http-protocol as a dev-dependency for root tests.
Cargo.lock Reflects dependency graph updates (adds hex, links http-protocol to consumers, removes unused deps).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Remove the From<peer::Peer> impl for DictionaryPeer from http-protocol
(responses/announce_deserialization) along with the torrust-tracker-primitives
dependency. Replace the 3 call sites in axum-http-server integration tests
with direct struct construction.

Also update deny.toml to allow http-protocol as a dependency of
tracker-client-lib and the root tracker crate.
…odule docs

- Added unit test for `percent_encode_byte_array` in `http-protocol`
- Updated module doc comments in `axum-http-server` and `tracker-client` to reflect consolidation
- Added `Signedness` to project-words.txt for spell check
…nse type consolidation

- New `analysis-announce-query-vs-announce.md` — analysis of merging
  `announce_builder::Query` into `Announce`
- New `analysis-announce-response-types.md` — analysis of restructuring
  response types into layered modules
- Updated `ISSUE.md` — added DD6-DD9 design decisions, subtasks T7-T17,
  and progress log entries
…:Announce

- Merged `announce_builder::Query` and its builder into `announce::Announce`
- Added `peer_addr: Option<IpAddr>` field per BEP 3
- Added `Display` impl for URL query string serialization
- Added `AnnounceBuilder` with ergonomic construction (u64→NumberOfBytes conversion)
- Added `extract_peer_addr()` — invalid peer_addr values are silently ignored (BEP 3 optional)
- Removed `announce_builder` module (deleted announce_builder.rs and mod.rs reference)
- Updated ~54 call sites across 7 files
- All linters and tests pass
…modules

Replaced flat `announce.rs` with `announce/{data,encoding}.rs` directory module.

- `data.rs` — DTO layer: `AnnounceData`, `AnnouncePolicy`, `SwarmMetadata`, `Peer`
- `encoding.rs` — Encoding layer: `Announce<E>`, `Normal`, `Compact`, peers, tests
- `mod.rs` — Re-exports for backward compatibility (no call site changes needed)

All linters and tests pass. Progress: T10 done, spec updated.
Moved deserialization types from `announce_deserialization.rs` into `announce/deserialization.rs`

- Renamed: `Announce` → `DeserializedNormal`, `Compact` → `DeserializedCompactParsed`
- Added `peers6` field to `DeserializedCompact` (IPv6 support per BEP 7)
- Replaced `CompactPeer` (IPv4-only struct) with shared `encoding::CompactPeer` enum (IPv4+V6)
- Added `CompactPeer::new_from_bytes` supporting both 6-byte IPv4 and 18-byte IPv6 formats
- Deleted `announce_deserialization.rs`
- Updated all 8 import sites across 6 files
- Spec progress: T11 marked DONE
- All linters and tests pass
…dules

Flat scrape.rs and scrape_deserialization.rs replaced by scrape/{data,encoding,deserialization}.rs directory module.

- data.rs - DTO layer: SwarmMetadata, ScrapeData
- encoding.rs - Encoding layer: Bencoded struct + tests
- deserialization.rs - Client-side: Response, File, ResponseBuilder, BencodeParseError
- Deleted both old flat files
- Updated all 7 import sites
- All linters and tests pass
- Progress: T12-T14 done, spec updated
…-client

Replaced the duplicate test-specific HTTP client in client.rs with a thin wrapper around the canonical tracker-client crate.

- Added torrust-tracker-client-lib as a dev-dependency
- Rewrote client.rs to delegate all methods to TrackerClient
- Preserved the exact same public API (new, bind, authenticated, announce, scrape, etc.)
- No call sites needed updating
- Key type mismatch resolved via Key::value() -> TrackerClientKey::new()
- Progress: T16 phase 1 done
…r-client

Removed the duplicate test-specific HTTP client and migrated contract.rs tests to use the canonical tracker-client package directly.

- Deleted tests/server/client.rs
- Removed pub mod client from tests/server/mod.rs
- Added torrust-tracker-client-lib as a dev-dependency
- Migrated all contract.rs tests to use TrackerClient directly
- Added reqwest::Url, std::time::Duration imports where needed
- Fixed type mismatches (.unwrap() on Result, .unwrap() removal on Vec returns)
- All linters and tests pass
- Progress: T15 done, spec updated

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 49 out of 50 changed files in this pull request and generated 1 comment.

Comments suppressed due to low confidence (2)

packages/http-protocol/src/v1/responses/announce/encoding.rs:225

  • CompactPeer::new_from_bytes indexes into bytes without validating that the slice is exactly 6 (IPv4) or 18 (IPv6) bytes. Because this is a public helper, callers can pass a shorter slice and trigger an out-of-bounds panic (or pass an unexpected length and silently get the IPv4 path). Handle unexpected lengths explicitly to avoid UB-like panics and make failures diagnosable.
    packages/http-protocol/src/v1/responses/scrape/deserialization.rs:127
  • InfoHash::from(info_hash_bytes.as_slice()) is an infallible conversion and may panic internally on malformed/malicious scrape responses (e.g., a dict key that is not 20 bytes). Since this function already returns Result<_, BencodeParseError>, it should validate/parse the key fallibly (e.g., InfoHash::try_from(info_hash_bytes)), and map the conversion error into a dedicated BencodeParseError variant rather than panicking.

pub port: u16,

// Optional params
/// The peer IP address (BEP 3 `ip` parameter).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will open a new issue for this.

…ment

Adds Environment<Running>::base_url() that returns a reqwest::Url from the
bind address, replacing ~40 duplicate Url::parse(&format!("http://{}/", ...))
call sites in the HTTP tracker contract tests.
… module

Split the large contract.rs (2018 lines) into smaller per-concern modules
to improve maintainability and make it easier for AI agents to work with.

- for_all_config_modes: further split into and_running_on_reverse_proxy,
  receiving_an_announce_request, receiving_an_scrape_request
- configured_as_whitelisted
- configured_as_private
- configured_as_private_and_whitelisted (with TODOs for missing tests)
- using_ipv6_v6only
All automated checks pass (linter, tests, pre-commit, pre-push).
Manual verification M1-M4 all PASS. Updated issue spec progress,
acceptance criteria, and manual verification evidence.
New skill in .github/skills/usage/use-tracker-client/ covering HTTP/UDP
announce and scrape commands, output formats, verification workflow,
and troubleshooting for the unified tracker_client binary.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 61 out of 62 changed files in this pull request and generated 1 comment.

Comments suppressed due to low confidence (2)

packages/http-protocol/src/v1/responses/announce/encoding.rs:244

  • CompactPeer::new_from_bytes will panic with an out-of-bounds index if bytes.len() is anything other than 6 or 18 (e.g., malformed input, partial chunk). Since this is a public helper, it should validate the length and fail deterministically with a clear message (or return a Result/Option).
    packages/http-protocol/src/v1/responses/announce/deserialization.rs:82
  • DeserializedCompact now includes a peers6 field (IPv6 compact peer list), but DeserializedCompactParsed::from(DeserializedCompact) only iterates over compact_announce.peers (IPv4, 6-byte chunks). As a result, IPv6 peers are silently dropped during parsing even though CompactPeer::new_from_bytes supports 18-byte IPv6 entries.

Comment on lines 96 to +100

// Optional params
/// The peer IP address (BEP 3 `ip` parameter).
pub peer_addr: Option<IpAddr>,

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will open a new issue for this.

@josecelano

Copy link
Copy Markdown
Member Author

ACK de92be2

@josecelano
josecelano merged commit 085811f into torrust:develop Jul 15, 2026
16 checks passed
josecelano added a commit that referenced this pull request Jul 15, 2026
…ssues/open to docs/issues/closed

174904d chore(ci): point to ADR instead of closed issue spec in deployment-packages.yaml (Jose Celano)
2e2178f docs(skill): document branch-already-exists edge case in cleanup-completed-issues skill (Jose Celano)
1bfd306 chore(issues): archive closed issue specs #1447, #1459, #1505, #1926, #1938, #1944, #1959, #1964, #1965, #1969 to docs/issues/closed (Jose Celano)

Pull request description:

  Archives the following 10 issue specs that are closed on GitHub, moving them from `docs/issues/open/` to `docs/issues/closed/`:

  | Issue | Title | PR |
  |-------|-------|-----|
  | #1447 | Change logging threshold for connection ID error to WARNING | #1975 |
  | #1459 | Docker Security Overhaul | #1958 |
  | #1505 | Optimize peer IP list from swarm (implementation rejected) | #1949 |
  | #1926 | Define package versioning strategy | #1961 |
  | #1938 | REST API Contract-First Migration EPIC | #1960 (SI-1→5) |
  | #1944 | SI-6: Align REST API client | #1968 |
  | #1959 | SI-7: Review tests, align v1 namespace | #1963 |
  | #1964 | Rename number-of-downloads BTreeMap type alias | #1972 |
  | #1965 | SI-34: Consolidate duplicate HTTP types | #1974 |
  | #1969 | SI-8: Eliminate unwraps from REST API client | #1973 |

  ### Changes Made

  - All 10 specs verified `CLOSED` on GitHub with merged PRs
  - Files/directories moved via `git mv` to `docs/issues/closed/`
  - Frontmatter updated: `status: done`, `spec-path` → closed path, `last-updated-utc: 2026-07-15`
  - Workflow checkpoints updated and progress log entries added
  - Supplementary files in multi-file directories updated with new paths
  - Parent EPIC specs (#1669, #1938) updated: subissue status, spec paths, and table references
  - Fixed stale references in `.github/workflows/deployment-packages.yaml`, `docs/adrs/`, and `docs/issues/closed/` files
  - Pre-commit and pre-push hooks passed (linter, tests, doc-tests, nightly checks)

ACKs for top commit:
  josecelano:
    ACK 174904d

Tree-SHA512: c7e38354bb5898fc5125a0b68fd61a02ca273689593638eb3b955b9176038ef82c40fc98b0a2f722eb18d8d429d2f2dbb6f205eee3061211ab9906c5be46942b

@da2ce7 da2ce7 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a post-merge review of the change from #1974 (merge commit 085811fa9) as it stands at 39d6d7e1b on the default branch; every path:line below is at that commit.

What still runs: packages/http-protocol owns the client-side request builders (AnnounceBuilder with the Display of Announce, and scrape_builder::Query), the response deserialization types (DeserializedNormal, DeserializedCompact, DeserializedCompactParsed and the scrape Response::try_from_bencoded), the split of the announce and scrape responses into data, deserialization and encoding modules, and percent_encode_byte_array. The tracker client library, the console client's unified http commands and its HTTP checker build and parse tracker traffic with those types, and the contract tests live under packages/axum-http-server/tests/server/v1/contract/. Beyond what the description lists, the change also parsed a new peer_addr query field into the server-side Announce, silently dropping invalid values, and gave the builder an expect on byte counts above i64::MAX; both are history now (the field became the BEP 3 ip parameter with explicit validation in 3de7341, 3820989 and 6928864, and the byte count holds a u64 since f499f9d), so they are not raised here.

[Minor] The scrape response parser can panic on a tracker's reply. packages/http-protocol/src/v1/responses/scrape/deserialization.rs:126 turns each key of the files dictionary into an info-hash with the infallible InfoHash::from(&[u8]), which needs exactly 20 bytes (the in-tree copy of the crate this type came from, removed in 9a05943, asserted the length, and an infallible conversion could otherwise only mangle a wrong-length key). A tracker that answers a scrape with d5:filesd3:abcd8:completei1e10:downloadedi0e10:incompletei0eeee therefore never reaches the BencodeParseError path the callers rely on: the unified scrape command (console/tracker-client/src/console/clients/unified/http.rs:218) does not write its unrecognized_response diagnostic, and in the checker (console/tracker-client/src/console/clients/checker/checks/http.rs:97) the panic ends the HTTP task, so run_checks returns a runtime error at console/tracker-client/src/console/clients/unified/check.rs:144 and drops the results already gathered for every other HTTP, UDP and health-check target. The panic predates this change (the removed client-local InfoHash::new copied the slice the same way); this change carried it into the protocol crate. Smallest fix: InfoHash::try_from(info_hash_bytes.clone()) mapped to a new BencodeParseError variant (the enum is already #[non_exhaustive]), with tests for a 19-byte and a 21-byte key.

[Minor] The HTTP side of the client now announces with one fixed peer id from every host. AnnounceBuilder::with_default_values() (packages/http-protocol/src/v1/requests/announce.rs:458) sets peer_id to the constant -qB00000000000000001, and both production callers keep it unless the operator passes --peer-id: the unified http announce command (console/tracker-client/src/console/clients/unified/http.rs:159) and the HTTP checker (console/tracker-client/src/console/clients/checker/checks/http.rs:73). Before this change the client's own builder used default_production_peer_id() (packages/tracker-client/src/peer_id.rs:19: the -RC3000- prefix and a 12-digit suffix drawn once per process), as the UDP checker still does (console/tracker-client/src/console/clients/udp/checker.rs:137); the description does not mention the change. BEP 3 asks each downloader to generate its own peer id at random. Concrete sequence: two hosts run the HTTP checker against the same public tracker, and both announce event=started for the checker's fixed info-hash 9c38422213e30bff212b30c360d26f9a02136422 under the same peer id, whose -qB prefix is another client's code; a tracker that identifies peers by peer id cannot tell the two hosts apart (this tracker keys swarm entries by socket address, so it is not affected itself). Smallest fix: have the two console call sites call .with_peer_id(&default_production_peer_id()) when no peer id is given, keeping the constant as the protocol crate's test default.

[Minor] The parsed compact announce response ignores peers6 and trailing bytes. This change added peers6 to DeserializedCompact and an 18-byte IPv6 branch to CompactPeer::new_from_bytes, but From<DeserializedCompact> for DeserializedCompactParsed (packages/http-protocol/src/v1/responses/announce/deserialization.rs:79) reads only peers, in 6-byte chunks, and discards the remainder (:81). A response whose peers is empty and whose peers6 holds one 18-byte entry parses to an empty peer list, and a 13-byte peers string parses to two peers with no error. At this head the type's only consumer is the contract helper assert_compact_announce_response (packages/axum-http-server/tests/server/asserts.rs:78), so no contract test can assert the server's IPv6 compact peers and a regression in the peers6 encoding would pass; the type is public, so a library user loses IPv6 peers without notice. Smallest fix: also read peers6.as_chunks::<18>() into the parsed list, and turn a non-empty remainder in either string into an error through a TryFrom.

[Nit] CompactPeer::new_from_bytes (packages/http-protocol/src/v1/responses/announce/encoding.rs:231) is public, takes any slice, indexes it without a length check (a 5-byte slice panics, with no # Panics section) and reads every length other than 18 as IPv4. Its one caller already holds fixed-size chunks, so two constructors taking &[u8; 6] and &[u8; 18] remove both the panic and the guess.

[Nit] packages/tracker-client/src/http/client/mod.rs:2 and :3 still export requests and responses, which now hold only module docs. A downstream crate that imported torrust_tracker_client::http::client::requests::announce::QueryBuilder gets an unresolved import with no pointer to the new paths. Remove the two modules, or re-export the moved types from them under #[deprecated] for one release.

Checked and found sound at this head: percent_encode_byte_array and the server-side info-hash and peer-id decoding (InfoHash::try_from and explicit 20-byte checks in packages/http-protocol/src/percent_encoding.rs); the query strings written by Announce and scrape_builder::Query, which hold only alphanumerics and %XX escapes for the 20-byte fields, decimal numbers and an IP literal; the scrape file-field parser's errors for missing, unknown and non-integer fields; the hex-keyed Serialize of the scrape Response; the move of the announce and scrape encoders into encoding modules without a change in output; the consumers' imports in the tracker client library and the console client; and the split of the former contract.rs into the contract/ directory, with 53 tests before and after and none ignored.

This branch was previously deployed

1 inactive deployment
coverage — de92be28 Deployed Jul 15, 2026 by josecelano via Generate Coverage Report #1569
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

EPIC 1669 SI-34: Consolidate duplicate HTTP types into http-protocol

3 participants