flow-toolkit 0.1.0-rc.5

Ordinary typed Rust functions and exact native data for Flow Tools, served from a Rust library's one launcher.
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
//! The Tool process protocol, served (`abi.md`, *The Tool process
//! protocol*): frames on standard input and output, as `flow-abi` reads and
//! writes them.
//!
//! `describe` is answered with this toolkit's data version and each
//! declaration's identity and type description, in the order of the
//! `--contract` file, which is the number a `call` names its declaration by.
//! Each `call` runs on a thread of its own while it runs and is answered by
//! one `reply`, written as one frame, or held by one `hold`; a `cancel` sets
//! the call's flag. A thread whose call is answered waits up to a second for
//! the next call before ending, so calls made one after another reuse one
//! thread, and a new thread starts only when no thread is waiting. A `call`
//! that withdraws a held call runs like any other with its flag already set,
//! so the author can withdraw the question it asked; the host drops whatever
//! it answers, and a hold for it, which the closed call cannot take, is not
//! sent. When the input ends, the calls still running finish and are
//! answered, and the server returns.
//!
//! A generic call's views are validated against the declaration's
//! description once per distinct `CallTypes`, so a
//! type instantiated again is not validated again, and its arguments are
//! read at the validated concrete types. A declaration whose values hold a
//! std value carried whole is read at its own description's types; any
//! other reads its arguments' own encodings.
//!
//! Each line a call's [`Context::log`] writes is a `log` frame naming the
//! call's run and call, and a line [`log`] writes outside any call names
//! neither. Lines written before the host's `describe` request, such as a
//! `#[lifespan]`'s while it starts, are held until it arrives and sent
//! before the answer. Standard error stays the author's own.
//!
//! The toolkit never makes up an answer. A call whose declaration number
//! names nothing served, whose views or arguments do not decode at the
//! declared types, or that is larger than the toolkit reads, gets a
//! `no_answer` before the author's code runs; so does a call whose code
//! panics, or whose value does not encode at the declared type (`abi.md`,
//! *Toolkits*). The process goes on serving its other calls. An `ack` the
//! host sends for a reply changes nothing here, and a frame that is no
//! message the toolkit acts on is ignored.

use std::cell::{Cell, RefCell};
use std::io::Write;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};

use flow_abi::{Catalog, Outcome, TypeSpec, ValidatedTypes, description};
use flow_span::{CallRef, RunId};
use flow_tool_protocol::{Level, Log, Message, write_frame};
use flow_types::{StdEnum, ToolProblemCtor, Type};

use flow_abi::EncodeError;
use flow_abi::Mode;
use flow_abi::primitives::Reader;
use flow_abi::wire::{Shaped, ValueReader, ValueWriter, WireForm};

use crate::data::{DecodeError, LIMITS, inside, refused};
use crate::key::CallKey;
use flow_value::Instant;

#[cfg(unix)]
mod serving;

#[cfg(all(test, unix))]
pub(crate) use serving::Buffer;
#[cfg(unix)]
pub(crate) use serving::{Declaration, Server, logging_to};

/// Why a call got no value back: std's `ToolProblem` (`errors.md`, *Tool
/// problems*), which a Tool answers with and also takes or answers as data.
///
/// A Tool function returning `Result<R, ToolProblem>` declares `R`, and
/// answers `Ok(r)` with a value or `Err(problem)` with one of these. A
/// domain failure, such as a declined card, is not a `ToolProblem`: it is a
/// value of `R`, which may itself be a `Result`. The enum is exhaustive: an
/// author's `match` names each case.
#[derive(Clone, PartialEq, Eq, Debug)]
#[expect(
    clippy::exhaustive_enums,
    reason = "mirrors std's ToolProblem, whose cases authors match on"
)]
pub enum ToolProblem {
    /// The work did not begin, and why.
    NotStarted(String),
    /// The work began and stopped before a value, and why.
    Interrupted(String),
    /// The network to the Tool failed.
    NetworkError {
        /// Whether the request went out.
        sent: bool,
        /// Why.
        reason: String,
    },
}

