|
| 1 | +/* |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +//! Middleware for handling [ALB health |
| 7 | +//! checks](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/target-group-health-checks.html). |
| 8 | +//! |
| 9 | +//! # Example |
| 10 | +//! |
| 11 | +//! ```no_run |
| 12 | +//! # use aws_smithy_http_server::{body, plugin::{PluginPipeline, alb_health_check::AlbHealthCheckLayer}}; |
| 13 | +//! # use hyper::{Body, Response, StatusCode}; |
| 14 | +//! let plugins = PluginPipeline::new() |
| 15 | +//! // Handle all `/ping` health check requests by returning a `200 OK`. |
| 16 | +//! .http_layer(AlbHealthCheckLayer::from_handler("/ping", |_req| async { |
| 17 | +//! StatusCode::OK |
| 18 | +//! })); |
| 19 | +//! |
| 20 | +//! ``` |
| 21 | +
|
| 22 | +use std::borrow::Cow; |
| 23 | +use std::convert::Infallible; |
| 24 | +use std::task::{Context, Poll}; |
| 25 | + |
| 26 | +use futures_util::{Future, FutureExt}; |
| 27 | +use http::StatusCode; |
| 28 | +use hyper::{Body, Request, Response}; |
| 29 | +use pin_project_lite::pin_project; |
| 30 | +use tower::{service_fn, util::Oneshot, Layer, Service, ServiceExt}; |
| 31 | + |
| 32 | +use crate::body::BoxBody; |
| 33 | + |
| 34 | +use super::either::EitherProj; |
| 35 | +use super::Either; |
| 36 | + |
| 37 | +/// A [`tower::Layer`] used to apply [`AlbHealthCheckService`]. |
| 38 | +#[derive(Clone, Debug)] |
| 39 | +pub struct AlbHealthCheckLayer<HealthCheckHandler> { |
| 40 | + health_check_uri: Cow<'static, str>, |
| 41 | + health_check_handler: HealthCheckHandler, |
| 42 | +} |
| 43 | + |
| 44 | +impl AlbHealthCheckLayer<()> { |
| 45 | + /// Handle health check requests at `health_check_uri` with the specified handler. |
| 46 | + pub fn from_handler<HandlerFuture: Future<Output = StatusCode>, H: Fn(Request<Body>) -> HandlerFuture + Clone>( |
| 47 | + health_check_uri: impl Into<Cow<'static, str>>, |
| 48 | + health_check_handler: H, |
| 49 | + ) -> AlbHealthCheckLayer< |
| 50 | + impl Service< |
| 51 | + Request<Body>, |
| 52 | + Response = StatusCode, |
| 53 | + Error = Infallible, |
| 54 | + Future = impl Future<Output = Result<StatusCode, Infallible>>, |
| 55 | + > + Clone, |
| 56 | + > { |
| 57 | + let service = service_fn(move |req| health_check_handler(req).map(Ok)); |
| 58 | + |
| 59 | + AlbHealthCheckLayer::new(health_check_uri, service) |
| 60 | + } |
| 61 | + |
| 62 | + /// Handle health check requests at `health_check_uri` with the specified service. |
| 63 | + pub fn new<H: Service<Request<Body>, Response = StatusCode>>( |
| 64 | + health_check_uri: impl Into<Cow<'static, str>>, |
| 65 | + health_check_handler: H, |
| 66 | + ) -> AlbHealthCheckLayer<H> { |
| 67 | + AlbHealthCheckLayer { |
| 68 | + health_check_uri: health_check_uri.into(), |
| 69 | + health_check_handler, |
| 70 | + } |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +impl<S, H: Clone> Layer<S> for AlbHealthCheckLayer<H> { |
| 75 | + type Service = AlbHealthCheckService<H, S>; |
| 76 | + |
| 77 | + fn layer(&self, inner: S) -> Self::Service { |
| 78 | + AlbHealthCheckService { |
| 79 | + inner, |
| 80 | + layer: self.clone(), |
| 81 | + } |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +/// A middleware [`Service`] responsible for handling health check requests. |
| 86 | +#[derive(Clone, Debug)] |
| 87 | +pub struct AlbHealthCheckService<H, S> { |
| 88 | + inner: S, |
| 89 | + layer: AlbHealthCheckLayer<H>, |
| 90 | +} |
| 91 | + |
| 92 | +impl<H, S> Service<Request<Body>> for AlbHealthCheckService<H, S> |
| 93 | +where |
| 94 | + S: Service<Request<Body>, Response = Response<BoxBody>> + Clone, |
| 95 | + S::Future: std::marker::Send + 'static, |
| 96 | + H: Service<Request<Body>, Response = StatusCode, Error = Infallible> + Clone, |
| 97 | +{ |
| 98 | + type Response = S::Response; |
| 99 | + |
| 100 | + type Error = S::Error; |
| 101 | + |
| 102 | + type Future = AlbHealthCheckFuture<H, S>; |
| 103 | + |
| 104 | + fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { |
| 105 | + // The check that the service is ready is done by `Oneshot` below. |
| 106 | + Poll::Ready(Ok(())) |
| 107 | + } |
| 108 | + |
| 109 | + fn call(&mut self, req: Request<Body>) -> Self::Future { |
| 110 | + if req.uri() == self.layer.health_check_uri.as_ref() { |
| 111 | + let clone = self.layer.health_check_handler.clone(); |
| 112 | + let service = std::mem::replace(&mut self.layer.health_check_handler, clone); |
| 113 | + let handler_future = service.oneshot(req); |
| 114 | + |
| 115 | + AlbHealthCheckFuture::handler_future(handler_future) |
| 116 | + } else { |
| 117 | + let clone = self.inner.clone(); |
| 118 | + let service = std::mem::replace(&mut self.inner, clone); |
| 119 | + let service_future = service.oneshot(req); |
| 120 | + |
| 121 | + AlbHealthCheckFuture::service_future(service_future) |
| 122 | + } |
| 123 | + } |
| 124 | +} |
| 125 | + |
| 126 | +type HealthCheckFutureInner<H, S> = Either<Oneshot<H, Request<Body>>, Oneshot<S, Request<Body>>>; |
| 127 | + |
| 128 | +pin_project! { |
| 129 | + /// Future for [`AlbHealthCheckService`]. |
| 130 | + pub struct AlbHealthCheckFuture<H: Service<Request<Body>, Response = StatusCode>, S: Service<Request<Body>>> { |
| 131 | + #[pin] |
| 132 | + inner: HealthCheckFutureInner<H, S> |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +impl<H: Service<Request<Body>, Response = StatusCode>, S: Service<Request<Body>>> AlbHealthCheckFuture<H, S> { |
| 137 | + fn handler_future(handler_future: Oneshot<H, Request<Body>>) -> Self { |
| 138 | + Self { |
| 139 | + inner: Either::Left { value: handler_future }, |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + fn service_future(service_future: Oneshot<S, Request<Body>>) -> Self { |
| 144 | + Self { |
| 145 | + inner: Either::Right { value: service_future }, |
| 146 | + } |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +impl< |
| 151 | + H: Service<Request<Body>, Response = StatusCode, Error = Infallible>, |
| 152 | + S: Service<Request<Body>, Response = Response<BoxBody>>, |
| 153 | + > Future for AlbHealthCheckFuture<H, S> |
| 154 | +{ |
| 155 | + type Output = Result<S::Response, S::Error>; |
| 156 | + |
| 157 | + fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
| 158 | + let either_proj = self.project().inner.project(); |
| 159 | + |
| 160 | + match either_proj { |
| 161 | + EitherProj::Left { value } => { |
| 162 | + let polled: Poll<Self::Output> = value.poll(cx).map(|res| { |
| 163 | + res.map(|status_code| { |
| 164 | + Response::builder() |
| 165 | + .status(status_code) |
| 166 | + .body(crate::body::empty()) |
| 167 | + .unwrap() |
| 168 | + }) |
| 169 | + .map_err(|never| match never {}) |
| 170 | + }); |
| 171 | + polled |
| 172 | + } |
| 173 | + EitherProj::Right { value } => value.poll(cx), |
| 174 | + } |
| 175 | + } |
| 176 | +} |
0 commit comments