sheave_core/
handlers.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! # Handling RTMP connections and data streaming.
//!
//! Currently following handlers have been implemented.
//!
//! * [`Handshake`]
//! * [`connect`]
//! * [`releaseStream`]
//! * [`FCPublish`]
//! * [`createStream`]
//! * [`publish`]
//!
//! [`Handshake`]: crate::handshake::Handshake
//! [`connect`]: crate::messages::Connect
//! [`releaseStream`]: crate::messages::ReleaseStream
//! [`FCPublish`]: crate::messages::FcPublish
//! [`createStream`]: crate::messages::CreateStream
//! [`publish`]: crate::messages::Publish

mod rtmp_context;
mod inconsistent_sha;
mod stream_wrapper;
mod vec_stream;
mod status;
mod measure_acknowledgement;
mod chain;
mod while_ok;
mod middlewares;
mod map_err;
mod stream_got_exhausted;

use std::{
    io::Result as IOResult,
    pin::Pin,
    sync::Arc,
    task::{
        Context as FutureContext,
        Poll
    }
};
use tokio::io::{
    AsyncRead,
    AsyncWrite
};
use self::{
    chain::*,
    while_ok::*,
    middlewares::{
        Wrap,
        wrap
    },
    map_err::{
        MapErr,
        map_err,
    }
};
pub use self::{
    rtmp_context::*,
    inconsistent_sha::*,
    stream_wrapper::*,
    vec_stream::*,
    status::*,
    middlewares::Middleware,
    map_err::ErrorHandler,
    measure_acknowledgement::*,
    stream_got_exhausted::*
};

