lenso-service 0.1.24

Public contracts for Lenso Providers and Autonomous Services.
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
use lenso_contracts::digest_json;
use schemars::JsonSchema;
use serde::{Deserialize, Deserializer, Serialize, de};
use serde_json::{Value, json};
use std::collections::BTreeSet;
use std::num::NonZeroU32;
use utoipa::ToSchema;

const WORKLOAD_CONTROL_SCALAR_MAX_LENGTH: usize = 255;
const WORKLOAD_CONTROL_SAFE_MESSAGE_MAX_LENGTH: usize = 1_024;

pub const WORKLOAD_CONTROL_PROTOCOL: &str = "lenso.workload-control.v1";
pub const WORKLOAD_CONTROL_OBSERVE_PATH: &str = "/workload-control/v1/observe";
pub const WORKLOAD_CONTROL_OPERATIONS_PATH: &str = "/workload-control/v1/operations";
pub const WORKLOAD_CONTROL_OPERATION_PATH: &str = "/workload-control/v1/operations/{operationId}";

#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema, ToSchema,
)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WorkloadReference {
    pub system_id: String,
    pub service_id: String,
    pub workload_id: String,
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema, ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum WorkloadControlCapability {
    Suspend,
    Resume,
    Restart,
    Scale,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum WorkloadOperationalState {
    Running,
    Suspended,
    Transitioning,
    Failed,
    Unknown,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum WorkloadProtection {
    Controllable,
    ControlPlane,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema, ToSchema)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum WorkloadControlAction {
    Suspend,
    Resume,
    Restart,
    Scale {
        #[serde(rename = "targetCapacity")]
        #[schema(value_type = u32, minimum = 1)]
        target_capacity: NonZeroU32,
    },
}

impl<'de> Deserialize<'de> for WorkloadControlAction {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = Value::deserialize(deserializer)?;
        parse_workload_control_action(&value).map_err(de::Error::custom)
    }
}

fn parse_workload_control_action(value: &Value) -> Result<WorkloadControlAction, &'static str> {
    let object = value
        .as_object()
        .ok_or("Workload Control action must be an object")?;
    let kind = object
        .get("kind")
        .and_then(Value::as_str)
        .ok_or("Workload Control action requires kind")?;
    match kind {
        "suspend" if object.len() == 1 => Ok(WorkloadControlAction::Suspend),
        "resume" if object.len() == 1 => Ok(WorkloadControlAction::Resume),
        "restart" if object.len() == 1 => Ok(WorkloadControlAction::Restart),
        "scale" if object.len() == 2 => {
            let capacity = object
                .get("targetCapacity")
                .and_then(Value::as_u64)
                .and_then(|capacity| u32::try_from(capacity).ok())
                .and_then(NonZeroU32::new)
                .ok_or("Scale requires a positive targetCapacity")?;
            Ok(WorkloadControlAction::Scale {
                target_capacity: capacity,
            })
        }
        "suspend" | "resume" | "restart" | "scale" => {
            Err("Workload Control action contains unknown fields")
        }
        _ => Err("Workload Control action kind is unsupported"),
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum WorkloadControlActorKind {
    Operator,
    Automation,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WorkloadControlActor {
    pub kind: WorkloadControlActorKind,
    pub subject: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WorkloadMutationRequest {
    pub protocol: String,
    pub workload: WorkloadReference,
    pub action: WorkloadControlAction,
    pub observed_revision: String,
    pub idempotency_key: String,
    pub actor: WorkloadControlActor,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum WorkloadControlAuthorityDecision {
    Accepted,
    Denied,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WorkloadControlAuthority {
    pub adapter_id: String,
    pub decision: WorkloadControlAuthorityDecision,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum WorkloadOperationPhase {
    Accepted,
    Executing,
    Verifying,
    Succeeded,
    Failed,
    Denied,
}

impl WorkloadOperationPhase {
    #[must_use]
    pub const fn can_advance_to(self, next: Self) -> bool {
        matches!(
            (self, next),
            (Self::Accepted, Self::Accepted)
                | (
                    Self::Accepted,
                    Self::Executing | Self::Verifying | Self::Succeeded | Self::Failed
                )
                | (Self::Executing, Self::Executing)
                | (
                    Self::Executing,
                    Self::Verifying | Self::Succeeded | Self::Failed
                )
                | (
                    Self::Verifying,
                    Self::Verifying | Self::Succeeded | Self::Failed
                )
                | (Self::Succeeded, Self::Succeeded)
                | (Self::Failed, Self::Failed)
                | (Self::Denied, Self::Denied)
        )
    }

    #[must_use]
    pub const fn is_terminal(self) -> bool {
        matches!(self, Self::Succeeded | Self::Failed | Self::Denied)
    }
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema, ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum WorkloadControlErrorCode {
    Unauthenticated,
    Unauthorized,
    UnsupportedAction,
    ProtectedWorkload,
    StaleRevision,
    ActiveMutation,
    IdempotencyConflict,
    AuthorityUnavailable,
    IncompatibleProtocol,
    WorkloadNotFound,
    OperationNotFound,
    InvalidCapacity,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WorkloadControlFailure {
    pub code: WorkloadControlErrorCode,
    /// Sanitized, provider-neutral text limited to 1,024 Unicode characters.
    pub message: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WorkloadControlError {
    pub protocol: String,
    pub code: WorkloadControlErrorCode,
    /// Sanitized, provider-neutral text limited to 1,024 Unicode characters.
    pub message: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub operation_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub current_revision: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub active_operation: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WorkloadOperationResult {
    pub state: WorkloadOperationalState,
    pub observed_revision: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct OperationRecord {
    pub protocol: String,
    pub operation_id: String,
    pub request: WorkloadMutationRequest,
    pub authority: WorkloadControlAuthority,
    pub phase: WorkloadOperationPhase,
    pub requested_at_unix_ms: u64,
    pub decided_at_unix_ms: u64,
    pub updated_at_unix_ms: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub finished_at_unix_ms: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result: Option<WorkloadOperationResult>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub failure: Option<WorkloadControlFailure>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WorkloadObservation {
    pub protocol: String,
    pub workload: WorkloadReference,
    pub state: WorkloadOperationalState,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observed_revision: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub capabilities: BTreeSet<WorkloadControlCapability>,
    pub protection: WorkloadProtection,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub active_operation: Option<String>,
    pub observed_at_unix_ms: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WorkloadObservationRequest {
    pub protocol: String,
    pub workload: WorkloadReference,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(
    tag = "kind",
    content = "document",
    rename_all = "snake_case",
    deny_unknown_fields
)]
pub enum WorkloadControlMessage {
    ObservationRequest(WorkloadObservationRequest),
    Observation(WorkloadObservation),
    MutationRequest(WorkloadMutationRequest),
    OperationRecord(OperationRecord),
    Error(WorkloadControlError),
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema, ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum WorkloadControlValidationIssueCode {
    InvalidProtocol,
    InvalidWorkloadReference,
    InvalidMutationRequest,
    InvalidOperationRecord,
    InvalidOperationResult,
    InvalidOperationFailure,
    InvalidErrorDocument,
    KnownStateMissingRevision,
    UnknownStateHasRevision,
    AuthorityDecisionMismatch,
    NonMonotonicTimestamps,
    TerminalOutcomeMismatch,
}

#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema, ToSchema,
)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WorkloadControlValidationIssue {
    pub code: WorkloadControlValidationIssueCode,
    pub path: String,
    pub message: String,
    pub next_action: String,
}

#[must_use]
pub fn validate_workload_control_message(
    message: &WorkloadControlMessage,
) -> Vec<WorkloadControlValidationIssue> {
    let mut issues = Vec::new();
    match message {
        WorkloadControlMessage::ObservationRequest(request) => {
            validate_protocol(&request.protocol, "$.document.protocol", &mut issues);
            validate_workload_reference(&request.workload, "$.document.workload", &mut issues);
        }
        WorkloadControlMessage::Observation(observation) => {
            validate_protocol(&observation.protocol, "$.document.protocol", &mut issues);
            validate_workload_reference(&observation.workload, "$.document.workload", &mut issues);
            validate_observation_revision(observation, &mut issues);
        }
        WorkloadControlMessage::MutationRequest(request) => {
            validate_mutation_request(request, "$.document", &mut issues);
        }
        WorkloadControlMessage::OperationRecord(record) => {
            validate_operation_record(record, &mut issues);
        }
        WorkloadControlMessage::Error(error) => {
            validate_error_document(error, &mut issues);
        }
    }
    issues
}

fn validate_protocol(protocol: &str, path: &str, issues: &mut Vec<WorkloadControlValidationIssue>) {
    if protocol != WORKLOAD_CONTROL_PROTOCOL {
        push_validation_issue(
            issues,
            WorkloadControlValidationIssueCode::InvalidProtocol,
            path,
            "protocol does not identify Workload Control v1",
            "Use the exact negotiated Workload Control protocol.",
        );
    }
}

fn validate_workload_reference(
    workload: &WorkloadReference,
    path: &str,
    issues: &mut Vec<WorkloadControlValidationIssue>,
) {
    for (field, value) in [
        ("systemId", workload.system_id.as_str()),
        ("serviceId", workload.service_id.as_str()),
        ("workloadId", workload.workload_id.as_str()),
    ] {
        if !valid_control_scalar(value) {
            push_validation_issue(
                issues,
                WorkloadControlValidationIssueCode::InvalidWorkloadReference,
                &format!("{path}.{field}"),
                "Workload Reference fields must be non-empty stable identities",
                "Use System, Service, and Workload identities declared by the Lenso topology.",
            );
        }
    }
}

fn validate_mutation_request(
    request: &WorkloadMutationRequest,
    path: &str,
    issues: &mut Vec<WorkloadControlValidationIssue>,
) {
    validate_protocol(&request.protocol, &format!("{path}.protocol"), issues);
    validate_workload_reference(&request.workload, &format!("{path}.workload"), issues);
    for (field, value, message) in [
        (
            "observedRevision",
            request.observed_revision.as_str(),
            "mutation requires the authority revision that was observed",
        ),
        (
            "idempotencyKey",
            request.idempotency_key.as_str(),
            "mutation requires a stable idempotency key",
        ),
        (
            "actor.subject",
            request.actor.subject.as_str(),
            "mutation actor requires a stable subject",
        ),
    ] {
        if !valid_control_scalar(value) {
            push_validation_issue(
                issues,
                WorkloadControlValidationIssueCode::InvalidMutationRequest,
                &format!("{path}.{field}"),
                message,
                "Supply the missing authority input before submitting the mutation.",
            );
        }
    }
}

fn validate_observation_revision(
    observation: &WorkloadObservation,
    issues: &mut Vec<WorkloadControlValidationIssue>,
) {
    if observation
        .active_operation
        .as_deref()
        .is_some_and(|operation_id| !valid_control_scalar(operation_id))
    {
        push_validation_issue(
            issues,
            WorkloadControlValidationIssueCode::InvalidOperationRecord,
            "$.document.activeOperation",
            "active operation identity must be non-empty and at most 255 characters when present",
            "Omit an unavailable handle or use the bounded identity assigned by the accepting Adapter.",
        );
    }

    match observation.state {
        WorkloadOperationalState::Unknown if observation.observed_revision.is_some() => {
            push_validation_issue(
                issues,
                WorkloadControlValidationIssueCode::UnknownStateHasRevision,
                "$.document.observedRevision",
                "unknown state cannot carry an observed revision",
                "Remove the revision until the authority supplies current operational state.",
            );
        }
        WorkloadOperationalState::Running
        | WorkloadOperationalState::Suspended
        | WorkloadOperationalState::Transitioning
        | WorkloadOperationalState::Failed
            if observation
                .observed_revision
                .as_deref()
                .is_none_or(|revision| !valid_control_scalar(revision)) =>
        {
            push_validation_issue(
                issues,
                WorkloadControlValidationIssueCode::KnownStateMissingRevision,
                "$.document.observedRevision",
                "known operational state requires the authority's observed revision",
                "Observe the Workload through its active Workload Control Adapter.",
            );
        }
        _ => {}
    }
}

fn validate_operation_record(
    record: &OperationRecord,
    issues: &mut Vec<WorkloadControlValidationIssue>,
) {
    validate_protocol(&record.protocol, "$.document.protocol", issues);
    validate_mutation_request(&record.request, "$.document.request", issues);
    for (path, value) in [
        ("$.document.operationId", record.operation_id.as_str()),
        (
            "$.document.authority.adapterId",
            record.authority.adapter_id.as_str(),
        ),
    ] {
        if !valid_control_scalar(value) {
            push_validation_issue(
                issues,
                WorkloadControlValidationIssueCode::InvalidOperationRecord,
                path,
                "operation identity and Adapter identity must be non-empty and at most 255 characters",
                "Use stable identities assigned by the accepting Adapter.",
            );
        }
    }
    let authority_matches = matches!(
        (record.authority.decision, record.phase),
        (
            WorkloadControlAuthorityDecision::Accepted,
            WorkloadOperationPhase::Accepted
                | WorkloadOperationPhase::Executing
                | WorkloadOperationPhase::Verifying
                | WorkloadOperationPhase::Succeeded
                | WorkloadOperationPhase::Failed
        ) | (
            WorkloadControlAuthorityDecision::Denied,
            WorkloadOperationPhase::Denied
        )
    );
    if !authority_matches {
        push_validation_issue(
            issues,
            WorkloadControlValidationIssueCode::AuthorityDecisionMismatch,
            "$.document.authority.decision",
            "authority decision must agree with the operation phase",
            "Use denied only for an authority denial and accepted for executable operations.",
        );
    }

    let timestamps_are_monotonic = record.requested_at_unix_ms <= record.decided_at_unix_ms
        && record.decided_at_unix_ms <= record.updated_at_unix_ms
        && record
            .finished_at_unix_ms
            .is_none_or(|finished| record.updated_at_unix_ms <= finished);
    if !timestamps_are_monotonic {
        push_validation_issue(
            issues,
            WorkloadControlValidationIssueCode::NonMonotonicTimestamps,
            "$.document",
            "operation timestamps must be monotonic",
            "Preserve request, decision, update, and finish ordering from the Adapter.",
        );
    }

    let outcome_matches = match record.phase {
        WorkloadOperationPhase::Accepted
        | WorkloadOperationPhase::Executing
        | WorkloadOperationPhase::Verifying => {
            record.finished_at_unix_ms.is_none()
                && record.result.is_none()
                && record.failure.is_none()
        }
        WorkloadOperationPhase::Succeeded => {
            record.finished_at_unix_ms.is_some()
                && record.result.is_some()
                && record.failure.is_none()
        }
        WorkloadOperationPhase::Failed | WorkloadOperationPhase::Denied => {
            record.finished_at_unix_ms.is_some()
                && record.result.is_none()
                && record.failure.is_some()
        }
    };
    if !outcome_matches {
        push_validation_issue(
            issues,
            WorkloadControlValidationIssueCode::TerminalOutcomeMismatch,
            "$.document",
            "operation phase, finish timestamp, result, and failure are inconsistent",
            "Use a result only for succeeded and a typed failure only for failed or denied.",
        );
    }

    if record.phase == WorkloadOperationPhase::Succeeded
        && let Some(result) = &record.result
    {
        let is_final_known_state = matches!(
            result.state,
            WorkloadOperationalState::Running | WorkloadOperationalState::Suspended
        );
        if !is_final_known_state {
            push_validation_issue(
                issues,
                WorkloadControlValidationIssueCode::InvalidOperationResult,
                "$.document.result.state",
                "a succeeded operation requires a final known operational state",
                "Use running or suspended only after the Adapter verifies the final state.",
            );
        } else {
            let expected_state = match record.request.action {
                WorkloadControlAction::Suspend => WorkloadOperationalState::Suspended,
                WorkloadControlAction::Resume
                | WorkloadControlAction::Restart
                | WorkloadControlAction::Scale { .. } => WorkloadOperationalState::Running,
            };
            if result.state != expected_state {
                push_validation_issue(
                    issues,
                    WorkloadControlValidationIssueCode::InvalidOperationResult,
                    "$.document.result.state",
                    "the succeeded result state does not match the requested action",
                    "Return suspended for Suspend and running for Resume, Restart, or Scale.",
                );
            }
        }
        if !valid_control_scalar(&result.observed_revision) {
            push_validation_issue(
                issues,
                WorkloadControlValidationIssueCode::InvalidOperationResult,
                "$.document.result.observedRevision",
                "a succeeded operation requires a valid authority revision",
                "Return the non-empty bounded revision observed after verification.",
            );
        }
    }

    if let Some(failure) = &record.failure
        && !valid_safe_message(&failure.message)
    {
        push_validation_issue(
            issues,
            WorkloadControlValidationIssueCode::InvalidOperationFailure,
            "$.document.failure.message",
            "operation failure message must be sanitized, non-empty, and at most 1,024 characters",
            "Return a bounded provider-neutral explanation without secrets or infrastructure identifiers.",
        );
    }
}

fn validate_error_document(
    error: &WorkloadControlError,
    issues: &mut Vec<WorkloadControlValidationIssue>,
) {
    validate_protocol(&error.protocol, "$.document.protocol", issues);
    if !valid_safe_message(&error.message) {
        push_validation_issue(
            issues,
            WorkloadControlValidationIssueCode::InvalidErrorDocument,
            "$.document.message",
            "error message must be sanitized, non-empty, and at most 1,024 characters",
            "Return a bounded provider-neutral explanation without secrets or infrastructure identifiers.",
        );
    }
    for (field, value) in [
        ("operationId", error.operation_id.as_deref()),
        ("currentRevision", error.current_revision.as_deref()),
        ("activeOperation", error.active_operation.as_deref()),
    ] {
        if value.is_some_and(|value| !valid_control_scalar(value)) {
            push_validation_issue(
                issues,
                WorkloadControlValidationIssueCode::InvalidErrorDocument,
                &format!("$.document.{field}"),
                "error references must be non-empty and at most 255 characters when present",
                "Omit unavailable references and use bounded authority identities when present.",
            );
        }
    }
}

fn push_validation_issue(
    issues: &mut Vec<WorkloadControlValidationIssue>,
    code: WorkloadControlValidationIssueCode,
    path: &str,
    message: &str,
    next_action: &str,
) {
    issues.push(WorkloadControlValidationIssue {
        code,
        path: path.to_owned(),
        message: message.to_owned(),
        next_action: next_action.to_owned(),
    });
}

fn valid_control_scalar(value: &str) -> bool {
    !value.trim().is_empty() && value.chars().count() <= WORKLOAD_CONTROL_SCALAR_MAX_LENGTH
}

fn valid_safe_message(value: &str) -> bool {
    !value.trim().is_empty() && value.chars().count() <= WORKLOAD_CONTROL_SAFE_MESSAGE_MAX_LENGTH
}

#[must_use]
pub fn workload_control_schema() -> Value {
    let mut schema = serde_json::to_value(schemars::schema_for!(WorkloadControlMessage))
        .expect("Workload Control schema must serialize");
    schema["$id"] = Value::String(
        "https://contracts.lenso.local/workload-control/lenso.workload-control.v1.schema.json"
            .to_owned(),
    );
    schema["title"] = Value::String("Lenso Workload Control Messages".to_owned());
    for definition in [
        "WorkloadObservationRequest",
        "WorkloadObservation",
        "WorkloadMutationRequest",
        "OperationRecord",
        "WorkloadControlError",
    ] {
        schema["$defs"][definition]["properties"]["protocol"] =
            json!({ "type": "string", "const": WORKLOAD_CONTROL_PROTOCOL });
    }
    for field in ["systemId", "serviceId", "workloadId"] {
        patch_control_scalar(&mut schema, "WorkloadReference", field);
    }
    patch_control_scalar(&mut schema, "WorkloadMutationRequest", "observedRevision");
    patch_control_scalar(&mut schema, "WorkloadMutationRequest", "idempotencyKey");
    patch_control_scalar(&mut schema, "WorkloadControlActor", "subject");
    patch_control_scalar(&mut schema, "WorkloadObservation", "observedRevision");
    patch_control_scalar(&mut schema, "WorkloadObservation", "activeOperation");
    patch_control_scalar(&mut schema, "WorkloadOperationResult", "observedRevision");
    patch_control_scalar(&mut schema, "OperationRecord", "operationId");
    patch_control_scalar(&mut schema, "WorkloadControlAuthority", "adapterId");
    patch_safe_message(&mut schema, "WorkloadControlFailure", "message");
    patch_safe_message(&mut schema, "WorkloadControlError", "message");
    for field in ["operationId", "currentRevision", "activeOperation"] {
        patch_control_scalar(&mut schema, "WorkloadControlError", field);
    }
    schema
}

fn patch_control_scalar(schema: &mut Value, definition: &str, field: &str) {
    schema["$defs"][definition]["properties"][field]["minLength"] = json!(1);
    schema["$defs"][definition]["properties"][field]["maxLength"] =
        json!(WORKLOAD_CONTROL_SCALAR_MAX_LENGTH);
    schema["$defs"][definition]["properties"][field]["pattern"] = json!(r".*\S.*");
}

fn patch_safe_message(schema: &mut Value, definition: &str, field: &str) {
    schema["$defs"][definition]["properties"][field]["minLength"] = json!(1);
    schema["$defs"][definition]["properties"][field]["maxLength"] =
        json!(WORKLOAD_CONTROL_SAFE_MESSAGE_MAX_LENGTH);
    schema["$defs"][definition]["properties"][field]["pattern"] = json!(r".*\S.*");
}

#[must_use]
pub fn workload_control_schema_digest() -> String {
    digest_json(&workload_control_schema()).expect("Workload Control schema must be digestible")
}