flow-toolkit 0.1.0

Ordinary typed Rust functions and exact native data for Flow Tools, automatically prepared from direct native imports.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
//! Function-first Rust metadata and adapters. Functions remain ordinary Rust callables.
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);

/// A process resource retained across calls and explicitly closed at normal shutdown.
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> {
    /// Creates a resource with asynchronous cleanup, run after all calls finish.
    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))),
        }
    }
    /// Creates a resource with synchronous cleanup.
    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)))
    }
    /// Erases the concrete type for a generated lifecycle factory.
    #[doc(hidden)]
    pub fn into_lifecycle(self) -> Lifecycle {
        let value = self.value.clone();
        Lifecycle {
            value: self.value,
            close: Box::new(move || (self.close)(value)),
        }
    }
}
/// A generated lifecycle factory's process resource and cleanup operation.
pub struct Lifecycle {
    value: Arc<dyn Any + Send + Sync>,
    close: Close,
}
/// A generated resource initializer, invoked only while serving.
pub type Start = fn() -> Result<Lifecycle, String>;
impl crate::Context {
    /// Retrieves the initialized process resource by its actual Rust type.
    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()
    }
}

/// A native boundary value with contextual conversion for generic calls.
/// Native scalars, containers and `#[derive(Flow)]` supply implementations.
pub trait FlowType: Data {
    /// Metadata hook emitted by the boundary derive.
    #[doc(hidden)]
    fn flow_type(types: &mut Types) -> String;
    /// Reads a value using the compiler-validated concrete call type.
    fn decode_context(
        codec: &crate::ContextCodec,
        value: &Json,
    ) -> Result<Self, crate::DecodeError> {
        Self::decode(&codec.decode(value)?)
    }
    /// Writes a value using the compiler-validated concrete call type.
    fn encode_context(&self, codec: &crate::ContextCodec) -> Result<Json, crate::DecodeError> {
        codec.encode(&self.encode())
    }
    /// Encodes a named field, including the special Option-field representation.
    fn encode_field(&self) -> Option<Json> {
        Some(self.encode())
    }
    /// Decodes a named field; Option aliases retain omission semantics.
    fn decode_field(value: Option<&Json>) -> Result<Self, crate::DecodeError> {
        Self::decode(value.ok_or_else(|| crate::data::refused("is missing"))?)
    }
}

/// The symbolic body emitted only by automatic boundary derives.
#[doc(hidden)]
pub trait Shape {
    /// Builds the declaration body with symbolic type parameters.
    fn shape(types: &mut Types) -> String;
}

/// Named declarations collected during metadata construction.
#[derive(Default)]
pub struct Types {
    definitions: BTreeMap<String, String>,
    owners: BTreeMap<String, &'static str>,
    collision: Option<String>,
    parameters: Vec<Vec<String>>,
}
impl Types {
    /// Enters the symbolic type parameters of one declaration.
    pub fn parameters(&mut self, names: &[&str]) {
        self.parameters
            .push(names.iter().map(|s| (*s).into()).collect());
    }
    /// Leaves a declaration's symbolic type parameters.
    pub fn end_parameters(&mut self) {
        self.parameters.pop();
    }

    /// Marks a named type before traversing its fields, allowing recursive records.
    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
        }
    }
    /// Completes the declaration of a previously visited type.
    pub fn finish(&mut self, name: &str, source: String) {
        self.definitions.insert(name.into(), source);
    }
}

/// A generic Tool value admitted through a validated concrete call codec.
/// The index distinguishes independent native type parameters at the automatic bridge.
#[derive(Clone, Debug)]
pub struct Value<const INDEX: usize> {
    value: Json,
    codec: crate::ContextCodec,
}
impl<const INDEX: usize> Value<INDEX> {
    /// Validates an application-produced value against this invocation's concrete type.
    pub fn new(codec: &crate::ContextCodec, value: &Json) -> Result<Self, crate::DecodeError> {
        Ok(Self {
            value: codec.decode(value)?,
            codec: codec.clone(),
        })
    }
    /// The normalized encoding of this typed value.
    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),
        }
    }
}
/// Adds one named field through its actual Rust type, including aliases.
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));
    }
}
/// Reads one named field through its actual Rust type, including aliases.
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;
/// Generated metadata plus an invocation factory; construction does not call the tool.
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 {
    /// Adds the function-owned type parameter names generated by the attribute.
    pub(crate) fn with_generics(mut self, names: &[&str]) -> Self {
        self.generic = names.iter().map(|name| (*name).into()).collect();
        self
    }

    /// Builds metadata emitted by `#[tool]` through the generated adapter ABI.
    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,
        }
    }
}

/// Ordinary Flow source describing the registered Rust functions.
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)
}

/// Runs a generated launcher with one optional explicit resource initializer.
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)
}

/// Binds generated adapters to the compiler's canonical declaration inventory.
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> {
    // Keep the original protocol stream private before redirecting ordinary Rust logging.
    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")),
    }
}

/// Drives an asynchronous tool with a full Tokio runtime on its invocation thread.
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)] // Exercises the fallible lifecycle factory signature.
    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)] // Opening succeeds so the cleanup failure can be observed.
    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"));
    }
}