use std::time::Instant;
use bytes::Bytes;
use serde::Deserialize;
use super::App;
use crate::bridge::InvocationScope;
use crate::execution::{ResponseBodyOperation, response_body_operation};
use crate::wire::{BridgeBytes, WireBytes};
use crate::{Error, Result};
pub(crate) struct OpenResponseBody {
id: u64,
scope: InvocationScope,
deadline: Option<Instant>,
received: usize,
}
impl OpenResponseBody {
pub(super) fn new(
id: u64,
scope: InvocationScope,
deadline: Option<Instant>,
received: usize,
) -> Self {
Self {
id,
scope,
deadline,
received,
}
}
pub(crate) fn deadline(&self) -> Option<Instant> {
self.deadline
}
}
pub(crate) struct PulledChunk {
pub chunk: Bytes,
pub next: Option<OpenResponseBody>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct WirePull {
chunk: WireBytes,
done: bool,
}
impl App {
pub(crate) async fn pull_response_body(
&mut self,
mut open: OpenResponseBody,
) -> Result<PulledChunk> {
let expression = response_body_operation(ResponseBodyOperation::Pull, open.id);
let value = match self.evaluate(expression, open.deadline).await {
Ok(value) => value,
Err(error) => {
self.close(open.scope);
return Err(error);
}
};
let pulled: WirePull = match serde_json::from_value(value) {
Ok(pulled) => pulled,
Err(error) => {
self.reusable = false;
self.close(open.scope);
return Err(Error::JavaScript(format!(
"invalid response body chunk: {error}"
)));
}
};
let chunk = match self.host.receive(pulled.chunk) {
Ok(chunk) => chunk,
Err(error) => {
self.reusable = false;
self.close(open.scope);
return Err(error);
}
};
open.received = open.received.saturating_add(chunk.len());
if let Err(error) = self.check_response_bytes(open.received) {
if pulled.done {
self.close(open.scope);
} else {
self.cancel_response_body(open).await;
}
return Err(error);
}
if pulled.done {
self.close(open.scope);
return Ok(PulledChunk { chunk, next: None });
}
Ok(PulledChunk {
chunk,
next: Some(open),
})
}
pub(crate) async fn cancel_response_body(&mut self, open: OpenResponseBody) {
let expression = response_body_operation(ResponseBodyOperation::Cancel, open.id);
let _ = self.evaluate(expression, open.deadline).await;
self.close(open.scope);
}
}