flow-abi 0.1.0-rc.5

The host boundary's value encoding: the binary encoding and the JSON form, the canonical form and its hash, JSON Schemas, Tool signatures, and the answers a Tool call passes.
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
//! A type's JSON Schema, draft 2020-12 (`abi.md`, *Schemas*).
//!
//! The schema is generated from the declarations and describes the encoding
//! above; it adds no rule, and where JSON Schema cannot say what the encoding
//! says — an integer's exact size, a set's order — the encoding decides.
//!
//! # Readings
//!
//! - A generic declaration has one `$defs` entry per list of arguments it is
//!   used with, keyed by its identity with those arguments written after it:
//!   `std@v1/result.Result<Int, Text>`. Types of one name declared in blocks
//!   of one module are told apart by the `#n` their module gives them in
//!   source order, `Point#2` for the second.
//! - `Option` is written in place, not in `$defs`: inside a record it is its
//!   payload's schema, and elsewhere a `oneOf` of `"None"` and `{"Some": ...}`.
//! - A constructor's object form allows no other member, since decoding
//!   refuses one; a record allows them, since a reply may carry extra fields.
//! - A positional payload of several values and a tuple are arrays of exactly
//!   their length; `Unit` is the empty array, and `Never` the schema `false`.
//! - A host type is a `string`: the token.
//! - A member's doc comment sits beside what it documents: a field's on its
//!   property schema, a constructor's on its `oneOf` branch. A field whose
//!   schema is `false` is written `{"allOf": [false]}` to carry one.

use std::collections::{HashMap, VecDeque};
use std::fmt::Write as _;

use flow_types::{OptionCtor, Payload};

use crate::catalog::{Catalog, StdForm};
use crate::error::{EncodeError, EncodeErrorKind, Place};
use crate::json::Json;
use flow_types::{Body, DeclId, Type, Versions};

/// The `$schema` this crate writes.
pub const DIALECT: &str = "https://json-schema.org/draft/2020-12/schema";

/// How many `$defs` entries one schema may have. A type whose
/// declarations reach more argument lists than this is refused rather than
/// written.
const DEFS: usize = 1_000;

/// The schema of `ty`, with each named type in `$defs` and every doc comment
/// as a `description`.
///
/// # Errors
///
/// An [`EncodeError`] when `ty` has no schema, such as a function's, or
/// names more declarations than a schema may define.
pub fn schema(catalog: &Catalog, ty: &Type) -> Result<Json, EncodeError> {
    Writer::new(catalog).document(ty)
}

struct Writer<'c> {
    catalog: &'c Catalog,
    keys: HashMap<(DeclId, Vec<Type>), String>,
    defs: Vec<(String, Json)>,
    pending: VecDeque<(usize, DeclId, Vec<Type>)>,
}

impl<'c> Writer<'c> {
    fn new(catalog: &'c Catalog) -> Self {
        Writer {
            catalog,
            keys: HashMap::new(),
            defs: Vec::new(),
            pending: VecDeque::new(),
        }
    }

    /// The whole schema of `ty`: its own schema with `$schema` and, when it
    /// names any declaration, `$defs`.
    fn document(mut self, ty: &Type) -> Result<Json, EncodeError> {
        let mut root = self.schema(ty)?;
        // Each `$defs` entry is written after the one before it, so writing
        // one that names another only queues it: however deep a chain of
        // declarations runs, the writer's own stack does not.
        while let Some((slot, decl, args)) = self.pending.pop_front() {
            self.defs[slot].1 = self.body(decl, &args)?;
        }
        let mut members = vec![("$schema".to_owned(), Json::String(DIALECT.into()))];
        match root {
            Json::Object(ref mut own) => members.append(own),
            // `true` and `false` schemas, which a `$defs` can't be added to.
            other => members.push(("allOf".into(), Json::Array(vec![other]))),
        }
        if !self.defs.is_empty() {
            members.push(("$defs".into(), Json::Object(self.defs)));
        }
        Ok(Json::Object(members))
    }

