flow-abi 0.1.0

The value encoding at the host boundary: type-directed JSON encoding and decoding, the canonical form and its hash, JSON Schemas, and Tool declaration fingerprints.
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
//! Encoding a value at its type (`abi.md`, *The value encoding*), and the
//! canonical text and hash taken over it.

use std::fmt;
use std::sync::Arc;

use flow_value::{Decimal, Dict, Payload, TaskId, Value, Variant};
use sha2::{Digest as _, Sha256};

use crate::error::{EncodeError, Path};
use crate::json::Json;
use crate::types::{Body, Catalog, DeclId, Type};

/// Returns `value`, of type `ty`, as JSON.
///
/// The encoding carries no type tags: the type decides it. A value that does
/// not have the type, and a type with no encoding, are [`EncodeError`]s; a
/// checked program reaches neither.
pub fn encode(catalog: &Catalog, ty: &Type, value: &Value) -> Result<Json, EncodeError> {
    Encoder::new(catalog, None, None).value(ty, value)
}

/// Returns `value`, of type `ty`, as a checkpoint's arguments hold it
/// (`trace.md`, *Checkpoints*): as [`encode`] writes it, except that a task
/// is the id of the call it is parked on, which `tasks` gives for the task
/// and the type of its result. A task `tasks` names no call for is an
/// [`EncodeError`].
pub fn encode_checkpoint(
    catalog: &Catalog,
    ty: &Type,
    value: &Value,
    tasks: &mut dyn FnMut(TaskId, &Type) -> Option<String>,
) -> Result<Json, EncodeError> {
    Encoder::new(catalog, Some(tasks), None).value(ty, value)
}

/// Returns the canonical text of `value`, of type `ty`: the one text history
/// stores and every hash is taken over (`abi.md`, *The canonical form*).
pub fn canonical(catalog: &Catalog, ty: &Type, value: &Value) -> Result<String, EncodeError> {
    Ok(encode(catalog, ty, value)?.canonical())
}

/// Returns the canonical text of `value`, of type `ty`, when it takes at
/// most `max_bytes` bytes, and `None` otherwise.
///
/// The text is measured as the value is encoded, and encoding stops soon
/// after it passes `max_bytes`: a value whose text would be far longer, such
/// as a list holding one long text many times over, costs no more than the
/// bound and the one part that crossed it.
pub fn canonical_within(
    catalog: &Catalog,
    ty: &Type,
    value: &Value,
    max_bytes: usize,
) -> Result<Option<String>, EncodeError> {
    let mut encoder = Encoder::new(catalog, None, Some(max_bytes));
    match encoder.value(ty, value) {
        Ok(json) => {
            let text = json.canonical();
            debug_assert_eq!(
                encoder.room.map(|room| room + text.len()),
                Some(max_bytes),
                "measured exactly"
            );
            Ok(Some(text))
        }
        Err(_) if encoder.over => Ok(None),
        Err(error) => Err(error),
    }
}

/// A SHA-256 hash, written `sha256:` followed by lowercase hex.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Digest(pub [u8; 32]);

impl Digest {
    /// The hash of `bytes`.
    pub fn of(bytes: &[u8]) -> Digest {
        Digest(Sha256::digest(bytes).into())
    }
}

impl fmt::Display for Digest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("sha256:")?;
        self.0.iter().try_for_each(|byte| write!(f, "{byte:02x}"))
    }
}

/// Whether two declarations are one: the same shape, or equal ones.
fn same<T: PartialEq>(a: &Arc<T>, b: &Arc<T>) -> bool {
    Arc::ptr_eq(a, b) || a == b
}

/// How a checkpoint names a task: by the id of its call, given the task and
/// the type of its result.
type Tasks<'c> = &'c mut dyn FnMut(TaskId, &Type) -> Option<String>;

struct Encoder<'c> {
    catalog: &'c Catalog,
    path: Path,
    /// How a checkpoint names a task; `None` outside one.
    tasks: Option<Tasks<'c>>,
    /// How many more bytes the canonical text may take; `None` for no
    /// bound.
    room: Option<usize>,
    /// Whether encoding stopped because the text passed its bound.
    over: bool,
}

impl<'c> Encoder<'c> {
    fn new(catalog: &'c Catalog, tasks: Option<Tasks<'c>>, room: Option<usize>) -> Self {
        Encoder {
            catalog,
            path: Path::default(),
            tasks,
            room,
            over: false,
        }
    }

    /// Counts `bytes` more of canonical text, or stops encoding when they
    /// do not fit.
    fn spend(&mut self, bytes: u128) -> Result<(), EncodeError> {
        let Some(room) = &mut self.room else {
            return Ok(());
        };
        match usize::try_from(bytes) {
            Ok(bytes) if bytes <= *room => {
                *room -= bytes;
                Ok(())
            }
            _ => {
                self.over = true;
                Err(EncodeError::new(
                    &self.path,
                    "has a text longer than its bound",
                ))
            }
        }
    }

    /// `text` as a JSON string.
    fn string(&mut self, text: &str) -> Result<Json, EncodeError> {
        self.spend(quoted_len(text))?;
        Ok(Json::String(text.to_owned()))
    }

    /// `number` as a JSON number.
    fn number(&mut self, number: Decimal) -> Result<Json, EncodeError> {
        self.spend(number.text_len())?;
        Ok(Json::Number(number))
    }

    /// The `[`, `]` and commas of an array of `items` elements, or the `{`,
    /// `}` and commas of an object of `items` members.
    fn brackets(&mut self, items: usize) -> Result<(), EncodeError> {
        self.spend(2 + items.saturating_sub(1) as u128)
    }

    /// The key of an object member and the `:` after it.
    fn key(&mut self, name: &str) -> Result<(), EncodeError> {
        self.spend(quoted_len(name) + 1)
    }
    fn mismatch(&self, ty: &Type) -> EncodeError {
        EncodeError::new(
            &self.path,
            format!("is not a value of {}", self.catalog.name(ty)),
        )
    }

    fn at<T>(
        &mut self,
        step: impl FnOnce(&mut Path),
        go: impl FnOnce(&mut Self) -> Result<T, EncodeError>,
    ) -> Result<T, EncodeError> {
        step(&mut self.path);
        let result = go(self)?;
        self.path.pop();
        Ok(result)
    }

