Skip to content

Refactor fairness logic with injectable clock#249

Closed
leynos wants to merge 2 commits intomainfrom
codex/refactor-fairness-methods-per-code-review-comments
Closed

Refactor fairness logic with injectable clock#249
leynos wants to merge 2 commits intomainfrom
codex/refactor-fairness-methods-per-code-review-comments

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Aug 3, 2025

Summary

  • add pluggable clock to FairnessTracker
  • rename and simplify fairness checks
  • clean up example lint expectations

Testing

  • make lint
  • make test

https://chatgpt.com/codex/tasks/task_e_688e7e7f5fa08322b09309cc34ee0625

Summary by Sourcery

Introduce a pluggable clock abstraction and refactor fairness logic to use it, simplify and rename methods for clarity, and propagate updates across code and tests.

New Features:

  • Add Clock trait with TokioClock implementation for injectable timing in fairness tracker
  • Parameterize FairnessTracker over a generic clock and provide with_clock constructor

Enhancements:

  • Rename should_yield to should_yield_to_low_priority and streamline threshold/time checks
  • Unify reset, clear, after_low, and set_config behaviors into a single clear method
  • Replace combined let predicates with nested if constructs and expand one-line functions for readability
  • Update lint attributes in examples from expect to allow dead_code

Tests:

  • Update fairness tests to use new tracker name and should_yield_to_low_priority method

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Aug 3, 2025

Reviewer's Guide

Refactors the fairness logic to use a pluggable Clock abstraction, renames and streamlines its yielding checks (should_yield_to_low_priority), updates all related usages and tests, and applies code style and lint cleanup across server, push, and example modules.

Class diagram for refactored FairnessTracker with pluggable Clock

classDiagram
    class Clock {
        <<trait>>
        +now() Instant
        +elapsed(start: Instant) Duration
    }
    class TokioClock {
        +now() Instant
        +elapsed(start: Instant) Duration
    }
    Clock <|.. TokioClock

    class FairnessConfig {
        +max_high_before_low: usize
        +time_slice: Option<Duration>
    }
    class FairnessTracker {
        +config: FairnessConfig
        +high_counter: usize
        +high_start: Option<Instant>
        +clock: Clock
        +new(config: FairnessConfig)
        +with_clock(config: FairnessConfig, clock: Clock)
        +set_config(config: FairnessConfig)
        +after_high()
        +should_yield_to_low_priority() bool
        +after_low()
        +reset()
    }
    Clock <.. FairnessTracker : uses
    FairnessConfig <.. FairnessTracker : has
Loading

Class diagram for updated ConnectionActor usage of FairnessTracker

classDiagram
    class ConnectionActor {
        +fairness: FairnessTracker
        +set_fairness(fairness: FairnessConfig)
        +after_high(...)
        +after_low(...)
    }
    class FairnessTracker {
        +should_yield_to_low_priority() bool
        +after_high()
        +after_low()
    }
    ConnectionActor --> FairnessTracker : uses
Loading

Class diagram for Clock trait and TokioClock implementation

classDiagram
    class Clock {
        <<trait>>
        +now() Instant
        +elapsed(start: Instant) Duration
    }
    class TokioClock {
        +now() Instant
        +elapsed(start: Instant) Duration
    }
    Clock <|.. TokioClock
Loading

File-Level Changes

Change Details Files
Introduce pluggable Clock abstraction and generic FairnessTracker
  • Added Clock trait and TokioClock implementation
  • Made FairnessTracker generic over a Clock type
  • Introduced with_clock constructor and delegated new() to it
src/fairness.rs
Simplify and rename fairness checking and reset logic
  • Renamed should_yield to should_yield_to_low_priority with clear control flow
  • Consolidated reset/after_low into a single clear() helper
  • Updated instantiations and tests to use FairnessTracker and new method names
src/fairness.rs
src/connection.rs
Apply code style refinements and lint expectation cleanup
  • Expanded single-line functions into multi-line with braces for clarity
  • Replaced expect(dead_code) attributes with allow(dead_code)
  • Simplified nested if let patterns into explicit conditional blocks
src/server.rs
src/push.rs
examples/metadata_routing.rs

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 3, 2025

Warning

Rate limit exceeded

@leynos has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 9 minutes and 15 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 9fb7f17 and 5002f77.