    fn schema(&mut self, ty: &Type) -> Result<Json, EncodeError> {
        enum Visit<'a> {
            Read(&'a Type),
            Write { ty: &'a Type, start: usize },
        }

        let mut pending = vec![Visit::Read(ty)];
        let mut schemas = Vec::new();
        while let Some(visit) = pending.pop() {
            let (ty, start) = match visit {
                Visit::Read(ty) => {
                    pending.push(Visit::Write {
                        ty,
                        start: schemas.len(),
                    });
                    match ty {
                        Type::List(item) | Type::Set(item) | Type::Option(item) => {
                            pending.push(Visit::Read(item));
                        }
                        Type::Dict(key, item) => {
                            pending.push(Visit::Read(item));
                            if *self.catalog.erase(key) != Type::Text {
                                pending.push(Visit::Read(key));
                            }
                        }
                        Type::Tuple(parts) => {
                            pending.extend(parts.iter().rev().map(Visit::Read));
                        }
                        Type::Int
                        | Type::Decimal
                        | Type::Bool
                        | Type::Text
                        | Type::Bytes
                        | Type::Duration
                        | Type::Instant
                        | Type::Unit
                        | Type::Never
                        | Type::Json
                        | Type::Named(_, _)
                        | Type::Param(_)
                        | Type::Task(_)
                        | Type::Function { .. }
                        | Type::NotData => {}
                    }
                    continue;
                }
                Visit::Write { ty, start } => (ty, start),
            };
            let parts = schemas.split_off(start);
            schemas.push(self.schema_node(ty, parts)?);
        }
        Ok(schemas.pop().expect("one root schema"))
    }

    fn schema_node(&mut self, ty: &Type, parts: Vec<Json>) -> Result<Json, EncodeError> {
        let object = |members: Vec<(&str, Json)>| {
            Json::Object(
                members
                    .into_iter()
                    .map(|(key, value)| (key.to_owned(), value))
                    .collect(),
            )
        };
        let string = |text: &str| Json::String(text.to_owned());
        let typed = |name: &str| object(vec![("type", string(name))]);
        let mut parts = parts.into_iter();
        let schema = match ty {
            Type::Int => typed("integer"),
            Type::Decimal => typed("number"),
            Type::Bool => typed("boolean"),
            Type::Text => typed("string"),
            Type::Bytes => object(vec![
                ("type", string("string")),
                ("contentEncoding", string("base64")),
            ]),
            Type::Duration => object(vec![
                ("type", string("string")),
                ("format", string("duration")),
            ]),
            Type::Instant => object(vec![
                ("type", string("string")),
                ("format", string("date-time")),
            ]),
            Type::Unit => array(Vec::new()),
            Type::Never => Json::Bool(false),
            Type::Json => Json::Object(Vec::new()),
            Type::List(_) => object(vec![
                ("type", string("array")),
                ("items", parts.next().expect("a list item schema")),
            ]),
            Type::Set(_) => object(vec![
                ("type", string("array")),
                ("items", parts.next().expect("a set item schema")),
                ("uniqueItems", Json::Bool(true)),
            ]),
            Type::Dict(key, _) if *self.catalog.erase(key) == Type::Text => object(vec![
                ("type", string("object")),
                (
                    "additionalProperties",
                    parts.next().expect("a dictionary item schema"),
                ),
            ]),
            Type::Dict(_, _) => object(vec![
                ("type", string("array")),
                ("items", array(parts.collect())),
            ]),
            Type::Option(_) => object(vec![(
                "oneOf",
                Json::Array(vec![
                    constant(OptionCtor::None.name()),
                    single(
                        OptionCtor::Some.name(),
                        parts.next().expect("an option item schema"),
                    ),
                ]),
            )]),
            Type::Tuple(_) => array(parts.collect()),
            Type::Named(decl, args) => {
                object(vec![("$ref", string(&self.reference(*decl, args)?))])
            }
            Type::Param(_) | Type::Task(_) | Type::Function { .. } | Type::NotData => {
                return Err(EncodeError::new(
                    &Place::default(),
                    EncodeErrorKind::NoEncoding,
                    "has a type with no encoding",
                ));
            }
        };
        Ok(schema)
    }

    /// The `$ref` to `decl` applied to `args`, queueing its `$defs` entry
    /// the first time it is reached.
    fn reference(&mut self, decl: DeclId, args: &[Type]) -> Result<String, EncodeError> {
        let id = (decl, args.to_vec());
        if let Some(key) = self.keys.get(&id) {
            return Ok(pointer(key));
        }
        if self.keys.len() == DEFS {
            return Err(too_large());
        }
        let written = self
            .catalog
            .written(&Type::Named(decl, args.to_vec()), Versions::Shown);
        let key = written;
        self.keys.insert(id, key.clone());
        self.pending
            .push_back((self.defs.len(), decl, args.to_vec()));
        self.defs.push((key.clone(), Json::Null));
        Ok(pointer(&key))
    }

    fn body(&mut self, decl: DeclId, args: &[Type]) -> Result<Json, EncodeError> {
        let declared = self.catalog.decl(decl);
        let member = |index: usize| declared.members.get(index);
        let members: Vec<(String, Json)> = match &declared.body {
            // A newtype's entry is its base's schema, with nothing of its
            // own but its doc comment (`abi.md`, *Schemas*).
            Body::Newtype(base) => {
                let mut schema = self.schema(&base.subst(args))?;
                // `url.Url` alone adds the format `uri`.
                if StdForm::of(declared) == Some(StdForm::Url)
                    && let Json::Object(members) = &mut schema
                {
                    members.push(("format".to_owned(), Json::String("uri".to_owned())));
                }
                return Ok(Self::described(schema, declared.doc.as_deref()));
            }
            Body::Record(shape, fields) => {
                let fields: Vec<Type> = fields.iter().map(|field| field.subst(args)).collect();
                let names: Vec<&str> = shape.fields().collect();
                let docs: Vec<Option<&str>> = (0..names.len())
                    .map(|index| member(index).and_then(|member| member.doc.as_deref()))
                    .collect();
                self.fields(&names, &fields, &docs)?
            }
            Body::Enum(shape, ctors) => {
                let branches = ctors
                    .iter()
                    .enumerate()
                    .map(|(index, parts)| {
                        let ctor = shape
                            .constructor(index)
                            .expect("one payload per constructor");
                        let parts: Vec<Type> = parts.iter().map(|part| part.subst(args)).collect();
                        let doc = member(index).and_then(|member| member.doc.as_deref());
                        let payload = match ctor.payload() {
                            Payload::None => {
                                return Ok(Self::described(constant(ctor.name()), doc));
                            }
                            Payload::Positional(1) => self.schema(&parts[0])?,
                            Payload::Positional(_) => array(
                                parts
                                    .iter()
                                    .map(|part| self.schema(part))
                                    .collect::<Result<_, _>>()?,
                            ),
                            Payload::Named(names) => {
                                let names: Vec<&str> = names.iter().map(|name| &**name).collect();
                                let docs: Vec<Option<&str>> = (0..names.len())
                                    .map(|field| {
                                        member(index)
                                            .and_then(|member| member.fields.get(field))
                                            .and_then(Option::as_deref)
                                    })
                                    .collect();
                                Json::Object(self.fields(&names, &parts, &docs)?)
                            }
                        };
                        Ok(Self::described(single(ctor.name(), payload), doc))
                    })
                    .collect::<Result<_, EncodeError>>()?;
                vec![("oneOf".into(), Json::Array(branches))]
            }
            Body::NonData => {
                return Err(EncodeError::new(
                    &Place::default(),
                    EncodeErrorKind::NoEncoding,
                    "has a type with no encoding",
                ));
            }
            Body::Host => vec![("type".into(), Json::String("string".into()))],
        };
        Ok(Self::described(
            Json::Object(members),
            declared.doc.as_deref(),
        ))
    }

    /// `schema` with `doc` as its `description`, when there is one and the
    /// schema is written to be read.
    fn described(mut schema: Json, doc: Option<&str>) -> Json {
        let Some(doc) = doc else {
            return schema;
        };
        let description = ("description".to_owned(), Json::String(doc.to_owned()));
        match schema {
            Json::Object(ref mut members) => {
                members.push(description);
                schema
            }
            // `false`, the one schema a field can have that is not an
            // object.
            other => Json::Object(vec![
                ("allOf".to_owned(), Json::Array(vec![other])),
                description,
            ]),
        }
    }

    /// An object schema's members for named fields: each field's schema, an
    /// `Option` field's being its payload's, described by its doc comment in
    /// `docs`, every other field required, and in a signature the names in
    /// declaration order as `order`.
    fn fields(
        &mut self,
        names: &[&str],
        types: &[Type],
        docs: &[Option<&str>],
    ) -> Result<Vec<(String, Json)>, EncodeError> {
        let mut properties = Vec::new();
        let mut required = Vec::new();
        for ((name, ty), doc) in names.iter().zip(types).zip(docs) {
            // A field whose type erases to `Option<X>` is written as any
            // `Option<X>` field is, not required and with `X`'s schema; for a
            // newtype over one, the newtype's doc stands in for a missing
            // field doc, since its `$defs` entry is not referred to here.
            let catalog = self.catalog;
            let (schema, doc) = if let Type::Option(item) = &*catalog.erase(ty) {
                let own = match ty {
                    Type::Named(decl, _) => catalog.decl(*decl).doc.as_deref(),
                    _ => None,
                };
                (self.schema(item)?, doc.or(own))
            } else {
                required.push(Json::String((*name).to_owned()));
                (self.schema(ty)?, *doc)
            };
            properties.push(((*name).to_owned(), Self::described(schema, doc)));
        }
        let members = vec![
            ("type".to_owned(), Json::String("object".into())),
            ("properties".to_owned(), Json::Object(properties)),
            ("required".to_owned(), Json::Array(required)),
        ];
        Ok(members)
    }
}

fn too_large() -> EncodeError {
    EncodeError::new(
        &Place::default(),
        EncodeErrorKind::TooLarge,
        "has a type too large to describe",
    )
}

/// `{"const": name}`: a constructor with no payload.
fn constant(name: &str) -> Json {
    Json::Object(vec![("const".into(), Json::String(name.to_owned()))])
}

/// An object with exactly the one member `name`, holding `payload`.
fn single(name: &str, payload: Json) -> Json {
    Json::Object(vec![
        ("type".into(), Json::String("object".into())),
        (
            "properties".into(),
            Json::Object(vec![(name.to_owned(), payload)]),
        ),
        (
            "required".into(),
            Json::Array(vec![Json::String(name.to_owned())]),
        ),
        ("additionalProperties".into(), Json::Bool(false)),
    ])
}

/// An array of exactly `parts`, in order.
fn array(parts: Vec<Json>) -> Json {
    let count = Json::Number(flow_value::Decimal::from(&flow_value::Int::from_count(
        parts.len(),
    )));
    Json::Object(vec![
        ("type".into(), Json::String("array".into())),
        ("prefixItems".into(), Json::Array(parts)),
        ("items".into(), Json::Bool(false)),
        ("minItems".into(), count),
    ])
}

/// The `$ref` naming the `$defs` entry `key`: a JSON Pointer in a URI
/// fragment, with `~` and `/` escaped as the pointer requires and every
/// character a fragment can't hold percent-encoded.
pub(crate) fn pointer(key: &str) -> String {
    let mut out = String::from("#/$defs/");
    let escaped = key.replace('~', "~0").replace('/', "~1");
    for byte in escaped.bytes() {
        if byte.is_ascii_alphanumeric() || b"-._~!$&'()*+,;=:@/".contains(&byte) {
            out.push(char::from(byte));
        } else {
            write!(out, "%{byte:02X}").expect("writing to a string");
        }
    }
    out
}