use std::convert::Infallible;
use http_body_util::{BodyExt as _, StreamBody};
use hyper::body::{Bytes, Frame};
use mlua::{Function, LuaString, Table as LuaTable, UserData, UserDataMethods, Value};
use tokio::sync::OwnedSemaphorePermit;
use tracing::Instrument as _;
use crate::handler::build_response;
use nitr_core::{DeadlineHandle, Result, RuntimeGuard};
type ChunkSender = async_channel::Sender<std::result::Result<Frame<Bytes>, Infallible>>;
const CHANNEL_CAPACITY: usize = 2;
struct LuaWriter {
tx: ChunkSender,
deadline: DeadlineHandle,
}
impl UserData for LuaWriter {
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
methods.add_async_method("write", |_, this, chunk: LuaString| async move {
let bytes = Bytes::copy_from_slice(&chunk.as_bytes());
this.tx
.send(Ok(Frame::data(bytes)))
.await
.map_err(|_| mlua::Error::RuntimeError("client disconnected".into()))?;
this.deadline.extend();
Ok(())
});
}
}
pub(crate) fn stream_response(
mut rt: RuntimeGuard,
lua_resp: &LuaTable,
body_fn: Function,
permit: OwnedSemaphorePermit,
) -> Result<super::handler::HttpResponse> {
let (tx, rx) = async_channel::bounded(CHANNEL_CAPACITY);
let deadline = rt.deadline_handle();
let writer = rt.lua().create_userdata(LuaWriter {
tx: tx.clone(),
deadline: deadline.clone(),
})?;
let resp = build_response(lua_resp, StreamBody::new(rx).boxed())?;
tokio::spawn(
async move {
let _permit = permit;
match rt
.call_function_streaming::<Value>(body_fn.clone(), &writer)
.await
{
Ok(Value::String(first)) => {
let mut chunk = Bytes::copy_from_slice(&first.as_bytes());
loop {
if tx.send(Ok(Frame::data(chunk))).await.is_err() {
break;
}
deadline.extend();
match rt
.call_function_streaming::<Option<LuaString>>(body_fn.clone(), ())
.await
{
Ok(Some(next)) => chunk = Bytes::copy_from_slice(&next.as_bytes()),
Ok(None) => break,
Err(err) => {
tracing::error!("streaming iterator failed mid-body: {err}");
break;
}
}
}
}
Ok(_) => {}
Err(err) => {
let msg = err.to_string();
if msg.contains("client disconnected") {
tracing::debug!("stream cancelled: client disconnected");
} else {
tracing::error!("streaming body failed mid-body: {err}");
}
}
}
tx.close();
}
.instrument(tracing::Span::current()),
);
Ok(resp)
}