impl ToolProblem {
    /// Its constructor among std's.
    fn ctor(&self) -> ToolProblemCtor {
        match self {
            ToolProblem::NotStarted(_) => ToolProblemCtor::NotStarted,
            ToolProblem::Interrupted(_) => ToolProblemCtor::Interrupted,
            ToolProblem::NetworkError { .. } => ToolProblemCtor::NetworkError,
        }
    }
}

/// std's `ToolProblem`, its constructors found by name in the enum the
/// catalog declares.
impl Shaped for ToolProblem {
    const FORM: WireForm = WireForm::Std {
        module: "",
        name: "ToolProblem",
        args: &[],
    };

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        let ctors = flow_abi::form(out.catalog(), ty)
            .enumeration()
            .and_then(|shape| StdEnum::<ToolProblemCtor>::of(shape.shape).ok())
            .ok_or_else(|| out.refuse(ty))?;
        let index = ctors.index(self.ctor());
        match self {
            ToolProblem::NotStarted(reason) | ToolProblem::Interrupted(reason) => {
                out.variant(ty, index, &[reason])
            }
            ToolProblem::NetworkError { sent, reason } => out.variant(ty, index, &[sent, reason]),
        }
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        let ctors = flow_abi::form(input.catalog(), ty)
            .enumeration()
            .and_then(|shape| StdEnum::<ToolProblemCtor>::of(shape.shape).ok())
            .ok_or_else(|| input.mismatch(ty))?;
        input.variant(ty, |input, index, parts| match ctors.which(index) {
            Some(ToolProblemCtor::NotStarted) => parts.read(input).map(ToolProblem::NotStarted),
            Some(ToolProblemCtor::Interrupted) => parts.read(input).map(ToolProblem::Interrupted),
            Some(ToolProblemCtor::NetworkError) => Ok(ToolProblem::NetworkError {
                sent: parts.read(input)?,
                reason: parts.read(input)?,
            }),
            None => Err(input.mismatch(ty)),
        })
    }
}

impl std::fmt::Display for ToolProblem {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ToolProblem::NotStarted(why) => write!(formatter, "not started: {why}"),
            ToolProblem::Interrupted(why) => write!(formatter, "interrupted: {why}"),
            ToolProblem::NetworkError { sent: true, reason } => {
                write!(
                    formatter,
                    "network error after the request went out: {reason}"
                )
            }
            ToolProblem::NetworkError {
                sent: false,
                reason,
            } => write!(
                formatter,
                "network error before the request went out: {reason}"
            ),
        }
    }
}

impl std::error::Error for ToolProblem {}

/// No answer yet, but the promise of one (`history.md`, *A hold is a
/// promise*): a `hold` frame. The call stays open until a reply addressed
/// to it arrives, through [`reply`](crate::reply()) by the call's key, or
/// the Tool answers when the host asks again, which it does once each time
/// the run is resumed, and with a `retry_at` also at that instant. A hold
/// says that asking again under the call's key is safe, so the Tool must
/// answer a second ask as the same call.
#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub struct Hold {
    /// When to be asked again, if at a time of its own.
    pub retry_at: Option<Instant>,
}

impl Hold {
    /// A hold with no time of its own.
    pub fn new() -> Hold {
        Hold { retry_at: None }
    }

    /// A hold that has the host ask again at `time`, as exactly as the
    /// platform's clock gives it.
    ///
    /// # Panics
    ///
    /// When `time` is further from the epoch than an `i128` of nanoseconds
    /// reaches, which no platform's clock holds.
    pub fn until(time: std::time::SystemTime) -> Hold {
        Hold {
            retry_at: Some(
                flow_abi::wire::instant_of(time)
                    .expect("a SystemTime's nanoseconds from the epoch fit an i128"),
            ),
        }
    }
}

impl std::fmt::Display for Hold {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.retry_at {
            None => write!(formatter, "held"),
            Some(retry_at) => write!(formatter, "held, to be asked again at {retry_at}"),
        }
    }
}

impl std::error::Error for Hold {}

