1#![forbid(unsafe_code)]
49#![warn(missing_docs)]
50
51use std::collections::BTreeSet;
52use std::error::Error as StdError;
53use std::fmt;
54use std::marker::PhantomData;
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
58pub enum Role {
59 Human,
61 Humanoid,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq, Hash)]
67pub struct Participant {
68 id: String,
69 role: Role,
70 adult_attested: bool,
71 independent_refusal: bool,
72}
73
74impl Participant {
75 pub fn adult_human(id: impl Into<String>) -> Result<Self, Error> {
78 Ok(Self {
79 id: required(id.into(), "participant id")?,
80 role: Role::Human,
81 adult_attested: true,
82 independent_refusal: true,
83 })
84 }
85
86 pub fn autonomous_humanoid(id: impl Into<String>) -> Result<Self, Error> {
89 Ok(Self {
90 id: required(id.into(), "participant id")?,
91 role: Role::Humanoid,
92 adult_attested: false,
93 independent_refusal: true,
94 })
95 }
96
97 pub fn unattested_human(id: impl Into<String>) -> Result<Self, Error> {
100 Ok(Self {
101 id: required(id.into(), "participant id")?,
102 role: Role::Human,
103 adult_attested: false,
104 independent_refusal: true,
105 })
106 }
107
108 pub fn non_autonomous_humanoid(id: impl Into<String>) -> Result<Self, Error> {
111 Ok(Self {
112 id: required(id.into(), "participant id")?,
113 role: Role::Humanoid,
114 adult_attested: false,
115 independent_refusal: false,
116 })
117 }
118
119 pub fn id(&self) -> &str {
121 &self.id
122 }
123
124 pub const fn role(&self) -> Role {
126 self.role
127 }
128
129 pub const fn adult_attested(&self) -> bool {
131 self.adult_attested
132 }
133
134 pub const fn independent_refusal(&self) -> bool {
136 self.independent_refusal
137 }
138}
139
140#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
145pub struct Activity(String);
146
147impl Activity {
148 pub fn new(id: impl Into<String>) -> Result<Self, Error> {
150 Ok(Self(required(id.into(), "activity id")?))
151 }
152
153 pub fn id(&self) -> &str {
155 &self.0
156 }
157}
158
159#[derive(Debug, Clone, PartialEq, Eq)]
164pub struct Consent {
165 participant_id: String,
166 allowed: BTreeSet<Activity>,
167}
168
169impl Consent {
170 pub fn new(
172 participant_id: impl Into<String>,
173 allowed: impl IntoIterator<Item = Activity>,
174 ) -> Result<Self, Error> {
175 Ok(Self {
176 participant_id: required(participant_id.into(), "participant id")?,
177 allowed: allowed.into_iter().collect(),
178 })
179 }
180
181 pub fn refuse_all(participant_id: impl Into<String>) -> Result<Self, Error> {
183 Self::new(participant_id, [])
184 }
185
186 pub fn participant_id(&self) -> &str {
188 &self.participant_id
189 }
190
191 pub fn allows(&self, activity: &Activity) -> bool {
193 self.allowed.contains(activity)
194 }
195
196 pub fn allowed(&self) -> impl Iterator<Item = &Activity> {
198 self.allowed.iter()
199 }
200}
201
202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub struct SafetyChecklist {
205 pub human_capacity_confirmed: bool,
207 pub emergency_stop_reachable: bool,
209 pub force_and_speed_limits_enabled: bool,
211 pub collision_detection_enabled: bool,
213 pub privacy_acknowledged: bool,
215}
216
217impl SafetyChecklist {
218 pub const fn all_confirmed() -> Self {
220 Self {
221 human_capacity_confirmed: true,
222 emergency_stop_reachable: true,
223 force_and_speed_limits_enabled: true,
224 collision_detection_enabled: true,
225 privacy_acknowledged: true,
226 }
227 }
228
229 pub const fn none_confirmed() -> Self {
231 Self {
232 human_capacity_confirmed: false,
233 emergency_stop_reachable: false,
234 force_and_speed_limits_enabled: false,
235 collision_detection_enabled: false,
236 privacy_acknowledged: false,
237 }
238 }
239
240 pub const fn is_complete(self) -> bool {
242 self.human_capacity_confirmed
243 && self.emergency_stop_reachable
244 && self.force_and_speed_limits_enabled
245 && self.collision_detection_enabled
246 && self.privacy_acknowledged
247 }
248}
249
250#[derive(Debug, Clone, PartialEq, Eq)]
252pub struct SessionPlan {
253 human: Participant,
254 humanoid: Participant,
255}
256
257impl SessionPlan {
258 pub fn new(first: Participant, second: Participant) -> Result<Self, Error> {
261 if first.id == second.id {
262 return Err(Error::DuplicateParticipant(first.id));
263 }
264 let (human, humanoid) = match (first.role, second.role) {
265 (Role::Human, Role::Humanoid) => (first, second),
266 (Role::Humanoid, Role::Human) => (second, first),
267 _ => return Err(Error::RequiredRoles),
268 };
269 if !human.adult_attested {
270 return Err(Error::AdultAttestationRequired);
271 }
272 if !human.independent_refusal || !humanoid.independent_refusal {
273 return Err(Error::IndependentRefusalRequired);
274 }
275 Ok(Self { human, humanoid })
276 }
277
278 pub const fn human(&self) -> &Participant {
280 &self.human
281 }
282
283 pub const fn humanoid(&self) -> &Participant {
285 &self.humanoid
286 }
287
288 pub fn activate(
291 self,
292 first_consent: Consent,
293 second_consent: Consent,
294 checklist: SafetyChecklist,
295 ) -> Result<ActiveSession, Error> {
296 if !checklist.is_complete() {
297 return Err(Error::IncompleteSafetyChecklist);
298 }
299 let (human_consent, humanoid_consent) = if first_consent.participant_id == self.human.id
300 && second_consent.participant_id == self.humanoid.id
301 {
302 (first_consent, second_consent)
303 } else if second_consent.participant_id == self.human.id
304 && first_consent.participant_id == self.humanoid.id
305 {
306 (second_consent, first_consent)
307 } else {
308 return Err(Error::ConsentParticipantMismatch);
309 };
310 Ok(ActiveSession {
311 human: self.human,
312 humanoid: self.humanoid,
313 human_consent,
314 humanoid_consent,
315 status: SessionStatus::Active,
316 event_sequence: 0,
317 })
318 }
319}
320
321#[derive(Debug, Clone, PartialEq, Eq)]
323pub enum SessionStatus {
324 Active,
326 ConsentWithdrawn {
328 by: String,
330 },
331 EmergencyStopped {
333 by: String,
335 },
336 Completed,
338}
339
340impl SessionStatus {
341 pub const fn is_active(&self) -> bool {
343 matches!(self, Self::Active)
344 }
345}
346
347#[derive(Debug)]
349pub struct Authorization<'a> {
350 activity: &'a Activity,
351 sequence: u64,
352 session_borrow: PhantomData<&'a mut ActiveSession>,
353}
354
355impl Authorization<'_> {
356 pub const fn activity(&self) -> &Activity {
358 self.activity
359 }
360
361 pub const fn sequence(&self) -> u64 {
363 self.sequence
364 }
365}
366
367#[derive(Debug)]
369pub struct ActiveSession {
370 human: Participant,
371 humanoid: Participant,
372 human_consent: Consent,
373 humanoid_consent: Consent,
374 status: SessionStatus,
375 event_sequence: u64,
376}
377
378impl ActiveSession {
379 pub const fn status(&self) -> &SessionStatus {
381 &self.status
382 }
383
384 pub fn mutually_allows(&self, activity: &Activity) -> bool {
386 self.status.is_active()
387 && self.human_consent.allows(activity)
388 && self.humanoid_consent.allows(activity)
389 }
390
391 pub fn authorize<R>(
398 &mut self,
399 activity: &Activity,
400 operation: impl for<'a> FnOnce(Authorization<'a>) -> R,
401 ) -> Result<R, Error> {
402 if !self.status.is_active() {
403 return Err(Error::SessionNotActive);
404 }
405 if !self.human_consent.allows(activity) {
406 return Err(Error::ActivityNotAllowed {
407 participant: self.human.id.clone(),
408 activity: activity.id().to_owned(),
409 });
410 }
411 if !self.humanoid_consent.allows(activity) {
412 return Err(Error::ActivityNotAllowed {
413 participant: self.humanoid.id.clone(),
414 activity: activity.id().to_owned(),
415 });
416 }
417 self.event_sequence = self
418 .event_sequence
419 .checked_add(1)
420 .ok_or(Error::SequenceOverflow)?;
421 Ok(operation(Authorization {
422 activity,
423 sequence: self.event_sequence,
424 session_borrow: PhantomData,
425 }))
426 }
427
428 pub fn withdraw(&mut self, participant_id: &str) -> Result<(), Error> {
431 self.ensure_participant(participant_id)?;
432 if !self.status.is_active() {
433 return Err(Error::SessionNotActive);
434 }
435 self.status = SessionStatus::ConsentWithdrawn {
436 by: participant_id.to_owned(),
437 };
438 Ok(())
439 }
440
441 pub fn emergency_stop(&mut self, source: impl Into<String>) -> Result<(), Error> {
443 let source = required(source.into(), "emergency stop source")?;
444 if !self.status.is_active() {
445 return Err(Error::SessionNotActive);
446 }
447 self.status = SessionStatus::EmergencyStopped { by: source };
448 Ok(())
449 }
450
451 pub fn complete(&mut self) -> Result<(), Error> {
453 if !self.status.is_active() {
454 return Err(Error::SessionNotActive);
455 }
456 self.status = SessionStatus::Completed;
457 Ok(())
458 }
459
460 fn ensure_participant(&self, participant_id: &str) -> Result<(), Error> {
461 if participant_id == self.human.id || participant_id == self.humanoid.id {
462 Ok(())
463 } else {
464 Err(Error::UnknownParticipant(participant_id.to_owned()))
465 }
466 }
467}
468
469#[derive(Debug, Clone, PartialEq, Eq)]
471#[non_exhaustive]
472pub enum Error {
473 EmptyField(&'static str),
475 DuplicateParticipant(String),
477 RequiredRoles,
479 AdultAttestationRequired,
481 IndependentRefusalRequired,
483 ConsentParticipantMismatch,
485 IncompleteSafetyChecklist,
487 SessionNotActive,
489 ActivityNotAllowed {
491 participant: String,
493 activity: String,
495 },
496 UnknownParticipant(String),
498 SequenceOverflow,
500}
501
502impl fmt::Display for Error {
503 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504 match self {
505 Self::EmptyField(field) => write!(f, "{field} cannot be empty"),
506 Self::DuplicateParticipant(id) => write!(f, "duplicate participant ID: {id}"),
507 Self::RequiredRoles => f.write_str("session requires one human and one humanoid"),
508 Self::AdultAttestationRequired => f.write_str("adult human attestation is required"),
509 Self::IndependentRefusalRequired => {
510 f.write_str("both participants must be able to independently refuse")
511 }
512 Self::ConsentParticipantMismatch => {
513 f.write_str("consent records do not match planned participants")
514 }
515 Self::IncompleteSafetyChecklist => {
516 f.write_str("every mandatory safety check must be confirmed")
517 }
518 Self::SessionNotActive => f.write_str("session is not active"),
519 Self::ActivityNotAllowed {
520 participant,
521 activity,
522 } => write!(
523 f,
524 "participant {participant} did not allow activity {activity}"
525 ),
526 Self::UnknownParticipant(id) => write!(f, "unknown participant: {id}"),
527 Self::SequenceOverflow => f.write_str("authorization sequence overflow"),
528 }
529 }
530}
531
532impl StdError for Error {}
533
534fn required(value: String, field: &'static str) -> Result<String, Error> {
535 if value.trim().is_empty() {
536 Err(Error::EmptyField(field))
537 } else {
538 Ok(value)
539 }
540}
541
542#[cfg(test)]
543mod tests {
544 use super::*;
545
546 fn activity() -> Activity {
547 Activity::new("affection-v1").unwrap()
548 }
549
550 fn plan() -> SessionPlan {
551 SessionPlan::new(
552 Participant::adult_human("h").unwrap(),
553 Participant::autonomous_humanoid("r").unwrap(),
554 )
555 .unwrap()
556 }
557
558 fn active_with(human_allows: bool, robot_allows: bool) -> ActiveSession {
559 let act = activity();
560 plan()
561 .activate(
562 Consent::new("h", human_allows.then_some(act.clone())).unwrap(),
563 Consent::new("r", robot_allows.then_some(act)).unwrap(),
564 SafetyChecklist::all_confirmed(),
565 )
566 .unwrap()
567 }
568
569 #[test]
570 fn adult_attestation_is_mandatory() {
571 let result = SessionPlan::new(
572 Participant::unattested_human("h").unwrap(),
573 Participant::autonomous_humanoid("r").unwrap(),
574 );
575 assert!(matches!(result, Err(Error::AdultAttestationRequired)));
576 }
577
578 #[test]
579 fn independent_humanoid_refusal_is_mandatory() {
580 let result = SessionPlan::new(
581 Participant::adult_human("h").unwrap(),
582 Participant::non_autonomous_humanoid("r").unwrap(),
583 );
584 assert!(matches!(result, Err(Error::IndependentRefusalRequired)));
585 }
586
587 #[test]
588 fn every_safety_check_is_mandatory() {
589 let act = activity();
590 let result = plan().activate(
591 Consent::new("h", [act.clone()]).unwrap(),
592 Consent::new("r", [act]).unwrap(),
593 SafetyChecklist::none_confirmed(),
594 );
595 assert!(matches!(result, Err(Error::IncompleteSafetyChecklist)));
596 }
597
598 #[test]
599 fn mutual_explicit_consent_authorizes_bounded_operation() {
600 let mut session = active_with(true, true);
601 let act = activity();
602 let observed = session
603 .authorize(&act, |authorization| {
604 (
605 authorization.activity().id().to_owned(),
606 authorization.sequence(),
607 )
608 })
609 .unwrap();
610 assert_eq!(observed, ("affection-v1".to_owned(), 1));
611 assert_eq!(session.authorize(&act, |a| a.sequence()).unwrap(), 2);
612 }
613
614 #[test]
615 fn either_participants_absence_of_consent_blocks() {
616 let act = activity();
617 let mut human_refuses = active_with(false, true);
618 assert!(matches!(
619 human_refuses.authorize(&act, |_| ()),
620 Err(Error::ActivityNotAllowed { participant, .. }) if participant == "h"
621 ));
622 let mut robot_refuses = active_with(true, false);
623 assert!(matches!(
624 robot_refuses.authorize(&act, |_| ()),
625 Err(Error::ActivityNotAllowed { participant, .. }) if participant == "r"
626 ));
627 }
628
629 #[test]
630 fn withdrawal_immediately_and_irreversibly_blocks() {
631 let act = activity();
632 let mut session = active_with(true, true);
633 session.withdraw("r").unwrap();
634 assert_eq!(
635 session.status(),
636 &SessionStatus::ConsentWithdrawn { by: "r".to_owned() }
637 );
638 assert!(matches!(
639 session.authorize(&act, |_| ()),
640 Err(Error::SessionNotActive)
641 ));
642 assert!(matches!(session.complete(), Err(Error::SessionNotActive)));
643 }
644
645 #[test]
646 fn emergency_stop_is_irreversible() {
647 let act = activity();
648 let mut session = active_with(true, true);
649 session.emergency_stop("physical-button").unwrap();
650 assert_eq!(
651 session.status(),
652 &SessionStatus::EmergencyStopped {
653 by: "physical-button".to_owned()
654 }
655 );
656 assert!(matches!(
657 session.authorize(&act, |_| ()),
658 Err(Error::SessionNotActive)
659 ));
660 }
661
662 #[test]
663 fn normal_completion_prevents_future_authorization() {
664 let act = activity();
665 let mut session = active_with(true, true);
666 session.complete().unwrap();
667 assert_eq!(session.status(), &SessionStatus::Completed);
668 assert!(matches!(
669 session.authorize(&act, |_| ()),
670 Err(Error::SessionNotActive)
671 ));
672 }
673
674 #[test]
675 fn consent_records_must_match_both_participants() {
676 let result = plan().activate(
677 Consent::refuse_all("h").unwrap(),
678 Consent::refuse_all("someone-else").unwrap(),
679 SafetyChecklist::all_confirmed(),
680 );
681 assert!(matches!(result, Err(Error::ConsentParticipantMismatch)));
682 }
683}