Skip to main content

embedded_svc/http/
server.rs

1use core::fmt::Debug;
2
3use crate::io::{Error, Read, Write};
4
5pub use super::{Headers, Method, Query, Status};
6pub use crate::io::ErrorType;
7
8#[derive(Debug)]
9#[cfg_attr(feature = "defmt", derive(defmt::Format))]
10pub struct Request<C>(C);
11
12impl<C> Request<C>
13where
14    C: Connection,
15{
16    pub fn wrap(connection: C) -> Request<C> {
17        if connection.is_response_initiated() {
18            panic!("connection is not in request phase");
19        }
20
21        Request(connection)
22    }
23
24    pub fn split(&mut self) -> (&C::Headers, &mut C::Read) {
25        self.0.split()
26    }
27
28    pub fn into_response<'b>(
29        mut self,
30        status: u16,
31        message: Option<&'b str>,
32        headers: &'b [(&'b str, &'b str)],
33    ) -> Result<Response<C>, C::Error> {
34        self.0.initiate_response(status, message, headers)?;
35
36        Ok(Response(self.0))
37    }
38
39    pub fn into_status_response(self, status: u16) -> Result<Response<C>, C::Error> {
40        self.into_response(status, None, &[])
41    }
42
43    pub fn into_ok_response(self) -> Result<Response<C>, C::Error> {
44        self.into_response(200, Some("OK"), &[])
45    }
46
47    pub fn connection(&mut self) -> &mut C {
48        &mut self.0
49    }
50
51    pub fn release(self) -> C {
52        self.0
53    }
54
55    pub fn uri(&self) -> &'_ str {
56        self.0.uri()
57    }
58
59    pub fn method(&self) -> Method {
60        self.0.method()
61    }
62
63    pub fn header(&self, name: &str) -> Option<&'_ str> {
64        self.0.header(name)
65    }
66
67    pub fn read(&mut self, buf: &mut [u8]) -> Result<usize, C::Error> {
68        self.0.read(buf)
69    }
70}
71
72impl<C> ErrorType for Request<C>
73where
74    C: ErrorType,
75{
76    type Error = C::Error;
77}
78
79impl<C> Read for Request<C>
80where
81    C: Connection,
82{
83    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
84        Request::read(self, buf)
85    }
86}
87
88impl<C> Headers for Request<C>
89where
90    C: Connection,
91{
92    fn header(&self, name: &str) -> Option<&'_ str> {
93        Request::header(self, name)
94    }
95}
96
97impl<C> Query for Request<C>
98where
99    C: Connection,
100{
101    fn uri(&self) -> &'_ str {
102        Request::uri(self)
103    }
104
105    fn method(&self) -> Method {
106        Request::method(self)
107    }
108}
109
110#[derive(Debug)]
111#[cfg_attr(feature = "defmt", derive(defmt::Format))]
112pub struct Response<C>(C);
113
114impl<C> Response<C>
115where
116    C: Connection,
117{
118    pub fn wrap(connection: C) -> Response<C> {
119        if !connection.is_response_initiated() {
120            panic!("connection is not in response phase");
121        }
122
123        Response(connection)
124    }
125
126    pub fn connection(&mut self) -> &mut C {
127        &mut self.0
128    }
129
130    pub fn release(self) -> C {
131        self.0
132    }
133
134    pub fn write(&mut self, buf: &[u8]) -> Result<usize, C::Error> {
135        self.0.write(buf)
136    }
137
138    pub fn flush(&mut self) -> Result<(), C::Error> {
139        self.0.flush()
140    }
141}
142
143impl<C> ErrorType for Response<C>
144where
145    C: ErrorType,
146{
147    type Error = C::Error;
148}
149
150impl<C> Write for Response<C>
151where
152    C: Connection,
153{
154    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
155        Response::write(self, buf)
156    }
157
158    fn flush(&mut self) -> Result<(), Self::Error> {
159        Response::flush(self)
160    }
161}
162
163pub trait Connection: Query + Headers + Read + Write {
164    type Headers: Query + Headers;
165
166    type Read: Read<Error = Self::Error>;
167
168    type RawConnectionError: Error;
169
170    type RawConnection: Read<Error = Self::RawConnectionError>
171        + Write<Error = Self::RawConnectionError>;
172
173    fn split(&mut self) -> (&Self::Headers, &mut Self::Read);
174
175    fn initiate_response<'a>(
176        &'a mut self,
177        status: u16,
178        message: Option<&'a str>,
179        headers: &'a [(&'a str, &'a str)],
180    ) -> Result<(), Self::Error>;
181
182    fn is_response_initiated(&self) -> bool;
183
184    fn raw_connection(&mut self) -> Result<&mut Self::RawConnection, Self::Error>;
185}
186
187impl<C> Connection for &mut C
188where
189    C: Connection,
190{
191    type Headers = C::Headers;
192
193    type Read = C::Read;
194
195    type RawConnectionError = C::RawConnectionError;
196
197    type RawConnection = C::RawConnection;
198
199    fn split(&mut self) -> (&Self::Headers, &mut Self::Read) {
200        (*self).split()
201    }
202
203    fn initiate_response<'a>(
204        &'a mut self,
205        status: u16,
206        message: Option<&'a str>,
207        headers: &'a [(&'a str, &'a str)],
208    ) -> Result<(), Self::Error> {
209        (*self).initiate_response(status, message, headers)
210    }
211
212    fn is_response_initiated(&self) -> bool {
213        (**self).is_response_initiated()
214    }
215
216    fn raw_connection(&mut self) -> Result<&mut Self::RawConnection, Self::Error> {
217        (*self).raw_connection()
218    }
219}
220
221pub trait Handler<C>: Send
222where
223    C: Connection,
224{
225    type Error: Debug;
226
227    fn handle(&self, connection: &mut C) -> Result<(), Self::Error>;
228}
229
230impl<C, H> Handler<C> for &H
231where
232    C: Connection,
233    H: Handler<C> + Send + Sync,
234{
235    type Error = H::Error;
236
237    fn handle(&self, connection: &mut C) -> Result<(), Self::Error> {
238        (*self).handle(connection)
239    }
240}
241
242pub struct FnHandler<F>(F);
243
244impl<F> FnHandler<F> {
245    pub const fn new<C, E>(f: F) -> Self
246    where
247        C: Connection,
248        F: Fn(Request<&mut C>) -> Result<(), E> + Send,
249        E: Debug,
250    {
251        Self(f)
252    }
253}
254
255impl<C, F, E> Handler<C> for FnHandler<F>
256where
257    C: Connection,
258    F: Fn(Request<&mut C>) -> Result<(), E> + Send,
259    E: Debug,
260{
261    type Error = E;
262
263    fn handle(&self, connection: &mut C) -> Result<(), Self::Error> {
264        self.0(Request::wrap(connection))
265    }
266}
267
268pub trait Middleware<C, H>: Send
269where
270    C: Connection,
271    H: Handler<C>,
272{
273    type Error: Debug;
274
275    fn handle(&self, connection: &mut C, handler: &H) -> Result<(), Self::Error>;
276
277    fn compose(self, handler: H) -> CompositeHandler<Self, H>
278    where
279        Self: Sized,
280    {
281        CompositeHandler::new(self, handler)
282    }
283}
284
285pub struct CompositeHandler<M, H> {
286    middleware: M,
287    handler: H,
288}
289
290impl<M, H> CompositeHandler<M, H> {
291    pub fn new(middleware: M, handler: H) -> Self {
292        Self {
293            middleware,
294            handler,
295        }
296    }
297}
298
299impl<M, H, C> Handler<C> for CompositeHandler<M, H>
300where
301    M: Middleware<C, H>,
302    H: Handler<C>,
303    C: Connection,
304{
305    type Error = M::Error;
306
307    fn handle(&self, connection: &mut C) -> Result<(), Self::Error> {
308        self.middleware.handle(connection, &self.handler)
309    }
310}
311
312pub mod asynch {
313    use core::fmt::Debug;
314
315    use crate::io::{asynch::Read, asynch::Write};
316
317    pub use super::{Headers, Method, Query, Status};
318    pub use crate::io::{Error, ErrorType};
319
320    #[derive(Debug)]
321    #[cfg_attr(feature = "defmt", derive(defmt::Format))]
322    pub struct Request<C>(C);
323
324    impl<C> Request<C>
325    where
326        C: Connection,
327    {
328        pub fn wrap(connection: C) -> Request<C> {
329            if connection.is_response_initiated() {
330                panic!("connection is not in request phase");
331            }
332
333            Request(connection)
334        }
335
336        pub fn split(&mut self) -> (&C::Headers, &mut C::Read) {
337            self.0.split()
338        }
339
340        pub async fn into_response<'b>(
341            mut self,
342            status: u16,
343            message: Option<&'b str>,
344            headers: &'b [(&'b str, &'b str)],
345        ) -> Result<Response<C>, C::Error> {
346            self.0.initiate_response(status, message, headers).await?;
347
348            Ok(Response(self.0))
349        }
350
351        pub async fn into_status_response(self, status: u16) -> Result<Response<C>, C::Error> {
352            self.into_response(status, None, &[]).await
353        }
354
355        pub async fn into_ok_response(self) -> Result<Response<C>, C::Error> {
356            self.into_response(200, Some("OK"), &[]).await
357        }
358
359        pub fn connection(&mut self) -> &mut C {
360            &mut self.0
361        }
362
363        pub fn release(self) -> C {
364            self.0
365        }
366
367        pub fn uri(&self) -> &'_ str {
368            self.0.uri()
369        }
370
371        pub fn method(&self) -> Method {
372            self.0.method()
373        }
374
375        pub fn header(&self, name: &str) -> Option<&'_ str> {
376            self.0.header(name)
377        }
378
379        pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize, C::Error> {
380            self.0.read(buf).await
381        }
382    }
383
384    impl<C> ErrorType for Request<C>
385    where
386        C: ErrorType,
387    {
388        type Error = C::Error;
389    }
390
391    impl<C> Read for Request<C>
392    where
393        C: Connection,
394    {
395        async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
396            Request::read(self, buf).await
397        }
398    }
399
400    impl<C> Query for Request<C>
401    where
402        C: Connection,
403    {
404        fn uri(&self) -> &'_ str {
405            Request::uri(self)
406        }
407
408        fn method(&self) -> Method {
409            Request::method(self)
410        }
411    }
412
413    impl<C> Headers for Request<C>
414    where
415        C: Connection,
416    {
417        fn header(&self, name: &str) -> Option<&'_ str> {
418            Request::header(self, name)
419        }
420    }
421
422    #[derive(Debug)]
423    #[cfg_attr(feature = "defmt", derive(defmt::Format))]
424    pub struct Response<C>(C);
425
426    impl<C> Response<C>
427    where
428        C: Connection,
429    {
430        pub fn wrap(connection: C) -> Response<C> {
431            if !connection.is_response_initiated() {
432                panic!("connection is not in response phase");
433            }
434
435            Response(connection)
436        }
437
438        pub fn connection(&mut self) -> &mut C {
439            &mut self.0
440        }
441
442        pub fn release(self) -> C {
443            self.0
444        }
445
446        pub async fn write(&mut self, buf: &[u8]) -> Result<usize, C::Error> {
447            self.0.write(buf).await
448        }
449
450        pub async fn flush(&mut self) -> Result<(), C::Error> {
451            self.0.flush().await
452        }
453    }
454
455    impl<C> ErrorType for Response<C>
456    where
457        C: ErrorType,
458    {
459        type Error = C::Error;
460    }
461
462    impl<C> Write for Response<C>
463    where
464        C: Connection,
465    {
466        async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
467            Response::write(self, buf).await
468        }
469
470        async fn flush(&mut self) -> Result<(), Self::Error> {
471            Response::flush(self).await
472        }
473    }
474
475    pub trait Connection: Query + Headers + Read + Write {
476        type Headers: Query + Headers;
477
478        type Read: Read<Error = Self::Error>;
479
480        type RawConnectionError: Error;
481
482        type RawConnection: Read<Error = Self::RawConnectionError>
483            + Write<Error = Self::RawConnectionError>;
484
485        fn split(&mut self) -> (&Self::Headers, &mut Self::Read);
486
487        async fn initiate_response(
488            &mut self,
489            status: u16,
490            message: Option<&str>,
491            headers: &[(&str, &str)],
492        ) -> Result<(), Self::Error>;
493
494        fn is_response_initiated(&self) -> bool;
495
496        fn raw_connection(&mut self) -> Result<&mut Self::RawConnection, Self::Error>;
497    }
498
499    impl<C> Connection for &mut C
500    where
501        C: Connection,
502    {
503        type Headers = C::Headers;
504
505        type Read = C::Read;
506
507        type RawConnectionError = C::RawConnectionError;
508
509        type RawConnection = C::RawConnection;
510
511        fn split(&mut self) -> (&Self::Headers, &mut Self::Read) {
512            (*self).split()
513        }
514
515        async fn initiate_response(
516            &mut self,
517            status: u16,
518            message: Option<&str>,
519            headers: &[(&str, &str)],
520        ) -> Result<(), Self::Error> {
521            (*self).initiate_response(status, message, headers).await
522        }
523
524        fn is_response_initiated(&self) -> bool {
525            (**self).is_response_initiated()
526        }
527
528        fn raw_connection(&mut self) -> Result<&mut Self::RawConnection, Self::Error> {
529            (*self).raw_connection()
530        }
531    }
532
533    pub trait Handler<C>: Send
534    where
535        C: Connection,
536    {
537        type Error: Debug;
538
539        async fn handle(&self, connection: &mut C) -> Result<(), Self::Error>;
540    }
541
542    impl<H, C> Handler<C> for &H
543    where
544        C: Connection,
545        H: Handler<C> + Send + Sync,
546    {
547        type Error = H::Error;
548
549        async fn handle(&self, connection: &mut C) -> Result<(), Self::Error> {
550            (*self).handle(connection).await
551        }
552    }
553
554    pub trait Middleware<C, H>: Send
555    where
556        C: Connection,
557        H: Handler<C>,
558    {
559        type Error: Debug;
560
561        async fn handle(&self, connection: &mut C, handler: &H) -> Result<(), Self::Error>;
562
563        fn compose(self, handler: H) -> CompositeHandler<Self, H>
564        where
565            Self: Sized,
566        {
567            CompositeHandler::new(self, handler)
568        }
569    }
570
571    pub struct CompositeHandler<M, H> {
572        middleware: M,
573        handler: H,
574    }
575
576    impl<M, H> CompositeHandler<M, H> {
577        pub fn new(middleware: M, handler: H) -> Self {
578            Self {
579                middleware,
580                handler,
581            }
582        }
583    }
584
585    impl<M, H, C> Handler<C> for CompositeHandler<M, H>
586    where
587        M: Middleware<C, H>,
588        H: Handler<C>,
589        C: Connection,
590    {
591        type Error = M::Error;
592
593        async fn handle(&self, connection: &mut C) -> Result<(), Self::Error> {
594            self.middleware.handle(connection, &self.handler).await
595        }
596    }
597}