/// The interface for handling RTMP connection steps with `Future`.
///
/// This trait unifies surfaces of handler APIs:
///
/// * `RtmpContext` is required.
/// * Terminating with unit (`()`) is required.
///
/// The first requirement makes `RtmpContext` reusable for upper APIs.
/// And the second requirement makes handlers return `Ok(())` when successfully terminates because currently they are run on `main`.
///
/// ```rust
/// use std::{
///     io::Result as IOResult,
///     pin::Pin,
///     sync::Arc,
///     task::{
///         Context as FutureContext,
///         Poll
///     }
/// };
/// use futures::future::poll_fn;
/// use tokio::io::{
///     AsyncRead,
///     AsyncWrite
/// };
/// use sheave_core::handlers::{
///     AsyncHandler,
///     RtmpContext
/// };
///
/// struct SomethingHandler<RW: AsyncRead + AsyncWrite + Unpin>(Arc<RW>);
///
/// impl<RW: AsyncRead + AsyncWrite + Unpin> AsyncHandler for SomethingHandler<RW> {
///     fn poll_handle(self: Pin<&mut Self>, cx: &mut FutureContext<'_>, rtmp_context: &mut RtmpContext) -> Poll<IOResult<()>> {
///         // Something to handle
///
///         Poll::Ready(Ok(()))
///     }
/// }
///
/// #[tokio::main]
/// async fn main() -> IOResult<()> {
///     // Consider this is Tokio's `JoinHandle` which is run on `main`.
///     poll_fn(
///         |cx| {
///             use std::{
///                 pin::pin,
///                 sync::Arc
///             };
///             use sheave_core::handlers::{
///                 AsyncHandler,
///                 VecStream,
///                 StreamWrapper
///             };
///
///             let stream = Arc::new(StreamWrapper::new(VecStream::default()));
///             pin!(SomethingHandler(stream)).poll_handle(cx, &mut RtmpContext::default())
///         }
///     ).await
/// }
/// ```
///
/// [`RtmpContext`]: RtmpContext
pub trait AsyncHandler {
    fn poll_handle(self: Pin<&mut Self>, cx: &mut FutureContext<'_>, rtmp_context: &mut RtmpContext) -> Poll<IOResult<()>>;
}

/// The extension methods for handlers.
///
/// Currently following extensions have been implemented.
///
/// * [`chain`]
/// * [`wrap`]
/// * [`while_ok`]
/// * [`map_err`]
///
/// [`chain`]: AsyncHandlerExt::chain
/// [`wrap`]: AsyncHandlerExt::wrap
/// [`while_ok`]: AsyncHandlerExt::while_ok
/// [`map_err`]: AsyncHandlerExt::map_err
pub trait AsyncHandlerExt: AsyncHandler {
    /// Chains this handler with `next`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::{
    ///     io::Result as IOResult,
    ///     pin::Pin,
    ///     sync::Arc,
    ///     task::{
    ///         Context as FutureContext,
    ///         Poll
    ///     }
    /// };
    /// use futures::future::poll_fn;
    /// use tokio::io::{
    ///     AsyncRead,
    ///     AsyncWrite
    /// };
    /// use sheave_core::handlers::{
    ///     AsyncHandler,
    ///     RtmpContext
    /// };
    ///
    /// struct HandlerA<RW: AsyncRead + AsyncWrite + Unpin>(Arc<RW>);
    /// struct HandlerB<RW: AsyncRead + AsyncWrite + Unpin>(Arc<RW>);
    ///
    /// impl<RW: AsyncRead + AsyncWrite + Unpin> AsyncHandler for HandlerA<RW> {
    ///     fn poll_handle(self: Pin<&mut Self>, cx: &mut FutureContext<'_>, rtmp_context: &mut RtmpContext) -> Poll<IOResult<()>> {
    ///         // Something to handle.
    ///
    ///         Poll::Ready(Ok(()))
    ///     }
    /// }
    ///
    /// impl<RW: AsyncRead + AsyncWrite + Unpin> AsyncHandler for HandlerB<RW> {
    ///     fn poll_handle(self: Pin<&mut Self>, cx: &mut FutureContext<'_>, rtmp_context: &mut RtmpContext) -> Poll<IOResult<()>> {
    ///         // Something to handle.
    ///
    ///         Poll::Ready(Ok(()))
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> IOResult<()> {
    ///     poll_fn(
    ///         |cx| {
    ///             use std::pin::pin;
    ///             use sheave_core::handlers::{
    ///                 AsyncHandlerExt,
    ///                 StreamWrapper,
    ///                 VecStream
    ///             };
    ///
    ///             let stream = Arc::new(StreamWrapper::new(VecStream::default()));
    ///             pin!(
    ///                 HandlerA(Arc::clone(&stream))
    ///                     .chain(HandlerB(Arc::clone(&stream)))
    ///             ).poll_handle(cx, &mut RtmpContext::default())
    ///         }
    ///     ).await
    /// }
    /// ```
    fn chain<H>(self, next: H) -> Chain<Self, H>
    where
        H: AsyncHandler + Unpin,
        Self: Sized + Unpin
    {
        chain(self, next)
    }

    /// Wraps previous handlers into a middleware.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::{
    ///     io::Result as IOResult,
    ///     pin::Pin,
    ///     sync::Arc,
    ///     task::{
    ///         Context as FutureContext,
    ///         Poll
    ///     }
    /// };
    /// use futures::{
    ///     future::poll_fn,
    ///     ready
    /// };
    /// use tokio::io::{
    ///     AsyncRead,
    ///     AsyncWrite
    /// };
    /// use sheave_core::handlers::{
    ///     AsyncHandler,
    ///     Middleware,
    ///     RtmpContext
    /// };
    ///
    /// struct SomethingHandler<RW: AsyncRead + AsyncWrite + Unpin>(Arc<RW>);
    ///
    /// impl<RW: AsyncRead + AsyncWrite + Unpin> AsyncHandler for SomethingHandler<RW> {
    ///     fn poll_handle(self: Pin<&mut Self>, cx: &mut FutureContext<'_>, rtmp_context: &mut RtmpContext) -> Poll<IOResult<()>> {
    ///         // Something to handle.
    ///
    ///         Poll::Ready(Ok(()))
    ///     }
    /// }
    ///
    /// struct SomethingMiddleware<'a, W: Unpin>(Pin<&'a mut W>);
    ///
    /// impl<W: Unpin> Middleware for SomethingMiddleware<'_, W> {
    ///     fn poll_handle_wrapped<H: AsyncHandler + Unpin>(self: Pin<&mut Self>, cx: &mut FutureContext<'_>, rtmp_context: &mut RtmpContext, handler: Pin<&mut H>) -> Poll<IOResult<()>> {
    ///         println!("Starts wrapping.");
    ///         ready!(handler.poll_handle(cx, rtmp_context))?;
    ///         println!("Ends wrapping.");
    ///         Poll::Ready(Ok(()))
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let result = poll_fn(
    ///         |cx| {
    ///             use std::pin::pin;
    ///             use sheave_core::handlers::{
    ///                 AsyncHandlerExt,
    ///                 StreamWrapper,
    ///                 VecStream
    ///             };
    ///
    ///             let stream = Arc::new(StreamWrapper::new(VecStream::default()));
    ///             pin!(
    ///                 SomethingHandler(Arc::clone(&stream))
    ///                     .wrap(SomethingMiddleware(stream.make_weak_pin()))
    ///             ).poll_handle(cx, &mut RtmpContext::default())
    ///         }
    ///     ).await;
    ///     assert!(result.is_ok())
    /// }
    /// ```
    fn wrap<M>(self, middleware: M) -> Wrap<M, Self>
    where
        M: Middleware + Unpin,
        Self: Sized + Unpin
    {
        wrap(middleware, self)
    }

    /// Loops while the body returns `Ok(())` or `Pending`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::{
    ///     io::{
    ///         Error as IOError,
    ///         ErrorKind,
    ///         Result as IOResult
    ///     },
    ///     pin::Pin,
    ///     sync::Arc,
    ///     task::{
    ///         Context as FutureContext,
    ///         Poll
    ///     }
    /// };
    /// use futures::future::poll_fn;
    /// use tokio::io::{
    ///     AsyncRead,
    ///     AsyncWrite
    /// };
    /// use sheave_core::handlers::{
    ///     AsyncHandler,
    ///     RtmpContext,
    ///     StreamWrapper
    /// };
    ///
    /// struct SomethingHandler<RW: AsyncRead + AsyncWrite + Unpin>(Arc<RW>);
    ///
    /// impl<RW: AsyncRead + AsyncWrite + Unpin> AsyncHandler for SomethingHandler<RW> {
    ///     fn poll_handle(self: Pin<&mut Self>, _cx: &mut FutureContext<'_>, _rtmp_context: &mut RtmpContext) -> Poll<IOResult<()>> {
    ///         // Something to handle.
    ///
    ///         Poll::Ready(Ok(()))
    ///     }
    /// }
    ///
    /// struct AnotherHandler<RW: AsyncRead + AsyncWrite + Unpin>(Arc<RW>);
    ///
    /// impl<RW: AsyncRead + AsyncWrite + Unpin> AsyncHandler for AnotherHandler<RW> {
    ///     fn poll_handle(self: Pin<&mut Self>, _cx: &mut FutureContext<'_>, _rtmp_context: &mut RtmpContext) -> Poll<IOResult<()>> {
    ///         Poll::Ready(Err(IOError::from(ErrorKind::Other)))
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let result = poll_fn(
    ///         |cx| {
    ///             use std::pin::pin;
    ///             use sheave_core::handlers::{
    ///                 AsyncHandlerExt,
    ///                 VecStream
    ///             };
    ///
    ///             let stream = Arc::new(StreamWrapper::new(VecStream::default()));
    ///             pin!(
    ///                 SomethingHandler(Arc::clone(&stream))
    ///                     .while_ok(AnotherHandler(Arc::clone(&stream)))
    ///             ).poll_handle(cx, &mut RtmpContext::default())
    ///         }
    ///     ).await;
    ///     assert!(result.is_err())
    /// }
    /// ```
    fn while_ok<H>(self, body: H) -> WhileOk<Self, H>
    where
        H: AsyncHandler + Unpin,
        Self: Sized + Unpin
    {
        while_ok(self, body)
    }

    /// Handles some error when previous handler returns `Err`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::{
    ///     io::{
    ///         Error as IOError,
    ///         Result as IOResult
    ///     },
    ///     pin::Pin,
    ///     sync::Arc,
    ///     task::{
    ///         Context as FutureContext,
    ///         Poll
    ///     }
    /// };
    /// use futures::future::poll_fn;
    /// use tokio::io::{
    ///     AsyncRead,
    ///     AsyncWrite
    /// };
    /// use sheave_core::handlers::{
    ///     AsyncHandler,
    ///     ErrorHandler,
    ///     RtmpContext
    /// };
    ///
    /// struct SomethingHandler<RW: AsyncRead + AsyncWrite + Unpin>(Arc<RW>);
    ///
    /// impl<RW: AsyncRead + AsyncWrite + Unpin> AsyncHandler for SomethingHandler<RW> {
    ///     fn poll_handle(self: Pin<&mut Self>, _cx: &mut FutureContext<'_>, _rtmp_context: &mut RtmpContext) -> Poll<IOResult<()>> {
    ///         Poll::Ready(Err(IOError::other("Something Wrong.")))
    ///     }
    /// }
    ///
    /// struct SomethingWrongHandler<'a, RW>(Pin<&'a mut RW>);
    ///
    /// impl<RW> ErrorHandler for SomethingWrongHandler<'_, RW> {
    ///     fn poll_handle_error(self: Pin<&mut Self>, _cx: &mut FutureContext<'_>, _rtmp_context: &mut RtmpContext, error: IOError) -> Poll<IOResult<()>> {
    ///         println!("{error}");
    ///
    ///         // This `Ok` means that handled its error successfully.
    ///         Poll::Ready(Ok(()))
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let result = poll_fn(
    ///         |cx| {
    ///             use std::pin::pin;
    ///             use sheave_core::handlers::{
    ///                 AsyncHandlerExt,
    ///                 StreamWrapper,
    ///                 VecStream
    ///             };
    ///
    ///             let stream = Arc::new(StreamWrapper::new(VecStream::default()));
    ///             pin!(
    ///                 SomethingHandler(Arc::clone(&stream))
    ///                     .map_err(SomethingWrongHandler(stream.make_weak_pin()))
    ///             ).poll_handle(cx, &mut RtmpContext::default())
    ///         }
    ///     ).await;
    ///     assert!(result.is_ok())
    /// }
    /// ```
    fn map_err<E>(self, error_handler: E) -> MapErr<Self, E>
    where
        E: ErrorHandler + Unpin,
        Self: Sized + Unpin
    {
        map_err(self, error_handler)
    }
}

impl<H: AsyncHandler> AsyncHandlerExt for H {}

/// The interface for providing the way to construct any handler to clients/servers.
///
/// Servers / Clients pass streams and contexts to any handler they contain.
/// Here we are necessary to be careful that some stream can't clone. (e.g. sockets)
/// But we need to share these while handling RTMP communication steps.
/// Therefore this provides the way of cloning stream instances via the (smart) pointer.
///
/// # Examples
///
/// ```rust
/// use std::{
///     future::Future,
///     io::Result as IOResult,
///     marker::PhantomData,
///     pin::{
///         Pin,
///         pin
///     },
///     sync::Arc,
///     task::{
///         Context as FutureContext,
///         Poll
///     }
/// };
/// use tokio::io::{
///     AsyncRead,
///     AsyncWrite,
///     ReadBuf
/// };
/// use sheave_core::handlers::{
///     AsyncHandler,
///     HandlerConstructor,
///     RtmpContext
/// };
///
/// struct SomethingStream;
///
/// impl AsyncRead for SomethingStream {
///     fn poll_read(self: Pin<&mut Self>, _cx: &mut FutureContext<'_>, _buf: &mut ReadBuf<'_>) -> Poll<IOResult<()>> {
///         // Something to read.
///
///         Poll::Ready(Ok(()))
///     }
/// }
///
/// impl AsyncWrite for SomethingStream {
///     fn poll_write(self: Pin<&mut Self>, _cx: &mut FutureContext<'_>, buf: &[u8]) -> Poll<IOResult<usize>> {
///         // Something to write.
///
///         Poll::Ready(Ok(buf.len()))
///     }
///
///     fn poll_flush(self: Pin<&mut Self>, _cx: &mut FutureContext<'_>) -> Poll<IOResult<()>> {
///         // Something to flush.
///
///         Poll::Ready(Ok(()))
///     }
///
///     fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut FutureContext<'_>) -> Poll<IOResult<()>> {
///         // Something to shutdown.
///
///         Poll::Ready(Ok(()))
///     }
/// }
///
/// struct SomethingHandler<RW: AsyncRead + AsyncWrite + Unpin>(Arc<RW>);
///
/// impl<RW: AsyncRead + AsyncWrite + Unpin> AsyncHandler for SomethingHandler<RW> {
///     fn poll_handle(self: Pin<&mut Self>, _cx: &mut FutureContext<'_>, _rtmp_context: &mut RtmpContext) -> Poll<IOResult<()>> {
///         // Something to handle.
///
///         Poll::Ready(Ok(()))
///     }
/// }
///
/// impl<RW: AsyncRead + AsyncWrite + Unpin> HandlerConstructor<RW> for SomethingHandler<RW> {
///     fn new(stream: Arc<RW>) -> Self {
///         Self(stream)
///     }
/// }
///
/// struct SomethingRunner<RW, C>
/// where
///     RW: AsyncRead + AsyncWrite + Unpin,
///     C: HandlerConstructor<RW>
/// {
///     stream: Arc<RW>,
///     rtmp_context: Arc<RtmpContext>,
///     handler_constructor: PhantomData<C>
/// }
///
/// impl<RW, C> SomethingRunner<RW, C>
/// where
///     RW: AsyncRead + AsyncWrite + Unpin,
///     C: HandlerConstructor<RW>
/// {
///     pub fn new(stream: RW, rtmp_context: RtmpContext, handler_constructor: PhantomData<C>) -> Self {
///         Self {
///             stream: Arc::new(stream),
///             rtmp_context: Arc::new(rtmp_context),
///             handler_constructor
///         }
///     }
/// }
///
/// impl<RW, C> Future for SomethingRunner<RW, C>
/// where
///     RW: AsyncRead + AsyncWrite + Unpin,
///     C: HandlerConstructor<RW>
/// {
///     type Output = IOResult<()>;
///
///     fn poll(self: Pin<&mut Self>, cx: &mut FutureContext<'_>) -> Poll<Self::Output> {
///         pin!(C::new(Arc::clone(&self.stream))).poll_handle(cx, self.rtmp_context.make_weak_mut())
///     }
/// }
///
/// #[tokio::main]
/// async fn main() {
///     let stream = SomethingStream;
///     let rtmp_context = RtmpContext::default();
///     let handler_constructor = PhantomData::<SomethingHandler<SomethingStream>>;
///     let runner = SomethingRunner::new(stream, rtmp_context, handler_constructor);
///     let result = runner.await;
///
///     assert!(result.is_ok());
/// }
/// ```
pub trait HandlerConstructor<RW: AsyncRead + AsyncWrite + Unpin>: AsyncHandler {
    fn new(stream: Arc<RW>) -> Self;
}