    fn items<'v>(
        &mut self,
        ty: &Type,
        items: impl Iterator<Item = &'v Value>,
    ) -> Result<Json, EncodeError> {
        let items = items
            .enumerate()
            .map(|(index, item)| self.at(|path| path.index(index), |me| me.value(ty, item)))
            .collect::<Result<Vec<_>, _>>()?;
        self.brackets(items.len())?;
        Ok(Json::Array(items))
    }

    fn value(&mut self, ty: &Type, value: &Value) -> Result<Json, EncodeError> {
        let json = match (ty, value) {
            (Type::Int, Value::Int(number)) => self.number(Decimal::from(number))?,
            (Type::Decimal, Value::Decimal(number)) => self.number(number.clone())?,
            (Type::Bool, Value::Bool(flag)) => self.boolean(*flag)?,
            (Type::Text, Value::Text(text)) => self.string(text.as_str())?,
            (Type::Bytes, Value::Bytes(bytes)) => self.string(&bytes.to_base64())?,
            (Type::Duration, Value::Duration(span)) => self.string(&span.to_string())?,
            (Type::Instant, Value::Instant(at)) => self.string(&at.to_string())?,
            (Type::Unit, Value::Unit) => {
                self.brackets(0)?;
                Json::Array(Vec::new())
            }
            (Type::Json, Value::Variant(variant))
                if same(variant.shape(), &self.catalog.json().shape) =>
            {
                self.raw(variant)?
            }
            (Type::List(item), Value::List(items)) => self.items(item, items.iter())?,
            (Type::Set(item), Value::Set(items)) => self.items(item, items.iter())?,
            (Type::Dict(key, item), Value::Dict(entries)) => self.dict(ty, key, item, entries)?,
            (Type::Option(item), Value::Variant(variant))
                if same(variant.shape(), &self.catalog.option().shape) =>
            {
                // A value of std's `Option` is `None` or `Some` of one value.
                match variant.payload().first() {
                    None => self.string("None")?,
                    Some(inner) => {
                        self.brackets(1)?;
                        self.key("Some")?;
                        let inner =
                            self.at(|path| path.name("Some"), |me| me.value(item, inner))?;
                        Json::Object(vec![("Some".into(), inner)])
                    }
                }
            }
            (Type::Tuple(parts), Value::Tuple(tuple)) if parts.len() == tuple.parts().len() => {
                let items = parts
                    .iter()
                    .zip(tuple.parts())
                    .enumerate()
                    .map(|(index, (part, item))| {
                        self.at(|path| path.index(index), |me| me.value(part, item))
                    })
                    .collect::<Result<Vec<_>, _>>()?;
                self.brackets(items.len())?;
                Json::Array(items)
            }
            (Type::Named(decl, args), _) => self.named(ty, *decl, args, value)?,
            (Type::Task(result), Value::Task(task)) if self.tasks.is_some() => {
                let tasks = self.tasks.as_mut().expect("checked by the guard");
                match tasks(*task, result) {
                    Some(call) => self.string(&call)?,
                    None => {
                        return Err(EncodeError::new(
                            &self.path,
                            "is a task that is not parked on its only call",
                        ));
                    }
                }
            }
            (Type::NotData | Type::Function { .. } | Type::Param(_) | Type::Task(_), _) => {
                return Err(EncodeError::new(&self.path, "has a type with no encoding"));
            }
            _ => return Err(self.mismatch(ty)),
        };
        Ok(json)
    }

    /// A dictionary: an object when its keys are text, and otherwise its
    /// `[key, value]` pairs in ascending key order.
    fn dict(
        &mut self,
        ty: &Type,
        key: &Type,
        item: &Type,
        entries: &Dict,
    ) -> Result<Json, EncodeError> {
        if *key == Type::Text {
            self.brackets(entries.len())?;
            let members = entries
                .iter()
                .map(|(name, entry)| {
                    let Value::Text(name) = name else {
                        return Err(self.mismatch(ty));
                    };
                    let name = name.as_str();
                    self.key(name)?;
                    let json = self.at(|path| path.key(name), |me| me.value(item, entry))?;
                    Ok((name.to_owned(), json))
                })
                .collect::<Result<_, _>>()?;
            return Ok(Json::Object(members));
        }
        self.brackets(entries.len())?;
        let pairs = entries
            .iter()
            .enumerate()
            .map(|(index, (name, entry))| {
                self.at(
                    |path| path.index(index),
                    |me| {
                        me.brackets(2)?;
                        let name = me.at(|path| path.index(0), |me| me.value(key, name))?;
                        let entry = me.at(|path| path.index(1), |me| me.value(item, entry))?;
                        Ok(Json::Array(vec![name, entry]))
                    },
                )
            })
            .collect::<Result<_, _>>()?;
        Ok(Json::Array(pairs))
    }

    /// A value of a declared record, enum or host type.
    fn named(
        &mut self,
        ty: &Type,
        decl: DeclId,
        args: &[Type],
        value: &Value,
    ) -> Result<Json, EncodeError> {
        match (&self.catalog.decl(decl).body, value) {
            (Body::Record(shape, fields), Value::Record(record)) if same(record.shape(), shape) => {
                let names = record.shape().fields();
                let fields = fields.iter().map(|field| field.subst(args));
                self.fields(names.zip(fields).zip(record.fields()))
            }
            (Body::Enum(shape, ctors), Value::Variant(variant)) if same(variant.shape(), shape) => {
                let parts: Vec<Type> = ctors[variant.index()]
                    .iter()
                    .map(|part| part.subst(args))
                    .collect();
                self.variant(variant, &parts)
            }
            (Body::NonData, _) => Err(EncodeError::new(&self.path, "has a type with no encoding")),
            (Body::Host, Value::Host(token)) => self.string(token.as_str()),
            _ => Err(self.mismatch(ty)),
        }
    }

    /// An object of named fields, leaving out each `Option` field that holds
    /// `None` and writing the payload of each that holds `Some`.
    fn fields<'v>(
        &mut self,
        fields: impl Iterator<Item = ((&'v str, Type), &'v Value)>,
    ) -> Result<Json, EncodeError> {
        let mut members = Vec::new();
        for ((name, ty), value) in fields {
            let json = self.at(
                |path| path.name(name),
                |me| match (&ty, value) {
                    (Type::Option(item), Value::Variant(variant))
                        if same(variant.shape(), &me.catalog.option().shape) =>
                    {
                        match variant.payload().first() {
                            None => Ok(None),
                            Some(inner) => me.value(item, inner).map(Some),
                        }
                    }
                    _ => me.value(&ty, value).map(Some),
                },
            )?;
            if let Some(json) = json {
                self.key(name)?;
                members.push((name.to_owned(), json));
            }
        }
        self.brackets(members.len())?;
        Ok(Json::Object(members))
    }

    /// An enum value: its constructor's name, alone or keying its payload.
    fn variant(&mut self, variant: &Variant, parts: &[Type]) -> Result<Json, EncodeError> {
        let ctor = variant.constructor();
        let name = ctor.name();
        let payload = self.at(
            |path| path.name(name),
            |me| match ctor.payload() {
                Payload::None => Ok(None),
                Payload::Positional(1) => me.value(&parts[0], &variant.payload()[0]).map(Some),
                Payload::Positional(_) => {
                    let items = parts
                        .iter()
                        .zip(variant.payload())
                        .enumerate()
                        .map(|(index, (part, item))| {
                            me.at(|path| path.index(index), |me| me.value(part, item))
                        })
                        .collect::<Result<Vec<_>, _>>()?;
                    me.brackets(items.len())?;
                    Ok(Some(Json::Array(items)))
                }
                Payload::Named(names) => {
                    let names = names.iter().map(|name| &**name);
                    let fields = names.zip(parts.iter().cloned()).zip(variant.payload());
                    me.fields(fields).map(Some)
                }
            },
        )?;
        match payload {
            None => self.string(name),
            Some(payload) => {
                self.brackets(1)?;
                self.key(name)?;
                Ok(Json::Object(vec![(name.to_owned(), payload)]))
            }
        }
    }

    /// A `json.Value` as the JSON value it stands for.
    fn raw(&mut self, variant: &Variant) -> Result<Json, EncodeError> {
        // Each constructor of `json.Value` carries a payload of its own kind,
        // so the payload names the constructor.
        let json = match variant.payload() {
            [] => {
                self.spend(4)?;
                Json::Null
            }
            [Value::Bool(value)] => self.boolean(*value)?,
            [Value::Decimal(value)] => self.number(value.clone())?,
            [Value::Text(value)] => self.string(value.as_str())?,
            [Value::List(items)] => self.items(&Type::Json, items.iter())?,
            [value @ Value::Dict(_)] => self.value(&Type::dict(Type::Text, Type::Json), value)?,
            _ => return Err(self.mismatch(&Type::Json)),
        };
        Ok(json)
    }

    /// `flag` as a JSON boolean.
    fn boolean(&mut self, flag: bool) -> Result<Json, EncodeError> {
        self.spend(if flag { 4 } else { 5 })?;
        Ok(Json::Bool(flag))
    }
}

/// How many bytes `text` takes as a canonical JSON string, quotes included
/// (`abi.md`, *The canonical form*).
fn quoted_len(text: &str) -> u128 {
    let escaped: usize = text
        .chars()
        .map(|code_point| match code_point {
            '"' | '\\' | '\u{8}' | '\u{c}' | '\n' | '\r' | '\t' => 2,
            '\u{0}'..='\u{1f}' => 6,
            other => other.len_utf8(),
        })
        .sum();
    escaped as u128 + 2
}