-
Notifications
You must be signed in to change notification settings - Fork 0
Add echo example and route test utilities #86
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| use std::io; | ||
|
|
||
| use wireframe::{ | ||
| app::{Middleware, WireframeApp}, | ||
| server::WireframeServer, | ||
| }; | ||
|
|
||
| /// Simple middleware demonstrating the `wrap` API. | ||
| /// | ||
| /// `Middleware` has no hooks yet, so this type is just a marker. | ||
| struct Logger; | ||
| impl Middleware for Logger {} | ||
|
|
||
| #[tokio::main] | ||
| async fn main() -> io::Result<()> { | ||
| let factory = || { | ||
| WireframeApp::new() | ||
| .unwrap() | ||
| .wrap(Logger) | ||
| .unwrap() | ||
| .route( | ||
| 1, | ||
| Box::new(|_| { | ||
| Box::pin(async move { | ||
| println!("echo request received"); | ||
| // `WireframeApp` automatically echoes the envelope back. | ||
| }) | ||
| }), | ||
| ) | ||
| .unwrap() | ||
| }; | ||
|
|
||
| WireframeServer::new(factory) | ||
| .bind("127.0.0.1:7878".parse().unwrap())? | ||
| .run() | ||
| .await | ||
| } | ||
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,66 @@ | ||
| use std::sync::{ | ||
| Arc, | ||
| atomic::{AtomicUsize, Ordering}, | ||
| }; | ||
|
|
||
| use bytes::BytesMut; | ||
| use wireframe::{ | ||
| Serializer, | ||
| app::WireframeApp, | ||
| frame::{FrameProcessor, LengthPrefixedProcessor}, | ||
| message::Message, | ||
| serializer::BincodeSerializer, | ||
| }; | ||
|
|
||
| mod util; | ||
| use util::run_app_with_frame; | ||
|
|
||
| #[derive(bincode::Encode, bincode::BorrowDecode, PartialEq, Debug)] | ||
| struct TestEnvelope { | ||
| id: u32, | ||
| msg: Vec<u8>, | ||
| } | ||
|
|
||
| #[derive(bincode::Encode, bincode::BorrowDecode, PartialEq, Debug)] | ||
| struct Echo(u8); | ||
|
|
||
| #[tokio::test] | ||
| async fn handler_receives_message_and_echoes_response() { | ||
| let called = Arc::new(AtomicUsize::new(0)); | ||
| let called_clone = called.clone(); | ||
| let app = WireframeApp::new() | ||
| .unwrap() | ||
| .frame_processor(LengthPrefixedProcessor) | ||
| .route( | ||
| 1, | ||
| Box::new(move |_| { | ||
| let called_inner = called_clone.clone(); | ||
| Box::pin(async move { | ||
| called_inner.fetch_add(1, Ordering::SeqCst); | ||
| // `WireframeApp` sends the envelope back automatically | ||
| }) | ||
| }), | ||
| ) | ||
| .unwrap(); | ||
| let msg_bytes = Echo(42).to_bytes().unwrap(); | ||
| let env = TestEnvelope { | ||
| id: 1, | ||
| msg: msg_bytes, | ||
| }; | ||
| let env_bytes = BincodeSerializer.serialize(&env).unwrap(); | ||
| let mut framed = BytesMut::new(); | ||
| LengthPrefixedProcessor | ||
| .encode(&env_bytes, &mut framed) | ||
| .unwrap(); | ||
|
|
||
| let out = run_app_with_frame(app, framed.to_vec()).await.unwrap(); | ||
|
|
||
| let mut buf = BytesMut::from(&out[..]); | ||
| let frame = LengthPrefixedProcessor.decode(&mut buf).unwrap().unwrap(); | ||
| let (resp_env, _) = BincodeSerializer | ||
| .deserialize::<TestEnvelope>(&frame) | ||
| .unwrap(); | ||
| let (echo, _) = Echo::from_bytes(&resp_env.msg).unwrap(); | ||
| assert_eq!(echo, Echo(42)); | ||
| assert_eq!(called.load(Ordering::SeqCst), 1); | ||
| } |
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 @@ | ||
| use tokio::io::{self, AsyncReadExt, AsyncWriteExt, duplex}; | ||
| use wireframe::app::WireframeApp; | ||
|
|
||
| /// Feed a single frame into `app` and collect the response bytes. | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// Propagates I/O errors from the in-memory connection. | ||
| /// | ||
| /// # Panics | ||
| /// | ||
| /// Panics if the spawned task running the application panics. | ||
| /// Optional duplex buffer capacity for `run_app_with_frame`. | ||
| const DEFAULT_CAPACITY: usize = 4096; | ||
|
|
||
| /// Run `app` with a single input `frame` using the default buffer capacity. | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// Returns any I/O errors encountered while interacting with the in-memory | ||
| /// duplex stream. | ||
| pub async fn run_app_with_frame(app: WireframeApp, frame: Vec<u8>) -> io::Result<Vec<u8>> { | ||
| run_app_with_frame_with_capacity(app, frame, DEFAULT_CAPACITY).await | ||
| } | ||
|
|
||
| /// Drive `app` with a single frame using a duplex buffer of `capacity` bytes. | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// Propagates any I/O errors from the in-memory connection. | ||
| /// | ||
| /// # Panics | ||
| /// | ||
| /// Panics if the spawned task running the application panics. | ||
| pub async fn run_app_with_frame_with_capacity( | ||
| app: WireframeApp, | ||
| frame: Vec<u8>, | ||
| capacity: usize, | ||
| ) -> io::Result<Vec<u8>> { | ||
| let (mut client, server) = duplex(capacity); | ||
| let server_task = tokio::spawn(async move { | ||
| app.handle_connection(server).await; | ||
| }); | ||
|
|
||
| client.write_all(&frame).await?; | ||
| client.shutdown().await?; | ||
|
|
||
| let mut buf = Vec::new(); | ||
| client.read_to_end(&mut buf).await?; | ||
|
|
||
| server_task.await.unwrap(); | ||
| Ok(buf) | ||
| } |
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.
Uh oh!
There was an error while loading. Please reload this page.