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
//! The server itself, where the toolkit serves: on Unix, where
//! `run_protocol` gives it a protocol output of its own. Elsewhere serving
//! is refused before a server is made.

use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::io::{self, Read, Write};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::{Arc, Mutex};

use flow_abi::primitives::Reader;
use flow_abi::{Catalog, TypeSpec, ValidatedTypes, description};
use flow_span::{CallRef, RunId};
use flow_start::{Bound, Tasks};
use flow_tool_protocol::{Call, Frame, Kind, Message, Reply, Route, read_frame, write_frame};
use flow_types::Type;

use super::{Adapter, Answered, Args, Cancellation, Context, Output, PROCESS, Sink, lock};
use crate::data::{DecodeError, LIMITS};
use crate::key::CallKey;

/// One declaration an implementation serves: what `describe` lists for it,
/// and the method answering its calls.
pub(crate) struct Declaration {
    identity: description::Identity,
    spec: TypeSpec,
    adapter: Adapter,
}

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

impl Declaration {
    /// The declaration `describe` lists as `identity` with the description
    /// `spec`, answered by `adapter`.
    pub(crate) fn new(
        identity: description::Identity,
        spec: TypeSpec,
        adapter: Adapter,
    ) -> Declaration {
        Declaration {
            identity,
            spec,
            adapter,
        }
    }
}

/// An implementation's declarations, served over the Tool process
/// protocol.
#[derive(Debug)]
pub(crate) struct Server {
    declarations: Vec<Declaration>,
    /// For each declaration, the validated types of the generic calls it
    /// admitted, by their views: a type instantiated again is not
    /// validated again.
    admitted: Vec<Mutex<HashMap<description::CallTypes, Arc<ValidatedTypes>>>>,
}

/// How many generic instantiations a declaration keeps admitted.
const ADMITTED: usize = 64;

/// How many bytes of views a declaration's admitted instantiations may
/// hold together.
const ADMITTED_BYTES: usize = 1 << 20;

/// The most bytes of views a declaration keeps admitted for one
/// instantiation; larger views are validated on each call.
const ADMITTED_VIEW: usize = 64 << 10;

/// The largest frame the toolkit reads: well past what any host sends.
const FRAME_LIMIT: usize = LIMITS.text_bytes;

/// The stack each call runs on: room for its arguments and answer to nest
/// as deeply as [`LIMITS`] lets them, read and written by recursion, before
/// the limit refuses them.
const CALL_STACK: usize = 64 * 1024 * 1024;

impl Server {
    /// A server for `declarations`, in the order `describe` lists them.
    pub(crate) fn new(declarations: Vec<Declaration>) -> Server {
        let admitted = declarations
            .iter()
            .map(|_| Mutex::new(HashMap::new()))
            .collect();
        Server {
            declarations,
            admitted,
        }
    }

    /// The validated types of a call to the declaration at `index` with the
    /// views `generic`, validated once per distinct instantiation.
    fn types(
        &self,
        index: usize,
        generic: Option<&description::CallTypes>,
    ) -> Result<Option<Arc<ValidatedTypes>>, DecodeError> {
        let spec = &self.declarations[index].spec;
        let Some(generic) = generic else {
            return spec.validate_call(None).map(|types| types.map(Arc::new));
        };
        let admitted = &self.admitted[index];
        if let Some(types) = lock(admitted).get(generic) {
            return Ok(Some(Arc::clone(types)));
        }
        let types = Arc::new(
            spec.validate_call(Some(generic))?
                .expect("a generic call's views validate to its types"),
        );
        let size = types.types().len();
        if size <= ADMITTED_VIEW {
            let mut admitted = lock(admitted);
            let held: usize = admitted.values().map(|types| types.types().len()).sum();
            if admitted.len() >= ADMITTED || held + size > ADMITTED_BYTES {
                admitted.clear();
            }
            admitted.insert(generic.clone(), Arc::clone(&types));
        }
        Ok(Some(types))
    }

    /// [`Server::run`], writing to `sink`, which [`log`] writes to as well
    /// while it serves.
    pub(crate) fn run_process(&self, mut input: impl Read, sink: &Sink) -> io::Result<()> {
        self.serve(&mut input, sink, FRAME_LIMIT)
    }

