use std::cell::{Cell, RefCell};
use std::io::Write;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use flow_abi::{Catalog, Outcome, TypeSpec, ValidatedTypes, description};
use flow_span::{CallRef, RunId};
use flow_tool_protocol::{Level, Log, Message, write_frame};
use flow_types::{StdEnum, ToolProblemCtor, Type};
use flow_abi::EncodeError;
use flow_abi::Mode;
use flow_abi::primitives::Reader;
use flow_abi::wire::{Shaped, ValueReader, ValueWriter, WireForm};
use crate::data::{DecodeError, LIMITS, inside, refused};
use crate::key::CallKey;
use flow_value::Instant;
#[cfg(unix)]
mod serving;
#[cfg(all(test, unix))]
pub(crate) use serving::Buffer;
#[cfg(unix)]
pub(crate) use serving::{Declaration, Server, logging_to};
#[derive(Clone, PartialEq, Eq, Debug)]
#[expect(
clippy::exhaustive_enums,
reason = "mirrors std's ToolProblem, whose cases authors match on"
)]
pub enum ToolProblem {
NotStarted(String),
Interrupted(String),
NetworkError {
sent: bool,
reason: String,
},
}
impl ToolProblem {
fn ctor(&self) -> ToolProblemCtor {
match self {
ToolProblem::NotStarted(_) => ToolProblemCtor::NotStarted,
ToolProblem::Interrupted(_) => ToolProblemCtor::Interrupted,
ToolProblem::NetworkError { .. } => ToolProblemCtor::NetworkError,
}
}
}
impl Shaped for ToolProblem {
const FORM: WireForm = WireForm::Std {
module: "",
name: "ToolProblem",
args: &[],
};
fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
let ctors = flow_abi::form(out.catalog(), ty)
.enumeration()
.and_then(|shape| StdEnum::<ToolProblemCtor>::of(shape.shape).ok())
.ok_or_else(|| out.refuse(ty))?;
let index = ctors.index(self.ctor());
match self {
ToolProblem::NotStarted(reason) | ToolProblem::Interrupted(reason) => {
out.variant(ty, index, &[reason])
}
ToolProblem::NetworkError { sent, reason } => out.variant(ty, index, &[sent, reason]),
}
}
fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
let ctors = flow_abi::form(input.catalog(), ty)
.enumeration()
.and_then(|shape| StdEnum::<ToolProblemCtor>::of(shape.shape).ok())
.ok_or_else(|| input.mismatch(ty))?;
input.variant(ty, |input, index, parts| match ctors.which(index) {
Some(ToolProblemCtor::NotStarted) => parts.read(input).map(ToolProblem::NotStarted),
Some(ToolProblemCtor::Interrupted) => parts.read(input).map(ToolProblem::Interrupted),
Some(ToolProblemCtor::NetworkError) => Ok(ToolProblem::NetworkError {
sent: parts.read(input)?,
reason: parts.read(input)?,
}),
None => Err(input.mismatch(ty)),
})
}
}
impl std::fmt::Display for ToolProblem {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ToolProblem::NotStarted(why) => write!(formatter, "not started: {why}"),
ToolProblem::Interrupted(why) => write!(formatter, "interrupted: {why}"),
ToolProblem::NetworkError { sent: true, reason } => {
write!(
formatter,
"network error after the request went out: {reason}"
)
}
ToolProblem::NetworkError {
sent: false,
reason,
} => write!(
formatter,
"network error before the request went out: {reason}"
),
}
}
}
impl std::error::Error for ToolProblem {}
#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub struct Hold {
pub retry_at: Option<Instant>,
}
impl Hold {
pub fn new() -> Hold {
Hold { retry_at: None }
}
pub fn until(time: std::time::SystemTime) -> Hold {
Hold {
retry_at: Some(
flow_abi::wire::instant_of(time)
.expect("a SystemTime's nanoseconds from the epoch fit an i128"),
),
}
}
}
impl std::fmt::Display for Hold {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.retry_at {
None => write!(formatter, "held"),
Some(retry_at) => write!(formatter, "held, to be asked again at {retry_at}"),
}
}
}
impl std::error::Error for Hold {}
#[derive(Clone, PartialEq, Eq, Debug)]
#[expect(
clippy::exhaustive_enums,
reason = "a call is answered with a problem or held, and nothing else"
)]
pub enum NoAnswer {
Problem(ToolProblem),
Hold(Hold),
}
impl From<ToolProblem> for NoAnswer {
fn from(problem: ToolProblem) -> NoAnswer {
NoAnswer::Problem(problem)
}
}
impl From<Hold> for NoAnswer {
fn from(hold: Hold) -> NoAnswer {
NoAnswer::Hold(hold)
}
}
impl std::fmt::Display for NoAnswer {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
NoAnswer::Problem(problem) => problem.fmt(formatter),
NoAnswer::Hold(hold) => hold.fmt(formatter),
}
}
}
impl std::error::Error for NoAnswer {}
#[derive(Clone, PartialEq, Eq, Debug)]
#[expect(
clippy::exhaustive_enums,
reason = "a Tool answers its own error or does not answer, and nothing else"
)]
pub enum Refusal<E> {
Own(E),
NoAnswer(NoAnswer),
}
impl<E> From<E> for Refusal<E> {
fn from(error: E) -> Refusal<E> {
Refusal::Own(error)
}
}
impl<E> Refusal<E> {
pub fn not_started(reason: String) -> Refusal<E> {
Refusal::problem(ToolProblem::NotStarted(reason))
}
pub fn interrupted(reason: String) -> Refusal<E> {
Refusal::problem(ToolProblem::Interrupted(reason))
}
pub fn problem(problem: ToolProblem) -> Refusal<E> {
Refusal::NoAnswer(NoAnswer::Problem(problem))
}
pub fn hold(hold: Hold) -> Refusal<E> {
Refusal::NoAnswer(NoAnswer::Hold(hold))
}
pub(crate) fn answer<T>(result: Result<T, Refusal<E>>) -> Result<Result<T, E>, NoAnswer> {
match result {
Ok(value) => Ok(Ok(value)),
Err(Refusal::Own(error)) => Ok(Err(error)),
Err(Refusal::NoAnswer(missing)) => Err(missing),
}
}
}
impl<V> From<ToolProblem> for Outcome<V> {
fn from(problem: ToolProblem) -> Outcome<V> {
match problem {
ToolProblem::NotStarted(reason) => Outcome::NotStarted(reason),
ToolProblem::Interrupted(reason) => Outcome::Interrupted(reason),
ToolProblem::NetworkError { sent, reason } => Outcome::NetworkError { sent, reason },
}
}
}
#[cfg(unix)]
impl From<NoAnswer> for Answered {
fn from(missing: NoAnswer) -> Answered {
match missing {
NoAnswer::Problem(problem) => Answered::Reply(problem.into()),
NoAnswer::Hold(Hold { retry_at }) => Answered::Hold(retry_at),
}
}
}
#[cfg(unix)]
#[derive(Clone, PartialEq, Eq, Debug)]
pub(crate) enum Answered {
Reply(Outcome),
Hold(Option<Instant>),
NoAnswer(String),
}
#[derive(Clone, Debug)]
pub struct Context {
key: CallKey,
cancelled: Cancellation,
types: Option<Arc<ValidatedTypes>>,
sink: Option<Sink>,
}
impl Context {
pub fn try_new(
key: CallKey,
spec: &TypeSpec,
generic: Option<&description::CallTypes>,
cancelled: Cancellation,
) -> Result<Context, DecodeError> {
let types = spec.validate_call(generic)?.map(Arc::new);
Ok(Context {
key,
cancelled,
types,
sink: None,
})
}
pub fn types(&self) -> Option<&ValidatedTypes> {
self.types.as_deref()
}
pub fn for_test(key: CallKey) -> Context {
Context {
key,
cancelled: Cancellation::default(),
types: None,
sink: None,
}
}
pub fn run(&self) -> &RunId {
self.key.run()
}
pub fn call(&self) -> &CallRef {
self.key.call()
}
pub fn key(&self) -> CallKey {
self.key.clone()
}
pub fn schema(&self) -> Option<&str> {
self.types.as_deref()?.schema()
}
fn bound(&self) -> Result<(&ValidatedTypes, &Type), DecodeError> {
let types = self.types.as_deref();
match types.map(ValidatedTypes::bindings) {
Some([(_, bound)]) => Ok((types.expect("a generic call's types"), bound)),
_ => Err(refused(
"is not read at a type: the call does not bind exactly one type parameter",
)),
}
}
pub fn decode<T: Shaped>(&self, data: &str) -> Result<T, DecodeError> {
let (types, bound) = self.bound()?;
let value = flow_abi::decode_text(types.catalog(), bound, data, Mode::Reply, &LIMITS)?;
flow_abi::of_shaped_value(&value, types.catalog(), bound)
}
pub fn to_json<T: Shaped>(&self, value: &T) -> Result<String, DecodeError> {
let (types, bound) = self.bound()?;
let value = flow_abi::shaped_value(value, types.catalog(), bound)
.map_err(|error| refused(error.problem))?;
flow_abi::canonical(types.catalog(), bound, &value).map_err(|error| refused(error.problem))
}
pub fn log(&self, level: Level, message: &str) {
if let Some(sink) = &self.sink {
sink.log(Log {
run: Some(*self.run()),
call: Some(self.call().clone()),
level,
message: message.to_owned(),
});
}
}
pub fn cancelled(&self) -> bool {
self.cancelled.is_cancelled()
}
pub fn cancel(&self) {
self.cancelled.cancel();
}
pub fn cancellation(&self) -> Cancellation {
self.cancelled.clone()
}
}
pub fn log(level: Level, message: &str) {
let sink = lock(&PROCESS).clone();
if let Some(sink) = sink {
sink.log(Log {
run: None,
call: None,
level,
message: message.to_owned(),
});
}
}
static PROCESS: Mutex<Option<Sink>> = Mutex::new(None);
#[derive(Clone)]
pub(crate) struct Sink(Arc<Mutex<Output>>);
struct Output {
writer: Box<dyn Write + Send>,
#[cfg(unix)]
reply_limit: Option<u64>,
asked: bool,
held: Vec<Log>,
}
impl std::fmt::Debug for Sink {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.debug_struct("Sink").finish_non_exhaustive()
}
}
impl Sink {
fn log(&self, log: Log) {
let mut output = lock(&self.0);
if output.asked {
let _ = write_frame(&mut output.writer, &Message::Log(log));
} else {
output.held.push(log);
}
}
}
#[derive(Clone, Debug, Default)]
pub struct Cancellation(Arc<CancelState>);
#[derive(Debug, Default)]
struct CancelState {
cancelled: AtomicBool,
woken: tokio::sync::Notify,
}
impl Cancellation {
pub fn is_cancelled(&self) -> bool {
self.0.cancelled.load(Ordering::SeqCst)
}
pub fn cancel(&self) {
self.0.cancelled.store(true, Ordering::SeqCst);
self.0.woken.notify_waiters();
}
pub async fn wait(&self) {
loop {
let woken = self.0.woken.notified();
let mut woken = std::pin::pin!(woken);
woken.as_mut().enable();
if self.is_cancelled() {
return;
}
woken.await;
}
}
}
#[derive(Debug)]
pub struct Args<'a> {
reader: RefCell<Reader<'a>>,
catalog: &'a Catalog,
params: Vec<&'a Type>,
next: Cell<usize>,
#[cfg(unix)]
result: &'a Type,
}
impl Args<'_> {
pub fn take<T: Shaped>(&self, name: &str) -> Result<T, DecodeError> {
let at = self.next.get();
self.next.set(at + 1);
let read = || {
let ty = self
.params
.get(at)
.ok_or_else(|| refused("is no parameter of the declaration"))?;
flow_abi::read_shaped(
&mut self.reader.borrow_mut(),
self.catalog,
ty,
Mode::Rebuild,
&LIMITS,
)
};
read().map_err(|error| inside(error, name))
}
pub fn finish(&self) -> Result<(), DecodeError> {
let reader = self.reader.borrow();
if reader.is_empty() {
Ok(())
} else {
Err(refused(format!(
"ends at byte {}, with {} bytes left over after the last argument",
reader.position(),
reader.remaining()
)))
}
}
#[cfg(unix)]
fn answer<T: Shaped>(&self, value: &T) -> Result<Vec<u8>, DecodeError> {
let mut out = Vec::new();
flow_abi::write_shaped(&mut out, self.catalog, self.result, value)
.map_err(|error| refused(error.problem))?;
Ok(out)
}
}
pub struct Adapter(#[cfg(unix)] Box<Adapted>);
#[cfg(unix)]
type Adapted = dyn Fn(&Context, &Args<'_>) -> Answered + Send + Sync;
impl std::fmt::Debug for Adapter {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.debug_struct("Adapter").finish_non_exhaustive()
}
}
impl Adapter {
pub fn new<T, F>(method: F) -> Adapter
where
T: Shaped,
F: Fn(&Context, &Args<'_>) -> Result<Result<T, NoAnswer>, DecodeError>
+ Send
+ Sync
+ 'static,
{
#[cfg(not(unix))]
{
let _ = method;
Adapter()
}
#[cfg(unix)]
Adapter(Box::new(move |context, args| match method(context, args) {
Ok(Ok(value)) => match args.answer(&value) {
Ok(bytes) => Answered::Reply(Outcome::Ok(flow_abi::wire::Rest(bytes))),
Err(error) => Answered::NoAnswer(format!("the result does not encode: {error}")),
},
Ok(Err(problem)) => problem.into(),
Err(error) => Answered::NoAnswer(format!("the arguments do not decode: {error}")),
}))
}
}
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}