1#![forbid(unsafe_code)]
3use crate::dialect::Dialect;
4use crate::role::{Cast, RoleCardinality, RoleDecl};
5use crate::state::{Act, Rule, StateBounds, Value};
6use alloc::boxed::Box;
7use alloc::collections::{BTreeMap, BTreeSet};
8use alloc::string::{String, ToString};
9use alloc::vec::Vec;
10
11#[derive(Clone, Debug, PartialEq, Eq)]
13#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
14pub struct Definition {
15 pub name: String,
16 pub address: String,
17 pub body_address: String,
18 pub author: Option<String>,
19 pub roles: Vec<RoleDecl>,
20 pub bounds: StateBounds,
21 pub opener: Option<String>,
22}
23pub fn resolve(d: &mut Dialect) {
24 if !d
25 .state
26 .as_ref()
27 .is_some_and(|s| s.fields().any(|(_, r)| matches!(r, Rule::Context { .. })))
28 {
29 return;
30 }
31 let definition = Definition {
32 name: d.name.clone(),
33 address: crate::canonical::dialect_hash(d),
34 body_address: crate::canonical::dialect_name(d),
35 author: d.author.clone(),
36 roles: d.roles.clone(),
37 bounds: crate::r7::bounds_of(d),
38 opener: d
39 .causal_protocol
40 .as_ref()
41 .and_then(crate::state::opener_verb)
42 .map(String::from),
43 };
44 if let Some(clause) = &mut d.state {
45 for entry in &mut clause.entries {
46 if let crate::state::Entry::Field {
47 rule: Rule::Context {
48 definition: cache, ..
49 },
50 ..
51 } = entry
52 {
53 *cache = Some(Box::new(definition.clone()));
54 }
55 }
56 }
57}
58fn map(items: impl IntoIterator<Item = (String, Value)>) -> Value {
59 Value::Map(
60 items
61 .into_iter()
62 .collect::<BTreeMap<_, _>>()
63 .into_iter()
64 .map(|(k, v)| (Value::Str(k), v))
65 .collect(),
66 )
67}
68fn obj<const N: usize>(items: [(&str, Value); N]) -> Value {
69 map(items.into_iter().map(|(k, v)| (k.into(), v)))
70}
71fn text(s: &str) -> Value {
72 Value::Str(s.into())
73}
74fn lookup(value: &Value, key: &str) -> Value {
75 if value.fault_evidence().is_some() {
76 return value.clone();
77 }
78 match value {
79 Value::Map(items) => items
80 .iter()
81 .find(|(k, _)| *k == text(key))
82 .map(|(_, v)| v.clone())
83 .unwrap_or(Value::Absent),
84 _ => Value::Absent,
85 }
86}
87pub fn roster_role(path: &[String]) -> Option<&str> {
88 match path {
89 [a, b, role] if a == "thread" && b == "roles" => Some(role),
90 _ => None,
91 }
92}
93pub fn stable_path(path: &[String]) -> bool {
94 match path.first().map(String::as_str) {
95 Some("dialect") => true,
96 Some("thread") if path.len() >= 2 => path.get(1).is_some_and(|p| {
97 matches!(p.as_str(), "id" | "root" | "initiator" | "opener" | "roles")
98 }),
99 _ => false,
100 }
101}
102
103pub fn schema(path: &[String]) -> crate::state::StateType {
104 use crate::state::{ScalarType as S, StateType as T};
105 let string = || T::OptScalar(S::Str);
106 let set = || T::Set(S::Str);
107 let object = |fields: Vec<(&str, T)>| {
108 T::Object(fields.into_iter().map(|(k, v)| (k.into(), v)).collect())
109 };
110 let dialect = object(alloc::vec![
111 ("address", string()),
112 ("body-address", string()),
113 ("name", string()),
114 ("author", string()),
115 ("roles", T::Map(S::Str, Box::new(string()))),
116 (
117 "bounds",
118 object(alloc::vec![
119 ("max-fields", T::Int),
120 ("max-list", T::Int),
121 ("max-number", T::Int),
122 ("max-string", T::Int)
123 ])
124 )
125 ]);
126 let thread = object(alloc::vec![
127 ("id", string()),
128 ("root", string()),
129 ("initiator", string()),
130 ("opener", string()),
131 ("roles", T::Map(S::Str, Box::new(set())))
132 ]);
133 let observation = object(alloc::vec![("accepted-count", T::Int), ("frontier", set())]);
134 let mut value = object(alloc::vec![
135 ("dialect", dialect),
136 ("thread", thread),
137 ("observation", observation)
138 ]);
139 for key in path {
140 value = match value {
141 T::Object(fields) => fields
142 .into_iter()
143 .find(|(k, _)| k == key)
144 .map(|(_, v)| v)
145 .unwrap_or(T::Unknown),
146 T::Map(_, v) => *v,
147 _ => T::Unknown,
148 };
149 }
150 value
151}
152impl Definition {
153 pub fn valid_path(&self, path: &[String]) -> bool {
154 let p: Vec<&str> = path.iter().map(String::as_str).collect();
155 match p.as_slice() {
156 [] | ["dialect"] | ["thread"] | ["observation"] => true,
157 ["dialect", "address" | "body-address" | "name" | "author" | "roles" | "bounds"] => {
158 true
159 }
160 ["dialect", "bounds", "max-fields" | "max-list" | "max-number" | "max-string"] => true,
161 ["dialect", "roles", role] => self.roles.iter().any(|r| r.name == *role),
162 ["thread", "id" | "root" | "initiator" | "opener" | "roles"] => true,
163 ["thread", "roles", role] => self.roles.iter().any(|r| r.name == *role),
164 ["observation", "accepted-count" | "frontier"] => true,
165 _ => false,
166 }
167 }
168 fn dialect(&self) -> Value {
169 obj([
170 ("name", text(&self.name)),
171 ("address", text(&self.address)),
172 ("body-address", text(&self.body_address)),
173 (
174 "author",
175 self.author.as_deref().map(text).unwrap_or(Value::Absent),
176 ),
177 (
178 "roles",
179 map(self.roles.iter().map(|r| {
180 (
181 r.name.clone(),
182 text(match r.cardinality {
183 RoleCardinality::Singleton => "singleton",
184 RoleCardinality::Indexed => "indexed",
185 }),
186 )
187 })),
188 ),
189 (
190 "bounds",
191 obj([
192 ("max-fields", Value::Int(self.bounds.max_fields as i128)),
193 ("max-list", Value::Int(self.bounds.max_list as i128)),
194 ("max-number", Value::Int(self.bounds.max_number as i128)),
195 ("max-string", Value::Int(self.bounds.max_string as i128)),
196 ]),
197 ),
198 ])
199 }
200 fn cast(&self, root: &Act) -> Result<Cast, String> {
201 let mut message = &root.message;
202 loop {
203 match message {
204 crate::message::Message::Wrapped {
205 wrapper: crate::message::WrapperType::WithRoles,
206 params,
207 ..
208 } => {
209 let cast = crate::role::parse_wrapper_cast(params, &self.roles)
210 .map_err(|e| e.to_string())?;
211 if cast
212 .dialect_pin
213 .as_ref()
214 .is_some_and(|pin| *pin != self.address)
215 {
216 return Err("wrong context dialect pin".into());
217 }
218 return Ok(cast);
219 }
220 crate::message::Message::Wrapped { content, .. } => message = content,
221 crate::message::Message::Dialect { inner, .. } => message = inner,
222 _ if self.roles.is_empty() => {
223 return Ok(Cast {
224 singleton: BTreeMap::new(),
225 indexed: BTreeMap::new(),
226 dialect_pin: None,
227 })
228 }
229 _ => return Err("context root is missing its sealed cast".into()),
230 }
231 }
232 }
233 fn thread(&self, acts: &[Act]) -> Value {
234 let roots: Vec<&Act> = acts.iter().filter(|a| a.predecessors.is_empty()).collect();
235 if roots.is_empty() {
236 return Value::Absent;
237 }
238 let evidence = || roots.iter().map(|a| a.address.clone()).collect();
239 let root = roots[0];
240 if roots
241 .iter()
242 .any(|other| other.address != root.address || other.signer != root.signer)
243 {
244 return crate::state::conflict_top("incompatible thread roots or casts", evidence());
245 }
246 let casts: Vec<Result<Cast, String>> = roots.iter().map(|r| self.cast(r)).collect();
247 if let Some(reason) = casts.iter().filter_map(|c| c.as_ref().err()).min() {
248 return crate::state::conflict_top(reason, evidence());
249 }
250 let cast = casts[0].as_ref().unwrap();
251 if casts.iter().any(|c| c.as_ref().ok() != Some(cast)) {
252 return crate::state::conflict_top("incompatible thread roots or casts", evidence());
253 }
254 if acts
255 .iter()
256 .any(|a| a.simple().thread() != root.simple().thread())
257 {
258 return crate::state::conflict_top(
259 "mixed thread context",
260 acts.iter().map(|a| a.address.clone()).collect(),
261 );
262 }
263 let roles = map(cast
264 .singleton
265 .iter()
266 .map(|(r, k)| (r.clone(), Value::Set(alloc::vec![text(&k.0)])))
267 .chain(cast.indexed.iter().map(|(r, ks)| {
268 (
269 r.clone(),
270 Value::Set(ks.iter().map(|k| text(&k.0)).collect()),
271 )
272 })));
273 let openers: BTreeMap<&str, &Act> = acts
274 .iter()
275 .filter(|a| self.opener.as_ref().is_some_and(|v| *v == a.verb))
276 .map(|a| (a.address.as_str(), a))
277 .collect();
278 let opener = match openers.len() {
279 0 => Value::Absent,
280 1 => text(openers.keys().next().unwrap()),
281 _ => crate::state::conflict_top(
282 "opener fork",
283 openers.keys().map(|s| s.to_string()).collect(),
284 ),
285 };
286 obj([
287 (
288 "id",
289 root.simple().thread().map(text).unwrap_or(Value::Absent),
290 ),
291 ("root", text(&root.address)),
292 ("initiator", text(&root.signer)),
293 ("opener", opener),
294 ("roles", roles),
295 ])
296 }
297 fn retain_fault_evidence(&self, path: &[String], acts: &[Act], value: Value) -> Value {
301 let Some(mut evidence) = value.fault_evidence() else {
302 return value;
303 };
304 if let Some(root) = acts.iter().find(|a| a.predecessors.is_empty()) {
305 if acts
306 .iter()
307 .any(|a| a.simple().thread() != root.simple().thread())
308 {
309 evidence.extend(acts.iter().map(|a| a.address.clone()));
310 }
311 let observes_opener = path.is_empty()
312 || (path.first().is_some_and(|p| p == "thread")
313 && (path.len() == 1 || (path.len() == 2 && path[1] == "opener")));
314 if observes_opener {
315 let openers: BTreeSet<&str> = acts
316 .iter()
317 .filter(|a| self.opener.as_ref().is_some_and(|v| *v == a.verb))
318 .map(|a| a.address.as_str())
319 .collect();
320 if openers.len() > 1 {
321 evidence.extend(openers.into_iter().map(String::from));
322 }
323 }
324 }
325 let reason = match &value {
326 Value::Map(entries) => entries.iter().find_map(|(key, value)| match (key, value) {
327 (Value::Str(key), Value::Str(reason)) if key == "reason" => Some(reason.as_str()),
328 _ => None,
329 }),
330 _ => None,
331 }
332 .unwrap_or("context conflicts");
333 crate::state::conflict_top(reason, evidence)
334 }
335
336 pub fn read(&self, path: &[String], acts: &[Act]) -> Value {
337 let observation = || {
338 obj([
339 (
340 "accepted-count",
341 Value::Int(
342 acts.iter()
343 .map(|a| &a.address)
344 .collect::<BTreeSet<_>>()
345 .len() as i128,
346 ),
347 ),
348 (
349 "frontier",
350 Value::Set(
351 crate::state::frontier(acts)
352 .into_iter()
353 .map(Value::Str)
354 .collect(),
355 ),
356 ),
357 ])
358 };
359 let thread = || {
360 let value = self.thread(acts);
361 if path.is_empty() || path.len() == 1 {
362 let opener = lookup(&value, "opener");
363 if opener.fault_evidence().is_some() {
364 return opener;
365 }
366 }
367 value
368 };
369 let full = match path.first().map(String::as_str) {
370 Some("dialect") => self.dialect(),
371 Some("thread") => thread(),
372 Some("observation") => observation(),
373 None => {
374 let thread = thread();
375 if thread.fault_evidence().is_some() {
376 return self.retain_fault_evidence(path, acts, thread);
377 }
378 obj([
379 ("dialect", self.dialect()),
380 ("thread", thread),
381 ("observation", observation()),
382 ])
383 }
384 _ => return Value::Absent,
385 };
386 let value = path
387 .iter()
388 .skip(1)
389 .fold(full, |value, key| lookup(&value, key));
390 self.retain_fault_evidence(path, acts, value)
391 }
392}