diff --git a/Cargo.lock b/Cargo.lock index 68692b044a..f7d56a4b8d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4883,11 +4883,10 @@ dependencies = [ [[package]] name = "torrust-server-lib" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93819242b8132dfed96890ef7011ce954b12784bb8011db9968faa174919f785" +checksum = "8aef800d3f20c6c35fc18f1d6405271dcebabe7e88fe4b14f31105dd23b4321f" dependencies = [ - "derive_more 2.1.1", "tokio", "tokio-util", "torrust-net-primitives", @@ -5082,7 +5081,6 @@ dependencies = [ "tokio", "tokio-util", "torrust-located-error", - "torrust-server-lib", "torrust-tracker-configuration", "tower", "tracing", diff --git a/Cargo.toml b/Cargo.toml index 0d77835695..f4560866c4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -112,7 +112,7 @@ torrust-tracker-axum-server = { version = "0.1.0", path = "packages/axum-server" torrust-tracker-rest-api-client = { version = "0.1.0", path = "packages/rest-api-client" } torrust-tracker-rest-api-runtime-adapter = { version = "0.1.0", path = "packages/rest-api-runtime-adapter" } torrust-tracker-rest-api-protocol = { version = "0.1.0", path = "packages/rest-api-protocol" } -torrust-server-lib = "0.5.0" +torrust-server-lib = "0.6.0" torrust-clock = "3.0.0" torrust-tracker-configuration = { version = "3.0.0", path = "packages/configuration" } torrust-tracker-primitives = { version = "3.0.0", path = "packages/primitives" } diff --git a/docs/features/shutdown-process/README.md b/docs/features/shutdown-process/README.md index 87050cc904..ca38caa146 100644 --- a/docs/features/shutdown-process/README.md +++ b/docs/features/shutdown-process/README.md @@ -18,7 +18,7 @@ semantic-links: Draft — implementation in progress under [EPIC #1488](../../issues/open/1488-overhaul-tracker-shutdown/ISSUE.md), which tracks each sub-issue's status. The [legacy API migration guide](legacy-api-migration.md) maps each -deprecated shutdown symbol to its token-aware replacement. The [task inventory](task-inventory.md) +removed legacy shutdown symbol to its token-aware replacement. The [task inventory](task-inventory.md) records the current state; for example, the standalone HTTP test environment and example use the token-aware lifecycle after SI-16 (#2412). diff --git a/docs/features/shutdown-process/legacy-api-migration.md b/docs/features/shutdown-process/legacy-api-migration.md index 9d84897848..7a38ad203a 100644 --- a/docs/features/shutdown-process/legacy-api-migration.md +++ b/docs/features/shutdown-process/legacy-api-migration.md @@ -1,18 +1,21 @@ --- doc-type: feature-supporting-analysis status: draft -last-updated-utc: "2026-11-10 11:29" +last-updated-utc: "2026-11-10 15:30" semantic-links: related-artifacts: - docs/features/shutdown-process/README.md - docs/issues/closed/2751-1488-si-18-deprecate-legacy-shutdown-api/ISSUE.md + - docs/issues/open/2801-1488-si-19-remove-legacy-shutdown-api/ISSUE.md --- # Migrating from the Legacy Shutdown API EPIC [#1488](../../issues/open/1488-overhaul-tracker-shutdown/ISSUE.md) replaces the `Halted` oneshot-channel shutdown with a `tokio_util::sync::CancellationToken` that the caller injects and cancels. SI-18 (issue #2751) -deprecates the legacy API at the source; nothing is removed and behavior is unchanged. SI-19 removes it. +deprecated the legacy API at the source, and SI-19 (issue #2801) removed it: the symbols in the first column +below no longer exist, and `torrust-server-lib` 0.6.0 removes its own. Use this guide to migrate code that still +calls them. ## What changed @@ -23,12 +26,13 @@ deprecates the legacy API at the source; nothing is removed and behavior is unch the drain outcome. The UDP server differs: its `CancellationRunning` holds only `local_addr` and one receive-loop `task`, which returns `Ok(())` after cancellation, so await that task; there is no drain controller. - **Do not subscribe to signals in a library.** The executable subscribes to SIGINT and SIGTERM and cancels the - token; `global_shutdown_signal` and `shutdown_signal*` are deprecated in `torrust-server-lib` 0.5.0. + token; `global_shutdown_signal` and `shutdown_signal*` were deprecated in `torrust-server-lib` 0.5.0 and are + removed in 0.6.0. No server library subscribes to operating-system signals. ## Replacement table -| Deprecated | Replacement | -| ---------- | ----------- | +| Removed (SI-19) | Replacement | +| --------------- | ----------- | | `axum-http-server`: `HttpServer::start`, `start_with_health_check`, `RunningHttpServer` | `start_with_cancellation`, `start_with_cancellation_and_health_check` | | `axum-http-server`: `Running`, `Running.halt_task`, `HttpServer::stop` | `CancellationRunning`; cancel the token and join `task` and `shutdown_controller` | | `axum-rest-api-server`: `ApiServer::start`, `Launcher::start`, `RunningApiServer` | `ApiServer::start_with_cancellation` | @@ -41,6 +45,6 @@ deprecates the legacy API at the source; nothing is removed and behavior is unch | `torrust-tracker`: `HaltSignal`, `NestedServerTask` | a `CancellationToken` and the token-aware shutdown controller | | `torrust-server-lib`: `Halted`, `shutdown_signal*`, `global_shutdown_signal` | `CancellationToken`, `cancellation_signal` (see the library's `CHANGELOG.md`) | -Each deprecation message names its replacement and says the removal is planned for the next breaking release of -the package. The five server package crates are unpublished and the root types are not in the published 3.0.0, so -these notes are in-repo guidance; only the `torrust-server-lib` deprecation has a support window (0.5.x). +The five server package crates are unpublished and the root types were never in a published release, so for them +this guide is in-repo history; only `torrust-server-lib` had a support window (0.5.x), which ended when the +maintainer approved 0.6.0 on 2026-11-10 (recorded in the start gate of the [SI-19 spec](../../issues/open/2801-1488-si-19-remove-legacy-shutdown-api/ISSUE.md), merged in torrust/torrust-tracker#2803). diff --git a/docs/features/shutdown-process/task-inventory.md b/docs/features/shutdown-process/task-inventory.md index d6219af490..6d6ed11bab 100644 --- a/docs/features/shutdown-process/task-inventory.md +++ b/docs/features/shutdown-process/task-inventory.md @@ -354,11 +354,9 @@ use of the root token is the legacy `udp_ban_cleanup` job. library-level OS signals for any server component. The HTTP and UDP test environments and examples use the token-aware path after SI-16 (#2412) and SI-17 (#2448), and the REST API and health-check API test - environments do after SI-23 (#2449) and SI-24 (#2450). The legacy `Halted` - APIs remain for other legacy callers until deprecation and removal in - SI-18 and SI-19. - The legacy UDP launcher is now an adapter over - the token-aware receive loop, so it can no longer panic or detach it. + environments do after SI-23 (#2449) and SI-24 (#2450). SI-18 (#2751) + deprecated the legacy `Halted` APIs and SI-19 (#2801) removed them, together + with the legacy UDP launcher adapter. 5. HTTP, REST, and health-check drain controllers are component-owned and joined. Aligning their drain budgets with the manager deadline is SI-20. 6. Health-check lifecycle uses the token-aware path after SI-13 but does not diff --git a/docs/issues/open/2801-1488-si-19-remove-legacy-shutdown-api/ISSUE.md b/docs/issues/open/2801-1488-si-19-remove-legacy-shutdown-api/ISSUE.md index 7f8cec9265..508c1d3ec7 100644 --- a/docs/issues/open/2801-1488-si-19-remove-legacy-shutdown-api/ISSUE.md +++ b/docs/issues/open/2801-1488-si-19-remove-legacy-shutdown-api/ISSUE.md @@ -2,14 +2,14 @@ schema-version: 1 doc-type: issue issue-type: task -status: planned +status: in-progress priority: p1 epic: 1488 github-issue: 2801 spec-path: docs/issues/open/2801-1488-si-19-remove-legacy-shutdown-api/ISSUE.md -branch: "2801-remove-legacy-shutdown-api-spec" -related-pr: null -last-updated-utc: "2026-11-10 14:25" +branch: "2801-remove-legacy-shutdown-api" +related-pr: 2807 +last-updated-utc: "2026-11-10 17:27" semantic-links: skill-links: - create-issue @@ -77,8 +77,8 @@ evidence goes in this issue's `manual-verification-evidence.md` (SI-18's gate ev torrust/torrust-server-lib#5, PR torrust/torrust-server-lib/pull/6 (merged into `main` at `2dd04f4`), release notes in its `CHANGELOG.md`; crates.io reports `max_version` 0.6.0 (checked 2026-11-10). This is an external - dependency this task waits for; the maintainer published it, which is the - publication SI-18 assigned to SI-19. + dependency this task waits for; its publication is the step SI-18 assigned to + SI-19. ## Scope @@ -122,7 +122,7 @@ evidence goes in this issue's `manual-verification-evidence.md` (SI-18's gate ev maintainer agreed on 2026-11-10 to split it into its own follow-up issue. - The `torrust-server-lib` 0.6.0 removal and its publication: SI-18 assigned the publication to SI-19, but it was done in the `torrust-server-lib` repository - (torrust/torrust-server-lib#5, PR 6) and published by the maintainer before + (torrust/torrust-server-lib#5, PR 6) and published before implementation, so it is an external dependency this task only waits for. - Changing cancellation-tree behavior, component child ownership, timeout policy, exit-code policy, or readiness behavior. @@ -150,20 +150,22 @@ evidence goes in this issue's `manual-verification-evidence.md` (SI-18's gate ev ## Acceptance Criteria - [ ] All start-gate evidence is complete and independently reviewed. -- [ ] `Halted` shutdown API and legacy shutdown helpers are removed from their - declared packages; `Started` remains available and tested. -- [ ] Server-library code contains no OS-signal subscription. -- [ ] Workspace searches find no legacy shutdown API reference outside archived - documentation describing the migration history. -- [ ] The tracker binary and standalone HTTP/UDP examples handle SIGINT and +- [x] `Halted` shutdown API and legacy shutdown helpers are removed from their + declared packages; `Started` remains available in `torrust-server-lib` 0.6.0 and + is no longer used in this workspace. +- [x] Server-library code contains no OS-signal subscription. +- [x] Workspace searches find no use of the legacy shutdown API. Descriptions of it + remain only in archived documentation and migration history, and in five lines + of live specs of other issues (see the evidence, Test 1). +- [x] The tracker binary and standalone HTTP/UDP examples handle SIGINT and Unix SIGTERM only at their executable boundaries. -- [ ] Deterministic tests request cancellation through tokens/lifecycle APIs and +- [x] Deterministic tests request cancellation through tokens/lifecycle APIs and verify owned child completion without OS signals. -- [ ] End-to-end SIGINT and SIGTERM tests verify one orderly shutdown sequence +- [x] End-to-end SIGINT and SIGTERM tests verify one orderly shutdown sequence per component with no duplicate library signal handling. -- [ ] Container and service-manager verification follows the deadline policy +- [x] Container and service-manager verification follows the deadline policy defined by Q4 and the deployment guidance defined by the final policy task. -- [ ] `linter all` passes. +- [x] `linter all` passes. ## Dependencies @@ -188,12 +190,12 @@ Status values: `TODO`, `IN_PROGRESS`, `BLOCKED`, `DONE`. | ID | Status | Task | Notes / Expected Output | | --- | ------ | ---- | ----------------------- | -| T1 | TODO | Wait for `torrust-server-lib` 0.6.0 (done) and branch from the merged spec. No change and no commit. | Recorded in the progress log only. | -| T2 | TODO | `udp-server`: remove `Server::start`, legacy `Running` and `RunningUdpServer`, `Server::stop`, `Launcher::run_with_graceful_shutdown`, `Spawner::spawn_launcher`, `LaunchRequest`, `legacy_stop_requested`, `halt_requested`, and the `global_shutdown_signal` use. | Legacy-only tests removed; token lifecycle tests stay. | -| T3 | TODO | `axum-http-server`, `axum-rest-api-server`, `axum-health-check-api-server`, `axum-server`: remove the legacy `start`, `start_with_health_check`, `stop`, `Running` structs and aliases, `Running::new`, `halt_task`, `rx_halt`, `RunningServer` and `graceful_shutdown`. | Token-aware paths keep their child ownership and join behavior. | -| T4 | TODO | Root: remove `HaltSignal` and `NestedServerTask` and their tests; bump `torrust-server-lib` to 0.6.0 in every `Cargo.toml`; drop every `#[allow(deprecated)]` added by SI-18 and the compat tests that exist only for removed symbols. | The bump lands with the removals, since 0.6.0 removes `Halted` and an earlier bump would not build. `cargo check --workspace --all-targets` warning-free. | -| T5 | TODO | Update docs: the migration guide `docs/features/shutdown-process/legacy-api-migration.md` (removed, with history), the shutdown-process docs, and the EPIC row. | Workspace search finds legacy symbols only in archived history. | -| T6 | TODO | Verify and record evidence: searches, deterministic tests, SIGINT/SIGTERM for the tracker and both standalone examples, container check. | `manual-verification-evidence.md`. | +| T1 | DONE | Wait for `torrust-server-lib` 0.6.0 (done) and branch from the merged spec. No change and no commit. | Recorded in the progress log only. | +| T2 | DONE | `udp-server`: remove `Server::start`, legacy `Running` and `RunningUdpServer`, `Server::stop`, `Launcher::run_with_graceful_shutdown`, `Spawner::spawn_launcher`, `LaunchRequest`, `legacy_stop_requested`, `halt_requested`, and the `global_shutdown_signal` use. | Legacy-only tests removed; token lifecycle tests stay. | +| T3 | DONE | `axum-http-server`, `axum-rest-api-server`, `axum-health-check-api-server`, `axum-server`: remove the legacy `start`, `start_with_health_check`, `stop`, `Running` structs and aliases, `Running::new`, `halt_task`, `rx_halt`, `RunningServer` and `graceful_shutdown`. | Token-aware paths keep their child ownership and join behavior. | +| T4 | DONE | Root: remove `HaltSignal` and `NestedServerTask` and their tests; bump `torrust-server-lib` to 0.6.0 in every `Cargo.toml`; drop every `#[allow(deprecated)]` added by SI-18 and the compat tests that exist only for removed symbols. | The bump lands with the removals, since 0.6.0 removes `Halted` and an earlier bump would not build. `cargo check --workspace --all-targets` warning-free. | +| T5 | DONE | Update docs: the migration guide `docs/features/shutdown-process/legacy-api-migration.md` (removed, with history), and the shutdown-process docs. The EPIC row 19 is flipped to Done by the close-out archive step, as for SI-18 row 18. | Workspace search finds no use of the legacy symbols; descriptions remain in archived docs and the listed live specs. | +| T6 | DONE | Verify and record evidence: searches, deterministic tests, SIGINT/SIGTERM for the tracker and both standalone examples, container check. | `manual-verification-evidence.md`. | ## Commit Points @@ -215,11 +217,11 @@ Sign every commit with GPG. - [x] Folder-style spec drafted in `docs/issues/drafts/`, moved to `docs/issues/open/` - [x] Spec reviewed and approved by the maintainer (issue creation and spec-only PR approved in chat, 2026-11-10) - [x] GitHub issue created and issue number added to this spec (#2801) -- [ ] Spec-only PR merged into `develop` before implementation +- [x] Spec-only PR merged into `develop` before implementation (PR 2803) - [x] `torrust-server-lib` 0.6.0 published (external dependency, 2026-11-10) -- [ ] Implementation completed +- [x] Implementation completed - [ ] Automatic verification completed (`linter all`, relevant tests, pre-push checks) -- [ ] Manual verification scenarios executed and recorded in `manual-verification-evidence.md` +- [x] Manual verification scenarios executed and recorded in `manual-verification-evidence.md` - [ ] Acceptance criteria reviewed after implementation and updated with evidence - [ ] Evidence-based implementation completion review recorded: an issue-local `implementation-retrospective.md` for material discoveries, or a progress-log entry that says why none was needed - [ ] Independent reviewer reports recorded in `agent-review-reports.md` @@ -234,6 +236,11 @@ Sign every commit with GPG. - 2026-11-10 13:36 UTC - AI agent (Claude Sonnet 5.5) - Added the implementation-completion-review checkpoint and requirement for Copilot's finding R2 (commit at 13:36:46 UTC). - 2026-11-10 13:59 UTC - AI agent (Claude Sonnet 5.5) - Edited the spec for the second review of PR 2803: the 0.6.0 wording reconciled with SI-18 (F11), the removal list stated as the 27 `#[deprecated]` attributes (F12), and these log entries and the stamp corrected (F4). The audit record `docs/pr-reviews/pr-2803-review/PR-REVIEW.md` is added in the same round (F8). - 2026-11-10 14:25 UTC - AI agent (Claude Sonnet 5.5) - Edited the spec for the third review of PR 2803: the stamps now match the commit times (F4) and the removal bullet says the HTTP and REST `Running` structs (F15). +- 2026-11-10 15:47 UTC - AI agent (Claude Sonnet 5.5) - Implemented T2 to T6 on branch `2801-remove-legacy-shutdown-api` after the spec PR 2803 merged: removed the legacy API from `udp-server` and the three axum servers and `axum-server`, removed `HaltSignal` and `NestedServerTask`, bumped `torrust-server-lib` to 0.6.0, and updated the migration guide. `Started` is no longer used or tested inside this workspace; it stays available in `torrust-server-lib` 0.6.0. The public `Error::Stop`, `StartupNotification` and `StartupNotificationDropped` variants of the HTTP and REST servers are now unused but were not deprecated, so they stay (candidate follow-up). Evidence in `manual-verification-evidence.md`. +- 2026-11-10 16:18 UTC - AI agent (Claude Sonnet 5.5) - Addressed the first review of PR 2807 (F1 to F11): wording for `Started`, the T5 note, the evidence (raw search output, the script, the approval link), the status and frontmatter, one removed-API line in a live draft, the token-aware owner test, and the docs left by the removal. The audit is `docs/pr-reviews/pr-2807-review/PR-REVIEW.md`. +- 2026-11-10 16:55 UTC - AI agent (Claude Sonnet 5.5) - Addressed the second review of PR 2807 (F12 to F16): the live-spec search pasted as run, the ten signal invocations and the tracker configuration recorded, the criterion, row and evidence item reworded to match the five live-spec matches, and `branch` pointed at the implementation branch. +- 2026-11-10 16:57 UTC - AI agent (Claude Sonnet 5.5) - Removed the statements that the maintainer published `torrust-server-lib` 0.6.0 from the gate item, the scope note and the evidence, because the evidence only shows that 0.6.0 is published on crates.io. +- 2026-11-10 17:27 UTC - AI agent (Claude Sonnet 5.5) - Addressed the third review of PR 2807 (F17 to F19): the evidence cites the merge of the `torrust-server-lib` PR and describes the verification configuration as a reduced copy, and the second-round entry above is stamped at its commit minute. ## Design and Ownership Review @@ -259,11 +266,11 @@ Executable-boundary verification follows the EPIC protocol (signal each direct P | ID | Scenario | Human-oriented command/steps | Expected Result | Status | Evidence | | -- | -------- | ---------------------------- | --------------- | ------ | -------- | -| M1 | Start-gate evidence | Link SI-18 evidence, the migration issues, #1588, Q5, the approval and the 0.6.0 release. | Every gate item has a link or command output. | TODO | `manual-verification-evidence.md` | -| M2 | Legacy symbols removed | `git grep` for `Halted`, `shutdown_signal`, `global_shutdown_signal`, `HaltSignal`, `NestedServerTask`, `run_with_graceful_shutdown`, `spawn_launcher`, `LaunchRequest` and `tokio::signal` outside executables. | Only archived history matches. | TODO | `manual-verification-evidence.md` | -| M3 | Token lifecycle owns completion | Run the component tests that cancel an injected token. | Owned children joined; no OS signal needed. | TODO | `manual-verification-evidence.md` | -| M4 | Tracker and standalone binaries | SIGINT and SIGTERM to the tracker and both standalone examples. | One application-owned shutdown sequence each; bindings released. | TODO | `manual-verification-evidence.md` | -| M5 | Container / service manager | Stop the container per `docs/containers.md#stopping-the-tracker`. | Orderly shutdown within the Q4 deadline; result per Q3. | TODO | `manual-verification-evidence.md` | +| M1 | Start-gate evidence | Link SI-18 evidence, the migration issues, #1588, Q5, the approval and the 0.6.0 release. | Every gate item has a link or command output. | DONE | `manual-verification-evidence.md` | +| M2 | Legacy symbols removed | `git grep` for `Halted`, `shutdown_signal`, `global_shutdown_signal`, `HaltSignal`, `NestedServerTask`, `run_with_graceful_shutdown`, `spawn_launcher`, `LaunchRequest` and `tokio::signal` outside executables. | No use remains; descriptions match only in archived history and the live specs the evidence lists. | DONE | `manual-verification-evidence.md` | +| M3 | Token lifecycle owns completion | Run the component tests that cancel an injected token. | Owned children joined; no OS signal needed. | DONE | `manual-verification-evidence.md` | +| M4 | Tracker and standalone binaries | SIGINT and SIGTERM to the tracker and both standalone examples. | One application-owned shutdown sequence each; bindings released. | DONE | `manual-verification-evidence.md` | +| M5 | Container / service manager | Stop the container per `docs/containers.md#stopping-the-tracker`. | Orderly shutdown within the Q4 deadline; result per Q3. | DONE | `manual-verification-evidence.md` | Record every command result with its toolchain or runtime. If a scenario fails, record the failure and diagnosis in the progress log before proceeding. @@ -276,15 +283,15 @@ None. | AC | Status | Evidence | | -- | ------ | -------- | -| Start-gate evidence complete and reviewed | TODO | M1 | -| Legacy API removed, `Started` kept and tested | TODO | M2 and the package tests | -| No OS-signal subscription in server libraries | TODO | M2 | -| No legacy reference outside archived history | TODO | M2 | -| Binaries handle SIGINT/SIGTERM only at their boundaries | TODO | M4 | -| Deterministic token tests | TODO | M3 | -| End-to-end SIGINT/SIGTERM, one sequence | TODO | M4 | -| Container and service-manager verification | TODO | M5 | -| `linter all` passes | TODO | Pre-commit hook output | +| Start-gate evidence complete and reviewed | IN_PROGRESS | M1 is DONE; the independent review is the review of the implementation PR 2807, to be recorded in `agent-review-reports.md` or the audit | +| Legacy API removed; `Started` remains available in `torrust-server-lib` 0.6.0 and is no longer used here | DONE | M2 | +| No OS-signal subscription in server libraries | DONE | M2 | +| No use of the removed API remains; descriptions remain in archived docs and five lines of live specs | DONE | M2 | +| Binaries handle SIGINT/SIGTERM only at their boundaries | DONE | M4 | +| Deterministic token tests | DONE | M3 | +| End-to-end SIGINT/SIGTERM, one sequence | DONE | M4 | +| Container and service-manager verification | DONE | M5 | +| `linter all` passes | DONE | `linter all` run on 2026-11-10 after the evidence edit (below) | ## Risks and Trade-offs diff --git a/docs/issues/open/2801-1488-si-19-remove-legacy-shutdown-api/manual-verification-evidence.md b/docs/issues/open/2801-1488-si-19-remove-legacy-shutdown-api/manual-verification-evidence.md index c9a0fa2ffc..1f06dd5560 100644 --- a/docs/issues/open/2801-1488-si-19-remove-legacy-shutdown-api/manual-verification-evidence.md +++ b/docs/issues/open/2801-1488-si-19-remove-legacy-shutdown-api/manual-verification-evidence.md @@ -1,74 +1,298 @@ -# Verification Evidence — Legacy Shutdown API Removal + -> **Status**: Not started - do not populate implementation evidence until every -> SI-19 start-gate condition and the declared external compatibility window are met. +# Verification Evidence — Legacy Shutdown API Removal (#2801) + +> **Status**: Verified on 2026-11-10 (M1 to M5). ## Environment -- Date: -- OS: -- Rust version (`rustc --version`): -- Tracker commit/branch: -- `torrust-server-lib` breaking release/version: 0.6.0 +- Date: 2026-11-10 +- OS: Linux 7.0.0-43-generic +- Rust version (`rustc --version`): rustc 1.99.1 (58cf8f9c3 2026-10-13) +- Tracker commit/branch: `2801-remove-legacy-shutdown-api` (head recorded in the PR) +- `torrust-server-lib` breaking release/version: 0.6.0 (crates.io `max_version` 0.6.0) ## Start-Gate Evidence -- [ ] Link completed SI-18 deprecation evidence (#2751, PRs 2752, 2793, 2797). -- [ ] Link the completed token-lifecycle migrations (SI-11 through SI-17, SI-23 #2449, SI-24 #2450). -- [ ] Link #1588 final task inventory. -- [ ] Link the maintainer approval ending the 0.5.x window (no fixed end date) and the `torrust-server-lib` 0.6.0 release notes (torrust/torrust-server-lib#5, PR 6). -- [ ] Link Q4/Q5 decisions and deployment/process-wrapper policy. +- [x] SI-18 deprecation evidence: issue #2751, PRs 2752, 2793 and close-out 2797; + `docs/issues/closed/2751-1488-si-18-deprecate-legacy-shutdown-api/manual-verification-evidence.md`. +- [x] Token-lifecycle migrations: SI-11 to SI-17, SI-23 (#2449) and SI-24 (#2450), all Done in the EPIC table + `docs/issues/open/1488-overhaul-tracker-shutdown/ISSUE.md`. +- [x] #1588 (closed) final task inventory. +- [x] The maintainer's approval ending the 0.5.x window (given in chat on 2026-11-10, with no issue or PR comment of + its own) and the `torrust-server-lib` 0.6.0 release notes: torrust/torrust-server-lib#5, PR + torrust/torrust-server-lib/pull/6, merged (the spec's gate item records the merge; release notes in `CHANGELOG.md`). The + maintainer merged the spec PR torrust/torrust-tracker#2803, whose start gate records the approval. +- [x] Q4/Q5 decisions and the deployment policy: `docs/features/shutdown-process/questions.md` and + `docs/containers.md#stopping-the-tracker`. ## Source and Deterministic Tests ### Test 1: Legacy symbols and library signal handling are gone -- [ ] Search the workspace for removed `Halted` shutdown symbols and legacy - signal helpers. -- [ ] Verify remaining matches are only archived migration history. -- [ ] Verify no server-library module subscribes to SIGINT or SIGTERM. +- [x] Search the workspace for removed `Halted` shutdown symbols and legacy signal helpers. +- [x] No use of the removed API remains. Descriptions of it match in archived migration history, ADRs, analysis and the migration guide, and in five lines of four live specs of other issues (listed below). +- [x] No server-library module subscribes to SIGINT or SIGTERM. -**Evidence:** +**Evidence:** output at this head. The last search covers the live specs under `docs/issues/open` and +`docs/issues/drafts`; its matches are old descriptions of the legacy API in specs of other issues, not uses of it. ```text -(paste searches and review output) +$ git grep -nE "Halted|shutdown_signal_with_message|global_shutdown_signal|HaltSignal|NestedServerTask|run_with_graceful_shutdown|spawn_launcher|LaunchRequest|RunningHttpServer|RunningApiServer|RunningUdpServer" -- "*.rs" "*.toml" +(exit 1) + +$ git grep -nE "tokio::signal|SignalKind|ctrl_c" -- "*.rs" | grep -vE "^(src/main.rs|src/console/profiling.rs|packages/[a-z-]+/examples/)" +console/tracker-client/src/console/clients/checker/monitor/udp.rs:178: _ = tokio::signal::ctrl_c() => { +console/tracker-client/src/console/clients/checker/monitor/udp.rs:231: _ = tokio::signal::ctrl_c() => { + +$ git grep -nlE "Halted|HaltSignal|NestedServerTask|global_shutdown_signal|run_with_graceful_shutdown" -- . ":!docs/issues" ":!docs/pr-reviews" +docs/adrs/20260902074438_adopt_supervised_cancellation_tree_for_shutdown.md +docs/adrs/20261021184946_order_shutdown_by_event_flow_and_drain_event_listeners.md +docs/analysis/20260716-shutdown-process/README.md +docs/features/shutdown-process/README.md +docs/features/shutdown-process/legacy-api-migration.md +docs/features/shutdown-process/questions.md +docs/features/shutdown-process/task-inventory.md +docs/media/flamegraph.svg +docs/media/flamegraph_generated_without_sudo.svg +docs/research/20260716-console-shutdown-patterns/README.md + +$ git grep -nE "Halted|HaltSignal|NestedServerTask|global_shutdown_signal|run_with_graceful_shutdown|shutdown_signal_with_message|spawn_launcher|LaunchRequest" -- docs/issues/open docs/issues/drafts ":!docs/issues/open/2801*" ":!docs/issues/open/1488*" | sed 's/[[:space:]]*$//' +docs/issues/drafts/1488-si-9-improve-udp-shutdown/ISSUE.md:48:Replace the UDP server's shutdown `Halted` oneshot and OS-signal wait with a +docs/issues/drafts/1488-si-9-improve-udp-shutdown/ISSUE.md:112: shutdown `Halted` oneshot or OS-signal listener. +docs/issues/drafts/simplify-udp-server-main-loop/ISSUE.md:99:- Changes to `run_with_graceful_shutdown`. +docs/issues/open/1419-allow-multiple-integration-tests-at-main-app-level/ISSUE.md:420:server wrappers already forward the manager token to their private `Halted::Normal` channels, but +docs/issues/open/1419-allow-multiple-integration-tests-at-main-app-level/completion-plan.md:45:`CancellationToken`. Each wrapper forwards cancellation to its private `Halted::Normal` channel ``` +The last search also finds the legacy draft `docs/issues/drafts/simplify-udp-server-main-loop/ISSUE.md`, which lists +`run_with_graceful_shutdown` as out of scope for a UDP main-loop refactor. The pre-commit frontmatter validator refuses to +stage that file (it has the legacy frontmatter shape and needs a full migration), so the line stays; it describes a +removed function and is not a use of it. + +The two `ctrl_c` hits belong to the `tracker_client check` monitor, a command-line executable and not a server +library, so they stay at an executable boundary. `src/main.rs`, `src/console/profiling.rs` and the four examples +are executables. + ### Test 2: Token lifecycle owns completion -- [ ] Run deterministic component tests using injected cancellation tokens. -- [ ] Verify every component joins or deliberately aborts its owned child tasks. -- [ ] Verify no test needs an OS signal to prove component cancellation. +- [x] Deterministic component tests using injected cancellation tokens run and pass. +- [x] Every component joins or deliberately aborts its owned child tasks (the token-aware tests of each package). +- [x] No test needs an OS signal to prove component cancellation. **Evidence:** ```text -(paste focused test output) +$ cargo test --workspace +exit=0; 119 test result lines; 3947 passed, 0 failed +$ cargo check --workspace --all-targets +(no warnings) ``` ## End-to-End Evidence -- [ ] Tracker binary: SIGINT and SIGTERM produce one application-owned shutdown - sequence with no duplicate library signal handling. -- [ ] Standalone HTTP example: SIGINT and SIGTERM use the in-process stop path. -- [ ] Standalone UDP example: SIGINT and SIGTERM use the in-process stop path. -- [ ] Container/service-manager evidence uses the deadlines specified by Q4. -- [ ] Process results match the Q3 exit-code policy. +- [x] Tracker binary: SIGINT and SIGTERM produce one application-owned shutdown sequence (one + `Torrust tracker shutting down (SIGTERM|SIGINT)` line) with no duplicate library signal handling. +- [x] Standalone HTTP example (both variants): SIGINT and SIGTERM use the in-process stop path. +- [x] Standalone UDP example (both variants): SIGINT and SIGTERM use the in-process stop path. +- [x] Container/service-manager evidence uses the deadlines specified by Q4 (M5). +- [x] Process results match the Q3 exit-code policy (exit 0 for each stop). -**Evidence:** +**Evidence:** the script below (`e2e.sh`, run from the repository root as +`e2e.sh `) execs the binary in the background (so `$!` is the direct +PID), waits for readiness, sends the signal to that PID, waits at most 20 s, then records the exit status and the +listeners left for the PID. The tracker used `.tmp/2801-tracker.toml`, a reduced copy of the development template (one UDP +and one HTTP tracker, the REST API and the health-check API on the ports `28969`, `28070`, `28212` and `28313` on +`127.0.0.1`, and a temporary SQLite file; the second UDP and HTTP trackers, `[udp_tracker_server]` and +`[core.tracker_policy]` are left out, and `[health_check_api]` is added). + +```sh +#!/usr/bin/env bash +# usage: e2e.sh (run from repo root; command is exec'd so $! is the direct PID) +name=$1; sig=$2; shift 2 +log=.tmp/2801-$name-$sig.log +env -u TORRUST_TRACKER_CONFIG_TOML -u TORRUST_TRACKER_CONFIG_TOML_PATH RUST_LOG=info "$@" > "$log" 2>&1 & +pid=$! +for i in $(seq 1 100); do + if grep -qE "Listening on|Started health check API|started: " "$log" 2>/dev/null; then break; fi + sleep 0.2 +done +sleep 1 +echo "$name/$sig: PID=$pid comm=$(cat /proc/$pid/comm 2>/dev/null)" +ss -ltnup 2>/dev/null | grep "pid=$pid," | awk '{print " bound: "$1" "$5}' +kill -s "$sig" "$pid" +start=$(date +%s.%N) +for i in $(seq 1 200); do kill -0 "$pid" 2>/dev/null || break; sleep 0.1; done +if kill -0 "$pid" 2>/dev/null; then echo " STILL RUNNING after 20s"; kill -KILL "$pid"; fi +wait "$pid"; code=$? +end=$(date +%s.%N) +LC_ALL=C printf " exit=%s elapsed=%.1fs\n" "$code" "$(echo "$end - $start" | bc)" +echo " remaining listeners for pid: $(ss -ltnup 2>/dev/null | grep -c "pid=$pid,")" +echo " shutdown log lines: $(grep -ciE 'shutting down|shutdown' "$log")" +``` + +```text +tracker/INT: PID=2792986 comm=torrust-tracker + bound: udp 127.0.0.1:28969 + bound: tcp 127.0.0.1:28212 + bound: tcp 127.0.0.1:28313 + bound: tcp 127.0.0.1:28070 + exit=0 elapsed=0.1s + remaining listeners for pid: 0 + shutdown log lines: 11 +http_only_public_tracker/INT: PID=2793876 comm=http_only_pub + bound: tcp 127.0.0.1:56697 + exit=0 elapsed=0.0s + remaining listeners for pid: 0 + shutdown log lines: 1 +http_only_public_tracker_production_style/INT: PID=2794572 comm=http_only_pub + bound: tcp 127.0.0.1:36379 + exit=0 elapsed=0.0s + remaining listeners for pid: 0 + shutdown log lines: 1 +udp_only_public_tracker/INT: PID=2794645 comm=udp_only_pub + bound: udp 127.0.0.1:42783 + exit=0 elapsed=0.1s + remaining listeners for pid: 0 + shutdown log lines: 1 +udp_only_public_tracker_production_style/INT: PID=2796755 comm=udp_only_pub + bound: udp 127.0.0.1:37830 + exit=0 elapsed=0.1s + remaining listeners for pid: 0 + shutdown log lines: 1 +tracker/TERM: PID=2796853 comm=torrust-tracker + bound: udp 127.0.0.1:28969 + bound: tcp 127.0.0.1:28212 + bound: tcp 127.0.0.1:28313 + bound: tcp 127.0.0.1:28070 + exit=0 elapsed=0.1s + remaining listeners for pid: 0 + shutdown log lines: 11 +http_only_public_tracker/TERM: PID=2796969 comm=http_only_pub + bound: tcp 127.0.0.1:48169 + exit=0 elapsed=0.0s + remaining listeners for pid: 0 + shutdown log lines: 1 +http_only_public_tracker_production_style/TERM: PID=2797137 comm=http_only_pub + bound: tcp 127.0.0.1:37251 + exit=0 elapsed=0.0s + remaining listeners for pid: 0 + shutdown log lines: 1 +udp_only_public_tracker/TERM: PID=2797194 comm=udp_only_pub + bound: udp 127.0.0.1:55070 + exit=0 elapsed=0.1s + remaining listeners for pid: 0 + shutdown log lines: 1 +udp_only_public_tracker_production_style/TERM: PID=2797268 comm=udp_only_pub + bound: udp 127.0.0.1:36351 + exit=0 elapsed=0.1s + remaining listeners for pid: 0 + shutdown log lines: 1 + +``` + +The ten invocations (the script removes the two config environment variables, so the tracker reads its configuration +only from `--config-toml-path`; `target/debug` holds the artifacts of `cargo build --bin torrust-tracker` and +`cargo build -p torrust-tracker-axum-http-server -p torrust-tracker-udp-server --examples`): + +```sh +for s in INT TERM; do + e2e.sh tracker $s ./target/debug/torrust-tracker --config-toml-path .tmp/2801-tracker.toml + for ex in http_only_public_tracker http_only_public_tracker_production_style \ + udp_only_public_tracker udp_only_public_tracker_production_style; do + e2e.sh $ex $s ./target/debug/examples/$ex + done +done +``` + +The configuration file `.tmp/2801-tracker.toml`: + +```toml +[metadata] +app = "torrust-tracker" +purpose = "configuration" +schema_version = "3.0.0" + +[logging] +trace_filter = "info" +trace_style = "full" + +[core] +inactive_peer_cleanup_interval = 120 +listed = false +private = false + +[core.database] +driver = "sqlite3" +path = ".tmp/2801-sqlite3.db" + +[application.shutdown] +deadline_in_secs = 25 +http_drain_in_secs = 15 +udp_request_drain_in_secs = 5 +event_listener_drain_in_secs = 5 + +[[udp_trackers]] +bind_address = "127.0.0.1:28969" +tracker_usage_statistics = true + +[[http_trackers]] +bind_address = "127.0.0.1:28070" +tracker_usage_statistics = true + +[http_api] +bind_address = "127.0.0.1:28212" + +[http_api.access_tokens] +admin = "MyAccessToken" + +[health_check_api] +bind_address = "127.0.0.1:28313" +``` + +Tracker shutdown sequence for SIGTERM (filtered; one `shutting down` line): ```text -(paste raw logs and command output) + INFO torrust_tracker: Torrust tracker shutting down (SIGTERM) ... + INFO torrust_tracker_lib::bootstrap::jobs::manager: Job completed after cooperative cancellation job=http_api + INFO torrust_tracker_lib::bootstrap::jobs::manager: Job completed after cooperative cancellation job=health_check_api + INFO torrust_tracker: Torrust tracker successfully shutdown. ``` +Each example log shows exactly one `Received SIG...` and one `Stopped.` line. + +### M5: Container + +The image was built with `docker build --target debug --tag torrust-tracker:2801-debug --file Containerfile .`; the +in-image `cargo nextest run` ran 1778 tests, 1778 passed. An earlier build attempt failed once on +`server::contract::http::it_should_return_error_when_http_service_was_stopped_after_registration` +(`axum-health-check-api-server`), which passed in seven local runs of its package and in the rebuild: a flaky test, not +a regression (the test only reads a stopped service's port). + +The tracker is container process 1; `docker stop -t 35` follows the deadline policy of +`docs/containers.md#stopping-the-tracker` (at least `deadline_in_secs` plus 5 s): + +```text +TERM: running=true pid1=torrust-tracker + exit=0 oom=false elapsed=0.2s shutdown_lines=1 +2026-11-10T15:46:09.823733Z INFO torrust_tracker: Torrust tracker shutting down (SIGTERM) ... +2026-11-10T15:46:09.824063Z INFO torrust_tracker: Torrust tracker successfully shutdown. +INT: running=true pid1=torrust-tracker + exit=0 oom=false elapsed=0.1s shutdown_lines=1 +2026-11-10T15:46:10.801573Z INFO torrust_tracker: Torrust tracker shutting down (SIGINT) ... +2026-11-10T15:46:10.801837Z INFO torrust_tracker: Torrust tracker successfully shutdown. +``` + +Exit code 0 matches the Q3 policy; the container is not killed (`oom=false`, no `137`). + ## Summary | Check | Result | Evidence link or note | | ------------------------------- | ------- | --------------------- | -| Start gate | Pending | | -| Legacy shutdown symbols removed | Pending | | -| No library OS signals | Pending | | -| Deterministic lifecycle tests | Pending | | -| Tracker signal handling | Pending | | -| Standalone signals | Pending | | -| Deployment verification | Pending | | +| Start gate | Pass | Start-Gate Evidence | +| Legacy shutdown symbols removed | Pass | Test 1 | +| No library OS signals | Pass | Test 1 | +| Deterministic lifecycle tests | Pass | Test 2 | +| Tracker signal handling | Pass | End-to-End Evidence | +| Standalone signals | Pass | End-to-End Evidence | +| Deployment verification | Pass | M5 (container) | diff --git a/docs/pr-reviews/pr-2807-review/PR-REVIEW.md b/docs/pr-reviews/pr-2807-review/PR-REVIEW.md new file mode 100644 index 0000000000..83d33983cc --- /dev/null +++ b/docs/pr-reviews/pr-2807-review/PR-REVIEW.md @@ -0,0 +1,450 @@ +--- +semantic-links: + skill-links: + - process-pr-review + related-artifacts: + - .github/skills/dev/pr-reviews/process-pr-review/SKILL.md +--- + + + +# PR #2807 Review Audit + +Source: pull-request reviews and inline review threads for https://github.com/torrust/torrust-tracker/pull/2807. + +## Ownership + +The PR author owns this tracked audit record. Reviewers, including repository review agents, +deliver findings through GitHub and have no repository-artifact obligation. + +- Post-merge workflow approval: N/A + +## Status Values + +- Relationship: `ORIGINAL`, `RE_RAISE_OF:` +- Disposition: `FIXED`, `NO_ACTION`, `SUPERSEDED`, `FOLLOW_UP` +- Thread state: `OPEN`, `RESOLVED`, `NON_RESOLVABLE`, `SUPERSEDED`. `OPEN` applies prospectively + to audits created or updated for approved follow-up work; historical audits remain valid without + bulk migration. +- Severity: `Blocker`, `Major`, `Minor`, `Nit`, `Suggestion`; append `(inferred)` when derived + from free prose. +- Author class: `Copilot`, `Human`, `Unknown` +- Category: `link-integrity`, `formatting`, `metadata`, `testing`, `correctness`, + `documentation`, `maintainability`, `security`, `other` +- An outdated thread whose concern was fixed is `FIXED`/`RESOLVED`, even when GitHub marks the + original thread outdated after the push. For in-PR feedback, use `NO_ACTION`/`SUPERSEDED` only + for a duplicate, superseded, or no-change concern. A post-merge `NO_ACTION` requires maintainer + approval to decline the follow-up work. +- When the current identity cannot resolve a thread (`viewerCanResolve` is `false`), keep the + disposition established from the current tree and record `Thread state=OPEN`. The reviewer or PR + author resolves it; permission says nothing about whether the concern was fixed. + +## Findings + +Eight reviews: Copilot review 5845178584 (a summary with no actionable finding, so it has no row), da2ce7 review 5845212310 (round 1, eleven findings, which keep the reviewer's IDs) da2ce7 review 5845706883 (round 2, six findings) da2ce7 review 5846280739 (round 3, three findings) da2ce7 review 5846656529 (round 4, two findings) da2ce7 review 5846951116 (round 5, two findings) and da2ce7 review 5847226991 (round 6, one finding, asked by the maintainer after the five-round limit) and da2ce7 review 5848152684 (round 7, one finding, again asked by the maintainer). The round 2 `F10` re-raises `F10` and became `F17`; the other round 2 IDs (`F12` to `F16`) are the reviewer's. In round 3 the reviewer's `F17` (a re-raise of `F14`) became `F20`; its `F18` and `F19` kept their IDs. In round 4 the reviewer's `F20` and `F21` became `F21` and `F22`. In round 5 the reviewer's `F22` and `F23` became `F23` and `F24`. In round 6 the reviewer's `F24` became `F25`; in round 7 the reviewer's `F25` became `F26`. + +| Finding ID | Review finding reference | Author class | Severity | Category | Relationship | Disposition | Thread state | +| ---------- | ------------------------ | ------------ | -------- | -------- | ------------ | ----------- | ------------ | +| F1 | review-finding:pr-2807-f1 | Human | Minor | documentation | ORIGINAL | FIXED | RESOLVED | +| F2 | review-finding:pr-2807-f2 | Human | Minor | documentation | ORIGINAL | FIXED | RESOLVED | +| F3 | review-finding:pr-2807-f3 | Human | Minor | documentation | ORIGINAL | FIXED | RESOLVED | +| F4 | review-finding:pr-2807-f4 | Human | Minor | documentation | ORIGINAL | FIXED | RESOLVED | +| F5 | review-finding:pr-2807-f5 | Human | Minor | testing | ORIGINAL | FIXED | RESOLVED | +| F6 | review-finding:pr-2807-f6 | Human | Minor | documentation | ORIGINAL | FIXED | RESOLVED | +| F7 | review-finding:pr-2807-f7 | Human | Minor | documentation | ORIGINAL | FIXED | RESOLVED | +| F8 | review-finding:pr-2807-f8 | Human | Nit | maintainability | ORIGINAL | NO_ACTION | SUPERSEDED | +| F9 | review-finding:pr-2807-f9 | Human | Nit | metadata | ORIGINAL | FIXED | RESOLVED | +| F10 | review-finding:pr-2807-f10 | Human | Nit | documentation | ORIGINAL | FIXED | RESOLVED | +| F11 | review-finding:pr-2807-f11 | Human | Suggestion | testing | ORIGINAL | FIXED | RESOLVED | +| F12 | review-finding:pr-2807-f12 | Human | Minor | documentation | ORIGINAL | FIXED | RESOLVED | +| F17 | review-finding:pr-2807-f17 | Human | Nit | documentation | RE_RAISE_OF:F10 | FIXED | RESOLVED | +| F13 | review-finding:pr-2807-f13 | Human | Nit | metadata | ORIGINAL | FIXED | RESOLVED | +| F14 | review-finding:pr-2807-f14 | Human | Nit | documentation | ORIGINAL | FIXED | RESOLVED | +| F15 | review-finding:pr-2807-f15 | Human | Nit | maintainability | ORIGINAL | NO_ACTION | SUPERSEDED | +| F16 | review-finding:pr-2807-f16 | Human | Suggestion | documentation | ORIGINAL | FIXED | RESOLVED | +| F20 | review-finding:pr-2807-f20 | Human | Nit | documentation | RE_RAISE_OF:F14 | FIXED | RESOLVED | +| F18 | review-finding:pr-2807-f18 | Human | Nit | metadata | ORIGINAL | FIXED | RESOLVED | +| F19 | review-finding:pr-2807-f19 | Human | Nit | documentation | ORIGINAL | FIXED | RESOLVED | +| F21 | review-finding:pr-2807-f21 | Human | Nit | documentation | ORIGINAL | FIXED | RESOLVED | +| F22 | review-finding:pr-2807-f22 | Human | Nit | maintainability | ORIGINAL | NO_ACTION | SUPERSEDED | +| F23 | review-finding:pr-2807-f23 | Human | Nit | documentation | ORIGINAL | FIXED | RESOLVED | +| F24 | review-finding:pr-2807-f24 | Human | Nit | documentation | ORIGINAL | FIXED | RESOLVED | +| F25 | review-finding:pr-2807-f25 | Human | Nit | documentation | ORIGINAL | FIXED | RESOLVED | +| F26 | review-finding:pr-2807-f26 | Human | Nit | documentation | ORIGINAL | FIXED | RESOLVED | + +## Finding Details + +### F1 - `Started` is recorded as kept and tested, but nothing in this workspace uses or tests it + +- PR number: 2807 +- Source review ID: 5845212310 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527363973 +- Concern: The acceptance row, the criterion and the log say `Started` remains available and tested; no `.rs` file imports `torrust_server_lib::signals`. +- Solution: The acceptance row and the criterion say it remains available in `torrust-server-lib` 0.6.0 and is no longer used here, and the progress-log entry says it is no longer used or tested here. +- Current-tree verification: `git grep -n "no longer used" docs/issues/open/2801-1488-si-19-remove-legacy-shutdown-api/ISSUE.md` finds the three statements. +- Resolution reference: docs(issues): [#2801] correct the SI-19 spec and evidence after the review +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527434600 + +### F2 - T5 is DONE and names the EPIC row, but the EPIC is not changed + +- PR number: 2807 +- Source review ID: 5845212310 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527363984 +- Concern: T5 says the EPIC row is updated, yet this PR leaves row 19 as Planned. +- Solution: T5 no longer lists the row and its notes say the close-out archive step flips it, as for SI-18. +- Current-tree verification: The T5 row of the Implementation Plan was read after the edit. +- Resolution reference: docs(issues): [#2801] correct the SI-19 spec and evidence after the review +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527435128 + +### F3 - Start-gate reviewed is DONE but unchecked elsewhere, and the approval has no link + +- PR number: 2807 +- Source review ID: 5845212310 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527363993 +- Concern: The row is DONE while the criterion is open and no review has concluded; the approval cites only a chat. +- Solution: The row is IN_PROGRESS and the approval item links the merged `torrust-server-lib` PR 6 and PR 2803; the migration guide cites the spec's start gate and PR 2803. +- Current-tree verification: The row and the first evidence section were read after the edit. +- Resolution reference: docs(issues): [#2801] correct the SI-19 spec and evidence after the review +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527435687 + +### F4 - Test 1 records a paraphrase, not the command output, and miscounts the ADRs + +- PR number: 2807 +- Source review ID: 5845212310 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527364002 +- Concern: The evidence elides output, miscounts two ADRs as three and does not include `e2e.sh`. +- Solution: The evidence pastes the raw output and inlines the script. +- Current-tree verification: The commands were re-run at this head and their output pasted. +- Resolution reference: docs(issues): [#2801] correct the SI-19 spec and evidence after the review +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527436173 + +### F5 - The converted test duplicates the existing drain test + +- PR number: 2807 +- Source review ID: 5845212310 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527364008 +- Concern: The converted HTTP test repeats the arrange, act and assertion of the drain test. +- Solution: The test is deleted. +- Current-tree verification: `git grep -n "preserve_the_launcher_bind_address" packages` prints nothing. +- Resolution reference: refactor: [#2801] cover the token-aware server owner and fix the docs left by the removal +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527436734 + +### F6 - Three UdpError variants are never built and their docs describe the removed stop path + +- PR number: 2807 +- Source review ID: 5845212310 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527364026 +- Concern: The enum and `OwnedReceiveLoop` docs still describe the removed stop and join. +- Solution: The `UdpError` doc names the unused variants and says why they stay; the `OwnedReceiveLoop` doc no longer mentions joining. +- Current-tree verification: The two doc comments were read after the edit; `cargo check --workspace --all-targets` is warning-free. +- Resolution reference: refactor: [#2801] cover the token-aware server owner and fix the docs left by the removal +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527437197 + +### F7 - The module rustdoc still routes starts through removed functions + +- PR number: 2807 +- Source review ID: 5845212310 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527364033 +- Concern: The REST module doc names `ApiServer::start` and `Launcher::start`; "This additive path" has nothing left to add to. +- Solution: The module doc describes `start_with_cancellation`, and the phrase is "This path" in the four servers. +- Current-tree verification: `git grep -n "additive path" packages` prints nothing. +- Resolution reference: refactor: [#2801] cover the token-aware server owner and fix the docs left by the removal +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527437590 + +### F8 - The lock edit for axum-server lands one commit after its manifest edit + +- PR number: 2807 +- Source review ID: 5845212310 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527364042 +- Concern: The lock line arrives in the next commit, so a `--locked` build at one commit would fail. +- Solution: No change: the reviewer says a rewrite is not needed, and rewriting a reviewed branch is avoided. +- Current-tree verification: The reply states the decision. +- Resolution reference: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527438132 +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527438132 + +### F9 - The workflow status lags the work + +- PR number: 2807 +- Source review ID: 5845212310 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527364055 +- Concern: The spec-only checkpoint is unchecked and the frontmatter still says planned with no PR. +- Solution: The checkpoint is ticked and `status` and `related-pr` are updated. +- Current-tree verification: The frontmatter and the checkpoint were read after the edit. +- Resolution reference: docs(issues): [#2801] correct the SI-19 spec and evidence after the review +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527438615 + +### F10 - The workspace search excludes docs/issues + +- PR number: 2807 +- Source review ID: 5845212310 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527364062 +- Concern: The search skipped live specs, one of which names a removed function. +- Solution: The evidence also searches `docs/issues/open` and `docs/issues/drafts` and pastes the output; the line in the legacy-shape draft stays because the frontmatter validator refuses to stage that file. +- Current-tree verification: The search was re-run and its output is in the evidence. +- Resolution reference: docs(issues): [#2801] correct the SI-19 spec and evidence after the review +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527439123 + +### F11 - Port the two nested-owner abort tests to TokenAwareServerTask + +- PR number: 2807 +- Source review ID: 5845212310 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527364074 +- Concern: The removed tests were the only tests of the owner-abort contract. +- Solution: A test constructs `TokenAwareServerTask::new` and checks both children are aborted with the component. +- Current-tree verification: `cargo test -p torrust-tracker --lib manager` passes (48 passed). +- Resolution reference: refactor: [#2801] cover the token-aware server owner and fix the docs left by the removal +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527439588 + +### F12 - The live-spec block is not a runnable command, and its output drops one of the five matches + +- PR number: 2807 +- Source review ID: 5845706883 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527713351 +- Concern: The block is prose, shows four of five matches, rewrites a line and leaves a trailing space. +- Solution: The evidence pastes the real command with its full output (five lines). +- Current-tree verification: `git diff --check` prints nothing and the command prints the five lines. +- Resolution reference: docs(issues): [#2801] paste the real live-spec search and its full output +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527857390 + +### F17 - Re-raise: the criterion still says only archived history matches, but the new search finds live specs + +- PR number: 2807 +- Source review ID: 5845706883 +- Reviewer finding ID: F10 +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527713365 +- Concern: The criterion, the acceptance row and the evidence item say nothing remains outside archived history, but five live-spec lines match. +- Solution: The three places (and the M2 expectation and T5 note) now say no use remains and descriptions match in archived docs and five live-spec lines. +- Current-tree verification: `git grep -n "five lines" docs/issues/open/2801-1488-si-19-remove-legacy-shutdown-api` lists the places. +- Resolution reference: docs(issues): [#2801] say that live specs still describe the removed API +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527857932 + +### F13 - branch still names the spec branch, while related-pr names the implementation PR + +- PR number: 2807 +- Source review ID: 5845706883 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527713374 +- Concern: The frontmatter `branch` names the merged spec branch. +- Solution: `branch` is `2801-remove-legacy-shutdown-api`. +- Current-tree verification: Line 10 of the spec was read after the edit. +- Resolution reference: docs(issues): [#2801] point the spec branch at the implementation branch +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527858338 + +### F14 - Two Solutions say more than the bytes + +- PR number: 2807 +- Source review ID: 5845706883 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527713383 +- Concern: F1 and F3 Solutions and the F3 reply claimed wording and links the files do not have. +- Solution: The two Solutions and two replies now match the files. In the same sweep the statements that the maintainer published 0.6.0 were removed from the spec and the evidence, because the evidence only shows it is published (commit "docs(issues): [#2801] state only what the evidence shows about the 0.6.0 publication"). +- Current-tree verification: The Solutions, the replies and `git grep -n "maintainer published" docs/issues/open/2801-1488-si-19-remove-legacy-shutdown-api` (which prints only the progress-log entry that describes the removal, `ISSUE.md:242`) were checked. +- Resolution reference: docs(pr-reviews): [#2807] align the audit with the bytes and record the second round +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527858834 + +### F15 - Two commits each carry several independent fixes + +- PR number: 2807 +- Source review ID: 5845706883 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527713390 +- Concern: Two commits of round 1 fix several findings each. +- Solution: No change: the reviewer notes a rewrite is not needed; the fixes of round 2 are in separate commits. +- Current-tree verification: The reply states the decision. +- Resolution reference: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527859329 +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527859329 + +### F16 - Record the ten invocations so M4 can be re-run from this file + +- PR number: 2807 +- Source review ID: 5845706883 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527713414 +- Concern: The evidence does not record the ten commands or the tracker configuration. +- Solution: The evidence records the ten invocations as one loop and inlines the tracker configuration. +- Current-tree verification: The evidence was read after the edit. +- Resolution reference: docs(issues): [#2801] record the ten signal verification invocations +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4527859808 + +### F20 - Two statements of this round's sweep go further than the bytes + +- PR number: 2807 +- Source review ID: 5846280739 +- Reviewer finding ID: F17 +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4528154725 +- Concern: The F14 verification says a grep prints nothing but it prints the progress-log entry, and the F3 reply cites a merge the evidence no longer cites. +- Solution: The verification says what the grep prints; the evidence now says the `torrust-server-lib` PR is merged (commit "docs(issues): [#2801] cite the merge of the torrust-server-lib PR in the evidence"), so the F3 reply is true again. +- Current-tree verification: The grep was re-run, and the other grep commands named in this audit were re-run and print what their rows say. +- Resolution reference: docs(pr-reviews): [#2807] correct the audit verification of the 0.6.0 sweep +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4528211310 + +### F18 - The 16:54 stamp matches no commit or forge time + +- PR number: 2807 +- Source review ID: 5846280739 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4528154746 +- Concern: The second-round log entry of the spec is stamped 16:54, but its commit was made at 16:55. +- Solution: The entry is stamped 16:55. +- Current-tree verification: `git log --format=%cI` of the commit was compared with the stamp. +- Resolution reference: docs(issues): [#2801] stamp the second round log entry at its commit minute +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4528211789 + +### F19 - The inlined configuration is not the copy of the development template the line describes + +- PR number: 2807 +- Source review ID: 5846280739 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4528154758 +- Concern: The line says a copy of the development template, but the inlined file leaves out sections and adds one. +- Solution: The line describes a reduced copy and names what was left out and added. +- Current-tree verification: The line and the inlined file were compared. +- Resolution reference: docs(issues): [#2801] describe the verification configuration as a reduced copy +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4528212187 + +### F21 - The PR description still says the converted HTTP test runs on the token path + +- PR number: 2807 +- Source review ID: 5846656529 +- Reviewer finding ID: F20 +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4528446814 +- Concern: The description says a deleted test runs on the token path. +- Solution: The description says the token-path drain test asserts that the HTTP server keeps its bind address; its Verification section says the 3947-test run was made before the review rounds and what changed since. +- Current-tree verification: `gh pr view 2807 --json body` was read after the edit. +- Resolution reference: https://github.com/torrust/torrust-tracker/pull/2807#issuecomment-6774847290 +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4528458114 + +### F22 - The commit that adds this entry is named for the restamp only + +- PR number: 2807 +- Source review ID: 5846656529 +- Reviewer finding ID: F21 +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4528446826 +- Concern: One commit restamps an entry, adds a log entry and moves the stamp, under a subject that names only the restamp. +- Solution: No change: the reviewer notes no rewrite is needed; as for F15, the branch is not rewritten. The consolidated response https://github.com/torrust/torrust-tracker/pull/2807#issuecomment-6774847290 lists this finding and its disposition and cites the reply. +- Current-tree verification: The reply states the decision. +- Resolution reference: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4528458638 +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4528458638 + +### F23 - The response this row cites calls round 4 the third review round + +- PR number: 2807 +- Source review ID: 5846951116 +- Reviewer finding ID: F22 +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4528664835 +- Concern: The PR conversation response that is the resolution reference of F21 opens "Third review round" for the review this audit calls round 4. +- Solution: The response calls review 5846656529 "Round 4" and opens "Consolidated response for review rounds 4 and 5 of da2ce7" (it opened "Fourth review round" until the edit of F25). +- Current-tree verification: The comment was read after the edit (`gh api repos/torrust/torrust-tracker/issues/comments/6774847290`). +- Resolution reference: https://github.com/torrust/torrust-tracker/pull/2807#issuecomment-6774847290 +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4528688756 + +### F24 - The description cites a package-test run that no record of the PR names + +- PR number: 2807 +- Source review ID: 5846951116 +- Reviewer finding ID: F23 +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4528664840 +- Concern: The PR description says package tests passed again at the second round head (245 passed) without a source. +- Solution: The description names the source, the run recorded in review 5845706883, and the conversation response states the edit. +- Current-tree verification: `gh pr view 2807 --json body` was read after the edit. +- Resolution reference: https://github.com/torrust/torrust-tracker/pull/2807#issuecomment-6774847290 +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4528689284 + +### F25 - The response now spans two review rounds without the resolution reference of the round-4 F21 + +- PR number: 2807 +- Source review ID: 5847226991 +- Reviewer finding ID: F24 +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4528874414 +- Concern: The consolidated PR response covers two rounds but gives dispositions only as prose and does not cite the reply of the round 4 F21 (audit F22). +- Solution: The response lists the disposition and resolution reference of each of the four findings and cites that reply; the F22 row cites the response. +- Current-tree verification: The response was read after the edit (`gh api repos/torrust/torrust-tracker/issues/comments/6774847290`). +- Resolution reference: https://github.com/torrust/torrust-tracker/pull/2807#issuecomment-6774847290 +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4529400162 + +### F26 - This Solution and the response both say the response opens "Fourth review round", which it no longer does + +- PR number: 2807 +- Source review ID: 5848152684 +- Reviewer finding ID: F25 +- Source URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4529587172 +- Concern: After the consolidating edit, the response no longer opens "Fourth review round", but its Round 5 sentence and the F23 Solution still say it does. +- Solution: The Round 5 sentence of the response, the F23 Solution and the F22 reply now say what the response says for round 4: it calls review 5846656529 "Round 4" and opens "Consolidated response for review rounds 4 and 5 of da2ce7". +- Current-tree verification: The response, the F22 reply and the PR description were read after the edits (`gh pr view 2807 --json body` has no "Fourth review round"), and `git grep -n "Fourth review round" docs` finds only the quotations of the phrase in this row and in the F23 Solution. +- Resolution reference: https://github.com/torrust/torrust-tracker/pull/2807#issuecomment-6774847290 +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2807#discussion_r4530701124 + +## Processing Log + +- 2026-11-10 16:10 UTC - Copilot review received (16:10:42 UTC) (no actionable finding). +- 2026-11-10 16:12 UTC - da2ce7 review received (16:12:39 UTC) (approval with eleven findings, `F1` to `F11`). +- 2026-11-10 16:19 UTC - Replies posted on all eleven threads (16:18:48 to 16:19:14 UTC); the audit started in the commit that carries this entry. +- 2026-11-10 16:43 UTC - da2ce7 review received (round 2: approval of the pushed head, six findings, `F12` to `F17` here; submitted 16:43:09 UTC). +- 2026-11-10 16:56 UTC - Replies posted on the six threads (16:55:52 to 16:56:05 UTC) and two earlier replies edited; the audit corrected in the commit that carries this entry. +- 2026-11-10 17:22 UTC - da2ce7 review received (round 3: approval of the pushed head, three nits, `F18` to `F20` here; submitted 17:22:39 UTC). +- 2026-11-10 17:27 UTC - Replies posted on the three threads (17:27:51 to 17:27:56 UTC); the audit corrected in the commit that carries this entry. +- 2026-11-10 17:49 UTC - da2ce7 review received (round 4: approval of the pushed head, two nits, `F21` and `F22` here; submitted 17:49:19 UTC). +- 2026-11-10 17:50 UTC - The PR description edited, the conversation response posted and the two replies posted (17:50:22 and 17:50:24 UTC); the audit corrected in the commit that carries this entry. +- 2026-11-10 18:09 UTC - da2ce7 review received (round 5: approval of the pushed head, two nits, `F23` and `F24` here; submitted 18:09:23 UTC). +- 2026-11-10 18:11 UTC - The conversation response and the PR description edited and the two replies posted (18:11:30 and 18:11:32 UTC); the audit corrected in the commit that carries this entry. +- 2026-11-10 18:28 UTC - da2ce7 review received (round 6: approval of the pushed head, one nit, `F25` here; submitted 18:28:45 UTC). The five-round limit was reached, so the maintainer was asked and chose to fix it. +- 2026-11-10 19:18 UTC - The conversation response edited (19:18:01 UTC) and the reply posted (19:18:03 UTC); the audit corrected in the commit that carries this entry. +- 2026-11-10 19:35 UTC - da2ce7 review received (round 7: approval of the pushed head, one nit, `F26` here; submitted 19:35:49 UTC). The maintainer chose to fix it. +- 2026-11-10 21:22 UTC - The conversation response and the F22 reply edited (21:22:44 UTC) and the reply posted (21:22:47 UTC); the audit corrected in the commit that carries this entry. + +## Completion Rules + +- Re-derive the reply claim against the current tree before replying or resolving a thread. +- Reply on every resolvable thread before resolving it. +- For an outdated thread whose concern was fixed, record `Disposition=FIXED` and + `Thread state=RESOLVED`, even if GitHub marks the thread outdated after the push. For a + duplicate, superseded, or no-change in-PR thread, reply exactly + `Superseded by : .`, record `Disposition=NO_ACTION` and + `Thread state=SUPERSEDED`, then resolve it. A post-merge `NO_ACTION` requires maintainer + approval to decline the follow-up work. When the current identity cannot resolve a thread + (`viewerCanResolve` is `false`), still reply, keep the disposition established from the current + tree, and record `Thread state=OPEN`; the reviewer or PR author resolves it. +- A consolidated PR conversation response may cover multiple review rounds only when it names + every review ID and every finding ID with its disposition and resolution reference. Record its + durable URL in each related row. +- Cite a fix by its unique Conventional Commit subject or durable reply URL, never by a branch SHA + that can change after a rebase. +- Refresh review threads using GraphQL and confirm that no unresolved actionable thread remains. diff --git a/packages/axum-health-check-api-server/Cargo.toml b/packages/axum-health-check-api-server/Cargo.toml index 70980f04b2..364f7f075c 100644 --- a/packages/axum-health-check-api-server/Cargo.toml +++ b/packages/axum-health-check-api-server/Cargo.toml @@ -33,7 +33,7 @@ thiserror = "2" tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } tokio-util = "0.7.15" torrust-tracker-axum-server = { version = "0.1.0", path = "../axum-server" } -torrust-server-lib = "0.5.0" +torrust-server-lib = "0.6.0" torrust-tracker-primitives = { version = "3.0.0", path = "../primitives" } torrust-tracker-configuration = { version = "3.0.0", path = "../configuration", optional = true } torrust-net-primitives = "0.1.0" diff --git a/packages/axum-health-check-api-server/src/server.rs b/packages/axum-health-check-api-server/src/server.rs index 380a928915..a9eec032cf 100644 --- a/packages/axum-health-check-api-server/src/server.rs +++ b/packages/axum-health-check-api-server/src/server.rs @@ -10,25 +10,14 @@ 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 tokio::task::JoinHandle; use tokio_util::sync::CancellationToken; use torrust_net_primitives::service_binding::{Protocol, ServiceBinding}; use torrust_server_lib::logging::{Latency, STARTED_ON}; use torrust_server_lib::registar::{Registar, RegistrationError, ServiceRegistration}; -#[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" -)] -use torrust_server_lib::signals::{Halted, Started}; -#[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" -)] -use torrust_tracker_axum_server::signals::{GracefulShutdownOutcome, graceful_shutdown, graceful_shutdown_on_cancellation}; +use torrust_tracker_axum_server::signals::{GracefulShutdownOutcome, graceful_shutdown_on_cancellation}; use torrust_tracker_primitives::{Readiness, RuntimeServiceMetadata}; use tower_http::LatencyUnit; use tower_http::classify::ServerErrorsFailureClass; @@ -36,7 +25,7 @@ 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 tracing::{Level, Span, instrument}; +use tracing::{Level, Span}; use crate::HEALTH_CHECK_API_LOG_TARGET; use crate::handlers::{HealthCheckState, health_check_handler}; @@ -57,8 +46,7 @@ pub enum Error { /// A token-aware health-check runtime and its owned drain controller. /// -/// The caller must retain and join both handles. [`RunningServer`] remains the -/// compatibility path for consumers using [`Halted`]. +/// The caller must retain and join both handles. pub struct CancellationRunning { pub local_addr: SocketAddr, /// The binding this server registered in the `registar`. A caller that @@ -69,104 +57,12 @@ pub struct CancellationRunning { pub shutdown_controller: JoinHandle, } -/// A health-check server's runtime future and its graceful-shutdown controller. -/// -/// The caller owns both tasks. It must join them during normal shutdown or -/// abort them when its enclosing component is aborted. -#[deprecated( - since = "0.2.0", - note = "use `CancellationRunning` from `start_with_cancellation`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" -)] -pub struct RunningServer { - pub running: F, - pub shutdown_controller: JoinHandle<()>, -} - -/// Starts Health Check API server. -/// -/// # Errors -/// -/// Returns an error if the listener cannot bind or be configured, or if the -/// startup receiver is dropped before the listener is reported. -#[instrument(skip(bind_to, tx, rx_halt, registar))] -#[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" -)] -/// -/// The deprecation is part of the contract until SI-19 removes this item. Using it without an allowance fails -/// under `deny(deprecated)`: -/// -/// ``` -/// use torrust_tracker_axum_health_check_api_server::server::start; -/// let _ = start; -/// ``` -/// -/// ```compile_fail -/// #![deny(deprecated)] -/// use torrust_tracker_axum_health_check_api_server::server::start; -/// let _ = start; -/// ``` -#[deprecated( - since = "0.2.0", - note = "use `start_with_cancellation` with a `CancellationToken`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" -)] -pub fn start( - bind_to: SocketAddr, - tx: Sender, - rx_halt: Receiver, - registar: Registar, -) -> Result> + Send>, std::io::Error> { - // The signal-based path has no application lifecycle: it is always ready. - let router = router(registar, Readiness::default()); - - let socket = std::net::TcpListener::bind(bind_to)?; - socket.set_nonblocking(true)?; - let address = socket.local_addr()?; - 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, address).map_err(std::io::Error::other)?; - - let handle = Handle::new(); - - tracing::debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting service with graceful shutdown in a spawned task ..."); - - let shutdown_controller = 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)? - .handle(handle) - .serve(router.into_make_service_with_connect_info::()); - - if tx - .send(Started { - service_binding, - address, - }) - .is_err() - { - shutdown_controller.abort(); - return Err(std::io::Error::new( - std::io::ErrorKind::BrokenPipe, - "health check startup receiver was dropped", - )); - } - - Ok(RunningServer { - running, - shutdown_controller, - }) -} - /// Starts the Health Check API using an injected cancellation token. /// /// `readiness` is read on every `/health_check` request: while it is not ready the endpoint /// answers `503 Service Unavailable` without probing any registered service. /// -/// This additive path does not subscribe to operating-system signals. It +/// This path does not subscribe to operating-system signals. It /// registers the service and, if registration fails, cancels /// `cancellation_token`, stops both children, and releases the listener before /// returning. Otherwise the caller owns the returned runtime task and drain @@ -354,40 +250,6 @@ mod tests { } } - /// The deprecated `Halted`-based `start` must keep working until SI-19 removes it. - #[tokio::test] - #[allow( - deprecated, - reason = "proves the deprecated legacy `start` still compiles and works until SI-19" - )] - async fn it_should_stop_the_legacy_server_when_a_normal_halt_is_sent() { - use torrust_server_lib::signals::{Halted, Started}; - - // Arrange - let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); - let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); - let running = crate::server::start(any_available_port(), tx_start, rx_halt, Registar::default()) - .expect("the legacy health check API should start"); - let server = tokio::spawn(running.running); - rx_start.await.expect("the legacy start should report the bound address"); - - // Act - tx_halt - .send(Halted::Normal) - .expect("the legacy halt receiver should be alive"); - - // Assert - tokio::time::timeout(TEST_COMPLETION_TIMEOUT, running.shutdown_controller) - .await - .expect("the legacy shutdown controller should finish") - .expect("the legacy shutdown controller should not panic"); - tokio::time::timeout(TEST_COMPLETION_TIMEOUT, server) - .await - .expect("the legacy server should stop after the halt") - .expect("the legacy server task should not panic") - .expect("the legacy server should stop without an I/O error"); - } - #[tokio::test] async fn it_should_register_the_token_aware_health_check_api_service() { // Arrange diff --git a/packages/axum-http-server/Cargo.toml b/packages/axum-http-server/Cargo.toml index 63ba997ca7..de5890729a 100644 --- a/packages/axum-http-server/Cargo.toml +++ b/packages/axum-http-server/Cargo.toml @@ -38,7 +38,7 @@ serde = { version = "1", features = [ "derive" ] } tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } tokio-util = "0.7.15" torrust-tracker-axum-server = { version = "0.1.0", path = "../axum-server" } -torrust-server-lib = "0.5.0" +torrust-server-lib = "0.6.0" torrust-clock = { version = "3.0.0", optional = true } torrust-tracker-configuration = { version = "3.0.0", path = "../configuration" } torrust-net-primitives = "0.1.0" diff --git a/packages/axum-http-server/src/server.rs b/packages/axum-http-server/src/server.rs index 7027d5be49..fc40a59b41 100644 --- a/packages/axum-http-server/src/server.rs +++ b/packages/axum-http-server/src/server.rs @@ -8,7 +8,6 @@ use axum_server::tls_rustls::RustlsConfig; use derive_more::Constructor; use futures::future::BoxFuture; use socket2::{Domain, Socket, Type}; -use tokio::sync::oneshot::{Receiver, Sender}; use tokio::task::JoinHandle; use tokio_util::sync::CancellationToken; use torrust_net_primitives::service_binding::{Protocol, ServiceBinding}; @@ -16,20 +15,10 @@ use torrust_server_lib::logging::STARTED_ON; use torrust_server_lib::registar::{ FnSpawnServiceHeathCheck, ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm, }; -#[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" -)] -use torrust_server_lib::signals::{Halted, Started}; use torrust_tracker_axum_server::custom_axum_server::{self, TimeoutAcceptor}; -#[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" -)] -use torrust_tracker_axum_server::signals::{GracefulShutdownOutcome, graceful_shutdown, graceful_shutdown_on_cancellation}; +use torrust_tracker_axum_server::signals::{GracefulShutdownOutcome, graceful_shutdown_on_cancellation}; use torrust_tracker_http_core::container::HttpTrackerCoreContainer; use torrust_tracker_primitives::RuntimeServiceMetadata; -use tracing::instrument; use super::v1::routes::router; use crate::HTTP_TRACKER_LOG_TARGET; @@ -161,51 +150,6 @@ impl Launcher { })) } } - - #[instrument(skip(self, http_tracker_container, tx_start, rx_halt))] - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - fn start( - &self, - http_tracker_container: &Arc, - tx_start: Sender, - rx_halt: Receiver, - ) -> Result, Error> { - let socket = Self::create_tcp_listener(self.bind_to, self.ipv6_v6only).map_err(|source| Error::Bind { source })?; - let address = socket.local_addr().map_err(|source| Error::Listener { source })?; - - 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).map_err(|error| Error::Listener { - source: std::io::Error::other(error), - })?; - - tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{address}"); - - let running = self.server_future(socket, handle, http_tracker_container, &service_binding)?; - - tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", address); - - tx_start - .send(Started { - service_binding, - address, - }) - .map_err(|_| Error::StartupNotificationDropped)?; - - Ok(running) - } } /// A HTTP server instance controller with no HTTP instance running. @@ -215,21 +159,6 @@ impl Launcher { )] pub type StoppedHttpServer = HttpServer; -/// A HTTP server instance controller with a running HTTP instance. -#[allow( - clippy::module_name_repetitions, - reason = "type alias distinguishes the HTTP server running state" -)] -#[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" -)] -#[deprecated( - since = "0.1.0", - note = "use `HttpServer::start_with_cancellation` and keep the returned `CancellationRunning`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" -)] -pub type RunningHttpServer = HttpServer; - /// A HTTP server instance controller. /// /// It's responsible for: @@ -259,30 +188,9 @@ pub struct Stopped { launcher: Launcher, } -/// A running HTTP server state. -#[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" -)] -#[deprecated( - since = "0.1.0", - note = "use `CancellationRunning` from `start_with_cancellation` and cancel the injected `CancellationToken`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" -)] -pub struct Running { - /// The address where the server is bound. - pub binding: SocketAddr, - #[deprecated( - since = "0.1.0", - note = "cancel the injected `CancellationToken` instead of sending `Halted`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" - )] - pub halt_task: tokio::sync::oneshot::Sender, - pub task: tokio::task::JoinHandle, -} - /// A token-aware HTTP tracker runtime and its owned drain controller. /// -/// The caller must retain and join both handles. The existing [`Running`] state -/// remains the compatibility path for consumers using [`Halted`]. +/// The caller must retain and join both handles. pub struct CancellationRunning { pub binding: SocketAddr, pub task: JoinHandle, @@ -298,55 +206,9 @@ impl HttpServer { } } - /// 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. - /// - #[instrument( - skip(self, http_tracker_container, form, metadata), - fields( - service_role = metadata.service_role().as_str(), - instance_index = metadata.configuration_instance_id().instance_index(), - ) - )] - /// - /// The deprecation is part of the contract until SI-19 removes this item. Using it without an allowance fails - /// under `deny(deprecated)`: - /// - /// ``` - /// use torrust_tracker_axum_http_server::server::{HttpServer, Stopped}; - /// let _ = HttpServer::::start; - /// ``` - /// - /// ```compile_fail - /// #![deny(deprecated)] - /// use torrust_tracker_axum_http_server::server::{HttpServer, Stopped}; - /// let _ = HttpServer::::start; - /// ``` - #[deprecated( - since = "0.1.0", - note = "use `HttpServer::start_with_cancellation` with a `CancellationToken`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" - )] - #[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" - )] - pub async fn start( - self, - http_tracker_container: Arc, - form: ServiceRegistrationForm, - metadata: RuntimeServiceMetadata, - ) -> Result, Error> { - self.start_with_health_check(http_tracker_container, form, metadata, check_fn) - .await - } - /// Starts the HTTP tracker using an injected cancellation token. /// - /// This additive path does not subscribe to operating-system signals. Its + /// This path does not subscribe to operating-system signals. Its /// caller owns the returned runtime task and drain controller. /// /// # Errors @@ -364,76 +226,9 @@ impl HttpServer { .await } - /// Starts the server and registers the supplied health-check callback. - /// - /// The application uses [`check_fn`]. This explicit callback seam lets - /// integration tests use a client that trusts their test certificate - /// without altering production certificate validation. - /// - /// # Errors - /// - /// Returns an error if no `SocketAddr` is returned after launching the - /// server. - /// - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - #[deprecated( - since = "0.1.0", - note = "use `HttpServer::start_with_cancellation_and_health_check` with a `CancellationToken`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" - )] - pub async fn start_with_health_check( - self, - http_tracker_container: Arc, - form: ServiceRegistrationForm, - metadata: RuntimeServiceMetadata, - health_check: FnSpawnServiceHeathCheck, - ) -> 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 server = launcher.start(&http_tracker_container, tx_start, rx_halt)?; - let task = tokio::spawn(async move { - server.await; - launcher - }); - - let started = rx_start.await.map_err(|source| Error::StartupNotification { source })?; - - let service_binding = started.service_binding; - let binding = started.address; - - if let Some(public_url) = metadata.public_url() { - tracing::info!(service_binding = %service_binding, public_url = %public_url, "Started HTTP tracker"); - } else { - tracing::info!(service_binding = %service_binding, "Started HTTP tracker"); - } - - if let Err(source) = form - .register(ServiceRegistration::new(service_binding, metadata, Some(health_check))) - .await - { - let _ = tx_halt.send(Halted::Normal); - drop(task.await); - return Err(Error::Registration { source }); - } - - Ok(HttpServer { - state: Running { - binding, - halt_task: tx_halt, - task, - }, - }) - } - /// Starts the HTTP tracker using an injected cancellation token and /// registers the supplied health-check callback. /// - /// This is the token-aware counterpart of [`Self::start_with_health_check`]. /// The application uses [`check_fn`] through [`Self::start_with_cancellation`]; /// this seam lets integration tests use a client that trusts their test /// certificate. It does not subscribe to operating-system signals; the caller @@ -525,40 +320,6 @@ fn start_token_aware_runtime( )) } -#[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" -)] -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. - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - #[deprecated( - since = "0.1.0", - note = "cancel the `CancellationToken` passed to `start_with_cancellation` and join `CancellationRunning::task` and `shutdown_controller`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" - )] - pub async fn stop(self) -> Result, Error> { - self.state.halt_task.send(Halted::Normal).map_err(|_| Error::Stop { - message: "task killer channel was closed".to_string(), - })?; - - let launcher = self.state.task.await.map_err(|error| Error::Stop { - message: error.to_string(), - })?; - - Ok(HttpServer { - state: Stopped { launcher }, - }) - } -} - /// Checks the Health by connecting to the HTTP tracker endpoint. /// /// # Errors @@ -892,27 +653,6 @@ mod tests { } } - #[tokio::test] - #[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" - )] - async fn it_should_preserve_the_launcher_bind_address_after_starting_and_stopping() { - // Arrange - let scenario = ServerStartWithAvailableHttpBinding::new(); - let http_tracker_container = scenario.container().await; - - // Act - let started = HttpServer::new(scenario.launcher().await) - .start(http_tracker_container, scenario.registration_form(), scenario.metadata()) - .await - .expect("it should start the server"); - let stopped = started.stop().await.expect("it should stop the server"); - - // Assert - assert_eq!(stopped.state.launcher.bind_to, scenario.bind_to); - } - #[tokio::test] async fn it_should_drain_the_token_aware_http_server_when_its_cancellation_token_is_cancelled() { // Arrange @@ -1067,33 +807,6 @@ mod tests { TcpListener::bind(scenario.bind_to).expect("HTTP listener should be released after token-aware registration failure"); } - #[tokio::test] - #[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" - )] - async fn it_should_release_the_listener_and_preserve_the_duplicate_binding_error_when_registration_fails() { - // Arrange - let scenario = ServerStartWithDuplicateRegistration::new().await; - let http_tracker_container = scenario.container().await; - - // Act - let result = HttpServer::new(scenario.launcher()) - .start(http_tracker_container, scenario.registration_form(), scenario.metadata()) - .await; - - // Assert - let binding = match result { - Err(Error::Registration { - source: RegistrationError::DuplicateBinding(binding), - }) => binding, - Err(error) => panic!("HTTP starter should retain the registration failure source: {error}"), - Ok(_) => panic!("duplicate registration should fail"), - }; - assert_eq!(binding.bind_address(), scenario.bind_to); - TcpListener::bind(scenario.bind_to).expect("HTTP listener should be released after registration failure"); - } - /// Serves a canned HTTP response to one connection on a local port, then stops and returns its address. fn serve_status(status_line: &'static str) -> SocketAddr { let listener = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind a local test server"); diff --git a/packages/axum-rest-api-server/Cargo.toml b/packages/axum-rest-api-server/Cargo.toml index d291685afe..d5871c23f8 100644 --- a/packages/axum-rest-api-server/Cargo.toml +++ b/packages/axum-rest-api-server/Cargo.toml @@ -54,7 +54,7 @@ torrust-tracker-rest-api-client = { version = "0.1.0", path = "../rest-api-clien torrust-tracker-rest-api-application = { version = "0.1.0", path = "../rest-api-application" } torrust-tracker-rest-api-protocol = { version = "0.1.0", path = "../rest-api-protocol" } torrust-tracker-rest-api-runtime-adapter = { version = "0.1.0", path = "../rest-api-runtime-adapter" } -torrust-server-lib = "0.5.0" +torrust-server-lib = "0.6.0" torrust-clock = { version = "3.0.0", optional = true } torrust-tracker-configuration = { version = "3.0.0", path = "../configuration" } torrust-metrics = "0.2.0" diff --git a/packages/axum-rest-api-server/src/server.rs b/packages/axum-rest-api-server/src/server.rs index 0bde9ecf7d..b691769736 100644 --- a/packages/axum-rest-api-server/src/server.rs +++ b/packages/axum-rest-api-server/src/server.rs @@ -1,28 +1,20 @@ //! Logic to run the HTTP API server. //! -//! It contains two main structs: `ApiServer` and `Launcher`, -//! and two main functions: `start` and `start_tls`. +//! It contains two main structs: `ApiServer` and `Launcher`. //! //! The `ApiServer` struct is responsible for: -//! - Starting and stopping the server. +//! - Starting the server with an injected `CancellationToken`. //! - 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. +//! `ApiServer::start_with_cancellation` starts the server and returns a +//! `CancellationRunning`, whose `task` and `shutdown_controller` the caller +//! owns and joins after cancelling the token. +//! +//! The `Launcher` struct holds the bind address, the optional TLS +//! configuration and the drain timeout. +//! +//! The application starts the server through `start_with_cancellation`. Tests +//! use the same path and start and stop the server multiple times. use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; @@ -33,27 +25,17 @@ use derive_more::Constructor; use derive_more::derive::Display; use futures::future::BoxFuture; use thiserror::Error; -use tokio::sync::oneshot::{Receiver, Sender}; use tokio::task::JoinHandle; use tokio_util::sync::CancellationToken; use torrust_net_primitives::service_binding::{Protocol, ServiceBinding}; use torrust_server_lib::logging::STARTED_ON; use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; -#[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" -)] -use torrust_server_lib::signals::{Halted, Started}; use torrust_tracker_axum_server::custom_axum_server::{self, TimeoutAcceptor}; -#[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" -)] -use torrust_tracker_axum_server::signals::{GracefulShutdownOutcome, graceful_shutdown, graceful_shutdown_on_cancellation}; +use torrust_tracker_axum_server::signals::{GracefulShutdownOutcome, graceful_shutdown_on_cancellation}; use torrust_tracker_configuration::v3_0_0::tracker_api::AccessTokens; use torrust_tracker_primitives::RuntimeServiceMetadata; use torrust_tracker_rest_api_runtime_adapter::v1::container::TrackerHttpApiCoreContainer; -use tracing::{Level, instrument}; +use tracing::instrument; use super::routes::router; use crate::API_LOG_TARGET; @@ -97,21 +79,6 @@ pub struct RuntimeError { )] pub type StoppedApiServer = ApiServer; -/// An alias for the `ApiServer` struct with the `Running` state. -#[allow( - clippy::module_name_repetitions, - reason = "type alias distinguishes the REST API server running state" -)] -#[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" -)] -#[deprecated( - since = "0.1.0", - note = "use `ApiServer::start_with_cancellation` and keep the returned `CancellationRunning`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" -)] -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. /// @@ -136,64 +103,15 @@ pub struct Stopped { launcher: Launcher, } -/// The `Running` state of the `ApiServer` struct. -#[derive(Debug, Display)] -#[display("Running (with local address): {local_addr}")] -#[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" -)] -#[deprecated( - since = "0.1.0", - note = "use `CancellationRunning` from `ApiServer::start_with_cancellation` and cancel the injected `CancellationToken`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" -)] -pub struct Running { - pub local_addr: SocketAddr, - #[deprecated( - since = "0.1.0", - note = "cancel the injected `CancellationToken` instead of sending `Halted`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" - )] - pub halt_task: tokio::sync::oneshot::Sender, - pub task: tokio::task::JoinHandle, -} - /// A token-aware REST API runtime and its owned drain controller. /// -/// The caller must retain and join both handles. The existing [`Running`] state -/// remains the compatibility path for consumers using [`Halted`]. +/// The caller must retain and join both handles. pub struct CancellationRunning { pub local_addr: SocketAddr, pub task: JoinHandle>, pub shutdown_controller: JoinHandle, } -#[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" -)] -impl Running { - #[must_use] - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - #[deprecated( - since = "0.1.0", - note = "use `ApiServer::start_with_cancellation`, which returns `CancellationRunning`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" - )] - pub const 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 const fn new(launcher: Launcher) -> Self { @@ -202,87 +120,9 @@ impl ApiServer { } } - /// Starts the API server with the given configuration. - /// - /// # Errors - /// - /// It would return an error if no `SocketAddr` is returned after launching the server. - /// - #[instrument( - skip(self, http_api_container, form, metadata, access_tokens), - fields( - service_role = metadata.service_role().as_str(), - instance_index = metadata.configuration_instance_id().instance_index(), - ), - err, - ret(Display, level = Level::INFO) - )] - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - /// - /// The deprecation is part of the contract until SI-19 removes this item. Using it without an allowance fails - /// under `deny(deprecated)`: - /// - /// ``` - /// use torrust_tracker_axum_rest_api_server::server::{ApiServer, Stopped}; - /// let _ = ApiServer::::start; - /// ``` - /// - /// ```compile_fail - /// #![deny(deprecated)] - /// use torrust_tracker_axum_rest_api_server::server::{ApiServer, Stopped}; - /// let _ = ApiServer::::start; - /// ``` - #[deprecated( - since = "0.1.0", - note = "use `ApiServer::start_with_cancellation` with a `CancellationToken`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" - )] - pub async fn start( - self, - http_api_container: Arc, - form: ServiceRegistrationForm, - metadata: RuntimeServiceMetadata, - 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 running = launcher.start(&http_api_container, access_tokens, tx_start, rx_halt)?; - let task = tokio::spawn(async move { - running.await; - launcher - }); - - let started = rx_start.await.map_err(|source| Error::StartupNotification { source })?; - if let Some(public_url) = metadata.public_url() { - tracing::info!(target: API_LOG_TARGET, service_binding = %started.service_binding, public_url = %public_url, "Started tracker API"); - } else { - tracing::info!(target: API_LOG_TARGET, service_binding = %started.service_binding, "Started tracker API"); - } - - if let Err(source) = form - .register(ServiceRegistration::new(started.service_binding, metadata, Some(check_fn))) - .await - { - let _ = tx_halt.send(Halted::Normal); - drop(task.await); - return Err(Error::Registration { source }); - } - - let api_server = ApiServer { - state: Running::new(started.address, tx_halt, task), - }; - - Ok(api_server) - } - /// Starts the REST API using an injected cancellation token. /// - /// This additive path does not subscribe to operating-system signals. Its + /// This path does not subscribe to operating-system signals. Its /// caller owns the returned runtime task and drain controller. /// /// # Errors @@ -408,40 +248,6 @@ fn start_token_aware_runtime( )) } -#[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" -)] -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))] - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - #[deprecated( - since = "0.1.0", - note = "cancel the `CancellationToken` passed to `start_with_cancellation` and join `CancellationRunning::task` and `shutdown_controller`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" - )] - pub async fn stop(self) -> Result, Error> { - self.state.halt_task.send(Halted::Normal).map_err(|_| Error::Stop { - message: "task killer channel was closed".to_string(), - })?; - - let launcher = self.state.task.await.map_err(|error| Error::Stop { - message: error.to_string(), - })?; - - Ok(ApiServer { - state: Stopped { launcher }, - }) - } -} - /// Checks the Health by connecting to the API service endpoint. /// /// # Errors @@ -509,97 +315,6 @@ impl std::fmt::Display for 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. - /// - /// # Errors - /// - /// Returns an error when the listener cannot bind or be configured. - #[instrument(skip(self, http_api_container, access_tokens, tx_start, rx_halt))] - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - #[deprecated( - since = "0.1.0", - note = "use the token-aware path through `ApiServer::start_with_cancellation`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" - )] - pub fn start( - &self, - http_api_container: &Arc, - access_tokens: Arc, - tx_start: Sender, - rx_halt: Receiver, - ) -> Result, Error> { - let socket = std::net::TcpListener::bind(self.bind_to).map_err(|source| Error::Bind { source })?; - socket.set_nonblocking(true).map_err(|source| Error::Listener { source })?; - let address = socket.local_addr().map_err(|source| Error::Listener { source })?; - - 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).map_err(|error| Error::Listener { - source: std::io::Error::other(error), - })?; - - let router = router(http_api_container, access_tokens, &service_binding); - - tracing::info!(target: API_LOG_TARGET, "Starting on: {protocol}://{address}"); - - let running: BoxFuture<'static, ()> = if let Some(tls) = tls { - let server = - custom_axum_server::from_tcp_rustls_with_timeouts(socket, tls).map_err(|source| Error::Listener { source })?; - Box::pin(async move { - if let Err(error) = server - .handle(handle) - // The TimeoutAcceptor is commented because TLS 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 - { - tracing::error!(%error, "Tracker API TLS server stopped with an error"); - } - }) - } else { - let server = custom_axum_server::from_tcp_with_timeouts(socket).map_err(|source| Error::Listener { source })?; - Box::pin(async move { - if let Err(error) = server - .handle(handle) - .acceptor(TimeoutAcceptor) - .serve(router.into_make_service_with_connect_info::()) - .await - { - tracing::error!(%error, "Tracker API server stopped with an error"); - } - }) - }; - - tracing::info!(target: API_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", address); - - tx_start - .send(Started { - service_binding, - address, - }) - .map_err(|_| Error::StartupNotificationDropped)?; - - Ok(running) - } -} - #[cfg(test)] mod tests { use std::net::{Ipv4Addr, SocketAddr, TcpListener}; @@ -671,40 +386,6 @@ mod tests { .expect("the REST API drain controller should not panic"); } - #[tokio::test] - #[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" - )] - async fn it_should_be_able_to_start_and_stop() { - let cfg = Arc::new(ephemeral_public()); - let http_api_config = Arc::new(cfg.http_api.clone().expect("missing HTTP API configuration")); - - initialize_global_services(&cfg); - - let bind_to = http_api_config.bind_address; - - let access_tokens = Arc::new(http_api_config.access_tokens.clone()); - - let stopped = ApiServer::new(Launcher::new(bind_to, None, cfg.application.shutdown.http_drain())); - - let register = &Registar::::default(); - - let api = within_deadline(api_container(&cfg)).await; - - let started = within_deadline(stopped.start( - api.container.clone(), - register.give_form(), - RuntimeServiceMetadata::new(ConfigurationInstanceId::new(ServiceRole::RestApi, 0)), - access_tokens, - )) - .await - .expect("it should start the server"); - let stopped = within_deadline(started.stop()).await.expect("it should stop the server"); - - assert_eq!(stopped.state.launcher.bind_to, bind_to); - } - #[tokio::test] async fn it_should_drain_the_token_aware_rest_api_when_its_cancellation_token_is_cancelled() { // Arrange diff --git a/packages/axum-server/Cargo.toml b/packages/axum-server/Cargo.toml index 66490959b0..5dd765b48e 100644 --- a/packages/axum-server/Cargo.toml +++ b/packages/axum-server/Cargo.toml @@ -27,7 +27,6 @@ pin-project-lite = "0" thiserror = "2" tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } tokio-util = { version = "0.7", features = [ "rt" ] } -torrust-server-lib = "0.5.0" torrust-tracker-configuration = { version = "3.0.0", path = "../configuration" } torrust-located-error = "3.0.0" tower = { version = "0", features = [ "timeout" ] } diff --git a/packages/axum-server/src/signals.rs b/packages/axum-server/src/signals.rs index dea7adf3b1..30caa4aaf3 100644 --- a/packages/axum-server/src/signals.rs +++ b/packages/axum-server/src/signals.rs @@ -3,11 +3,6 @@ use std::time::Duration; use tokio::time::{Instant, sleep, sleep_until}; use tokio_util::sync::CancellationToken; -#[allow( - deprecated, - reason = "the legacy `graceful_shutdown` still uses the deprecated `Halted` channel; SI-19 removes both" -)] -use torrust_server_lib::signals::{Halted, shutdown_signal_with_message}; use tracing::instrument; /// Longest drain the timer accepts; a longer request is shortened to it. One year is far beyond any @@ -72,71 +67,6 @@ pub async fn graceful_shutdown_on_cancellation( } } -#[allow( - deprecated, - reason = "the legacy `graceful_shutdown` still uses the deprecated `Halted` channel; SI-19 removes both" -)] -#[instrument(skip(handle, rx_halt, message))] -/// -/// The deprecation is part of the contract until SI-19 removes this item. Using it without an allowance fails -/// under `deny(deprecated)`: -/// -/// ``` -/// use torrust_tracker_axum_server::signals::graceful_shutdown; -/// let _ = graceful_shutdown; -/// ``` -/// -/// ```compile_fail -/// #![deny(deprecated)] -/// use torrust_tracker_axum_server::signals::graceful_shutdown; -/// let _ = graceful_shutdown; -/// ``` -#[deprecated( - since = "0.1.0", - note = "use `graceful_shutdown_on_cancellation` with an injected `CancellationToken`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" -)] -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; - } -} - #[cfg(test)] mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; diff --git a/packages/udp-server/Cargo.toml b/packages/udp-server/Cargo.toml index e5b930f678..11ef0c46ba 100644 --- a/packages/udp-server/Cargo.toml +++ b/packages/udp-server/Cargo.toml @@ -37,7 +37,7 @@ serde = "1.0.219" thiserror = "2" tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync", "time" ] } tokio-util = "0.7.15" -torrust-server-lib = "0.5.0" +torrust-server-lib = "0.6.0" torrust-clock = "3.0.0" torrust-tracker-configuration = { version = "3.0.0", path = "../configuration" } torrust-tracker-events = { version = "0.1.0", path = "../events" } diff --git a/packages/udp-server/src/server/launcher.rs b/packages/udp-server/src/server/launcher.rs index 21f753e6bb..b4b2944329 100644 --- a/packages/udp-server/src/server/launcher.rs +++ b/packages/udp-server/src/server/launcher.rs @@ -5,20 +5,13 @@ use std::time::Duration; use derive_more::Constructor; use futures_util::StreamExt; use tokio::select; -use tokio::sync::oneshot; use tokio::task::{JoinHandle, JoinSet}; use tokio::time::timeout; use tokio_util::sync::CancellationToken; use torrust_net_primitives::service_binding::{Protocol, ServiceBinding}; use torrust_server_lib::logging::STARTED_ON; use torrust_server_lib::registar::ServiceHealthCheckJob; -#[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" -)] -use torrust_server_lib::signals::{Halted, Started, global_shutdown_signal}; use torrust_tracker_client::udp::client::check; -use torrust_tracker_configuration::v3_0_0::shutdown::Shutdown; use torrust_tracker_udp_core::container::UdpTrackerCoreContainer; use torrust_tracker_udp_core::event::ConnectionContext; use torrust_tracker_udp_core::{self, ConnectionIdValidationPolicy, UDP_TRACKER_LOG_TARGET}; @@ -44,7 +37,7 @@ pub(crate) struct StartedReceiveLoop { pub task: JoinHandle>, } -/// Aborts the receive loop if its owner is dropped before joining it or handing it on. +/// Aborts the receive loop if its owner is dropped before handing it on. pub(crate) struct OwnedReceiveLoop(Option>>); impl OwnedReceiveLoop { @@ -52,13 +45,6 @@ impl OwnedReceiveLoop { Self(Some(task)) } - async fn join(&mut self) -> Result<(), std::io::Error> { - match &mut self.0 { - Some(task) => task.await.map_err(std::io::Error::other)?, - None => Ok(()), - } - } - /// Hands the task to a new owner without aborting it. pub(crate) fn into_task(mut self) -> JoinHandle> { self.0.take().expect("the receive loop is handed on at most once") @@ -183,83 +169,6 @@ impl Drop for OwnedReceiveLoop { } impl Launcher { - /// It starts the UDP server instance with graceful shutdown. - /// - /// This legacy entry point adapts the token-aware receive loop: a halt - /// message, a dropped halt sender, or the global OS shutdown signal cancels - /// the loop, which is then joined. Dropping this future aborts the loop. - /// - /// # Errors - /// - /// Returns an error if the startup notification receiver is dropped or the - /// receive loop stops with an error. - #[instrument(skip(udp_tracker_core_container, udp_tracker_server_container, bound_socket, tx_start, rx_halt))] - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - #[deprecated( - since = "0.1.0", - note = "use `Server::start_with_cancellation`, which runs the token-aware launcher; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" - )] - pub async fn run_with_graceful_shutdown( - udp_tracker_core_container: Arc, - udp_tracker_server_container: Arc, - bound_socket: BoundSocket, - cookie_lifetime: Duration, - connection_id_validation: ConnectionIdValidationPolicy, - tx_start: oneshot::Sender, - rx_halt: oneshot::Receiver, - ) -> Result<(), std::io::Error> { - let local_udp_url = bound_socket.url().to_string(); - let cancellation_token = CancellationToken::new(); - - let StartedReceiveLoop { - service_binding, - address, - task, - } = Self::start_receive_loop( - udp_tracker_core_container, - udp_tracker_server_container, - bound_socket, - cookie_lifetime, - connection_id_validation, - cancellation_token.clone(), - // The legacy launcher path takes no shutdown settings; SI-19 removes it. - Shutdown::default().udp_request_drain(), - ); - let mut receive_loop = OwnedReceiveLoop::new(task); - - if tx_start - .send(Started { - service_binding, - address, - }) - .is_err() - { - cancellation_token.cancel(); - drop(receive_loop.join().await); - return Err(std::io::Error::new( - std::io::ErrorKind::BrokenPipe, - "UDP startup receiver was dropped", - )); - } - - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (started)"); - - select! { - result = receive_loop.join() => { - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (stopped)"); - result - }, - () = legacy_stop_requested(rx_halt, format!("Halting UDP Service Bound to Socket: {address}")) => { - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (halting)"); - cancellation_token.cancel(); - receive_loop.join().await - } - } - } - /// Logs the listener startup and spawns the receive loop, which stops /// admitting datagrams when `cancellation_token` is cancelled, drains its /// request processors for at most `request_drain_deadline`, and returns `Ok(())`. @@ -506,35 +415,6 @@ impl Launcher { } } -/// Resolves when a legacy consumer asks the UDP server to stop. -/// -/// A dropped halt sender counts as a stop request instead of a panic. The -/// global OS signal is still observed until the legacy API is removed (SI-19). -#[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" -)] -async fn legacy_stop_requested(rx_halt: oneshot::Receiver, message: String) { - select! { - () = halt_requested(rx_halt) => (), - () = global_shutdown_signal() => tracing::debug!(target: UDP_TRACKER_LOG_TARGET, "Global shutdown signal processed"), - } - - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "{message}"); -} - -#[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" -)] -async fn halt_requested(rx_halt: oneshot::Receiver) { - if let Ok(signal) = rx_halt.await { - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, "Halt signal processed: {signal}"); - } else { - tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "UDP halt sender dropped; stopping the server"); - } -} - fn log_listener_startup( bind_to: std::net::SocketAddr, connection_id_validation: ConnectionIdValidationPolicy, @@ -588,19 +468,12 @@ async fn publish_event_if_sender_available(sender: &Sender, event: Event) { #[cfg(test)] mod tests { - use std::io::ErrorKind; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; - use tokio::sync::oneshot; use torrust_net_primitives::service_binding::{Protocol, ServiceBinding}; - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - use torrust_server_lib::signals::{Halted, Started}; use torrust_tracker_configuration::v3_0_0::logging; use torrust_tracker_primitives::{ConfigurationInstanceId, ServiceRole}; use torrust_tracker_test_helpers::configuration::ephemeral_public; @@ -613,7 +486,6 @@ mod tests { use crate::container::UdpTrackerServerContainer; use crate::event::Event; use crate::event::receiver::Receiver; - use crate::server::bound_socket::BoundSocket; const TEST_LOG_TARGET: &str = "udp://test"; // This is an absolute failure bound, not a scheduling delay. Event-publication regressions @@ -745,112 +617,6 @@ mod tests { .expect("the event receiver should remain connected") } - #[tokio::test] - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - async fn it_should_report_a_broken_pipe_when_the_startup_notification_receiver_is_dropped() { - // Arrange - let launcher = UdpLauncherTestContext::new().await; - let bound_socket = BoundSocket::bind(launcher.bind_address, false).expect("UDP socket should bind"); - let (startup_notification_sender, startup_notification_receiver) = oneshot::channel::(); - let (_halt_sender, halt_receiver) = oneshot::channel::(); - drop(startup_notification_receiver); - - // Act - let result = Launcher::run_with_graceful_shutdown( - launcher.udp_tracker_core_container, - launcher.udp_tracker_server_container, - bound_socket, - launcher.cookie_lifetime, - ConnectionIdValidationPolicy::Strict, - startup_notification_sender, - halt_receiver, - ) - .await; - - // Assert - assert_eq!( - result.expect_err("startup notification should fail").kind(), - ErrorKind::BrokenPipe - ); - } - - #[tokio::test] - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - async fn it_should_release_the_socket_when_the_startup_notification_receiver_is_dropped() { - // Arrange - let launcher = UdpLauncherTestContext::new().await; - let bound_socket = BoundSocket::bind(launcher.bind_address, false).expect("UDP socket should bind"); - let bound_address = bound_socket.address(); - let (startup_notification_sender, startup_notification_receiver) = oneshot::channel::(); - let (_halt_sender, halt_receiver) = oneshot::channel::(); - drop(startup_notification_receiver); - - // Act - let _result = Launcher::run_with_graceful_shutdown( - launcher.udp_tracker_core_container, - launcher.udp_tracker_server_container, - bound_socket, - launcher.cookie_lifetime, - ConnectionIdValidationPolicy::Strict, - startup_notification_sender, - halt_receiver, - ) - .await; - - // Assert - BoundSocket::bind(bound_address, false).expect("UDP socket should be released after startup notification failure"); - } - - /// A legacy launcher that has sent its startup notification and is waiting for a halt. - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - struct RunningLegacyLauncher { - bound_address: SocketAddr, - halt_sender: oneshot::Sender, - task: tokio::task::JoinHandle>, - } - - impl RunningLegacyLauncher { - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - async fn start() -> Self { - let launcher = UdpLauncherTestContext::new().await; - let bound_socket = BoundSocket::bind(launcher.bind_address, false).expect("UDP socket should bind"); - let bound_address = bound_socket.address(); - let (startup_notification_sender, startup_notification_receiver) = oneshot::channel::(); - let (halt_sender, halt_receiver) = oneshot::channel::(); - let task = tokio::spawn(Launcher::run_with_graceful_shutdown( - launcher.udp_tracker_core_container, - launcher.udp_tracker_server_container, - bound_socket, - launcher.cookie_lifetime, - torrust_tracker_udp_core::ConnectionIdValidationPolicy::Strict, - startup_notification_sender, - halt_receiver, - )); - tokio::time::timeout(LIFECYCLE_TIMEOUT, startup_notification_receiver) - .await - .expect("the legacy launcher should start within the test deadline") - .expect("the legacy launcher should send its startup notification"); - - Self { - bound_address, - halt_sender, - task, - } - } - } - async fn wait_until_bindable(address: SocketAddr) -> bool { tokio::time::timeout(LIFECYCLE_TIMEOUT, async { while std::net::UdpSocket::bind(address).is_err() { @@ -861,47 +627,6 @@ mod tests { .is_ok() } - #[tokio::test] - async fn it_should_stop_without_panicking_and_release_the_socket_when_the_legacy_halt_sender_is_dropped() { - // Arrange - let launcher = RunningLegacyLauncher::start().await; - - // Act - drop(launcher.halt_sender); - let result = tokio::time::timeout(LIFECYCLE_TIMEOUT, launcher.task) - .await - .expect("the legacy launcher should stop within the test deadline"); - - // Assert - assert!( - matches!(result, Ok(Ok(()))), - "a dropped halt sender should stop the legacy launcher cleanly: {result:?}" - ); - assert!( - wait_until_bindable(launcher.bound_address).await, - "the legacy launcher must release its socket at {} within {LIFECYCLE_TIMEOUT:?}", - launcher.bound_address - ); - } - - #[tokio::test] - async fn it_should_release_the_socket_when_the_legacy_launcher_task_is_aborted() { - // Arrange - let launcher = RunningLegacyLauncher::start().await; - let _halt_sender = launcher.halt_sender; - - // Act - launcher.task.abort(); - drop(launcher.task.await); - - // Assert - assert!( - wait_until_bindable(launcher.bound_address).await, - "aborting the legacy launcher must release its socket at {} within {LIFECYCLE_TIMEOUT:?}", - launcher.bound_address - ); - } - #[tokio::test] async fn it_should_discard_a_request_whose_source_port_is_zero() { // Arrange diff --git a/packages/udp-server/src/server/mod.rs b/packages/udp-server/src/server/mod.rs index f2277f6a14..792281c1af 100644 --- a/packages/udp-server/src/server/mod.rs +++ b/packages/udp-server/src/server/mod.rs @@ -12,16 +12,17 @@ pub mod request_buffer; pub mod spawner; pub mod states; -/// Error that can occur when starting or stopping the UDP server. +/// Error that can occur when starting 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. +/// - The service cannot be registered. /// -/// Some errors triggered while stopping the server are: -/// -/// - The [`Server`] cannot send the shutdown signal to the spawned UDP service thread. +/// `StartupNotification`, `Launcher` and `FailedToStartOrStopServer` belong to +/// the legacy start and stop path that SI-19 removed. They are no longer +/// constructed and stay only to keep the enum's public surface unchanged until +/// the next breaking cleanup. #[derive(Debug, Error)] #[non_exhaustive] pub enum UdpError { @@ -67,20 +68,7 @@ where #[cfg(test)] mod tests { - use std::net::{Ipv4Addr, UdpSocket}; - use std::sync::Arc; - use std::time::Duration; - - use torrust_net_primitives::service_binding::{Protocol, ServiceBinding}; - use torrust_server_lib::registar::{Registar, RegistrationError, ServiceRegistration}; use torrust_tracker_configuration::v3_0_0::{Configuration, logging}; - use torrust_tracker_primitives::{ConfigurationInstanceId, RuntimeServiceMetadata, ServiceRole}; - use torrust_tracker_test_helpers::configuration::ephemeral_public; - use torrust_tracker_udp_core::container::UdpTrackerCoreContainer; - - use super::spawner::Spawner; - use super::{Server, UdpError}; - use crate::container::UdpTrackerServerContainer; fn initialize_global_services(configuration: &Configuration) { initialize_static(); @@ -91,175 +79,6 @@ mod tests { torrust_clock::initialize_static(); } - #[tokio::test] - #[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" - )] - 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 configuration_instance_id = ConfigurationInstanceId::new(ServiceRole::UdpTracker, 0); - let register = &Registar::::default(); - - let stopped = Server::new(Spawner::new(bind_to)); - - let udp_tracker_core_container = UdpTrackerCoreContainer::initialize( - &core_config, - &udp_tracker_config, - cfg.udp_tracker_server.max_connection_id_errors_per_ip, - configuration_instance_id, - ) - .await; - let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); - - let started = stopped - .start( - udp_tracker_core_container, - udp_tracker_server_container, - register.give_form(), - RuntimeServiceMetadata::new(configuration_instance_id), - config.cookie_lifetime, - torrust_tracker_udp_core::ConnectionIdValidationPolicy::Strict, - ) - .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] - #[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" - )] - 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 configuration_instance_id = ConfigurationInstanceId::new(ServiceRole::UdpTracker, 0); - let register = &Registar::::default(); - - let stopped = Server::new(Spawner::new(bind_to)); - - let udp_tracker_core_container = UdpTrackerCoreContainer::initialize( - &core_config, - &udp_tracker_config, - cfg.udp_tracker_server.max_connection_id_errors_per_ip, - configuration_instance_id, - ) - .await; - let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); - - let started = stopped - .start( - udp_tracker_core_container, - udp_tracker_server_container, - register.give_form(), - RuntimeServiceMetadata::new(configuration_instance_id), - udp_tracker_config.cookie_lifetime, - torrust_tracker_udp_core::ConnectionIdValidationPolicy::Strict, - ) - .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); - } - - #[tokio::test] - #[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" - )] - async fn it_should_preserve_registration_error_and_release_listener_when_registration_fails() { - // Arrange - let mut cfg = ephemeral_public(); - let reserved_socket = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).expect("reserve UDP listener address"); - let bind_to = reserved_socket.local_addr().expect("read UDP listener address"); - drop(reserved_socket); - cfg.udp_trackers.as_mut().expect("test configuration enables UDP")[0].bind_address = bind_to; - let cfg = Arc::new(cfg); - let core_config = Arc::new(cfg.core.clone()); - let udp_tracker_config = Arc::new(cfg.udp_trackers.as_ref().expect("test configuration enables UDP")[0].clone()); - let configuration_instance_id = ConfigurationInstanceId::new(ServiceRole::UdpTracker, 0); - let registar = Registar::default(); - registar - .give_form() - .register(ServiceRegistration::new( - ServiceBinding::new(Protocol::UDP, bind_to).expect("UDP service binding should be valid"), - RuntimeServiceMetadata::new(configuration_instance_id), - None, - )) - .await - .expect("reserve the UDP service registration"); - initialize_global_services(&cfg); - let udp_tracker_core_container = UdpTrackerCoreContainer::initialize( - &core_config, - &udp_tracker_config, - cfg.udp_tracker_server.max_connection_id_errors_per_ip, - configuration_instance_id, - ) - .await; - let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); - - // Act - let result = Server::new(Spawner::new(bind_to)) - .start( - udp_tracker_core_container, - udp_tracker_server_container, - registar.give_form(), - RuntimeServiceMetadata::new(configuration_instance_id), - udp_tracker_config.cookie_lifetime, - torrust_tracker_udp_core::ConnectionIdValidationPolicy::Strict, - ) - .await; - - // Assert - let UdpError::Registration { - source: RegistrationError::DuplicateBinding(binding), - } = result.expect_err("duplicate registration should fail") - else { - panic!("UDP starter should retain the registration failure source"); - }; - assert_eq!(binding.bind_address(), bind_to); - UdpSocket::bind(bind_to).expect("UDP listener should be released after registration failure"); - } - mod token_aware_start { use std::net::{Ipv4Addr, SocketAddr, UdpSocket}; use std::sync::Arc; diff --git a/packages/udp-server/src/server/spawner.rs b/packages/udp-server/src/server/spawner.rs index bf968ebf12..479ec66bfb 100644 --- a/packages/udp-server/src/server/spawner.rs +++ b/packages/udp-server/src/server/spawner.rs @@ -1,46 +1,8 @@ -//! A thin wrapper for tokio spawn to launch the UDP server launcher as a new task. +//! The UDP server spawner: the address a UDP server binds to. use std::net::SocketAddr; -use std::sync::Arc; -use std::time::Duration; use derive_more::Constructor; use derive_more::derive::Display; -use tokio::sync::oneshot; -use tokio::task::JoinHandle; -#[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" -)] -use torrust_server_lib::signals::{Halted, Started}; -use torrust_tracker_udp_core::ConnectionIdValidationPolicy; -use torrust_tracker_udp_core::container::UdpTrackerCoreContainer; - -use super::launcher::Launcher; -use crate::container::UdpTrackerServerContainer; -use crate::server::bound_socket::BoundSocket; - -#[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" -)] -#[deprecated( - since = "0.1.0", - note = "use `Server::start_with_cancellation`, which spawns the launcher with a `CancellationToken`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" -)] -pub struct LaunchRequest { - pub udp_tracker_core_container: Arc, - pub udp_tracker_server_container: Arc, - pub cookie_lifetime: Duration, - pub connection_id_validation: ConnectionIdValidationPolicy, - pub bound_socket: BoundSocket, - pub tx_start: oneshot::Sender, - #[deprecated( - since = "0.1.0", - note = "use a `CancellationToken` instead of a `Halted` receiver; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" - )] - pub rx_halt: oneshot::Receiver, -} - // `derive_more::Constructor` generates `field: field` initializers on this MSRV-compatible version. // Nightly Clippy diagnoses that proc-macro expansion; remove this allowance once derive_more emits // field-init shorthand. @@ -53,34 +15,3 @@ pub struct LaunchRequest { pub struct Spawner { pub bind_to: SocketAddr, } - -impl Spawner { - /// It spawns a new task to run the UDP server instance. - /// - #[must_use] - #[deprecated( - since = "0.1.0", - note = "use `Server::start_with_cancellation`, which spawns the launcher with a `CancellationToken`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" - )] - #[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" - )] - pub fn spawn_launcher(&self, request: LaunchRequest) -> JoinHandle> { - let spawner = Self::new(self.bind_to); - - tokio::spawn(async move { - Launcher::run_with_graceful_shutdown( - request.udp_tracker_core_container, - request.udp_tracker_server_container, - request.bound_socket, - request.cookie_lifetime, - request.connection_id_validation, - request.tx_start, - request.rx_halt, - ) - .await - .map(|()| spawner) - }) - } -} diff --git a/packages/udp-server/src/server/states.rs b/packages/udp-server/src/server/states.rs index 87fa3edebd..1e6eb59952 100644 --- a/packages/udp-server/src/server/states.rs +++ b/packages/udp-server/src/server/states.rs @@ -2,38 +2,24 @@ //! //! # Test ownership //! -//! Colocated tests cover deterministic `await_startup_notification` error -//! mappings. The public `server` module owns registration-error preservation -//! and listener-release coverage for both start paths, and token-aware stop -//! coverage. The launcher owns the legacy halt and drop-path regression tests. -//! Bind failures and `Running::stop` remain legacy lifecycle behavior slated -//! for removal in SI-19 (Issue #1488); do not add coverage-only tests for -//! those paths here. +//! The public `server` module owns registration-error preservation, +//! listener-release coverage and token-aware stop coverage. Bind failures are +//! not covered by coverage-only tests here. use std::fmt::Debug; use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; -use derive_more::Constructor; use derive_more::derive::Display; use tokio::task::JoinHandle; use tokio_util::sync::CancellationToken; use torrust_server_lib::registar::{ServiceRegistration, ServiceRegistrationForm}; -#[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" -)] -use torrust_server_lib::signals::{Halted, Started}; use torrust_tracker_primitives::RuntimeServiceMetadata; use torrust_tracker_udp_core::container::UdpTrackerCoreContainer; use torrust_tracker_udp_core::{ConnectionIdValidationPolicy, UDP_TRACKER_LOG_TARGET}; -use tracing::{Level, instrument}; +use tracing::instrument; -#[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" -)] -use super::spawner::{LaunchRequest, Spawner}; +use super::spawner::Spawner; use super::{Server, UdpError}; use crate::container::UdpTrackerServerContainer; use crate::server::bound_socket::BoundSocket; @@ -46,21 +32,6 @@ use crate::server::launcher::{Launcher, OwnedReceiveLoop, StartedReceiveLoop}; )] pub type StoppedUdpServer = Server; -/// A UDP server instance controller with a running UDP instance. -#[allow( - clippy::module_name_repetitions, - reason = "type alias distinguishes the UDP server running state" -)] -#[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" -)] -#[deprecated( - since = "0.1.0", - note = "use `Server::start_with_cancellation` and keep the returned `CancellationRunning`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" -)] -pub type RunningUdpServer = Server; - /// A stopped UDP server state. #[derive(Debug, Display)] #[display("Stopped: {spawner}")] @@ -68,40 +39,10 @@ pub struct Stopped { pub spawner: Spawner, } -/// A running UDP server state. -// `derive_more::Constructor` generates `field: field` initializers on this MSRV-compatible version. -// Nightly Clippy diagnoses that proc-macro expansion; remove this allowance once derive_more emits -// field-init shorthand. -#[allow( - clippy::redundant_field_names, - reason = "derive_more::Constructor emits field initializers on this MSRV-compatible version" -)] -#[derive(Debug, Display, Constructor)] -#[display("Running (with local address): {local_addr}")] -#[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" -)] -#[deprecated( - since = "0.1.0", - note = "use `CancellationRunning` from `Server::start_with_cancellation` and cancel the injected `CancellationToken`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" -)] -pub struct Running { - /// The address where the server is bound. - pub local_addr: SocketAddr, - #[deprecated( - since = "0.1.0", - note = "cancel the injected `CancellationToken` instead of sending `Halted`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" - )] - pub halt_task: tokio::sync::oneshot::Sender, - pub task: JoinHandle>, -} - /// A token-aware UDP runtime: the receive-loop task, owned by the caller. /// /// The task returns `Ok(())` after cancellation and an error when the receive -/// loop stops for any other reason. [`Running`] remains the compatibility path -/// for consumers using [`Halted`]. +/// loop stops for any other reason. pub struct CancellationRunning { /// The address where the server is bound. pub local_addr: SocketAddr, @@ -117,111 +58,9 @@ impl Server { } } - /// 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. - /// - #[instrument( - skip(self, udp_tracker_core_container, udp_tracker_server_container, form, metadata), - fields( - service_role = metadata.service_role().as_str(), - instance_index = metadata.configuration_instance_id().instance_index(), - ), - err, - ret(Display, level = Level::INFO) - )] - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - /// - /// The deprecation is part of the contract until SI-19 removes this item. Using it without an allowance fails - /// under `deny(deprecated)`: - /// - /// ``` - /// use torrust_tracker_udp_server::server::{Server, states::Stopped}; - /// let _ = Server::::start; - /// ``` - /// - /// ```compile_fail - /// #![deny(deprecated)] - /// use torrust_tracker_udp_server::server::{Server, states::Stopped}; - /// let _ = Server::::start; - /// ``` - #[deprecated( - since = "0.1.0", - note = "use `Server::start_with_cancellation` with a `CancellationToken`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" - )] - pub async fn start( - self, - udp_tracker_core_container: Arc, - udp_tracker_server_container: Arc, - form: ServiceRegistrationForm, - metadata: RuntimeServiceMetadata, - cookie_lifetime: Duration, - connection_id_validation: ConnectionIdValidationPolicy, - ) -> Result, UdpError> { - 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 bound_socket = BoundSocket::bind( - self.state.spawner.bind_to, - udp_tracker_core_container.udp_tracker_config.network.ipv6_v6only, - ) - .map_err(|source| UdpError::Bind { source: *source })?; - let mut task = self.state.spawner.spawn_launcher(LaunchRequest { - udp_tracker_core_container, - udp_tracker_server_container, - cookie_lifetime, - connection_id_validation, - bound_socket, - tx_start, - rx_halt, - }); - - let started = await_startup_notification(rx_start, &mut task).await?; - - let service_binding = started.service_binding; - let local_addr = started.address; - - if let Some(public_url) = metadata.public_url() { - tracing::info!(target: UDP_TRACKER_LOG_TARGET, service_binding = %service_binding, public_url = %public_url, "Started UDP tracker"); - } else { - tracing::info!(target: UDP_TRACKER_LOG_TARGET, service_binding = %service_binding, "Started UDP tracker"); - } - - if let Err(error) = form - .register(ServiceRegistration::new(service_binding, metadata, Some(Launcher::check))) - .await - { - let _ = tx_halt.send(Halted::Normal); - drop(task.await); - return Err(UdpError::Registration { source: error }); - } - - 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) - } - /// Starts the UDP server using an injected cancellation token. /// - /// This additive path does not subscribe to operating-system signals and + /// This path does not subscribe to operating-system signals and /// has no launcher task. It registers the service and, if registration /// fails, cancels `cancellation_token`, stops the receive loop, and /// releases the socket before returning. Otherwise the caller owns the @@ -298,131 +137,3 @@ impl Server { }) } } - -async fn await_startup_notification( - rx_start: tokio::sync::oneshot::Receiver, - task: &mut JoinHandle>, -) -> Result { - match rx_start.await { - Ok(started) => Ok(started), - Err(notification_error) => match task.await { - Ok(Err(source)) => Err(UdpError::Launcher { source }), - Ok(Ok(_)) => Err(UdpError::StartupNotification { - source: notification_error, - }), - Err(error) => Err(UdpError::FailedToStartOrStopServer(error.to_string())), - }, - } -} - -#[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" -)] -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))] - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - #[deprecated( - since = "0.1.0", - note = "cancel the `CancellationToken` passed to `start_with_cancellation` and await the returned `task`; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" - )] - 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 - .map_err(|error| UdpError::FailedToStartOrStopServer(error.to_string()))? - .map_err(|source| UdpError::Launcher { source })?; - - let stopped_api_server: Server = Server { - state: Stopped { spawner: launcher }, - }; - - Ok(stopped_api_server) - } -} - -#[cfg(test)] -mod tests { - use std::net::SocketAddr; - - use tokio::sync::oneshot; - use tokio::task::JoinHandle; - - use super::{UdpError, await_startup_notification}; - use crate::server::spawner::Spawner; - - fn launcher_task_with_successful_result() -> JoinHandle> { - tokio::spawn(async { Ok(Spawner::new(SocketAddr::from(([127, 0, 0, 1], 6969)))) }) - } - - #[tokio::test] - async fn it_should_preserve_a_broken_pipe_launcher_error_when_startup_notification_fails() { - // Arrange - let (tx_start, rx_start) = oneshot::channel(); - drop(tx_start); - let mut task = tokio::spawn(async { - Err::(std::io::Error::new( - std::io::ErrorKind::BrokenPipe, - "UDP startup receiver was dropped", - )) - }); - - // Act - let result = await_startup_notification(rx_start, &mut task).await; - - // Assert - let UdpError::Launcher { source } = result.expect_err("launcher startup failure should be returned") else { - panic!("launcher error should not be collapsed into a startup-notification error"); - }; - assert_eq!(source.kind(), std::io::ErrorKind::BrokenPipe); - } - - #[tokio::test] - async fn it_should_return_a_startup_notification_error_when_the_launcher_finishes_successfully() { - // Arrange - let (tx_start, rx_start) = oneshot::channel(); - drop(tx_start); - let mut task = launcher_task_with_successful_result(); - - // Act - let result = await_startup_notification(rx_start, &mut task).await; - - // Assert - assert!(matches!(result, Err(UdpError::StartupNotification { .. }))); - } - - #[tokio::test] - async fn it_should_return_a_server_failure_error_when_the_launcher_task_is_aborted() { - // Arrange - let (tx_start, rx_start) = oneshot::channel(); - drop(tx_start); - let mut task = launcher_task_with_successful_result(); - task.abort(); - - // Act - let result = await_startup_notification(rx_start, &mut task).await; - - // Assert - assert!(matches!(result, Err(UdpError::FailedToStartOrStopServer(_)))); - } -} diff --git a/src/bootstrap/jobs/manager.rs b/src/bootstrap/jobs/manager.rs index 1bcc4e18e8..3fdc556b5d 100644 --- a/src/bootstrap/jobs/manager.rs +++ b/src/bootstrap/jobs/manager.rs @@ -30,15 +30,9 @@ use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::task::{Context, Poll}; use std::time::Duration; -use tokio::sync::oneshot::Sender; use tokio::task::{Id, JoinError, JoinHandle, JoinSet}; use tokio::time::{Instant, timeout_at}; use tokio_util::sync::CancellationToken; -#[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" -)] -use torrust_server_lib::signals::Halted; use tracing::{info, warn}; /// A component's explicit terminal result. @@ -127,177 +121,6 @@ pub fn incomplete_components(outcomes: &[JobOutcome]) -> Vec<&str> { .collect() } -/// Delivers a normal halt signal when its component is dropped. -#[derive(Debug)] -#[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" -)] -#[deprecated( - since = "4.0.0", - note = "use a `CancellationToken` and the token-aware shutdown controller; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" -)] -pub struct HaltSignal { - sender: Option>, -} - -#[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" -)] -impl HaltSignal { - #[must_use] - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - pub const fn new(sender: Sender) -> Self { - Self { sender: Some(sender) } - } - - /// Signals normal shutdown. It is harmless when shutdown was already signalled. - /// - /// # Errors - /// - /// Returns the unsent signal when the receiver has already been dropped. - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - pub fn signal_shutdown(&mut self) -> Result<(), Halted> { - self.sender.take().map_or(Ok(()), |sender| sender.send(Halted::Normal)) - } -} - -#[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" -)] -impl Drop for HaltSignal { - fn drop(&mut self) { - let _ = self.signal_shutdown(); - } -} - -/// Owns a component's spawned server task until it has been joined. -/// -/// Dropping the outer component runner can occur while its `select!` branch is -/// awaiting this task, for example when `JobManager` escalates at its deadline. -/// The drop implementation sends the normal halt signal and aborts the child, -/// so the child cannot continue detached from its component owner. -#[derive(Debug)] -#[deprecated( - since = "4.0.0", - note = "use a `CancellationToken` and the token-aware shutdown controller; removal is planned for the next breaking release of this package (SI-19, EPIC #1488); executables, not libraries, own OS-signal subscriptions (see docs/features/shutdown-process/legacy-api-migration.md)" -)] -#[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" -)] -pub struct NestedServerTask { - halt_signal: HaltSignal, - task: JoinHandle, - shutdown_controller: Option>, -} - -#[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" -)] -impl NestedServerTask { - #[must_use] - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - pub const fn new(halt_task: Sender, task: JoinHandle) -> Self { - Self { - halt_signal: HaltSignal::new(halt_task), - task, - shutdown_controller: None, - } - } - - /// Creates an owner that also supervises a server's shutdown controller. - #[must_use] - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - pub const fn with_shutdown_controller( - halt_task: Sender, - task: JoinHandle, - shutdown_controller: JoinHandle<()>, - ) -> Self { - Self { - halt_signal: HaltSignal::new(halt_task), - task, - shutdown_controller: Some(shutdown_controller), - } - } - - /// Signals normal shutdown. It is harmless when shutdown was already signalled. - /// - /// # Errors - /// - /// Returns the unsent signal when the receiver has already been dropped. - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - pub fn signal_shutdown(&mut self) -> Result<(), Halted> { - self.halt_signal.signal_shutdown() - } - - /// Joins the nested server task. - /// - /// # Errors - /// - /// Returns the nested task's join error when it panics or is aborted. - #[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" - )] - pub async fn join(&mut self) -> Result { - (&mut self.task).await - } - - /// Joins the shutdown controller after normal halt has been signalled. - /// - /// # Errors - /// - /// Returns the controller's join error when it panics or is aborted. - #[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" - )] - pub async fn join_shutdown_controller(&mut self) -> Result<(), JoinError> { - if let Some(shutdown_controller) = &mut self.shutdown_controller { - shutdown_controller.await - } else { - Ok(()) - } - } -} - -#[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" -)] -impl Drop for NestedServerTask { - #[allow( - deprecated, - reason = "deprecated legacy shutdown API kept for compatibility until SI-19 removes it" - )] - fn drop(&mut self) { - let _ = self.signal_shutdown(); - self.task.abort(); - if let Some(shutdown_controller) = &self.shutdown_controller { - shutdown_controller.abort(); - } - } -} - /// Owns a token-aware server task and its cancellation drain controller. /// /// Dropping the outer component runner aborts both children, preventing either @@ -1145,11 +968,6 @@ mod tests { use tokio::sync::oneshot; use tokio::time::{Duration, sleep, timeout}; use tokio_util::sync::CancellationToken; - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - use torrust_server_lib::signals::Halted; use super::{ ComponentCompletion, ComponentError, ComponentId, ComponentRegistry, ComponentResult, EXIT_CODE_GRACEFUL_SHUTDOWN, @@ -1287,63 +1105,15 @@ mod tests { } #[tokio::test] - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - async fn it_should_abort_a_nested_server_task_when_the_component_is_aborted_after_the_deadline() { - // Arrange - let mut manager = JobManager::new(); - let (child_completion_sender, child_completion_receiver) = oneshot::channel::<()>(); - let (halt_sender, halt_receiver) = oneshot::channel(); - let (server_ready_sender, server_ready_receiver) = oneshot::channel(); - reserve_and_spawn(&mut manager, "server-component", async move { - let mut server = super::NestedServerTask::new( - halt_sender, - tokio::spawn(async move { - let _ = child_completion_receiver.await; - }), - ); - server_ready_sender - .send(()) - .expect("the test waits until the nested server owner is constructed"); - server - .join() - .await - .map_err(|error| ComponentError::new(format!("server task failed: {error}")))?; - Ok(ComponentCompletion::Completed) - }); - - // Act - server_ready_receiver - .await - .expect("the nested server owner must be constructed before the deadline starts"); - let outcomes = manager.wait_for_all(Duration::ZERO).await; - - // Assert - assert_eq!(outcomes[0].status, JobStatus::Aborted); - assert!( - child_completion_sender.send(()).is_err(), - "the nested task receiver must be dropped after the outer task abort" - ); - assert!(matches!(halt_receiver.await, Ok(Halted::Normal))); - } - - #[tokio::test] - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - async fn it_should_abort_a_nested_shutdown_controller_when_the_component_is_aborted_after_the_deadline() { + async fn it_should_abort_a_token_aware_server_task_and_its_shutdown_controller_when_the_component_is_aborted_after_the_deadline() + { // Arrange let mut manager = JobManager::new(); let (server_completion_sender, server_completion_receiver) = oneshot::channel::<()>(); let (controller_completion_sender, controller_completion_receiver) = oneshot::channel::<()>(); - let (halt_sender, halt_receiver) = oneshot::channel(); let (server_ready_sender, server_ready_receiver) = oneshot::channel(); reserve_and_spawn(&mut manager, "server-component", async move { - let mut server = super::NestedServerTask::with_shutdown_controller( - halt_sender, + let mut server = super::TokenAwareServerTask::new( tokio::spawn(async move { let _ = server_completion_receiver.await; }), @@ -1369,7 +1139,6 @@ mod tests { // Assert assert_eq!(outcomes[0].status, JobStatus::Aborted); - assert!(matches!(halt_receiver.await, Ok(Halted::Normal))); assert!( server_completion_sender.send(()).is_err(), "the nested server receiver must be dropped after the outer task abort" @@ -1380,41 +1149,6 @@ mod tests { ); } - #[tokio::test] - #[allow( - deprecated, - reason = "legacy shutdown path on the deprecated `Halted` channel; SI-19 removes it" - )] - async fn it_should_signal_and_drop_an_uncooperative_running_future_when_the_component_is_aborted_after_the_deadline() { - // Arrange - let mut manager = JobManager::new(); - let (running_completion_sender, running_completion_receiver) = oneshot::channel::<()>(); - let (halt_sender, halt_receiver) = oneshot::channel(); - let (halt_signal_ready_sender, halt_signal_ready_receiver) = oneshot::channel(); - reserve_and_spawn(&mut manager, "running-server-component", async move { - let _halt_signal = super::HaltSignal::new(halt_sender); - halt_signal_ready_sender - .send(()) - .expect("the test waits until the halt signal guard is constructed"); - let _ = running_completion_receiver.await; - Ok(ComponentCompletion::Completed) - }); - - // Act - halt_signal_ready_receiver - .await - .expect("the halt signal guard must be constructed before the deadline starts"); - let outcomes = manager.wait_for_all(Duration::ZERO).await; - - // Assert - assert_eq!(outcomes[0].status, JobStatus::Aborted); - assert!(matches!(halt_receiver.await, Ok(Halted::Normal))); - assert!( - running_completion_sender.send(()).is_err(), - "the running future receiver must be dropped after the outer task abort" - ); - } - #[tokio::test(start_paused = true)] async fn it_should_apply_the_same_deadline_to_direct_and_legacy_jobs() { // Arrange