    fn serve(&self, input: &mut impl Read, sink: &Sink, limit: usize) -> io::Result<()> {
        // Every call running under a `(run, call)` key: a host may send one
        // key twice, and a `cancel` then reaches each of them.
        let open: Open = Mutex::new(HashMap::new());
        std::thread::scope(|scope| {
            // However serving ends, the calls still running are joined.
            // Each call may wait as long as its author likes, so the host's
            // calls out bound them.
            let calls = Tasks::scoped(scope, Bound::Unbounded);
            loop {
                let frame = match read_frame(input, limit) {
                    Ok(Some(frame)) => frame,
                    Ok(None) => break,
                    // The input ended inside a frame: no message, and no more.
                    Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => break,
                    Err(error) => return Err(error),
                };
                let body = match frame {
                    Frame::Body(body) => body,
                    Frame::TooLarge { length, head } => {
                        if let Some((run, call)) = Message::head(&head, &[Kind::Call]) {
                            let reason = format!(
                                "the call is {length} bytes, larger than the {limit} this implementation reads"
                            );
                            write(sink, run, call, Answered::NoAnswer(reason))?;
                        }
                        continue;
                    }
                };
                match Message::parse(Route::Process, &body) {
                    Ok(Message::Describe { reply_limit, .. }) => {
                        sink.describe(&self.described(), reply_limit)?;
                    }
                    // A withdrawal of a held call runs with its flag set.
                    Ok(Message::Call(call)) => {
                        let cancelled = Cancellation::default();
                        if call.cancelled() {
                            cancelled.cancel();
                        }
                        lock(&open)
                            .entry((call.run, call.call.clone()))
                            .or_default()
                            .push(cancelled.clone());
                        let handed = Handed {
                            call: Some(call),
                            cancelled,
                            open: &open,
                            sink,
                        };
                        calls.spawn_with_stack("flow-call", CALL_STACK, move || {
                            handed.answer(self);
                        });
                    }
                    Ok(Message::Cancel { run, call }) => {
                        for cancelled in lock(&open).get(&(run, call)).into_iter().flatten() {
                            cancelled.cancel();
                        }
                    }
                    // An `ack` says what the host did with a reply this
                    // process sent, which is already out and needs nothing
                    // more; the other frames are no message a toolkit acts on.
                    Ok(
                        Message::Ack { .. }
                        | Message::Described(_)
                        | Message::Reply(_)
                        | Message::Hold { .. }
                        | Message::NoAnswer { .. }
                        | Message::Log(_)
                        | Message::Type { .. }
                        | Message::Typed { .. },
                    ) => {}
                    // A call that does not read, whose key does, has no
                    // answer; any other frame that does not read is noise.
                    Err(error) => {
                        if let Some((run, call)) = Message::head(&body, &[Kind::Call]) {
                            let reason = format!("the call does not read: {error}");
                            write(sink, run, call, Answered::NoAnswer(reason))?;
                        }
                    }
                }
            }
            calls.join().map_err(io::Error::other)
        })
    }

    /// The answer to `describe`: this toolkit's data version, and each
    /// declaration's identity and description.
    fn described(&self) -> Message {
        Message::described(
            self.declarations
                .iter()
                .map(|declaration| (declaration.identity.clone(), declaration.spec.clone()))
                .collect(),
        )
    }

    /// What is sent for `call`, whose log lines go to `sink`.
    fn answer(&self, call: &Call, cancelled: Cancellation, sink: &Sink) -> Answered {
        let Some((index, declaration)) = usize::try_from(call.tool)
            .ok()
            .and_then(|tool| Some((tool, self.declarations.get(tool)?)))
        else {
            return Answered::NoAnswer(format!(
                "this implementation serves {} declarations, and none is number {}",
                self.declarations.len(),
                call.tool
            ));
        };
        let spec = &declaration.spec;
        let types = match self.types(index, call.views()) {
            Ok(types) => types,
            Err(error) => return Answered::NoAnswer(format!("invalid call types: {error}")),
        };
        let bytes = &call.args.0[..];
        let context = Context {
            key: CallKey::new(call.run, call.call.clone()),
            cancelled,
            types: types.clone(),
            sink: Some(sink.clone()),
        };
        let args = match types.as_deref() {
            Some(types) => Args::new(
                bytes,
                types.catalog(),
                types.params().iter().map(|(_, ty)| ty).collect(),
                types.result(),
            ),
            None => Args::new(
                bytes,
                spec.catalog(),
                spec.signature().params.iter().map(|(_, ty)| ty).collect(),
                &spec.signature().result,
            ),
        };
        stopped(|| (declaration.adapter.0)(&context, &args))
    }
}

