Skip to content

feat(rest-api-application): migrate stats context to contract-first architecture - #1954

Merged
josecelano merged 6 commits into
torrust:developfrom
josecelano:1942-migrate-stats-context
Jun 27, 2026
Merged

josecelano merged 6 commits into
torrust:developfrom
josecelano:1942-migrate-stats-context

Conversation

@josecelano

@josecelano josecelano commented Jun 26, 2026 •

Copy link
Copy Markdown
Member

Description

Implements SI-4: Migrate stats context to contract-first architecture (sub-issue of #1938).

Changes

  • rest-api-protocol: Added v1::context::stats/ with Stats (28 fields) and LabeledStats DTOs. Added torrust-metrics dep for MetricCollection.
  • rest-api-application: Defined StatsQueryPort trait and StatsApiService use-case.
  • rest-api-runtime-adapter: Implemented TrackerStatsAdapter — aggregation logic moved here from rest-api-core (Option 3). Added deps: http-core, udp-core, udp-server, swarm-coordination-registry.
  • axum-rest-api-server: Rewired handlers to single Arc<StatsApiService> instead of 7-element tuple state. Prometheus serialization stays in Axum (Option A).
  • deny.toml: Updated wrapper lists for udp-server, http-core, udp-core to allow the adapter.

Architecture flow

Handlers → StatsApiService (use-case)
         → StatsQueryPort (trait)
         → TrackerStatsAdapter (adapter, owns aggregation)
         → 7 tracker repositories/services

Aggregation Strategy

Three options were considered (see spec for details). Option 3 (applied): move aggregation from rest-api-core into the adapter, advancing SI-5's deprecation goal.

Verification

  • Stats and LabeledStats DTOs defined in protocol
  • StatsQueryPort trait defined in application
  • StatsApiService use-case implemented
  • TrackerStatsAdapter implemented (aggregation moved from rest-api-core)
  • Axum handlers dispatch through use-case (no more tuple state)
  • Prometheus serialization preserved in Axum (Option A)
  • Pre-commit checks pass
  • Pre-push checks (CI)

Copilot AI review requested due to automatic review settings June 26, 2026 19:25
@josecelano josecelano self-assigned this Jun 26, 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

Migrates the REST API stats context to the contract-first layered architecture (protocol → application → runtime-adapter → axum transport), moving aggregation out of rest-api-core into a dedicated runtime adapter and rewiring Axum handlers to call a single application-layer use-case service.

Changes:

  • Added Stats / LabeledStats DTOs to rest-api-protocol and introduced torrust-metrics for MetricCollection.
  • Added StatsQueryPort + StatsApiService in rest-api-application, and implemented TrackerStatsAdapter in rest-api-runtime-adapter to own aggregation.
  • Rewired Axum stats/metrics handlers to use Arc<StatsApiService> state; updated dependency-layer deny rules and supporting docs.

Reviewed changes

Copilot reviewed 23 out of 24 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
project-words.txt Adds new dictionary words and reorders entries to keep cspell dictionary tidy.
packages/rest-api-runtime-adapter/src/adapters/stats.rs Introduces TrackerStatsAdapter implementing StatsQueryPort and performing stats aggregation/metric merges.
packages/rest-api-runtime-adapter/src/adapters/mod.rs Exposes the new stats adapter module.
packages/rest-api-runtime-adapter/Cargo.toml Adds runtime-adapter dependencies required for stats aggregation (http-core, udp-*, swarm-*, tokio, torrust-metrics).
packages/rest-api-protocol/src/v1/context/stats/resources/stats.rs Defines contract DTOs for /api/v1/stats and /api/v1/metrics.
packages/rest-api-protocol/src/v1/context/stats/resources/mod.rs Registers the stats resources module.
packages/rest-api-protocol/src/v1/context/stats/mod.rs Adds the stats context module in the protocol layer.
packages/rest-api-protocol/src/v1/context/mod.rs Registers the new stats context.
packages/rest-api-protocol/Cargo.toml Adds torrust-metrics dependency to support MetricCollection in protocol DTOs.
packages/rest-api-application/src/use_cases/stats.rs Adds the StatsApiService application use-case that delegates to the port.
packages/rest-api-application/src/use_cases/mod.rs Registers the new stats use-case module.
packages/rest-api-application/src/ports/stats.rs Introduces StatsQueryPort defining the application boundary for stats queries.
packages/rest-api-application/src/ports/mod.rs Registers the new stats port module.
packages/axum-rest-api-server/tests/server/v1/contract/context/stats.rs Updates tests to import Stats from rest-api-protocol (contract-first).
packages/axum-rest-api-server/tests/server/v1/asserts.rs Updates asserts to use protocol Stats type.
packages/axum-rest-api-server/src/v1/routes.rs Wires TrackerStatsAdapter + StatsApiService and injects into stats routes.
packages/axum-rest-api-server/src/v1/context/stats/routes.rs Switches stats routing state from tuple repositories to Arc<StatsApiService>.
packages/axum-rest-api-server/src/v1/context/stats/responses.rs Keeps Prometheus serialization in Axum, now using protocol DTOs directly.
packages/axum-rest-api-server/src/v1/context/stats/resources.rs Removes Axum-local stats DTOs (now owned by protocol).
packages/axum-rest-api-server/src/v1/context/stats/mod.rs Removes resources module export (DTOs moved to protocol).
packages/axum-rest-api-server/src/v1/context/stats/handlers.rs Refactors handlers to call StatsApiService instead of rest-api-core aggregation.
docs/issues/open/1942-1938-si-4-migrate-stats-context.md Updates SI-4 spec with applied aggregation strategy and task statuses.
deny.toml Allows rest-api-runtime-adapter to wrap udp-server, http-core, and udp-core per layer rules.
Cargo.lock Locks new dependency graph including torrust-metrics and tokio for runtime-adapter.

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

@josecelano josecelano linked an issue Jun 26, 2026 that may be closed by this pull request
9 tasks
…rchitecture

- Add Stats (28-field) and LabeledStats DTOs to rest-api-protocol
- Add torrust-metrics dependency to rest-api-protocol for MetricCollection
- Define StatsQueryPort trait in rest-api-application
- Implement StatsApiService use-case in rest-api-application
- Implement TrackerStatsAdapter in rest-api-runtime-adapter
  (moved aggregation logic from rest-api-core - Option 3)
- Rewire Axum handlers to dispatch through StatsApiService
- Remove 7+ tuple state wiring from handlers and routes
- Keep Prometheus serialization in Axum responses.rs (Option A)
- Update issue spec with Option 3 documentation
- Update deny.toml with new adapter dependency edges
…s adapter

- Remove dead code in get_labeled_stats (unused prefetch lines)
- Remove unnecessary #[allow(deprecated)] directive
- Remove unused ban_service field and import
- Fix inconsistent expect panic messages (remove 'msg: ' prefix)
- Remove unused tokio dependency from adapter Cargo.toml
- Fix duplicate deps in adapter Cargo.toml
- Fix clippy struct_field_names lint on adapter
- Update spec verification checklist to reflect pre-commit status
@josecelano
josecelano force-pushed the 1942-migrate-stats-context branch from eb45e77 to 791e3f9 Compare June 26, 2026 21:07
- Added new ClippyFixer agent to automate clippy warning fixes
- Added fix-clippy-warnings skill with proper clippy handling guidelines
- Updated run-linters skill to reference the new clippy fix skill
- All changes follow repository rules about preferring fixes over allowances
- All clippy warnings in SI-4 were properly fixed with as_chunks instead of #[allow]
@josecelano
josecelano requested a review from a team as a code owner June 27, 2026 11:45
@josecelano

Copy link
Copy Markdown
Member Author

ACK bb10343

@josecelano
josecelano merged commit 5a8e788 into torrust:develop Jun 27, 2026
16 checks passed
@josecelano
josecelano deleted the 1942-migrate-stats-context branch June 27, 2026 12:50

@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 #1954 as it stands at e170b9620 on the default branch.

What still runs: the StatsQueryPort port and the StatsApiService use case in rest-api-application; the TrackerStatsAdapter in rest-api-runtime-adapter, now at src/v1/adapters/stats.rs, which reads each repository through read_metrics and carries the completed-download fields that 1946763 added; the Stats and LabeledStats DTOs in rest-api-protocol, where Stats is now generated by the stats! macro; one Arc<StatsApiService> as the state of both stats routes; and the as_chunks decoding in udp-protocol. The rest-api-core copy of the aggregation, which this change duplicated rather than moved, has since been removed, so that duplication is gone. The description leaves out two things: the stats handlers' switch from axum_extra::extract::Query to axum::extract::Query, and the udp-protocol rewrite. It also says seven repositories feed the adapter; the adapter takes six, because the only use of the UDP ban service was a read whose result nobody used. The extractor switch keeps the accepted format values (json, prometheus or absent) and the rejection of any other value, and the handler tests at the tip pin both.

[Nit] packages/rest-api-runtime-adapter/src/v1/adapters/stats.rs:65 makes three separate get_* calls for completed, completed_in_session and completed_persisted. Each call takes the tracker-core statistics read lock on its own (packages/tracker-core/src/statistics/repository.rs:223). On the write side, the legacy and in-session counters are incremented under two separate write locks (packages/tracker-core/src/statistics/event/handler.rs:71). With persistence disabled, completed and completed_in_session hold the same count. A download that completes while a GET /api/v1/stats request is being served can still produce completed: N with completed_in_session: N+1, or the reverse, depending on where the write falls between the reads. The next request agrees again, so the only harm is a one-sample mismatch for a consumer that compares the two fields. These reads came in with 1946763. Smallest fix: read the three counters in one read_metrics closure, and increment the two in-memory counters under one write lock.

[Nit] The expect at packages/rest-api-runtime-adapter/src/v1/adapters/stats.rs:142, and the four after it, panic if two subsystems ever export the same metric name. The function this code replaced, get_labeled_metrics in rest-api-core, documented that condition in a # Panics section. The section was dropped when the code moved, and neither StatsQueryPort::get_labeled_stats (packages/rest-api-application/src/v1/ports/stats.rs:25) nor the adapter mentions it. The five collections export distinct metric names today, and the contract tests that request GET /api/v1/metrics would catch a collision, so nothing panics at this head. The REST API router has no panic-catching layer, though, so a colliding name added later would close the connection without a response on every /metrics request. Smallest fix: restore the # Panics note on the adapter method, and name the duplicate-name condition in it.

[Nit] To read the UDP server statistics repository, this change made rest-api-runtime-adapter depend on torrust-tracker-udp-server, and it allowed that dependency in deny.toml:57. docs/packages.md:72 counts udp-server among the tracker internals the adapter wraps. packages/AGENTS.md:10, however, says dependencies only flow downward, and its diagram draws the runtime adapter below the server layer that holds udp-server (packages/AGENTS.md:17). The two documents disagree about the edge this change added, so a contributor who follows packages/AGENTS.md reads a sanctioned dependency as a layering violation. Smallest fix: record the exception in packages/AGENTS.md, or move the UDP server statistics repository to a lower layer.

Checked and found sound: every field of /api/v1/stats maps to the same source as in the rest-api-core aggregation it replaced, including tcp4_connections_handled and tcp6_connections_handled as announces plus scrapes. The dropped ban-service read and the swarm-metadata future that was never awaited were dead code. completed_persisted_enabled is taken from the same validated persistent_torrent_completed_stat setting that the statistics repository uses, and the core container rejects that setting when no database is configured. Both stats routes sit behind the API token middleware. The read_metrics closures neither nest locks nor block. The as_chunks rewrite rejects a trailing partial record exactly as chunks_exact did, and as_chunks is within the 1.88 MSRV. The dangling resources::Stats doc links this change left behind have since been fixed.

This branch was previously deployed

1 inactive deployment
coverage — bb10343c Deployed Jun 27, 2026 by josecelano via Generate Coverage Report #1502
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.

SI-4: Migrate stats context to contract-first architecture

3 participants