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
//! The Tool process protocol, served (`abi.md`, *The Tool process
//! protocol*): JSON-RPC 2.0, one message per line.
//!
//! `describe` is answered from the declarations the code was generated
//! from; each `call` runs on a thread of its own and is answered by one
//! `reply`, written whole; a `cancel` sets the call's flag. When the input
//! ends, the calls still running finish and are answered, and the server
//! returns.

use std::collections::HashMap;
use std::io::{self, BufRead, Write};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};

use flow_abi::{Json, Limits, TypeSpec, ValidatedTypes};

use crate::data::{ContextCodec, Data, DecodeError, variant, within};

/// Why a call did not produce its success value.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Problem<E> {
    /// The declared error: the call happened and failed.
    Failed(E),
    /// The call definitely did not happen, with why.
    NotRun(String),
    /// The call may or may not have happened, with why.
    Unknown(String),
}

/// What a method knows about the call it answers.
#[derive(Clone, Debug)]
pub struct Context {
    run: String,
    call: String,
    schema: Option<Json>,
    cancelled: Arc<AtomicBool>,
    types: Option<Arc<ValidatedTypes>>,
}

impl Context {
    /// Validates the complete call views before making an author context.
    #[allow(clippy::needless_pass_by_value)] // The public constructor takes ownership of both wire views.
    pub fn try_new(
        run: &str,
        call: &str,
        spec: &TypeSpec,
        schema: Option<Json>,
        types: Option<Json>,
        cancelled: Arc<AtomicBool>,
    ) -> Result<Context, DecodeError> {
        let types = spec
            .validate_call(schema.as_ref(), types.as_ref())?
            .map(Arc::new);
        Ok(Context {
            run: run.to_owned(),
            call: call.to_owned(),
            schema,
            cancelled,
            types,
        })
    }

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

    fn graph(&self) -> Result<Arc<ValidatedTypes>, DecodeError> {
        self.types
            .clone()
            .ok_or_else(|| crate::data::refused("nongeneric context has no dynamic codecs"))
    }

    /// A generic binding's owned codec, when that binding crosses the boundary.
    pub fn codec(&self, name: &str) -> Result<ContextCodec, DecodeError> {
        let graph = self.graph()?;
        let ty = graph
            .binding(name)
            .cloned()
            .ok_or_else(|| crate::data::refused(format!("unknown binding {name}")))?;
        ContextCodec::new(graph, ty, flow_abi::Mode::Reply)
    }
    /// An argument's owned concrete codec.
    pub fn argument_codec(&self, name: &str) -> Result<ContextCodec, DecodeError> {
        let graph = self.graph()?;
        let ty = graph
            .argument(name)
            .cloned()
            .ok_or_else(|| crate::data::refused(format!("unknown argument {name}")))?;
        ContextCodec::new(graph, ty, flow_abi::Mode::Rebuild)
    }
    /// The owned success codec.
    pub fn success_codec(&self) -> Result<ContextCodec, DecodeError> {
        let graph = self.graph()?;
        ContextCodec::new(graph.clone(), graph.ok().clone(), flow_abi::Mode::Reply)
    }
    /// The owned failure codec.
    pub fn failure_codec(&self) -> Result<ContextCodec, DecodeError> {
        let graph = self.graph()?;
        ContextCodec::new(graph.clone(), graph.err().clone(), flow_abi::Mode::Reply)
    }

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

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

    /// For a generic Tool, the schema of the success type the caller
    /// expects.
    pub fn schema(&self) -> Option<&Json> {
        self.schema.as_ref()
    }

    /// Writes one call-correlated operational log record outside protocol stdout.
    pub fn log(&self, level: &str, message: &str) -> io::Result<()> {
        if !matches!(level, "trace" | "debug" | "info" | "warn" | "error") {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "log level must be trace, debug, info, warn or error",
            ));
        }
        let record = Json::Object(vec![
            ("run".into(), Json::String(self.run.clone())),
            ("call".into(), Json::String(self.call.clone())),
            ("level".into(), Json::String(level.into())),
            ("message".into(), Json::String(message.into())),
        ]);
        let line = format!("\nFLOW_LOG {}\n", record.canonical());
        io::stderr().lock().write_all(line.as_bytes())
    }

    /// Whether the host asked to stop work on this call. It proves nothing
    /// either way.
    pub fn cancelled(&self) -> bool {
        self.cancelled.load(Ordering::SeqCst)
    }

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

/// A call's arguments, by parameter key.
#[derive(Debug)]
pub struct Args<'j>(&'j Json);

impl Args<'_> {
    /// A named raw argument for a generated contextual factory.
    pub fn json(&self, name: &str) -> Result<&Json, DecodeError> {
        self.0
            .get(name)
            .ok_or_else(|| crate::data::inside(crate::data::refused("is missing"), name))
    }
    /// The argument `name`, decoded.
    pub fn take<T: Data>(&self, name: &str) -> Result<T, DecodeError> {
        match self.0.get(name) {
            Some(value) => within(value, name, T::decode),
            None => Err(crate::data::inside(
                crate::data::refused("is missing"),
                name,
            )),
        }
    }
}

