Skip to content

refactor: redone concurency model - #7

Merged
bernoussama merged 3 commits into
mainfrom
dev
Jul 24, 2025
Merged

refactor: redone concurency model#7
bernoussama merged 3 commits into
mainfrom
dev

Conversation

@bernoussama

@bernoussama bernoussama commented Jul 24, 2025

Copy link
Copy Markdown
Owner

This pull request refactors the ipou codebase to improve modularity, maintainability, and performance. The most significant changes include reorganizing the code structure, introducing task-based concurrency, and optimizing packet handling. Below is a categorized summary of the key changes:

Code Structure and Organization

  • Moved the Peer struct and IpouError type from src/ipou.rs and src/error.rs respectively to src/lib.rs, consolidating shared types into a central location. The error module was removed. [1] [2] [3]
  • Introduced a new tasks module in src/tasks/mod.rs to encapsulate asynchronous task logic for handling TUN and UDP packets, as well as coordinating results. [1] [2]

Constants and Type Definitions

  • Added constants such as MTU, CHANNEL_BUFFER_SIZE, and ENCRYPTION_OVERHEAD to src/lib.rs for centralized configuration.
  • Defined new types DecryptedPacket and EncryptedPacket for better type clarity and consistency.

Task-Based Concurrency

  • Replaced the monolithic tokio::select! loop in src/main.rs with three concurrent tasks: tun_listener, udp_listener, and result_coordinator. These tasks are spawned using tokio::spawn and managed with tokio::try_join!. [1] [2]
  • Moved the logic for handling TUN and UDP packets to tun_listener and udp_listener functions in the tasks module.

Packet Handling Optimization

  • Updated handle_tun_packet and handle_udp_packet in src/net/mod.rs to use pre-allocated buffers ([u8; MTU] and [u8; MTU + 512]) instead of slices, reducing memory allocations. [1] [2]
  • Encapsulated packet processing logic into the result_coordinator task to streamline the sending of packets to the TUN device and UDP socket.

Minor Cleanup

  • Removed redundant constants and unused imports from src/main.rs after moving them to src/lib.rs.

These changes improve the modularity of the codebase by separating concerns, enhance performance through optimized packet handling, and make the code easier to maintain by introducing clear abstractions for tasks.

Summary by CodeRabbit

  • New Features

    • Introduced improved handling of network packets with new asynchronous tasks for TUN device and UDP socket listeners, as well as a coordinator for packet forwarding.
    • Added new message types and constants for clearer networking and encryption parameter management.
  • Refactor

    • Restructured main application logic for better modularity and concurrency, delegating packet processing to dedicated tasks.
    • Updated function signatures for packet handlers to use more specific types and fixed-size buffers.
  • Chores

    • Removed unused error handling and peer-related code for a cleaner codebase.

@bernoussama
bernoussama requested a review from Copilot July 24, 2025 14:49
@coderabbitai

coderabbitai Bot commented Jul 24, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This update removes the error.rs and ipou.rs modules, eliminating related types. It introduces new constants, message types, and type aliases in lib.rs, and adds a new tasks module for structured asynchronous packet processing. The main function is refactored to use dedicated listener and coordinator tasks, and network handling functions are updated for improved type safety and buffer management.

Changes

File(s) Change Summary
src/error.rs, src/ipou.rs Deleted files; removed custom error type, result alias, and Peer struct.
src/lib.rs Added constants, message types, type aliases, and the tasks module; removed error module.
src/main.rs Refactored main function to use structured concurrency with dedicated async tasks and new message types.
src/net/mod.rs Updated function signatures and buffer management for packet handlers; improved type safety for channels.
src/tasks/mod.rs New module implementing async listeners and coordinator for TUN/UDP packet processing and forwarding.

Sequence Diagram(s)

