-
Notifications
You must be signed in to change notification settings - Fork 0
Implement trait foundations #8
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
Changes from all commits
175c11b
6008d78
c3fbe27
8ee8a59
a17e4dc
ea3a7a8
ac17228
6acff82
601045b
b711bcf
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,127 @@ | ||
use std::net::SocketAddr; | ||
use std::sync::Arc; | ||
|
||
/// Request context passed to extractors. | ||
/// | ||
/// This type contains metadata about the current connection and provides | ||
/// access to application state registered with [`WireframeApp`]. | ||
#[derive(Default)] | ||
pub struct MessageRequest { | ||
/// Address of the peer that sent the current message. | ||
pub peer_addr: Option<SocketAddr>, | ||
} | ||
|
||
/// Raw payload buffer handed to extractors. | ||
#[derive(Default)] | ||
pub struct Payload<'a> { | ||
/// Incoming bytes not yet processed. | ||
pub data: &'a [u8], | ||
} | ||
|
||
impl Payload<'_> { | ||
/// Advances the payload by `count` bytes. | ||
/// | ||
/// Consumes up to `count` bytes from the front of the slice, ensuring we | ||
/// never slice beyond the available buffer. | ||
pub fn advance(&mut self, count: usize) { | ||
let n = count.min(self.data.len()); | ||
self.data = &self.data[n..]; | ||
} | ||
|
||
/// Returns the number of bytes remaining. | ||
#[must_use] | ||
pub fn remaining(&self) -> usize { | ||
self.data.len() | ||
} | ||
} | ||
|
||
/// Trait for extracting data from a [`MessageRequest`]. | ||
pub trait FromMessageRequest: Sized { | ||
/// Error type returned when extraction fails. | ||
type Error: std::error::Error + Send + Sync + 'static; | ||
|
||
/// Perform extraction from the request and payload. | ||
/// | ||
/// # Errors | ||
/// | ||
/// Returns an error if extraction fails. | ||
fn from_message_request( | ||
req: &MessageRequest, | ||
payload: &mut Payload<'_>, | ||
) -> Result<Self, Self::Error>; | ||
} | ||
|
||
/// Shared application state accessible to handlers. | ||
#[derive(Clone)] | ||
pub struct SharedState<T: Send + Sync>(Arc<T>); | ||
|
||
impl<T: Send + Sync> SharedState<T> { | ||
/// Construct a new [`SharedState`]. | ||
/// | ||
/// # Examples | ||
/// | ||
/// ```ignore | ||
/// use std::sync::Arc; | ||
/// use wireframe::extractor::SharedState; | ||
/// | ||
/// let data = Arc::new(5u32); | ||
/// let state = SharedState::new(Arc::clone(&data)); | ||
/// assert_eq!(*state, 5); | ||
/// ``` | ||
#[must_use] | ||
|
||
#[cfg(test)] | ||
leynos marked this conversation as resolved.
Show resolved
Hide resolved
|
||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn advance_consumes_bytes() { | ||
let mut payload = Payload { data: b"hello" }; | ||
payload.advance(2); | ||
assert_eq!(payload.data, b"llo"); | ||
payload.advance(10); | ||
assert!(payload.data.is_empty()); | ||
} | ||
|
||
#[test] | ||
fn remaining_reports_length() { | ||
let mut payload = Payload { data: b"abc" }; | ||
assert_eq!(payload.remaining(), 3); | ||
payload.advance(1); | ||
assert_eq!(payload.remaining(), 2); | ||
} | ||
} | ||
/// Creates a new `SharedState` instance wrapping the provided `Arc<T>`. | ||
/// | ||
/// # Examples | ||
/// | ||
/// ``` | ||
/// use std::sync::Arc; | ||
/// let state = Arc::new(42); | ||
/// let shared = SharedState::new(state.clone()); | ||
/// assert_eq!(*shared, 42); | ||
/// ``` | ||
pub fn new(inner: Arc<T>) -> Self { | ||
Self(inner) | ||
} | ||
} | ||
|
||
impl<T: Send + Sync> std::ops::Deref for SharedState<T> { | ||
type Target = T; | ||
|
||
/// Returns a reference to the inner shared state value. | ||
/// | ||
/// This allows transparent access to the underlying state managed by `SharedState`. | ||
/// | ||
/// # Examples | ||
/// | ||
/// ``` | ||
/// use std::sync::Arc; | ||
/// let state = Arc::new(42); | ||
/// let shared = SharedState::new(state.clone()); | ||
/// assert_eq!(*shared, 42); | ||
/// ``` | ||
fn deref(&self) -> &Self::Target { | ||
&self.0 | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
use async_trait::async_trait; | ||
use bytes::BytesMut; | ||
|
||
/// Trait defining how raw bytes are decoded into frames and how frames are | ||
/// encoded back into bytes for transmission. | ||
/// | ||
/// The `Frame` associated type represents a logical unit extracted from or | ||
/// written to the wire. Errors are represented by the `Error` associated type, | ||
/// which must implement [`std::error::Error`]. | ||
#[async_trait] | ||
pub trait FrameProcessor: Send + Sync { | ||
/// Logical frame type extracted from the stream. | ||
type Frame; | ||
|
||
/// Error type returned by `decode` and `encode`. | ||
type Error: std::error::Error + Send + Sync + 'static; | ||
|
||
/// Attempt to decode the next frame from `src`. | ||
async fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Frame>, Self::Error>; | ||
|
||
/// Encode `frame` and append the bytes to `dst`. | ||
async fn encode(&mut self, frame: &Self::Frame, dst: &mut BytesMut) -> Result<(), Self::Error>; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,6 @@ | ||
pub mod app; | ||
pub mod extractor; | ||
pub mod frame; | ||
pub mod message; | ||
pub mod middleware; | ||
pub mod server; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
use async_trait::async_trait; | ||
|
||
/// Incoming request wrapper passed through middleware. | ||
#[derive(Debug)] | ||
pub struct ServiceRequest; | ||
|
||
/// Response produced by a handler or middleware. | ||
#[derive(Debug, Default)] | ||
pub struct ServiceResponse; | ||
|
||
/// Continuation used by middleware to call the next service in the chain. | ||
pub struct Next<'a, S> | ||
where | ||
S: Service + ?Sized, | ||
{ | ||
service: &'a S, | ||
} | ||
|
||
impl<'a, S> Next<'a, S> | ||
where | ||
S: Service + ?Sized, | ||
{ | ||
/// Creates a new `Next` instance wrapping a reference to the given service. | ||
/// | ||
/// | ||
/// ```ignore | ||
/// use wireframe::middleware::{ServiceRequest, ServiceResponse, Next, Service}; | ||
/// ``` | ||
/// Service produced by the middleware. | ||
type Wrapped: Service; | ||
async fn transform(&self, service: S) -> Self::Wrapped; | ||
Comment on lines
+30
to
+31
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. issue: Invalid associated items inside Move |
||
/// let service = MyService::default(); | ||
/// let next = Next::new(&service); | ||
type Wrapped: Service; | ||
async fn transform(&self, service: S) -> Self::Wrapped; | ||
Self { service } | ||
} | ||
|
||
/// Call the next service with the given request. | ||
/// | ||
/// # Errors | ||
/// | ||
/// Asynchronously invokes the next service in the middleware chain with the given request. | ||
/// | ||
/// Returns the response from the wrapped service, or propagates any error produced. | ||
/// | ||
/// # Examples | ||
/// | ||
/// ``` | ||
/// # use your_crate::{ServiceRequest, ServiceResponse, Next, Service}; | ||
/// # struct DummyService; | ||
/// # #[async_trait::async_trait] | ||
/// # impl Service for DummyService { | ||
/// # type Error = std::convert::Infallible; | ||
/// # async fn call(&self, _req: ServiceRequest) -> Result<ServiceResponse, Self::Error> { | ||
/// # Ok(ServiceResponse::default()) | ||
/// # } | ||
/// # } | ||
/// # let service = DummyService; | ||
/// let next = Next::new(&service); | ||
/// let req = ServiceRequest {}; | ||
/// let res = tokio_test::block_on(next.call(req)); | ||
/// assert!(res.is_ok()); | ||
/// ``` | ||
pub async fn call(&self, req: ServiceRequest) -> Result<ServiceResponse, S::Error> { | ||
self.service.call(req).await | ||
} | ||
} | ||
|
||
/// Trait representing an asynchronous service. | ||
#[async_trait] | ||
pub trait Service: Send + Sync { | ||
/// Error type returned by the service. | ||
type Error: std::error::Error + Send + Sync + 'static; | ||
|
||
/// Handle the incoming request and produce a response. | ||
async fn call(&self, req: ServiceRequest) -> Result<ServiceResponse, Self::Error>; | ||
} | ||
|
||
/// Factory for wrapping services with middleware. | ||
#[async_trait] | ||
pub trait Transform<S>: Send + Sync | ||
leynos marked this conversation as resolved.
Show resolved
Hide resolved
|
||
where | ||
S: Service, | ||
{ | ||
/// Wrapped service produced by the middleware. | ||
type Output: Service; | ||
|
||
/// Create a new middleware service wrapping `service`. | ||
async fn transform(&self, service: S) -> Self::Output; | ||
} |
Uh oh!
There was an error while loading. Please reload this page.