📒 Files selected for processing (4)
  • examples/metadata_routing.rs (1 hunks)
  • examples/ping_pong.rs (1 hunks)
  • src/server.rs (3 hunks)
  • wireframe_testing/src/helpers.rs (2 hunks)

Summary by CodeRabbit

  • Refactor

    • Improved code readability and maintainability through consistent formatting and clearer conditional structures.
    • Introduced a pluggable clock abstraction for fairness tracking, enabling more flexible and testable time measurement.
    • Renamed and clarified internal method and struct names related to fairness management.
  • Bug Fixes

    • Corrected conditional logic in rate limiting to ensure accurate validation of push rates.
  • Style

    • Updated lint attributes for demonstration and documentation-related code sections.

Walkthrough

Refactor the fairness logic by renaming and generalising the Fairness struct to FairnessTracker with a pluggable clock abstraction, update related method names and usages throughout the codebase, and apply minor formatting and lint annotation changes in several files. No public API signatures are altered.

Changes

Cohort / File(s) Change Summary
Fairness abstraction and refactor
src/fairness.rs, src/connection.rs
Rename Fairness to FairnessTracker, introduce a generic Clock trait, update method names (e.g., should_yieldshould_yield_to_low_priority), refactor time handling, and adjust usages in connection logic to use the new abstraction.
Formatting and lint annotation changes
examples/metadata_routing.rs, src/server.rs, src/push.rs
Change lint attributes from #[expect(dead_code, ...)] to #[allow(dead_code)] with comments, expand single-line functions to block form, and clarify conditional logic without altering behaviour or signatures.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ConnectionActor
    participant FairnessTracker
    participant Clock

    Client->>ConnectionActor: Send request
    ConnectionActor->>FairnessTracker: after_high()
    FairnessTracker->>Clock: now()
    FairnessTracker-->>ConnectionActor: Update internal state
    ConnectionActor->>FairnessTracker: should_yield_to_low_priority()
    FairnessTracker->>Clock: elapsed(start)
    FairnessTracker-->>ConnectionActor: Return bool (should yield?)
    ConnectionActor->>Client: Respond or yield to low priority
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Possibly related PRs

Poem

In code’s fair halls where time is tracked,
A Clock now ticks where once it lacked.
Fairness renamed, with traits in tow,
Dead code allowed—let comments show.
Refactor done, abstraction won,
Reviewers cheer: the work’s well spun!
⏰✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/refactor-fairness-methods-per-code-review-comments

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown

@codescene-delta-analysis codescene-delta-analysis Bot left a comment

Choose a reason for hiding this comment

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

Code Health Improved (1 files improve in Code Health)

Gates Passed
6 Quality Gates Passed

See analysis details in CodeScene

View Improvements
File Code Health Impact Categories Improved
push.rs 9.69 → 10.00 Complex Conditional

Quality Gate Profile: Pay Down Tech Debt
Want more control? Customize Code Health rules or catch issues early with our IDE extension and CLI tool.

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey @leynos - I've reviewed your changes - here's some feedback:

  • Consider allowing injection of a custom Clock into the connection actor to enable deterministic end-to-end tests rather than always using the TokioClock.
  • The public reset method simply delegates to clear; you could remove the redundant alias or unify them under a single name to simplify the API.
  • The should_yield_to_low_priority implementation works but could be more concise by leveraging zip + is_some_and or pattern matching instead of nested ifs.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider allowing injection of a custom Clock into the connection actor to enable deterministic end-to-end tests rather than always using the TokioClock.
- The public reset method simply delegates to clear; you could remove the redundant alias or unify them under a single name to simplify the API.
- The should_yield_to_low_priority implementation works but could be more concise by leveraging zip + is_some_and or pattern matching instead of nested ifs.

## Individual Comments

### Comment 1
<location> `src/fairness.rs:12` </location>
<code_context>

 use crate::connection::FairnessConfig;