sequenceDiagram
    participant Main
    participant TunListener
    participant UdpListener
    participant ResultCoordinator
    participant TunDevice
    participant UdpSocket

    Main->>TunListener: spawn tun_listener()
    Main->>UdpListener: spawn udp_listener()
    Main->>ResultCoordinator: spawn result_coordinator()

    TunDevice->>TunListener: Packet received
    TunListener->>ResultCoordinator: EncryptedPacket via channel

    UdpSocket->>UdpListener: Packet received
    UdpListener->>ResultCoordinator: DecryptedPacket via channel

    ResultCoordinator->>TunDevice: Write DecryptedPacket
    ResultCoordinator->>UdpSocket: Send EncryptedPacket
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Poem

In tunnels and sockets, the packets now flow,
With listeners and tasks all ready to go.
Old errors and peers have hopped far away,
As rabbits refactor the network ballet.
Three tasks now juggle, in harmony run—
Hooray for clean code, and more hopping fun! 🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch dev

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 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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Summary of Changes

Hello @bernoussama, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly refactors the ipou codebase by overhauling its concurrency model and improving its overall structure. The changes aim to enhance modularity, maintainability, and performance, particularly in packet handling, by distributing responsibilities across dedicated asynchronous tasks and optimizing memory usage.

Highlights

  • Concurrency Model Redesign: The core change is a shift from a single tokio::select! loop in src/main.rs to a more modular, task-based concurrency model. This involves introducing dedicated tun_listener, udp_listener, and result_coordinator tasks, each handling specific aspects of packet processing, managed by tokio::spawn and tokio::try_join!.
  • Code Structure Reorganization: Shared types like Peer and IpouError have been consolidated into src/lib.rs, and a new src/tasks module has been created to house the new asynchronous task logic, improving overall modularity and separation of concerns. The src/error.rs and src/ipou.rs files were removed as part of this consolidation.
  • Packet Handling Optimization: Packet processing functions (handle_tun_packet, handle_udp_packet) in src/net/mod.rs now utilize pre-allocated fixed-size buffers ([u8; MTU], [u8; MTU + 512]) instead of dynamically sized slices, aiming to reduce memory allocations and potentially improve performance. The result_coordinator task now centralizes the sending of processed packets.
  • Centralized Constants and Types: Key constants (MTU, CHANNEL_BUFFER_SIZE, ENCRYPTION_OVERHEAD) and new type aliases (DecryptedPacket, EncryptedPacket) along with message enums (TunMessage, UdpMessage) have been defined in src/lib.rs for better clarity and centralized configuration.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull Request Overview

This pull request refactors the concurrency model of the ipou codebase to improve modularity and performance. The changes replace a monolithic tokio::select! loop with task-based concurrency using dedicated listener functions and channels for communication.

Key changes include:

  • Introduction of task-based concurrency with separate TUN/UDP listeners and result coordinator
  • Code consolidation by moving shared types and constants to src/lib.rs
  • Optimization of packet handling with pre-allocated fixed-size buffers

Reviewed Changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/tasks/mod.rs New module implementing task-based concurrency with tun_listener, udp_listener, and result_coordinator functions
src/net/mod.rs Updated packet handlers to use fixed-size buffers instead of slices for better performance
src/main.rs Refactored main loop to spawn concurrent tasks using tokio::try_join! instead of tokio::select!
src/lib.rs Consolidated shared types, constants, and error definitions from separate modules
src/ipou.rs Removed file - Peer struct moved to lib.rs
src/error.rs Removed file - error types moved to lib.rs

Comment thread src/tasks/mod.rs
}
}

// Receive enccrypted packets from channel and send to UDP

Copilot AI Jul 24, 2025

Copy link

Choose a reason for hiding this comment

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

The word 'enccrypted' is misspelled. It should be 'encrypted'.

Suggested change
// Receive enccrypted packets from channel and send to UDP
// Receive encrypted packets from channel and send to UDP

Copilot uses AI. Check for mistakes.
Comment thread src/lib.rs
Comment on lines +25 to +32
DecryptedPacket,
Shutdown,
}

