Skip to main content

flow_toolkit/
server.rs

1//! The Tool process protocol, served (`abi.md`, *The Tool process
2//! protocol*): frames on standard input and output, as `flow-abi` reads and
3//! writes them.
4//!
5//! `describe` is answered with this toolkit's data version and each
6//! declaration's identity and type description, in the order of the
7//! `--contract` file, which is the number a `call` names its declaration by.
8//! Each `call` runs on a thread of its own while it runs and is answered by
9//! one `reply`, written as one frame, or held by one `hold`; a `cancel` sets
10//! the call's flag. A thread whose call is answered waits up to a second for
11//! the next call before ending, so calls made one after another reuse one
12//! thread, and a new thread starts only when no thread is waiting. A `call`
13//! that withdraws a held call runs like any other with its flag already set,
14//! so the author can withdraw the question it asked; the host drops whatever
15//! it answers, and a hold for it, which the closed call cannot take, is not
16//! sent. When the input ends, the calls still running finish and are
17//! answered, and the server returns.
18//!
19//! A generic call's views are validated against the declaration's
20//! description once per distinct `CallTypes`, so a
21//! type instantiated again is not validated again, and its arguments are
22//! read at the validated concrete types. A declaration whose values hold a
23//! std value carried whole is read at its own description's types; any
24//! other reads its arguments' own encodings.
25//!
26//! Each line a call's [`Context::log`] writes is a `log` frame naming the
27//! call's run and call, and a line [`log`] writes outside any call names
28//! neither. Lines written before the host's `describe` request, such as a
29//! `#[lifespan]`'s while it starts, are held until it arrives and sent
30//! before the answer. Standard error stays the author's own.
31//!
32//! The toolkit never makes up an answer. A call whose declaration number
33//! names nothing served, whose views or arguments do not decode at the
34//! declared types, or that is larger than the toolkit reads, gets a
35//! `no_answer` before the author's code runs; so does a call whose code
36//! panics, or whose value does not encode at the declared type (`abi.md`,
37//! *Toolkits*). The process goes on serving its other calls. An `ack` the
38//! host sends for a reply changes nothing here, and a frame that is no
39//! message the toolkit acts on is ignored.
40
41use std::cell::{Cell, RefCell};
42use std::io::Write;
43use std::sync::atomic::{AtomicBool, Ordering};
44use std::sync::{Arc, Mutex};
45
46use flow_abi::{Catalog, Outcome, TypeSpec, ValidatedTypes, description};
47use flow_span::{CallRef, RunId};
48use flow_tool_protocol::{Level, Log, Message, write_frame};
49use flow_types::{StdEnum, ToolProblemCtor, Type};
50
51use flow_abi::EncodeError;
52use flow_abi::Mode;
53use flow_abi::primitives::Reader;
54use flow_abi::wire::{Shaped, ValueReader, ValueWriter, WireForm};
55
56use crate::data::{DecodeError, LIMITS, inside, refused};
57use crate::key::CallKey;
58use flow_value::Instant;
59
60#[cfg(unix)]
61mod serving;
62
63#[cfg(all(test, unix))]
64pub(crate) use serving::Buffer;
65#[cfg(unix)]
66pub(crate) use serving::{Declaration, Server, logging_to};
67
68/// Why a call got no value back: std's `ToolProblem` (`errors.md`, *Tool
69/// problems*), which a Tool answers with and also takes or answers as data.
70///
71/// A Tool function returning `Result<R, ToolProblem>` declares `R`, and
72/// answers `Ok(r)` with a value or `Err(problem)` with one of these. A
73/// domain failure, such as a declined card, is not a `ToolProblem`: it is a
74/// value of `R`, which may itself be a `Result`. The enum is exhaustive: an
75/// author's `match` names each case.
76#[derive(Clone, PartialEq, Eq, Debug)]
77#[expect(
78    clippy::exhaustive_enums,
79    reason = "mirrors std's ToolProblem, whose cases authors match on"
80)]
81pub enum ToolProblem {
82    /// The work did not begin, and why.
83    NotStarted(String),
84    /// The work began and stopped before a value, and why.
85    Interrupted(String),
86    /// The network to the Tool failed.
87    NetworkError {
88        /// Whether the request went out.
89        sent: bool,
90        /// Why.
91        reason: String,
92    },
93}
94
95impl ToolProblem {
96    /// Its constructor among std's.
97    fn ctor(&self) -> ToolProblemCtor {
98        match self {
99            ToolProblem::NotStarted(_) => ToolProblemCtor::NotStarted,
100            ToolProblem::Interrupted(_) => ToolProblemCtor::Interrupted,
101            ToolProblem::NetworkError { .. } => ToolProblemCtor::NetworkError,
102        }
103    }
104}
105
106/// std's `ToolProblem`, its constructors found by name in the enum the
107/// catalog declares.
108impl Shaped for ToolProblem {
109    const FORM: WireForm = WireForm::Std {
110        module: "",
111        name: "ToolProblem",
112        args: &[],
113    };
114
115    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
116        let ctors = flow_abi::form(out.catalog(), ty)
117            .enumeration()
118            .and_then(|shape| StdEnum::<ToolProblemCtor>::of(shape.shape).ok())
119            .ok_or_else(|| out.refuse(ty))?;
120        let index = ctors.index(self.ctor());
121        match self {
122            ToolProblem::NotStarted(reason) | ToolProblem::Interrupted(reason) => {
123                out.variant(ty, index, &[reason])
124            }
125            ToolProblem::NetworkError { sent, reason } => out.variant(ty, index, &[sent, reason]),
126        }
127    }
128
129    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
130        let ctors = flow_abi::form(input.catalog(), ty)
131            .enumeration()
132            .and_then(|shape| StdEnum::<ToolProblemCtor>::of(shape.shape).ok())
133            .ok_or_else(|| input.mismatch(ty))?;
134        input.variant(ty, |input, index, parts| match ctors.which(index) {
135            Some(ToolProblemCtor::NotStarted) => parts.read(input).map(ToolProblem::NotStarted),
136            Some(ToolProblemCtor::Interrupted) => parts.read(input).map(ToolProblem::Interrupted),
137            Some(ToolProblemCtor::NetworkError) => Ok(ToolProblem::NetworkError {
138                sent: parts.read(input)?,
139                reason: parts.read(input)?,
140            }),
141            None => Err(input.mismatch(ty)),
142        })
143    }
144}
145
146impl std::fmt::Display for ToolProblem {
147    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148        match self {
149            ToolProblem::NotStarted(why) => write!(formatter, "not started: {why}"),
150            ToolProblem::Interrupted(why) => write!(formatter, "interrupted: {why}"),
151            ToolProblem::NetworkError { sent: true, reason } => {
152                write!(
153                    formatter,
154                    "network error after the request went out: {reason}"
155                )
156            }
157            ToolProblem::NetworkError {
158                sent: false,
159                reason,
160            } => write!(
161                formatter,
162                "network error before the request went out: {reason}"
163            ),
164        }
165    }
166}
167
168impl std::error::Error for ToolProblem {}
169
170/// No answer yet, but the promise of one (`history.md`, *A hold is a
171/// promise*): a `hold` frame. The call stays open until a reply addressed
172/// to it arrives, through [`reply`](crate::reply()) by the call's key, or
173/// the Tool answers when the host asks again, which it does once each time
174/// the run is resumed, and with a `retry_at` also at that instant. A hold
175/// says that asking again under the call's key is safe, so the Tool must
176/// answer a second ask as the same call.
177#[derive(Clone, PartialEq, Eq, Debug, Default)]
178pub struct Hold {
179    /// When to be asked again, if at a time of its own.
180    pub retry_at: Option<Instant>,
181}
182
183impl Hold {
184    /// A hold with no time of its own.
185    pub fn new() -> Hold {
186        Hold { retry_at: None }
187    }
188
189    /// A hold that has the host ask again at `time`, as exactly as the
190    /// platform's clock gives it.
191    ///
192    /// # Panics
193    ///
194    /// When `time` is further from the epoch than an `i128` of nanoseconds
195    /// reaches, which no platform's clock holds.
196    pub fn until(time: std::time::SystemTime) -> Hold {
197        Hold {
198            retry_at: Some(
199                flow_abi::wire::instant_of(time)
200                    .expect("a SystemTime's nanoseconds from the epoch fit an i128"),
201            ),
202        }
203    }
204}
205
206impl std::fmt::Display for Hold {
207    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
208        match &self.retry_at {
209            None => write!(formatter, "held"),
210            Some(retry_at) => write!(formatter, "held, to be asked again at {retry_at}"),
211        }
212    }
213}
214
215impl std::error::Error for Hold {}
216
217/// What a Tool returns instead of a value: a [`ToolProblem`], answered, or
218/// a [`Hold`], the promise of an answer. A Tool function returning
219/// `Result<R, NoAnswer>` declares `R`; `?` turns either into one.
220#[derive(Clone, PartialEq, Eq, Debug)]
221#[expect(
222    clippy::exhaustive_enums,
223    reason = "a call is answered with a problem or held, and nothing else"
224)]
225pub enum NoAnswer {
226    /// A problem, which answers the call.
227    Problem(ToolProblem),
228    /// A hold, which leaves it open.
229    Hold(Hold),
230}
231
232impl From<ToolProblem> for NoAnswer {
233    fn from(problem: ToolProblem) -> NoAnswer {
234        NoAnswer::Problem(problem)
235    }
236}
237
238impl From<Hold> for NoAnswer {
239    fn from(hold: Hold) -> NoAnswer {
240        NoAnswer::Hold(hold)
241    }
242}
243
244impl std::fmt::Display for NoAnswer {
245    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246        match self {
247            NoAnswer::Problem(problem) => problem.fmt(formatter),
248            NoAnswer::Hold(hold) => hold.fmt(formatter),
249        }
250    }
251}
252
253impl std::error::Error for NoAnswer {}
254
255/// Why a Tool whose result is `Result<R, E>` has no `R`: its own error `E`,
256/// answered as the value `Err(e)`, or no answer at all. A Tool function
257/// returning `Result<R, Refusal<E>>` declares `Result<R, E>`; `?` turns an
258/// `E` into a refusal, and the constructors make the rest.
259#[derive(Clone, PartialEq, Eq, Debug)]
260#[expect(
261    clippy::exhaustive_enums,
262    reason = "a Tool answers its own error or does not answer, and nothing else"
263)]
264pub enum Refusal<E> {
265    /// The Tool's own error, answered inside its result.
266    Own(E),
267    /// A problem or a hold.
268    NoAnswer(NoAnswer),
269}
270
271impl<E> From<E> for Refusal<E> {
272    fn from(error: E) -> Refusal<E> {
273        Refusal::Own(error)
274    }
275}
276
277impl<E> Refusal<E> {
278    /// The work did not begin, and why.
279    pub fn not_started(reason: String) -> Refusal<E> {
280        Refusal::problem(ToolProblem::NotStarted(reason))
281    }
282
283    /// The work began and stopped before a value, and why.
284    pub fn interrupted(reason: String) -> Refusal<E> {
285        Refusal::problem(ToolProblem::Interrupted(reason))
286    }
287
288    /// A problem, which answers the call.
289    pub fn problem(problem: ToolProblem) -> Refusal<E> {
290        Refusal::NoAnswer(NoAnswer::Problem(problem))
291    }
292
293    /// A hold, which leaves the call open.
294    pub fn hold(hold: Hold) -> Refusal<E> {
295        Refusal::NoAnswer(NoAnswer::Hold(hold))
296    }
297
298    /// The call's answer: its value or own error inside the result, or no
299    /// answer.
300    pub(crate) fn answer<T>(result: Result<T, Refusal<E>>) -> Result<Result<T, E>, NoAnswer> {
301        match result {
302            Ok(value) => Ok(Ok(value)),
303            Err(Refusal::Own(error)) => Ok(Err(error)),
304            Err(Refusal::NoAnswer(missing)) => Err(missing),
305        }
306    }
307}
308
309impl<V> From<ToolProblem> for Outcome<V> {
310    fn from(problem: ToolProblem) -> Outcome<V> {
311        match problem {
312            ToolProblem::NotStarted(reason) => Outcome::NotStarted(reason),
313            ToolProblem::Interrupted(reason) => Outcome::Interrupted(reason),
314            ToolProblem::NetworkError { sent, reason } => Outcome::NetworkError { sent, reason },
315        }
316    }
317}
318
319#[cfg(unix)]
320impl From<NoAnswer> for Answered {
321    /// What is sent for `missing`: a `reply` with its problem, or a `hold`.
322    fn from(missing: NoAnswer) -> Answered {
323        match missing {
324            NoAnswer::Problem(problem) => Answered::Reply(problem.into()),
325            NoAnswer::Hold(Hold { retry_at }) => Answered::Hold(retry_at),
326        }
327    }
328}
329
330/// What the toolkit sends for one call: a `reply` with an answer, a `hold`,
331/// or a `no_answer` with the reason.
332#[cfg(unix)]
333#[derive(Clone, PartialEq, Eq, Debug)]
334pub(crate) enum Answered {
335    /// A `reply`.
336    Reply(Outcome),
337    /// A `hold`, with its `retry_at`.
338    Hold(Option<Instant>),
339    /// A `no_answer`.
340    NoAnswer(String),
341}
342
343/// What a method knows about the call it answers.
344#[derive(Clone, Debug)]
345pub struct Context {
346    key: CallKey,
347    cancelled: Cancellation,
348    /// The validated concrete types of a generic call.
349    types: Option<Arc<ValidatedTypes>>,
350    /// Where the call's log lines go: the protocol's output, or nowhere for
351    /// a call a test makes.
352    sink: Option<Sink>,
353}
354
355impl Context {
356    /// The context of the call `key` names to the declaration `spec`
357    /// describes, with `generic`'s views for a generic one, validated
358    /// completely before the author's code sees it. Its log lines go
359    /// nowhere.
360    ///
361    /// # Errors
362    ///
363    /// Refuses views that do not fit `spec`: views given to a nongeneric
364    /// declaration, missing from a generic one, or describing types the
365    /// declaration does not admit.
366    pub fn try_new(
367        key: CallKey,
368        spec: &TypeSpec,
369        generic: Option<&description::CallTypes>,
370        cancelled: Cancellation,
371    ) -> Result<Context, DecodeError> {
372        let types = spec.validate_call(generic)?.map(Arc::new);
373        Ok(Context {
374            key,
375            cancelled,
376            types,
377            sink: None,
378        })
379    }
380
381    /// The admitted concrete type description, if this Tool is generic.
382    pub fn types(&self) -> Option<&ValidatedTypes> {
383        self.types.as_deref()
384    }
385
386    /// The context of a call made by a test rather than a host: the call
387    /// `key` names, of a nongeneric Tool, not cancelled. [`Context::cancel`]
388    /// makes it one that withdraws its call.
389    pub fn for_test(key: CallKey) -> Context {
390        Context {
391            key,
392            cancelled: Cancellation::default(),
393            types: None,
394            sink: None,
395        }
396    }
397
398    /// The run's id.
399    pub fn run(&self) -> &RunId {
400        self.key.run()
401    }
402
403    /// The call's id, which a call sent again after a crash keeps.
404    pub fn call(&self) -> &CallRef {
405        self.key.call()
406    }
407
408    /// The call's key, its run's id and its own together: the address a Tool
409    /// hands the outside world as an idempotency key or a callback address,
410    /// and that [`reply`](crate::reply()) answers.
411    pub fn key(&self) -> CallKey {
412        self.key.clone()
413    }
414
415    /// For a call to a Tool with exactly one type parameter, the canonical
416    /// text of the JSON Schema of the concrete type the call binds to it,
417    /// made from the call's types: what a model's structured output, or any
418    /// other outside producer, is asked to fit. `None` for a nongeneric call
419    /// and for one whose Tool has several type parameters.
420    pub fn schema(&self) -> Option<&str> {
421        self.types.as_deref()?.schema()
422    }
423
424    /// The validated types of the call and the concrete type it binds to its
425    /// one type parameter.
426    fn bound(&self) -> Result<(&ValidatedTypes, &Type), DecodeError> {
427        let types = self.types.as_deref();
428        match types.map(ValidatedTypes::bindings) {
429            Some([(_, bound)]) => Ok((types.expect("a generic call's types"), bound)),
430            _ => Err(refused(
431                "is not read at a type: the call does not bind exactly one type parameter",
432            )),
433        }
434    }
435
436    /// Reads JSON text `data`, such as a model's output, as a value of the
437    /// concrete type the call binds to its one type parameter, by the rules
438    /// of *Decoding* (`abi.md`), and gives it as `T`, the Rust type the Tool
439    /// writes for it: [`Encoded`](crate::Encoded) for the type parameter itself.
440    ///
441    /// # Errors
442    ///
443    /// Refuses `data` that is not JSON of a value of that type, saying why:
444    /// the author turns the error into a value of the Tool's declared result.
445    /// Refused too for a nongeneric call, and for one whose Tool has several
446    /// type parameters.
447    pub fn decode<T: Shaped>(&self, data: &str) -> Result<T, DecodeError> {
448        let (types, bound) = self.bound()?;
449        let value = flow_abi::decode_text(types.catalog(), bound, data, Mode::Reply, &LIMITS)?;
450        flow_abi::of_shaped_value(&value, types.catalog(), bound)
451    }
452
453    /// The canonical text of `value`'s JSON form (`abi.md`, *The JSON
454    /// form*) at the concrete type the call binds to its one type parameter,
455    /// as its `CallTypes` gives it: what a Tool hands a model.
456    ///
457    /// # Errors
458    ///
459    /// Refuses a value that is not one of that type, and a call that does not
460    /// bind exactly one type parameter.
461    pub fn to_json<T: Shaped>(&self, value: &T) -> Result<String, DecodeError> {
462        let (types, bound) = self.bound()?;
463        let value = flow_abi::shaped_value(value, types.catalog(), bound)
464            .map_err(|error| refused(error.problem))?;
465        flow_abi::canonical(types.catalog(), bound, &value).map_err(|error| refused(error.problem))
466    }
467
468    /// Writes one line to the run's log at `level`, as a `log` frame naming
469    /// the call's run and call. A call a test makes logs nowhere.
470    pub fn log(&self, level: Level, message: &str) {
471        if let Some(sink) = &self.sink {
472            sink.log(Log {
473                run: Some(*self.run()),
474                call: Some(self.call().clone()),
475                level,
476                message: message.to_owned(),
477            });
478        }
479    }
480
481    /// Whether the host asked to stop work on this call, or withdrew it: a
482    /// held call that was closed is sent once more with this set, so the
483    /// author can withdraw the question it asked, and whatever it answers is
484    /// dropped. It proves nothing either way.
485    pub fn cancelled(&self) -> bool {
486        self.cancelled.is_cancelled()
487    }
488
489    /// Asks to stop work on this call, as a `cancel` does.
490    pub fn cancel(&self) {
491        self.cancelled.cancel();
492    }
493
494    /// The call's cancellation, which work that blocks can wait on beside
495    /// whatever else it waits for, instead of asking [`Context::cancelled`]
496    /// again and again.
497    pub fn cancellation(&self) -> Cancellation {
498        self.cancelled.clone()
499    }
500}
501
502/// Writes one line to the log of the process that serves this library's
503/// Tools, outside any call, such as from a `#[lifespan]`: a `log` frame
504/// naming neither a run nor a call (`abi.md`, *Toolkits*). A line written
505/// before the host's `describe` request is sent once it arrives; outside a
506/// served process the line goes nowhere.
507pub fn log(level: Level, message: &str) {
508    let sink = lock(&PROCESS).clone();
509    if let Some(sink) = sink {
510        sink.log(Log {
511            run: None,
512            call: None,
513            level,
514            message: message.to_owned(),
515        });
516    }
517}
518
519/// The protocol output of the process serving its Tools, once serving
520/// starts, for [`log`].
521static PROCESS: Mutex<Option<Sink>> = Mutex::new(None);
522
523/// The protocol's output, shared by everything that writes a frame: the
524/// serving loop, each call's answer and each log line. Log lines written
525/// before the host's `describe` request wait in it until the request comes.
526#[derive(Clone)]
527pub(crate) struct Sink(Arc<Mutex<Output>>);
528
529struct Output {
530    writer: Box<dyn Write + Send>,
531    #[cfg(unix)]
532    reply_limit: Option<u64>,
533    /// Whether the host sent its `describe` request.
534    asked: bool,
535    /// The log lines written before it did.
536    held: Vec<Log>,
537}
538
539impl std::fmt::Debug for Sink {
540    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
541        formatter.debug_struct("Sink").finish_non_exhaustive()
542    }
543}
544
545impl Sink {
546    /// Writes `log` as a frame, or holds it until the host's `describe`
547    /// request. A line that cannot be written is lost: the log is the
548    /// implementation's report, and the call it came from goes on.
549    fn log(&self, log: Log) {
550        let mut output = lock(&self.0);
551        if output.asked {
552            let _ = write_frame(&mut output.writer, &Message::Log(log));
553        } else {
554            output.held.push(log);
555        }
556    }
557}
558
559/// Whether the host asked to stop work on a call, and a way to wait until it
560/// does. Clones share one state: a cancel through any of them is seen by all.
561#[derive(Clone, Debug, Default)]
562pub struct Cancellation(Arc<CancelState>);
563
564#[derive(Debug, Default)]
565struct CancelState {
566    cancelled: AtomicBool,
567    woken: tokio::sync::Notify,
568}
569
570impl Cancellation {
571    /// Whether the call was cancelled.
572    pub fn is_cancelled(&self) -> bool {
573        self.0.cancelled.load(Ordering::SeqCst)
574    }
575
576    /// Cancels the call and wakes everything waiting in
577    /// [`Cancellation::wait`].
578    pub fn cancel(&self) {
579        self.0.cancelled.store(true, Ordering::SeqCst);
580        self.0.woken.notify_waiters();
581    }
582
583    /// Resolves once the call is cancelled, at once if it already is.
584    pub async fn wait(&self) {
585        loop {
586            let woken = self.0.woken.notified();
587            let mut woken = std::pin::pin!(woken);
588            woken.as_mut().enable();
589            if self.is_cancelled() {
590                return;
591            }
592            woken.await;
593        }
594    }
595}
596
597/// A call's arguments: their bytes, each parameter's value one after
598/// another at its type, read in declaration order by the generated adapter.
599#[derive(Debug)]
600pub struct Args<'a> {
601    reader: RefCell<Reader<'a>>,
602    catalog: &'a Catalog,
603    params: Vec<&'a Type>,
604    next: Cell<usize>,
605    #[cfg(unix)]
606    result: &'a Type,
607}
608
609impl Args<'_> {
610    /// The next argument, the parameter `name`'s: a generated adapter takes
611    /// them in declaration order.
612    ///
613    /// # Errors
614    ///
615    /// Refuses bytes that are not the encoding of a value of the parameter's
616    /// type, a value the Rust type does not hold, and an argument past the
617    /// last parameter.
618    pub fn take<T: Shaped>(&self, name: &str) -> Result<T, DecodeError> {
619        let at = self.next.get();
620        self.next.set(at + 1);
621        let read = || {
622            let ty = self
623                .params
624                .get(at)
625                .ok_or_else(|| refused("is no parameter of the declaration"))?;
626            flow_abi::read_shaped(
627                &mut self.reader.borrow_mut(),
628                self.catalog,
629                ty,
630                Mode::Rebuild,
631                &LIMITS,
632            )
633        };
634        read().map_err(|error| inside(error, name))
635    }
636
637    /// Refuses bytes left over after the last argument a typed adapter took.
638    ///
639    /// # Errors
640    ///
641    /// Refused when any bytes remain.
642    pub fn finish(&self) -> Result<(), DecodeError> {
643        let reader = self.reader.borrow();
644        if reader.is_empty() {
645            Ok(())
646        } else {
647            Err(refused(format!(
648                "ends at byte {}, with {} bytes left over after the last argument",
649                reader.position(),
650                reader.remaining()
651            )))
652        }
653    }
654
655    /// The bytes of `value`, the author's answer, at the declared result.
656    #[cfg(unix)]
657    fn answer<T: Shaped>(&self, value: &T) -> Result<Vec<u8>, DecodeError> {
658        let mut out = Vec::new();
659        flow_abi::write_shaped(&mut out, self.catalog, self.result, value)
660            .map_err(|error| refused(error.problem))?;
661        Ok(out)
662    }
663}
664
665/// A generated adapter: it reads the arguments, calls the author's code and
666/// writes what it returned.
667pub struct Adapter(#[cfg(unix)] Box<Adapted>);
668
669/// What an [`Adapter`] runs for each call.
670#[cfg(unix)]
671type Adapted = dyn Fn(&Context, &Args<'_>) -> Answered + Send + Sync;
672
673impl std::fmt::Debug for Adapter {
674    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
675        formatter.debug_struct("Adapter").finish_non_exhaustive()
676    }
677}
678
679impl Adapter {
680    /// The adapter calling `method`, which reads its arguments from `Args`
681    /// and returns the author's answer, whose value is written at the call's
682    /// result type.
683    pub fn new<T, F>(method: F) -> Adapter
684    where
685        T: Shaped,
686        F: Fn(&Context, &Args<'_>) -> Result<Result<T, NoAnswer>, DecodeError>
687            + Send
688            + Sync
689            + 'static,
690    {
691        #[cfg(not(unix))]
692        {
693            let _ = method;
694            Adapter()
695        }
696        #[cfg(unix)]
697        Adapter(Box::new(move |context, args| match method(context, args) {
698            Ok(Ok(value)) => match args.answer(&value) {
699                Ok(bytes) => Answered::Reply(Outcome::Ok(flow_abi::wire::Rest(bytes))),
700                Err(error) => Answered::NoAnswer(format!("the result does not encode: {error}")),
701            },
702            Ok(Err(problem)) => problem.into(),
703            Err(error) => Answered::NoAnswer(format!("the arguments do not decode: {error}")),
704        }))
705    }
706}
707
708/// Locks `mutex`, recovering it from a panicked holder. Poisoning breaks no
709/// invariant here: the output is written one whole frame per lock, and the
710/// open-call map is changed by single inserts and removes. Anything that
711/// keeps multi-step state under one of these locks must revisit this.
712fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
713    mutex
714        .lock()
715        .unwrap_or_else(std::sync::PoisonError::into_inner)
716}