flexibility 0.1.0

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, IEC 104 converters.
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! `canon@1`: the canonical text both parties hash, and the digest of it. It is the Open Utility
//! Stack's one digest form (its `contracts/common/digest.md`):
//!
//! - JSON in the RFC 8785 canonical form, restricted to integers, strings, arrays and objects:
//!   keys sorted, no whitespace, strings escaped minimally, no floats anywhere.
//! - Every integer lies within ±2^53, where RFC 8785's number form is exact, so any RFC 8785
//!   library re-encodes the text to the same bytes. A value beyond is refused when the document
//!   is built ([`MAX_EXACT`]), never rounded.
//! - Every document names itself in a `profile` field (`flexibility.settlement@1`,
//!   `flexibility.baseline@1`, …), so the same bytes are never two kinds of document.
//! - A [`Digest`] is written `sha256:` and 64 lowercase hex digits.
//!
//! Anyone can recompute one with a standard SHA-256 tool:
//!
//! ```text
//! printf 'sha256:%s\n' "$(printf '%s' "$CANONICAL" | shasum -a 256 | cut -d' ' -f1)"
//! ```

use std::collections::BTreeMap;
use std::fmt::{self, Write as _};
use std::str::FromStr;

use sha2::{Digest as _, Sha256};

use crate::{Deviation, Error, Grid, Power, Provenance, Series, Window};

/// The largest integer magnitude in a canonical text, 2^53: RFC 8785 writes numbers as IEEE
/// doubles, which are exact up to here. An energy total of 2^53 watt-seconds is about 2.5 TWh.
pub const MAX_EXACT: i128 = 1 << 53;

/// The profile of a document this crate writes: `flexibility.<kind>@1`.
pub(crate) fn profile(kind: &str) -> Value {
    Value::Str(format!("flexibility.{kind}@1"))
}

/// A SHA-256 digest of a canonical text, written `sha256:` and 64 lowercase hex digits.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Digest([u8; 32]);

impl Digest {
    /// The SHA-256 of `bytes`.
    ///
    /// ```
    /// use flexibility::Digest;
    /// assert_eq!(
    ///     Digest::of(b"abc").to_string(),
    ///     "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
    /// );
    /// ```
    #[must_use]
    pub fn of(bytes: &[u8]) -> Digest {
        Digest(Sha256::digest(bytes).into())
    }

    /// The 32 bytes.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }
}

impl fmt::Display for Digest {
    /// `sha256:` and 64 lowercase hex digits.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("sha256:")?;
        for b in self.0 {
            write!(f, "{b:02x}")?;
        }
        Ok(())
    }
}

impl FromStr for Digest {
    type Err = Error;

    /// `sha256:` and 64 hex digits, either case.
    fn from_str(text: &str) -> Result<Digest, Error> {
        let bad = || Error::ParseDigest {
            text: text.chars().take(80).collect(),
        };
        let b = text.strip_prefix("sha256:").ok_or_else(bad)?.as_bytes();
        if b.len() != 64 {
            return Err(bad());
        }
        let mut out = [0u8; 32];
        for (i, pair) in b.as_chunks::<2>().0.iter().enumerate() {
            let hi = hex(pair[0]).ok_or_else(bad)?;
            let lo = hex(pair[1]).ok_or_else(bad)?;
            out[i] = hi << 4 | lo;
        }
        Ok(Digest(out))
    }
}

fn hex(c: u8) -> Option<u8> {
    match c {
        b'0'..=b'9' => Some(c - b'0'),
        b'a'..=b'f' => Some(c - b'a' + 10),
        b'A'..=b'F' => Some(c - b'A' + 10),
        _ => None,
    }
}

/// A canonical value: the only shapes `canon@1` has.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Value {
    Int(i128),
    Str(String),
    Arr(Vec<Value>),
    Obj(BTreeMap<&'static str, Value>),
}

