|
| 1 | +use core::fmt::Display; |
| 2 | +use core::future::Future; |
| 3 | +use core::pin::Pin; |
| 4 | +use core::task::{Context, Poll}; |
| 5 | + |
| 6 | +use crate::core::type_storage::*; |
| 7 | +use crate::http::{HttpHandlerReturn, HttpModule, HttpPhase, HttpRequestHandler, Request}; |
| 8 | +use crate::{async_ as ngx_async, ngx_log_debug_http}; |
| 9 | + |
| 10 | +use crate::ffi::{ngx_http_request_t, ngx_int_t, ngx_post_event, ngx_posted_events}; |
| 11 | + |
| 12 | +use pin_project_lite::*; |
| 13 | + |
| 14 | +/// An asynchronous HTTP request handler trait. |
| 15 | +pub trait AsyncHandler { |
| 16 | + /// The phase in which the handler will be executed. |
| 17 | + const PHASE: HttpPhase; |
| 18 | + /// The associated HTTP module type. |
| 19 | + type Module: HttpModule; |
| 20 | + /// The return type of the asynchronous worker function. |
| 21 | + type ReturnType: HttpHandlerReturn; |
| 22 | + /// The asynchronous worker function to be implemented. |
| 23 | + fn worker(request: &mut Request) -> impl Future<Output = Self::ReturnType>; |
| 24 | +} |
| 25 | + |
| 26 | +const fn async_phase(phase: HttpPhase) -> HttpPhase { |
| 27 | + assert!( |
| 28 | + !matches!(phase, HttpPhase::Content), |
| 29 | + "Content phase is not supported" |
| 30 | + ); |
| 31 | + phase |
| 32 | +} |
| 33 | + |
| 34 | +/// An error type for asynchronous handler operations. |
| 35 | +#[derive(Debug)] |
| 36 | +pub enum AsyncHandlerError { |
| 37 | + /// Indicates that the context creation failed. |
| 38 | + ContextCreationFailed, |
| 39 | + /// Indicates that there is no async launcher available. |
| 40 | + NoAsyncLauncher, |
| 41 | +} |
| 42 | + |
| 43 | +impl Display for AsyncHandlerError { |
| 44 | + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
| 45 | + match self { |
| 46 | + AsyncHandlerError::ContextCreationFailed => { |
| 47 | + write!(f, "AsyncHandler: Context creation failed") |
| 48 | + } |
| 49 | + AsyncHandlerError::NoAsyncLauncher => { |
| 50 | + write!(f, "AsyncHandler: No async launcher available") |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +impl<AH> HttpRequestHandler for AH |
| 57 | +where |
| 58 | + AH: AsyncHandler + 'static, |
| 59 | +{ |
| 60 | + const PHASE: HttpPhase = async_phase(AH::PHASE); |
| 61 | + type ReturnType = Result<ngx_int_t, AsyncHandlerError>; |
| 62 | + |
| 63 | + fn handler(request: &mut Request) -> Self::ReturnType { |
| 64 | + let mut pool = request.pool(); |
| 65 | + let mut ctx = <AsyncRequestContext as TypeStorage>::get_mut(&mut pool); |
| 66 | + #[allow(clippy::manual_inspect)] |
| 67 | + if ctx.is_none() { |
| 68 | + ctx = |
| 69 | + <AsyncRequestContext as TypeStorage>::add(AsyncRequestContext::default(), &mut pool) |
| 70 | + .map(|ctx| { |
| 71 | + let request_ptr: *mut ngx_http_request_t = request.as_mut() as *mut _ as _; |
| 72 | + ctx.launcher = Some(ngx_async::spawn(handler_future::<AH>(request_ptr))); |
| 73 | + ctx |
| 74 | + }) |
| 75 | + }; |
| 76 | + |
| 77 | + let ctx = ctx.ok_or(AsyncHandlerError::ContextCreationFailed)?; |
| 78 | + |
| 79 | + if ctx.launcher.is_none() { |
| 80 | + Err(AsyncHandlerError::NoAsyncLauncher) |
| 81 | + } else if ctx.launcher.as_ref().unwrap().is_finished() { |
| 82 | + let rc = futures::executor::block_on(ctx.launcher.take().unwrap()); |
| 83 | + ngx_log_debug_http!(request, "handler_wrapper: task joined; rc = {}", rc); |
| 84 | + <AsyncRequestContext as TypeStorage>::delete(&pool); |
| 85 | + Ok(rc) |
| 86 | + } else { |
| 87 | + ngx_log_debug_http!(request, "handler_wrapper: running"); |
| 88 | + Ok(nginx_sys::NGX_AGAIN as _) |
| 89 | + } |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +#[derive(Default)] |
| 94 | +struct AsyncRequestContext { |
| 95 | + launcher: Option<async_task::Task<ngx_int_t>>, |
| 96 | +} |
| 97 | + |
| 98 | +pin_project! { |
| 99 | + struct HandlerFuture<Fut> |
| 100 | + where |
| 101 | + Fut: Future<Output = ngx_int_t>, |
| 102 | + { |
| 103 | + #[pin] |
| 104 | + worker_fut: Fut, |
| 105 | + request: *const ngx_http_request_t, |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +fn handler_future<AH>(request: *mut ngx_http_request_t) -> impl Future<Output = ngx_int_t> |
| 110 | +where |
| 111 | + AH: AsyncHandler, |
| 112 | +{ |
| 113 | + let fut = async move { |
| 114 | + let request = unsafe { Request::from_ngx_http_request(request) }; |
| 115 | + AH::worker(request).await.into_ngx_int_t(request) |
| 116 | + }; |
| 117 | + |
| 118 | + HandlerFuture::<_> { |
| 119 | + worker_fut: fut, |
| 120 | + request, |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +impl<Fut> Future for HandlerFuture<Fut> |
| 125 | +where |
| 126 | + Fut: Future<Output = ngx_int_t>, |
| 127 | +{ |
| 128 | + type Output = ngx_int_t; |
| 129 | + |
| 130 | + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
| 131 | + let this = self.project(); |
| 132 | + let request = unsafe { Request::from_const_ngx_http_request(*this.request) }; |
| 133 | + |
| 134 | + match this.worker_fut.poll(cx) { |
| 135 | + Poll::Pending => { |
| 136 | + ngx_log_debug_http!(request, "HandlerFuture: pending"); |
| 137 | + Poll::Pending |
| 138 | + } |
| 139 | + Poll::Ready(rc) => { |
| 140 | + unsafe { |
| 141 | + ngx_post_event( |
| 142 | + (*request.connection()).write, |
| 143 | + core::ptr::addr_of_mut!(ngx_posted_events), |
| 144 | + ) |
| 145 | + }; |
| 146 | + ngx_log_debug_http!(request, "HandlerFuture: ready"); |
| 147 | + Poll::Ready(rc) |
| 148 | + } |
| 149 | + } |
| 150 | + } |
| 151 | +} |
0 commit comments