/// What a Tool returns instead of a value: a [`ToolProblem`], answered, or
/// a [`Hold`], the promise of an answer. A Tool function returning
/// `Result<R, NoAnswer>` declares `R`; `?` turns either into one.
#[derive(Clone, PartialEq, Eq, Debug)]
#[expect(
    clippy::exhaustive_enums,
    reason = "a call is answered with a problem or held, and nothing else"
)]
pub enum NoAnswer {
    /// A problem, which answers the call.
    Problem(ToolProblem),
    /// A hold, which leaves it open.
    Hold(Hold),
}

impl From<ToolProblem> for NoAnswer {
    fn from(problem: ToolProblem) -> NoAnswer {
        NoAnswer::Problem(problem)
    }
}

impl From<Hold> for NoAnswer {
    fn from(hold: Hold) -> NoAnswer {
        NoAnswer::Hold(hold)
    }
}

impl std::fmt::Display for NoAnswer {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            NoAnswer::Problem(problem) => problem.fmt(formatter),
            NoAnswer::Hold(hold) => hold.fmt(formatter),
        }
    }
}

impl std::error::Error for NoAnswer {}

/// Why a Tool whose result is `Result<R, E>` has no `R`: its own error `E`,
/// answered as the value `Err(e)`, or no answer at all. A Tool function
/// returning `Result<R, Refusal<E>>` declares `Result<R, E>`; `?` turns an
/// `E` into a refusal, and the constructors make the rest.
#[derive(Clone, PartialEq, Eq, Debug)]
#[expect(
    clippy::exhaustive_enums,
    reason = "a Tool answers its own error or does not answer, and nothing else"
)]
pub enum Refusal<E> {
    /// The Tool's own error, answered inside its result.
    Own(E),
    /// A problem or a hold.
    NoAnswer(NoAnswer),
}

impl<E> From<E> for Refusal<E> {
    fn from(error: E) -> Refusal<E> {
        Refusal::Own(error)
    }
}

impl<E> Refusal<E> {
    /// The work did not begin, and why.
    pub fn not_started(reason: String) -> Refusal<E> {
        Refusal::problem(ToolProblem::NotStarted(reason))
    }

    /// The work began and stopped before a value, and why.
    pub fn interrupted(reason: String) -> Refusal<E> {
        Refusal::problem(ToolProblem::Interrupted(reason))
    }

    /// A problem, which answers the call.
    pub fn problem(problem: ToolProblem) -> Refusal<E> {
        Refusal::NoAnswer(NoAnswer::Problem(problem))
    }

    /// A hold, which leaves the call open.
    pub fn hold(hold: Hold) -> Refusal<E> {
        Refusal::NoAnswer(NoAnswer::Hold(hold))
    }

    /// The call's answer: its value or own error inside the result, or no
    /// answer.
    pub(crate) fn answer<T>(result: Result<T, Refusal<E>>) -> Result<Result<T, E>, NoAnswer> {
        match result {
            Ok(value) => Ok(Ok(value)),
            Err(Refusal::Own(error)) => Ok(Err(error)),
            Err(Refusal::NoAnswer(missing)) => Err(missing),
        }
    }
}

impl<V> From<ToolProblem> for Outcome<V> {
    fn from(problem: ToolProblem) -> Outcome<V> {
        match problem {
            ToolProblem::NotStarted(reason) => Outcome::NotStarted(reason),
            ToolProblem::Interrupted(reason) => Outcome::Interrupted(reason),
            ToolProblem::NetworkError { sent, reason } => Outcome::NetworkError { sent, reason },
        }
    }
}

#[cfg(unix)]
impl From<NoAnswer> for Answered {
    /// What is sent for `missing`: a `reply` with its problem, or a `hold`.
    fn from(missing: NoAnswer) -> Answered {
        match missing {
            NoAnswer::Problem(problem) => Answered::Reply(problem.into()),
            NoAnswer::Hold(Hold { retry_at }) => Answered::Hold(retry_at),
        }
    }
}

/// What the toolkit sends for one call: a `reply` with an answer, a `hold`,
/// or a `no_answer` with the reason.
#[cfg(unix)]
#[derive(Clone, PartialEq, Eq, Debug)]
pub(crate) enum Answered {
    /// A `reply`.
    Reply(Outcome),
    /// A `hold`, with its `retry_at`.
    Hold(Option<Instant>),
    /// A `no_answer`.
    NoAnswer(String),
}

