inyanga 0.1.1

Axum/mlua based server-side lua scripting
Documentation
use std::{
	sync::Arc,
	task::{Context, Poll},
};

use axum::{
	body::{Body, HttpBody},
	http::{Method, Request, StatusCode, Uri, header},
	response::{IntoResponse, Response},
};
use futures_util::future::BoxFuture;
use http_body_util::BodyExt;
use tower;

pub mod parser;

pub trait Binder
{
	fn get_lua_bindings(
		&self,
		_uri: &Uri,
		_request_body: &Body,
		_is_post: bool,
	) -> parser::InsideScopeHook;
}

#[derive(Clone)]
pub struct Layer
{
	pub binder: Option<Arc<dyn Binder + Send + Sync>>,
}

impl<S> tower::Layer<S> for Layer
{
	type Service = Service<S>;

	fn layer(&self, inner: S) -> Self::Service
	{
		Service {
			inner,
			binder: self.binder.clone(),
		}
	}
}

#[derive(Clone)]
pub struct Service<S>
{
	pub inner: S,
	pub binder: Option<Arc<dyn Binder + Send + Sync>>,
}

impl<S> Service<S>
where
	S: tower::Service<Request<Body>, Response = Response> + Send + 'static,
	S::Future: Send + 'static,
{
	pub fn handle_request(
		&mut self,
		request: Request<Body>,
	) -> (
		Uri,
		Body,
		bool,
		impl std::future::Future<Output = Result<S::Response, S::Error>> + Send + use<S>,
	)
	{
		let mut is_post = false;
		let (mut request_parts, request_body) = request.into_parts();

		if Method::POST == request_parts.method
		{
			let handle_post = match request_parts.headers.get(header::CONTENT_TYPE)
			{
				Some(content) => match content.to_str()
				{
					Ok(content) =>
					{
						content.eq_ignore_ascii_case("application/x-www-form-urlencoded")
					}
					_ => false,
				},
				None => true,
			};

			if handle_post
			{
				request_parts.method = Method::GET;
				is_post = true;
			}
		}

		request_parts.headers.remove(header::IF_MODIFIED_SINCE);

		let uri = request_parts.uri.clone();
		let response = self.inner.call(axum::http::Request::from_parts(
			request_parts,
			axum::body::Body::empty(),
		));

		(uri, request_body, is_post, response)
	}

	fn bind_params<'a>(p: &mut parser::Parser, type_: parser::Param, query: &'a str)
	{
		for (key, value) in querystring::querify(query)
		{
			p.bind_param(type_, key.to_string(), value.to_string());
		}
	}

	pub fn overwrite_response<T>(
		&mut self,
		uri: Uri,
		request_body: Body,
		is_post: bool,
		response: T,
		inside_scope_hook: parser::InsideScopeHook,
	) -> <Self as tower::Service<Request<Body>>>::Future
	where
		T: std::future::Future<Output = Result<S::Response, S::Error>> + Send + 'static,
	{
		Box::pin(async move {
			let mut response: Response = response.await?;

			let mut p = parser::Parser::new();

			if let Some(query) = uri.query()
			{
				Self::bind_params(&mut p, parser::Param::URL, query);
			}

			if is_post
			{
				let request_buffers = request_body.collect().await;

				let request_bytes = match request_buffers
				{
					Ok(buffers) => buffers.to_bytes(),
					Err(_) =>
					{
						return Ok(
							(StatusCode::PAYLOAD_TOO_LARGE, "Cannot handle POST payload")
								.into_response(),
						);
					}
				};

				match std::str::from_utf8(&request_bytes)
				{
					Ok(query) => Self::bind_params(&mut p, parser::Param::POST, query),
					Err(e) =>
					{
						return Ok((
							StatusCode::INTERNAL_SERVER_ERROR,
							format!("Parsing request body {}", e),
						)
							.into_response());
					}
				}
			}

			let is_html = match response.headers().get(header::CONTENT_TYPE)
			{
				Some(content) => match content.to_str().expect("").parse::<mime::Mime>()
				{
					Ok(m) => (m.type_(), m.subtype()) == (mime::TEXT, mime::HTML),
					_ => false,
				},
				_ => false,
			};

			if StatusCode::OK == response.status() && is_html
			{
				while !response.body().is_end_stream()
				{
					let data = response.body_mut().frame().await;
					match data
					{
						Some(Ok(frame)) => match frame.into_data()
						{
							Ok(bytes) => p.parse(bytes),
							Err(_) =>
							{
								return Ok((StatusCode::INTERNAL_SERVER_ERROR, "data frame error")
									.into_response());
							}
						},
						Some(Err(error)) =>
						{
							return Ok((StatusCode::INTERNAL_SERVER_ERROR, format!("{}", error))
								.into_response());
						}
						None => break,
					};
				}

				let (mut parts, _) = response.into_parts();
				parts.headers.remove(header::CONTENT_LENGTH);

				Ok(match p.finalize(inside_scope_hook)
				{
					Ok(chunks) =>
					{
						let stream = futures_util::stream::iter(chunks);
						let body = axum::body::Body::from_stream(stream);
						axum::response::Response::from_parts(parts, body)
					}
					Err(error) =>
					{
						(StatusCode::INTERNAL_SERVER_ERROR, format!("{}", error)).into_response()
					}
				})
			}
			else
			{
				Ok(response)
			}
		})
	}
}

impl<S> tower::Service<Request<Body>> for Service<S>
where
	S: tower::Service<Request<Body>, Response = Response> + Send + 'static,
	S::Future: Send + 'static,
{
	type Response = S::Response;
	type Error = S::Error;
	// `BoxFuture` is a type alias for `Pin<Box<dyn Future + Send + 'a>>`
	type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

	fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>
	{
		self.inner.poll_ready(cx)
	}

	fn call(&mut self, request: Request<Body>) -> Self::Future
	{
		let (uri, request_body, is_post, response) = self.handle_request(request);
		let bindings = self
			.binder
			.as_ref()
			.map(|b| b.get_lua_bindings(&uri, &request_body, is_post))
			.unwrap_or(None);
		self.overwrite_response(uri, request_body, is_post, response, bindings)
	}
}