1use std::collections::{BTreeMap, BTreeSet};
4
5use serde::{Deserialize, Serialize, de::DeserializeOwned};
6use serde_json::Value;
7
8use super::{InvocationExtension, ProtocolError, VALUE_PROFILE};
9
10pub const AUTHORING_API_VERSION: u32 = 2;
12pub const DEFAULT_MAX_FRAME_BYTES: u64 = 1_048_576;
14
15pub 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#[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#[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#[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#[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#[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#[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#[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
121pub type InitializedResult = InitializeParams;
123
124#[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#[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#[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#[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#[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#[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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
313#[serde(deny_unknown_fields)]
314pub struct EventPublishParams {
315 pub session: String,
316 pub correlation_id: String,
317 pub endpoint_id: String,
318 pub capability_id: String,
319 pub descriptor_version: String,
320 pub descriptor_digest: String,
321 pub operation: String,
322 pub scope: InvocationScope,
323 pub event: Value,
324}
325
326#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
328#[serde(deny_unknown_fields)]
329pub struct OutboundEventPublishParams {
330 pub session: String,
331 pub correlation_id: String,
332 pub requirement_id: String,
333 pub route_id: String,
334 pub operation: String,
335 pub scope: InvocationScope,
336 pub event: Value,
337}
338
339#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
341#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
342pub enum EventPublishOutcome {
343 Accepted,
344 Runtime { failure: RuntimeFailure },
345}
346
347#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
348#[serde(deny_unknown_fields)]
349pub struct EventPublishResult {
350 pub session: String,
351 pub correlation_id: String,
352 pub outcome: EventPublishOutcome,
353}
354
355pub type OutboundEventPublishResult = EventPublishResult;
356
357#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
359#[serde(deny_unknown_fields)]
360pub struct StreamOpenParams {
361 pub session: String,
362 pub correlation_id: String,
363 pub endpoint_id: String,
364 pub capability_id: String,
365 pub descriptor_version: String,
366 pub descriptor_digest: String,
367 pub operation: String,
368 pub scope: InvocationScope,
369 pub request: Value,
370}
371
372#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
374#[serde(deny_unknown_fields)]
375pub struct OutboundStreamOpenParams {
376 pub session: String,
377 pub correlation_id: String,
378 pub requirement_id: String,
379 pub route_id: String,
380 pub operation: String,
381 pub scope: InvocationScope,
382 pub request: Value,
383}
384
385#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
387#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
388pub enum StreamOpenOutcome {
389 Opened { stream_id: String },
390 Domain { error: Value },
391 Runtime { failure: RuntimeFailure },
392}
393
394#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
395#[serde(deny_unknown_fields)]
396pub struct StreamOpenResult {
397 pub session: String,
398 pub correlation_id: String,
399 pub outcome: StreamOpenOutcome,
400}
401
402pub type OutboundStreamOpenResult = StreamOpenResult;
403
404#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
406#[serde(deny_unknown_fields)]
407pub struct StreamSendParams {
408 pub session: String,
409 pub correlation_id: String,
410 pub stream_id: String,
411 pub sequence: String,
412 pub message: Value,
413}
414
415#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
417#[serde(deny_unknown_fields)]
418pub struct StreamReceiveParams {
419 pub session: String,
420 pub correlation_id: String,
421 pub stream_id: String,
422}
423
424pub type StreamCloseSendParams = StreamReceiveParams;
426
427pub type StreamCancelParams = StreamReceiveParams;
429
430#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
432#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
433pub enum StreamActionOutcome {
434 Accepted,
435 Runtime { failure: RuntimeFailure },
436}
437
438#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
439#[serde(deny_unknown_fields)]
440pub struct StreamActionResult {
441 pub session: String,
442 pub correlation_id: String,
443 pub stream_id: String,
444 pub outcome: StreamActionOutcome,
445}
446
447#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
449#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
450pub enum StreamTerminalOutcome {
451 Success,
452 Domain { error: Value },
453}
454
455#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
457#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
458pub enum StreamReceiveOutcome {
459 Message { sequence: String, message: Value },
460 PeerHalfClosed,
461 Terminal { outcome: StreamTerminalOutcome },
462 Runtime { failure: RuntimeFailure },
463}
464
465#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
466#[serde(deny_unknown_fields)]
467pub struct StreamReceiveResult {
468 pub session: String,
469 pub correlation_id: String,
470 pub stream_id: String,
471 pub outcome: StreamReceiveOutcome,
472}
473
474#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
476#[serde(deny_unknown_fields)]
477pub struct CancelParams {
478 pub session: String,
479 pub scope_id: String,
480 pub correlation_id: String,
481 pub reason: String,
482}
483
484#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
485#[serde(deny_unknown_fields)]
486pub struct CancelAck {
487 pub session: String,
488 pub scope_id: String,
489 pub correlation_id: String,
490 pub accepted: bool,
491}
492
493#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
495#[serde(deny_unknown_fields)]
496pub struct Settlement {
497 pub session: String,
498 pub scope_id: String,
499 pub correlation_id: String,
500 pub state: SettlementState,
501}
502
503#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
504#[serde(rename_all = "snake_case")]
505pub enum SettlementState {
506 Completed,
507 Cancelled,
508 Abandoned,
509}
510
511#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
513#[serde(deny_unknown_fields)]
514pub struct StopParams {
515 pub session: String,
516 pub cleanup_scope_id: String,
517 pub remaining_budget_nanos: String,
518}
519
520#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
521#[serde(deny_unknown_fields)]
522pub struct CleanupDiagnostic {
523 pub code: String,
524 pub detail: String,
525}
526
527#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
528#[serde(deny_unknown_fields)]
529pub struct StoppedResult {
530 pub session: String,
531 pub cleanup_scope_id: String,
532 pub hook: StopHookOutcome,
533 pub diagnostics: Vec<CleanupDiagnostic>,
534}
535
536#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
537#[serde(rename_all = "snake_case")]
538pub enum StopHookOutcome {
539 NotDeclared,
540 Completed,
541 Failed,
542}
543
544impl SessionIdentity {
545 pub fn validate(&self) -> Result<(), ProtocolError> {
546 validate_token("session", &self.session)?;
547 validate_token("plugin_instance", &self.plugin_instance)?;
548 validate_decimal("plugin_generation", &self.plugin_generation)?;
549 validate_digest("artifact_digest", &self.artifact_digest)?;
550 validate_digest("contract_digest", &self.contract_digest)?;
551 validate_token("runtime_profile", &self.runtime_profile)?;
552 if self.value_profile != VALUE_PROFILE {
553 return Err(error("unsupported portable value profile"));
554 }
555 Ok(())
556 }
557}
558
559impl AuthoringLimits {
560 pub fn validate(&self) -> Result<(), ProtocolError> {
561 validate_limit(
562 "max_frame_bytes",
563 self.max_frame_bytes,
564 DEFAULT_MAX_FRAME_BYTES,
565 )?;
566 validate_limit(
567 "max_active_invocations",
568 u64::from(self.max_active_invocations),
569 1_024,
570 )?;
571 validate_limit(
572 "max_active_outbound_calls",
573 u64::from(self.max_active_outbound_calls),
574 1_024,
575 )?;
576 validate_limit("max_queued_calls", u64::from(self.max_queued_calls), 65_536)?;
577 validate_limit(
578 "max_unfinished_executions",
579 u64::from(self.max_unfinished_executions),
580 65_536,
581 )?;
582 validate_limit(
583 "max_retired_ids",
584 u64::from(self.max_retired_ids),
585 1_048_576,
586 )
587 }
588}
589
590impl InitializeParams {
591 pub fn validate(&self) -> Result<(), ProtocolError> {
593 if self.api_version != AUTHORING_API_VERSION {
594 return Err(error("unsupported Authoring API version"));
595 }
596 self.identity.validate()?;
597 self.limits.validate()?;
598 validate_sorted(
599 &self.required_declarations,
600 |value| &value.requirement_id,
601 "required_declarations",
602 )?;
603 validate_sorted(
604 &self.provided_endpoints,
605 |value| &value.endpoint_id,
606 "provided_endpoints",
607 )?;
608
609 let mut declarations = BTreeMap::new();
610 for declaration in &self.required_declarations {
611 declaration.validate()?;
612 declarations.insert(declaration.requirement_id.as_str(), declaration);
613 }
614 let mut counts = BTreeMap::<&str, usize>::new();
615 let mut next_orders = BTreeMap::<&str, u32>::new();
616 let mut route_ids = BTreeSet::new();
617 let mut providers = BTreeSet::new();
618 let mut previous_route: Option<(&str, u32, &str)> = None;
619 for route in &self.routes {
620 route.validate()?;
621 if !route_ids.insert(route.route_id.as_str()) {
622 return Err(error("route_id must be unique within a session"));
623 }
624 let sort_key = (
625 route.requirement_id.as_str(),
626 route.provider_order,
627 route.provider_instance.as_str(),
628 );
629 if previous_route.is_some_and(|previous| previous >= sort_key) {
630 return Err(error(
631 "routes must be sorted by requirement_id, provider_order and provider_instance",
632 ));
633 }
634 previous_route = Some(sort_key);
635 let declaration = declarations
636 .get(route.requirement_id.as_str())
637 .ok_or_else(|| error("route references an unknown requirement_id"))?;
638 if route.capability_id != declaration.capability_id
639 || route.descriptor_version != declaration.descriptor_version
640 || route.descriptor_digest != declaration.descriptor_digest
641 {
642 return Err(error(
643 "route descriptor does not match its named requirement",
644 ));
645 }
646 let expected = next_orders
647 .entry(route.requirement_id.as_str())
648 .or_default();
649 if route.provider_order != *expected {
650 return Err(error(
651 "requirement routes must use contiguous provider_order values",
652 ));
653 }
654 if !providers.insert((
655 route.requirement_id.as_str(),
656 route.provider_instance.as_str(),
657 )) {
658 return Err(error("one requirement cannot bind the same provider twice"));
659 }
660 *expected += 1;
661 *counts.entry(route.requirement_id.as_str()).or_default() += 1;
662 }
663 for declaration in &self.required_declarations {
664 let count = counts
665 .get(declaration.requirement_id.as_str())
666 .copied()
667 .unwrap_or_default();
668 match declaration.cardinality {
669 RequirementCardinality::One if count != 1 => {
670 return Err(error("one requirement must bind exactly one route"));
671 }
672 RequirementCardinality::Optional if count > 1 => {
673 return Err(error("optional requirement may bind at most one route"));
674 }
675 RequirementCardinality::Many
676 | RequirementCardinality::One
677 | RequirementCardinality::Optional => {}
678 }
679 }
680 for endpoint in &self.provided_endpoints {
681 endpoint.validate()?;
682 }
683 Ok(())
684 }
685
686 pub fn validate_for_runtime_profile(&self, expected: &str) -> Result<(), ProtocolError> {
688 self.validate()?;
689 if self.identity.runtime_profile != expected {
690 return Err(error(
691 "runtime profile does not match the selected Adapter profile",
692 ));
693 }
694 Ok(())
695 }
696
697 pub fn validate_initialized(
699 &self,
700 initialized: &InitializedResult,
701 ) -> Result<(), ProtocolError> {
702 initialized.validate()?;
703 if initialized != self {
704 return Err(error(
705 "initialized result does not exactly echo initialization",
706 ));
707 }
708 Ok(())
709 }
710}
711
712impl RequirementDeclaration {
713 fn validate(&self) -> Result<(), ProtocolError> {
714 validate_requirement_id(&self.requirement_id)?;
715 validate_descriptor(
716 &self.capability_id,
717 &self.descriptor_version,
718 &self.descriptor_digest,
719 )
720 }
721}
722
723impl RouteDescriptor {
724 fn validate(&self) -> Result<(), ProtocolError> {
725 validate_token("route_id", &self.route_id)?;
726 validate_requirement_id(&self.requirement_id)?;
727 validate_token("provider_instance", &self.provider_instance)?;
728 validate_descriptor(
729 &self.capability_id,
730 &self.descriptor_version,
731 &self.descriptor_digest,
732 )
733 }
734}
735
736impl ProvidedEndpoint {
737 fn validate(&self) -> Result<(), ProtocolError> {
738 validate_token("endpoint_id", &self.endpoint_id)?;
739 validate_descriptor(
740 &self.capability_id,
741 &self.descriptor_version,
742 &self.descriptor_digest,
743 )
744 }
745}
746
747impl InvocationScope {
748 pub fn validate(&self) -> Result<(), ProtocolError> {
749 validate_token("scope_id", &self.scope_id)?;
750 if let Some(parent) = &self.parent_scope_id {
751 validate_token("parent_scope_id", parent)?;
752 }
753 validate_decimal("remaining_budget_nanos", &self.remaining_budget_nanos)?;
754 validate_sorted_strings(&self.permissions, "permissions")?;
755 let mut keys = BTreeSet::new();
756 for extension in &self.extensions {
757 extension.validate()?;
758 if !keys.insert(extension.key.as_str()) {
759 return Err(error("extensions must be sorted and unique"));
760 }
761 }
762 if self
763 .extensions
764 .windows(2)
765 .any(|pair| pair[0].key >= pair[1].key)
766 {
767 return Err(error("extensions must be sorted and unique"));
768 }
769 Ok(())
770 }
771
772 pub fn validate_child_of(&self, parent: &Self) -> Result<(), ProtocolError> {
774 self.validate()?;
775 parent.validate()?;
776 if self.parent_scope_id.as_deref() != Some(parent.scope_id.as_str()) {
777 return Err(error("outbound scope must name its exact parent scope"));
778 }
779 if decimal_value(&self.remaining_budget_nanos)?
780 > decimal_value(&parent.remaining_budget_nanos)?
781 {
782 return Err(error("outbound remaining budget may not increase"));
783 }
784 if self.permissions != parent.permissions || self.extensions != parent.extensions {
785 return Err(error(
786 "outbound scope must preserve permissions and extensions",
787 ));
788 }
789 Ok(())
790 }
791}
792
793impl ConstructParams {
794 pub fn validate_for(&self, identity: &SessionIdentity) -> Result<(), ProtocolError> {
795 validate_session(&self.session, identity)?;
796 validate_token("lifecycle_scope_id", &self.lifecycle_scope_id)?;
797 validate_decimal("remaining_budget_nanos", &self.remaining_budget_nanos).map(|_| ())
798 }
799}
800impl ConstructedResult {
801 pub fn validate_for(&self, request: &ConstructParams) -> Result<(), ProtocolError> {
802 validate_echo(
803 &self.session,
804 &self.lifecycle_scope_id,
805 &request.session,
806 &request.lifecycle_scope_id,
807 )?;
808 if let FactoryOutcome::Failed { detail } = &self.outcome {
809 validate_detail(detail)?;
810 }
811 Ok(())
812 }
813}
814impl InvokeParams {
815 pub fn validate_for(&self, identity: &SessionIdentity) -> Result<(), ProtocolError> {
816 validate_session(&self.session, identity)?;
817 validate_decimal("correlation_id", &self.correlation_id)?;
818 validate_token("endpoint_id", &self.endpoint_id)?;
819 validate_descriptor(
820 &self.capability_id,
821 &self.descriptor_version,
822 &self.descriptor_digest,
823 )?;
824 validate_token("operation", &self.operation)?;
825 self.scope.validate()
826 }
827}
828impl InvokeParams {
829 pub fn validate_against(&self, initialize: &InitializeParams) -> Result<(), ProtocolError> {
831 self.validate_for(&initialize.identity)?;
832 let endpoint = initialize
833 .provided_endpoints
834 .iter()
835 .find(|endpoint| endpoint.endpoint_id == self.endpoint_id)
836 .ok_or_else(|| error("invoke references an unknown endpoint_id"))?;
837 if endpoint.capability_id != self.capability_id
838 || endpoint.descriptor_version != self.descriptor_version
839 || endpoint.descriptor_digest != self.descriptor_digest
840 {
841 return Err(error(
842 "invoke descriptor does not match its admitted endpoint",
843 ));
844 }
845 Ok(())
846 }
847}
848impl InvocationResult {
849 pub fn validate_for(&self, request: &InvokeParams) -> Result<(), ProtocolError> {
850 validate_echo(
851 &self.session,
852 &self.correlation_id,
853 &request.session,
854 &request.correlation_id,
855 )?;
856 if let InvocationOutcome::Runtime { failure } = &self.outcome {
857 failure.validate()?;
858 }
859 Ok(())
860 }
861
862 pub fn validate_for_outbound(&self, request: &OutboundCallParams) -> Result<(), ProtocolError> {
864 validate_echo(
865 &self.session,
866 &self.correlation_id,
867 &request.session,
868 &request.correlation_id,
869 )?;
870 if let InvocationOutcome::Runtime { failure } = &self.outcome {
871 failure.validate()?;
872 }
873 Ok(())
874 }
875}
876impl OutboundCallParams {
877 pub fn validate_for(
878 &self,
879 identity: &SessionIdentity,
880 parent: &InvocationScope,
881 ) -> Result<(), ProtocolError> {
882 validate_session(&self.session, identity)?;
883 validate_decimal("correlation_id", &self.correlation_id)?;
884 validate_requirement_id(&self.requirement_id)?;
885 validate_token("route_id", &self.route_id)?;
886 validate_token("operation", &self.operation)?;
887 self.scope.validate_child_of(parent)
888 }
889}
890impl OutboundCallParams {
891 pub fn validate_against(
893 &self,
894 initialize: &InitializeParams,
895 parent: &InvocationScope,
896 parent_active: bool,
897 ) -> Result<(), ProtocolError> {
898 self.validate_for(&initialize.identity, parent)?;
899 if !parent_active {
900 return Err(error("closed parent scope cannot start an outbound call"));
901 }
902 let route = initialize
903 .routes
904 .iter()
905 .find(|route| route.route_id == self.route_id)
906 .ok_or_else(|| error("outbound call references an unknown route_id"))?;
907 if route.requirement_id != self.requirement_id {
908 return Err(error("outbound route belongs to another requirement"));
909 }
910 Ok(())
911 }
912}
913impl EventPublishParams {
914 pub fn validate_against(&self, initialize: &InitializeParams) -> Result<(), ProtocolError> {
915 validate_provided_operation(
916 &self.session,
917 &self.correlation_id,
918 &self.endpoint_id,
919 &self.capability_id,
920 &self.descriptor_version,
921 &self.descriptor_digest,
922 &self.operation,
923 &self.scope,
924 initialize,
925 "event publication",
926 )
927 }
928}
929impl OutboundEventPublishParams {
930 pub fn validate_against(
931 &self,
932 initialize: &InitializeParams,
933 parent: &InvocationScope,
934 parent_active: bool,
935 ) -> Result<(), ProtocolError> {
936 validate_outbound_operation(
937 &self.session,
938 &self.correlation_id,
939 &self.requirement_id,
940 &self.route_id,
941 &self.operation,
942 &self.scope,
943 initialize,
944 parent,
945 parent_active,
946 "event publication",
947 )
948 }
949}
950impl EventPublishResult {
951 pub fn validate_for(&self, request: &EventPublishParams) -> Result<(), ProtocolError> {
952 self.validate_identity(&request.session, &request.correlation_id)
953 }
954
955 pub fn validate_for_outbound(
956 &self,
957 request: &OutboundEventPublishParams,
958 ) -> Result<(), ProtocolError> {
959 self.validate_identity(&request.session, &request.correlation_id)
960 }
961
962 fn validate_identity(&self, session: &str, correlation_id: &str) -> Result<(), ProtocolError> {
963 validate_echo(&self.session, &self.correlation_id, session, correlation_id)?;
964 if let EventPublishOutcome::Runtime { failure } = &self.outcome {
965 failure.validate()?;
966 }
967 Ok(())
968 }
969}
970impl StreamOpenParams {
971 pub fn validate_against(&self, initialize: &InitializeParams) -> Result<(), ProtocolError> {
972 validate_provided_operation(
973 &self.session,
974 &self.correlation_id,
975 &self.endpoint_id,
976 &self.capability_id,
977 &self.descriptor_version,
978 &self.descriptor_digest,
979 &self.operation,
980 &self.scope,
981 initialize,
982 "stream open",
983 )
984 }
985}
986impl OutboundStreamOpenParams {
987 pub fn validate_against(
988 &self,
989 initialize: &InitializeParams,
990 parent: &InvocationScope,
991 parent_active: bool,
992 ) -> Result<(), ProtocolError> {
993 validate_outbound_operation(
994 &self.session,
995 &self.correlation_id,
996 &self.requirement_id,
997 &self.route_id,
998 &self.operation,
999 &self.scope,
1000 initialize,
1001 parent,
1002 parent_active,
1003 "stream open",
1004 )
1005 }
1006}
1007impl StreamOpenResult {
1008 pub fn validate_for(&self, request: &StreamOpenParams) -> Result<(), ProtocolError> {
1009 self.validate_identity(&request.session, &request.correlation_id)
1010 }
1011
1012 pub fn validate_for_outbound(
1013 &self,
1014 request: &OutboundStreamOpenParams,
1015 ) -> Result<(), ProtocolError> {
1016 self.validate_identity(&request.session, &request.correlation_id)
1017 }
1018
1019 fn validate_identity(&self, session: &str, correlation_id: &str) -> Result<(), ProtocolError> {
1020 validate_echo(&self.session, &self.correlation_id, session, correlation_id)?;
1021 match &self.outcome {
1022 StreamOpenOutcome::Opened { stream_id } => {
1023 validate_decimal("stream_id", stream_id).map(|_| ())
1024 }
1025 StreamOpenOutcome::Domain { .. } => Ok(()),
1026 StreamOpenOutcome::Runtime { failure } => failure.validate(),
1027 }
1028 }
1029}
1030impl StreamSendParams {
1031 pub fn validate_for(&self, identity: &SessionIdentity) -> Result<(), ProtocolError> {
1032 validate_stream_action(
1033 &self.session,
1034 &self.correlation_id,
1035 &self.stream_id,
1036 identity,
1037 )?;
1038 validate_decimal("sequence", &self.sequence).map(|_| ())
1039 }
1040}
1041impl StreamReceiveParams {
1042 pub fn validate_for(&self, identity: &SessionIdentity) -> Result<(), ProtocolError> {
1043 validate_stream_action(
1044 &self.session,
1045 &self.correlation_id,
1046 &self.stream_id,
1047 identity,
1048 )
1049 }
1050}
1051impl StreamActionResult {
1052 pub fn validate_for(&self, request: &StreamReceiveParams) -> Result<(), ProtocolError> {
1053 validate_stream_result(
1054 &self.session,
1055 &self.correlation_id,
1056 &self.stream_id,
1057 &request.session,
1058 &request.correlation_id,
1059 &request.stream_id,
1060 )?;
1061 if let StreamActionOutcome::Runtime { failure } = &self.outcome {
1062 failure.validate()?;
1063 }
1064 Ok(())
1065 }
1066
1067 pub fn validate_for_send(&self, request: &StreamSendParams) -> Result<(), ProtocolError> {
1068 validate_stream_result(
1069 &self.session,
1070 &self.correlation_id,
1071 &self.stream_id,
1072 &request.session,
1073 &request.correlation_id,
1074 &request.stream_id,
1075 )?;
1076 if let StreamActionOutcome::Runtime { failure } = &self.outcome {
1077 failure.validate()?;
1078 }
1079 Ok(())
1080 }
1081}
1082impl StreamReceiveResult {
1083 pub fn validate_for(&self, request: &StreamReceiveParams) -> Result<(), ProtocolError> {
1084 validate_stream_result(
1085 &self.session,
1086 &self.correlation_id,
1087 &self.stream_id,
1088 &request.session,
1089 &request.correlation_id,
1090 &request.stream_id,
1091 )?;
1092 match &self.outcome {
1093 StreamReceiveOutcome::Message { sequence, .. } => {
1094 validate_decimal("sequence", sequence).map(|_| ())
1095 }
1096 StreamReceiveOutcome::Runtime { failure } => failure.validate(),
1097 StreamReceiveOutcome::PeerHalfClosed | StreamReceiveOutcome::Terminal { .. } => Ok(()),
1098 }
1099 }
1100}
1101impl CancelParams {
1102 pub fn validate_for(&self, identity: &SessionIdentity) -> Result<(), ProtocolError> {
1103 validate_session(&self.session, identity)?;
1104 validate_token("scope_id", &self.scope_id)?;
1105 validate_decimal("correlation_id", &self.correlation_id)?;
1106 validate_detail(&self.reason)
1107 }
1108}
1109impl CancelAck {
1110 pub fn validate_for(&self, request: &CancelParams) -> Result<(), ProtocolError> {
1111 validate_echo(
1112 &self.session,
1113 &self.scope_id,
1114 &request.session,
1115 &request.scope_id,
1116 )?;
1117 if self.correlation_id != request.correlation_id || !self.accepted {
1118 return Err(error("cancel acknowledgement mismatch"));
1119 }
1120 Ok(())
1121 }
1122}
1123impl Settlement {
1124 pub fn validate_for(&self, identity: &SessionIdentity) -> Result<(), ProtocolError> {
1125 validate_session(&self.session, identity)?;
1126 validate_token("scope_id", &self.scope_id)?;
1127 validate_decimal("correlation_id", &self.correlation_id).map(|_| ())
1128 }
1129}
1130impl StopParams {
1131 pub fn validate_for(&self, identity: &SessionIdentity) -> Result<(), ProtocolError> {
1132 validate_session(&self.session, identity)?;
1133 validate_token("cleanup_scope_id", &self.cleanup_scope_id)?;
1134 validate_decimal("remaining_budget_nanos", &self.remaining_budget_nanos).map(|_| ())
1135 }
1136}
1137impl StoppedResult {
1138 pub fn validate_for(&self, request: &StopParams) -> Result<(), ProtocolError> {
1139 validate_echo(
1140 &self.session,
1141 &self.cleanup_scope_id,
1142 &request.session,
1143 &request.cleanup_scope_id,
1144 )?;
1145 for diagnostic in &self.diagnostics {
1146 validate_token("cleanup diagnostic code", &diagnostic.code)?;
1147 validate_detail(&diagnostic.detail)?;
1148 }
1149 Ok(())
1150 }
1151}
1152
1153fn validate_descriptor(capability: &str, version: &str, digest: &str) -> Result<(), ProtocolError> {
1154 validate_token("capability_id", capability)?;
1155 validate_token("descriptor_version", version)?;
1156 validate_digest("descriptor_digest", digest)
1157}
1158
1159#[expect(
1160 clippy::too_many_arguments,
1161 reason = "wire identity fields remain explicit"
1162)]
1163fn validate_provided_operation(
1164 session: &str,
1165 correlation_id: &str,
1166 endpoint_id: &str,
1167 capability_id: &str,
1168 descriptor_version: &str,
1169 descriptor_digest: &str,
1170 operation: &str,
1171 scope: &InvocationScope,
1172 initialize: &InitializeParams,
1173 interaction: &str,
1174) -> Result<(), ProtocolError> {
1175 validate_session(session, &initialize.identity)?;
1176 validate_decimal("correlation_id", correlation_id)?;
1177 validate_token("endpoint_id", endpoint_id)?;
1178 validate_descriptor(capability_id, descriptor_version, descriptor_digest)?;
1179 validate_token("operation", operation)?;
1180 scope.validate()?;
1181 let endpoint = initialize
1182 .provided_endpoints
1183 .iter()
1184 .find(|endpoint| endpoint.endpoint_id == endpoint_id)
1185 .ok_or_else(|| error(format!("{interaction} references an unknown endpoint_id")))?;
1186 if endpoint.capability_id != capability_id
1187 || endpoint.descriptor_version != descriptor_version
1188 || endpoint.descriptor_digest != descriptor_digest
1189 {
1190 return Err(error(format!(
1191 "{interaction} descriptor does not match its admitted endpoint"
1192 )));
1193 }
1194 Ok(())
1195}
1196
1197#[expect(
1198 clippy::too_many_arguments,
1199 reason = "wire identity fields remain explicit"
1200)]
1201fn validate_outbound_operation(
1202 session: &str,
1203 correlation_id: &str,
1204 requirement_id: &str,
1205 route_id: &str,
1206 operation: &str,
1207 scope: &InvocationScope,
1208 initialize: &InitializeParams,
1209 parent: &InvocationScope,
1210 parent_active: bool,
1211 interaction: &str,
1212) -> Result<(), ProtocolError> {
1213 validate_session(session, &initialize.identity)?;
1214 validate_decimal("correlation_id", correlation_id)?;
1215 validate_requirement_id(requirement_id)?;
1216 validate_token("route_id", route_id)?;
1217 validate_token("operation", operation)?;
1218 scope.validate_child_of(parent)?;
1219 if !parent_active {
1220 return Err(error(format!(
1221 "closed parent scope cannot start an outbound {interaction}"
1222 )));
1223 }
1224 let route = initialize
1225 .routes
1226 .iter()
1227 .find(|route| route.route_id == route_id)
1228 .ok_or_else(|| {
1229 error(format!(
1230 "outbound {interaction} references an unknown route_id"
1231 ))
1232 })?;
1233 if route.requirement_id != requirement_id {
1234 return Err(error("outbound route belongs to another requirement"));
1235 }
1236 Ok(())
1237}
1238
1239fn validate_stream_action(
1240 session: &str,
1241 correlation_id: &str,
1242 stream_id: &str,
1243 identity: &SessionIdentity,
1244) -> Result<(), ProtocolError> {
1245 validate_session(session, identity)?;
1246 validate_decimal("correlation_id", correlation_id)?;
1247 validate_decimal("stream_id", stream_id).map(|_| ())
1248}
1249
1250fn validate_stream_result(
1251 session: &str,
1252 correlation_id: &str,
1253 stream_id: &str,
1254 expected_session: &str,
1255 expected_correlation_id: &str,
1256 expected_stream_id: &str,
1257) -> Result<(), ProtocolError> {
1258 validate_echo(
1259 session,
1260 correlation_id,
1261 expected_session,
1262 expected_correlation_id,
1263 )?;
1264 if stream_id != expected_stream_id {
1265 return Err(error("stream result identity mismatch"));
1266 }
1267 validate_decimal("stream_id", stream_id).map(|_| ())
1268}
1269fn validate_session(session: &str, identity: &SessionIdentity) -> Result<(), ProtocolError> {
1270 if session != identity.session {
1271 return Err(error("message session does not match admitted session"));
1272 }
1273 Ok(())
1274}
1275fn validate_echo(
1276 session: &str,
1277 id: &str,
1278 expected_session: &str,
1279 expected_id: &str,
1280) -> Result<(), ProtocolError> {
1281 if session != expected_session || id != expected_id {
1282 return Err(error("response identity mismatch"));
1283 }
1284 Ok(())
1285}
1286fn validate_detail(value: &str) -> Result<(), ProtocolError> {
1287 if value.is_empty() || value.len() > 1_024 {
1288 return Err(error("detail must contain 1..=1024 bytes"));
1289 }
1290 Ok(())
1291}
1292fn validate_limit(name: &str, value: u64, maximum: u64) -> Result<(), ProtocolError> {
1293 if value == 0 || value > maximum {
1294 return Err(error(format!("{name} must be within 1..={maximum}")));
1295 }
1296 Ok(())
1297}
1298fn validate_token(name: &str, value: &str) -> Result<(), ProtocolError> {
1299 if value.is_empty()
1300 || value.len() > 256
1301 || !value.bytes().all(|byte| {
1302 byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b'@' | b'/' | b':')
1303 })
1304 {
1305 return Err(error(format!("{name} must be a portable token")));
1306 }
1307 Ok(())
1308}
1309fn validate_requirement_id(value: &str) -> Result<(), ProtocolError> {
1310 if value.is_empty()
1311 || value.len() > 64
1312 || !value.as_bytes()[0].is_ascii_lowercase()
1313 || !value
1314 .bytes()
1315 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
1316 {
1317 return Err(error("requirement_id must match ^[a-z][a-z0-9_]{0,63}$"));
1318 }
1319 Ok(())
1320}
1321fn validate_digest(name: &str, value: &str) -> Result<(), ProtocolError> {
1322 let Some(hex) = value.strip_prefix("sha256:") else {
1323 return Err(error(format!("{name} must be a canonical SHA-256 digest")));
1324 };
1325 if hex.len() != 64
1326 || !hex
1327 .bytes()
1328 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1329 {
1330 return Err(error(format!("{name} must be a canonical SHA-256 digest")));
1331 }
1332 Ok(())
1333}
1334fn validate_decimal(name: &str, value: &str) -> Result<u64, ProtocolError> {
1335 if value.is_empty()
1336 || (value.len() > 1 && value.starts_with('0'))
1337 || !value.bytes().all(|byte| byte.is_ascii_digit())
1338 {
1339 return Err(error(format!("{name} must be a canonical decimal string")));
1340 }
1341 decimal_value(value)
1342}
1343fn decimal_value(value: &str) -> Result<u64, ProtocolError> {
1344 value
1345 .parse()
1346 .map_err(|_| error("decimal string exceeds unsigned 64-bit range"))
1347}
1348fn validate_sorted<T>(
1349 values: &[T],
1350 key: impl Fn(&T) -> &str,
1351 name: &str,
1352) -> Result<(), ProtocolError> {
1353 if values.windows(2).any(|pair| key(&pair[0]) >= key(&pair[1])) {
1354 return Err(error(format!("{name} must be sorted and unique")));
1355 }
1356 Ok(())
1357}
1358fn validate_sorted_strings(values: &[String], name: &str) -> Result<(), ProtocolError> {
1359 if values.windows(2).any(|pair| pair[0] >= pair[1]) {
1360 return Err(error(format!("{name} must be sorted and unique")));
1361 }
1362 for value in values {
1363 validate_token(name, value)?;
1364 }
1365 Ok(())
1366}
1367fn error(detail: impl Into<String>) -> ProtocolError {
1368 ProtocolError::new(detail)
1369}