/// What a method knows about the call it answers.
#[derive(Clone, Debug)]
pub struct Context {
    key: CallKey,
    cancelled: Cancellation,
    /// The validated concrete types of a generic call.
    types: Option<Arc<ValidatedTypes>>,
    /// Where the call's log lines go: the protocol's output, or nowhere for
    /// a call a test makes.
    sink: Option<Sink>,
}

impl Context {
    /// The context of the call `key` names to the declaration `spec`
    /// describes, with `generic`'s views for a generic one, validated
    /// completely before the author's code sees it. Its log lines go
    /// nowhere.
    ///
    /// # Errors
    ///
    /// Refuses views that do not fit `spec`: views given to a nongeneric
    /// declaration, missing from a generic one, or describing types the
    /// declaration does not admit.
    pub fn try_new(
        key: CallKey,
        spec: &TypeSpec,
        generic: Option<&description::CallTypes>,
        cancelled: Cancellation,
    ) -> Result<Context, DecodeError> {
        let types = spec.validate_call(generic)?.map(Arc::new);
        Ok(Context {
            key,
            cancelled,
            types,
            sink: None,
        })
    }

    /// The admitted concrete type description, if this Tool is generic.
    pub fn types(&self) -> Option<&ValidatedTypes> {
        self.types.as_deref()
    }

    /// The context of a call made by a test rather than a host: the call
    /// `key` names, of a nongeneric Tool, not cancelled. [`Context::cancel`]
    /// makes it one that withdraws its call.
    pub fn for_test(key: CallKey) -> Context {
        Context {
            key,
            cancelled: Cancellation::default(),
            types: None,
            sink: None,
        }
    }

    /// The run's id.
    pub fn run(&self) -> &RunId {
        self.key.run()
    }

    /// The call's id, which a call sent again after a crash keeps.
    pub fn call(&self) -> &CallRef {
        self.key.call()
    }

    /// The call's key, its run's id and its own together: the address a Tool
    /// hands the outside world as an idempotency key or a callback address,
    /// and that [`reply`](crate::reply()) answers.
    pub fn key(&self) -> CallKey {
        self.key.clone()
    }

    /// For a call to a Tool with exactly one type parameter, the canonical
    /// text of the JSON Schema of the concrete type the call binds to it,
    /// made from the call's types: what a model's structured output, or any
    /// other outside producer, is asked to fit. `None` for a nongeneric call
    /// and for one whose Tool has several type parameters.
    pub fn schema(&self) -> Option<&str> {
        self.types.as_deref()?.schema()
    }

    /// The validated types of the call and the concrete type it binds to its
    /// one type parameter.
    fn bound(&self) -> Result<(&ValidatedTypes, &Type), DecodeError> {
        let types = self.types.as_deref();
        match types.map(ValidatedTypes::bindings) {
            Some([(_, bound)]) => Ok((types.expect("a generic call's types"), bound)),
            _ => Err(refused(
                "is not read at a type: the call does not bind exactly one type parameter",
            )),
        }
    }

    /// Reads JSON text `data`, such as a model's output, as a value of the
    /// concrete type the call binds to its one type parameter, by the rules
    /// of *Decoding* (`abi.md`), and gives it as `T`, the Rust type the Tool
    /// writes for it: [`Encoded`](crate::Encoded) for the type parameter itself.
    ///
    /// # Errors
    ///
    /// Refuses `data` that is not JSON of a value of that type, saying why:
    /// the author turns the error into a value of the Tool's declared result.
    /// Refused too for a nongeneric call, and for one whose Tool has several
    /// type parameters.
    pub fn decode<T: Shaped>(&self, data: &str) -> Result<T, DecodeError> {
        let (types, bound) = self.bound()?;
        let value = flow_abi::decode_text(types.catalog(), bound, data, Mode::Reply, &LIMITS)?;
        flow_abi::of_shaped_value(&value, types.catalog(), bound)
    }

