1use std::{collections::HashSet, hash::BuildHasher};
9
10use crate::{ActionInput, ActionRegistry, ResourceSpec};
11
12#[derive(Clone, Debug, PartialEq, Eq)]
13pub struct ContractViolation {
14 pub address: String,
15 pub reason: String,
16}
17
18pub fn validate_surface<S: BuildHasher>(
19 resources: &[ResourceSpec],
20 registry: &ActionRegistry,
21 operation_handlers: &HashSet<String, S>,
22) -> Vec<ContractViolation> {
23 validate_surface_inner(resources, registry, Some(operation_handlers))
24}
25
26pub fn validate_surface_contracts(
31 resources: &[ResourceSpec],
32 registry: &ActionRegistry,
33) -> Vec<ContractViolation> {
34 validate_surface_inner(resources, registry, None::<&HashSet<String>>)
35}
36
37fn validate_surface_inner<S: BuildHasher>(
38 resources: &[ResourceSpec],
39 registry: &ActionRegistry,
40 operation_handlers: Option<&HashSet<String, S>>,
41) -> Vec<ContractViolation> {
42 let mut seen_resources = HashSet::new();
43 let mut seen_actions = HashSet::new();
44 let mut violations = Vec::new();
45 for resource in resources {
46 validate_resource(
47 resource,
48 registry,
49 operation_handlers,
50 &mut seen_resources,
51 &mut seen_actions,
52 &mut violations,
53 );
54 }
55 violations
56}
57
58fn validate_resource<S: BuildHasher>(
59 resource: &ResourceSpec,
60 registry: &ActionRegistry,
61 operation_handlers: Option<&HashSet<String, S>>,
62 seen_resources: &mut HashSet<String>,
63 seen_actions: &mut HashSet<String>,
64 violations: &mut Vec<ContractViolation>,
65) {
66 let resource_id = resource.id.as_str();
67 validate_resource_identity(resource, seen_resources, violations);
68 for action in &resource.actions {
69 let address = format!("{}{}{}", resource_id, crate::KEY_SEP, action.id);
70 if action.id.is_empty() || action.id.contains(crate::KEY_SEP) {
71 violations.push(issue(
72 &address,
73 "action id is empty or contains the separator",
74 ));
75 }
76 if !seen_actions.insert(address.clone()) {
77 violations.push(issue(&address, "duplicate action address"));
78 }
79 for reason in action.contract.validate_declaration() {
80 violations.push(issue(&address, &reason));
81 }
82 let mut parameter_names = HashSet::new();
83 for parameter in action.params() {
84 if !parameter.name.trim().is_empty() && !parameter_names.insert(parameter.name.as_ref())
85 {
86 violations.push(issue(&address, "parameter names must be unique"));
87 }
88 for reason in parameter.validate_declaration() {
89 violations.push(issue(
90 &address,
91 &format!("parameter `{}` {reason}", parameter.name),
92 ));
93 }
94 }
95 let encoded = action.published_encoding();
101 if let Err(error) = action.validate_deferred_shape() {
102 violations.push(issue(&address, &error.to_string()));
103 }
104 if let ActionInput::Deferred { type_id } = action.input() {
105 if action.kind == crate::OperationKind::Document && !registry.contains(type_id) {
106 violations.push(issue(&address, "document action type is not registered"));
107 }
108 if action
109 .operation_type
110 .as_ref()
111 .is_some_and(|declared| declared != type_id)
112 {
113 violations.push(issue(
114 &address,
115 "deferred operation type does not match its declaration",
116 ));
117 }
118 }
119 if action.kind == crate::OperationKind::Document && action.operation_type.is_some() {
120 violations.push(issue(
121 &address,
122 "document action declares an effect/view handler",
123 ));
124 }
125 if action.kind != crate::OperationKind::Document && action.operation_type.is_none() {
126 violations.push(issue(
127 &address,
128 "effect/view action has no declared operation type",
129 ));
130 }
131 if let Some(encoded) = encoded {
132 if action.kind == crate::OperationKind::Document && !registry.contains(&encoded.type_id)
133 {
134 violations.push(issue(&address, "document action type is not registered"));
135 }
136 if let Some(declared) = &action.operation_type
137 && encoded.type_id != *declared
138 {
139 violations.push(issue(
140 &address,
141 "encoded operation type does not match its declaration",
142 ));
143 }
144 }
145 if action.kind != crate::OperationKind::Document
146 && action.operation_type.as_ref().is_some_and(|type_id| {
147 operation_handlers.is_some_and(|handlers| !handlers.contains(type_id))
148 })
149 {
150 violations.push(issue(
151 &address,
152 "effect/view operation has no declared handler",
153 ));
154 }
155 }
156 validate_views(resource, violations);
157 for child in &resource.children {
158 validate_resource(
159 child,
160 registry,
161 operation_handlers,
162 seen_resources,
163 seen_actions,
164 violations,
165 );
166 }
167}
168
169fn validate_resource_identity(
170 resource: &ResourceSpec,
171 seen_resources: &mut HashSet<String>,
172 violations: &mut Vec<ContractViolation>,
173) {
174 let resource_id = resource.id.as_str();
175 if resource_id.is_empty() || resource.kind.is_empty() {
176 violations.push(issue(resource_id, "resource id and kind must be non-empty"));
177 }
178 if resource_id.contains(crate::KEY_SEP) {
179 violations.push(issue(
180 resource_id,
181 "resource id contains the address separator",
182 ));
183 }
184 if !seen_resources.insert(resource_id.to_string()) {
185 violations.push(issue(resource_id, "duplicate resource id"));
186 }
187}
188
189fn validate_views(resource: &ResourceSpec, violations: &mut Vec<ContractViolation>) {
190 let mut view_ids = HashSet::new();
191 let mut view_open_actions = HashSet::new();
192 let mut primary_views = 0usize;
193 for view in &resource.views {
194 let address = format!("{}{}view:{}", resource.id.as_str(), crate::KEY_SEP, view.id);
195 if !view_ids.insert(view.id.as_str()) {
196 violations.push(issue(&address, "duplicate view id"));
197 }
198 if !view_open_actions.insert(view.open_action.as_str()) {
199 violations.push(issue(
200 &address,
201 "at most one view may reference an open action",
202 ));
203 }
204 if view.primary {
205 primary_views = primary_views.saturating_add(1);
206 if primary_views > 1 {
207 violations.push(issue(&address, "at most one view may be primary"));
208 }
209 }
210 for reason in view.validate(resource) {
211 violations.push(issue(&address, &reason));
212 }
213 }
214}
215
216fn issue(address: &str, reason: &str) -> ContractViolation {
217 ContractViolation {
218 address: address.to_string(),
219 reason: reason.to_string(),
220 }
221}
222
223#[cfg(test)]
224mod tests {
225 use super::*;
226 use crate::{
227 ActionParam, ActionSpec, EncodedAction, OperationKind, ParamType, ResourceViewMountSpec,
228 ResourceViewSpec,
229 };
230
231 #[test]
235 fn protocol_surfaces_are_validated_before_publication() {
236 rejects_duplicate_unhandled_and_unsafe_surface_entries();
237 validates_explicit_resource_view_cardinality_and_bindings();
238 }
239
240 fn rejects_duplicate_unhandled_and_unsafe_surface_entries() {
241 let unsafe_effect =
242 ActionSpec::operation("erase", "Erase", OperationKind::Effect, "test.erase", &())
243 .unwrap()
244 .with_contract(crate::ActionContract {
245 kind: crate::ActionKind::Outside,
246 risk: crate::RiskLevel::Destructive,
247 confirmation: crate::ConfirmationPolicy::None,
248 ..crate::ActionContract::default()
249 });
250 let resources = vec![
251 ResourceSpec::new("same", "test.item", "One").with_action(unsafe_effect),
252 ResourceSpec::new("same", "test.item", "Two").with_action(
253 ActionSpec::immediate_encoded(
254 "edit",
255 "Edit",
256 crate::ExecutionLocus::ClientLocal,
257 EncodedAction::encode_operation("test.missing", &()).unwrap(),
258 ),
259 ),
260 ];
261 let violations = validate_surface(&resources, &ActionRegistry::new(), &HashSet::new());
262 let text = violations
263 .iter()
264 .map(|issue| issue.reason.as_str())
265 .collect::<Vec<_>>()
266 .join("\n");
267 assert!(text.contains("duplicate resource"));
268 assert!(text.contains("requires confirmation"));
269 assert!(text.contains("no declared handler"));
270 assert!(text.contains("not registered"));
271 }
272
273 fn validates_explicit_resource_view_cardinality_and_bindings() {
274 let open =
275 ActionSpec::operation("open", "Open", OperationKind::View, "test.open", &()).unwrap();
276 let mount = ActionSpec::typed_operation(
277 "mount",
278 "Mount",
279 "",
280 OperationKind::Effect,
281 "test.mount",
282 vec![
283 ActionParam::required("cap", ParamType::Text, "Capability"),
284 ActionParam::optional("target", ParamType::Integer, "View"),
285 ],
286 |_| EncodedAction::encode_operation("test.mount", &()).unwrap(),
287 )
288 .with_contract(crate::ActionContract {
289 confirmation: crate::ConfirmationPolicy::Confirm,
290 ..crate::ActionContract::default()
291 });
292 let resource = ResourceSpec::new("thing:1", "test.thing", "Thing")
293 .with_action(open)
294 .with_action(mount)
295 .with_view(
296 ResourceViewSpec::new("editor", "Editor", "open")
297 .with_primary(true)
298 .with_mount(ResourceViewMountSpec::new("mount", "cap", "target")),
299 )
300 .with_view(ResourceViewSpec::new("preview", "Preview", "open").with_primary(true));
301
302 let text = validate_surface_contracts(&[resource], &ActionRegistry::new())
303 .into_iter()
304 .map(|issue| issue.reason)
305 .collect::<Vec<_>>()
306 .join("\n");
307 assert!(text.contains("at most one view may reference an open action"));
308 assert!(text.contains("at most one view may be primary"));
309 assert!(text.contains("mount action `mount` must be a view operation"));
310 assert!(text.contains("mount action `mount` must not require confirmation"));
311 assert!(text.contains("mount action `mount` must not require caller parameters"));
312 assert!(text.contains("mount capability parameter `cap` must name an optional text"));
313 assert!(text.contains("mount view parameter `target` must name an optional text"));
314 }
315}