Skip to main content

lenso_process_protocol/
authoring.rs

1//! Runtime-neutral Authoring V2 values and validation.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use serde::{Deserialize, Serialize, de::DeserializeOwned};
6use serde_json::Value;
7
8use super::{InvocationExtension, ProtocolError, VALUE_PROFILE};
9
10/// First interoperable Authoring value API.
11pub const AUTHORING_API_VERSION: u32 = 2;
12/// Default maximum encoded frame size.
13pub const DEFAULT_MAX_FRAME_BYTES: u64 = 1_048_576;
14
15/// Decodes one bounded strict Authoring value.
16pub fn decode_frame<T: DeserializeOwned>(
17    wire: &[u8],
18    max_frame_bytes: u64,
19) -> Result<T, ProtocolError> {
20    if u64::try_from(wire.len()).map_or(true, |length| length > max_frame_bytes) {
21        return Err(error("Authoring frame exceeds max_frame_bytes"));
22    }
23    super::decode_strict(wire)
24}
25
26/// Immutable identity of one admitted Plugin generation.
27#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
28#[serde(deny_unknown_fields)]
29pub struct SessionIdentity {
30    pub session: String,
31    pub plugin_instance: String,
32    pub plugin_generation: String,
33    pub artifact_digest: String,
34    pub contract_digest: String,
35    pub runtime_profile: String,
36    pub value_profile: String,
37}
38
39/// Host bounds confirmed during initialization.
40#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
41#[serde(deny_unknown_fields)]
42pub struct AuthoringLimits {
43    pub max_frame_bytes: u64,
44    pub max_active_invocations: u32,
45    pub max_active_outbound_calls: u32,
46    pub max_queued_calls: u32,
47    pub max_unfinished_executions: u32,
48    pub max_retired_ids: u32,
49}
50
51impl AuthoringLimits {
52    #[must_use]
53    pub const fn defaults() -> Self {
54        Self {
55            max_frame_bytes: DEFAULT_MAX_FRAME_BYTES,
56            max_active_invocations: 32,
57            max_active_outbound_calls: 32,
58            max_queued_calls: 32,
59            max_unfinished_executions: 32,
60            max_retired_ids: 1_024,
61        }
62    }
63}
64
65/// Cardinality of one named requirement.
66#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
67#[serde(rename_all = "snake_case")]
68pub enum RequirementCardinality {
69    One,
70    Optional,
71    Many,
72}
73
74/// One source-declared dependency, keyed independently from its Capability.
75#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
76#[serde(deny_unknown_fields)]
77pub struct RequirementDeclaration {
78    pub requirement_id: String,
79    pub capability_id: String,
80    pub descriptor_version: String,
81    pub descriptor_digest: String,
82    pub cardinality: RequirementCardinality,
83}
84
85/// One exact provider selected for a named requirement.
86#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
87#[serde(deny_unknown_fields)]
88pub struct RouteDescriptor {
89    pub route_id: String,
90    pub requirement_id: String,
91    pub capability_id: String,
92    pub descriptor_version: String,
93    pub descriptor_digest: String,
94    pub provider_instance: String,
95    pub provider_order: u32,
96}
97
98/// One endpoint exported by the admitted Plugin instance.
99#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
100#[serde(deny_unknown_fields)]
101pub struct ProvidedEndpoint {
102    pub endpoint_id: String,
103    pub capability_id: String,
104    pub descriptor_version: String,
105    pub descriptor_digest: String,
106}
107
108/// Host-to-runtime initialization value.
109#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
110#[serde(deny_unknown_fields)]
111pub struct InitializeParams {
112    pub api_version: u32,
113    pub identity: SessionIdentity,
114    pub config: Value,
115    pub required_declarations: Vec<RequirementDeclaration>,
116    pub routes: Vec<RouteDescriptor>,
117    pub provided_endpoints: Vec<ProvidedEndpoint>,
118    pub limits: AuthoringLimits,
119}
120
121/// Runtime echo proving that it admitted exactly the Host initialization.
122pub type InitializedResult = InitializeParams;
123
124/// Host-to-runtime factory invocation.
125#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
126#[serde(deny_unknown_fields)]
127pub struct ConstructParams {
128    pub session: String,
129    pub lifecycle_scope_id: String,
130    pub remaining_budget_nanos: String,
131}
132
133/// Result of transferring the constructed object to the runtime.
134#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
135#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
136pub enum FactoryOutcome {
137    Constructed,
138    Failed { detail: String },
139}
140
141#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
142#[serde(deny_unknown_fields)]
143pub struct ConstructedResult {
144    pub session: String,
145    pub lifecycle_scope_id: String,
146    pub outcome: FactoryOutcome,
147}
148
149/// Invocation ancestry and ambient values that outbound calls must preserve.
150#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
151#[serde(deny_unknown_fields)]
152pub struct InvocationScope {
153    pub scope_id: String,
154    pub parent_scope_id: Option<String>,
155    pub remaining_budget_nanos: String,
156    pub permissions: Vec<String>,
157    pub extensions: Vec<InvocationExtension>,
158}
159
160/// Host-to-plugin operation invocation.
161#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
162#[serde(deny_unknown_fields)]
163pub struct InvokeParams {
164    pub session: String,
165    pub correlation_id: String,
166    pub endpoint_id: String,
167    pub capability_id: String,
168    pub descriptor_version: String,
169    pub descriptor_digest: String,
170    pub operation: String,
171    pub scope: InvocationScope,
172    pub payload: Value,
173}
174
175/// Portable operation outcome. It is distinct from execution settlement.
176#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
177#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
178pub enum RuntimeFailure {
179    Unavailable {
180        capability: String,
181    },
182    UnknownOperation {
183        capability: String,
184        operation: String,
185    },
186    AmbiguousBinding {
187        capability: String,
188        providers: u32,
189    },
190    ProtocolViolation {
191        capability: String,
192    },
193    MissingPluginFactory {
194        instance: String,
195        package_id: String,
196    },
197    UnavailableExecutionClass {
198        instance_key: String,
199        execution_class: String,
200    },
201    InvalidResolvedPlan {
202        detail: String,
203    },
204    AdmissionClosed,
205    ResourceExhausted {
206        capability: String,
207        operation: String,
208    },
209    DeadlineExceeded {
210        request_id: String,
211    },
212    Cancelled {
213        request_id: String,
214    },
215    Internal {
216        detail: String,
217    },
218    PluginFailure {
219        detail: String,
220    },
221    PluginRestartExhausted {
222        instance: String,
223        attempts: u32,
224    },
225}
226
227impl RuntimeFailure {
228    pub fn validate(&self) -> Result<(), ProtocolError> {
229        match self {
230            Self::Unavailable { capability } | Self::ProtocolViolation { capability } => {
231                validate_token("capability", capability)
232            }
233            Self::UnknownOperation {
234                capability,
235                operation,
236            }
237            | Self::ResourceExhausted {
238                capability,
239                operation,
240            } => {
241                validate_token("capability", capability)?;
242                validate_token("operation", operation)
243            }
244            Self::AmbiguousBinding {
245                capability,
246                providers,
247            } => {
248                validate_token("capability", capability)?;
249                validate_limit("providers", u64::from(*providers), 1_048_576)
250            }
251            Self::MissingPluginFactory {
252                instance,
253                package_id,
254            } => {
255                validate_token("instance", instance)?;
256                validate_token("package_id", package_id)
257            }
258            Self::UnavailableExecutionClass {
259                instance_key,
260                execution_class,
261            } => {
262                validate_token("instance_key", instance_key)?;
263                validate_token("execution_class", execution_class)
264            }
265            Self::InvalidResolvedPlan { detail }
266            | Self::Internal { detail }
267            | Self::PluginFailure { detail } => validate_detail(detail),
268            Self::AdmissionClosed => Ok(()),
269            Self::DeadlineExceeded { request_id } | Self::Cancelled { request_id } => {
270                validate_decimal("request_id", request_id).map(|_| ())
271            }
272            Self::PluginRestartExhausted { instance, attempts } => {
273                validate_token("instance", instance)?;
274                validate_limit("attempts", u64::from(*attempts), 1_048_576)
275            }
276        }
277    }
278}
279
280#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
281#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
282pub enum InvocationOutcome {
283    Success { value: Value },
284    Domain { error: Value },
285    Runtime { failure: RuntimeFailure },
286}
287
288#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
289#[serde(deny_unknown_fields)]
290pub struct InvocationResult {
291    pub session: String,
292    pub correlation_id: String,
293    pub outcome: InvocationOutcome,
294}
295
296/// Plugin-to-Host call through one exact Plan route.
297#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
298#[serde(deny_unknown_fields)]
299pub struct OutboundCallParams {
300    pub session: String,
301    pub correlation_id: String,
302    pub requirement_id: String,
303    pub route_id: String,
304    pub operation: String,
305    pub scope: InvocationScope,
306    pub payload: Value,
307}
308
309pub type OutboundCallResult = InvocationResult;
310
311/// Cancellation request. Acknowledgement does not imply execution settlement.
312#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
313#[serde(deny_unknown_fields)]
314pub struct CancelParams {
315    pub session: String,
316    pub scope_id: String,
317    pub correlation_id: String,
318    pub reason: String,
319}
320
321#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
322#[serde(deny_unknown_fields)]
323pub struct CancelAck {
324    pub session: String,
325    pub scope_id: String,
326    pub correlation_id: String,
327    pub accepted: bool,
328}
329
330/// Runtime observation that one execution has actually stopped.
331#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
332#[serde(deny_unknown_fields)]
333pub struct Settlement {
334    pub session: String,
335    pub scope_id: String,
336    pub correlation_id: String,
337    pub state: SettlementState,
338}
339
340#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
341#[serde(rename_all = "snake_case")]
342pub enum SettlementState {
343    Completed,
344    Cancelled,
345    Abandoned,
346}
347
348/// Fresh cleanup scope with the remaining shared cleanup budget.
349#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
350#[serde(deny_unknown_fields)]
351pub struct StopParams {
352    pub session: String,
353    pub cleanup_scope_id: String,
354    pub remaining_budget_nanos: String,
355}
356
357#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
358#[serde(deny_unknown_fields)]
359pub struct CleanupDiagnostic {
360    pub code: String,
361    pub detail: String,
362}
363
364#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
365#[serde(deny_unknown_fields)]
366pub struct StoppedResult {
367    pub session: String,
368    pub cleanup_scope_id: String,
369    pub hook: StopHookOutcome,
370    pub diagnostics: Vec<CleanupDiagnostic>,
371}
372
373#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
374#[serde(rename_all = "snake_case")]
375pub enum StopHookOutcome {
376    NotDeclared,
377    Completed,
378    Failed,
379}
380
381impl SessionIdentity {
382    pub fn validate(&self) -> Result<(), ProtocolError> {
383        validate_token("session", &self.session)?;
384        validate_token("plugin_instance", &self.plugin_instance)?;
385        validate_decimal("plugin_generation", &self.plugin_generation)?;
386        validate_digest("artifact_digest", &self.artifact_digest)?;
387        validate_digest("contract_digest", &self.contract_digest)?;
388        validate_token("runtime_profile", &self.runtime_profile)?;
389        if self.value_profile != VALUE_PROFILE {
390            return Err(error("unsupported portable value profile"));
391        }
392        Ok(())
393    }
394}
395
396impl AuthoringLimits {
397    pub fn validate(&self) -> Result<(), ProtocolError> {
398        validate_limit(
399            "max_frame_bytes",
400            self.max_frame_bytes,
401            DEFAULT_MAX_FRAME_BYTES,
402        )?;
403        validate_limit(
404            "max_active_invocations",
405            u64::from(self.max_active_invocations),
406            1_024,
407        )?;
408        validate_limit(
409            "max_active_outbound_calls",
410            u64::from(self.max_active_outbound_calls),
411            1_024,
412        )?;
413        validate_limit("max_queued_calls", u64::from(self.max_queued_calls), 65_536)?;
414        validate_limit(
415            "max_unfinished_executions",
416            u64::from(self.max_unfinished_executions),
417            65_536,
418        )?;
419        validate_limit(
420            "max_retired_ids",
421            u64::from(self.max_retired_ids),
422            1_048_576,
423        )
424    }
425}
426
427impl InitializeParams {
428    /// Validates initialization and exact requirement-to-route bindings.
429    pub fn validate(&self) -> Result<(), ProtocolError> {
430        if self.api_version != AUTHORING_API_VERSION {
431            return Err(error("unsupported Authoring API version"));
432        }
433        self.identity.validate()?;
434        self.limits.validate()?;
435        validate_sorted(
436            &self.required_declarations,
437            |value| &value.requirement_id,
438            "required_declarations",
439        )?;
440        validate_sorted(
441            &self.provided_endpoints,
442            |value| &value.endpoint_id,
443            "provided_endpoints",
444        )?;
445
446        let mut declarations = BTreeMap::new();
447        for declaration in &self.required_declarations {
448            declaration.validate()?;
449            declarations.insert(declaration.requirement_id.as_str(), declaration);
450        }
451        let mut counts = BTreeMap::<&str, usize>::new();
452        let mut next_orders = BTreeMap::<&str, u32>::new();
453        let mut route_ids = BTreeSet::new();
454        let mut providers = BTreeSet::new();
455        let mut previous_route: Option<(&str, u32, &str)> = None;
456        for route in &self.routes {
457            route.validate()?;
458            if !route_ids.insert(route.route_id.as_str()) {
459                return Err(error("route_id must be unique within a session"));
460            }
461            let sort_key = (
462                route.requirement_id.as_str(),
463                route.provider_order,
464                route.provider_instance.as_str(),
465            );
466            if previous_route.is_some_and(|previous| previous >= sort_key) {
467                return Err(error(
468                    "routes must be sorted by requirement_id, provider_order and provider_instance",
469                ));
470            }
471            previous_route = Some(sort_key);
472            let declaration = declarations
473                .get(route.requirement_id.as_str())
474                .ok_or_else(|| error("route references an unknown requirement_id"))?;
475            if route.capability_id != declaration.capability_id
476                || route.descriptor_version != declaration.descriptor_version
477                || route.descriptor_digest != declaration.descriptor_digest
478            {
479                return Err(error(
480                    "route descriptor does not match its named requirement",
481                ));
482            }
483            let expected = next_orders
484                .entry(route.requirement_id.as_str())
485                .or_default();
486            if route.provider_order != *expected {
487                return Err(error(
488                    "requirement routes must use contiguous provider_order values",
489                ));
490            }
491            if !providers.insert((
492                route.requirement_id.as_str(),
493                route.provider_instance.as_str(),
494            )) {
495                return Err(error("one requirement cannot bind the same provider twice"));
496            }
497            *expected += 1;
498            *counts.entry(route.requirement_id.as_str()).or_default() += 1;
499        }
500        for declaration in &self.required_declarations {
501            let count = counts
502                .get(declaration.requirement_id.as_str())
503                .copied()
504                .unwrap_or_default();
505            match declaration.cardinality {
506                RequirementCardinality::One if count != 1 => {
507                    return Err(error("one requirement must bind exactly one route"));
508                }
509                RequirementCardinality::Optional if count > 1 => {
510                    return Err(error("optional requirement may bind at most one route"));
511                }
512                RequirementCardinality::Many
513                | RequirementCardinality::One
514                | RequirementCardinality::Optional => {}
515            }
516        }
517        for endpoint in &self.provided_endpoints {
518            endpoint.validate()?;
519        }
520        Ok(())
521    }
522
523    /// Validates initialization for one exact Adapter-selected runtime profile.
524    pub fn validate_for_runtime_profile(&self, expected: &str) -> Result<(), ProtocolError> {
525        self.validate()?;
526        if self.identity.runtime_profile != expected {
527            return Err(error(
528                "runtime profile does not match the selected Adapter profile",
529            ));
530        }
531        Ok(())
532    }
533
534    /// Requires an exact initialized echo; partial admission is forbidden.
535    pub fn validate_initialized(
536        &self,
537        initialized: &InitializedResult,
538    ) -> Result<(), ProtocolError> {
539        initialized.validate()?;
540        if initialized != self {
541            return Err(error(
542                "initialized result does not exactly echo initialization",
543            ));
544        }
545        Ok(())
546    }
547}
548
549impl RequirementDeclaration {
550    fn validate(&self) -> Result<(), ProtocolError> {
551        validate_requirement_id(&self.requirement_id)?;
552        validate_descriptor(
553            &self.capability_id,
554            &self.descriptor_version,
555            &self.descriptor_digest,
556        )
557    }
558}
559
560impl RouteDescriptor {
561    fn validate(&self) -> Result<(), ProtocolError> {
562        validate_token("route_id", &self.route_id)?;
563        validate_requirement_id(&self.requirement_id)?;
564        validate_token("provider_instance", &self.provider_instance)?;
565        validate_descriptor(
566            &self.capability_id,
567            &self.descriptor_version,
568            &self.descriptor_digest,
569        )
570    }
571}
572
573impl ProvidedEndpoint {
574    fn validate(&self) -> Result<(), ProtocolError> {
575        validate_token("endpoint_id", &self.endpoint_id)?;
576        validate_descriptor(
577            &self.capability_id,
578            &self.descriptor_version,
579            &self.descriptor_digest,
580        )
581    }
582}
583
584impl InvocationScope {
585    pub fn validate(&self) -> Result<(), ProtocolError> {
586        validate_token("scope_id", &self.scope_id)?;
587        if let Some(parent) = &self.parent_scope_id {
588            validate_token("parent_scope_id", parent)?;
589        }
590        validate_decimal("remaining_budget_nanos", &self.remaining_budget_nanos)?;
591        validate_sorted_strings(&self.permissions, "permissions")?;
592        let mut keys = BTreeSet::new();
593        for extension in &self.extensions {
594            extension.validate()?;
595            if !keys.insert(extension.key.as_str()) {
596                return Err(error("extensions must be sorted and unique"));
597            }
598        }
599        if self
600            .extensions
601            .windows(2)
602            .any(|pair| pair[0].key >= pair[1].key)
603        {
604            return Err(error("extensions must be sorted and unique"));
605        }
606        Ok(())
607    }
608
609    /// Validates an outbound child scope against its parent invocation.
610    pub fn validate_child_of(&self, parent: &Self) -> Result<(), ProtocolError> {
611        self.validate()?;
612        parent.validate()?;
613        if self.parent_scope_id.as_deref() != Some(parent.scope_id.as_str()) {
614            return Err(error("outbound scope must name its exact parent scope"));
615        }
616        if decimal_value(&self.remaining_budget_nanos)?
617            > decimal_value(&parent.remaining_budget_nanos)?
618        {
619            return Err(error("outbound remaining budget may not increase"));
620        }
621        if self.permissions != parent.permissions || self.extensions != parent.extensions {
622            return Err(error(
623                "outbound scope must preserve permissions and extensions",
624            ));
625        }
626        Ok(())
627    }
628}
629
630impl ConstructParams {
631    pub fn validate_for(&self, identity: &SessionIdentity) -> Result<(), ProtocolError> {
632        validate_session(&self.session, identity)?;
633        validate_token("lifecycle_scope_id", &self.lifecycle_scope_id)?;
634        validate_decimal("remaining_budget_nanos", &self.remaining_budget_nanos).map(|_| ())
635    }
636}
637impl ConstructedResult {
638    pub fn validate_for(&self, request: &ConstructParams) -> Result<(), ProtocolError> {
639        validate_echo(
640            &self.session,
641            &self.lifecycle_scope_id,
642            &request.session,
643            &request.lifecycle_scope_id,
644        )?;
645        if let FactoryOutcome::Failed { detail } = &self.outcome {
646            validate_detail(detail)?;
647        }
648        Ok(())
649    }
650}
651impl InvokeParams {
652    pub fn validate_for(&self, identity: &SessionIdentity) -> Result<(), ProtocolError> {
653        validate_session(&self.session, identity)?;
654        validate_decimal("correlation_id", &self.correlation_id)?;
655        validate_token("endpoint_id", &self.endpoint_id)?;
656        validate_descriptor(
657            &self.capability_id,
658            &self.descriptor_version,
659            &self.descriptor_digest,
660        )?;
661        validate_token("operation", &self.operation)?;
662        self.scope.validate()
663    }
664}
665impl InvokeParams {
666    /// Validates the endpoint identity against the admitted initialization.
667    pub fn validate_against(&self, initialize: &InitializeParams) -> Result<(), ProtocolError> {
668        self.validate_for(&initialize.identity)?;
669        let endpoint = initialize
670            .provided_endpoints
671            .iter()
672            .find(|endpoint| endpoint.endpoint_id == self.endpoint_id)
673            .ok_or_else(|| error("invoke references an unknown endpoint_id"))?;
674        if endpoint.capability_id != self.capability_id
675            || endpoint.descriptor_version != self.descriptor_version
676            || endpoint.descriptor_digest != self.descriptor_digest
677        {
678            return Err(error(
679                "invoke descriptor does not match its admitted endpoint",
680            ));
681        }
682        Ok(())
683    }
684}
685impl InvocationResult {
686    pub fn validate_for(&self, request: &InvokeParams) -> Result<(), ProtocolError> {
687        validate_echo(
688            &self.session,
689            &self.correlation_id,
690            &request.session,
691            &request.correlation_id,
692        )?;
693        if let InvocationOutcome::Runtime { failure } = &self.outcome {
694            failure.validate()?;
695        }
696        Ok(())
697    }
698
699    /// Validates an outbound-call result against its exact request identity.
700    pub fn validate_for_outbound(&self, request: &OutboundCallParams) -> Result<(), ProtocolError> {
701        validate_echo(
702            &self.session,
703            &self.correlation_id,
704            &request.session,
705            &request.correlation_id,
706        )?;
707        if let InvocationOutcome::Runtime { failure } = &self.outcome {
708            failure.validate()?;
709        }
710        Ok(())
711    }
712}
713impl OutboundCallParams {
714    pub fn validate_for(
715        &self,
716        identity: &SessionIdentity,
717        parent: &InvocationScope,
718    ) -> Result<(), ProtocolError> {
719        validate_session(&self.session, identity)?;
720        validate_decimal("correlation_id", &self.correlation_id)?;
721        validate_requirement_id(&self.requirement_id)?;
722        validate_token("route_id", &self.route_id)?;
723        validate_token("operation", &self.operation)?;
724        self.scope.validate_child_of(parent)
725    }
726}
727impl OutboundCallParams {
728    /// Validates the opaque route against this exact session and named requirement.
729    pub fn validate_against(
730        &self,
731        initialize: &InitializeParams,
732        parent: &InvocationScope,
733        parent_active: bool,
734    ) -> Result<(), ProtocolError> {
735        self.validate_for(&initialize.identity, parent)?;
736        if !parent_active {
737            return Err(error("closed parent scope cannot start an outbound call"));
738        }
739        let route = initialize
740            .routes
741            .iter()
742            .find(|route| route.route_id == self.route_id)
743            .ok_or_else(|| error("outbound call references an unknown route_id"))?;
744        if route.requirement_id != self.requirement_id {
745            return Err(error("outbound route belongs to another requirement"));
746        }
747        Ok(())
748    }
749}
750impl CancelParams {
751    pub fn validate_for(&self, identity: &SessionIdentity) -> Result<(), ProtocolError> {
752        validate_session(&self.session, identity)?;
753        validate_token("scope_id", &self.scope_id)?;
754        validate_decimal("correlation_id", &self.correlation_id)?;
755        validate_detail(&self.reason)
756    }
757}
758impl CancelAck {
759    pub fn validate_for(&self, request: &CancelParams) -> Result<(), ProtocolError> {
760        validate_echo(
761            &self.session,
762            &self.scope_id,
763            &request.session,
764            &request.scope_id,
765        )?;
766        if self.correlation_id != request.correlation_id || !self.accepted {
767            return Err(error("cancel acknowledgement mismatch"));
768        }
769        Ok(())
770    }
771}
772impl Settlement {
773    pub fn validate_for(&self, identity: &SessionIdentity) -> Result<(), ProtocolError> {
774        validate_session(&self.session, identity)?;
775        validate_token("scope_id", &self.scope_id)?;
776        validate_decimal("correlation_id", &self.correlation_id).map(|_| ())
777    }
778}
779impl StopParams {
780    pub fn validate_for(&self, identity: &SessionIdentity) -> Result<(), ProtocolError> {
781        validate_session(&self.session, identity)?;
782        validate_token("cleanup_scope_id", &self.cleanup_scope_id)?;
783        validate_decimal("remaining_budget_nanos", &self.remaining_budget_nanos).map(|_| ())
784    }
785}
786impl StoppedResult {
787    pub fn validate_for(&self, request: &StopParams) -> Result<(), ProtocolError> {
788        validate_echo(
789            &self.session,
790            &self.cleanup_scope_id,
791            &request.session,
792            &request.cleanup_scope_id,
793        )?;
794        for diagnostic in &self.diagnostics {
795            validate_token("cleanup diagnostic code", &diagnostic.code)?;
796            validate_detail(&diagnostic.detail)?;
797        }
798        Ok(())
799    }
800}
801
802fn validate_descriptor(capability: &str, version: &str, digest: &str) -> Result<(), ProtocolError> {
803    validate_token("capability_id", capability)?;
804    validate_token("descriptor_version", version)?;
805    validate_digest("descriptor_digest", digest)
806}
807fn validate_session(session: &str, identity: &SessionIdentity) -> Result<(), ProtocolError> {
808    if session != identity.session {
809        return Err(error("message session does not match admitted session"));
810    }
811    Ok(())
812}
813fn validate_echo(
814    session: &str,
815    id: &str,
816    expected_session: &str,
817    expected_id: &str,
818) -> Result<(), ProtocolError> {
819    if session != expected_session || id != expected_id {
820        return Err(error("response identity mismatch"));
821    }
822    Ok(())
823}
824fn validate_detail(value: &str) -> Result<(), ProtocolError> {
825    if value.is_empty() || value.len() > 1_024 {
826        return Err(error("detail must contain 1..=1024 bytes"));
827    }
828    Ok(())
829}
830fn validate_limit(name: &str, value: u64, maximum: u64) -> Result<(), ProtocolError> {
831    if value == 0 || value > maximum {
832        return Err(error(format!("{name} must be within 1..={maximum}")));
833    }
834    Ok(())
835}
836fn validate_token(name: &str, value: &str) -> Result<(), ProtocolError> {
837    if value.is_empty()
838        || value.len() > 256
839        || !value.bytes().all(|byte| {
840            byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b'@' | b'/' | b':')
841        })
842    {
843        return Err(error(format!("{name} must be a portable token")));
844    }
845    Ok(())
846}
847fn validate_requirement_id(value: &str) -> Result<(), ProtocolError> {
848    if value.is_empty()
849        || value.len() > 64
850        || !value.as_bytes()[0].is_ascii_lowercase()
851        || !value
852            .bytes()
853            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
854    {
855        return Err(error("requirement_id must match ^[a-z][a-z0-9_]{0,63}$"));
856    }
857    Ok(())
858}
859fn validate_digest(name: &str, value: &str) -> Result<(), ProtocolError> {
860    let Some(hex) = value.strip_prefix("sha256:") else {
861        return Err(error(format!("{name} must be a canonical SHA-256 digest")));
862    };
863    if hex.len() != 64
864        || !hex
865            .bytes()
866            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
867    {
868        return Err(error(format!("{name} must be a canonical SHA-256 digest")));
869    }
870    Ok(())
871}
872fn validate_decimal(name: &str, value: &str) -> Result<u64, ProtocolError> {
873    if value.is_empty()
874        || (value.len() > 1 && value.starts_with('0'))
875        || !value.bytes().all(|byte| byte.is_ascii_digit())
876    {
877        return Err(error(format!("{name} must be a canonical decimal string")));
878    }
879    decimal_value(value)
880}
881fn decimal_value(value: &str) -> Result<u64, ProtocolError> {
882    value
883        .parse()
884        .map_err(|_| error("decimal string exceeds unsigned 64-bit range"))
885}
886fn validate_sorted<T>(
887    values: &[T],
888    key: impl Fn(&T) -> &str,
889    name: &str,
890) -> Result<(), ProtocolError> {
891    if values.windows(2).any(|pair| key(&pair[0]) >= key(&pair[1])) {
892        return Err(error(format!("{name} must be sorted and unique")));
893    }
894    Ok(())
895}
896fn validate_sorted_strings(values: &[String], name: &str) -> Result<(), ProtocolError> {
897    if values.windows(2).any(|pair| pair[0] >= pair[1]) {
898        return Err(error(format!("{name} must be sorted and unique")));
899    }
900    for value in values {
901        validate_token(name, value)?;
902    }
903    Ok(())
904}
905fn error(detail: impl Into<String>) -> ProtocolError {
906    ProtocolError::new(detail)
907}