    /// The canonical text of `value`'s JSON form (`abi.md`, *The JSON
    /// form*) at the concrete type the call binds to its one type parameter,
    /// as its `CallTypes` gives it: what a Tool hands a model.
    ///
    /// # Errors
    ///
    /// Refuses a value that is not one of that type, and a call that does not
    /// bind exactly one type parameter.
    pub fn to_json<T: Shaped>(&self, value: &T) -> Result<String, DecodeError> {
        let (types, bound) = self.bound()?;
        let value = flow_abi::shaped_value(value, types.catalog(), bound)
            .map_err(|error| refused(error.problem))?;
        flow_abi::canonical(types.catalog(), bound, &value).map_err(|error| refused(error.problem))
    }

    /// Writes one line to the run's log at `level`, as a `log` frame naming
    /// the call's run and call. A call a test makes logs nowhere.
    pub fn log(&self, level: Level, message: &str) {
        if let Some(sink) = &self.sink {
            sink.log(Log {
                run: Some(*self.run()),
                call: Some(self.call().clone()),
                level,
                message: message.to_owned(),
            });
        }
    }

    /// Whether the host asked to stop work on this call, or withdrew it: a
    /// held call that was closed is sent once more with this set, so the
    /// author can withdraw the question it asked, and whatever it answers is
    /// dropped. It proves nothing either way.
    pub fn cancelled(&self) -> bool {
        self.cancelled.is_cancelled()
    }

    /// Asks to stop work on this call, as a `cancel` does.
    pub fn cancel(&self) {
        self.cancelled.cancel();
    }

    /// The call's cancellation, which work that blocks can wait on beside
    /// whatever else it waits for, instead of asking [`Context::cancelled`]
    /// again and again.
    pub fn cancellation(&self) -> Cancellation {
        self.cancelled.clone()
    }
}

/// Writes one line to the log of the process that serves this library's
/// Tools, outside any call, such as from a `#[lifespan]`: a `log` frame
/// naming neither a run nor a call (`abi.md`, *Toolkits*). A line written
/// before the host's `describe` request is sent once it arrives; outside a
/// served process the line goes nowhere.
pub fn log(level: Level, message: &str) {
    let sink = lock(&PROCESS).clone();
    if let Some(sink) = sink {
        sink.log(Log {
            run: None,
            call: None,
            level,
            message: message.to_owned(),
        });
    }
}

/// The protocol output of the process serving its Tools, once serving
/// starts, for [`log`].
static PROCESS: Mutex<Option<Sink>> = Mutex::new(None);

/// The protocol's output, shared by everything that writes a frame: the
/// serving loop, each call's answer and each log line. Log lines written
/// before the host's `describe` request wait in it until the request comes.
#[derive(Clone)]
pub(crate) struct Sink(Arc<Mutex<Output>>);

struct Output {
    writer: Box<dyn Write + Send>,
    #[cfg(unix)]
    reply_limit: Option<u64>,
    /// Whether the host sent its `describe` request.
    asked: bool,
    /// The log lines written before it did.
    held: Vec<Log>,
}

impl std::fmt::Debug for Sink {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.debug_struct("Sink").finish_non_exhaustive()
    }
}

impl Sink {
    /// Writes `log` as a frame, or holds it until the host's `describe`
    /// request. A line that cannot be written is lost: the log is the
    /// implementation's report, and the call it came from goes on.
    fn log(&self, log: Log) {
        let mut output = lock(&self.0);
        if output.asked {
            let _ = write_frame(&mut output.writer, &Message::Log(log));
        } else {
            output.held.push(log);
        }
    }
}

/// Whether the host asked to stop work on a call, and a way to wait until it
/// does. Clones share one state: a cancel through any of them is seen by all.
#[derive(Clone, Debug, Default)]
pub struct Cancellation(Arc<CancelState>);

#[derive(Debug, Default)]
struct CancelState {
    cancelled: AtomicBool,
    woken: tokio::sync::Notify,
}

impl Cancellation {
    /// Whether the call was cancelled.
    pub fn is_cancelled(&self) -> bool {
        self.0.cancelled.load(Ordering::SeqCst)
    }

    /// Cancels the call and wakes everything waiting in
    /// [`Cancellation::wait`].
    pub fn cancel(&self) {
        self.0.cancelled.store(true, Ordering::SeqCst);
        self.0.woken.notify_waiters();
    }