impl Value {
    pub(crate) fn obj<const N: usize>(entries: [(&'static str, Value); N]) -> Value {
        Value::Obj(entries.into_iter().collect())
    }

    pub(crate) fn str(s: impl fmt::Display) -> Value {
        Value::Str(s.to_string())
    }

    pub(crate) fn int(i: impl Into<i128>) -> Value {
        Value::Int(i.into())
    }

    /// The canonical text.
    pub(crate) fn text(&self) -> String {
        let mut out = String::new();
        self.write(&mut out);
        out
    }

    pub(crate) fn digest(&self) -> Digest {
        Digest::of(self.text().as_bytes())
    }

    /// The value, refused if an integer in it lies beyond ±[`MAX_EXACT`]. Every document is
    /// checked once, when it is built; its text and digest are then infallible.
    pub(crate) fn exact(self) -> Result<Value, Error> {
        self.check("value")?;
        Ok(self)
    }

    fn check(&self, field: &'static str) -> Result<(), Error> {
        match self {
            Value::Int(i) if i.unsigned_abs() > MAX_EXACT.unsigned_abs() => {
                Err(Error::Unrepresentable {
                    protocol: CANON,
                    field,
                    value: i.to_string(),
                    reason: "is beyond ±2^53, where an RFC 8785 number is exact",
                })
            }
            Value::Int(_) | Value::Str(_) => Ok(()),
            Value::Arr(items) => items.iter().try_for_each(|v| v.check(field)),
            Value::Obj(map) => map.iter().try_for_each(|(k, v)| v.check(k)),
        }
    }

    fn write(&self, out: &mut String) {
        match self {
            Value::Int(i) => {
                let _ = write!(out, "{i}");
            }
            Value::Str(s) => write_string(out, s),
            Value::Arr(items) => {
                out.push('[');
                for (i, v) in items.iter().enumerate() {
                    if i > 0 {
                        out.push(',');
                    }
                    v.write(out);
                }
                out.push(']');
            }
            Value::Obj(map) => {
                // Keys are static ASCII, so byte order equals RFC 8785's UTF-16 order.
                out.push('{');
                for (i, (k, v)) in map.iter().enumerate() {
                    if i > 0 {
                        out.push(',');
                    }
                    write_string(out, k);
                    out.push(':');
                    v.write(out);
                }
                out.push('}');
            }
        }
    }
}

/// A JSON string as RFC 8785 writes it: `"` and `\` escaped, the five short control escapes,
/// other control characters as lowercase `\u00xx`, everything else verbatim UTF-8.
fn write_string(out: &mut String, s: &str) {
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\u{8}' => out.push_str("\\b"),
            '\u{c}' => out.push_str("\\f"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => {
                let _ = write!(out, "\\u{:04x}", c as u32);
            }
            c => out.push(c),
        }
    }
    out.push('"');
}

pub(crate) fn grid(g: &Grid) -> Value {
    Value::obj([
        ("count", Value::int(g.count())),
        ("first", Value::int(g.first())),
        ("isp", Value::str(g.isp())),
        ("start", Value::str(g.start())),
    ])
}

pub(crate) fn window(w: Window) -> Value {
    Value::obj([
        ("from", Value::str(w.from())),
        ("until", Value::str(w.until())),
    ])
}

pub(crate) fn provenance(p: &Provenance) -> Value {
    Value::obj([
        ("issued_at", Value::str(p.issued_at())),
        ("issuer", Value::str(p.issuer())),
        ("reference", Value::str(p.reference())),
    ])
}

/// The name of the encoding, in messages.
const CANON: &str = "canon@1";

/// The digest of a power series as an input: its document, `flexibility.power-series@1`.
pub(crate) fn power_input(s: &Series<Power>) -> Result<Digest, Error> {
    Ok(power_document(s).exact()?.digest())
}

/// The digest of a deviation series as an input: `flexibility.deviation-series@1`.
pub(crate) fn deviation_input(s: &Series<Deviation>) -> Result<Digest, Error> {
    let Value::Obj(mut map) = deviations(s) else {
        unreachable!("a series is an object")
    };
    map.insert("profile", profile("deviation-series"));
    Ok(Value::Obj(map).exact()?.digest())
}

fn power_document(s: &Series<Power>) -> Value {
    let Value::Obj(mut map) = powers(s) else {
        unreachable!("a series is an object")
    };
    map.insert("profile", profile("power-series"));
    Value::Obj(map)
}

pub(crate) fn powers(s: &Series<Power>) -> Value {
    Value::obj([
        ("grid", grid(s.grid())),
        (
            "watts",
            Value::Arr(s.values().iter().map(|p| Value::int(p.watts())).collect()),
        ),
    ])
}

pub(crate) fn deviations(s: &Series<Deviation>) -> Value {
    Value::obj([
        ("grid", grid(s.grid())),
        (
            "watts",
            Value::Arr(s.values().iter().map(|d| Value::int(d.watts())).collect()),
        ),
    ])
}

/// The canonical text of a power series, the document whose digest a settlement names as its
/// `actual` input: for callers who want to publish or check one input.
///
/// ```
/// use flexibility::jiff::{Timestamp, tz::TimeZone};
/// use flexibility::{canonical_series, Grid, IspDuration, Power, Series};
/// let grid = Grid::new(Timestamp::UNIX_EPOCH, IspDuration::FIFTEEN_MINUTES, 2, TimeZone::UTC)?;
/// let s = Series::new(grid, vec![Power::from_watts(1), Power::from_watts(-2)])?;
/// assert_eq!(
///     canonical_series(&s)?,
///     r#"{"grid":{"count":2,"first":1,"isp":"PT15M","start":"1970-01-01T00:00:00Z"},"profile":"flexibility.power-series@1","watts":[1,-2]}"#
/// );
/// # Ok::<(), flexibility::Error>(())
/// ```
///
/// # Errors
/// [`Error::Unrepresentable`] for a power beyond ±2^53 W.
pub fn canonical_series(series: &Series<Power>) -> Result<String, Error> {
    Ok(power_document(series).exact()?.text())
}

// --- Reading ---------------------------------------------------------------------------------

/// The largest canonical text [`Settlement::from_canonical`](crate::Settlement::from_canonical)
/// reads: 96 MiB, more than a settlement of [`MAX_ISPS`](crate::MAX_ISPS) lines needs.
pub const MAX_RECEIPT_BYTES: usize = 96 * 1024 * 1024;

/// Nesting deeper than this is refused (a settlement needs 3).
const MAX_DEPTH: usize = 8;

/// The longest integer read: 2^53 has 16 digits, and a sign.
const MAX_INT_CHARS: usize = 17;

/// A value as read from a canonical text. Object members keep their order, so the byte check
/// after reading sees duplicates and order.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Json {
    Int(i128),
    Str(String),
    Arr(Vec<Json>),
    Obj(Vec<(String, Json)>),
}

/// `text` escaped and cut to 64 characters, for an error message.
pub(crate) fn quote(text: &str) -> String {
    let mut out: String = text
        .chars()
        .take(64)
        .flat_map(char::escape_default)
        .collect();
    if text.chars().count() > 64 {
        out.push('…');
    }
    format!("`{out}`")
}

pub(crate) fn refuse(path: &str, reason: impl Into<String>) -> Error {
    Error::Receipt {
        path: path.to_owned(),
        reason: reason.into(),
    }
}

struct Reader<'a> {
    b: &'a [u8],
    i: usize,
}

impl Reader<'_> {
    fn fail(&self, what: &str) -> Error {
        refuse(
            "",
            format!("not canonical {}: {what} at byte {}", CANON, self.i),
        )
    }

    fn eat(&mut self, c: u8) -> Result<(), Error> {
        if self.b.get(self.i) == Some(&c) {
            self.i += 1;
            Ok(())
        } else {
            Err(self.fail(&format!("expected `{}`", c as char)))
        }
    }

    fn value(&mut self, depth: usize) -> Result<Json, Error> {
        if depth > MAX_DEPTH {
            return Err(self.fail("nesting too deep"));
        }
        match self.b.get(self.i) {
            Some(b'{') => {
                self.i += 1;
                let mut members = Vec::new();
                if self.b.get(self.i) == Some(&b'}') {
                    self.i += 1;
                    return Ok(Json::Obj(members));
                }
                loop {
                    let key = self.string()?;
                    self.eat(b':')?;
                    members.push((key, self.value(depth + 1)?));
                    match self.b.get(self.i) {
                        Some(b',') => self.i += 1,
                        Some(b'}') => {
                            self.i += 1;
                            return Ok(Json::Obj(members));
                        }
                        _ => return Err(self.fail("expected `,` or `}`")),
                    }
                }
            }
            Some(b'[') => {
                self.i += 1;
                let mut items = Vec::new();
                if self.b.get(self.i) == Some(&b']') {
                    self.i += 1;
                    return Ok(Json::Arr(items));
                }
                loop {
                    items.push(self.value(depth + 1)?);
                    match self.b.get(self.i) {
                        Some(b',') => self.i += 1,
                        Some(b']') => {
                            self.i += 1;
                            return Ok(Json::Arr(items));
                        }
                        _ => return Err(self.fail("expected `,` or `]`")),
                    }
                }
            }
            Some(b'"') => self.string().map(Json::Str),
            Some(b'-' | b'0'..=b'9') => self.int().map(Json::Int),
            _ => Err(self.fail("expected an object, array, string or integer")),
        }
    }

    fn int(&mut self) -> Result<i128, Error> {
        let start = self.i;
        if self.b.get(self.i) == Some(&b'-') {
            self.i += 1;
        }
        let digits = self.i;
        while self.b.get(self.i).is_some_and(u8::is_ascii_digit) {
            self.i += 1;
            if self.i - start > MAX_INT_CHARS {
                return Err(self.fail("integer too long"));
            }
        }
        let text = std::str::from_utf8(&self.b[start..self.i]).map_err(|_| self.fail("integer"))?;
        let leading_zero = self.b.get(digits) == Some(&b'0') && self.i - digits > 1;
        if self.i == digits || leading_zero || text == "-0" {
            return Err(self.fail("not a canonical integer"));
        }
        let n: i128 = text
            .parse()
            .map_err(|_| self.fail("integer out of range"))?;
        if n.unsigned_abs() > MAX_EXACT.unsigned_abs() {
            return Err(self.fail("integer beyond ±2^53"));
        }
        Ok(n)
    }

    fn string(&mut self) -> Result<String, Error> {
        self.eat(b'"')?;
        let mut out = Vec::new();
        loop {
            match self.b.get(self.i) {
                None => return Err(self.fail("unterminated string")),
                Some(b'"') => {
                    self.i += 1;
                    return String::from_utf8(out).map_err(|_| self.fail("invalid UTF-8"));
                }
                Some(b'\\') => {
                    let c = match self.b.get(self.i + 1) {
                        Some(b'"') => b'"',
                        Some(b'\\') => b'\\',
                        Some(b'b') => 0x08,
                        Some(b'f') => 0x0c,
                        Some(b'n') => b'\n',
                        Some(b'r') => b'\r',
                        Some(b't') => b'\t',
                        Some(b'u') => {
                            let hex4 = self
                                .b
                                .get(self.i + 2..self.i + 6)
                                .ok_or_else(|| self.fail("escape"))?;
                            let v = std::str::from_utf8(hex4)
                                .ok()
                                .and_then(|h| {
                                    u8::from_str_radix(h, 16)
                                        .ok()
                                        .filter(|_| h.starts_with("00"))
                                })
                                .filter(|&v| v < 0x20)
                                .ok_or_else(|| self.fail("an escape canon@1 does not write"))?;
                            self.i += 4;
                            v
                        }
                        _ => return Err(self.fail("an escape canon@1 does not write")),
                    };
                    out.push(c);
                    self.i += 2;
                }
                Some(&c) if c < 0x20 => return Err(self.fail("a raw control character")),
                Some(&c) => {
                    out.push(c);
                    self.i += 1;
                }
            }
        }
    }
}

/// Reads `text` as a `canon@1` value: objects, arrays, integers and canonical strings only, no
/// whitespace, within [`MAX_RECEIPT_BYTES`] and a fixed depth.
pub(crate) fn read(text: &str) -> Result<Json, Error> {
    if text.len() > MAX_RECEIPT_BYTES {
        return Err(refuse(
            "",
            format!("{} bytes is more than {MAX_RECEIPT_BYTES}", text.len()),
        ));
    }
    let mut r = Reader {
        b: text.as_bytes(),
        i: 0,
    };
    let v = r.value(0)?;
    if r.i != r.b.len() {
        return Err(r.fail("trailing bytes"));
    }
    Ok(v)
}

impl Json {
    /// The member `key` of an object at `path`.
    pub(crate) fn get<'a>(&'a self, path: &str, key: &str) -> Result<&'a Json, Error> {
        match self {
            Json::Obj(m) => m
                .iter()
                .find(|(k, _)| k == key)
                .map(|(_, v)| v)
                .ok_or_else(|| refuse(&join(path, key), "missing")),
            _ => Err(refuse(path, "not an object")),
        }
    }

    pub(crate) fn int(&self, path: &str) -> Result<i128, Error> {
        match self {
            Json::Int(i) => Ok(*i),
            _ => Err(refuse(path, "not an integer")),
        }
    }

    pub(crate) fn str(&self, path: &str) -> Result<&str, Error> {
        match self {
            Json::Str(s) => Ok(s),
            _ => Err(refuse(path, "not a string")),
        }
    }

    pub(crate) fn arr(&self, path: &str) -> Result<&[Json], Error> {
        match self {
            Json::Arr(a) => Ok(a),
            _ => Err(refuse(path, "not an array")),
        }
    }
}

pub(crate) fn join(path: &str, key: &str) -> String {
    if path.is_empty() {
        key.to_owned()
    } else {
        format!("{path}.{key}")
    }
}