pub type EncryptedPacket = (Vec<u8>, SocketAddr);
#[derive(Debug, Clone)]
pub enum UdpMessage {
EncryptedPacket,

Copilot AI Jul 24, 2025

Copy link

Choose a reason for hiding this comment

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

The TunMessage and UdpMessage enums are defined but appear unused. The enum variants don't contain data that would correspond to their names (DecryptedPacket, EncryptedPacket), making the design unclear.

Suggested change
DecryptedPacket,
Shutdown,
}
pub type EncryptedPacket = (Vec<u8>, SocketAddr);
#[derive(Debug, Clone)]
pub enum UdpMessage {
EncryptedPacket,
DecryptedPacket(DecryptedPacket), // Includes the actual packet data
Shutdown,
}
pub type EncryptedPacket = (Vec<u8>, SocketAddr);
#[derive(Debug, Clone)]
pub enum UdpMessage {
EncryptedPacket(EncryptedPacket), // Includes the encrypted packet and its destination

Copilot uses AI. Check for mistakes.
Comment thread src/net/mod.rs Outdated
packet: &mut Vec<u8>,
conf_clone: Arc<Config>,
runtime_conf: Arc<RuntimeConfig>,
utx_clone: mpsc::Sender<(Vec<u8>, SocketAddr)>,

Copilot AI Jul 24, 2025

Copy link

Choose a reason for hiding this comment

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

[nitpick] The parameter name 'utx_clone' suggests it's a clone, but it's actually the original sender passed to the function. Consider renaming to 'etx' or 'encrypted_tx' to match the naming convention used in the tasks module.

Suggested change
utx_clone: mpsc::Sender<(Vec<u8>, SocketAddr)>,
encrypted_tx: mpsc::Sender<(Vec<u8>, SocketAddr)>,

Copilot uses AI. Check for mistakes.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request refactors the application's concurrency model, improving modularity. The review focuses on improving robustness and correctness, specifically around error handling and resource management. The error handling for the joined tasks in main.rs is flawed, and errors from I/O operations in the result_coordinator task are currently ignored. The tun_listener spawns a new task for every incoming packet, which can be inefficient.

Comment thread src/main.rs
Comment on lines +101 to +103
tokio::try_join!(tun_listener, udp_listener, result_coordinator)
.map(|_| ())
.expect("Error joining tasks");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

critical

The .map(|_| ()) call discards the Results returned by the individual tasks. This means if tun_listener or udp_listener returns an IpouError, this error will be silently ignored, and the program will continue to run in a degraded state. The .expect() will only trigger on a JoinError, which typically happens if a task panics, not when it returns an Err.

You should handle both the JoinError from try_join! and the individual Results from each task.

Suggested change
tokio::try_join!(tun_listener, udp_listener, result_coordinator)
.map(|_| ())
.expect("Error joining tasks");
let (tun_res, udp_res, coord_res) = tokio::try_join!(tun_listener, udp_listener, result_coordinator)?;
tun_res?;
udp_res?;
coord_res?;

Comment thread src/tasks/mod.rs
Comment on lines +77 to +80
match dev.send(&decrypted_packet).await {
Ok(_sent) => {},
Err(_e) => {},
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

critical

Errors from dev.send() are silently ignored. This is dangerous as it can hide critical problems with the TUN device, causing silent packet loss. The error should be logged.

                       if let Err(e) = dev.send(&decrypted_packet).await {
                           eprintln!("Error sending packet to TUN device: {e}");
                       }

Comment thread src/tasks/mod.rs
Comment on lines +87 to +93
match sock.send_to(&encrypted_packet, peer_addr).await {
Ok(sent) => {
#[cfg(debug_assertions)]
println!("Sent {sent} bytes to {peer_addr}");
},
Err(_e) => {},
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

critical

Errors from sock.send_to() are silently ignored. This can mask network issues or other problems preventing data from being sent to a peer. This error should be logged.

                       match sock.send_to(&encrypted_packet, peer_addr).await {
                           Ok(sent) => {
                            #[cfg(debug_assertions)]
                            println!("Sent {sent} bytes to {peer_addr}");
                        },
                           Err(e) => {
                               eprintln!("Error sending encrypted packet to peer {peer_addr}: {e}");
                           }
                       }

Comment thread src/lib.rs
Comment on lines +22 to +34
pub type DecryptedPacket = Vec<u8>;
#[derive(Debug, Clone)]
pub enum TunMessage {
DecryptedPacket,
Shutdown,
}

pub type EncryptedPacket = (Vec<u8>, SocketAddr);
#[derive(Debug, Clone)]
pub enum UdpMessage {
EncryptedPacket,
Shutdown,
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The TunMessage and UdpMessage enums are defined but the variants DecryptedPacket in TunMessage and EncryptedPacket in UdpMessage are unit-like and don't carry any data. Consider having them carry data, e.g. TunMessage::Decrypted(DecryptedPacket).

Comment thread src/tasks/mod.rs
Comment on lines +24 to +32
if len >= 20 {
tokio::spawn(crate::net::handle_tun_packet(
tun_buf,
len,
Arc::clone(&conf_clone),
Arc::clone(&runtime_conf),
etx.clone(),
));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The tun_listener spawns a new task for every incoming packet. This "spawn-per-packet" model can be inefficient and lead to resource exhaustion under high packet load due to scheduler overhead and memory consumption. Consider using a bounded worker pool to limit concurrency.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (7)
src/lib.rs (2)

22-34: The enum variants should carry data instead of being unit-like.

The DecryptedPacket variant in TunMessage and EncryptedPacket variant in UdpMessage don't carry any data, making the design unclear. These should hold the actual packet data they represent.


23-34: Remove unused TunMessage and UdpMessage enums

Both TunMessage and UdpMessage are only defined in src/lib.rs and never referenced elsewhere in the codebase. To reduce dead code and avoid confusion, either remove these enums or document their intended future use.

Locations to address:

  • src/lib.rs: lines 23–34

Suggested change (if removing):

- #[derive(Debug, Clone)]
- pub enum TunMessage {
-     DecryptedPacket,
-     Shutdown,
- }
-
- #[derive(Debug, Clone)]
- pub enum UdpMessage {
-     EncryptedPacket,
-     Shutdown,
- }
src/main.rs (1)

101-103: Handle individual task errors properly instead of discarding them.

The .map(|_| ()) discards the Results from individual tasks, which means errors from tun_listener or udp_listener will be silently ignored. Only JoinErrors from panics will be caught.

src/tasks/mod.rs (4)

83-83: Fix typo in comment.


77-80: Log errors when sending to TUN device.

Silently ignoring errors can hide critical problems causing packet loss.


87-93: Log errors when sending to UDP socket.

Network errors should be logged for debugging and monitoring.


24-32: Consider using a bounded worker pool instead of spawn-per-packet.

Spawning a new task for every packet can lead to resource exhaustion under high load.

🧹 Nitpick comments (2)
src/main.rs (1)

57-57: Remove unnecessary Arc clone.

The runtime_config_clone variable is unnecessary since you can reuse runtime_config directly in the udp_listener spawn.

-    let runtime_config_clone = Arc::clone(&runtime_config);
-
     let mut tun_config = tun::Configuration::default();
     let udp_listener = tokio::spawn(tasks::udp_listener(
         Arc::clone(&sock_arc),
-        runtime_config_clone,
+        runtime_config,
         dtx,
     ));

Also applies to: 89-93

src/net/mod.rs (1)

71-71: Remove unnecessary clone when sending packet.

The packet.clone() is unnecessary since packet is a locally owned Vec that can be moved directly.

-                        if let Err(e) = etx.send((packet.clone(), peer.sock_addr)).await {
+                        if let Err(e) = etx.send((packet, peer.sock_addr)).await {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2c87399 and 19f7855.

📒 Files selected for processing (6)
  • src/error.rs (0 hunks)
  • src/ipou.rs (0 hunks)
  • src/lib.rs (1 hunks)
  • src/main.rs (3 hunks)
  • src/net/mod.rs (4 hunks)
  • src/tasks/mod.rs (1 hunks)
💤 Files with no reviewable changes (2)
  • src/ipou.rs
  • src/error.rs
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/main.rs (1)
src/tasks/mod.rs (3)
  • tun_listener (12-35)
  • udp_listener (37-59)
  • result_coordinator (61-97)
src/tasks/mod.rs (2)
src/main.rs (2)
  • mpsc (79-79)
  • mpsc (81-81)
src/net/mod.rs (2)
  • handle_tun_packet (45-90)
  • handle_udp_packet (10-43)
src/net/mod.rs (1)
src/main.rs (2)
  • mpsc (79-79)
  • mpsc (81-81)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (rust)
🔇 Additional comments (2)
src/tasks/mod.rs (2)

18-32: Critical: Buffer reuse causes data races.

The tun_buf is reused in the loop but passed by value to spawned tasks. Since arrays are copied, and the spawned tasks execute asynchronously, the next loop iteration may overwrite the buffer before the spawned task processes it, causing data corruption.

     loop {
         // Listen for TUN packets
         let len = dev.recv(&mut tun_buf).await?;
         // Spawn handler task for each packet
         if len >= 20 {
+            let packet_data = tun_buf[..len].to_vec();
             tokio::spawn(crate::net::handle_tun_packet(
-                tun_buf,
+                packet_data,
                 len,
                 Arc::clone(&conf_clone),
                 Arc::clone(&runtime_conf),
                 etx.clone(),
             ));
         }

Note: This will require updating handle_tun_packet to accept a Vec<u8> instead of a fixed array.

Likely an incorrect or invalid review comment.


42-56: Critical: Buffer reuse causes data races.

Same issue as tun_listener - the udp_buf is reused while spawned tasks may still be reading from it.

     loop {
         // Listen for UDP packets
         let (len, peer_addr) = sock.recv_from(&mut udp_buf).await?;
         // Spawn handler task for each packet
         if len >= 28 {
             // 12 bytes nonce + 16 bytes auth tag
+            let packet_data = udp_buf[..len].to_vec();
             tokio::spawn(crate::net::handle_udp_packet(
-                udp_buf,
+                packet_data,
                 len,
                 peer_addr,
                 Arc::clone(&runtime_conf),
                 dtx.clone(),
             ));
         };

Note: This will require updating handle_udp_packet to accept a Vec<u8> instead of a fixed array.

Likely an incorrect or invalid review comment.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (2)
src/tasks/mod.rs (2)

24-32: Consider using a bounded worker pool instead of spawn-per-packet model

The current implementation spawns a new task for every incoming packet, which can lead to resource exhaustion and scheduler overhead under high packet load.


88-88: Fix typo in comment

The word 'enccrypted' should be 'encrypted'.

-                   // Receive enccrypted packets from channel and send to UDP
+                   // Receive encrypted packets from channel and send to UDP
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 19f7855 and edfac26.

📒 Files selected for processing (1)
  • src/tasks/mod.rs (1 hunks)
🔇 Additional comments (1)
src/tasks/mod.rs (1)

77-85: Good error handling implementation

The error handling for both TUN device and UDP socket operations properly logs errors instead of silently ignoring them, which addresses the previous review concerns.

Also applies to: 92-100

Comment thread src/tasks/mod.rs
Comment on lines +47 to +56
if len >= 28 {
// 12 bytes nonce + 16 bytes auth tag
tokio::spawn(crate::net::handle_udp_packet(
udp_buf,
len,
peer_addr,
Arc::clone(&runtime_conf),
dtx.clone(),
));
};

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.

🛠️ Refactor suggestion

Apply the same worker pool pattern here

Similar to tun_listener, this function also spawns a task per packet which can cause performance issues under load.

🤖 Prompt for AI Agents
In src/tasks/mod.rs around lines 47 to 56, the code currently spawns a new Tokio
task for each UDP packet, which can lead to performance degradation under high
load. Refactor this section to use a worker pool pattern similar to the one used
in tun_listener. Instead of spawning a new task per packet, send the packet data
to a bounded channel or task queue that a fixed number of worker tasks consume,
thereby limiting concurrency and improving resource management.

@bernoussama
bernoussama merged commit 3354239 into main Jul 24, 2025
3 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Jul 27, 2025
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.

2 participants