    /// Resolves once the call is cancelled, at once if it already is.
    pub async fn wait(&self) {
        loop {
            let woken = self.0.woken.notified();
            let mut woken = std::pin::pin!(woken);
            woken.as_mut().enable();
            if self.is_cancelled() {
                return;
            }
            woken.await;
        }
    }
}

/// A call's arguments: their bytes, each parameter's value one after
/// another at its type, read in declaration order by the generated adapter.
#[derive(Debug)]
pub struct Args<'a> {
    reader: RefCell<Reader<'a>>,
    catalog: &'a Catalog,
    params: Vec<&'a Type>,
    next: Cell<usize>,
    #[cfg(unix)]
    result: &'a Type,
}

impl Args<'_> {
    /// The next argument, the parameter `name`'s: a generated adapter takes
    /// them in declaration order.
    ///
    /// # Errors
    ///
    /// Refuses bytes that are not the encoding of a value of the parameter's
    /// type, a value the Rust type does not hold, and an argument past the
    /// last parameter.
    pub fn take<T: Shaped>(&self, name: &str) -> Result<T, DecodeError> {
        let at = self.next.get();
        self.next.set(at + 1);
        let read = || {
            let ty = self
                .params
                .get(at)
                .ok_or_else(|| refused("is no parameter of the declaration"))?;
            flow_abi::read_shaped(
                &mut self.reader.borrow_mut(),
                self.catalog,
                ty,
                Mode::Rebuild,
                &LIMITS,
            )
        };
        read().map_err(|error| inside(error, name))
    }

    /// Refuses bytes left over after the last argument a typed adapter took.
    ///
    /// # Errors
    ///
    /// Refused when any bytes remain.
    pub fn finish(&self) -> Result<(), DecodeError> {
        let reader = self.reader.borrow();
        if reader.is_empty() {
            Ok(())
        } else {
            Err(refused(format!(
                "ends at byte {}, with {} bytes left over after the last argument",
                reader.position(),
                reader.remaining()
            )))
        }
    }

    /// The bytes of `value`, the author's answer, at the declared result.
    #[cfg(unix)]
    fn answer<T: Shaped>(&self, value: &T) -> Result<Vec<u8>, DecodeError> {
        let mut out = Vec::new();
        flow_abi::write_shaped(&mut out, self.catalog, self.result, value)
            .map_err(|error| refused(error.problem))?;
        Ok(out)
    }
}

/// A generated adapter: it reads the arguments, calls the author's code and
/// writes what it returned.
pub struct Adapter(#[cfg(unix)] Box<Adapted>);

/// What an [`Adapter`] runs for each call.
#[cfg(unix)]
type Adapted = dyn Fn(&Context, &Args<'_>) -> Answered + Send + Sync;

impl std::fmt::Debug for Adapter {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.debug_struct("Adapter").finish_non_exhaustive()
    }
}

impl Adapter {
    /// The adapter calling `method`, which reads its arguments from `Args`
    /// and returns the author's answer, whose value is written at the call's
    /// result type.
    pub fn new<T, F>(method: F) -> Adapter
    where
        T: Shaped,
        F: Fn(&Context, &Args<'_>) -> Result<Result<T, NoAnswer>, DecodeError>
            + Send
            + Sync
            + 'static,
    {
        #[cfg(not(unix))]
        {
            let _ = method;
            Adapter()
        }
        #[cfg(unix)]
        Adapter(Box::new(move |context, args| match method(context, args) {
            Ok(Ok(value)) => match args.answer(&value) {
                Ok(bytes) => Answered::Reply(Outcome::Ok(flow_abi::wire::Rest(bytes))),
                Err(error) => Answered::NoAnswer(format!("the result does not encode: {error}")),
            },
            Ok(Err(problem)) => problem.into(),
            Err(error) => Answered::NoAnswer(format!("the arguments do not decode: {error}")),
        }))
    }
}

/// Locks `mutex`, recovering it from a panicked holder. Poisoning breaks no
/// invariant here: the output is written one whole frame per lock, and the
/// open-call map is changed by single inserts and removes. Anything that
/// keeps multi-step state under one of these locks must revisit this.
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    mutex
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}