use std::any::Any;
use std::collections::{BTreeMap, BTreeSet};
use std::convert::Infallible;
use std::fmt::Write as _;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use crate::server::Server;
use crate::{Data, Json};
use flow_abi::TypeSpec;
type CloseFuture = Pin<Box<dyn Future<Output = Result<(), String>> + Send>>;
type Close = Box<dyn FnOnce() -> CloseFuture + Send>;
static RESOURCE: Mutex<Option<Arc<dyn Any + Send + Sync>>> = Mutex::new(None);
pub struct Resource<T: Send + Sync + 'static> {
value: Arc<T>,
close: Box<dyn FnOnce(Arc<T>) -> CloseFuture + Send>,
}
impl<T: Send + Sync + 'static> Resource<T> {
pub fn new<F, Fut>(value: T, close: F) -> Self
where
F: FnOnce(Arc<T>) -> Fut + Send + 'static,
Fut: Future<Output = Result<(), String>> + Send + 'static,
{
Self {
value: Arc::new(value),
close: Box::new(move |value| Box::pin(close(value))),
}
}
pub fn sync<F>(value: T, close: F) -> Self
where
F: FnOnce(Arc<T>) -> Result<(), String> + Send + 'static,
{
Self::new(value, move |value| std::future::ready(close(value)))
}
#[doc(hidden)]
pub fn into_lifecycle(self) -> Lifecycle {
let value = self.value.clone();
Lifecycle {
value: self.value,
close: Box::new(move || (self.close)(value)),
}
}
}
pub struct Lifecycle {
value: Arc<dyn Any + Send + Sync>,
close: Close,
}
pub type Start = fn() -> Result<Lifecycle, String>;
impl crate::Context {
pub fn resource<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
RESOURCE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.as_ref()?
.clone()
.downcast::<T>()
.ok()
}
}
pub trait FlowType: Data {
#[doc(hidden)]
fn flow_type(types: &mut Types) -> String;
fn decode_context(
codec: &crate::ContextCodec,
value: &Json,
) -> Result<Self, crate::DecodeError> {
Self::decode(&codec.decode(value)?)
}
fn encode_context(&self, codec: &crate::ContextCodec) -> Result<Json, crate::DecodeError> {
codec.encode(&self.encode())
}
fn encode_field(&self) -> Option<Json> {
Some(self.encode())
}
fn decode_field(value: Option<&Json>) -> Result<Self, crate::DecodeError> {
Self::decode(value.ok_or_else(|| crate::data::refused("is missing"))?)
}
}
#[doc(hidden)]
pub trait Shape {
fn shape(types: &mut Types) -> String;
}
#[derive(Default)]
pub struct Types {
definitions: BTreeMap<String, String>,
owners: BTreeMap<String, &'static str>,
collision: Option<String>,
parameters: Vec<Vec<String>>,
}
impl Types {
pub fn parameters(&mut self, names: &[&str]) {
self.parameters
.push(names.iter().map(|s| (*s).into()).collect());
}
pub fn end_parameters(&mut self) {
self.parameters.pop();
}
pub fn begin(&mut self, name: &str, owner: &'static str) -> bool {
if let Some(previous) = self.owners.get(name) {
if *previous != owner {
self.collision = Some(format!(
"distinct Rust types share Flow name {name}: {previous} and {owner}"
));
}
false
} else {
self.owners.insert(name.into(), owner);
true
}
}
pub fn finish(&mut self, name: &str, source: String) {
self.definitions.insert(name.into(), source);
}
}
#[derive(Clone, Debug)]
pub struct Value<const INDEX: usize> {
value: Json,
codec: crate::ContextCodec,
}
impl<const INDEX: usize> Value<INDEX> {
pub fn new(codec: &crate::ContextCodec, value: &Json) -> Result<Self, crate::DecodeError> {
Ok(Self {
value: codec.decode(value)?,
codec: codec.clone(),
})
}
pub fn json(&self) -> &Json {
&self.value
}
}
impl<const INDEX: usize> Data for Value<INDEX> {
fn encode(&self) -> Json {
self.value.clone()
}
fn decode(_: &Json) -> Result<Self, crate::DecodeError> {
Err(crate::data::refused(
"a generic value requires a validated invocation codec",
))
}
}
impl<const INDEX: usize> FlowType for Value<INDEX> {
fn flow_type(types: &mut Types) -> String {
types
.parameters
.last()
.and_then(|names| names.get(INDEX))
.cloned()
.expect("generic parameter scope")
}
fn decode_context(
codec: &crate::ContextCodec,
value: &Json,
) -> Result<Self, crate::DecodeError> {
Self::new(codec, value)
}
}
impl<const INDEX: usize> PartialEq for Value<INDEX> {
fn eq(&self, other: &Self) -> bool {
self.cmp(other).is_eq()
}
}
impl<const INDEX: usize> Eq for Value<INDEX> {}
impl<const INDEX: usize> PartialOrd for Value<INDEX> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl<const INDEX: usize> Ord for Value<INDEX> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.codec
.compare(&self.value, &other.value)
.expect("values of the same generic Rust type have the same admitted Flow type")
}
}
macro_rules! scalar {
($($rust:ty => $flow:literal),* $(,)?) => {$ (
impl FlowType for $rust { fn flow_type(_: &mut Types) -> String { $flow.to_owned() } }
)*};
}
scalar!(crate::Int => "Int", crate::Decimal => "Decimal", bool => "Bool", String => "Text", () => "Unit", Infallible => "Never", crate::Bytes => "Bytes", crate::Duration => "duration.Duration", crate::Instant => "time.Instant", crate::JsonValue => "json.Value");
impl<T: FlowType> FlowType for Vec<T> {
fn flow_type(types: &mut Types) -> String {
format!("List<{}>", T::flow_type(types))
}
fn encode_context(&self, codec: &crate::ContextCodec) -> Result<Json, crate::DecodeError> {
let child = codec.element()?;
let values = self
.iter()
.map(|value| value.encode_context(&child))
.collect::<Result<Vec<_>, _>>()?;
codec.encode(&Json::Array(values))
}
fn decode_context(
codec: &crate::ContextCodec,
value: &Json,
) -> Result<Self, crate::DecodeError> {
let value = codec.decode(value)?;
let Json::Array(values) = value else {
return Err(crate::data::refused("expected list"));
};
let child = codec.element()?;
values
.iter()
.map(|value| T::decode_context(&child, value))
.collect()
}
}
impl<T: FlowType, E: FlowType> FlowType for std::result::Result<T, E> {
fn flow_type(types: &mut Types) -> String {
format!("Result<{}, {}>", T::flow_type(types), E::flow_type(types))
}
fn encode_context(&self, codec: &crate::ContextCodec) -> Result<Json, crate::DecodeError> {
let value = match self {
Ok(value) => crate::data::variant(
"Ok",
value.encode_context(&codec.variant("Ok")?.positional(0)?)?,
),
Err(value) => crate::data::variant(
"Err",
value.encode_context(&codec.variant("Err")?.positional(0)?)?,
),
};
codec.encode(&value)
}
fn decode_context(
codec: &crate::ContextCodec,
value: &Json,
) -> Result<Self, crate::DecodeError> {
let value = codec.decode(value)?;
match crate::data::constructor(&value)? {
("Ok", Some(payload)) => {
T::decode_context(&codec.variant("Ok")?.positional(0)?, payload).map(Ok)
}
("Err", Some(payload)) => {
E::decode_context(&codec.variant("Err")?.positional(0)?, payload).map(Err)
}
_ => Err(crate::data::refused("expected Result")),
}
}
}
impl<T: FlowType> FlowType for Option<T> {
fn encode_context(&self, codec: &crate::ContextCodec) -> Result<Json, crate::DecodeError> {
let value = match self {
None => Json::String("None".into()),
Some(value) => crate::data::variant("Some", value.encode_context(&codec.element()?)?),
};
codec.encode(&value)
}
fn decode_context(
codec: &crate::ContextCodec,
value: &Json,
) -> Result<Self, crate::DecodeError> {
let value = codec.decode(value)?;
match crate::data::constructor(&value)? {
("None", None) => Ok(None),
("Some", Some(value)) => T::decode_context(&codec.element()?, value).map(Some),
_ => Err(crate::data::refused("expected Option")),
}
}
fn flow_type(types: &mut Types) -> String {
format!("Option<{}>", T::flow_type(types))
}
fn encode_field(&self) -> Option<Json> {
self.as_ref().map(Data::encode)
}
fn decode_field(value: Option<&Json>) -> Result<Self, crate::DecodeError> {
match value {
None | Some(Json::Null) => Ok(None),
Some(value) => T::decode(value).map(Some),
}
}
}
pub fn encode_field<T: FlowType>(fields: &mut Vec<(String, Json)>, name: &str, value: &T) {
if let Some(value) = value.encode_field() {
fields.push((name.into(), value));
}
}
pub fn decode_field<T: FlowType>(json: &Json, name: &str) -> Result<T, crate::DecodeError> {
T::decode_field(json.get(name)).map_err(|error| crate::data::inside(error, name))
}
impl<T: FlowType + Ord> FlowType for BTreeSet<T> {
fn encode_context(&self, codec: &crate::ContextCodec) -> Result<Json, crate::DecodeError> {
let child = codec.element()?;
let values = self
.iter()
.map(|value| value.encode_context(&child))
.collect::<Result<Vec<_>, _>>()?;
codec.encode(&Json::Array(values))
}
fn decode_context(
codec: &crate::ContextCodec,
value: &Json,
) -> Result<Self, crate::DecodeError> {
let value = codec.decode(value)?;
let Json::Array(values) = value else {
return Err(crate::data::refused("expected set"));
};
let child = codec.element()?;
values
.iter()
.map(|value| T::decode_context(&child, value))
.collect()
}
fn flow_type(types: &mut Types) -> String {
format!("Set<{}>", T::flow_type(types))
}
}
impl<K: FlowType + Ord, V: FlowType> FlowType for BTreeMap<K, V> {
fn encode_context(&self, codec: &crate::ContextCodec) -> Result<Json, crate::DecodeError> {
let key = codec.key()?;
let item = codec.value()?;
let pairs = self
.iter()
.map(|(k, v)| Ok((k.encode_context(&key)?, v.encode_context(&item)?)))
.collect::<Result<Vec<_>, crate::DecodeError>>()?;
let value = if key.is_text() {
Json::Object(
pairs
.into_iter()
.map(|(k, v)| match k {
Json::String(k) => Ok((k, v)),
_ => Err(crate::data::refused("expected text key")),
})
.collect::<Result<_, _>>()?,
)
} else {
Json::Array(
pairs
.into_iter()
.map(|(k, v)| Json::Array(vec![k, v]))
.collect(),
)
};
codec.encode(&value)
}
fn decode_context(
codec: &crate::ContextCodec,
value: &Json,
) -> Result<Self, crate::DecodeError> {
let value = codec.decode(value)?;
let key = codec.key()?;
let item = codec.value()?;
match value {
Json::Array(values) => values
.iter()
.map(|value| {
let parts = crate::data::positional(value, 2)?;
Ok((
K::decode_context(&key, &parts[0])?,
V::decode_context(&item, &parts[1])?,
))
})
.collect(),
Json::Object(values) => values
.iter()
.map(|(k, v)| {
Ok((
K::decode_context(&key, &Json::String(k.clone()))?,
V::decode_context(&item, v)?,
))
})
.collect(),
_ => Err(crate::data::refused("expected dictionary")),
}
}
fn flow_type(types: &mut Types) -> String {
format!("Dict<{}, {}>", K::flow_type(types), V::flow_type(types))
}
}
impl<T: FlowType> FlowType for Box<T> {
fn encode_context(&self, codec: &crate::ContextCodec) -> Result<Json, crate::DecodeError> {
T::encode_context(self, codec)
}
fn decode_context(
codec: &crate::ContextCodec,
value: &Json,
) -> Result<Self, crate::DecodeError> {
T::decode_context(codec, value).map(Box::new)
}
fn flow_type(types: &mut Types) -> String {
T::flow_type(types)
}
}
macro_rules! tuple {
($($t:ident),+) => { #[allow(non_snake_case, unused_assignments)] impl<$($t: FlowType),+> FlowType for ($($t,)+) { fn flow_type(types: &mut Types) -> String { format!("({})",vec![$($t::flow_type(types)),+].join(", ")) }
fn decode_context(codec: &crate::ContextCodec,value:&Json)->Result<Self,crate::DecodeError> {
let normalized=codec.decode(value)?; let Json::Array(parts)=normalized else { return Err(crate::data::refused("expected tuple")); };
let mut index=0; Ok(($({ let child=codec.positional(index)?; let value=$t::decode_context(&child,&parts[index])?; index+=1; value },)+))
}
fn encode_context(&self,codec:&crate::ContextCodec)->Result<Json,crate::DecodeError> {
let ($($t,)+)=self; let mut index=0; let parts=vec![$({ let child=codec.positional(index)?; index+=1; $t.encode_context(&child)? },)+]; codec.encode(&Json::Array(parts))
} } };
}
tuple!(A, B);
tuple!(A, B, C);
tuple!(A, B, C, D);
type Factory = fn(&str, TypeSpec) -> crate::__bridge::Adapter;
pub struct Function {
name: &'static str,
generic: Vec<String>,
docs: &'static str,
params: Vec<(String, String)>,
ok: String,
err: String,
types: Types,
factory: Factory,
}
impl Function {
pub(crate) fn with_generics(mut self, names: &[&str]) -> Self {
self.generic = names.iter().map(|name| (*name).into()).collect();
self
}
pub(crate) fn new(
name: &'static str,
docs: &'static str,
params: Vec<(String, String)>,
ok: String,
err: String,
types: Types,
factory: Factory,
) -> Self {
Self {
name,
generic: Vec::new(),
docs,
params,
ok,
err,
types,
factory,
}
}
}
pub fn extract(functions: &[Function]) -> Result<String, String> {
let mut definitions = BTreeMap::new();
let mut owners = BTreeMap::new();
let mut names = BTreeSet::new();
let mut source = String::new();
for function in functions {
if let Some(error) = &function.types.collision {
return Err(error.clone());
}
if !names.insert(function.name) {
return Err(format!("duplicate Tool name {}", function.name));
}
for (name, owner) in &function.types.owners {
if let Some(previous) = owners.insert(name, owner)
&& previous != owner
{
return Err(format!("distinct Rust types share Flow name {name}"));
}
}
for (name, definition) in &function.types.definitions {
definitions.insert(name, definition);
}
}
for (needle, module) in [
("json.Value", "json"),
("duration.Duration", "duration"),
("time.Instant", "time"),
] {
if functions.iter().any(|f| {
f.params.iter().any(|(_, t)| t.contains(needle))
|| f.ok.contains(needle)
|| f.err.contains(needle)
}) || definitions.values().any(|s| s.contains(needle))
{
let _ = writeln!(source, "use \"std@v1/{module}\"\n");
}
}
for definition in definitions.values() {
source.push_str(definition);
source.push_str("\n\n");
}
for function in functions {
for line in function.docs.lines() {
source.push_str("/// ");
source.push_str(line);
source.push('\n');
}
let params = function
.params
.iter()
.map(|(name, ty)| format!("{name}: {ty}"))
.collect::<Vec<_>>()
.join(", ");
let generics = if function.generic.is_empty() {
String::new()
} else {
format!("<{}>", function.generic.join(", "))
};
let _ = write!(
source,
"@tool pub flow {}{generics}({params}) -> Result<{}, {}>\n\n",
function.name, function.ok, function.err
);
}
Ok(source)
}
pub(crate) fn launcher_with_lifecycle(
functions: &[Function],
start: Option<Start>,
) -> Result<(), String> {
let args = std::env::args().skip(1).collect::<Vec<_>>();
if args == ["extract"] {
print!("{}", extract(functions)?);
return Ok(());
}
if args.len() != 3 || args[0] != "serve" {
return Err("generated launcher expects extract or serve CONTRACT MODULE".into());
}
let contract = std::fs::read_to_string(&args[1]).map_err(|e| e.to_string())?;
serve(functions, &contract, &args[2], start)
}
pub(crate) fn serve(
functions: &[Function],
contract: &str,
module: &str,
start: Option<Start>,
) -> Result<(), String> {
let listing = flow_abi::parse(contract, &crate::data::LIMITS).map_err(|e| e.to_string())?;
let data = text(&listing, "data")?;
let mut declarations = Vec::new();
let mut served = BTreeSet::new();
for program in array(&listing, "programs")? {
let Some(Json::Object(types)) = program.get("types") else {
return Err("contract has no type map".into());
};
let templates = types.iter().cloned().collect::<BTreeMap<_, _>>();
for tool in array(program, "tools")? {
let identity = tool.get("tool").ok_or("Tool has no identity")?;
if text(identity, "file")?.trim_start_matches("./")
!= module.trim_end_matches(".flow").trim_start_matches("./")
{
continue;
}
let name = text(identity, "name")?;
let function = functions
.iter()
.find(|f| f.name == name)
.ok_or_else(|| format!("no Rust function implements {name}"))?;
if !served.insert(name.to_owned()) {
return Err(format!("ambiguous Tool {name} in contract"));
}
let spec = Json::Object(
["generic", "params", "ok", "err"]
.into_iter()
.map(|key| (key.to_owned(), tool.get(key).cloned().unwrap_or(Json::Null)))
.chain(std::iter::once((
"declarations".into(),
reachable_templates(tool, &templates)?,
)))
.collect(),
);
let spec = TypeSpec::read(&spec).map_err(|e| e.to_string())?;
let entry = Json::Object(
["tool", "fingerprint", "signature"]
.into_iter()
.map(|key| (key.to_owned(), tool.get(key).cloned().unwrap_or(Json::Null)))
.collect(),
);
declarations.push((function.factory)(&entry.canonical(), spec).0);
}
}
if served.is_empty() {
return Err("canonical inventory contains no registered Rust functions".into());
}
run_protocol(&Server::new(data, declarations), start)
}
#[cfg(unix)]
fn run_protocol(server: &Server, start: Option<Start>) -> Result<(), String> {
let protocol = rustix::io::dup(std::io::stdout()).map_err(|error| error.to_string())?;
rustix::stdio::dup2_stdout(std::io::stderr()).map_err(|error| error.to_string())?;
with_resource(start, || {
server
.run(std::io::stdin().lock(), std::fs::File::from(protocol))
.map_err(|error| error.to_string())
})
}
#[cfg(not(unix))]
fn run_protocol(_server: &Server, _start: Option<Start>) -> Result<(), String> {
Err("Rust function-first protocol serving is currently supported only on Unix".into())
}
fn with_resource(
start: Option<Start>,
serve: impl FnOnce() -> Result<(), String>,
) -> Result<(), String> {
let lifecycle = start
.map(|start| start())
.transpose()
.map_err(|error| format!("Rust resource initialization failed: {error}"))?;
if let Some(lifecycle) = &lifecycle {
let mut current = RESOURCE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if current.is_some() {
return Err("a Rust process resource is already initialized".into());
}
*current = Some(lifecycle.value.clone());
}
let result = serve();
if let Some(lifecycle) = lifecycle {
RESOURCE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take();
let closed = block_on((lifecycle.close)())
.map_err(|error| format!("Rust resource cleanup failed: {error}"));
match (result, closed) {
(Err(run), Err(close)) => Err(format!("{run}; {close}")),
(Err(error), _) | (_, Err(error)) => Err(error),
_ => Ok(()),
}
} else {
result
}
}
fn text<'a>(json: &'a Json, key: &str) -> Result<&'a str, String> {
match json.get(key) {
Some(Json::String(s)) => Ok(s),
_ => Err(format!("contract {key} must be text")),
}
}
fn array<'a>(json: &'a Json, key: &str) -> Result<&'a [Json], String> {
match json.get(key) {
Some(Json::Array(a)) => Ok(a),
_ => Err(format!("contract {key} must be an array")),
}
}
pub fn block_on<F: Future>(future: F) -> F::Output {
static RUNTIME: std::sync::LazyLock<tokio::runtime::Runtime> = std::sync::LazyLock::new(|| {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("tool async runtime")
});
RUNTIME.block_on(future)
}
pub(crate) fn reachable_templates(
tool: &Json,
templates: &BTreeMap<String, Json>,
) -> Result<Json, String> {
fn refs(term: &Json, queue: &mut Vec<String>) {
match term {
Json::Object(fields) => {
for (key, value) in fields {
if key == "Named"
&& let Some(Json::String(id)) = value.get("declaration")
{
queue.push(id.clone());
}
refs(value, queue);
}
}
Json::Array(parts) => {
for part in parts {
refs(part, queue);
}
}
_ => {}
}
}
let mut queue = Vec::new();
for key in ["params", "ok", "err"] {
refs(tool.get(key).unwrap_or(&Json::Null), &mut queue);
}
let mut chosen = BTreeMap::new();
while let Some(id) = queue.pop() {
if chosen.contains_key(&id) {
continue;
}
let template = templates
.get(&id)
.ok_or_else(|| format!("the listing does not describe the type {id}"))?;
refs(template, &mut queue);
chosen.insert(id, template.clone());
}
Ok(Json::Object(chosen.into_iter().collect()))
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
static STARTED: AtomicUsize = AtomicUsize::new(0);
static CLOSED: AtomicUsize = AtomicUsize::new(0);
#[allow(clippy::unnecessary_wraps)] fn start_sync() -> Result<Lifecycle, String> {
STARTED.fetch_add(1, Ordering::SeqCst);
Ok(Resource::sync(7_usize, |value| {
assert_eq!(*value, 7);
CLOSED.fetch_add(1, Ordering::SeqCst);
Ok(())
})
.into_lifecycle())
}
fn start_error() -> Result<Lifecycle, String> {
Err("fixture init error".into())
}
#[allow(clippy::unnecessary_wraps)] fn close_error() -> Result<Lifecycle, String> {
Ok(Resource::sync((), |_| Err("fixture close error".into())).into_lifecycle())
}
#[test]
fn synchronous_resource_is_typed_shared_and_closed_even_when_serving_fails() {
let spec = TypeSpec::read(
&crate::parse_json(
r#"{"generic":[],"params":[],"ok":"Unit","err":"Never","declarations":{}}"#,
)
.unwrap(),
)
.unwrap();
let context = crate::Context::try_new(
"run",
"call",
&spec,
None,
None,
Arc::new(AtomicBool::new(false)),
)
.unwrap();
assert!(context.resource::<usize>().is_none());
let error = with_resource(Some(start_sync), || {
let first = context.resource::<usize>().unwrap();
let second = context.resource::<usize>().unwrap();
assert!(Arc::ptr_eq(&first, &second));
assert_eq!(*first, 7);
assert!(context.resource::<String>().is_none());
Err("fixture serve failed".into())
})
.unwrap_err();
assert_eq!(error, "fixture serve failed");
assert_eq!(STARTED.load(Ordering::SeqCst), 1);
assert_eq!(CLOSED.load(Ordering::SeqCst), 1);
assert!(context.resource::<usize>().is_none());
assert!(context.log("invalid", "message").is_err());
assert!(with_resource(None, || Ok(())).is_ok());
assert!(
with_resource(Some(start_error), || panic!(
"startup failure must not serve"
))
.unwrap_err()
.contains("initialization failed")
);
assert!(
with_resource(Some(close_error), || Ok(()))
.unwrap_err()
.contains("cleanup failed")
);
let error = with_resource(Some(close_error), || Err("serve failed".into())).unwrap_err();
assert!(error.contains("serve failed") && error.contains("cleanup failed"));
}
}