+/// Abstraction over a time source returning [`Instant`]s.
+pub(crate) trait Clock {
+    type Instant: Copy;
</code_context>

<issue_to_address>
Consider removing the Clock trait and related generics to simplify the code while retaining deterministic tests.

Here’s a way to get rid of almost all of the extra indirection and still keep determinism in your tests (they already use `tokio::time::pause/advance`), by dropping the `Clock` trait, the generic, and the extra constructor:

```rust
use tokio::time::Instant;
use crate::connection::FairnessConfig;

#[derive(Debug)]
pub(crate) struct FairnessTracker {
    config: FairnessConfig,
    high_counter: usize,
    high_start: Option<Instant>,
}

impl FairnessTracker {
    pub(crate) fn new(config: FairnessConfig) -> Self {
        Self {
            config,
            high_counter: 0,
            high_start: None,
        }
    }

    pub(crate) fn set_config(&mut self, config: FairnessConfig) {
        self.config = config;
        self.reset();
    }

    pub(crate) fn after_high(&mut self) {
        self.high_counter += 1;
        if self.high_counter == 1 {
            self.high_start = Some(Instant::now());
        }
    }

    pub(crate) fn should_yield_to_low_priority(&self) -> bool {
        let threshold_hit = self.config.max_high_before_low > 0
            && self.high_counter >= self.config.max_high_before_low;

        let time_hit = self
            .config
            .time_slice
            .zip(self.high_start)
            .map_or(false, |(slice, start)| start.elapsed() >= slice);

        threshold_hit || time_hit
    }

    pub(crate) fn after_low(&mut self) {
        self.reset();
    }

    fn reset(&mut self) {
        self.high_counter = 0;
        self.high_start = None;
    }
}
```

What this buys you:

-  No more `Clock` trait + `TokioClock` type
-  Only one constructor (`new`) instead of two
-  Direct use of `Instant::now()` which your tests already control via `tokio::time::pause()`
-  No change to any existing tests (they still call `.should_yield_to_low_priority()` under the hood)
-  ~70 lines of boilerplate gone while preserving 100% of the behavior and test determinism.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src/fairness.rs

use crate::connection::FairnessConfig;

/// Abstraction over a time source returning [`Instant`]s.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

issue (complexity): Consider removing the Clock trait and related generics to simplify the code while retaining deterministic tests.

Here’s a way to get rid of almost all of the extra indirection and still keep determinism in your tests (they already use tokio::time::pause/advance), by dropping the Clock trait, the generic, and the extra constructor:

use tokio::time::Instant;
use crate::connection::FairnessConfig;

#[derive(Debug)]
pub(crate) struct FairnessTracker {
    config: FairnessConfig,
    high_counter: usize,
    high_start: Option<Instant>,
}

impl FairnessTracker {
    pub(crate) fn new(config: FairnessConfig) -> Self {
        Self {
            config,
            high_counter: 0,
            high_start: None,
        }
    }

    pub(crate) fn set_config(&mut self, config: FairnessConfig) {
        self.config = config;
        self.reset();
    }

    pub(crate) fn after_high(&mut self) {
        self.high_counter += 1;
        if self.high_counter == 1 {
            self.high_start = Some(Instant::now());
        }
    }

    pub(crate) fn should_yield_to_low_priority(&self) -> bool {
        let threshold_hit = self.config.max_high_before_low > 0
            && self.high_counter >= self.config.max_high_before_low;

        let time_hit = self
            .config
            .time_slice
            .zip(self.high_start)
            .map_or(false, |(slice, start)| start.elapsed() >= slice);

        threshold_hit || time_hit
    }

    pub(crate) fn after_low(&mut self) {
        self.reset();
    }

    fn reset(&mut self) {
        self.high_counter = 0;
        self.high_start = None;
    }
}

What this buys you:

  • No more Clock trait + TokioClock type
  • Only one constructor (new) instead of two
  • Direct use of Instant::now() which your tests already control via tokio::time::pause()
  • No change to any existing tests (they still call .should_yield_to_low_priority() under the hood)
  • ~70 lines of boilerplate gone while preserving 100% of the behavior and test determinism.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 9

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a562127 and 9fb7f17.

📒 Files selected for processing (5)
  • examples/metadata_routing.rs (1 hunks)
  • src/connection.rs (7 hunks)
  • src/fairness.rs (4 hunks)
  • src/push.rs (3 hunks)
  • src/server.rs (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Clippy warnings MUST be disallowed.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error consider using Arc to reduce the amount of data returned.
Every module must begin with a module level (//!) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Avoid unsafe code unless absolutely necessary and document any usage clearly.
Place function attributes after doc comments.
Do not use return in single-line functions.
Use predicate functions for conditional criteria with more than two branches.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.
Prefer semantic error enums: Derive std::error::Error (via the thiserror crate) for any condition the caller might inspect, retry, or map to an HTTP status.
Use an opaque error only at the app boundary: Use eyre::Report for human-readable logs; these should not be exposed in public APIs.
Never export the opaque type from a library: Convert to domain enums at API boundaries, and to eyre only in the main main() entrypoint or top-level async task.

Files:

  • examples/metadata_routing.rs
  • src/server.rs
  • src/push.rs
  • src/connection.rs
  • src/fairness.rs

⚙️ CodeRabbit Configuration File

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • Adhere to single responsibility and CQRS

  • Place function attributes after doc comments.

  • Do not use return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless absolutely necessary.

  • Every module must begin with a //! doc comment that explains the module's purpose and utility.

  • Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar

  • Lints must not be silenced except as a last resort.

    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

  • Ensure that any API or behavioural changes are reflected in the documentation in docs/

  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/

  • Files must not exceed 400 lines in length

    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.

Files:

  • examples/metadata_routing.rs
  • src/server.rs
  • src/push.rs
  • src/connection.rs
  • src/fairness.rs
🧬 Code Graph Analysis (1)
src/server.rs (1)
src/extractor.rs (1)
  • peer_addr (362-362)
🪛 GitHub Actions: CI
src/server.rs

[warning] 229-231: Prettier-like formatting warning: function worker_count should be formatted in a single line.

src/push.rs

[warning] 97-99: Prettier-like formatting warning: function from_arc should be formatted in a single line.


[warning] 255-258: Prettier-like formatting warning: function downgrade should be formatted in a single line.

src/connection.rs

[warning] 40-40: Prettier-like formatting warning: function active_connection_count should be formatted in a single line.


[warning] 184-184: Prettier-like formatting warning: function set_fairness should be formatted in a single line.


[warning] 188-188: Prettier-like formatting warning: function set_response should be formatted in a single line.


[warning] 198-198: Prettier-like formatting warning: function shutdown_token should be formatted in a single line.


[warning] 420-420: Prettier-like formatting warning: function after_low should be formatted in a single line.


[warning] 459-459: Prettier-like formatting warning: async function wait_shutdown should be formatted in a single line.


[warning] 468-468: Prettier-like formatting warning: async function recv_push should be formatted in a single line.


[warning] 550-550: Prettier-like formatting warning: function is_active should be formatted in a single line.


[warning] 554-554: Prettier-like formatting warning: function is_shutting_down should be formatted in a single line.


[warning] 558-558: Prettier-like formatting warning: function is_done should be formatted in a single line.

src/fairness.rs

[warning] 21-25: Prettier-like formatting warning: functions now and elapsed should be formatted in a single line.


[warning] 38-40: Prettier-like formatting warning: function new should be formatted in a single line.


[warning] 81-90: Prettier-like formatting warning: functions after_low and reset should be formatted in a single line.

🪛 GitHub Check: build-test
src/connection.rs

[warning] 198-198:
Diff in /home/runner/work/wireframe/wireframe/src/connection.rs


[warning] 420-420:
Diff in /home/runner/work/wireframe/wireframe/src/connection.rs


[warning] 468-468:
Diff in /home/runner/work/wireframe/wireframe/src/connection.rs

src/fairness.rs

[warning] 81-81:
Diff in /home/runner/work/wireframe/wireframe/src/fairness.rs


[warning] 38-38:
Diff in /home/runner/work/wireframe/wireframe/src/fairness.rs


[warning] 21-21:
Diff in /home/runner/work/wireframe/wireframe/src/fairness.rs

🔇 Additional comments (8)
src/push.rs (1)

389-393: LGTM! Improved conditional clarity.

The nested conditional structure is clearer than the combined pattern match and properly enforces rate bounds.

src/server.rs (1)

512-516: LGTM! Clearer error handling structure.

The nested conditional structure improves readability and explicitly separates the handler check from error handling.

src/connection.rs (3)

48-48: LGTM! Fairness refactoring properly integrated.

The changes correctly integrate the renamed FairnessTracker with its improved API, aligning with the PR's objective to refactor fairness logic with injectable clock.

Also applies to: 113-113, 171-171, 404-404


404-417: LGTM! Improved conditional structure.

The nested conditional structure is clearer and properly handles the fairness check before attempting to receive from the low-priority queue.


43-45: Format active_connection_count as a single line.

The pipeline indicates this function should be formatted on a single line.

Apply this diff to fix the formatting:

-pub fn active_connection_count() -> u64 {
-    ACTIVE_CONNECTIONS.load(Ordering::Relaxed)
-}
+pub fn active_connection_count() -> u64 { ACTIVE_CONNECTIONS.load(Ordering::Relaxed) }

Likely an incorrect or invalid review comment.

src/fairness.rs (3)

12-30: Excellent clock abstraction design!

The introduction of the Clock trait and generic FairnessTracker is a well-architected solution that:

  • Decouples time measurement from the runtime
  • Enables deterministic testing
  • Follows dependency injection principles
  • Maintains backward compatibility with the default TokioClock

Also applies to: 33-54


68-82: LGTM! Clearer method name and implementation.

The rename to should_yield_to_low_priority better describes the method's purpose, and the explicit conditional structure improves readability over the previous combinator approach.


58-58: Good refactoring with the clear method.

Extracting the common reset logic into a private clear method follows the DRY principle and improves maintainability.

Also applies to: 84-95

Comment thread examples/metadata_routing.rs Outdated
dead_code,
reason = "placeholder for demonstration of metadata routing"
)]
#[allow(dead_code)] // placeholder for demonstration of metadata routing
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Revert to #[expect] - #[allow] is forbidden.

The coding guidelines explicitly forbid the use of #[allow]. Only narrowly scoped #[expect(lint, reason = "...")] is permitted.

Apply this diff to comply with the coding guidelines:

-#[allow(dead_code)] // placeholder for demonstration of metadata routing
+#[expect(dead_code, reason = "placeholder for demonstration of metadata routing")]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#[allow(dead_code)] // placeholder for demonstration of metadata routing
#[expect(dead_code, reason = "placeholder for demonstration of metadata routing")]
🤖 Prompt for AI Agents
In examples/metadata_routing.rs at line 63, replace the attribute
#[allow(dead_code)] with #[expect(dead_code, reason = "placeholder for
demonstration of metadata routing")] to comply with coding guidelines that
forbid #[allow] and require narrowly scoped #[expect] with a reason.

Comment thread src/connection.rs
Comment on lines +187 to +189
pub fn set_response(&mut self, stream: Option<FrameStream<F, E>>) {
self.response = stream;
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix multiple single-line function formatting issues.

The pipeline indicates these functions should all be formatted on a single line.

Apply these diffs to fix the formatting:

-    pub fn set_fairness(&mut self, fairness: FairnessConfig) {
-        self.fairness.set_config(fairness);
-    }
+    pub fn set_fairness(&mut self, fairness: FairnessConfig) { self.fairness.set_config(fairness); }

-    pub fn set_response(&mut self, stream: Option<FrameStream<F, E>>) {
-        self.response = stream;
-    }
+    pub fn set_response(&mut self, stream: Option<FrameStream<F, E>>) { self.response = stream; }

-    pub fn shutdown_token(&self) -> CancellationToken {
-        self.shutdown.clone()
-    }
+    pub fn shutdown_token(&self) -> CancellationToken { self.shutdown.clone() }

-    fn after_low(&mut self) {
-        self.fairness.after_low();
-    }
+    fn after_low(&mut self) { self.fairness.after_low(); }

-    async fn wait_shutdown(token: CancellationToken) {
-        token.cancelled_owned().await;
-    }
+    async fn wait_shutdown(token: CancellationToken) { token.cancelled_owned().await; }

-    async fn recv_push(rx: &mut mpsc::Receiver<F>) -> Option<F> {
-        rx.recv().await
-    }
+    async fn recv_push(rx: &mut mpsc::Receiver<F>) -> Option<F> { rx.recv().await }

-    fn is_active(&self) -> bool {
-        matches!(self.run_state, RunState::Active)
-    }
+    fn is_active(&self) -> bool { matches!(self.run_state, RunState::Active) }

-    fn is_shutting_down(&self) -> bool {
-        matches!(self.run_state, RunState::ShuttingDown)
-    }
+    fn is_shutting_down(&self) -> bool { matches!(self.run_state, RunState::ShuttingDown) }

-    fn is_done(&self) -> bool {
-        matches!(self.run_state, RunState::Finished)
-    }
+    fn is_done(&self) -> bool { matches!(self.run_state, RunState::Finished) }

Also applies to: 192-194, 198-200, 423-425, 462-464, 468-470, 553-555, 557-559, 562-564

🧰 Tools
🪛 GitHub Actions: CI

[warning] 188-188: Prettier-like formatting warning: function set_response should be formatted in a single line.

🤖 Prompt for AI Agents
In src/connection.rs at lines 187-189 and also at lines 192-194, 198-200,
423-425, 462-464, 468-470, 553-555, 557-559, and 562-564, multiple single-line
functions are currently formatted as multi-line blocks. Refactor each of these
functions to be single-line functions by placing the entire function definition,
including the signature and body, on one line to comply with the pipeline
formatting requirements.

Comment thread src/fairness.rs
Comment on lines +24 to +29
fn now(&self) -> Self::Instant {
tokio::time::Instant::now()
}
fn elapsed(&self, start: Self::Instant) -> Duration {
start.elapsed()
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Format Clock trait methods as single lines.

The pipeline indicates these methods should be formatted on single lines.

Apply this diff to fix the formatting:

-    fn now(&self) -> Self::Instant {
-        tokio::time::Instant::now()
-    }
-    fn elapsed(&self, start: Self::Instant) -> Duration {
-        start.elapsed()
-    }
+    fn now(&self) -> Self::Instant { tokio::time::Instant::now() }
+    fn elapsed(&self, start: Self::Instant) -> Duration { start.elapsed() }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fn now(&self) -> Self::Instant {
tokio::time::Instant::now()
}
fn elapsed(&self, start: Self::Instant) -> Duration {
start.elapsed()
}
fn now(&self) -> Self::Instant { tokio::time::Instant::now() }
fn elapsed(&self, start: Self::Instant) -> Duration { start.elapsed() }
🤖 Prompt for AI Agents
In src/fairness.rs around lines 24 to 29, the methods of the Clock trait are
currently formatted with braces on separate lines. Reformat the now() and
elapsed() methods to be single-line functions without braces, placing the entire
function definition on one line each to comply with the pipeline formatting
requirements.

Comment thread src/fairness.rs
Comment on lines 41 to +43
pub(crate) fn new(config: FairnessConfig) -> Self {
Self::with_clock(config, TokioClock)
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Format new method as a single line.

The pipeline indicates this method should be formatted on a single line.

Apply this diff to fix the formatting:

-    pub(crate) fn new(config: FairnessConfig) -> Self {
-        Self::with_clock(config, TokioClock)
-    }
+    pub(crate) fn new(config: FairnessConfig) -> Self { Self::with_clock(config, TokioClock) }
🤖 Prompt for AI Agents
In src/fairness.rs around lines 41 to 43, the new method should be formatted as
a single line to comply with the pipeline formatting rules. Change the method
definition to a single line by removing the line break and extra indentation, so
it reads: pub(crate) fn new(config: FairnessConfig) -> Self {
Self::with_clock(config, TokioClock) }.

Comment thread src/fairness.rs
Comment on lines +84 to +90
pub(crate) fn after_low(&mut self) {
self.clear();
}

pub(crate) fn reset(&mut self) {
self.clear();
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Format after_low and reset methods as single lines.

The pipeline indicates these methods should be formatted on single lines.

Apply this diff to fix the formatting:

-    pub(crate) fn after_low(&mut self) {
-        self.clear();
-    }
+    pub(crate) fn after_low(&mut self) { self.clear(); }

-    pub(crate) fn reset(&mut self) {
-        self.clear();
-    }
+    pub(crate) fn reset(&mut self) { self.clear(); }
🧰 Tools
🪛 GitHub Actions: CI

[warning] 81-90: Prettier-like formatting warning: functions after_low and reset should be formatted in a single line.

🤖 Prompt for AI Agents
In src/fairness.rs around lines 84 to 90, the methods after_low and reset are
currently formatted with braces on separate lines. To fix the formatting,
rewrite both methods as single-line functions by placing the function signature
and the call to self.clear() on the same line, removing the extra line breaks
and braces.

Comment thread src/push.rs
Comment on lines +100 to +102
pub(crate) fn from_arc(arc: Arc<PushHandleInner<F>>) -> Self {
Self(arc)
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Format from_arc as a single line.

The pipeline indicates this function should be formatted on a single line.

Apply this diff to fix the formatting:

-    pub(crate) fn from_arc(arc: Arc<PushHandleInner<F>>) -> Self {
-        Self(arc)
-    }
+    pub(crate) fn from_arc(arc: Arc<PushHandleInner<F>>) -> Self { Self(arc) }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub(crate) fn from_arc(arc: Arc<PushHandleInner<F>>) -> Self {
Self(arc)
}
pub(crate) fn from_arc(arc: Arc<PushHandleInner<F>>) -> Self { Self(arc) }
🤖 Prompt for AI Agents
In src/push.rs around lines 100 to 102, the function from_arc should be
formatted as a single line to comply with the pipeline formatting rules. Change
the function definition to a single line by removing the line breaks and placing
the entire function body on the same line as the signature.

Comment thread src/push.rs
Comment on lines +258 to +260
pub(crate) fn downgrade(&self) -> Weak<PushHandleInner<F>> {
Arc::downgrade(&self.0)
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Format downgrade as a single line.

The pipeline indicates this function should be formatted on a single line.

Apply this diff to fix the formatting:

-    pub(crate) fn downgrade(&self) -> Weak<PushHandleInner<F>> {
-        Arc::downgrade(&self.0)
-    }
+    pub(crate) fn downgrade(&self) -> Weak<PushHandleInner<F>> { Arc::downgrade(&self.0) }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub(crate) fn downgrade(&self) -> Weak<PushHandleInner<F>> {
Arc::downgrade(&self.0)
}
pub(crate) fn downgrade(&self) -> Weak<PushHandleInner<F>> { Arc::downgrade(&self.0) }
🤖 Prompt for AI Agents
In src/push.rs around lines 258 to 260, the downgrade function is currently
formatted across multiple lines but should be condensed into a single line.
Rewrite the entire function definition as a single line by placing the function
signature and its body on the same line without line breaks.

Comment thread src/server.rs
Comment on lines +232 to +234
pub const fn worker_count(&self) -> usize {
self.workers
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Format worker_count as a single line.

The pipeline indicates this method should be formatted on a single line.

Apply this diff to fix the formatting:

-    pub const fn worker_count(&self) -> usize {
-        self.workers
-    }
+    pub const fn worker_count(&self) -> usize { self.workers }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub const fn worker_count(&self) -> usize {
self.workers
}
pub const fn worker_count(&self) -> usize { self.workers }
🤖 Prompt for AI Agents
In src/server.rs around lines 232 to 234, the worker_count method should be
formatted as a single line function. Change the method definition to a single
line by placing the entire function signature and body on one line, like `pub
const fn worker_count(&self) -> usize { self.workers }`.

Comment thread src/server.rs Outdated
dead_code,
reason = "used only in doctest to illustrate an empty preamble"
)]
#[allow(dead_code)] // used only in doctest to illustrate an empty preamble
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Revert to #[expect] - #[allow] is forbidden.

The coding guidelines explicitly forbid the use of #[allow]. Only narrowly scoped #[expect(lint, reason = "...")] is permitted.

Apply this diff to comply with the coding guidelines:

-#[allow(dead_code)] // used only in doctest to illustrate an empty preamble
+#[expect(dead_code, reason = "used only in doctest to illustrate an empty preamble")]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#[allow(dead_code)] // used only in doctest to illustrate an empty preamble
#[expect(dead_code, reason = "used only in doctest to illustrate an empty preamble")]
🤖 Prompt for AI Agents
In src/server.rs at line 563, replace the attribute #[allow(dead_code)] with
#[expect(dead_code, reason = "used only in doctest to illustrate an empty
preamble")] to comply with coding guidelines that forbid #[allow] and require
narrowly scoped #[expect] attributes with a reason.

Copy link
Copy Markdown

@codescene-delta-analysis codescene-delta-analysis Bot left a comment

Choose a reason for hiding this comment

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

Code Health Improved (1 files improve in Code Health)

Gates Passed
6 Quality Gates Passed

See analysis details in CodeScene

View Improvements
File Code Health Impact Categories Improved
push.rs 9.69 → 10.00 Complex Conditional

Quality Gate Profile: Pay Down Tech Debt
Want more control? Customize Code Health rules or catch issues early with our IDE extension and CLI tool.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Aug 5, 2025

Stale (main branch has been refactored)

@leynos leynos closed this Aug 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant