distributed_cli 4.0.0

The `distributed` CLI for Distributed applications: contracts check/accept, scaffold projects, describe manifests, compile clients, and render schema artifacts. Also a library so other CLIs (e.g. hops) can mount its commands.
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
use std::collections::{BTreeMap, BTreeSet};

use crate::client_compiler::manifest::{
    ManifestCommand, ManifestCommandShape, ManifestEffect, ManifestEffectExpression,
    ManifestEffectField, ManifestEffectKey, ManifestEffectRelationship, ManifestField,
    ManifestInputDefault, ManifestModel, ManifestNormalization, ManifestProjectionPreviewSource,
    ManifestTypeField,
};
use crate::client_compiler::ClientCompileError;

use super::support::{command_error, constant_matches};
use super::CommandManifestValidation;

pub(super) fn validate_trusted_preset_inventory(
    command: &ManifestCommand,
) -> Result<(), ClientCompileError> {
    fn expression_names<'a>(expression: &'a ManifestEffectExpression, out: &mut BTreeSet<&'a str>) {
        if let ManifestEffectExpression::TrustedPreset { name } = expression {
            out.insert(name);
        }
    }
    fn key_names<'a>(key: &'a ManifestEffectKey, out: &mut BTreeSet<&'a str>) {
        for field in &key.fields {
            expression_names(&field.value, out);
        }
    }

    let mut referenced = BTreeSet::new();
    if let Some(effects) = &command.extensions.effects {
        for effect in &effects.operations {
            match effect {
                ManifestEffect::Upsert { key, fields, .. }
                | ManifestEffect::Patch { key, fields, .. } => {
                    key_names(key, &mut referenced);
                    for field in fields {
                        expression_names(&field.value, &mut referenced);
                    }
                }
                ManifestEffect::Delete { key, .. } => key_names(key, &mut referenced),
                ManifestEffect::Link { source, target, .. }
                | ManifestEffect::Unlink { source, target, .. } => {
                    key_names(source, &mut referenced);
                    key_names(target, &mut referenced);
                }
                ManifestEffect::InvalidateRelationship { source, .. } => {
                    key_names(source, &mut referenced);
                }
                ManifestEffect::InvalidateModel { .. } => {}
            }
        }
    }
    if let Some(confirmations) = &command.extensions.confirmations {
        for confirmation in &confirmations.expected {
            key_names(&confirmation.key, &mut referenced);
            if let Some(partition) = &confirmation.partition {
                expression_names(partition, &mut referenced);
            }
        }
    }
    if let Some(direct) = &command.extensions.direct_projection {
        if let Some(partition) = &direct.partition {
            expression_names(partition, &mut referenced);
        }
    }
    if let Some(projection) = &command.extensions.projection {
        for occurrence in &projection.preview_occurrences {
            for value in &occurrence.values {
                if let ManifestProjectionPreviewSource::TrustedPreset { name, .. } = &value.source {
                    referenced.insert(name);
                }
            }
        }
    }

    let declared = command
        .extensions
        .trusted_presets
        .iter()
        .map(|descriptor| descriptor.name.as_str())
        .collect::<BTreeSet<_>>();
    if declared != referenced {
        return Err(command_error(
            command,
            "client.manifest.trusted_preset_inventory",
            "trusted_presets must exactly describe every trusted preset expression",
        ));
    }
    Ok(())
}

pub(super) fn validate_defaults(
    command: &ManifestCommand,
    version: u32,
    defaults: &[ManifestInputDefault],
) -> Result<(), ClientCompileError> {
    if version != 1 || defaults.is_empty() {
        return Err(command_error(
            command,
            "client.manifest.input_defaults",
            "input_defaults must be version 1 with at least one entry",
        ));
    }
    let ManifestCommandShape::Object { definition } = &command.input else {
        return Err(command_error(
            command,
            "client.manifest.input_default_path",
            "generated defaults require a typed object input",
        ));
    };
    let mut paths = BTreeSet::new();
    for default in defaults {
        let [field_name] = default.path.as_slice() else {
            return Err(command_error(
                command,
                "client.manifest.input_default_path",
                "generated default must target exactly one top-level input field",
            ));
        };
        if !paths.insert(field_name.as_str()) {
            return Err(command_error(
                command,
                "client.manifest.input_default_path",
                format!("repeats generated default path `{field_name}`"),
            ));
        }
        let field = definition
            .fields
            .iter()
            .find(|field| field.name == *field_name)
            .ok_or_else(|| {
                command_error(
                    command,
                    "client.manifest.input_default_path",
                    format!("generated default references unknown input field `{field_name}`"),
                )
            })?;
        if field.nullable
            || field.list
            || field.nested.is_some()
            || !matches!(field.type_name.as_str(), "String" | "ID")
        {
            return Err(command_error(
                command,
                "client.manifest.input_default_path",
                format!(
                    "generated default `{field_name}` requires a non-null, non-list String/ID field"
                ),
            ));
        }
    }
    Ok(())
}

pub(super) fn validate_effect(
    command: &ManifestCommand,
    effect: &ManifestEffect,
    models: &BTreeMap<String, ManifestModel>,
    report: &mut CommandManifestValidation,
) -> Result<(), ClientCompileError> {
    match effect {
        ManifestEffect::Upsert { model, key, fields }
        | ManifestEffect::Patch { model, key, fields } => {
            let model = addressable_model(command, model, models)?;
            validate_key(command, model, key, false, report)?;
            validate_effect_fields(command, model, fields)
        }
        ManifestEffect::Delete { model, key } => {
            let model = addressable_model(command, model, models)?;
            validate_key(command, model, key, false, report)
        }
        ManifestEffect::Link {
            relationship,
            source,
            target,
        }
        | ManifestEffect::Unlink {
            relationship,
            source,
            target,
        } => {
            let (source_model, target_model) =
                validate_relationship(command, relationship, models)?;
            require_addressable(command, source_model)?;
            require_addressable(command, target_model)?;
            validate_key(command, source_model, source, false, report)?;
            validate_key(command, target_model, target, false, report)
        }
        ManifestEffect::InvalidateModel { model } => {
            require_model(command, model, models).map(|_| ())
        }
        ManifestEffect::InvalidateRelationship {
            relationship,
            source,
        } => {
            let (source_model, _) = validate_relationship(command, relationship, models)?;
            require_addressable(command, source_model)?;
            validate_key(command, source_model, source, false, report)
        }
    }
}

fn validate_effect_fields(
    command: &ManifestCommand,
    model: &ManifestModel,
    fields: &[ManifestEffectField],
) -> Result<(), ClientCompileError> {
    let identity = model
        .identity()
        .expect("effect model addressability checked before field validation");
    let mut names = BTreeSet::new();
    for assignment in fields {
        if !names.insert(assignment.field.as_str()) {
            return Err(command_error(
                command,
                "client.manifest.effect_field",
                format!("effect repeats `{}.{}`", model.id, assignment.field),
            ));
        }
        let field = model.field(&assignment.field).ok_or_else(|| {
            command_error(
                command,
                "client.manifest.effect_field",
                format!(
                    "effect references unknown field `{}.{}`",
                    model.id, assignment.field
                ),
            )
        })?;
        if identity.iter().any(|key| key.name == assignment.field) {
            return Err(command_error(
                command,
                "client.manifest.effect_field",
                format!(
                    "effect cannot assign identity field `{}.{}`",
                    model.id, field.name
                ),
            ));
        }
        validate_expression(command, &assignment.value, field)?;
    }
    Ok(())
}

fn validate_relationship<'a>(
    command: &ManifestCommand,
    relationship: &ManifestEffectRelationship,
    models: &'a BTreeMap<String, ManifestModel>,
) -> Result<(&'a ManifestModel, &'a ManifestModel), ClientCompileError> {
    let source = require_model(command, &relationship.source_model, models)?;
    let declared = source.relationship(&relationship.field).ok_or_else(|| {
        command_error(
            command,
            "client.manifest.effect_relationship",
            format!(
                "effect references unknown relationship `{}.{}`",
                relationship.source_model, relationship.field
            ),
        )
    })?;
    if declared.target_model != relationship.target_model {
        return Err(command_error(
            command,
            "client.manifest.effect_relationship",
            format!(
                "relationship `{}.{}` targets `{}`, not `{}`",
                relationship.source_model,
                relationship.field,
                declared.target_model,
                relationship.target_model
            ),
        ));
    }
    let target = require_model(command, &relationship.target_model, models)?;
    Ok((source, target))
}

pub(super) fn validate_key(
    command: &ManifestCommand,
    model: &ManifestModel,
    key: &ManifestEffectKey,
    allow_embedded: bool,
    report: &mut CommandManifestValidation,
) -> Result<(), ClientCompileError> {
    match &model.normalization {
        ManifestNormalization::Normalized { fields, .. } => {
            let actual = key
                .fields
                .iter()
                .map(|field| field.field.as_str())
                .collect::<Vec<_>>();
            let expected = fields
                .iter()
                .map(|field| field.name.as_str())
                .collect::<Vec<_>>();
            if actual != expected {
                return Err(command_error(
                    command,
                    "client.manifest.effect_key",
                    format!(
                        "key for `{}` must exactly match ordered identity ({})",
                        model.id,
                        expected.join(", ")
                    ),
                ));
            }
        }
        ManifestNormalization::Embedded if allow_embedded => {
            report
                .commands_requiring_revalidation
                .insert(command.name.clone());
            if key.fields.is_empty() {
                return Err(command_error(
                    command,
                    "client.manifest.confirmation_key",
                    format!(
                        "embedded confirmation key for `{}` must not be empty",
                        model.id
                    ),
                ));
            }
            let mut names = BTreeSet::new();
            if key
                .fields
                .iter()
                .any(|field| !names.insert(field.field.as_str()))
            {
                return Err(command_error(
                    command,
                    "client.manifest.confirmation_key",
                    format!(
                        "embedded confirmation key for `{}` repeats a field",
                        model.id
                    ),
                ));
            }
        }
        ManifestNormalization::Embedded => {
            return Err(command_error(
                command,
                "client.manifest.effect_identity",
                format!(
                    "key-addressed effect cannot target embedded model `{}`",
                    model.id
                ),
            ));
        }
    }
    for key_field in &key.fields {
        let field = model.field(&key_field.field).ok_or_else(|| {
            command_error(
                command,
                "client.manifest.effect_key",
                format!(
                    "key for `{}` references unknown field `{}`",
                    model.id, key_field.field
                ),
            )
        })?;
        validate_expression(command, &key_field.value, field)?;
    }
    Ok(())
}

pub(super) fn validate_expression(
    command: &ManifestCommand,
    expression: &ManifestEffectExpression,
    expected: &ManifestField,
) -> Result<(), ClientCompileError> {
    match expression {
        ManifestEffectExpression::Input { path } => {
            let (field, inherited_nullable) = input_field(command, path)?;
            let json_container =
                expected.scalar == "JSON" && (field.list || field.nested.is_some());
            if !json_container
                && (field.list || field.nested.is_some() || field.type_name != expected.scalar)
            {
                return Err(command_error(
                    command,
                    "client.manifest.effect_input_type",
                    format!(
                        "input `{}` cannot populate `{}:{}`",
                        path.join("."),
                        expected.name,
                        expected.scalar
                    ),
                ));
            }
            if (inherited_nullable || field.nullable) && !expected.nullable {
                return Err(command_error(
                    command,
                    "client.manifest.effect_input_nullability",
                    format!(
                        "nullable input `{}` cannot populate non-null field `{}`",
                        path.join("."),
                        expected.name
                    ),
                ));
            }
            Ok(())
        }
        ManifestEffectExpression::TrustedPreset { name } => {
            let descriptor = command
                .extensions
                .trusted_presets
                .iter()
                .find(|descriptor| descriptor.name == *name)
                .ok_or_else(|| {
                    command_error(
                        command,
                        "client.manifest.effect_trusted_preset",
                        format!("uses undeclared trusted preset `{name}`"),
                    )
                })?;
            if descriptor.codec != expected.codec {
                return Err(command_error(
                    command,
                    "client.manifest.effect_trusted_preset",
                    format!(
                        "trusted preset `{name}` codec `{}` cannot populate `{}:{}` with codec `{}`",
                        descriptor.codec,
                        expected.name,
                        expected.scalar,
                        expected.codec
                    ),
                ));
            }
            Ok(())
        }
        ManifestEffectExpression::Constant { value } if constant_matches(value, expected) => Ok(()),
        ManifestEffectExpression::Constant { .. } => Err(command_error(
            command,
            "client.manifest.effect_constant",
            format!(
                "constant is incompatible with field `{}` (`{}`)",
                expected.name, expected.scalar
            ),
        )),
        ManifestEffectExpression::Null if expected.nullable => Ok(()),
        ManifestEffectExpression::Null => Err(command_error(
            command,
            "client.manifest.effect_null",
            format!("null cannot populate non-null field `{}`", expected.name),
        )),
    }
}

fn input_field<'a>(
    command: &'a ManifestCommand,
    path: &[String],
) -> Result<(&'a ManifestTypeField, bool), ClientCompileError> {
    if path.is_empty() {
        return Err(command_error(
            command,
            "client.manifest.effect_input_path",
            "effect input path must not be empty",
        ));
    }
    let ManifestCommandShape::Object { definition } = &command.input else {
        return Err(command_error(
            command,
            "client.manifest.effect_input_path",
            "effect input references require a typed object input",
        ));
    };
    let mut current = definition;
    let mut inherited_nullable = false;
    for (index, segment) in path.iter().enumerate() {
        let field = current
            .fields
            .iter()
            .find(|field| field.name == *segment)
            .ok_or_else(|| {
                command_error(
                    command,
                    "client.manifest.effect_input_path",
                    format!("effect references unknown input path `{}`", path.join(".")),
                )
            })?;
        if index + 1 == path.len() {
            return Ok((field, inherited_nullable));
        }
        if field.list {
            return Err(command_error(
                command,
                "client.manifest.effect_input_path",
                format!(
                    "effect input path `{}` descends through a list",
                    path.join(".")
                ),
            ));
        }
        inherited_nullable |= field.nullable;
        current = field.nested.as_deref().ok_or_else(|| {
            command_error(
                command,
                "client.manifest.effect_input_path",
                format!(
                    "effect input path `{}` descends through a scalar",
                    path.join(".")
                ),
            )
        })?;
    }
    unreachable!("a non-empty path either resolves or returns an error")
}

fn addressable_model<'a>(
    command: &ManifestCommand,
    name: &str,
    models: &'a BTreeMap<String, ManifestModel>,
) -> Result<&'a ManifestModel, ClientCompileError> {
    let model = require_model(command, name, models)?;
    require_addressable(command, model)?;
    Ok(model)
}

fn require_addressable(
    command: &ManifestCommand,
    model: &ManifestModel,
) -> Result<(), ClientCompileError> {
    if model.identity().is_some_and(|fields| !fields.is_empty()) {
        Ok(())
    } else {
        Err(command_error(
            command,
            "client.manifest.effect_identity",
            format!(
                "key-addressed effect cannot target embedded model `{}`",
                model.id
            ),
        ))
    }
}

pub(super) fn require_model<'a>(
    command: &ManifestCommand,
    name: &str,
    models: &'a BTreeMap<String, ManifestModel>,
) -> Result<&'a ManifestModel, ClientCompileError> {
    models.get(name).ok_or_else(|| {
        command_error(
            command,
            "client.manifest.effect_model",
            format!("references unknown model `{name}`"),
        )
    })
}