-
Notifications
You must be signed in to change notification settings - Fork 0
Add ping-pong example with middleware #105
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
leynos
wants to merge
10
commits into
main
Choose a base branch
from
codex/expand-examples-with-routing-and-middleware-demo
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
20e7fdc
Document new examples
leynos df8d1a6
Refine ping-pong example
leynos 423eca4
Refine ping-pong example
leynos 699f152
Refactor ping-pong builder to use Result
leynos cf28e2e
Handle ping overflow
leynos c0d8356
Improve ping-pong example
leynos e4c117b
Merge branch 'main' into codex/expand-examples-with-routing-and-middl…
leynos b1b7219
Add docs for ping-pong example
leynos 74351eb
Clarify HandlerService usage
leynos 0da488e
Add netcat usage example for echo
leynos File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
# Ping-Pong Example | ||
|
||
This example demonstrates routing, serialization, and middleware usage in a | ||
small ping/pong protocol. The server accepts a `Ping` message containing a | ||
counter and responds with a `Pong` containing the incremented value. Logging | ||
middleware prints each request and response. | ||
|
||
```mermaid | ||
classDiagram | ||
class Ping { | ||
+u32 0 | ||
+to_bytes() | ||
+from_bytes() | ||
} | ||
class Pong { | ||
+u32 0 | ||
+to_bytes() | ||
+from_bytes() | ||
} | ||
class ErrorMsg { | ||
+String 0 | ||
+to_bytes() | ||
+from_bytes() | ||
} | ||
class PongMiddleware { | ||
} | ||
class PongService { | ||
+inner: S | ||
+call(req: ServiceRequest) Result<ServiceResponse, Infallible> | ||
} | ||
class Logging { | ||
} | ||
class LoggingService { | ||
+inner: S | ||
+call(req: ServiceRequest) Result<ServiceResponse, Infallible> | ||
} | ||
class HandlerService { | ||
+id() | ||
+from_service(id, service) | ||
} | ||
PongMiddleware --|> Transform | ||
PongService --|> Service | ||
Logging --|> Transform | ||
LoggingService --|> Service | ||
HandlerService <.. PongService : inner | ||
HandlerService <.. LoggingService : inner | ||
PongMiddleware ..> HandlerService : transform | ||
Logging ..> HandlerService : transform | ||
WireframeApp <.. build_app : factory | ||
WireframeServer <.. main : uses | ||
build_app --> WireframeApp | ||
main --> WireframeServer | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,148 @@ | ||
use std::{io, net::SocketAddr, sync::Arc}; | ||
|
||
use async_trait::async_trait; | ||
use wireframe::{ | ||
app::{Result as AppResult, WireframeApp}, | ||
message::Message, | ||
middleware::{HandlerService, Service, ServiceRequest, ServiceResponse, Transform}, | ||
serializer::BincodeSerializer, | ||
server::WireframeServer, | ||
}; | ||
|
||
#[derive(bincode::Encode, bincode::BorrowDecode, Debug)] | ||
struct Ping(u32); | ||
|
||
#[derive(bincode::Encode, bincode::BorrowDecode, Debug)] | ||
struct Pong(u32); | ||
|
||
#[derive(bincode::Encode, bincode::BorrowDecode, Debug)] | ||
struct ErrorMsg(String); | ||
|
||
fn encode_error(msg: impl Into<String>) -> Vec<u8> { | ||
let err = ErrorMsg(msg.into()); | ||
match err.to_bytes() { | ||
Ok(bytes) => bytes, | ||
Err(e) => { | ||
eprintln!("failed to encode error: {e:?}"); | ||
Vec::new() | ||
} | ||
} | ||
} | ||
|
||
const PING_ID: u32 = 1; | ||
|
||
/// Handler invoked for `PING_ID` messages. | ||
/// | ||
/// The middleware chain generates the actual response, so this | ||
/// handler intentionally performs no work. | ||
#[allow(clippy::unused_async)] | ||
async fn ping_handler() {} | ||
|
||
struct PongMiddleware; | ||
|
||
struct PongService<S> { | ||
inner: S, | ||
} | ||
|
||
#[async_trait] | ||
impl<S> Service for PongService<S> | ||
where | ||
S: Service<Error = std::convert::Infallible> + Send + Sync + 'static, | ||
{ | ||
type Error = std::convert::Infallible; | ||
|
||
async fn call(&self, req: ServiceRequest) -> Result<ServiceResponse, Self::Error> { | ||
let (ping_req, _) = match Ping::from_bytes(req.frame()) { | ||
Ok(val) => val, | ||
Err(e) => { | ||
eprintln!("failed to decode ping: {e:?}"); | ||
return Ok(ServiceResponse::new(encode_error(format!( | ||
"decode error: {e:?}" | ||
)))); | ||
} | ||
}; | ||
let mut response = self.inner.call(req).await?; | ||
let pong_resp = if let Some(v) = ping_req.0.checked_add(1) { | ||
Pong(v) | ||
} else { | ||
eprintln!("ping overflowed at {}", ping_req.0); | ||
return Ok(ServiceResponse::new(encode_error("overflow"))); | ||
}; | ||
match pong_resp.to_bytes() { | ||
Ok(bytes) => *response.frame_mut() = bytes, | ||
Err(e) => { | ||
eprintln!("failed to encode pong: {e:?}"); | ||
return Ok(ServiceResponse::new(encode_error(format!( | ||
"encode error: {e:?}" | ||
)))); | ||
} | ||
} | ||
Ok(response) | ||
} | ||
} | ||
|
||
#[async_trait] | ||
impl Transform<HandlerService> for PongMiddleware { | ||
type Output = HandlerService; | ||
|
||
// `HandlerService` is a boxed trait object without generic parameters, | ||
// so the transform signature uses the concrete type directly. | ||
async fn transform(&self, service: HandlerService) -> Self::Output { | ||
let id = service.id(); | ||
HandlerService::from_service(id, PongService { inner: service }) | ||
} | ||
} | ||
|
||
struct Logging; | ||
|
||
struct LoggingService<S> { | ||
inner: S, | ||
} | ||
|
||
#[async_trait] | ||
impl<S> Service for LoggingService<S> | ||
where | ||
S: Service<Error = std::convert::Infallible> + Send + Sync + 'static, | ||
{ | ||
type Error = std::convert::Infallible; | ||
|
||
async fn call(&self, req: ServiceRequest) -> Result<ServiceResponse, Self::Error> { | ||
println!("request: {:?}", req.frame()); | ||
let resp = self.inner.call(req).await?; | ||
println!("response: {:?}", resp.frame()); | ||
Ok(resp) | ||
} | ||
} | ||
|
||
#[async_trait] | ||
impl Transform<HandlerService> for Logging { | ||
type Output = HandlerService; | ||
|
||
// `HandlerService` is a concrete type, not a generic wrapper. | ||
async fn transform(&self, service: HandlerService) -> Self::Output { | ||
let id = service.id(); | ||
HandlerService::from_service(id, LoggingService { inner: service }) | ||
} | ||
} | ||
|
||
fn build_app() -> AppResult<WireframeApp> { | ||
WireframeApp::new()? | ||
.serializer(BincodeSerializer) | ||
.route(PING_ID, Arc::new(|_| Box::pin(ping_handler())))? | ||
.wrap(PongMiddleware)? | ||
.wrap(Logging) | ||
} | ||
|
||
#[tokio::main] | ||
async fn main() -> io::Result<()> { | ||
let factory = || build_app().expect("app build failed"); | ||
|
||
let default_addr = "127.0.0.1:7878"; | ||
let addr_str = std::env::args() | ||
.nth(1) | ||
.unwrap_or_else(|| default_addr.into()); | ||
let addr: SocketAddr = addr_str | ||
.parse() | ||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; | ||
WireframeServer::new(factory).bind(addr)?.run().await | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧹 Nitpick (assertive)
Consider using em dashes for consistency.
The documentation uses regular hyphens in the example descriptions. Consider using em dashes for better typographical consistency.
Also applies to: 212-212
🧰 Tools
🪛 LanguageTool
[typographical] ~209-~209: Consider using an em dash in dialogues and enumerations.
Context: ...the
examples/
directory: -echo.rs
– minimal echo server using routing - `pa...(DASH_RULE)
🤖 Prompt for AI Agents