/// What `answer` gives, or no answer when the author's code panics.
fn stopped(answer: impl FnOnce() -> Answered) -> Answered {
    catch_unwind(AssertUnwindSafe(answer)).unwrap_or_else(|panic| {
        let why = panic
            .downcast_ref::<&str>()
            .map(|text| (*text).to_owned())
            .or_else(|| panic.downcast_ref::<String>().cloned())
            .unwrap_or_else(|| "it panicked".to_owned());
        Answered::NoAnswer(format!("the implementation stopped: {why}"))
    })
}

/// A call handed to the thread that answers it. Dropped unanswered, as it
/// is when no thread could be made for it, it answers that the call has no
/// answer, so the host never waits on a call nothing runs.
struct Handed<'a> {
    /// The call, until it is answered.
    call: Option<Call>,
    cancelled: Cancellation,
    open: &'a Open,
    sink: &'a Sink,
}

impl Handed<'_> {
    /// Answers the call as `server` serves it.
    fn answer(mut self, server: &Server) {
        let Some(call) = self.call.take() else {
            return;
        };
        let answered = server.answer(&call, self.cancelled.clone(), self.sink);
        finished(self.open, &(call.run, call.call.clone()), &self.cancelled);
        // A withdrawn call is closed: holding it again promises nothing, so
        // nothing is sent.
        if call.cancelled() && matches!(answered, Answered::Hold(_)) {
            return;
        }
        let _ = write(self.sink, call.run, call.call, answered);
    }
}

impl Drop for Handed<'_> {
    fn drop(&mut self) {
        if let Some(call) = self.call.take() {
            finished(self.open, &(call.run, call.call.clone()), &self.cancelled);
            let reason = "no thread could be made for the call".to_owned();
            let _ = write(self.sink, call.run, call.call, Answered::NoAnswer(reason));
        }
    }
}

/// The cancel flag of each call running, by its `(run, call)` key.
type Open = Mutex<HashMap<(RunId, CallRef), Vec<Cancellation>>>;

/// Forgets the call whose flag is `cancelled`, leaving any other call
/// running under the same `key`.
fn finished(open: &Open, key: &(RunId, CallRef), cancelled: &Cancellation) {
    let mut open = lock(open);
    // The call's flag was entered under `key` before the call started, and a
    // key is removed only once its last flag is.
    let flags = open
        .get_mut(key)
        .expect("a running call's key stays open until it finishes");
    flags.retain(|flag| !Arc::ptr_eq(&flag.0, &cancelled.0));
    if flags.is_empty() {
        open.remove(key);
    }
}

/// Writes what is sent for `call` of `run`, a `reply`, a `hold` or a
/// `no_answer`, as one frame, whole, and flushes it.
fn write(sink: &Sink, run: RunId, call: CallRef, answered: Answered) -> io::Result<()> {
    let message = match answered {
        Answered::Reply(outcome) => Message::Reply(Reply { run, call, outcome }),
        Answered::Hold(retry_at) => Message::Hold {
            run,
            call,
            retry_at,
        },
        Answered::NoAnswer(reason) => Message::NoAnswer { run, call, reason },
    };
    sink.send(&message)
}

/// Serves with `sink` as the output [`log`] writes to, for as long as
/// `serve` runs.
pub(crate) fn logging_to<T>(sink: &Sink, serve: impl FnOnce() -> T) -> T {
    *lock(&PROCESS) = Some(sink.clone());
    let served = serve();
    lock(&PROCESS).take();
    served
}

impl Sink {
    /// The output that writes to `writer`.
    pub(crate) fn new(writer: impl Write + Send + 'static) -> Sink {
        Sink(Arc::new(Mutex::new(Output {
            writer: Box::new(writer),
            reply_limit: None,
            asked: false,
            held: Vec::new(),
        })))
    }

