Skip to content

Implement functional middleware builder#81

Open
leynos wants to merge 2 commits intomainfrom
codex/add-from_fn-constructor-to-middleware
Open

Implement functional middleware builder#81
leynos wants to merge 2 commits intomainfrom
codex/add-from_fn-constructor-to-middleware

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jun 19, 2025

Summary

  • implement middleware::from_fn to build middleware from async closures
  • document middleware usage in the README
  • silence a markdownlint warning in the design doc

Testing

  • make lint
  • make test

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

Summary by Sourcery

Introduce support for functional middleware by implementing a from_fn builder and document its usage, alongside minor markdown lint fixes in project docs.

New Features:

  • Add middleware::from_fn helper to enable building middleware from async functions or closures

Enhancements:

  • Implement FromFn, FnService, and integration with Transform and Service traits to support functional middleware

Documentation:

  • Document the from_fn middleware helper and usage example in the README

Chores:

  • Silence markdownlint warnings and clean up formatting in the design documentation

Summary by CodeRabbit

  • New Features

    • Introduced a flexible middleware mechanism, allowing users to create middleware from asynchronous functions for inspecting or modifying requests and responses.
  • Documentation

    • Added a "Middleware" section to the README with usage examples and explanations.
    • Improved formatting and clarity in the design documentation without altering technical content.

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jun 19, 2025

Reviewer's Guide

Introduces a functional middleware builder that enables creating middleware from async closures, documents its usage in the README, and cleans up the design document formatting to comply with markdownlint.

Class diagram for from_fn helper function

classDiagram
    class from_fn {
        +from_fn(f: F) FromFn<F>
    }
    from_fn --> FromFn : returns
Loading

File-Level Changes

Change Details Files
Functional middleware builder
  • Define FromFn struct and new() constructor
  • Add from_fn helper function
  • Implement FnService with Service and Transform traits
a/src/middleware.rs
b/src/middleware.rs
Middleware documentation
  • Add a ## Middleware section to README
  • Include from_fn usage example with logging closure
a/README.md
b/README.md
Design doc formatting and lint fixes
  • Merge broken lines to comply with MD013
  • Adjust code fence syntax for consistency
  • Remove extra blank lines and insert markdownlint-disable comment
a/docs/rust-binary-router-library-design.md
b/docs/rust-binary-router-library-design.md

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 Jun 19, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This update introduces a new function-based middleware abstraction in the codebase, allowing middleware to be constructed from asynchronous functions or closures. Documentation is updated to explain this mechanism, and editorial improvements are made to a design document. No changes are made to existing public APIs except for the new middleware feature.

Changes

File(s) Change Summary
README.md Added "Middleware" section documenting new function-based middleware and usage example.
docs/rust-binary-router-library-design.md Formatting, markdown, and editorial improvements; no content or logic changes.
src/middleware.rs Added FromFn<F>, from_fn, and FnService<S, F> for function-based async middleware; new traits implemented.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Middleware (FromFn)
    participant Next/Service

    Client->>Middleware (FromFn): send ServiceRequest
    Middleware (FromFn)->>Next/Service: call next with ServiceRequest
    Next/Service-->>Middleware (FromFn): return ServiceResponse
    Middleware (FromFn)-->>Client: return (possibly modified) ServiceResponse
Loading

Possibly related PRs

Poem

In the meadow of code, a new path appears,
Middleware from functions, reducing our fears.
With async and closure, requests hop through,
Logging and tweaking, as rabbits oft do.
Documentation polished, the story now clear—
🐇 Cheers for new middleware, let’s all give a cheer!

✨ Finishing Touches
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in Comment
  • Commit Unit Tests in branch codex/add-from_fn-constructor-to-middleware

🪧 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 auto-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
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 and they look great!

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `src/middleware.rs:96` </location>
<code_context>
+/// The function receives a [`ServiceRequest`] and a [`Next`] reference to invoke
+/// the remaining middleware chain. It must return a [`ServiceResponse`] wrapped
+/// in a [`Result`]. The error type is the same as the wrapped service.
+pub struct FromFn<F> {
+    f: F,
+}
</code_context>

<issue_to_address>
The module is missing a containing item comment (`//!`).

