use brazen::{envelope_error, envelope_head, Bytes, CanonicalError, TransportResponse};
use super::exec::ExecBody;
pub(super) fn respond(mut child: ExecBody) -> Result<TransportResponse, CanonicalError> {
let mut buf: Vec<u8> = Vec::new();
loop {
if let Some(head) = envelope_head(&buf)? {
let prefix = buf.split_off(head.body_start);
let first: Option<std::io::Result<Bytes>> = (!prefix.is_empty()).then_some(Ok(prefix));
return Ok(TransportResponse {
status: head.status,
retry_after: head.retry_after,
body: Box::new(first.into_iter().chain(child)),
});
}
match child.next() {
Some(Ok(chunk)) => buf.extend_from_slice(&chunk),
Some(Err(e)) => {
return Err(envelope_error(&format!(
"delegate failed before the response head: {e}"
)))
}
None => {
return Err(envelope_error(
"delegate closed stdout before the response head",
))
}
}
}
}