    /// Writes `message` as one frame, whole, and flushes it.
    fn send(&self, message: &Message) -> io::Result<()> {
        let mut output = lock(&self.0);
        let frame = message.frame();
        if let (Some(limit), Message::Reply(reply)) = (output.reply_limit, message) {
            let mut answer = Vec::new();
            flow_abi::wire::Wire::write(&reply.outcome, &mut answer);
            let length = answer.len();
            if u64::try_from(length).unwrap_or(u64::MAX) > limit {
                return write_frame(
                    &mut output.writer,
                    &Message::NoAnswer {
                        run: reply.run,
                        call: reply.call.clone(),
                        reason: format!(
                            "the answer is {length} bytes, past the host's reply_limit of {limit}"
                        ),
                    },
                );
            }
        }
        output.writer.write_all(&frame)?;
        output.writer.flush()
    }

    /// Notes the host's `describe` request and sends `answer`, after the
    /// log lines held until it came.
    fn describe(&self, answer: &Message, reply_limit: u64) -> io::Result<()> {
        let mut output = lock(&self.0);
        output.reply_limit = Some(reply_limit);
        output.asked = true;
        for log in std::mem::take(&mut output.held) {
            write_frame(&mut output.writer, &Message::Log(log))?;
        }
        write_frame(&mut output.writer, answer)
    }
}

impl<'a> Args<'a> {
    /// The arguments `bytes` hold, each at its parameter's type in
    /// `catalog`, the answer written at `result`.
    pub(crate) fn new(
        bytes: &'a [u8],
        catalog: &'a Catalog,
        params: Vec<&'a Type>,
        result: &'a Type,
    ) -> Self {
        Args {
            reader: RefCell::new(Reader::new(bytes)),
            catalog,
            params,
            next: Cell::new(0),
            result,
        }
    }
}

#[cfg(test)]
impl Server {
    /// Serves the frames read from `input`, writing each frame to `output`,
    /// until the input ends and every call is answered.
    pub(crate) fn run(
        &self,
        mut input: impl Read,
        output: impl Write + Send + 'static,
    ) -> io::Result<()> {
        self.serve(&mut input, &Sink::new(output), FRAME_LIMIT)
    }

    /// How many instantiations the declaration at `index` keeps admitted.
    pub(crate) fn admitted(&self, index: usize) -> usize {
        lock(&self.admitted[index]).len()
    }

    /// Serves `input` with a frame limit of `limit` bytes.
    pub(crate) fn run_within(
        &self,
        mut input: impl Read,
        output: impl Write + Send + 'static,
        limit: usize,
    ) -> io::Result<()> {
        self.serve(&mut input, &Sink::new(output), limit)
    }

    /// Everything serving the frames `input` holds writes, once it is done.
    pub(crate) fn served(&self, input: &[u8]) -> Vec<u8> {
        let output = Buffer::default();
        self.run(input, output.clone()).expect("served");
        output.taken()
    }
}

/// An output a test reads back once serving is done.
#[cfg(test)]
#[derive(Clone, Default)]
pub(crate) struct Buffer(Arc<Mutex<Vec<u8>>>);

#[cfg(test)]
impl Buffer {
    /// What was written to it.
    pub(crate) fn taken(&self) -> Vec<u8> {
        std::mem::take(&mut lock(&self.0))
    }
}

#[cfg(test)]
impl Write for Buffer {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        lock(&self.0).extend_from_slice(bytes);
        Ok(bytes.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
    use super::*;

    #[test]
    fn a_call_no_thread_ran_is_answered_with_no_answer_and_forgotten() {
        let output = Buffer::default();
        let sink = Sink::new(output.clone());
        let open: Open = Mutex::new(HashMap::new());
        let run = RunId::parse("0123456789abcdef0123456789abcdef").expect("a run id");
        let call = CallRef::parse("root#1").expect("a call id");
        let cancelled = Cancellation::default();
        lock(&open)
            .entry((run, call.clone()))
            .or_default()
            .push(cancelled.clone());
        drop(Handed {
            call: Some(Call {
                run,
                call: call.clone(),
                tool: 0,
                flags: flow_tool_protocol::Flags::Plain,
                args: flow_abi::wire::Rest::default(),
            }),
            cancelled,
            open: &open,
            sink: &sink,
        });
        assert!(lock(&open).is_empty(), "the call is forgotten");
        let written = output.taken();
        let Ok(Some(Frame::Body(body))) = read_frame(&mut &written[..], FRAME_LIMIT) else {
            panic!("one frame is written: {written:?}");
        };
        assert_eq!(
            Message::parse(Route::Process, &body).expect("a message"),
            Message::NoAnswer {
                run,
                call,
                reason: "no thread could be made for the call".to_owned(),
            }
        );
    }
}