Please add a module-level doc comment at the top of the file using `//!` to describe the purpose of this module.
</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/middleware.rs
/// The function receives a [`ServiceRequest`] and a [`Next`] reference to invoke
/// the remaining middleware chain. It must return a [`ServiceResponse`] wrapped
/// in a [`Result`]. The error type is the same as the wrapped service.
pub struct FromFn<F> {
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 (review_instructions): The module is missing a containing item comment (//!).

Please add a module-level doc comment at the top of the file using //! to describe the purpose of this module.

Review instructions:

Path patterns: **/*.rs

Instructions:
All modules MUST have a containing item comment (//!)

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

🔭 Outside diff range comments (1)
docs/rust-binary-router-library-design.md (1)

1085-1123: Fix code formatting issues in the example.

The code example has several formatting and syntax issues that need correction.

-     use std::time::{SystemTime, UNIX_EPOCH};
-     // Define a message ID enum if not using type-based routing directly
-     enum MyMessageType { Echo = 1 }
-     // Handler function
+     use std::time::{SystemTime, UNIX_EPOCH};
+
+     // Define a message ID enum if not using type-based routing directly
+     enum MyMessageType { Echo = 1 }
+
+     // Handler function
      async fn handle_echo(req: Message<EchoRequest>) -> WireframeResult<EchoResponse> {
          println!("Received echo request with payload: {}", req.payload);
          Ok(EchoResponse {
              original_payload: req.payload.clone(),
-             echoed_at: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs().
+             echoed_at: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(),
          })
      }
-     #[tokio::main] async fn main() -> std::io::Result\<()> { println!("Starting echo server on 127.0.0.1:8000");
+
+     #[tokio::main]
+     async fn main() -> std::io::Result<()> {
+         println!("Starting echo server on 127.0.0.1:8000");
+
      WireframeServer::new(|| {
          WireframeApp::new()
              //.frame_processor(LengthPrefixedCodec) // Simplified
@@ -1111,13 +1111,7 @@
          .run()
          .await
      }
-  This example, even in outline, demonstrates how derive macros for messages, a
-  separable framing component, and a clear handler signature with extractors
-  (`Message<EchoRequest>`) and a return type (`WireframeResult<EchoResponse>`)
-  simplify server implementation.
-
-  ```
-
-  ```
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b58662e and d21cd58.

📒 Files selected for processing (3)
  • README.md (1 hunks)
  • docs/rust-binary-router-library-design.md (17 hunks)
  • src/middleware.rs (1 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/rust-binary-router-library-design.md

[grammar] ~333-~333: The verb ‘derives’ is singular. Did you mean: “this derives” or “these derive”?
Context: ...rait in the library currently exposes these derives under a convenient Message trait, pro...

(SINGULAR_VERB_AFTER_THESE_OR_THOSE)


[uncategorized] ~769-~769: Loose punctuation mark.
Context: ...r_addr()); } ``` - SharedState<T>: Allows handlers to access shared applic...

(UNLIKELY_OPENING_PUNCTUATION)


[grammar] ~813-~813: Please add a punctuation mark at the end of paragraph.
Context: ...erate on "wireframe's" internal request and response types, which could be raw f...

(PUNCTUATION_PARAGRAPH_END)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build-test
🔇 Additional comments (7)
docs/rust-binary-router-library-design.md (1)

332-334: Fix grammatical error in documentation.

The static analysis tool correctly identified a grammar issue. The phrase "these derives" should be "this derives" since it refers to a single wrapper trait.

-  `bincode` 11 or `postcard`.12 A minimal wrapper trait in the library currently
-  exposes these derives under a convenient `Message` trait, providing `to_bytes`
-  and `from_bytes` helpers.
+  `bincode` 11 or `postcard`.12 A minimal wrapper trait in the library currently
+  exposes this derives under a convenient `Message` trait, providing `to_bytes`
+  and `from_bytes` helpers.

Likely an incorrect or invalid review comment.

src/middleware.rs (5)

29-49: LGTM! Well-documented constructor with proper attributes.

The implementation correctly uses #[inline], #[must_use], and provides comprehensive documentation with examples.


91-103: LGTM! Clean and simple middleware wrapper.

The FromFn<F> struct provides a clean abstraction for function-based middleware with an appropriate constructor.


105-131: Excellent documentation and API design.

The from_fn convenience function is well-documented with a comprehensive example that demonstrates the expected function signature and usage pattern.


154-168: LGTM! Proper Transform implementation.

The Transform implementation correctly creates the FnService with the appropriate service and function, enabling the middleware to be used in a middleware chain.


142-143: ```shell
#!/bin/bash
sed -n '120,180p' src/middleware.rs


</details>
<details>
<summary>README.md (1)</summary>

`109-124`: **Excellent documentation of the new middleware feature.**

The middleware section provides a clear, concise explanation with a practical example using the `tracing` crate. The example demonstrates the key concepts: receiving a request, calling the next handler, and processing the response.



The documentation correctly shows:
- Import of `from_fn` 
- Async closure syntax with move semantics
- Use of `next.call(req).await?` for chain progression
- Proper error propagation with `?` operator
- Practical logging example with `tracing::info!`

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Comment on lines +544 to +547
<!-- markdownlint-disable-next-line MD013 -->
| msg_header: &CommandHeader | msg_header.sub_type == CommandSubType::Special, handle_special_command ).message(MessageType::GenericCommand, handle_generic_command) // Fallback ``` |

````
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 malformed code block and improve readability.

The code block appears to have formatting issues with incomplete backticks and inconsistent indentation.

-  ````rust
-  Router::new()
-    .message_guarded(
-         MessageType::GenericCommand,
-         <!-- markdownlint-disable-next-line MD013 -->
-         | msg_header: &CommandHeader | msg_header.sub_type == CommandSubType::Special, handle_special_command ).message(MessageType::GenericCommand, handle_generic_command) // Fallback ``` |
-  ````
+  ```rust
+  Router::new()
+      .message_guarded(
+          MessageType::GenericCommand,
+          |msg_header: &CommandHeader| msg_header.sub_type == CommandSubType::Special,
+          handle_special_command
+      )
+      .message(MessageType::GenericCommand, handle_generic_command) // Fallback
+  ```
🤖 Prompt for AI Agents
In docs/rust-binary-router-library-design.md around lines 544 to 547, the code
block is malformed with incomplete backticks and inconsistent indentation. Fix
this by properly enclosing the code block with triple backticks and specifying
the language as rust. Also, reformat the code inside to have consistent
indentation and remove any HTML comments or inline markdownlint disables,
ensuring the code is clean and readable.

Comment on lines +813 to 814
Middleware would operate on "wireframe's" internal request and

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

Complete the sentence fragment.

The static analysis tool identified an incomplete sentence that needs proper punctuation.

-- The `Service` trait would define the actual request/response processing logic.
-  Middleware would operate on "wireframe's" internal request and
+- The `Service` trait would define the actual request/response processing logic.
+  Middleware would operate on "wireframe's" internal request and response types, 
+  which could be raw frames at one level or deserialized messages at another, 
+  depending on the middleware's purpose.

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 LanguageTool

[grammar] ~813-~813: Please add a punctuation mark at the end of paragraph.
Context: ...erate on "wireframe's" internal request and response types, which could be raw f...

(PUNCTUATION_PARAGRAPH_END)

🤖 Prompt for AI Agents
In docs/rust-binary-router-library-design.md around lines 813 to 814, the
sentence fragment "Middleware would operate on 'wireframe's' internal request
and" is incomplete. Complete the sentence by adding the missing part or
punctuation to form a full, clear sentence.

Comment thread src/middleware.rs
Comment on lines +142 to +151
F: for<'a> Fn(ServiceRequest, Next<'a, S>) -> Fut + Send + Sync + Clone,
Fut: std::future::Future<Output = Result<ServiceResponse, S::Error>> + Send,
{
type Error = S::Error;

async fn call(&self, req: ServiceRequest) -> Result<ServiceResponse, Self::Error> {
let next = Next::new(&self.service);
(self.f.clone())(req, next).await
}
}
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.

🧹 Nitpick (assertive)

Review the cloning strategy for performance implications.

The implementation clones the function F on every call, which could have performance implications for complex closures or when the middleware captures large amounts of data.

Consider whether the cloning is necessary or if there's a more efficient approach:

async fn call(&self, req: ServiceRequest) -> Result<ServiceResponse, Self::Error> {
    let next = Next::new(&self.service);
    // Consider if cloning can be avoided or moved to construction time
    (self.f.clone())(req, next).await
}

The current approach is correct for the typical use case of simple function pointers or lightweight closures, but document this behaviour if it's intentional.

🤖 Prompt for AI Agents
In src/middleware.rs around lines 142 to 151, the call method clones the
function F on every invocation, which may impact performance if F is a complex
closure or captures large data. To fix this, evaluate if cloning can be avoided
by either storing F in a way that allows borrowing instead of cloning or by
moving the clone operation to the middleware construction phase rather than per
call. If cloning is necessary, add documentation explaining this design choice
and its implications for performance.

Fixes broken code fences and syntax in the illustrative server example.
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