1use crate::protocol::ProtocolProgram;
10use crate::runtime::{Event, OutEvent, Runtime};
11use std::collections::BTreeMap;
12
13pub type SessionId = String;
14
15pub struct SessionHost {
17 pub program: ProtocolProgram,
18 pub capacity: usize,
19 granted: std::collections::BTreeSet<String>,
23 sessions: BTreeMap<SessionId, Runtime>,
24 journal: Vec<(SessionId, Event)>,
26 opened_roles: BTreeMap<SessionId, String>,
29 outbox: Vec<(SessionId, OutEvent)>,
31}
32
33impl SessionHost {
34 pub fn new(program: &ProtocolProgram) -> Result<Self, String> {
35 Ok(SessionHost {
36 program: program.clone(),
37 capacity: program.capacity.unwrap_or(usize::MAX),
38 granted: std::collections::BTreeSet::new(),
39 sessions: BTreeMap::new(),
40 journal: Vec::new(),
41 opened_roles: BTreeMap::new(),
42 outbox: Vec::new(),
43 })
44 }
45
46 pub fn new_gated(
49 program: &ProtocolProgram,
50 granted: &[String],
51 ) -> Result<Self, String> {
52 let mut host = SessionHost::new(program)?;
53 for g in granted {
54 host.granted.insert(g.clone());
55 }
56 Ok(host)
57 }
58
59 fn open_inner(&mut self, id: &str, role: &str, journal_it: bool) -> Result<(), String> {
62 let ungranted: Vec<&str> = self
63 .program
64 .capabilities
65 .iter()
66 .map(|c| c.name.as_str())
67 .filter(|name| !name.starts_with("stdlib.") && !self.granted.contains(*name))
68 .collect();
69 if !ungranted.is_empty() {
70 return Err(format!(
71 "capability gate: session '{id}' rejected — program requires {} which was not granted",
72 ungranted.join(", ")
73 ));
74 }
75 if self.sessions.contains_key(id) {
76 return Err(format!("session '{id}' already open"));
77 }
78 if self.sessions.len() >= self.capacity {
79 return Err(format!(
80 "capacity reached ({}) — session '{id}' rejected",
81 self.capacity
82 ));
83 }
84 let rt = Runtime::new(&self.program, role)
85 .map_err(|e| format!("session '{id}': {}", e.message))?;
86 self.sessions.insert(id.to_string(), rt);
87 self.opened_roles.insert(id.to_string(), role.to_string());
88 if journal_it {
89 self.journal
90 .push((id.to_string(), Event::SessionOpened { role: role.to_string() }));
91 }
92 Ok(())
93 }
94
95 pub fn peer_satisfies(card_capabilities: &[String]) -> impl Fn(&ProtocolProgram) -> Result<(), String> + '_ {
98 move |prog| {
99 let missing: Vec<&str> = prog
100 .capabilities
101 .iter()
102 .map(|c| c.name.as_str())
103 .filter(|n| !card_capabilities.contains(&n.to_string()))
104 .collect();
105 if missing.is_empty() {
106 Ok(())
107 } else {
108 Err(format!("peer AgentCard lacks: {}", missing.join(", ")))
109 }
110 }
111 }
112
113 pub fn open(&mut self, id: &str, role: &str) -> Result<(), String> {
115 let ungranted: Vec<&str> = self
118 .program
119 .capabilities
120 .iter()
121 .map(|c| c.name.as_str())
122 .filter(|name| !name.starts_with("stdlib.") && !self.granted.contains(*name))
123 .collect();
124 if !ungranted.is_empty() {
125 return Err(format!(
126 "capability gate: session '{id}' rejected — program requires {} which was not granted",
127 ungranted.join(", ")
128 ));
129 }
130 if self.sessions.contains_key(id) {
131 return Err(format!("session '{id}' already open"));
132 }
133 if self.sessions.len() >= self.capacity {
134 return Err(format!(
135 "capacity reached ({}) — session '{id}' rejected",
136 self.capacity
137 ));
138 }
139 let rt = Runtime::new(&self.program, role)
140 .map_err(|e| format!("session '{id}': {}", e.message))?;
141 self.sessions.insert(id.to_string(), rt);
142 self.opened_roles.insert(id.to_string(), role.to_string());
143 self.journal
146 .push((id.to_string(), Event::SessionOpened { role: role.to_string() }));
147 Ok(())
148 }
149
150 pub fn close(&mut self, id: &str) -> Result<(), String> {
151 let closed = self
152 .sessions
153 .remove(id)
154 .map(|_| ())
155 .ok_or_else(|| format!("session '{id}' not open"));
156 if closed.is_ok() {
158 self.journal.push((id.to_string(), Event::SessionClosed));
159 }
160 closed
161 }
162
163 pub fn is_open(&self, id: &str) -> bool {
164 self.sessions.contains_key(id)
165 }
166
167 pub fn session_count(&self) -> usize {
168 self.sessions.len()
169 }
170
171 pub fn deliver(&mut self, id: &str, ev: Event) -> Result<Vec<OutEvent>, String> {
173 if matches!(ev, Event::SessionClosed) {
177 self.close(id)?;
179 return Ok(Vec::new());
180 }
181 if let Event::SessionOpened { role } = &ev {
182 self.open(id, role)?;
185 return Ok(Vec::new());
186 }
187 if let Event::Tick(ms) = ev {
188 let rt = self
189 .sessions
190 .get_mut(id)
191 .ok_or_else(|| format!("session '{id}' not open"))?;
192 let outs = rt.tick(ms);
193 self.journal.push((id.to_string(), Event::Tick(ms)));
194 for o in &outs {
195 self.outbox.push((id.to_string(), o.clone()));
196 }
197 return Ok(outs);
198 }
199 let rt = self
200 .sessions
201 .get_mut(id)
202 .ok_or_else(|| format!("session '{id}' not open"))?;
203 let outs = rt.deliver(ev.clone());
204 self.journal.push((id.to_string(), ev));
206 for o in &outs {
207 self.outbox.push((id.to_string(), o.clone()));
208 }
209 Ok(outs)
210 }
211
212 pub fn tick(&mut self, elapsed_ms: i64) -> Vec<(SessionId, OutEvent)> {
214 let mut out = Vec::new();
215 for (id, rt) in self.sessions.iter_mut() {
216 for o in rt.tick(elapsed_ms) {
217 out.push((id.clone(), o));
218 }
219 }
220 for (id, o) in &out {
221 self.outbox.push((id.clone(), o.clone()));
222 }
223 for id in self.sessions.keys() {
226 self.journal.push((id.clone(), Event::Tick(elapsed_ms)));
227 }
228 out
229 }
230
231 pub fn journal(&self) -> &[(SessionId, Event)] {
233 &self.journal
234 }
235
236 pub fn outbox(&self) -> &[(SessionId, OutEvent)] {
238 &self.outbox
239 }
240
241 #[deprecated(note = "role inference from senders is unsound; use replay_from")]
248 pub fn replay(program: &ProtocolProgram, journal: &[(SessionId, Event)]) -> Result<Self, String> {
249 let opens: Vec<(SessionId, &str)> = journal
250 .iter()
251 .filter_map(|(id, ev)| match ev {
252 Event::SessionOpened { role } => Some((id.clone(), role.as_str())),
253 _ => None,
254 })
255 .collect();
256 if opens.is_empty() {
257 return Err(
258 "replay(): legacy journal without journaled session opens cannot be reconstructed faithfully — persist with journal_with_roles() and use replay_from()"
259 .to_string(),
260 );
261 }
262 let mut host = SessionHost::new(program)?;
263 for (id, ev) in journal {
264 if let Event::SessionOpened { .. } = ev {
265 let _ = host.deliver(id, ev.clone());
266 }
267 }
268 for (id, ev) in journal {
269 if host.is_open(id) {
270 let _ = host.deliver(id, ev.clone());
271 }
272 }
273 Ok(host)
274 }
275
276 pub fn journal_with_roles(
279 &self,
280 ) -> (Vec<(String, String)>, Vec<String>, Vec<(SessionId, Event)>) {
281 let roles: Vec<(String, String)> = self
284 .opened_roles
285 .iter()
286 .map(|(id, r)| (id.clone(), r.clone()))
287 .collect();
288 let grants: Vec<String> = self.granted.iter().cloned().collect();
289 (roles, grants, self.journal.clone())
290 }
291
292 pub fn replay_from(
294 program: &ProtocolProgram,
295 roles: &[(String, String)],
296 grants: &[String],
297 journal: &[(SessionId, Event)],
298 ) -> Result<Self, String> {
299 let mut host = SessionHost::new_gated(program, grants)?;
301 let journaled_opens: std::collections::BTreeSet<&str> = journal
305 .iter()
306 .filter_map(|(id, ev)| match ev {
307 Event::SessionOpened { .. } => Some(id.as_str()),
308 _ => None,
309 })
310 .collect();
311 for (id, role) in roles {
312 if !journaled_opens.contains(&id.as_str()) {
313 host.open(id, role)?;
314 }
315 }
316 for (id, ev) in journal {
317 match ev {
318 Event::SessionOpened { role } => {
319 host.open_inner(id, role, true)?;
321 }
322 _ => {
323 if host.is_open(id) {
324 let _ = host.deliver(id, ev.clone());
325 }
326 }
327 }
328 }
329 Ok(host)
330 }
331
332 pub fn sessions_iter(&self) -> impl Iterator<Item = (&String, &Runtime)> {
334 self.sessions.iter()
335 }
336
337 pub fn same_state_as(&self, other: &SessionHost) -> bool {
339 for (id, rt) in &self.sessions {
340 match other.sessions.get(id) {
341 None => return false,
342 Some(o) => {
343 if rt.commitment() != o.commitment() {
344 return false;
345 }
346 if rt.states_snapshot() != o.states_snapshot() {
347 return false;
348 }
349 }
350 }
351 }
352 self.sessions.len() == other.sessions.len()
353 }
354}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359 use crate::protocol::parse;
360 use crate::Performative;
361
362 const PROG: &str = "protocol p v1;\nroles buyer, seller;\ncapacity 2;\non request(\"q\") from buyer -> send propose to buyer;\non propose from seller -> send accept to seller;\non accept from buyer -> begin;\non breach -> send failure to buyer;\n";
363
364 fn event(from: &str, perf: Performative, pattern: Option<&str>) -> Event {
365 Event::In {
366 from: from.to_string(),
367 performative: perf,
368 pattern: pattern.map(|p| p.to_string()),
369 fields: None,
370 }
371 }
372
373 #[test]
374 fn sessions_are_isolated_and_capacity_enforced() {
375 let prog = parse(PROG).unwrap();
376 let mut host = SessionHost::new(&prog).unwrap();
377 host.open("s1", "seller").unwrap();
378 host.open("s2", "seller").unwrap();
379 assert!(host.open("s3", "seller").is_err());
381 let out = host.deliver("s1", event("buyer", Performative::Request, Some("(\"q\")"))).unwrap();
383 assert_eq!(out[0].performative, Performative::Propose);
384 assert_eq!(host.session_count(), 2);
385 host.close("s1").unwrap();
386 assert!(!host.is_open("s1"));
387 host.open("s3", "seller").unwrap();
389 assert_eq!(host.session_count(), 2);
390 assert!(host.deliver("nope", event("buyer", Performative::Request, None)).is_err());
392 }
393
394 #[test]
395 fn event_sourcing_replay_reconstructs_exactly() {
396 let prog = parse(PROG).unwrap();
397 let mut host = SessionHost::new(&prog).unwrap();
398 host.open("s1", "seller").unwrap();
399 host.deliver("s1", event("buyer", Performative::Request, Some("(\"q\")"))).unwrap();
400 host.deliver("s1", event("buyer", Performative::Accept, None)).unwrap();
401 let original = &host.sessions["s1"];
403
404 let (roles, grants, journal) = host.journal_with_roles();
406 assert_eq!(journal.len(), 3); let rebuilt = SessionHost::replay_from(&prog, &roles, &grants, &journal).unwrap();
408 assert!(host.same_state_as(&rebuilt), "replay must reconstruct exact state");
409 let _ = original; }
412
413 #[test]
414 fn capability_gate_is_enforced() {
415 let prog = parse(
416 "protocol p v1;\nroles a, b;\nuse fs.read as reader;\nuse net.http;\non query from a -> send inform to a;\non inform from b -> send bye;\n",
417 )
418 .unwrap();
419 let mut host = SessionHost::new(&prog).unwrap();
421 let err = host.open("s1", "a").unwrap_err();
422 assert!(err.contains("capability gate"), "{err}");
423 assert!(SessionHost::new_gated(&prog, &["fs.read".into()])
425 .unwrap()
426 .open("s1", "a")
427 .is_err());
428 let mut host = SessionHost::new_gated(
430 &prog,
431 &["fs.read".into(), "net.http".into()],
432 )
433 .unwrap();
434 host.open("s1", "a").unwrap();
435 assert_eq!(host.session_count(), 1);
436 let cards = vec![
438 vec!["fs.read".to_string(), "net.http".to_string(), "acl.speak".to_string()],
439 vec!["acl.speak".to_string()],
440 ];
441 SessionHost::peer_satisfies(&cards[0])(&prog)
442 .expect("peer has all needed capabilities");
443 assert!(SessionHost::peer_satisfies(&cards[1])(&prog).is_err());
444 let prog2 = parse("protocol q v1;\nroles a,b;\nuse stdlib.fipa;\non query from a -> send inform to a;\non inform from b -> send bye;\n").unwrap();
446 SessionHost::new_gated(&prog2, &[]).expect("stdlib.* needs no grant");
447 }
448
449 #[test]
452 fn soak_many_sessions_and_events() {
453 let prog = parse(&PROG.replace("capacity 2;", "capacity 200;")).unwrap();
454 let mut host = SessionHost::new(&prog).unwrap();
455 let sessions: Vec<String> = (0..200).map(|i| format!("s{i}")).collect();
456 for id in &sessions {
457 host.open(id, "seller").unwrap();
458 }
459 for round in 0..25 {
460 for id in sessions.iter().cycle().take(200) {
461 let ev = if round == 0 {
462 event("buyer", Performative::Request, Some("(\"q\")"))
463 } else if round % 2 == 1 {
464 event("buyer", Performative::Accept, None)
465 } else {
466 event("buyer", Performative::Query, None)
467 };
468 let _ = host.deliver(id, ev);
469 }
470 }
471 assert_eq!(host.session_count(), 200);
472 assert_eq!(host.journal().len(), 200 * 25 + 200); let (roles, grants, journal) = host.journal_with_roles();
475 assert_eq!(roles.len(), 200);
476 let rebuilt = SessionHost::replay_from(&prog, &roles, &grants, &journal).unwrap();
477 assert!(
478 host.same_state_as(&rebuilt),
479 "soak replay must reconstruct exact state"
480 );
481 let proposes = host
484 .outbox()
485 .iter()
486 .filter(|(_, o)| o.performative == Performative::Propose)
487 .count();
488 assert_eq!(proposes, 200);
489 }
490
491 #[test]
492 fn journal_records_unhandled_events_too() {
493 let prog = parse(PROG).unwrap();
494 let mut host = SessionHost::new(&prog).unwrap();
495 host.open("s1", "buyer").unwrap();
496 host.deliver("s1", event("seller", Performative::Request, None)).unwrap();
498 assert_eq!(host.journal().len(), 2); }
500}
501
502#[cfg(test)]
503mod full_replay_tests {
504 use super::*;
505 use crate::runtime::StateValue;
506 use crate::protocol::parse;
507 use std::collections::BTreeMap;
508
509 #[test]
512 fn replay_reproduces_timer_and_await_and_close() {
513 let prog = parse(
514 "protocol p v1;\nroles a, b;\nstate fired: bool;\nstate bids: list;\nstate ready: bool;\non request from a { await 2 propose into bids within 60s as ready; send inform to a; }\non propose from b -> send bye;\non inform from b -> send bye;\nevery 1s as b while not fired -> set fired = true;\non bye from b -> send inform to b;\non bye from a -> send inform to a;\n",
515 )
516 .unwrap();
517 let mut host = SessionHost::new(&prog).unwrap();
518 host.open("s1", "b").unwrap();
519 host.deliver(
520 "s1",
521 Event::In {
522 from: "a".into(),
523 performative: crate::Performative::Request,
524 pattern: None,
525 fields: None,
526 },
527 )
528 .unwrap();
529 host.deliver(
530 "s1",
531 Event::In {
532 from: "a".into(),
533 performative: crate::Performative::Propose,
534 pattern: None,
535 fields: Some(BTreeMap::from([("who".into(), crate::runtime::FieldValue::Str("b1".into()))])),
536 },
537 )
538 .unwrap();
539 let outs1 = host.tick(1500);
540 host.close("s1").unwrap();
541
542 let (roles, grants, journal) = host.journal_with_roles();
543 let rebuilt = SessionHost::replay_from(&prog, &roles, &grants, &journal).unwrap();
544 assert_eq!(
547 rebuilt
548 .sessions
549 .get("s1")
550 .map(|_| ()) .is_none(),
552 true
553 );
554 assert_eq!(rebuilt.journal().len(), host.journal().len());
556 let orig_rt = host.sessions.get("s1");
558 assert!(orig_rt.is_none(), "closed session removed");
559 let _ = outs1;
560
561 let mut h2 = SessionHost::new(&prog).unwrap();
563 h2.open("s2", "b").unwrap();
564 h2.deliver(
565 "s2",
566 Event::In {
567 from: "a".into(),
568 performative: crate::Performative::Request,
569 pattern: None,
570 fields: None,
571 },
572 )
573 .unwrap();
574 h2.deliver(
575 "s2",
576 Event::In {
577 from: "a".into(),
578 performative: crate::Performative::Propose,
579 pattern: None,
580 fields: None,
581 },
582 )
583 .unwrap();
584 h2.tick(1000);
585 let (roles2, grants2, journal2) = h2.journal_with_roles();
586 let rebuilt2 = SessionHost::replay_from(&prog, &roles2, &grants2, &journal2).unwrap();
587 let a = h2.sessions.get("s2").unwrap();
588 let b = rebuilt2.sessions.get("s2").unwrap();
589 assert_eq!(a.states_snapshot().get("fired"), b.states_snapshot().get("fired"));
590 assert_eq!(
591 a.states_snapshot().get("ready"),
592 b.states_snapshot().get("ready")
593 );
594 assert_eq!(
595 a.states_snapshot().get("bids").cloned().unwrap(),
596 b.states_snapshot().get("bids").cloned().unwrap()
597 );
598 assert_eq!(a.transcript().len(), b.transcript().len());
599 assert_eq!(a.now_ms(), b.now_ms());
600 }
601}
602
603#[cfg(test)]
604mod concurrent_conversations_tests {
605 use super::*;
606 use crate::protocol::parse;
607 use crate::runtime::StateValue;
608
609 #[test]
612 fn concurrent_instances_have_independent_phases_and_states() {
613 let prog = parse(
614 "protocol p v1;\nroles a, b;\nphase start;\nphase accepted;\nstate n: int;\non inform {\"k\": $k} from a in start { set n = $k; enter accepted; }\non inform {\"k\": $k} from a in accepted { set n = n + $k; }\non inform from b -> send bye;\n",
615 )
616 .unwrap();
617 let mut host = SessionHost::new(&prog).unwrap();
618 host.open("s1", "b").unwrap();
619 host.open("s2", "b").unwrap();
620 host.deliver(
621 "s1",
622 Event::In {
623 from: "a".into(),
624 performative: crate::Performative::Inform,
625 pattern: None,
626 fields: Some(BTreeMap::from([(
627 "k".into(),
628 crate::runtime::FieldValue::Int(5),
629 )])),
630 },
631 )
632 .unwrap();
633 host.deliver(
635 "s2",
636 Event::In {
637 from: "a".into(),
638 performative: crate::Performative::Inform,
639 pattern: None,
640 fields: Some(BTreeMap::from([(
641 "k".into(),
642 crate::runtime::FieldValue::Int(7),
643 )])),
644 },
645 )
646 .unwrap();
647 let s1 = host.sessions.get("s1").unwrap();
648 let s2 = host.sessions.get("s2").unwrap();
649 assert_eq!(s1.states_snapshot().get("n"), Some(&StateValue::Int(5)));
652 assert_eq!(s2.states_snapshot().get("n"), Some(&StateValue::Int(7)));
653 assert_eq!(s1.now_phase(), "accepted");
654 assert_eq!(s2.now_phase(), "accepted");
655 host.deliver(
658 "s1",
659 Event::In {
660 from: "a".into(),
661 performative: crate::Performative::Inform,
662 pattern: None,
663 fields: Some(BTreeMap::from([(
664 "k".into(),
665 crate::runtime::FieldValue::Int(3),
666 )])),
667 },
668 )
669 .unwrap();
670 assert_eq!(
671 host.sessions.get("s1").unwrap().states_snapshot().get("n"),
672 Some(&StateValue::Int(8))
673 );
674 assert_eq!(
675 host.sessions.get("s2").unwrap().states_snapshot().get("n"),
676 Some(&StateValue::Int(7))
677 );
678 }
679}
680
681#[cfg(test)]
682mod ordered_open_replay_tests {
683 use super::*;
684 use crate::protocol::parse;
685
686 fn prog() -> crate::protocol::ProtocolProgram {
687 parse(
688 "protocol p v1;\nroles a, b;\non inform from a -> send bye;\non inform from b -> send bye;\n",
689 )
690 .unwrap()
691 }
692
693 fn prog_capacity1() -> crate::protocol::ProtocolProgram {
697 parse(
698 "protocol p v1;\nroles a, b;\ncapacity 1;\non inform from a -> send bye;\non inform from b -> send bye;\n",
699 )
700 .unwrap()
701 }
702
703 fn inform(from: &str) -> Event {
704 Event::In {
705 from: from.into(),
706 performative: crate::Performative::Inform,
707 pattern: None,
708 fields: None,
709 }
710 }
711
712 #[test]
714 fn replay_respects_capacity_and_reincarnation() {
715 let program = prog_capacity1();
716 let mut host = SessionHost::new(&program).unwrap();
717 assert_eq!(host.capacity, 1);
718 host.open("s1", "b").unwrap();
719 host.deliver("s1", inform("a")).unwrap();
720 host.close("s1").unwrap();
721 host.open("s2", "b").unwrap();
723 host.deliver("s2", inform("a")).unwrap();
724
725 let (roles, grants, journal) = host.journal_with_roles();
726 let rebuilt = SessionHost::replay_from(&program, &roles, &grants, &journal)
727 .expect("replay must respect the ordered lifecycle");
728 assert!(!rebuilt.is_open("s1"));
730 assert!(rebuilt.is_open("s2"));
731 assert_eq!(rebuilt.session_count(), 1);
732 assert_eq!(rebuilt.capacity, 1);
734 assert_eq!(rebuilt.journal().len(), host.journal().len());
735 }
736
737 #[test]
740 fn same_id_reincarnation_replays() {
741 let program = prog_capacity1();
742 let mut host = SessionHost::new(&program).unwrap();
743 assert_eq!(host.capacity, 1);
744 host.open("s1", "b").unwrap();
745 host.deliver("s1", inform("a")).unwrap();
746 host.close("s1").unwrap();
747 host.open("s1", "b").unwrap(); host.deliver("s1", inform("a")).unwrap();
749
750 let (roles, grants, journal) = host.journal_with_roles();
751 let rebuilt = SessionHost::replay_from(&program, &roles, &grants, &journal).unwrap();
752 assert!(rebuilt.is_open("s1"));
753 assert_eq!(rebuilt.session_count(), 1);
754 assert_eq!(rebuilt.capacity, 1);
755 assert_eq!(rebuilt.journal().len(), host.journal().len());
756 assert_eq!(roles.len(), 1);
758 }
759}