harmos-domain 0.1.4

Harmos domain model: identifiers, contracts, catalogs and storage identities.
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
/* ***
 *
 * Harmos
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * ***
 */

/* === Modules === */

/* === Re-Exports === */

/* === Imports === */

// Standard Library Imports
use std::borrow::Cow;
use std::collections::BTreeSet;
use std::time::Duration;
// Third Party Imports
use serde::{Deserialize, Serialize};
// Local Imports
use crate::PREFIX;
use crate::catalog::Node;
use crate::config::SchemaSettings;
use crate::operations::{
    Backoff, Contract, Entry, Jitter, OperationPolicy, ReplaySafety, RestartPolicy, RetryPolicy, Visibility, WireDeclaration, lifecycle,
};
use crate::plugin::{Grant, Requirement};
use crate::schema::declaration::Named;
use crate::schema::graph::Schema;

/* === Constants === */

const ENTRY_LIMIT: usize = 4096;
const GRANT_LIMIT: usize = 256;

/* === Macros === */

/* === Type Aliases === */

/* === Structs === */

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "Decoded")]
pub struct Manifest {
    pub facility: String,
    pub owner: String,
    pub provides: Vec<Contract>,
    pub requires: Vec<Required>,
    pub lifecycle: [lifecycle::Descriptor; 2],
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Required {
    pub contract: Contract,

    #[serde(default)]
    pub grants: Vec<Grant>,
}

#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Identity {
    pub facility: String,
    pub id: String,
    pub version: String,
    pub description: String,
    pub config: String,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Decoded {
    #[serde(default)]
    kind: Option<String>,

    facility: String,
    owner: String,
    provides: Vec<Contract>,
    requires: Vec<Required>,
    lifecycle: [lifecycle::Descriptor; 2],
}

// Inert Artifact Metadata Names Direction Roots Without Repeating Their Fields.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NamedContract {
    pub operation: crate::operations::Definition,
    pub version: u32,
    pub codec: crate::operations::Codec,
    pub request: String,
    pub response: String,

    #[serde(default)]
    pub input: Option<String>,

    #[serde(default)]
    pub output: Option<String>,

    #[serde(default)]
    pub grpc: Option<crate::operations::Grpc>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NamedRequired {
    pub contract: NamedContract,

    #[serde(default)]
    pub grants: Vec<Grant>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NamedManifest {
    pub facility: String,
    pub owner: String,
    pub provides: Vec<NamedContract>,
    pub requires: Vec<NamedRequired>,
    pub lifecycle: [lifecycle::Descriptor; 2],
}

pub(crate) struct Encoder<const N: usize> {
    pub(crate) bytes: [u8; N],
    pub(crate) cursor: usize,
}

/* === Enums === */

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("missing complete {facility} contract inventory for `{owner}`")]
    Missing { facility: String, owner: String },

    #[error("multiple {facility} contract inventories for `{owner}`")]
    Duplicate { facility: String, owner: String },

    #[error("contract inventory exceeds its entry or fragment budget")]
    Budget,

    #[error("contract inventory requires a guest or sidecar facility and a valid artifact owner")]
    Identity,

    #[error("contract inventory has an invalid fragment kind")]
    Kind,

    #[error("requirement `{id}` carries a duplicate or invalid grant")]
    Grant { id: String },

    #[error("duplicate ordinary operation `{id}` in {direction}")]
    OperationDuplicate { direction: &'static str, id: String },

    #[error("invalid ordinary operation metadata: {0}")]
    Operation(#[from] crate::Error),

    #[error("SDK lifecycle inventory must contain initialization then shutdown")]
    LifecycleOrder,

    #[error("invalid SDK lifecycle inventory: {0}")]
    Lifecycle(#[from] lifecycle::Error),

    #[error("invalid shared contract schema: {0}")]
    Schema(#[from] crate::schema::graph::Error),

    #[error("invalid resolved contract: {0}")]
    Contract(#[from] crate::operations::ContractError),

    #[error("invalid contract inventory JSON: {0}")]
    Decode(#[from] serde_json::Error),
}

/* === Traits === */

/* === Implementations === */

impl NamedContract {
    pub fn resolve(self, declarations: &[Named], settings: &mut SchemaSettings) -> Result<Contract, Error> {
        let mut roots = vec![("request", self.request.as_str()), ("response", self.response.as_str())];
        if let Some(input) = &self.input {
            roots.push(("input", input.as_str()));
        }
        if let Some(output) = &self.output {
            roots.push(("output", output.as_str()));
        }
        let schema = Schema::from_named_roots(&roots, declarations, settings)?;
        let schema = super::retain_schema(schema, settings)?;
        Ok(Contract::new(self.operation, self.version, self.codec, schema)?.with_grpc(self.grpc)?)
    }
}

impl NamedManifest {
    pub fn resolve(self, declarations: &[Named], settings: &mut SchemaSettings) -> Result<Manifest, Error> {
        if self.provides.len() > ENTRY_LIMIT || self.requires.len() > ENTRY_LIMIT {
            return Err(Error::Budget);
        }
        let provides = self.provides.into_iter().map(|contract| contract.resolve(declarations, settings)).collect::<Result<_, _>>()?;
        let requires = self
            .requires
            .into_iter()
            .map(|entry| Ok(Required { contract: entry.contract.resolve(declarations, settings)?, grants: entry.grants }))
            .collect::<Result<_, Error>>()?;
        let manifest = Manifest { facility: self.facility, owner: self.owner, provides, requires, lifecycle: self.lifecycle };
        validate(&manifest)?;
        Ok(manifest)
    }
}

impl TryFrom<Decoded> for Manifest {
    type Error = Error;

    fn try_from(value: Decoded) -> Result<Self, Error> {
        if value.kind.as_deref().is_some_and(|kind| kind != "contracts") {
            return Err(Error::Kind);
        }
        let manifest = Self {
            facility: value.facility,
            owner: value.owner,
            provides: value.provides,
            requires: value.requires,
            lifecycle: value.lifecycle,
        };
        validate(&manifest)?;
        Ok(manifest)
    }
}

impl Required {
    pub fn from_tree(entries: &[Node<Requirement>]) -> Result<Vec<Self>, crate::operations::ContractError> {
        let mut required = Vec::with_capacity(crate::catalog::count(entries));
        crate::catalog::try_for_each(entries, |entry| {
            required.push(Self { contract: entry.declaration.contract()?, grants: entry.grants.to_vec() });
            Ok::<(), crate::operations::ContractError>(())
        })?;
        Ok(required)
    }

    pub fn grants(&self, grant: &Grant) -> bool {
        self.grants.contains(grant)
    }
}

impl<const N: usize> Encoder<N> {
    pub(crate) const fn raw(&mut self, bytes: &[u8]) {
        if N == 0 {
            self.cursor += bytes.len();
        } else {
            super::write(&mut self.bytes, &mut self.cursor, bytes);
        }
    }

    pub(crate) const fn quoted(&mut self, value: &str) {
        if N == 0 {
            self.cursor += super::quoted_len(value);
        } else {
            super::quoted(&mut self.bytes, &mut self.cursor, value);
        }
    }

    pub(crate) const fn number(&mut self, value: u64) {
        if N == 0 {
            self.cursor += super::digits(value);
        } else {
            super::number(&mut self.bytes, &mut self.cursor, value);
        }
    }
}

/* === Public Functions === */

pub fn decode(fragment: &[u8]) -> Result<Manifest, Error> {
    if fragment.len() > crate::FRAGMENT_LIMIT {
        return Err(Error::Budget);
    }
    Ok(serde_json::from_slice(fragment)?)
}

pub fn select(manifests: Vec<Manifest>, facility: &str, owner: &str) -> Result<Manifest, Error> {
    let mut matching = manifests.into_iter().filter(|value| value.facility == facility && value.owner == owner);
    let manifest = matching.next().ok_or_else(|| Error::Missing { facility: facility.to_owned(), owner: owner.to_owned() })?;
    if matching.next().is_some() {
        return Err(Error::Duplicate { facility: facility.to_owned(), owner: owner.to_owned() });
    }
    validate(&manifest)?;
    Ok(manifest)
}

pub fn validate(manifest: &Manifest) -> Result<(), Error> {
    if !valid_identity(&manifest.facility, &manifest.owner) {
        return Err(Error::Identity);
    }
    let required = manifest.requires.iter().map(|required| &required.contract);
    for (direction, contracts) in [("provides", manifest.provides.iter().collect::<Vec<_>>()), ("requires", required.collect())] {
        if contracts.len() > ENTRY_LIMIT {
            return Err(Error::Budget);
        }
        let mut ids = BTreeSet::new();
        for contract in contracts {
            contract.operation().validate()?;
            if !ids.insert(&contract.operation().id) {
                return Err(Error::OperationDuplicate { direction, id: contract.operation().id.to_string() });
            }
        }
    }
    let grants = manifest.requires.iter().map(|required| required.grants.len()).sum::<usize>();
    if grants > ENTRY_LIMIT {
        return Err(Error::Budget);
    }
    for required in &manifest.requires {
        let mut seen = BTreeSet::new();
        let operation = &required.contract.operation().id;
        for grant in &required.grants {
            if grant.operation() != operation.as_str()
                || grant.scope().is_none_or(|scope| scope.is_empty() || scope.len() > GRANT_LIMIT)
                || !seen.insert(grant)
            {
                return Err(Error::Grant { id: required.contract.operation().id.to_string() });
            }
        }
    }
    if manifest.lifecycle[0].action() != lifecycle::Action::Initialize || manifest.lifecycle[1].action() != lifecycle::Action::Shutdown {
        return Err(Error::LifecycleOrder);
    }
    Ok(())
}

pub const fn encoded_tree_len(
    facility: &str, owner: &str, provides: &[Node<WireDeclaration>], requires: &[Node<Requirement>], lifecycle: &[OperationPolicy; 2],
) -> usize {
    let size = encoded::<0>(facility, owner, provides, requires, lifecycle).cursor;
    assert!(size - PREFIX.len() - 1 <= crate::FRAGMENT_LIMIT);
    size
}

pub const fn encode_tree<const N: usize>(
    facility: &str, owner: &str, provides: &[Node<WireDeclaration>], requires: &[Node<Requirement>], lifecycle: &[OperationPolicy; 2],
) -> [u8; N] {
    assert!(N == encoded_tree_len(facility, owner, provides, requires, lifecycle));
    encoded::<N>(facility, owner, provides, requires, lifecycle).bytes
}

pub const fn identity_len(facility: &str, id: &str, version: &str, description: &str, config: &str) -> usize {
    let size = encoded_identity::<0>(facility, id, version, description, config).cursor;
    assert!(size - PREFIX.len() - 1 <= crate::FRAGMENT_LIMIT);
    size
}

pub const fn encode_identity<const N: usize>(facility: &str, id: &str, version: &str, description: &str, config: &str) -> [u8; N] {
    assert!(N == identity_len(facility, id, version, description, config));
    encoded_identity::<N>(facility, id, version, description, config).bytes
}

pub(crate) const fn valid_identity(facility: &str, owner: &str) -> bool {
    matches!(facility.as_bytes(), b"guest" | b"sidecar") && crate::artifact_subset(owner)
}

pub(crate) const fn wire<const N: usize>(out: &mut Encoder<N>, entry: &WireDeclaration) {
    out.raw(b"{\"operation\":");
    declaration(out, &entry.operation);
    out.raw(b",\"version\":");
    out.number(entry.version as u64);
    out.raw(b",\"codec\":\"postcard\",\"request\":");
    out.quoted(entry.request.name);
    out.raw(b",\"response\":");
    out.quoted(entry.response.name);
    if let Some(input) = entry.input {
        out.raw(b",\"input\":");
        out.quoted(input.name);
    }
    if let Some(output) = entry.output {
        out.raw(b",\"output\":");
        out.quoted(output.name);
    }
    if let Some(binding) = &entry.grpc {
        out.raw(b",\"grpc\":{\"package\":");
        out.quoted(match &binding.package {
            Cow::Borrowed(value) => value,
            Cow::Owned(_) => panic!("const gRPC package must be borrowed"),
        });
        out.raw(b",\"service\":");
        out.quoted(match &binding.service {
            Cow::Borrowed(value) => value,
            Cow::Owned(_) => panic!("const gRPC service must be borrowed"),
        });
        out.raw(b",\"method\":");
        out.quoted(match &binding.method {
            Cow::Borrowed(value) => value,
            Cow::Owned(_) => panic!("const gRPC method must be borrowed"),
        });
        out.raw(b"}");
    }
    out.raw(b"}");
}

pub(crate) const fn policy<const N: usize>(out: &mut Encoder<N>, value: OperationPolicy) {
    out.raw(b"{\"timeout\":");
    duration(out, value.timeout);
    out.raw(b",\"attempt_timeout\":");
    duration(out, value.attempt_timeout);
    out.raw(b",\"retries\":");
    match value.retries {
        RetryPolicy::Never => out.quoted("never"),
        RetryPolicy::OnTransient { max_retries, backoff: value } => {
            out.raw(b"{\"on_transient\":{\"max_retries\":");
            out.number(max_retries as u64);
            out.raw(b",\"backoff\":");
            backoff(out, value);
            out.raw(b"}}");
        }
    }
    out.raw(b",\"restart\":");
    match value.restart {
        RestartPolicy::Never => out.quoted("never"),
        RestartPolicy::OnTransient { credit, sustained_health, backoff: value } => {
            out.raw(b"{\"on_transient\":{\"credit\":");
            out.number(credit as u64);
            out.raw(b",\"sustained_health\":");
            duration(out, sustained_health);
            out.raw(b",\"backoff\":");
            backoff(out, value);
            out.raw(b"}}");
        }
    }
    out.raw(b"}");
}

/* === Private Functions === */

const fn encoded_identity<const N: usize>(facility: &str, id: &str, version: &str, description: &str, config: &str) -> Encoder<N> {
    assert!(valid_identity(facility, id));
    let mut out = Encoder { bytes: [0; N], cursor: 0 };
    out.raw(PREFIX);
    out.raw(b"{\"kind\":\"plugin\",\"facility\":");
    out.quoted(facility);
    out.raw(b",\"id\":");
    out.quoted(id);
    out.raw(b",\"version\":");
    out.quoted(version);
    out.raw(b",\"description\":");
    out.quoted(description);
    out.raw(b",\"config\":");
    out.quoted(config);
    out.raw(b"}\0");
    out
}

const fn encoded<const N: usize>(
    facility: &str, owner: &str, provides: &[Node<WireDeclaration>], requires: &[Node<Requirement>], lifecycle: &[OperationPolicy; 2],
) -> Encoder<N> {
    assert!(valid_identity(facility, owner));
    assert!(crate::catalog::count(provides) <= ENTRY_LIMIT);
    assert!(crate::catalog::count(requires) <= ENTRY_LIMIT);
    let mut out = Encoder { bytes: [0; N], cursor: 0 };
    out.raw(PREFIX);
    out.raw(b"{\"kind\":\"contracts\",\"facility\":");
    out.quoted(facility);
    out.raw(b",\"owner\":");
    out.quoted(owner);
    out.raw(b",\"provides\":[");
    tree(&mut out, provides, &mut true);
    out.raw(b"],\"requires\":[");
    required(&mut out, requires, &mut true);
    out.raw(b"],\"lifecycle\":[{\"action\":\"initialize\",\"version\":1,\"policy\":");
    policy(&mut out, lifecycle[0]);
    out.raw(b"},{\"action\":\"shutdown\",\"version\":1,\"policy\":");
    policy(&mut out, lifecycle[1]);
    out.raw(b"}]}\0");
    out
}

const fn required<const N: usize>(out: &mut Encoder<N>, entries: &[Node<Requirement>], first: &mut bool) {
    let mut index = 0;
    while index < entries.len() {
        match &entries[index] {
            Node::Leaf(entry) => {
                if !*first {
                    out.raw(b",");
                }
                *first = false;
                out.raw(b"{\"contract\":");
                wire(out, &entry.declaration);
                out.raw(b",\"grants\":[");
                let mut grant = 0;
                while grant < entry.grants.len() {
                    if grant > 0 {
                        out.raw(b",");
                    }
                    let (operation, scope) = entry.grants[grant].borrowed();
                    assert!(
                        super::publications::same_bytes(operation, entry.declaration.operation.id),
                        "a requirement grants only its own operation"
                    );
                    let Some(scope) = scope else {
                        panic!("a requirement grant names its scope");
                    };
                    assert!(!scope.is_empty() && scope.len() <= GRANT_LIMIT, "grant scopes are nonempty and bounded");
                    out.raw(b"{\"operation\":");
                    out.quoted(operation);
                    out.raw(b",\"scope\":");
                    out.quoted(scope);
                    out.raw(b"}");
                    grant += 1;
                }
                out.raw(b"]}");
            }
            Node::Nested(nested) => required(out, nested, first),
        }
        index += 1;
    }
}

const fn tree<const N: usize>(out: &mut Encoder<N>, entries: &[Node<WireDeclaration>], first: &mut bool) {
    let mut index = 0;
    while index < entries.len() {
        match &entries[index] {
            Node::Leaf(entry) => {
                if !*first {
                    out.raw(b",");
                }
                *first = false;
                wire(out, entry);
            }
            Node::Nested(nested) => tree(out, nested, first),
        }
        index += 1;
    }
}

const fn declaration<const N: usize>(out: &mut Encoder<N>, entry: &Entry) {
    out.raw(b"{\"id\":");
    out.quoted(entry.id);
    out.raw(b",\"description\":");
    out.quoted(entry.description);
    out.raw(b",\"policy\":");
    policy(out, entry.policy);
    out.raw(b",\"visibility\":");
    out.quoted(match entry.visibility {
        Visibility::Private => "private",
        Visibility::Shared => "shared",
        Visibility::Host => "host",
    });
    out.raw(b",\"replay\":");
    out.quoted(match entry.replay {
        ReplaySafety::Unknown => "unknown",
        ReplaySafety::Idempotent => "idempotent",
        ReplaySafety::Deduplicated => "deduplicated",
    });
    out.raw(b"}");
}

const fn duration<const N: usize>(out: &mut Encoder<N>, value: Duration) {
    out.raw(b"{\"secs\":");
    out.number(value.as_secs());
    out.raw(b",\"nanos\":");
    out.number(value.subsec_nanos() as u64);
    out.raw(b"}");
}

const fn backoff<const N: usize>(out: &mut Encoder<N>, value: Backoff) {
    let jitter = match value {
        Backoff::Fixed { delay, jitter } => {
            out.raw(b"{\"fixed\":{\"delay\":");
            duration(out, delay);
            jitter
        }
        Backoff::Exponential { initial, maximum, jitter } => {
            out.raw(b"{\"exponential\":{\"initial\":");
            duration(out, initial);
            out.raw(b",\"maximum\":");
            duration(out, maximum);
            jitter
        }
    };
    out.raw(b",\"jitter\":");
    out.quoted(match jitter {
        Jitter::None => "none",
        Jitter::Deterministic => "deterministic",
    });
    out.raw(b"}}");
}

/* === Tests === */