|
| 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::http::{HttpModule, HttpPhase, HttpRequestHandler, IntoHandlerStatus, Request}; |
| 7 | +use crate::{async_ as ngx_async, ngx_log_debug_http}; |
| 8 | + |
| 9 | +use crate::ffi::{ngx_http_request_t, ngx_int_t, ngx_post_event, ngx_posted_events}; |
| 10 | + |
| 11 | +use futures_util::FutureExt; |
| 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 Output: IntoHandlerStatus; |
| 22 | + /// The asynchronous worker function to be implemented. |
| 23 | + fn worker(request: &mut Request) -> impl Future<Output = Self::Output>; |
| 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 | + /// Indicates that the context deletion failed. |
| 42 | + ContextDeletionFailed, |
| 43 | +} |
| 44 | + |
| 45 | +impl Display for AsyncHandlerError { |
| 46 | + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
| 47 | + match self { |
| 48 | + AsyncHandlerError::ContextCreationFailed => { |
| 49 | + write!(f, "AsyncHandler: Context creation failed") |
| 50 | + } |
| 51 | + AsyncHandlerError::NoAsyncLauncher => { |
| 52 | + write!(f, "AsyncHandler: No async launcher available") |
| 53 | + } |
| 54 | + AsyncHandlerError::ContextDeletionFailed => { |
| 55 | + write!(f, "AsyncHandler: Context deletion failed") |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +#[derive(Default)] |
| 62 | +struct AsyncRequestContext { |
| 63 | + launcher: Option<async_task::Task<ngx_int_t>>, |
| 64 | +} |
| 65 | + |
| 66 | +impl<AH> HttpRequestHandler for AH |
| 67 | +where |
| 68 | + AH: AsyncHandler + 'static, |
| 69 | +{ |
| 70 | + const PHASE: HttpPhase = async_phase(AH::PHASE); |
| 71 | + type Output = Result<ngx_int_t, AsyncHandlerError>; |
| 72 | + |
| 73 | + fn handler(request: &mut Request) -> Self::Output { |
| 74 | + let mut pool = request.pool(); |
| 75 | + |
| 76 | + let ctx = pool |
| 77 | + .get_or_add_unique(|| { |
| 78 | + let request_ptr: *mut ngx_http_request_t = request.as_mut() as *mut _ as _; |
| 79 | + AsyncRequestContext { |
| 80 | + launcher: Some(ngx_async::spawn(handler_future::<AH>(request_ptr))), |
| 81 | + } |
| 82 | + }) |
| 83 | + .ok_or(AsyncHandlerError::ContextCreationFailed)?; |
| 84 | + |
| 85 | + match &ctx.launcher { |
| 86 | + None => Err(AsyncHandlerError::NoAsyncLauncher), |
| 87 | + Some(launcher) if launcher.is_finished() => { |
| 88 | + // task is finished, so both expect() should not panic |
| 89 | + let task = ctx |
| 90 | + .launcher |
| 91 | + .take() |
| 92 | + .expect("AsyncHandler: Task should be present"); |
| 93 | + let rc = task |
| 94 | + .now_or_never() |
| 95 | + .expect("AsyncHandler: Task should be ready"); |
| 96 | + ngx_log_debug_http!(request, "AsyncHandler: task joined; rc = {}", rc); |
| 97 | + pool.remove_unique::<AsyncRequestContext>() |
| 98 | + .ok_or(AsyncHandlerError::ContextDeletionFailed)?; |
| 99 | + Ok(rc) |
| 100 | + } |
| 101 | + Some(_) => { |
| 102 | + ngx_log_debug_http!(request, "AsyncHandler: running"); |
| 103 | + Ok(nginx_sys::NGX_AGAIN as _) |
| 104 | + } |
| 105 | + } |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +pin_project! { |
| 110 | + struct HandlerFuture<Fut> |
| 111 | + where |
| 112 | + Fut: Future<Output = ngx_int_t>, |
| 113 | + { |
| 114 | + #[pin] |
| 115 | + worker_fut: Fut, |
| 116 | + request: *const ngx_http_request_t, |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +fn handler_future<AH>(request: *mut ngx_http_request_t) -> impl Future<Output = ngx_int_t> |
| 121 | +where |
| 122 | + AH: AsyncHandler, |
| 123 | +{ |
| 124 | + let fut = async move { |
| 125 | + let request = unsafe { Request::from_ngx_http_request(request) }; |
| 126 | + AH::worker(request).await.into_handler_status(request) |
| 127 | + }; |
| 128 | + |
| 129 | + HandlerFuture::<_> { |
| 130 | + worker_fut: fut, |
| 131 | + request, |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +impl<Fut> Future for HandlerFuture<Fut> |
| 136 | +where |
| 137 | + Fut: Future<Output = ngx_int_t>, |
| 138 | +{ |
| 139 | + type Output = ngx_int_t; |
| 140 | + |
| 141 | + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
| 142 | + let this = self.project(); |
| 143 | + let request = unsafe { Request::from_const_ngx_http_request(*this.request) }; |
| 144 | + |
| 145 | + match this.worker_fut.poll(cx) { |
| 146 | + Poll::Pending => { |
| 147 | + ngx_log_debug_http!(request, "HandlerFuture: pending"); |
| 148 | + Poll::Pending |
| 149 | + } |
| 150 | + Poll::Ready(rc) => { |
| 151 | + unsafe { |
| 152 | + ngx_post_event( |
| 153 | + (*request.connection()).write, |
| 154 | + core::ptr::addr_of_mut!(ngx_posted_events), |
| 155 | + ) |
| 156 | + }; |
| 157 | + ngx_log_debug_http!(request, "HandlerFuture: ready"); |
| 158 | + Poll::Ready(rc) |
| 159 | + } |
| 160 | + } |
| 161 | + } |
| 162 | +} |
0 commit comments