type Handler = Box<dyn Fn(&Context, &Args<'_>) -> Json + Send + Sync>;

/// One declaration an implementation serves: what `describe` lists for it,
/// and the method answering its calls.
pub(crate) struct Declaration {
    entry: Json,
    spec: TypeSpec,
    handler: Handler,
}

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

impl Declaration {
    /// The declaration `describe` lists as `entry` — the JSON text of
    /// `{"tool", "fingerprint", "signature"}` — answered by `method`, which
    /// reads the arguments and calls the author's code.
    ///
    /// # Panics
    ///
    /// When `entry` is not JSON, which generated code never gives.
    pub(crate) fn new<T, E, F>(entry: &str, spec: TypeSpec, method: F) -> Declaration
    where
        T: Data,
        E: Data,
        F: Fn(&Context, &Args<'_>) -> Result<Result<T, Problem<E>>, DecodeError>
            + Send
            + Sync
            + 'static,
    {
        let entry = flow_abi::parse(entry, &Limits::default()).expect("a declaration's entry");
        Declaration {
            entry,
            spec,
            handler: Box::new(move |context, args| outcome(method(context, args))),
        }
    }

    /// A declaration whose generated contextual factories produce JSON after author invocation.
    pub(crate) fn contextual<F>(entry: &str, spec: TypeSpec, method: F) -> Declaration
    where
        F: Fn(&Context, &Args<'_>) -> Result<Result<Json, Problem<Json>>, DecodeError>
            + Send
            + Sync
            + 'static,
    {
        let entry = flow_abi::parse(entry, &Limits::default()).expect("a declaration's entry");
        Declaration {
            entry,
            spec,
            handler: Box::new(move |context, args| outcome(method(context, args))),
        }
    }

    fn serves(&self, tool: &Json) -> bool {
        let named = |key: &str| self.entry.get("tool").and_then(|own| own.get(key));
        let origin = if let Some(package) = named("package") {
            named("repository").is_none()
                && tool.get("repository").is_none()
                && tool.get("package") == Some(package)
        } else {
            tool.get("package").is_none()
                && named("repository").is_some()
                && named("repository") == tool.get("repository")
        };
        origin
            && ["file", "name"]
                .into_iter()
                .all(|key| named(key) == tool.get(key) && named(key).is_some())
    }
}

/// The reply's `outcome` for what a method returned.
fn outcome<T: Data, E: Data>(answer: Result<Result<T, Problem<E>>, DecodeError>) -> Json {
    match answer {
        Ok(Ok(value)) => variant("Ok", value.encode()),
        Ok(Err(Problem::Failed(error))) => variant("Failed", error.encode()),
        Ok(Err(Problem::NotRun(reason))) => variant("NotRun", Json::String(reason)),
        Ok(Err(Problem::Unknown(reason))) => variant("Unknown", Json::String(reason)),
        Err(error) => variant(
            "NotRun",
            Json::String(format!("the arguments do not decode: {error}")),
        ),
    }
}

#[cfg(test)]
mod origin_tests {
    use super::*;

    fn json(value: &str) -> Json {
        flow_abi::parse(value, &Limits::default()).unwrap()
    }

    #[test]
    fn package_calls_do_not_alias_other_packages_or_repository_origins() {
        for (origin, matched) in [
            (r#""package":"flow/example""#, true),
            (r#""package":"other/example""#, false),
            (r#""repository":"flow/example""#, false),
            (r#""package":"flow/example","repository":null"#, false),
        ] {
            let declaration = Declaration::new::<String, String, _>(
                r#"{"tool":{"package":"flow/example","version":"v1","file":"","name":"act"},"fingerprint":"sha256:x","signature":{}}"#,
                TypeSpec::read(&json(
                    r#"{"generic":[],"params":[],"ok":"Text","err":"Text","declarations":{}}"#,
                ))
                .unwrap(),
                |_, _| Ok(Ok("called".into())),
            );
            let server = Server::new("0.1", vec![declaration]);
            let input = format!(
                "{{\"jsonrpc\":\"2.0\",\"method\":\"call\",\"params\":{{\"run\":\"r\",\"call\":\"c\",\"tool\":{{{origin},\"version\":\"v9\",\"file\":\"\",\"name\":\"act\"}},\"args\":{{}}}}}}\n"
            );
            let mut output = Vec::new();
            server
                .run(std::io::Cursor::new(input), &mut output)
                .unwrap();
            let reply = json(std::str::from_utf8(&output).unwrap().trim());
            let outcome = reply.get("params").unwrap().get("outcome").unwrap();
            if matched {
                assert_eq!(outcome, &json(r#"{"Ok":"called"}"#));
            } else {
                assert!(outcome.get("NotRun").is_some());
            }
        }
    }
}

/// An implementation's declarations, served over the Tool process
/// protocol.
#[derive(Debug)]
pub(crate) struct Server {
    data: String,
    declarations: Vec<Declaration>,
}

impl Server {
    /// A server for `declarations`, answering `describe` with the data
    /// version `data`.
    pub(crate) fn new(data: &str, declarations: Vec<Declaration>) -> Server {
        Server {
            data: data.to_owned(),
            declarations,
        }
    }

    /// Serves the messages read from `input`, writing each answer to
    /// `output`, until the input ends and every call is answered.
    pub(crate) fn run(&self, input: impl BufRead, output: impl Write + Send) -> io::Result<()> {
        let output = Mutex::new(output);
        let open: Mutex<HashMap<(String, String), Arc<AtomicBool>>> = Mutex::new(HashMap::new());
        std::thread::scope(|scope| {
            for line in input.lines() {
                let line = line?;
                let Ok(message) = flow_abi::parse(&line, &crate::data::LIMITS) else {
                    continue;
                };
                let params = message.get("params");
                let text = |key: &str| match params.and_then(|params| params.get(key)) {
                    Some(Json::String(text)) => Some(text.clone()),
                    _ => None,
                };
                match message.get("method") {
                    Some(Json::String(method)) if method == "describe" => {
                        let id = message.get("id").cloned().unwrap_or(Json::Null);
                        write(&output, &self.described(id))?;
                    }
                    Some(Json::String(method)) if method == "call" => {
                        let (Some(run), Some(call)) = (text("run"), text("call")) else {
                            continue;
                        };
                        let params = params.cloned().unwrap_or(Json::Null);
                        let cancelled = Arc::new(AtomicBool::new(false));
                        lock(&open).insert((run.clone(), call.clone()), cancelled.clone());
                        let (output, open) = (&output, &open);
                        scope.spawn(move || {
                            let outcome = self.answer(&run, &call, cancelled, &params);
                            lock(open).remove(&(run.clone(), call.clone()));
                            let reply = reply(&run, &call, outcome);
                            let _ = write(output, &reply);
                        });
                    }
                    Some(Json::String(method)) if method == "cancel" => {
                        if let (Some(run), Some(call)) = (text("run"), text("call"))
                            && let Some(context) = lock(&open).get(&(run, call))
                        {
                            context.store(true, Ordering::SeqCst);
                        }
                    }
                    _ => {}
                }
            }
            Ok(())
        })
    }

    fn described(&self, id: Json) -> Json {
        let tools = self
            .declarations
            .iter()
            .map(|declaration| declaration.entry.clone())
            .collect();
        Json::Object(vec![
            ("jsonrpc".to_owned(), Json::String("2.0".to_owned())),
            ("id".to_owned(), id),
            (
                "result".to_owned(),
                Json::Object(vec![
                    ("data".to_owned(), Json::String(self.data.clone())),
                    ("tools".to_owned(), Json::Array(tools)),
                ]),
            ),
        ])
    }

    /// The outcome of the call `params` describes.
    fn answer(&self, run: &str, call: &str, cancelled: Arc<AtomicBool>, params: &Json) -> Json {
        let tool = params.get("tool").cloned().unwrap_or(Json::Null);
        let Some(declaration) = self.declarations.iter().find(|d| d.serves(&tool)) else {
            return variant(
                "NotRun",
                Json::String(format!(
                    "this implementation serves no declaration {}",
                    tool.canonical()
                )),
            );
        };
        let context = match Context::try_new(
            run,
            call,
            &declaration.spec,
            params.get("schema").cloned(),
            params.get("types").cloned(),
            cancelled,
        ) {
            Ok(context) => context,
            Err(error) => {
                return variant(
                    "NotRun",
                    Json::String(format!("invalid call types: {error}")),
                );
            }
        };
        let args = params.get("args").cloned().unwrap_or(Json::Null);
        let answered = catch_unwind(AssertUnwindSafe(|| {
            (declaration.handler)(&context, &Args(&args))
        }));
        answered.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());
            variant(
                "Unknown",
                Json::String(format!("the implementation stopped: {why}")),
            )
        })
    }
}

fn reply(run: &str, call: &str, outcome: Json) -> Json {
    Json::Object(vec![
        ("jsonrpc".to_owned(), Json::String("2.0".to_owned())),
        ("method".to_owned(), Json::String("reply".to_owned())),
        (
            "params".to_owned(),
            Json::Object(vec![
                ("run".to_owned(), Json::String(run.to_owned())),
                ("call".to_owned(), Json::String(call.to_owned())),
                ("outcome".to_owned(), outcome),
            ]),
        ),
    ])
}

fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    mutex
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

/// Writes `message` as one line, whole, and flushes it.
fn write(output: &Mutex<impl Write>, message: &Json) -> io::Result<()> {
    let mut line = message.canonical();
    line.push('\n');
    let mut output = lock(output);
    output.write_all(line.as_bytes())?;
    output.flush()
}