Skip to main content

flow_toolkit/
function.rs

1//! Function-first Rust metadata and adapters. Functions remain ordinary Rust callables.
2use std::any::Any;
3use std::collections::{BTreeMap, BTreeSet};
4use std::convert::Infallible;
5use std::fmt::Write as _;
6use std::future::Future;
7use std::pin::Pin;
8use std::sync::{Arc, Mutex};
9
10use crate::server::Server;
11use crate::{Data, Json};
12use flow_abi::TypeSpec;
13
14type CloseFuture = Pin<Box<dyn Future<Output = Result<(), String>> + Send>>;
15type Close = Box<dyn FnOnce() -> CloseFuture + Send>;
16static RESOURCE: Mutex<Option<Arc<dyn Any + Send + Sync>>> = Mutex::new(None);
17
18/// A process resource retained across calls and explicitly closed at normal shutdown.
19pub struct Resource<T: Send + Sync + 'static> {
20    value: Arc<T>,
21    close: Box<dyn FnOnce(Arc<T>) -> CloseFuture + Send>,
22}
23impl<T: Send + Sync + 'static> Resource<T> {
24    /// Creates a resource with asynchronous cleanup, run after all calls finish.
25    pub fn new<F, Fut>(value: T, close: F) -> Self
26    where
27        F: FnOnce(Arc<T>) -> Fut + Send + 'static,
28        Fut: Future<Output = Result<(), String>> + Send + 'static,
29    {
30        Self {
31            value: Arc::new(value),
32            close: Box::new(move |value| Box::pin(close(value))),
33        }
34    }
35    /// Creates a resource with synchronous cleanup.
36    pub fn sync<F>(value: T, close: F) -> Self
37    where
38        F: FnOnce(Arc<T>) -> Result<(), String> + Send + 'static,
39    {
40        Self::new(value, move |value| std::future::ready(close(value)))
41    }
42    /// Erases the concrete type for a generated lifecycle factory.
43    #[doc(hidden)]
44    pub fn into_lifecycle(self) -> Lifecycle {
45        let value = self.value.clone();
46        Lifecycle {
47            value: self.value,
48            close: Box::new(move || (self.close)(value)),
49        }
50    }
51}
52/// A generated lifecycle factory's process resource and cleanup operation.
53pub struct Lifecycle {
54    value: Arc<dyn Any + Send + Sync>,
55    close: Close,
56}
57/// A generated resource initializer, invoked only while serving.
58pub type Start = fn() -> Result<Lifecycle, String>;
59impl crate::Context {
60    /// Retrieves the initialized process resource by its actual Rust type.
61    pub fn resource<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
62        RESOURCE
63            .lock()
64            .unwrap_or_else(std::sync::PoisonError::into_inner)
65            .as_ref()?
66            .clone()
67            .downcast::<T>()
68            .ok()
69    }
70}
71
72/// A native boundary value with contextual conversion for generic calls.
73/// Native scalars, containers and `#[derive(Flow)]` supply implementations.
74pub trait FlowType: Data {
75    /// Metadata hook emitted by the boundary derive.
76    #[doc(hidden)]
77    fn flow_type(types: &mut Types) -> String;
78    /// Reads a value using the compiler-validated concrete call type.
79    fn decode_context(
80        codec: &crate::ContextCodec,
81        value: &Json,
82    ) -> Result<Self, crate::DecodeError> {
83        Self::decode(&codec.decode(value)?)
84    }
85    /// Writes a value using the compiler-validated concrete call type.
86    fn encode_context(&self, codec: &crate::ContextCodec) -> Result<Json, crate::DecodeError> {
87        codec.encode(&self.encode())
88    }
89    /// Encodes a named field, including the special Option-field representation.
90    fn encode_field(&self) -> Option<Json> {
91        Some(self.encode())
92    }
93    /// Decodes a named field; Option aliases retain omission semantics.
94    fn decode_field(value: Option<&Json>) -> Result<Self, crate::DecodeError> {
95        Self::decode(value.ok_or_else(|| crate::data::refused("is missing"))?)
96    }
97}
98
99/// The symbolic body emitted only by automatic boundary derives.
100#[doc(hidden)]
101pub trait Shape {
102    /// Builds the declaration body with symbolic type parameters.
103    fn shape(types: &mut Types) -> String;
104}
105
106/// Named declarations collected during metadata construction.
107#[derive(Default)]
108pub struct Types {
109    definitions: BTreeMap<String, String>,
110    owners: BTreeMap<String, &'static str>,
111    collision: Option<String>,
112    parameters: Vec<Vec<String>>,
113}
114impl Types {
115    /// Enters the symbolic type parameters of one declaration.
116    pub fn parameters(&mut self, names: &[&str]) {
117        self.parameters
118            .push(names.iter().map(|s| (*s).into()).collect());
119    }
120    /// Leaves a declaration's symbolic type parameters.
121    pub fn end_parameters(&mut self) {
122        self.parameters.pop();
123    }
124
125    /// Marks a named type before traversing its fields, allowing recursive records.
126    pub fn begin(&mut self, name: &str, owner: &'static str) -> bool {
127        if let Some(previous) = self.owners.get(name) {
128            if *previous != owner {
129                self.collision = Some(format!(
130                    "distinct Rust types share Flow name {name}: {previous} and {owner}"
131                ));
132            }
133            false
134        } else {
135            self.owners.insert(name.into(), owner);
136            true
137        }
138    }
139    /// Completes the declaration of a previously visited type.
140    pub fn finish(&mut self, name: &str, source: String) {
141        self.definitions.insert(name.into(), source);
142    }
143}
144
145/// A generic Tool value admitted through a validated concrete call codec.
146/// The index distinguishes independent native type parameters at the automatic bridge.
147#[derive(Clone, Debug)]
148pub struct Value<const INDEX: usize> {
149    value: Json,
150    codec: crate::ContextCodec,
151}
152impl<const INDEX: usize> Value<INDEX> {
153    /// Validates an application-produced value against this invocation's concrete type.
154    pub fn new(codec: &crate::ContextCodec, value: &Json) -> Result<Self, crate::DecodeError> {
155        Ok(Self {
156            value: codec.decode(value)?,
157            codec: codec.clone(),
158        })
159    }
160    /// The normalized encoding of this typed value.
161    pub fn json(&self) -> &Json {
162        &self.value
163    }
164}
165impl<const INDEX: usize> Data for Value<INDEX> {
166    fn encode(&self) -> Json {
167        self.value.clone()
168    }
169    fn decode(_: &Json) -> Result<Self, crate::DecodeError> {
170        Err(crate::data::refused(
171            "a generic value requires a validated invocation codec",
172        ))
173    }
174}
175impl<const INDEX: usize> FlowType for Value<INDEX> {
176    fn flow_type(types: &mut Types) -> String {
177        types
178            .parameters
179            .last()
180            .and_then(|names| names.get(INDEX))
181            .cloned()
182            .expect("generic parameter scope")
183    }
184    fn decode_context(
185        codec: &crate::ContextCodec,
186        value: &Json,
187    ) -> Result<Self, crate::DecodeError> {
188        Self::new(codec, value)
189    }
190}
191impl<const INDEX: usize> PartialEq for Value<INDEX> {
192    fn eq(&self, other: &Self) -> bool {
193        self.cmp(other).is_eq()
194    }
195}
196impl<const INDEX: usize> Eq for Value<INDEX> {}
197impl<const INDEX: usize> PartialOrd for Value<INDEX> {
198    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
199        Some(self.cmp(other))
200    }
201}
202impl<const INDEX: usize> Ord for Value<INDEX> {
203    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
204        self.codec
205            .compare(&self.value, &other.value)
206            .expect("values of the same generic Rust type have the same admitted Flow type")
207    }
208}
209
210macro_rules! scalar {
211    ($($rust:ty => $flow:literal),* $(,)?) => {$ (
212        impl FlowType for $rust { fn flow_type(_: &mut Types) -> String { $flow.to_owned() } }
213    )*};
214}
215scalar!(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");
216impl<T: FlowType> FlowType for Vec<T> {
217    fn flow_type(types: &mut Types) -> String {
218        format!("List<{}>", T::flow_type(types))
219    }
220    fn encode_context(&self, codec: &crate::ContextCodec) -> Result<Json, crate::DecodeError> {
221        let child = codec.element()?;
222        let values = self
223            .iter()
224            .map(|value| value.encode_context(&child))
225            .collect::<Result<Vec<_>, _>>()?;
226        codec.encode(&Json::Array(values))
227    }
228    fn decode_context(
229        codec: &crate::ContextCodec,
230        value: &Json,
231    ) -> Result<Self, crate::DecodeError> {
232        let value = codec.decode(value)?;
233        let Json::Array(values) = value else {
234            return Err(crate::data::refused("expected list"));
235        };
236        let child = codec.element()?;
237        values
238            .iter()
239            .map(|value| T::decode_context(&child, value))
240            .collect()
241    }
242}
243impl<T: FlowType, E: FlowType> FlowType for std::result::Result<T, E> {
244    fn flow_type(types: &mut Types) -> String {
245        format!("Result<{}, {}>", T::flow_type(types), E::flow_type(types))
246    }
247    fn encode_context(&self, codec: &crate::ContextCodec) -> Result<Json, crate::DecodeError> {
248        let value = match self {
249            Ok(value) => crate::data::variant(
250                "Ok",
251                value.encode_context(&codec.variant("Ok")?.positional(0)?)?,
252            ),
253            Err(value) => crate::data::variant(
254                "Err",
255                value.encode_context(&codec.variant("Err")?.positional(0)?)?,
256            ),
257        };
258        codec.encode(&value)
259    }
260    fn decode_context(
261        codec: &crate::ContextCodec,
262        value: &Json,
263    ) -> Result<Self, crate::DecodeError> {
264        let value = codec.decode(value)?;
265        match crate::data::constructor(&value)? {
266            ("Ok", Some(payload)) => {
267                T::decode_context(&codec.variant("Ok")?.positional(0)?, payload).map(Ok)
268            }
269            ("Err", Some(payload)) => {
270                E::decode_context(&codec.variant("Err")?.positional(0)?, payload).map(Err)
271            }
272            _ => Err(crate::data::refused("expected Result")),
273        }
274    }
275}
276impl<T: FlowType> FlowType for Option<T> {
277    fn encode_context(&self, codec: &crate::ContextCodec) -> Result<Json, crate::DecodeError> {
278        let value = match self {
279            None => Json::String("None".into()),
280            Some(value) => crate::data::variant("Some", value.encode_context(&codec.element()?)?),
281        };
282        codec.encode(&value)
283    }
284
285    fn decode_context(
286        codec: &crate::ContextCodec,
287        value: &Json,
288    ) -> Result<Self, crate::DecodeError> {
289        let value = codec.decode(value)?;
290        match crate::data::constructor(&value)? {
291            ("None", None) => Ok(None),
292            ("Some", Some(value)) => T::decode_context(&codec.element()?, value).map(Some),
293            _ => Err(crate::data::refused("expected Option")),
294        }
295    }
296
297    fn flow_type(types: &mut Types) -> String {
298        format!("Option<{}>", T::flow_type(types))
299    }
300    fn encode_field(&self) -> Option<Json> {
301        self.as_ref().map(Data::encode)
302    }
303    fn decode_field(value: Option<&Json>) -> Result<Self, crate::DecodeError> {
304        match value {
305            None | Some(Json::Null) => Ok(None),
306            Some(value) => T::decode(value).map(Some),
307        }
308    }
309}
310/// Adds one named field through its actual Rust type, including aliases.
311pub fn encode_field<T: FlowType>(fields: &mut Vec<(String, Json)>, name: &str, value: &T) {
312    if let Some(value) = value.encode_field() {
313        fields.push((name.into(), value));
314    }
315}
316/// Reads one named field through its actual Rust type, including aliases.
317pub fn decode_field<T: FlowType>(json: &Json, name: &str) -> Result<T, crate::DecodeError> {
318    T::decode_field(json.get(name)).map_err(|error| crate::data::inside(error, name))
319}
320impl<T: FlowType + Ord> FlowType for BTreeSet<T> {
321    fn encode_context(&self, codec: &crate::ContextCodec) -> Result<Json, crate::DecodeError> {
322        let child = codec.element()?;
323        let values = self
324            .iter()
325            .map(|value| value.encode_context(&child))
326            .collect::<Result<Vec<_>, _>>()?;
327        codec.encode(&Json::Array(values))
328    }
329
330    fn decode_context(
331        codec: &crate::ContextCodec,
332        value: &Json,
333    ) -> Result<Self, crate::DecodeError> {
334        let value = codec.decode(value)?;
335        let Json::Array(values) = value else {
336            return Err(crate::data::refused("expected set"));
337        };
338        let child = codec.element()?;
339        values
340            .iter()
341            .map(|value| T::decode_context(&child, value))
342            .collect()
343    }
344
345    fn flow_type(types: &mut Types) -> String {
346        format!("Set<{}>", T::flow_type(types))
347    }
348}
349impl<K: FlowType + Ord, V: FlowType> FlowType for BTreeMap<K, V> {
350    fn encode_context(&self, codec: &crate::ContextCodec) -> Result<Json, crate::DecodeError> {
351        let key = codec.key()?;
352        let item = codec.value()?;
353        let pairs = self
354            .iter()
355            .map(|(k, v)| Ok((k.encode_context(&key)?, v.encode_context(&item)?)))
356            .collect::<Result<Vec<_>, crate::DecodeError>>()?;
357        let value = if key.is_text() {
358            Json::Object(
359                pairs
360                    .into_iter()
361                    .map(|(k, v)| match k {
362                        Json::String(k) => Ok((k, v)),
363                        _ => Err(crate::data::refused("expected text key")),
364                    })
365                    .collect::<Result<_, _>>()?,
366            )
367        } else {
368            Json::Array(
369                pairs
370                    .into_iter()
371                    .map(|(k, v)| Json::Array(vec![k, v]))
372                    .collect(),
373            )
374        };
375        codec.encode(&value)
376    }
377    fn decode_context(
378        codec: &crate::ContextCodec,
379        value: &Json,
380    ) -> Result<Self, crate::DecodeError> {
381        let value = codec.decode(value)?;
382        let key = codec.key()?;
383        let item = codec.value()?;
384        match value {
385            Json::Array(values) => values
386                .iter()
387                .map(|value| {
388                    let parts = crate::data::positional(value, 2)?;
389                    Ok((
390                        K::decode_context(&key, &parts[0])?,
391                        V::decode_context(&item, &parts[1])?,
392                    ))
393                })
394                .collect(),
395            Json::Object(values) => values
396                .iter()
397                .map(|(k, v)| {
398                    Ok((
399                        K::decode_context(&key, &Json::String(k.clone()))?,
400                        V::decode_context(&item, v)?,
401                    ))
402                })
403                .collect(),
404            _ => Err(crate::data::refused("expected dictionary")),
405        }
406    }
407    fn flow_type(types: &mut Types) -> String {
408        format!("Dict<{}, {}>", K::flow_type(types), V::flow_type(types))
409    }
410}
411impl<T: FlowType> FlowType for Box<T> {
412    fn encode_context(&self, codec: &crate::ContextCodec) -> Result<Json, crate::DecodeError> {
413        T::encode_context(self, codec)
414    }
415
416    fn decode_context(
417        codec: &crate::ContextCodec,
418        value: &Json,
419    ) -> Result<Self, crate::DecodeError> {
420        T::decode_context(codec, value).map(Box::new)
421    }
422
423    fn flow_type(types: &mut Types) -> String {
424        T::flow_type(types)
425    }
426}
427macro_rules! tuple {
428    ($($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(", ")) }
429    fn decode_context(codec: &crate::ContextCodec,value:&Json)->Result<Self,crate::DecodeError> {
430        let normalized=codec.decode(value)?; let Json::Array(parts)=normalized else { return Err(crate::data::refused("expected tuple")); };
431        let mut index=0; Ok(($({ let child=codec.positional(index)?; let value=$t::decode_context(&child,&parts[index])?; index+=1; value },)+))
432    }
433    fn encode_context(&self,codec:&crate::ContextCodec)->Result<Json,crate::DecodeError> {
434        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))
435    } } };
436}
437tuple!(A, B);
438tuple!(A, B, C);
439tuple!(A, B, C, D);
440
441type Factory = fn(&str, TypeSpec) -> crate::__bridge::Adapter;
442/// Generated metadata plus an invocation factory; construction does not call the tool.
443pub struct Function {
444    name: &'static str,
445    generic: Vec<String>,
446    docs: &'static str,
447    params: Vec<(String, String)>,
448    ok: String,
449    err: String,
450    types: Types,
451    factory: Factory,
452}
453impl Function {
454    /// Adds the function-owned type parameter names generated by the attribute.
455    pub(crate) fn with_generics(mut self, names: &[&str]) -> Self {
456        self.generic = names.iter().map(|name| (*name).into()).collect();
457        self
458    }
459
460    /// Builds metadata emitted by `#[tool]` through the generated adapter ABI.
461    pub(crate) fn new(
462        name: &'static str,
463        docs: &'static str,
464        params: Vec<(String, String)>,
465        ok: String,
466        err: String,
467        types: Types,
468        factory: Factory,
469    ) -> Self {
470        Self {
471            name,
472            generic: Vec::new(),
473            docs,
474            params,
475            ok,
476            err,
477            types,
478            factory,
479        }
480    }
481}
482
483/// Ordinary Flow source describing the registered Rust functions.
484pub fn extract(functions: &[Function]) -> Result<String, String> {
485    let mut definitions = BTreeMap::new();
486    let mut owners = BTreeMap::new();
487    let mut names = BTreeSet::new();
488    let mut source = String::new();
489    for function in functions {
490        if let Some(error) = &function.types.collision {
491            return Err(error.clone());
492        }
493        if !names.insert(function.name) {
494            return Err(format!("duplicate Tool name {}", function.name));
495        }
496        for (name, owner) in &function.types.owners {
497            if let Some(previous) = owners.insert(name, owner)
498                && previous != owner
499            {
500                return Err(format!("distinct Rust types share Flow name {name}"));
501            }
502        }
503        for (name, definition) in &function.types.definitions {
504            definitions.insert(name, definition);
505        }
506    }
507    for (needle, module) in [
508        ("json.Value", "json"),
509        ("duration.Duration", "duration"),
510        ("time.Instant", "time"),
511    ] {
512        if functions.iter().any(|f| {
513            f.params.iter().any(|(_, t)| t.contains(needle))
514                || f.ok.contains(needle)
515                || f.err.contains(needle)
516        }) || definitions.values().any(|s| s.contains(needle))
517        {
518            let _ = writeln!(source, "use \"std@v1/{module}\"\n");
519        }
520    }
521    for definition in definitions.values() {
522        source.push_str(definition);
523        source.push_str("\n\n");
524    }
525    for function in functions {
526        for line in function.docs.lines() {
527            source.push_str("/// ");
528            source.push_str(line);
529            source.push('\n');
530        }
531        let params = function
532            .params
533            .iter()
534            .map(|(name, ty)| format!("{name}: {ty}"))
535            .collect::<Vec<_>>()
536            .join(", ");
537        let generics = if function.generic.is_empty() {
538            String::new()
539        } else {
540            format!("<{}>", function.generic.join(", "))
541        };
542        let _ = write!(
543            source,
544            "@tool pub flow {}{generics}({params}) -> Result<{}, {}>\n\n",
545            function.name, function.ok, function.err
546        );
547    }
548    Ok(source)
549}
550
551/// Runs a generated launcher with one optional explicit resource initializer.
552pub(crate) fn launcher_with_lifecycle(
553    functions: &[Function],
554    start: Option<Start>,
555) -> Result<(), String> {
556    let args = std::env::args().skip(1).collect::<Vec<_>>();
557    if args == ["extract"] {
558        print!("{}", extract(functions)?);
559        return Ok(());
560    }
561    if args.len() != 3 || args[0] != "serve" {
562        return Err("generated launcher expects extract or serve CONTRACT MODULE".into());
563    }
564    let contract = std::fs::read_to_string(&args[1]).map_err(|e| e.to_string())?;
565    serve(functions, &contract, &args[2], start)
566}
567
568/// Binds generated adapters to the compiler's canonical declaration inventory.
569pub(crate) fn serve(
570    functions: &[Function],
571    contract: &str,
572    module: &str,
573    start: Option<Start>,
574) -> Result<(), String> {
575    let listing = flow_abi::parse(contract, &crate::data::LIMITS).map_err(|e| e.to_string())?;
576    let data = text(&listing, "data")?;
577    let mut declarations = Vec::new();
578    let mut served = BTreeSet::new();
579    for program in array(&listing, "programs")? {
580        let Some(Json::Object(types)) = program.get("types") else {
581            return Err("contract has no type map".into());
582        };
583        let templates = types.iter().cloned().collect::<BTreeMap<_, _>>();
584        for tool in array(program, "tools")? {
585            let identity = tool.get("tool").ok_or("Tool has no identity")?;
586            if text(identity, "file")?.trim_start_matches("./")
587                != module.trim_end_matches(".flow").trim_start_matches("./")
588            {
589                continue;
590            }
591            let name = text(identity, "name")?;
592            let function = functions
593                .iter()
594                .find(|f| f.name == name)
595                .ok_or_else(|| format!("no Rust function implements {name}"))?;
596            if !served.insert(name.to_owned()) {
597                return Err(format!("ambiguous Tool {name} in contract"));
598            }
599            let spec = Json::Object(
600                ["generic", "params", "ok", "err"]
601                    .into_iter()
602                    .map(|key| (key.to_owned(), tool.get(key).cloned().unwrap_or(Json::Null)))
603                    .chain(std::iter::once((
604                        "declarations".into(),
605                        reachable_templates(tool, &templates)?,
606                    )))
607                    .collect(),
608            );
609            let spec = TypeSpec::read(&spec).map_err(|e| e.to_string())?;
610            let entry = Json::Object(
611                ["tool", "fingerprint", "signature"]
612                    .into_iter()
613                    .map(|key| (key.to_owned(), tool.get(key).cloned().unwrap_or(Json::Null)))
614                    .collect(),
615            );
616            declarations.push((function.factory)(&entry.canonical(), spec).0);
617        }
618    }
619    if served.is_empty() {
620        return Err("canonical inventory contains no registered Rust functions".into());
621    }
622    run_protocol(&Server::new(data, declarations), start)
623}
624#[cfg(unix)]
625fn run_protocol(server: &Server, start: Option<Start>) -> Result<(), String> {
626    // Keep the original protocol stream private before redirecting ordinary Rust logging.
627    let protocol = rustix::io::dup(std::io::stdout()).map_err(|error| error.to_string())?;
628    rustix::stdio::dup2_stdout(std::io::stderr()).map_err(|error| error.to_string())?;
629    with_resource(start, || {
630        server
631            .run(std::io::stdin().lock(), std::fs::File::from(protocol))
632            .map_err(|error| error.to_string())
633    })
634}
635#[cfg(not(unix))]
636fn run_protocol(_server: &Server, _start: Option<Start>) -> Result<(), String> {
637    Err("Rust function-first protocol serving is currently supported only on Unix".into())
638}
639fn with_resource(
640    start: Option<Start>,
641    serve: impl FnOnce() -> Result<(), String>,
642) -> Result<(), String> {
643    let lifecycle = start
644        .map(|start| start())
645        .transpose()
646        .map_err(|error| format!("Rust resource initialization failed: {error}"))?;
647    if let Some(lifecycle) = &lifecycle {
648        let mut current = RESOURCE
649            .lock()
650            .unwrap_or_else(std::sync::PoisonError::into_inner);
651        if current.is_some() {
652            return Err("a Rust process resource is already initialized".into());
653        }
654        *current = Some(lifecycle.value.clone());
655    }
656    let result = serve();
657    if let Some(lifecycle) = lifecycle {
658        RESOURCE
659            .lock()
660            .unwrap_or_else(std::sync::PoisonError::into_inner)
661            .take();
662        let closed = block_on((lifecycle.close)())
663            .map_err(|error| format!("Rust resource cleanup failed: {error}"));
664        match (result, closed) {
665            (Err(run), Err(close)) => Err(format!("{run}; {close}")),
666            (Err(error), _) | (_, Err(error)) => Err(error),
667            _ => Ok(()),
668        }
669    } else {
670        result
671    }
672}
673fn text<'a>(json: &'a Json, key: &str) -> Result<&'a str, String> {
674    match json.get(key) {
675        Some(Json::String(s)) => Ok(s),
676        _ => Err(format!("contract {key} must be text")),
677    }
678}
679fn array<'a>(json: &'a Json, key: &str) -> Result<&'a [Json], String> {
680    match json.get(key) {
681        Some(Json::Array(a)) => Ok(a),
682        _ => Err(format!("contract {key} must be an array")),
683    }
684}
685
686/// Drives an asynchronous tool with a full Tokio runtime on its invocation thread.
687pub fn block_on<F: Future>(future: F) -> F::Output {
688    static RUNTIME: std::sync::LazyLock<tokio::runtime::Runtime> = std::sync::LazyLock::new(|| {
689        tokio::runtime::Builder::new_multi_thread()
690            .enable_all()
691            .build()
692            .expect("tool async runtime")
693    });
694    RUNTIME.block_on(future)
695}
696
697pub(crate) fn reachable_templates(
698    tool: &Json,
699    templates: &BTreeMap<String, Json>,
700) -> Result<Json, String> {
701    fn refs(term: &Json, queue: &mut Vec<String>) {
702        match term {
703            Json::Object(fields) => {
704                for (key, value) in fields {
705                    if key == "Named"
706                        && let Some(Json::String(id)) = value.get("declaration")
707                    {
708                        queue.push(id.clone());
709                    }
710                    refs(value, queue);
711                }
712            }
713            Json::Array(parts) => {
714                for part in parts {
715                    refs(part, queue);
716                }
717            }
718            _ => {}
719        }
720    }
721    let mut queue = Vec::new();
722    for key in ["params", "ok", "err"] {
723        refs(tool.get(key).unwrap_or(&Json::Null), &mut queue);
724    }
725    let mut chosen = BTreeMap::new();
726    while let Some(id) = queue.pop() {
727        if chosen.contains_key(&id) {
728            continue;
729        }
730        let template = templates
731            .get(&id)
732            .ok_or_else(|| format!("the listing does not describe the type {id}"))?;
733        refs(template, &mut queue);
734        chosen.insert(id, template.clone());
735    }
736    Ok(Json::Object(chosen.into_iter().collect()))
737}
738
739#[cfg(test)]
740mod tests {
741    use super::*;
742    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
743    static STARTED: AtomicUsize = AtomicUsize::new(0);
744    static CLOSED: AtomicUsize = AtomicUsize::new(0);
745    #[allow(clippy::unnecessary_wraps)] // Exercises the fallible lifecycle factory signature.
746    fn start_sync() -> Result<Lifecycle, String> {
747        STARTED.fetch_add(1, Ordering::SeqCst);
748        Ok(Resource::sync(7_usize, |value| {
749            assert_eq!(*value, 7);
750            CLOSED.fetch_add(1, Ordering::SeqCst);
751            Ok(())
752        })
753        .into_lifecycle())
754    }
755    fn start_error() -> Result<Lifecycle, String> {
756        Err("fixture init error".into())
757    }
758    #[allow(clippy::unnecessary_wraps)] // Opening succeeds so the cleanup failure can be observed.
759    fn close_error() -> Result<Lifecycle, String> {
760        Ok(Resource::sync((), |_| Err("fixture close error".into())).into_lifecycle())
761    }
762    #[test]
763    fn synchronous_resource_is_typed_shared_and_closed_even_when_serving_fails() {
764        let spec = TypeSpec::read(
765            &crate::parse_json(
766                r#"{"generic":[],"params":[],"ok":"Unit","err":"Never","declarations":{}}"#,
767            )
768            .unwrap(),
769        )
770        .unwrap();
771        let context = crate::Context::try_new(
772            "run",
773            "call",
774            &spec,
775            None,
776            None,
777            Arc::new(AtomicBool::new(false)),
778        )
779        .unwrap();
780        assert!(context.resource::<usize>().is_none());
781        let error = with_resource(Some(start_sync), || {
782            let first = context.resource::<usize>().unwrap();
783            let second = context.resource::<usize>().unwrap();
784            assert!(Arc::ptr_eq(&first, &second));
785            assert_eq!(*first, 7);
786            assert!(context.resource::<String>().is_none());
787            Err("fixture serve failed".into())
788        })
789        .unwrap_err();
790        assert_eq!(error, "fixture serve failed");
791        assert_eq!(STARTED.load(Ordering::SeqCst), 1);
792        assert_eq!(CLOSED.load(Ordering::SeqCst), 1);
793        assert!(context.resource::<usize>().is_none());
794        assert!(context.log("invalid", "message").is_err());
795        assert!(with_resource(None, || Ok(())).is_ok());
796        assert!(
797            with_resource(Some(start_error), || panic!(
798                "startup failure must not serve"
799            ))
800            .unwrap_err()
801            .contains("initialization failed")
802        );
803        assert!(
804            with_resource(Some(close_error), || Ok(()))
805                .unwrap_err()
806                .contains("cleanup failed")
807        );
808        let error = with_resource(Some(close_error), || Err("serve failed".into())).unwrap_err();
809        assert!(error.contains("serve failed") && error.contains("cleanup failed"));
810    }
811}