use std::collections::HashMap;
use std::io::{self, BufRead, Write};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use flow_abi::{Json, Limits, TypeSpec, ValidatedTypes};
use crate::data::{ContextCodec, Data, DecodeError, variant, within};
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Problem<E> {
Failed(E),
NotRun(String),
Unknown(String),
}
#[derive(Clone, Debug)]
pub struct Context {
run: String,
call: String,
schema: Option<Json>,
cancelled: Arc<AtomicBool>,
types: Option<Arc<ValidatedTypes>>,
}
impl Context {
#[allow(clippy::needless_pass_by_value)] pub fn try_new(
run: &str,
call: &str,
spec: &TypeSpec,
schema: Option<Json>,
types: Option<Json>,
cancelled: Arc<AtomicBool>,
) -> Result<Context, DecodeError> {
let types = spec
.validate_call(schema.as_ref(), types.as_ref())?
.map(Arc::new);
Ok(Context {
run: run.to_owned(),
call: call.to_owned(),
schema,
cancelled,
types,
})
}
pub fn types(&self) -> Option<&ValidatedTypes> {
self.types.as_deref()
}
fn graph(&self) -> Result<Arc<ValidatedTypes>, DecodeError> {
self.types
.clone()
.ok_or_else(|| crate::data::refused("nongeneric context has no dynamic codecs"))
}
pub fn codec(&self, name: &str) -> Result<ContextCodec, DecodeError> {
let graph = self.graph()?;
let ty = graph
.binding(name)
.cloned()
.ok_or_else(|| crate::data::refused(format!("unknown binding {name}")))?;
ContextCodec::new(graph, ty, flow_abi::Mode::Reply)
}
pub fn argument_codec(&self, name: &str) -> Result<ContextCodec, DecodeError> {
let graph = self.graph()?;
let ty = graph
.argument(name)
.cloned()
.ok_or_else(|| crate::data::refused(format!("unknown argument {name}")))?;
ContextCodec::new(graph, ty, flow_abi::Mode::Rebuild)
}
pub fn success_codec(&self) -> Result<ContextCodec, DecodeError> {
let graph = self.graph()?;
ContextCodec::new(graph.clone(), graph.ok().clone(), flow_abi::Mode::Reply)
}
pub fn failure_codec(&self) -> Result<ContextCodec, DecodeError> {
let graph = self.graph()?;
ContextCodec::new(graph.clone(), graph.err().clone(), flow_abi::Mode::Reply)
}
pub fn run(&self) -> &str {
&self.run
}
pub fn call(&self) -> &str {
&self.call
}
pub fn schema(&self) -> Option<&Json> {
self.schema.as_ref()
}
pub fn log(&self, level: &str, message: &str) -> io::Result<()> {
if !matches!(level, "trace" | "debug" | "info" | "warn" | "error") {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"log level must be trace, debug, info, warn or error",
));
}
let record = Json::Object(vec![
("run".into(), Json::String(self.run.clone())),
("call".into(), Json::String(self.call.clone())),
("level".into(), Json::String(level.into())),
("message".into(), Json::String(message.into())),
]);
let line = format!("\nFLOW_LOG {}\n", record.canonical());
io::stderr().lock().write_all(line.as_bytes())
}
pub fn cancelled(&self) -> bool {
self.cancelled.load(Ordering::SeqCst)
}
pub fn cancel(&self) {
self.cancelled.store(true, Ordering::SeqCst);
}
}
#[derive(Debug)]
pub struct Args<'j>(&'j Json);
impl Args<'_> {
pub fn json(&self, name: &str) -> Result<&Json, DecodeError> {
self.0
.get(name)
.ok_or_else(|| crate::data::inside(crate::data::refused("is missing"), name))
}
pub fn take<T: Data>(&self, name: &str) -> Result<T, DecodeError> {
match self.0.get(name) {
Some(value) => within(value, name, T::decode),
None => Err(crate::data::inside(
crate::data::refused("is missing"),
name,
)),
}
}
}
type Handler = Box<dyn Fn(&Context, &Args<'_>) -> Json + Send + Sync>;
pub(crate) struct Declaration {
entry: Json,
spec: TypeSpec,
handler: Handler,
}
impl std::fmt::Debug for Declaration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Declaration")
.field("entry", &self.entry)
.finish_non_exhaustive()
}
}
impl Declaration {
pub(crate) fn new<T, E, F>(entry: &str, spec: TypeSpec, method: F) -> Declaration
where
T: Data,
E: Data,
F: Fn(&Context, &Args<'_>) -> Result<Result<T, Problem<E>>, DecodeError>
+ Send
+ Sync
+ 'static,
{
let entry = flow_abi::parse(entry, &Limits::default()).expect("a declaration's entry");
Declaration {
entry,
spec,
handler: Box::new(move |context, args| outcome(method(context, args))),
}
}
pub(crate) fn contextual<F>(entry: &str, spec: TypeSpec, method: F) -> Declaration
where
F: Fn(&Context, &Args<'_>) -> Result<Result<Json, Problem<Json>>, DecodeError>
+ Send
+ Sync
+ 'static,
{
let entry = flow_abi::parse(entry, &Limits::default()).expect("a declaration's entry");
Declaration {
entry,
spec,
handler: Box::new(move |context, args| outcome(method(context, args))),
}
}
fn serves(&self, tool: &Json) -> bool {
let named = |key: &str| self.entry.get("tool").and_then(|own| own.get(key));
let origin = if let Some(package) = named("package") {
named("repository").is_none()
&& tool.get("repository").is_none()
&& tool.get("package") == Some(package)
} else {
tool.get("package").is_none()
&& named("repository").is_some()
&& named("repository") == tool.get("repository")
};
origin
&& ["file", "name"]
.into_iter()
.all(|key| named(key) == tool.get(key) && named(key).is_some())
}
}
fn outcome<T: Data, E: Data>(answer: Result<Result<T, Problem<E>>, DecodeError>) -> Json {
match answer {
Ok(Ok(value)) => variant("Ok", value.encode()),
Ok(Err(Problem::Failed(error))) => variant("Failed", error.encode()),
Ok(Err(Problem::NotRun(reason))) => variant("NotRun", Json::String(reason)),
Ok(Err(Problem::Unknown(reason))) => variant("Unknown", Json::String(reason)),
Err(error) => variant(
"NotRun",
Json::String(format!("the arguments do not decode: {error}")),
),
}
}
#[cfg(test)]
mod origin_tests {
use super::*;
fn json(value: &str) -> Json {
flow_abi::parse(value, &Limits::default()).unwrap()
}
#[test]
fn package_calls_do_not_alias_other_packages_or_repository_origins() {
for (origin, matched) in [
(r#""package":"flow/example""#, true),
(r#""package":"other/example""#, false),
(r#""repository":"flow/example""#, false),
(r#""package":"flow/example","repository":null"#, false),
] {
let declaration = Declaration::new::<String, String, _>(
r#"{"tool":{"package":"flow/example","version":"v1","file":"","name":"act"},"fingerprint":"sha256:x","signature":{}}"#,
TypeSpec::read(&json(
r#"{"generic":[],"params":[],"ok":"Text","err":"Text","declarations":{}}"#,
))
.unwrap(),
|_, _| Ok(Ok("called".into())),
);
let server = Server::new("0.1", vec![declaration]);
let input = format!(
"{{\"jsonrpc\":\"2.0\",\"method\":\"call\",\"params\":{{\"run\":\"r\",\"call\":\"c\",\"tool\":{{{origin},\"version\":\"v9\",\"file\":\"\",\"name\":\"act\"}},\"args\":{{}}}}}}\n"
);
let mut output = Vec::new();
server
.run(std::io::Cursor::new(input), &mut output)
.unwrap();
let reply = json(std::str::from_utf8(&output).unwrap().trim());
let outcome = reply.get("params").unwrap().get("outcome").unwrap();
if matched {
assert_eq!(outcome, &json(r#"{"Ok":"called"}"#));
} else {
assert!(outcome.get("NotRun").is_some());
}
}
}
}
#[derive(Debug)]
pub(crate) struct Server {
data: String,
declarations: Vec<Declaration>,
}
impl Server {
pub(crate) fn new(data: &str, declarations: Vec<Declaration>) -> Server {
Server {
data: data.to_owned(),
declarations,
}
}
pub(crate) fn run(&self, input: impl BufRead, output: impl Write + Send) -> io::Result<()> {
let output = Mutex::new(output);
let open: Mutex<HashMap<(String, String), Arc<AtomicBool>>> = Mutex::new(HashMap::new());
std::thread::scope(|scope| {
for line in input.lines() {
let line = line?;
let Ok(message) = flow_abi::parse(&line, &crate::data::LIMITS) else {
continue;
};
let params = message.get("params");
let text = |key: &str| match params.and_then(|params| params.get(key)) {
Some(Json::String(text)) => Some(text.clone()),
_ => None,
};
match message.get("method") {
Some(Json::String(method)) if method == "describe" => {
let id = message.get("id").cloned().unwrap_or(Json::Null);
write(&output, &self.described(id))?;
}
Some(Json::String(method)) if method == "call" => {
let (Some(run), Some(call)) = (text("run"), text("call")) else {
continue;
};
let params = params.cloned().unwrap_or(Json::Null);
let cancelled = Arc::new(AtomicBool::new(false));
lock(&open).insert((run.clone(), call.clone()), cancelled.clone());
let (output, open) = (&output, &open);
scope.spawn(move || {
let outcome = self.answer(&run, &call, cancelled, ¶ms);
lock(open).remove(&(run.clone(), call.clone()));
let reply = reply(&run, &call, outcome);
let _ = write(output, &reply);
});
}
Some(Json::String(method)) if method == "cancel" => {
if let (Some(run), Some(call)) = (text("run"), text("call"))
&& let Some(context) = lock(&open).get(&(run, call))
{
context.store(true, Ordering::SeqCst);
}
}
_ => {}
}
}
Ok(())
})
}
fn described(&self, id: Json) -> Json {
let tools = self
.declarations
.iter()
.map(|declaration| declaration.entry.clone())
.collect();
Json::Object(vec![
("jsonrpc".to_owned(), Json::String("2.0".to_owned())),
("id".to_owned(), id),
(
"result".to_owned(),
Json::Object(vec![
("data".to_owned(), Json::String(self.data.clone())),
("tools".to_owned(), Json::Array(tools)),
]),
),
])
}
fn answer(&self, run: &str, call: &str, cancelled: Arc<AtomicBool>, params: &Json) -> Json {
let tool = params.get("tool").cloned().unwrap_or(Json::Null);
let Some(declaration) = self.declarations.iter().find(|d| d.serves(&tool)) else {
return variant(
"NotRun",
Json::String(format!(
"this implementation serves no declaration {}",
tool.canonical()
)),
);
};
let context = match Context::try_new(
run,
call,
&declaration.spec,
params.get("schema").cloned(),
params.get("types").cloned(),
cancelled,
) {
Ok(context) => context,
Err(error) => {
return variant(
"NotRun",
Json::String(format!("invalid call types: {error}")),
);
}
};
let args = params.get("args").cloned().unwrap_or(Json::Null);
let answered = catch_unwind(AssertUnwindSafe(|| {
(declaration.handler)(&context, &Args(&args))
}));
answered.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());
variant(
"Unknown",
Json::String(format!("the implementation stopped: {why}")),
)
})
}
}
fn reply(run: &str, call: &str, outcome: Json) -> Json {
Json::Object(vec![
("jsonrpc".to_owned(), Json::String("2.0".to_owned())),
("method".to_owned(), Json::String("reply".to_owned())),
(
"params".to_owned(),
Json::Object(vec![
("run".to_owned(), Json::String(run.to_owned())),
("call".to_owned(), Json::String(call.to_owned())),
("outcome".to_owned(), outcome),
]),
),
])
}
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn write(output: &Mutex<impl Write>, message: &Json) -> io::Result<()> {
let mut line = message.canonical();
line.push('\n');
let mut output = lock(output);
output.write_all(line.as_bytes())?;
output.flush()
}