use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::io::{self, Read, Write};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::{Arc, Mutex};
use flow_abi::primitives::Reader;
use flow_abi::{Catalog, TypeSpec, ValidatedTypes, description};
use flow_span::{CallRef, RunId};
use flow_start::{Bound, Tasks};
use flow_tool_protocol::{Call, Frame, Kind, Message, Reply, Route, read_frame, write_frame};
use flow_types::Type;
use super::{Adapter, Answered, Args, Cancellation, Context, Output, PROCESS, Sink, lock};
use crate::data::{DecodeError, LIMITS};
use crate::key::CallKey;
pub(crate) struct Declaration {
identity: description::Identity,
spec: TypeSpec,
adapter: Adapter,
}
impl std::fmt::Debug for Declaration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Declaration")
.field("identity", &self.identity)
.finish_non_exhaustive()
}
}
impl Declaration {
pub(crate) fn new(
identity: description::Identity,
spec: TypeSpec,
adapter: Adapter,
) -> Declaration {
Declaration {
identity,
spec,
adapter,
}
}
}
#[derive(Debug)]
pub(crate) struct Server {
declarations: Vec<Declaration>,
admitted: Vec<Mutex<HashMap<description::CallTypes, Arc<ValidatedTypes>>>>,
}
const ADMITTED: usize = 64;
const ADMITTED_BYTES: usize = 1 << 20;
const ADMITTED_VIEW: usize = 64 << 10;
const FRAME_LIMIT: usize = LIMITS.text_bytes;
const CALL_STACK: usize = 64 * 1024 * 1024;
impl Server {
pub(crate) fn new(declarations: Vec<Declaration>) -> Server {
let admitted = declarations
.iter()
.map(|_| Mutex::new(HashMap::new()))
.collect();
Server {
declarations,
admitted,
}
}
fn types(
&self,
index: usize,
generic: Option<&description::CallTypes>,
) -> Result<Option<Arc<ValidatedTypes>>, DecodeError> {
let spec = &self.declarations[index].spec;
let Some(generic) = generic else {
return spec.validate_call(None).map(|types| types.map(Arc::new));
};
let admitted = &self.admitted[index];
if let Some(types) = lock(admitted).get(generic) {
return Ok(Some(Arc::clone(types)));
}
let types = Arc::new(
spec.validate_call(Some(generic))?
.expect("a generic call's views validate to its types"),
);
let size = types.types().len();
if size <= ADMITTED_VIEW {
let mut admitted = lock(admitted);
let held: usize = admitted.values().map(|types| types.types().len()).sum();
if admitted.len() >= ADMITTED || held + size > ADMITTED_BYTES {
admitted.clear();
}
admitted.insert(generic.clone(), Arc::clone(&types));
}
Ok(Some(types))
}
pub(crate) fn run_process(&self, mut input: impl Read, sink: &Sink) -> io::Result<()> {
self.serve(&mut input, sink, FRAME_LIMIT)
}
fn serve(&self, input: &mut impl Read, sink: &Sink, limit: usize) -> io::Result<()> {
let open: Open = Mutex::new(HashMap::new());
std::thread::scope(|scope| {
let calls = Tasks::scoped(scope, Bound::Unbounded);
loop {
let frame = match read_frame(input, limit) {
Ok(Some(frame)) => frame,
Ok(None) => break,
Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => break,
Err(error) => return Err(error),
};
let body = match frame {
Frame::Body(body) => body,
Frame::TooLarge { length, head } => {
if let Some((run, call)) = Message::head(&head, &[Kind::Call]) {
let reason = format!(
"the call is {length} bytes, larger than the {limit} this implementation reads"
);
write(sink, run, call, Answered::NoAnswer(reason))?;
}
continue;
}
};
match Message::parse(Route::Process, &body) {
Ok(Message::Describe { reply_limit, .. }) => {
sink.describe(&self.described(), reply_limit)?;
}
Ok(Message::Call(call)) => {
let cancelled = Cancellation::default();
if call.cancelled() {
cancelled.cancel();
}
lock(&open)
.entry((call.run, call.call.clone()))
.or_default()
.push(cancelled.clone());
let handed = Handed {
call: Some(call),
cancelled,
open: &open,
sink,
};
calls.spawn_with_stack("flow-call", CALL_STACK, move || {
handed.answer(self);
});
}
Ok(Message::Cancel { run, call }) => {
for cancelled in lock(&open).get(&(run, call)).into_iter().flatten() {
cancelled.cancel();
}
}
Ok(
Message::Ack { .. }
| Message::Described(_)
| Message::Reply(_)
| Message::Hold { .. }
| Message::NoAnswer { .. }
| Message::Log(_)
| Message::Type { .. }
| Message::Typed { .. },
) => {}
Err(error) => {
if let Some((run, call)) = Message::head(&body, &[Kind::Call]) {
let reason = format!("the call does not read: {error}");
write(sink, run, call, Answered::NoAnswer(reason))?;
}
}
}
}
calls.join().map_err(io::Error::other)
})
}
fn described(&self) -> Message {
Message::described(
self.declarations
.iter()
.map(|declaration| (declaration.identity.clone(), declaration.spec.clone()))
.collect(),
)
}
fn answer(&self, call: &Call, cancelled: Cancellation, sink: &Sink) -> Answered {
let Some((index, declaration)) = usize::try_from(call.tool)
.ok()
.and_then(|tool| Some((tool, self.declarations.get(tool)?)))
else {
return Answered::NoAnswer(format!(
"this implementation serves {} declarations, and none is number {}",
self.declarations.len(),
call.tool
));
};
let spec = &declaration.spec;
let types = match self.types(index, call.views()) {
Ok(types) => types,
Err(error) => return Answered::NoAnswer(format!("invalid call types: {error}")),
};
let bytes = &call.args.0[..];
let context = Context {
key: CallKey::new(call.run, call.call.clone()),
cancelled,
types: types.clone(),
sink: Some(sink.clone()),
};
let args = match types.as_deref() {
Some(types) => Args::new(
bytes,
types.catalog(),
types.params().iter().map(|(_, ty)| ty).collect(),
types.result(),
),
None => Args::new(
bytes,
spec.catalog(),
spec.signature().params.iter().map(|(_, ty)| ty).collect(),
&spec.signature().result,
),
};
stopped(|| (declaration.adapter.0)(&context, &args))
}
}
fn stopped(answer: impl FnOnce() -> Answered) -> Answered {
catch_unwind(AssertUnwindSafe(answer)).unwrap_or_else(|panic| {
let why = panic
.downcast_ref::<&str>()
.map(|text| (*text).to_owned())
.or_else(|| panic.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "it panicked".to_owned());
Answered::NoAnswer(format!("the implementation stopped: {why}"))
})
}
struct Handed<'a> {
call: Option<Call>,
cancelled: Cancellation,
open: &'a Open,
sink: &'a Sink,
}
impl Handed<'_> {
fn answer(mut self, server: &Server) {
let Some(call) = self.call.take() else {
return;
};
let answered = server.answer(&call, self.cancelled.clone(), self.sink);
finished(self.open, &(call.run, call.call.clone()), &self.cancelled);
if call.cancelled() && matches!(answered, Answered::Hold(_)) {
return;
}
let _ = write(self.sink, call.run, call.call, answered);
}
}
impl Drop for Handed<'_> {
fn drop(&mut self) {
if let Some(call) = self.call.take() {
finished(self.open, &(call.run, call.call.clone()), &self.cancelled);
let reason = "no thread could be made for the call".to_owned();
let _ = write(self.sink, call.run, call.call, Answered::NoAnswer(reason));
}
}
}
type Open = Mutex<HashMap<(RunId, CallRef), Vec<Cancellation>>>;
fn finished(open: &Open, key: &(RunId, CallRef), cancelled: &Cancellation) {
let mut open = lock(open);
let flags = open
.get_mut(key)
.expect("a running call's key stays open until it finishes");
flags.retain(|flag| !Arc::ptr_eq(&flag.0, &cancelled.0));
if flags.is_empty() {
open.remove(key);
}
}
fn write(sink: &Sink, run: RunId, call: CallRef, answered: Answered) -> io::Result<()> {
let message = match answered {
Answered::Reply(outcome) => Message::Reply(Reply { run, call, outcome }),
Answered::Hold(retry_at) => Message::Hold {
run,
call,
retry_at,
},
Answered::NoAnswer(reason) => Message::NoAnswer { run, call, reason },
};
sink.send(&message)
}
pub(crate) fn logging_to<T>(sink: &Sink, serve: impl FnOnce() -> T) -> T {
*lock(&PROCESS) = Some(sink.clone());
let served = serve();
lock(&PROCESS).take();
served
}
impl Sink {
pub(crate) fn new(writer: impl Write + Send + 'static) -> Sink {
Sink(Arc::new(Mutex::new(Output {
writer: Box::new(writer),
reply_limit: None,
asked: false,
held: Vec::new(),
})))
}
fn send(&self, message: &Message) -> io::Result<()> {
let mut output = lock(&self.0);
let frame = message.frame();
if let (Some(limit), Message::Reply(reply)) = (output.reply_limit, message) {
let mut answer = Vec::new();
flow_abi::wire::Wire::write(&reply.outcome, &mut answer);
let length = answer.len();
if u64::try_from(length).unwrap_or(u64::MAX) > limit {
return write_frame(
&mut output.writer,
&Message::NoAnswer {
run: reply.run,
call: reply.call.clone(),
reason: format!(
"the answer is {length} bytes, past the host's reply_limit of {limit}"
),
},
);
}
}
output.writer.write_all(&frame)?;
output.writer.flush()
}
fn describe(&self, answer: &Message, reply_limit: u64) -> io::Result<()> {
let mut output = lock(&self.0);
output.reply_limit = Some(reply_limit);
output.asked = true;
for log in std::mem::take(&mut output.held) {
write_frame(&mut output.writer, &Message::Log(log))?;
}
write_frame(&mut output.writer, answer)
}
}
impl<'a> Args<'a> {
pub(crate) fn new(
bytes: &'a [u8],
catalog: &'a Catalog,
params: Vec<&'a Type>,
result: &'a Type,
) -> Self {
Args {
reader: RefCell::new(Reader::new(bytes)),
catalog,
params,
next: Cell::new(0),
result,
}
}
}
#[cfg(test)]
impl Server {
pub(crate) fn run(
&self,
mut input: impl Read,
output: impl Write + Send + 'static,
) -> io::Result<()> {
self.serve(&mut input, &Sink::new(output), FRAME_LIMIT)
}
pub(crate) fn admitted(&self, index: usize) -> usize {
lock(&self.admitted[index]).len()
}
pub(crate) fn run_within(
&self,
mut input: impl Read,
output: impl Write + Send + 'static,
limit: usize,
) -> io::Result<()> {
self.serve(&mut input, &Sink::new(output), limit)
}
pub(crate) fn served(&self, input: &[u8]) -> Vec<u8> {
let output = Buffer::default();
self.run(input, output.clone()).expect("served");
output.taken()
}
}
#[cfg(test)]
#[derive(Clone, Default)]
pub(crate) struct Buffer(Arc<Mutex<Vec<u8>>>);
#[cfg(test)]
impl Buffer {
pub(crate) fn taken(&self) -> Vec<u8> {
std::mem::take(&mut lock(&self.0))
}
}
#[cfg(test)]
impl Write for Buffer {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
lock(&self.0).extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
use super::*;
#[test]
fn a_call_no_thread_ran_is_answered_with_no_answer_and_forgotten() {
let output = Buffer::default();
let sink = Sink::new(output.clone());
let open: Open = Mutex::new(HashMap::new());
let run = RunId::parse("0123456789abcdef0123456789abcdef").expect("a run id");
let call = CallRef::parse("root#1").expect("a call id");
let cancelled = Cancellation::default();
lock(&open)
.entry((run, call.clone()))
.or_default()
.push(cancelled.clone());
drop(Handed {
call: Some(Call {
run,
call: call.clone(),
tool: 0,
flags: flow_tool_protocol::Flags::Plain,
args: flow_abi::wire::Rest::default(),
}),
cancelled,
open: &open,
sink: &sink,
});
assert!(lock(&open).is_empty(), "the call is forgotten");
let written = output.taken();
let Ok(Some(Frame::Body(body))) = read_frame(&mut &written[..], FRAME_LIMIT) else {
panic!("one frame is written: {written:?}");
};
assert_eq!(
Message::parse(Route::Process, &body).expect("a message"),
Message::NoAnswer {
run,
call,
reason: "no thread could be made for the call".to_owned(),
}
);
}
}