Skip to content

Conversation

@maschad
Copy link
Owner

@maschad maschad commented Jun 30, 2025

Summary by CodeRabbit

  • New Features

    • Added extensive benchmark suite for socket performance, including platform-specific tests for Linux and macOS.
    • Introduced automated benchmarking workflow that posts results on pull requests.
    • Re-exported the Protocol type at the crate root for easier access.
  • Bug Fixes

    • Improved test robustness for process info retrieval and socket port assertions across platforms.
    • Enhanced error handling and iteration safety in platform-specific socket code.
  • Tests

    • Added comprehensive integration and platform-specific tests for socket discovery, process mapping, performance, and resource usage on Linux and macOS.
    • Enhanced error handling and cross-platform consistency checks in socket discovery tests.
    • Introduced platform-specific test modules conditionally compiled per OS.
  • Chores

    • Updated documentation to summarize code fixes and maintain code quality.
    • Improved code formatting and import ordering for better maintainability.
  • Refactor

    • Renamed feature flag from serde to serde-support for conditional serde support across the codebase.
    • Removed unimplemented async stream re-export and updated related comments.

@coderabbitai
Copy link

coderabbitai bot commented Jun 30, 2025

Walkthrough

This update introduces a comprehensive benchmarking and testing infrastructure, including a GitHub Actions workflow for automated Rust benchmarks and extensive platform-specific and integration tests for socket enumeration. The public API is slightly expanded by re-exporting the Protocol type. Several code quality and correctness improvements are made, particularly for platform-specific socket handling.

Changes

File(s) Change Summary
.github/workflows/benchmark.yaml Added a GitHub Actions workflow to run and comment Rust benchmarks on pushes, PRs, and a weekly schedule.
Cargo.toml Added criterion as a dev-dependency; changed serde dependency to table format with feature rename to serde-support; configured a new benchmark suite named "socket_performance".
benches/socket_performance.rs Introduced a comprehensive Criterion-based benchmark suite for socket enumeration, filtering, process info, state analysis, concurrent enumeration, memory usage, and platform-specific performance.
src/lib.rs Re-exported Protocol from the types module, making it publicly available; removed conditional re-export of AsyncTrafficStream with a comment noting it is not implemented.
src/socket/platform.rs Improved process info retrieval test logic, relaxed port assertions, updated error handling in Linux socket file parsing, changed TCP stats functions to return Option<SocketStats>, added #[allow(dead_code)] to an unused function, and applied various test robustness improvements.
src/socket/socket.rs and src/types.rs Renamed feature flag from "serde" to "serde-support" for conditional compilation of serde-related imports and derives.
tests/integration/mod.rs Added integration test module with a public submodule for socket discovery.
tests/linux_tests.rs Added extensive Linux-specific tests for socket enumeration, process mapping, performance, resource usage, and edge cases.
tests/macos_tests.rs Added comprehensive macOS-specific tests for socket enumeration, process info, statistics, performance, and edge cases using libproc.
tests/platform/mod.rs Added platform-specific test module declarations for macOS and Linux.
tests/socket_discovery.rs Added integration tests for socket discovery, filtering, monitoring, error handling, cross-platform consistency, and performance.
CODERABBIT_FIXES.md Documented fixes: removed invalid const qualifiers, suppressed dead code warnings, improved iterator safety, and applied formatting changes.
bench_output.txt Added benchmark output report detailing performance results, statistical significance, and regressions for socket-related benchmarks.

Sequence Diagram(s)

sequenceDiagram
    participant GitHub
    participant Runner as GitHub Actions Runner
    participant Cargo
    participant PR as Pull Request

    GitHub->>Runner: Trigger benchmark workflow (push/PR/schedule)
    Runner->>Runner: Checkout code
    Runner->>Runner: Install Rust toolchain
    Runner->>Runner: Cache dependencies/build
    Runner->>Cargo: Run `cargo bench`
    Cargo-->>Runner: Benchmark results
    alt Triggered by Pull Request
        Runner->>PR: Post benchmark results as comment
    end
Loading

Poem

In the warren, code does scurry—
Benchmarks run in midnight hurry.
Sockets tested, ports explored,
Linux, Mac, and more adored.
With every hop, the tests grow neat—
A rabbit’s work is now complete!
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8d4cc59 and 8cba094.

📒 Files selected for processing (3)
  • Cargo.toml (1 hunks)
  • src/socket/socket.rs (2 hunks)
  • src/types.rs (7 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/socket/socket.rs
  • src/types.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • Cargo.toml
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: benchmark
  • GitHub Check: Test
  • GitHub Check: Format
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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 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

@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: 3

🔭 Outside diff range comments (1)
src/socket/platform.rs (1)

605-615: Unit-test still over-strict → causes CI failure

CI shows Failed to get process info … originating from assert!(process_info.is_some()).
get_process_info legitimately returns None for kernel / root PIDs, sandboxed daemons, etc.

-                assert!(
-                    process_info.is_some(),
-                    "Failed to get process info for PID {pid}"
-                );
+                // Some PIDs (e.g. kernel threads or permission-restricted processes)
+                // deliberately do not expose details – treat this as non-fatal.
+                if process_info.is_none() {
+                    log::debug!("process info unavailable for pid {pid}");
+                    continue;
+                }

This will stabilise the test while still exercising the happy-path.

🧹 Nitpick comments (9)
src/socket/platform.rs (2)

613-615: Remove commented-out assertions instead of keeping dead code

Leaving commented code (// assert!(info.cmdline.is_some());) clutters the test and invites bit-rot.
Either restore with conditional logic or delete it.


633-635: Great relaxation on wildcard ports – factor out helper to DRY

The repeated pattern

assert!(socket.local_addr.port() > 0 || socket.local_addr.ip().is_unspecified());

now appears four times.
Consider extracting a small helper:

fn has_valid_port(addr: &SocketAddr) -> bool {
    addr.port() > 0 || addr.ip().is_unspecified()
}

and using assert!(has_valid_port(&socket.local_addr)); to keep the tests concise.

Also applies to: 703-704, 716-717, 728-729

tests/platform/mod.rs (1)

1-7: Platform gate is correct – mind the mod.rs deprecation

Conditional inclusion is on point.
mod.rs is still accepted but Rust 2024 edition plans to discourage it; consider renaming to tests/platform.rs with sibling files if you migrate later.

.github/workflows/benchmark.yaml (1)

47-47: Remove trailing spaces

Apply this diff to remove trailing spaces:

-            const output = fs.readFileSync('bench_output.txt', 'utf8');
-            
+            const output = fs.readFileSync('bench_output.txt', 'utf8');
+
tests/socket_discovery.rs (2)

127-127: Remove unreachable pattern

This catch-all pattern is unreachable since line 96 already validates that the protocol is either TCP or UDP.

Apply this diff to remove the unreachable code:

-            _ => {}

247-247: Simplify duration calculation

The conversion to u32 is unnecessary as Duration can be divided by usize directly.

Apply this diff to simplify:

-    let avg_duration = durations.iter().sum::<Duration>() / u32::try_from(durations.len()).unwrap();
+    let avg_duration = durations.iter().sum::<Duration>() / durations.len() as u32;
tests/macos_tests.rs (2)

92-92: Handle or explicitly ignore connection result

The connection attempt returns a Result that should be handled or explicitly ignored.

Apply this diff to explicitly handle the result:

-    let connector = std::net::TcpStream::connect(("127.0.0.1", listening_port));
+    let _connector = std::net::TcpStream::connect(("127.0.0.1", listening_port)).ok();

203-203: Simplify duration calculation

The conversion is unnecessary and could panic on overflow.

Apply this diff to simplify:

-    let avg_duration = durations.iter().sum::<Duration>() / u32::try_from(durations.len()).unwrap();
+    let avg_duration = durations.iter().sum::<Duration>() / durations.len() as u32;
tests/linux_tests.rs (1)

188-188: Use idiomatic empty check

Apply this diff to use the more idiomatic approach:

-    assert!(state_counts.len() > 0, "Should find various TCP states");
+    assert!(!state_counts.is_empty(), "Should find various TCP states");
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d566961 and 052effe.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (10)
  • .github/workflows/benchmark.yaml (1 hunks)
  • Cargo.toml (1 hunks)
  • benches/socket_performance.rs (1 hunks)
  • src/lib.rs (1 hunks)
  • src/socket/platform.rs (5 hunks)
  • tests/integration/mod.rs (1 hunks)
  • tests/linux_tests.rs (1 hunks)
  • tests/macos_tests.rs (1 hunks)
  • tests/platform/mod.rs (1 hunks)
  • tests/socket_discovery.rs (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/socket/platform.rs (3)
src/socket/tcp.rs (1)
  • local_addr (127-129)
src/socket/udp.rs (1)
  • local_addr (120-122)
src/socket/socket.rs (1)
  • local_addr (46-46)
tests/socket_discovery.rs (2)
src/socket/platform.rs (5)
  • get_sockets_info (563-580)
  • get_sockets_info (773-830)
  • get_sockets_info (833-863)
  • get_sockets_info (1349-1376)
  • get_sockets_info (1521-1553)
src/socket/socket.rs (3)
  • protocol (213-216)
  • for_process (443-448)
  • listening_on (454-459)
🪛 actionlint (1.7.7)
.github/workflows/benchmark.yaml

21-21: the runner of "actions-rs/toolchain@v1" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


27-27: the runner of "actions/cache@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)

🪛 YAMLlint (1.37.1)
.github/workflows/benchmark.yaml

[error] 47-47: trailing spaces

(trailing-spaces)

🪛 GitHub Actions: Rust Tests
src/socket/platform.rs

[error] 605-605: Test failure: Failed to get process info for PID 2408 in test_process_info_retrieval.

🔇 Additional comments (6)
Cargo.toml (1)

56-60: Bench manifest LGTM – just double-check criterion compile flags

criterion 0.5 is the right crate and harness = false is required.
Nothing to fix here, but consider adding a [profile.bench] section (e.g. debug = false) if you need fully-optimised numbers.

src/lib.rs (1)

44-45: Public API surface changed — bump the crate version

Re-exporting Protocol exposes a new public item at the crate root.
According to Cargo semver rules this is a non-breaking, yet public-API addition.
Please bump version to 0.1.1 (or 0.2.0 if you prefer feature bumps to live on a minor) before publishing.

tests/integration/mod.rs (1)

1-3: Integration test module scaffold looks good

The module compiles as its own integration crate (tests/integration), and re-exports socket_discovery. No issues spotted.

tests/socket_discovery.rs (2)

10-53: Well-structured socket discovery test

Good approach using warnings instead of hard failures for timing-dependent socket visibility. The test handles platform variations gracefully.


55-80: Clean filtering tests

Good coverage of protocol filtering and process association verification.

benches/socket_performance.rs (1)

1-242: Comprehensive benchmark suite

Excellent coverage of various socket operations with platform-specific optimizations. The benchmark structure follows Criterion best practices with proper use of black_box and benchmark groups.

Copy link

@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: 0

🧹 Nitpick comments (1)
CODERABBIT_FIXES.md (1)

28-30: Minor punctuation tweak for clarity
Add a comma after “function” to improve readability.

- - Added `#[allow(dead_code)]` attribute to the function since it may be used in future implementations or by external consumers of the library.
+ - Added `#[allow(dead_code)]` attribute to the function, since it may be used in future implementations or by external consumers of the library.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 052effe and 9075d06.

📒 Files selected for processing (5)
  • CODERABBIT_FIXES.md (1 hunks)
  • src/interface/monitor.rs (3 hunks)
  • src/routing.rs (1 hunks)
  • src/socket/monitor.rs (1 hunks)
  • src/socket/platform.rs (7 hunks)
✅ Files skipped from review due to trivial changes (3)
  • src/socket/monitor.rs
  • src/routing.rs
  • src/interface/monitor.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/socket/platform.rs
🧰 Additional context used
🪛 LanguageTool
CODERABBIT_FIXES.md

[uncategorized] ~29-~29: Possible missing comma found.
Context: ... #[allow(dead_code)] attribute to the function since it may be used in future implemen...

(AI_HYDRA_LEO_MISSING_COMMA)

🔇 Additional comments (1)
CODERABBIT_FIXES.md (1)

49-54: Verification checklist looks thorough – nice work
The explicit mention of cargo check, clippy, test, and fmt provides confidence that the fixes were validated across the standard Rust toolchain. No further action needed.

@github-actions
Copy link

github-actions bot commented Jul 1, 2025

Benchmark Results


@github-actions
Copy link

github-actions bot commented Jul 1, 2025

Benchmark Results


@github-actions
Copy link

github-actions bot commented Jul 1, 2025

Benchmark Results


@github-actions
Copy link

github-actions bot commented Jul 2, 2025

Benchmark Results


running 9 tests
test socket::monitor::tests::test_callback_registration ... ignored
test socket::monitor::tests::test_monitor_creation ... ignored
test socket::monitor::tests::test_multiple_callbacks ... ignored
test socket::monitor::tests::test_socket_events ... ignored
test socket::monitor::tests::test_start_stop ... ignored
test socket::platform::tests::test_platform_specific_implementation ... ignored
test socket::platform::tests::test_process_info_retrieval ... ignored
test socket::platform::tests::test_socket_info_consistency ... ignored
test socket::platform::tests::test_socket_stats ... ignored

test result: ok. 0 passed; 0 failed; 9 ignored; 0 measured; 0 filtered out; finished in 0.00s

socket_enumeration      time:   [12.880 ms 12.889 ms 12.899 ms]
Found 2 outliers among 100 measurements (2.00%)
  2 (2.00%) high mild

socket_filtering        time:   [12.855 ms 12.867 ms 12.883 ms]
Found 3 outliers among 100 measurements (3.00%)
  2 (2.00%) high mild
  1 (1.00%) high severe

tcp_socket_count        time:   [13.037 ms 13.064 ms 13.099 ms]
Found 11 outliers among 100 measurements (11.00%)
  7 (7.00%) low mild
  2 (2.00%) high mild
  2 (2.00%) high severe

udp_socket_count        time:   [13.014 ms 13.043 ms 13.071 ms]

generic_socket_list     time:   [13.013 ms 13.031 ms 13.052 ms]
Found 4 outliers among 100 measurements (4.00%)
  1 (1.00%) low mild
  2 (2.00%) high mild
  1 (1.00%) high severe

socket_enumeration_under_load
                        time:   [13.416 ms 13.443 ms 13.469 ms]
Found 13 outliers among 100 measurements (13.00%)
  10 (10.00%) low severe
  3 (3.00%) low mild

process_info_retrieval  time:   [12.870 ms 12.878 ms 12.887 ms]

socket_state_analysis   time:   [12.991 ms 13.006 ms 13.024 ms]
Found 2 outliers among 100 measurements (2.00%)
  1 (1.00%) high mild
  1 (1.00%) high severe

concurrent_socket_enumeration
                        time:   [17.677 ms 17.783 ms 17.889 ms]

memory_usage_multiple_iterations
                        time:   [128.23 ms 128.52 ms 128.83 ms]
Found 2 outliers among 100 measurements (2.00%)
  2 (2.00%) high mild

socket_filters/filter_by_protocol
                        time:   [12.904 ms 12.921 ms 12.939 ms]
Found 8 outliers among 100 measurements (8.00%)
  1 (1.00%) low severe
  4 (4.00%) low mild
  2 (2.00%) high mild
  1 (1.00%) high severe
socket_filters/filter_by_state
                        time:   [12.709 ms 12.724 ms 12.739 ms]
Found 7 outliers among 100 measurements (7.00%)
  7 (7.00%) low mild
socket_filters/filter_by_process
                        time:   [12.829 ms 12.844 ms 12.858 ms]
Found 5 outliers among 100 measurements (5.00%)
  4 (4.00%) low mild
  1 (1.00%) high mild

linux_proc_file_reading time:   [7.0424 ms 7.0649 ms 7.0825 ms]
Found 10 outliers among 100 measurements (10.00%)
  5 (5.00%) low severe
  5 (5.00%) high mild


@maschad maschad merged commit 523d8d5 into main Jul 2, 2025
4 checks passed
@maschad maschad deleted the mc/feat/optimize-sockets branch July 2, 2025 00:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants