powerio-core 0.10.0

Shared source, diagnostic, module, collection, and output types for PowerIO.
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
use std::collections::BTreeMap;
use std::fmt;

use serde::Deserialize;
use serde_json::Value;

use crate::validation::{valid_nonempty_text, valid_rfc6901_pointer};
use crate::{Error, FormatId};

macro_rules! record_id {
    ($name:ident, $label:literal) => {
        #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub struct $name(Box<str>);

        impl $name {
            pub fn new(value: impl Into<String>) -> Result<Self, Error> {
                let value = value.into();
                if !valid_nonempty_text(&value) {
                    return Err(Error::new(
                        &crate::codes::REQUEST_RECORD_INVALID_IDENTIFIER,
                        concat!($label, " must be nonempty and bounded"),
                    ));
                }
                Ok(Self(value.into_boxed_str()))
            }

            #[must_use]
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str(&self.0)
            }
        }

        impl serde::Serialize for $name {
            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                serializer.serialize_str(&self.0)
            }
        }

        // A stored identifier is validated on the way in, with the byte bound
        // applied before the text is retained, so a malformed document fails
        // at the field rather than reaching a record.
        impl<'de> serde::Deserialize<'de> for $name {
            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                use serde::de::DeserializeSeed;
                let value = crate::bounded::BoundedStr {
                    what: $label,
                    max_bytes: crate::validation::MAX_IDENTIFIER_BYTES,
                }
                .deserialize(deserializer)?;
                Self::new(value).map_err(serde::de::Error::custom)
            }
        }
    };
}

record_id!(SourceId, "source ID");
record_id!(DiagnosticId, "diagnostic ID");
record_id!(HistoryId, "history ID");

/// Program identity recorded with a module.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Producer {
    name: Box<str>,
    version: Box<str>,
}

impl Producer {
    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Result<Self, Error> {
        let name = name.into();
        let version = version.into();
        if !valid_nonempty_text(&name) || !valid_nonempty_text(&version) {
            return Err(Error::new(
                &crate::codes::REQUEST_RECORD_INVALID_IDENTIFIER,
                "producer name and version must be nonempty and bounded",
            ));
        }
        Ok(Self {
            name: name.into_boxed_str(),
            version: version.into_boxed_str(),
        })
    }

    pub(crate) fn powerio() -> Self {
        Self {
            name: "powerio".into(),
            version: env!("CARGO_PKG_VERSION").into(),
        }
    }

    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    #[must_use]
    pub fn version(&self) -> &str {
        &self.version
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DigestAlgorithm {
    Sha256,
}

impl DigestAlgorithm {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Sha256 => "sha256",
        }
    }
}

/// Validated digest attached to a stored source descriptor.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Digest {
    algorithm: DigestAlgorithm,
    value: Box<str>,
}

impl Digest {
    pub fn sha256(value: impl Into<String>) -> Result<Self, Error> {
        let value = value.into();
        if value.len() != 64
            || !value
                .bytes()
                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
        {
            return Err(Error::new(
                &crate::codes::REQUEST_RECORD_INVALID_DIGEST,
                "a SHA-256 digest must contain 64 lowercase hexadecimal characters",
            ));
        }
        Ok(Self {
            algorithm: DigestAlgorithm::Sha256,
            value: value.into_boxed_str(),
        })
    }

    #[must_use]
    pub const fn algorithm(&self) -> DigestAlgorithm {
        self.algorithm
    }

    #[must_use]
    pub fn value(&self) -> &str {
        &self.value
    }
}

/// Durable description of one source buffer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SourceDescriptor {
    id: SourceId,
    name: Box<str>,
    byte_length: u64,
    format: Option<FormatId>,
    digest: Option<Digest>,
}

impl SourceDescriptor {
    pub fn new(id: SourceId, name: impl Into<String>, byte_length: u64) -> Result<Self, Error> {
        let name = name.into();
        if !valid_nonempty_text(&name) {
            return Err(Error::new(
                &crate::codes::REQUEST_RECORD_INVALID_IDENTIFIER,
                "source name must be nonempty and bounded",
            ));
        }
        Ok(Self {
            id,
            name: name.into_boxed_str(),
            byte_length,
            format: None,
            digest: None,
        })
    }

    #[must_use]
    pub fn id(&self) -> &SourceId {
        &self.id
    }

    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    #[must_use]
    pub const fn byte_length(&self) -> u64 {
        self.byte_length
    }

    #[must_use]
    pub const fn format(&self) -> Option<&FormatId> {
        self.format.as_ref()
    }

    #[must_use]
    pub const fn digest(&self) -> Option<&Digest> {
        self.digest.as_ref()
    }

    #[must_use]
    pub fn with_format(mut self, format: FormatId) -> Self {
        self.format = Some(format);
        self
    }

    #[must_use]
    pub fn with_digest(mut self, digest: Digest) -> Self {
        self.digest = Some(digest);
        self
    }
}

/// Half open byte range in one module source.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub struct SourceSpan {
    source: SourceId,
    byte_start: u64,
    byte_end: u64,
}

impl SourceSpan {
    pub fn new(source: SourceId, byte_start: u64, byte_end: u64) -> Result<Self, Error> {
        if byte_start > byte_end {
            return Err(Error::new(
                &crate::codes::REQUEST_RECORD_INVALID_SPAN,
                format!("source span {byte_start}..{byte_end} is reversed"),
            ));
        }
        Ok(Self {
            source,
            byte_start,
            byte_end,
        })
    }

    #[must_use]
    pub fn source(&self) -> &SourceId {
        &self.source
    }

    #[must_use]
    pub const fn byte_start(&self) -> u64 {
        self.byte_start
    }

    #[must_use]
    pub const fn byte_end(&self) -> u64 {
        self.byte_end
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SourceRelation {
    Exact,
    Defaulted,
    Inferred,
    ConvertedUnits,
    Aggregated,
    Split,
    Synthetic,
    Transformed,
    RetainedExtra,
}

impl SourceRelation {
    #[must_use]
    pub const fn allows_empty_spans(self) -> bool {
        matches!(self, Self::Defaulted | Self::Synthetic | Self::Transformed)
    }
}

/// Relation between one typed value target and its source bytes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SourceMapEntry {
    target: Box<str>,
    relation: SourceRelation,
    spans: Vec<SourceSpan>,
}

impl SourceMapEntry {
    pub fn new(
        target: impl Into<String>,
        relation: SourceRelation,
        spans: Vec<SourceSpan>,
    ) -> Result<Self, Error> {
        let target = target.into();
        if !valid_rfc6901_pointer(&target) {
            return Err(Error::new(
                &crate::codes::REQUEST_RECORD_INVALID_POINTER,
                "a source map target must be an RFC 6901 pointer",
            ));
        }
        if spans.is_empty() && !relation.allows_empty_spans() {
            return Err(Error::new(
                &crate::codes::REQUEST_RECORD_INVALID_SPAN,
                "this source relation requires at least one byte span",
            ));
        }
        if spans.len() > crate::validation::MAX_SOURCE_MAP_SPANS {
            return Err(Error::new(
                &crate::codes::REQUEST_RECORD_TOO_LARGE,
                format!(
                    "a source map entry carries more than {} byte spans",
                    crate::validation::MAX_SOURCE_MAP_SPANS
                ),
            ));
        }
        Ok(Self {
            target: target.into_boxed_str(),
            relation,
            spans,
        })
    }

    #[must_use]
    pub fn target(&self) -> &str {
        &self.target
    }

    #[must_use]
    pub const fn relation(&self) -> SourceRelation {
        self.relation
    }

    #[must_use]
    pub fn spans(&self) -> &[SourceSpan] {
        &self.spans
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum HistoryKind {
    Parse,
    Upgrade,
    Transform,
    Edit,
    Repair,
}

/// Structured description of an operation that produced the current value.
#[derive(Clone, Debug, PartialEq)]
pub struct HistoryEntry {
    id: HistoryId,
    kind: HistoryKind,
    name: Box<str>,
    input_kind: Option<Box<str>>,
    output_kind: Option<Box<str>>,
    parameters: BTreeMap<String, Value>,
    assumptions: Vec<String>,
    losses: Vec<String>,
}

impl HistoryEntry {
    pub fn new(id: HistoryId, kind: HistoryKind, name: impl Into<String>) -> Result<Self, Error> {
        let name = name.into();
        if !valid_nonempty_text(&name) {
            return Err(Error::new(
                &crate::codes::REQUEST_RECORD_INVALID_IDENTIFIER,
                "history operation name must be nonempty and bounded",
            ));
        }
        Ok(Self {
            id,
            kind,
            name: name.into_boxed_str(),
            input_kind: None,
            output_kind: None,
            parameters: BTreeMap::new(),
            assumptions: Vec::new(),
            losses: Vec::new(),
        })
    }

    #[must_use]
    pub fn id(&self) -> &HistoryId {
        &self.id
    }

    #[must_use]
    pub const fn kind(&self) -> HistoryKind {
        self.kind
    }

    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    #[must_use]
    pub fn input_kind(&self) -> Option<&str> {
        self.input_kind.as_deref()
    }

    #[must_use]
    pub fn output_kind(&self) -> Option<&str> {
        self.output_kind.as_deref()
    }

    #[must_use]
    pub const fn parameters(&self) -> &BTreeMap<String, Value> {
        &self.parameters
    }

    #[must_use]
    pub fn assumptions(&self) -> &[String] {
        &self.assumptions
    }

    #[must_use]
    pub fn losses(&self) -> &[String] {
        &self.losses
    }

    pub fn with_input_kind(mut self, kind: impl Into<String>) -> Result<Self, Error> {
        self.input_kind = Some(validated_kind(kind.into())?);
        Ok(self)
    }

    pub fn with_output_kind(mut self, kind: impl Into<String>) -> Result<Self, Error> {
        self.output_kind = Some(validated_kind(kind.into())?);
        Ok(self)
    }

    pub fn with_parameters(mut self, parameters: BTreeMap<String, Value>) -> Result<Self, Error> {
        if parameters.len() > crate::validation::MAX_HISTORY_PARAMETERS {
            return Err(history_too_large(
                "parameters",
                crate::validation::MAX_HISTORY_PARAMETERS,
            ));
        }
        if parameters.keys().any(|key| !valid_nonempty_text(key)) {
            return Err(Error::new(
                &crate::codes::REQUEST_RECORD_INVALID_IDENTIFIER,
                "a history parameter key must be nonempty and bounded",
            ));
        }
        self.parameters = parameters;
        Ok(self)
    }

    pub fn with_assumption(mut self, assumption: impl Into<String>) -> Result<Self, Error> {
        self.assumptions = push_history_note(self.assumptions, assumption.into(), "assumptions")?;
        Ok(self)
    }

    pub fn with_loss(mut self, loss: impl Into<String>) -> Result<Self, Error> {
        self.losses = push_history_note(self.losses, loss.into(), "losses")?;
        Ok(self)
    }
}

fn history_too_large(what: &str, limit: usize) -> Error {
    Error::new(
        &crate::codes::REQUEST_RECORD_TOO_LARGE,
        format!("a history entry carries more than {limit} {what}"),
    )
}

fn push_history_note(
    mut notes: Vec<String>,
    note: String,
    what: &'static str,
) -> Result<Vec<String>, Error> {
    if notes.len() >= crate::validation::MAX_HISTORY_NOTES {
        return Err(history_too_large(
            what,
            crate::validation::MAX_HISTORY_NOTES,
        ));
    }
    if !valid_nonempty_text(&note) {
        return Err(Error::new(
            &crate::codes::REQUEST_RECORD_INVALID_IDENTIFIER,
            format!("a history {what} note must be nonempty and bounded"),
        ));
    }
    notes.push(note);
    Ok(notes)
}

fn validated_kind(kind: String) -> Result<Box<str>, Error> {
    if !valid_nonempty_text(&kind) {
        return Err(Error::new(
            &crate::codes::REQUEST_RECORD_INVALID_IDENTIFIER,
            "a history value kind must be nonempty and bounded",
        ));
    }
    Ok(kind.into_boxed_str())
}

impl<'de> serde::Deserialize<'de> for SourceSpan {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        struct Wire {
            source: SourceId,
            byte_start: u64,
            byte_end: u64,
        }
        let wire = Wire::deserialize(deserializer)?;
        Self::new(wire.source, wire.byte_start, wire.byte_end).map_err(serde::de::Error::custom)
    }
}

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

    #[test]
    fn identifiers_and_digests_are_strict() {
        assert!(SourceId::new("").is_err());
        assert!(SourceId::new("x\0y").is_err());
        assert!(SourceId::new("x".repeat(65_537)).is_err());
        assert!(SourceId::new("Case A").is_ok());
        assert!(Digest::sha256("a".repeat(64)).is_ok());
        assert!(Digest::sha256("A".repeat(64)).is_err());
        assert!(Digest::sha256("a".repeat(63)).is_err());
    }

    #[test]
    fn source_map_spans_obey_relation_rules() {
        let id = SourceId::new("input").unwrap();
        assert!(SourceSpan::new(id.clone(), 2, 1).is_err());
        assert!(SourceMapEntry::new("/bus/0", SourceRelation::Exact, Vec::new()).is_err());
        assert!(SourceMapEntry::new("/bus/0", SourceRelation::Defaulted, Vec::new()).is_ok());
        assert!(SourceMapEntry::new("bad", SourceRelation::Synthetic, Vec::new()).is_err());
    }
}