1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3#![warn(missing_debug_implementations)]
4#![warn(missing_docs)]
5
6pub mod station;
7
8use core::fmt;
9use guatiao::schema::{FieldBuilder, KindBuilder, SchemaBuilder};
10use guatiao::value::convert::{FromValue, ToValue, TryAsRef};
11use guatiao::value::wire::channel::{self, Received, Receiver};
12use guatiao::{Alloc, Bytes, Map, Value};
13
14pub const MAX_ID_BYTES: usize = 256;
19pub const MAX_TERMINAL_BYTES: usize = 1024 * 1024;
21pub const MAX_CONTROL_MESSAGE_BYTES: usize = 16 * 1024;
23pub const MAX_REASON_BYTES: usize = 64;
25const LIFECYCLE_CHANNEL: u64 = 1;
26const TERMINAL_CHANNEL: u64 = 2;
27const RESIZE_CHANNEL: u64 = 3;
28const CONTROL_CHANNEL: u64 = 4;
29const GAP_CHANNEL: u64 = 5;
30
31#[derive(Debug, Clone, PartialEq, Eq)]
33#[non_exhaustive]
34pub struct InvalidIdentity;
35
36impl fmt::Display for InvalidIdentity {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 f.write_str("identity must be non-empty, bounded, and contain no control characters")
39 }
40}
41
42impl core::error::Error for InvalidIdentity {}
43
44#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
46pub struct OperationId(String);
47
48#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
50pub struct MissionId(String);
51
52#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
54pub struct RunId(String);
55
56macro_rules! identity {
57 ($name:ident) => {
58 impl $name {
59 pub fn new(value: impl Into<String>) -> Result<Self, InvalidIdentity> {
61 let value = value.into();
62 if value.is_empty()
63 || value.len() > MAX_ID_BYTES
64 || value.chars().any(char::is_control)
65 {
66 return Err(InvalidIdentity);
67 }
68 Ok(Self(value))
69 }
70
71 pub fn as_str(&self) -> &str {
73 &self.0
74 }
75 }
76
77 impl fmt::Display for $name {
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 f.write_str(&self.0)
80 }
81 }
82 };
83}
84
85#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
87pub struct ControlId(String);
88
89identity!(OperationId);
90identity!(MissionId);
91identity!(RunId);
92identity!(ControlId);
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96#[non_exhaustive]
97pub enum RunState {
98 Queued,
100 Working,
102 Blocked,
104 Stalled,
106 Parked,
108 Quarantined,
111 Held,
114 Verifying,
117 Done,
119 Failed,
121 Abandoned,
123}
124
125impl RunState {
126 pub const fn as_str(self) -> &'static str {
128 match self {
129 Self::Queued => "queued",
130 Self::Working => "working",
131 Self::Blocked => "blocked",
132 Self::Stalled => "stalled",
133 Self::Parked => "parked",
134 Self::Quarantined => "quarantined",
135 Self::Held => "held",
136 Self::Verifying => "verifying",
137 Self::Done => "done",
138 Self::Failed => "failed",
139 Self::Abandoned => "abandoned",
140 }
141 }
142
143 pub fn parse(state: &str) -> Option<Self> {
145 Some(match state {
146 "queued" => Self::Queued,
147 "working" => Self::Working,
148 "blocked" => Self::Blocked,
149 "stalled" => Self::Stalled,
150 "parked" => Self::Parked,
151 "quarantined" => Self::Quarantined,
152 "held" => Self::Held,
153 "verifying" => Self::Verifying,
154 "done" => Self::Done,
155 "failed" => Self::Failed,
156 "abandoned" => Self::Abandoned,
157 _ => return None,
158 })
159 }
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
164#[non_exhaustive]
165pub enum ControlAction {
166 Cancel,
169 Retry,
172 Resume,
174 Interrupt,
176 Drop,
179 Reload,
181}
182
183impl ControlAction {
184 pub const ALL: [Self; 6] = [
186 Self::Cancel,
187 Self::Retry,
188 Self::Resume,
189 Self::Interrupt,
190 Self::Drop,
191 Self::Reload,
192 ];
193
194 pub const fn as_str(self) -> &'static str {
196 match self {
197 Self::Cancel => "cancel",
198 Self::Retry => "retry",
199 Self::Resume => "resume",
200 Self::Interrupt => "interrupt",
201 Self::Drop => "drop",
202 Self::Reload => "reload",
203 }
204 }
205
206 pub fn parse(action: &str) -> Option<Self> {
208 Self::ALL
209 .into_iter()
210 .find(|candidate| candidate.as_str() == action)
211 }
212}
213
214#[derive(Debug, Clone, PartialEq, Eq)]
216#[non_exhaustive]
217pub struct InvalidControl;
218
219impl fmt::Display for InvalidControl {
220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221 f.write_str("control fields must be non-empty, bounded and free of control characters")
222 }
223}
224
225impl core::error::Error for InvalidControl {}
226
227#[derive(Clone, PartialEq, Eq)]
232pub struct MissionControl {
233 control_id: ControlId,
234 operation_id: OperationId,
235 mission_id: MissionId,
236 run_id: Option<RunId>,
237 action: ControlAction,
238 agent: Option<String>,
239 message: Option<String>,
240}
241
242impl fmt::Debug for MissionControl {
243 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244 f.debug_struct("MissionControl")
245 .field("control_id", &self.control_id)
246 .field("operation_id", &self.operation_id)
247 .field("mission_id", &self.mission_id)
248 .field("run_id", &self.run_id)
249 .field("action", &self.action)
250 .field("agent", &self.agent)
251 .field(
252 "message",
253 &self
254 .message
255 .as_ref()
256 .map(|message| format!("[REDACTED; {} bytes]", message.len())),
257 )
258 .finish()
259 }
260}
261
262impl MissionControl {
263 pub fn new(
265 control_id: ControlId,
266 operation_id: OperationId,
267 mission_id: MissionId,
268 action: ControlAction,
269 ) -> Self {
270 Self {
271 control_id,
272 operation_id,
273 mission_id,
274 run_id: None,
275 action,
276 agent: None,
277 message: None,
278 }
279 }
280
281 #[must_use]
283 pub fn with_run(mut self, run_id: RunId) -> Self {
284 self.run_id = Some(run_id);
285 self
286 }
287
288 pub fn with_agent(mut self, agent: impl Into<String>) -> Result<Self, InvalidControl> {
295 let agent = agent.into();
296 if agent.trim().is_empty() || agent.len() > MAX_ID_BYTES || agent.contains(char::is_control)
297 {
298 return Err(InvalidControl);
299 }
300 self.agent = Some(agent);
301 Ok(self)
302 }
303
304 pub fn with_message(mut self, message: impl Into<String>) -> Result<Self, InvalidControl> {
310 let message = message.into();
311 if message.trim().is_empty() || message.len() > MAX_CONTROL_MESSAGE_BYTES {
312 return Err(InvalidControl);
313 }
314 self.message = Some(message);
315 Ok(self)
316 }
317
318 pub fn control_id(&self) -> &ControlId {
320 &self.control_id
321 }
322
323 pub fn operation_id(&self) -> &OperationId {
325 &self.operation_id
326 }
327
328 pub fn mission_id(&self) -> &MissionId {
330 &self.mission_id
331 }
332
333 pub fn run_id(&self) -> Option<&RunId> {
335 self.run_id.as_ref()
336 }
337
338 pub const fn action(&self) -> ControlAction {
340 self.action
341 }
342
343 pub fn agent(&self) -> Option<&str> {
345 self.agent.as_deref()
346 }
347
348 pub fn message(&self) -> Option<&str> {
350 self.message.as_deref()
351 }
352}
353
354#[derive(Debug, Clone, PartialEq, Eq)]
356pub struct RunSnapshot {
357 pub operation_id: OperationId,
359 pub mission_id: MissionId,
361 pub run_id: RunId,
363 pub state: RunState,
365 pub sequence: u64,
367}
368
369#[derive(Debug, Clone, PartialEq, Eq)]
371pub struct LifecycleEvent {
372 pub operation_id: OperationId,
374 pub mission_id: MissionId,
376 pub run_id: RunId,
378 pub state: RunState,
380 pub reason: Option<String>,
385 pub sequence: u64,
387}
388
389#[derive(Clone, PartialEq, Eq)]
391pub struct TerminalData {
392 run_id: RunId,
394 sequence: u64,
396 direction: TerminalDirection,
398 bytes: Vec<u8>,
400}
401
402impl core::fmt::Debug for TerminalData {
403 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
404 f.debug_struct("TerminalData")
405 .field("run_id", &self.run_id)
406 .field("sequence", &self.sequence)
407 .field("direction", &self.direction)
408 .field(
409 "bytes",
410 &format_args!("[REDACTED; {} bytes]", self.bytes.len()),
411 )
412 .finish()
413 }
414}
415
416impl TerminalData {
417 pub fn new(
419 run_id: RunId,
420 sequence: u64,
421 direction: TerminalDirection,
422 bytes: Vec<u8>,
423 ) -> Result<Self, FrameTooLarge> {
424 if bytes.len() > MAX_TERMINAL_BYTES {
425 return Err(FrameTooLarge);
426 }
427 Ok(Self {
428 run_id,
429 sequence,
430 direction,
431 bytes,
432 })
433 }
434
435 pub fn run_id(&self) -> &RunId {
437 &self.run_id
438 }
439
440 pub const fn sequence(&self) -> u64 {
442 self.sequence
443 }
444
445 pub const fn direction(&self) -> TerminalDirection {
447 self.direction
448 }
449
450 pub fn bytes(&self) -> &[u8] {
452 &self.bytes
453 }
454}
455
456#[derive(Debug, Clone, Copy, PartialEq, Eq)]
458#[non_exhaustive]
459pub enum TerminalDirection {
460 Output,
462 Input,
464}
465
466impl TerminalDirection {
467 fn as_str(self) -> &'static str {
468 match self {
469 Self::Output => "output",
470 Self::Input => "input",
471 }
472 }
473}
474
475#[derive(Debug, Clone, PartialEq, Eq)]
482pub struct TerminalGap {
483 run_id: RunId,
484 after: u64,
485 before: u64,
486}
487
488impl TerminalGap {
489 pub fn new(run_id: RunId, after: u64, before: u64) -> Result<Self, InvalidGap> {
491 if after.checked_add(1).is_none_or(|next| next >= before) {
492 return Err(InvalidGap);
493 }
494 Ok(Self {
495 run_id,
496 after,
497 before,
498 })
499 }
500
501 pub fn run_id(&self) -> &RunId {
503 &self.run_id
504 }
505
506 pub const fn after(&self) -> u64 {
508 self.after
509 }
510
511 pub const fn before(&self) -> u64 {
513 self.before
514 }
515}
516
517#[derive(Debug, Clone, Copy, PartialEq, Eq)]
519#[non_exhaustive]
520pub struct InvalidGap;
521
522impl fmt::Display for InvalidGap {
523 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524 f.write_str("a gap must have a sequence between its ends")
525 }
526}
527
528impl core::error::Error for InvalidGap {}
529
530pub fn gap_frames(gap: &TerminalGap) -> Result<(Vec<u8>, Vec<u8>), guatiao::value::ValueError> {
532 let schema = SchemaBuilder::new()
533 .field(FieldBuilder::new("run_id", KindBuilder::string()).required())
534 .field(FieldBuilder::new("after", KindBuilder::int()).required())
535 .field(FieldBuilder::new("before", KindBuilder::int()).required())
536 .finish()?;
537 let mut value = Map::new();
538 value.set("run_id", gap.run_id.as_str());
539 value.set("after", gap.after);
540 value.set("before", gap.before);
541 frames(GAP_CHANNEL, &schema, &value.into())
542}
543
544pub fn lifecycle_frames(
546 event: &LifecycleEvent,
547) -> Result<(Vec<u8>, Vec<u8>), guatiao::value::ValueError> {
548 let schema = SchemaBuilder::new()
549 .field(FieldBuilder::new("operation_id", KindBuilder::string()).required())
550 .field(FieldBuilder::new("mission_id", KindBuilder::string()).required())
551 .field(FieldBuilder::new("run_id", KindBuilder::string()).required())
552 .field(FieldBuilder::new("state", KindBuilder::string()).required())
553 .field(FieldBuilder::new("reason", KindBuilder::string()))
554 .field(FieldBuilder::new("sequence", KindBuilder::int()).required())
555 .finish()?;
556 let mut value = Map::new();
557 value.set("operation_id", event.operation_id.as_str());
558 value.set("mission_id", event.mission_id.as_str());
559 value.set("run_id", event.run_id.as_str());
560 value.set("state", event.state.as_str());
561 if let Some(reason) = &event.reason {
562 value.set("reason", reason.as_str());
563 }
564 value.set("sequence", event.sequence);
565 frames(LIFECYCLE_CHANNEL, &schema, &value.into())
566}
567
568pub fn terminal_frames(
570 event: &TerminalData,
571) -> Result<(Vec<u8>, Vec<u8>), guatiao::value::ValueError> {
572 let schema = SchemaBuilder::new()
573 .field(FieldBuilder::new("run_id", KindBuilder::string()).required())
574 .field(FieldBuilder::new("sequence", KindBuilder::int()).required())
575 .field(FieldBuilder::new("direction", KindBuilder::string()).required())
576 .field(FieldBuilder::new("bytes", KindBuilder::bytes()).required())
577 .finish()?;
578 let mut value = Map::new();
579 value.set("run_id", event.run_id.as_str());
580 value.set("sequence", event.sequence);
581 value.set("direction", event.direction.as_str());
582 value.set(
583 "bytes",
584 Bytes::from(event.bytes.clone()).to_value_in(Alloc::rust())?,
585 );
586 frames(TERMINAL_CHANNEL, &schema, &value.into())
587}
588
589pub fn resize_frames(
591 event: &TerminalResize,
592) -> Result<(Vec<u8>, Vec<u8>), guatiao::value::ValueError> {
593 let schema = SchemaBuilder::new()
594 .field(FieldBuilder::new("run_id", KindBuilder::string()).required())
595 .field(FieldBuilder::new("sequence", KindBuilder::int()).required())
596 .field(FieldBuilder::new("columns", KindBuilder::int()).required())
597 .field(FieldBuilder::new("rows", KindBuilder::int()).required())
598 .finish()?;
599 let mut value = Map::new();
600 value.set("run_id", event.run_id.as_str());
601 value.set("sequence", event.sequence);
602 value.set("columns", u64::from(event.columns));
603 value.set("rows", u64::from(event.rows));
604 frames(RESIZE_CHANNEL, &schema, &value.into())
605}
606
607pub fn control_frames(
609 control: &MissionControl,
610) -> Result<(Vec<u8>, Vec<u8>), guatiao::value::ValueError> {
611 let schema = SchemaBuilder::new()
612 .field(FieldBuilder::new("control_id", KindBuilder::string()).required())
613 .field(FieldBuilder::new("operation_id", KindBuilder::string()).required())
614 .field(FieldBuilder::new("mission_id", KindBuilder::string()).required())
615 .field(FieldBuilder::new("run_id", KindBuilder::string()))
616 .field(FieldBuilder::new("action", KindBuilder::string()).required())
617 .field(FieldBuilder::new("agent", KindBuilder::string()))
618 .field(FieldBuilder::new("message", KindBuilder::string()))
619 .finish()?;
620 let mut value = Map::new();
621 value.set("control_id", control.control_id.as_str());
622 value.set("operation_id", control.operation_id.as_str());
623 value.set("mission_id", control.mission_id.as_str());
624 if let Some(run_id) = &control.run_id {
625 value.set("run_id", run_id.as_str());
626 }
627 value.set("action", control.action.as_str());
628 if let Some(agent) = &control.agent {
629 value.set("agent", agent.as_str());
630 }
631 if let Some(message) = &control.message {
632 value.set("message", message.as_str());
633 }
634 frames(CONTROL_CHANNEL, &schema, &value.into())
635}
636
637#[derive(Debug, Clone, PartialEq, Eq)]
639pub enum IncomingFrame {
640 Lifecycle(LifecycleEvent),
642 Terminal(TerminalData),
644 Resize(TerminalResize),
646 Control(MissionControl),
648 Gap(TerminalGap),
650 Closed(u64),
652}
653
654#[derive(Debug, Clone, PartialEq, Eq)]
656#[non_exhaustive]
657pub struct FrameDecodeError(String);
658
659impl fmt::Display for FrameDecodeError {
660 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
661 f.write_str(&self.0)
662 }
663}
664
665impl core::error::Error for FrameDecodeError {}
666
667#[derive(Debug, Default)]
669pub struct FrameReceiver {
670 receiver: Receiver,
671}
672
673impl FrameReceiver {
674 pub fn new() -> Self {
676 Self::default()
677 }
678
679 pub fn accept(&mut self, bytes: &[u8]) -> Result<Option<IncomingFrame>, FrameDecodeError> {
681 match self
682 .receiver
683 .accept(bytes)
684 .map_err(|error| FrameDecodeError(error.to_string()))?
685 {
686 Received::Schema(_) => Ok(None),
687 Received::Closed(channel) => Ok(Some(IncomingFrame::Closed(channel))),
688 Received::Value { channel, value } if channel == LIFECYCLE_CHANNEL => {
689 let map = Map::try_from(value)
690 .map_err(|_| FrameDecodeError("lifecycle frame must be a map".into()))?;
691 let state = RunState::parse(&text(&map, "state")?)
692 .ok_or_else(|| FrameDecodeError("unknown lifecycle state".into()))?;
693 let event = LifecycleEvent {
694 operation_id: OperationId::new(text(&map, "operation_id")?)
695 .map_err(|error| FrameDecodeError(error.to_string()))?,
696 mission_id: MissionId::new(text(&map, "mission_id")?)
697 .map_err(|error| FrameDecodeError(error.to_string()))?,
698 run_id: RunId::new(text(&map, "run_id")?)
699 .map_err(|error| FrameDecodeError(error.to_string()))?,
700 state,
701 reason: optional_text(&map, "reason")?
702 .map(|reason| {
703 valid_reason(&reason)
704 .then_some(reason)
705 .ok_or_else(|| FrameDecodeError("invalid lifecycle reason".into()))
706 })
707 .transpose()?,
708 sequence: number(&map, "sequence")?,
709 };
710 Ok(Some(IncomingFrame::Lifecycle(event)))
711 }
712 Received::Value { channel, value } if channel == TERMINAL_CHANNEL => {
713 let map = Map::try_from(value)
714 .map_err(|_| FrameDecodeError("terminal frame must be a map".into()))?;
715 let run_id = RunId::new(text(&map, "run_id")?)
716 .map_err(|error| FrameDecodeError(error.to_string()))?;
717 let direction = match text(&map, "direction")?.as_str() {
718 "input" => TerminalDirection::Input,
719 "output" => TerminalDirection::Output,
720 _ => return Err(FrameDecodeError("unknown terminal direction".into())),
721 };
722 let value = map
723 .get("bytes")
724 .ok_or_else(|| FrameDecodeError("missing terminal bytes".into()))?;
725 let bytes = TryAsRef::<[u8]>::try_as_ref(value)
726 .ok_or_else(|| FrameDecodeError("terminal bytes have the wrong type".into()))?
727 .to_vec();
728 let data = TerminalData::new(run_id, number(&map, "sequence")?, direction, bytes)
729 .map_err(|error| FrameDecodeError(error.to_string()))?;
730 Ok(Some(IncomingFrame::Terminal(data)))
731 }
732 Received::Value { channel, value } if channel == RESIZE_CHANNEL => {
733 let map = Map::try_from(value)
734 .map_err(|_| FrameDecodeError("resize frame must be a map".into()))?;
735 let event = TerminalResize::new(
736 RunId::new(text(&map, "run_id")?)
737 .map_err(|error| FrameDecodeError(error.to_string()))?,
738 number(&map, "sequence")?,
739 u16::try_from(number(&map, "columns")?)
740 .map_err(|_| FrameDecodeError("columns are out of range".into()))?,
741 u16::try_from(number(&map, "rows")?)
742 .map_err(|_| FrameDecodeError("rows are out of range".into()))?,
743 )
744 .map_err(|error| FrameDecodeError(error.to_string()))?;
745 Ok(Some(IncomingFrame::Resize(event)))
746 }
747 Received::Value { channel, value } if channel == CONTROL_CHANNEL => {
748 let map = Map::try_from(value)
749 .map_err(|_| FrameDecodeError("control frame must be a map".into()))?;
750 Ok(Some(IncomingFrame::Control(decode_control(&map)?)))
751 }
752 Received::Value { channel, value } if channel == GAP_CHANNEL => {
753 let map = Map::try_from(value)
754 .map_err(|_| FrameDecodeError("gap frame must be a map".into()))?;
755 let gap = TerminalGap::new(
756 RunId::new(text(&map, "run_id")?)
757 .map_err(|error| FrameDecodeError(error.to_string()))?,
758 number(&map, "after")?,
759 number(&map, "before")?,
760 )
761 .map_err(|error| FrameDecodeError(error.to_string()))?;
762 Ok(Some(IncomingFrame::Gap(gap)))
763 }
764 Received::Value { channel, .. } => Err(FrameDecodeError(format!(
765 "unsupported Universal Exports channel {channel}"
766 ))),
767 }
768 }
769}
770
771pub fn valid_reason(reason: &str) -> bool {
774 !reason.is_empty()
775 && reason.len() <= MAX_REASON_BYTES
776 && reason.bytes().all(|byte| {
777 byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"-_.".contains(&byte)
778 })
779}
780
781fn text(map: &Map, key: &str) -> Result<String, FrameDecodeError> {
782 let value = map
783 .get(key)
784 .ok_or_else(|| FrameDecodeError(format!("missing {key}")))?;
785 String::from_value(value).map_err(|_| FrameDecodeError(format!("{key} must be text")))
786}
787
788fn number(map: &Map, key: &str) -> Result<u64, FrameDecodeError> {
789 let value = map
790 .get(key)
791 .ok_or_else(|| FrameDecodeError(format!("missing {key}")))?;
792 u64::from_value(value).map_err(|_| FrameDecodeError(format!("{key} must be a number")))
793}
794
795fn optional_text(map: &Map, key: &str) -> Result<Option<String>, FrameDecodeError> {
796 map.get(key)
797 .map(|value| {
798 String::from_value(value).map_err(|_| FrameDecodeError(format!("{key} must be text")))
799 })
800 .transpose()
801}
802
803fn decode_control(map: &Map) -> Result<MissionControl, FrameDecodeError> {
804 let invalid = |error: InvalidIdentity| FrameDecodeError(error.to_string());
805 let action = ControlAction::parse(&text(map, "action")?)
806 .ok_or_else(|| FrameDecodeError("unknown control action".into()))?;
807 let mut control = MissionControl::new(
808 ControlId::new(text(map, "control_id")?).map_err(invalid)?,
809 OperationId::new(text(map, "operation_id")?).map_err(invalid)?,
810 MissionId::new(text(map, "mission_id")?).map_err(invalid)?,
811 action,
812 );
813 if let Some(run_id) = optional_text(map, "run_id")? {
814 control = control.with_run(RunId::new(run_id).map_err(invalid)?);
815 }
816 let invalid_control = |error: InvalidControl| FrameDecodeError(error.to_string());
817 if let Some(agent) = optional_text(map, "agent")? {
818 control = control.with_agent(agent).map_err(invalid_control)?;
819 }
820 if let Some(message) = optional_text(map, "message")? {
821 control = control.with_message(message).map_err(invalid_control)?;
822 }
823 Ok(control)
824}
825
826fn frames(
827 channel_id: u64,
828 schema: &Value,
829 value: &Value,
830) -> Result<(Vec<u8>, Vec<u8>), guatiao::value::ValueError> {
831 Ok((
832 channel::announce(channel_id, schema)?,
833 channel::send(channel_id, value)?,
834 ))
835}
836
837#[derive(Debug, Clone, PartialEq, Eq)]
839pub struct TerminalResize {
840 run_id: RunId,
842 sequence: u64,
844 columns: u16,
846 rows: u16,
848}
849
850impl TerminalResize {
851 pub fn new(run_id: RunId, sequence: u64, columns: u16, rows: u16) -> Result<Self, InvalidSize> {
853 if columns == 0 || rows == 0 {
854 return Err(InvalidSize);
855 }
856 Ok(Self {
857 run_id,
858 sequence,
859 columns,
860 rows,
861 })
862 }
863
864 pub fn run_id(&self) -> &RunId {
866 &self.run_id
867 }
868
869 pub const fn sequence(&self) -> u64 {
871 self.sequence
872 }
873
874 pub const fn columns(&self) -> u16 {
876 self.columns
877 }
878
879 pub const fn rows(&self) -> u16 {
881 self.rows
882 }
883}
884
885#[derive(Debug, Clone, Copy, PartialEq, Eq)]
887#[non_exhaustive]
888pub struct FrameTooLarge;
889
890impl fmt::Display for FrameTooLarge {
891 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
892 f.write_str("terminal frame exceeds the protocol limit")
893 }
894}
895
896impl core::error::Error for FrameTooLarge {}
897
898#[derive(Debug, Clone, Copy, PartialEq, Eq)]
900#[non_exhaustive]
901pub struct InvalidSize;
902
903impl fmt::Display for InvalidSize {
904 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
905 f.write_str("terminal dimensions must be greater than zero")
906 }
907}
908
909impl core::error::Error for InvalidSize {}
910
911#[cfg(test)]
912mod tests {
913 use super::*;
914 use guatiao::TryAsRef;
915
916 #[test]
917 fn mission_and_provider_id_are_separate_identities() {
918 let snapshot = RunSnapshot {
919 operation_id: OperationId::new("ai6").unwrap(),
920 mission_id: MissionId::new("mission-42").unwrap(),
921 run_id: RunId::new("provider-id-abc").unwrap(),
922 state: RunState::Working,
923 sequence: 1,
924 };
925 assert_eq!(snapshot.mission_id.as_str(), "mission-42");
926 assert_eq!(snapshot.run_id.as_str(), "provider-id-abc");
927 }
928
929 #[test]
930 fn identities_reject_controls_and_unbounded_values() {
931 assert!(MissionId::new("mission\n42").is_err());
932 assert!(RunId::new("x".repeat(MAX_ID_BYTES + 1)).is_err());
933 }
934
935 #[test]
936 fn terminal_data_preserves_binary_and_enforces_bound() {
937 let run = RunId::new("provider-id").unwrap();
938 let data =
939 TerminalData::new(run.clone(), 1, TerminalDirection::Output, vec![0xff, 0x00]).unwrap();
940 assert_eq!(data.bytes(), [0xff, 0x00]);
941 assert!(format!("{data:?}").contains("[REDACTED; 2 bytes]"));
942 assert!(!format!("{data:?}").contains("ff00"));
943 assert!(
944 TerminalData::new(
945 run,
946 2,
947 TerminalDirection::Output,
948 vec![0; MAX_TERMINAL_BYTES + 1]
949 )
950 .is_err()
951 );
952 }
953
954 #[test]
955 fn resize_dimensions_must_be_nonzero() {
956 let run = RunId::new("provider-id").unwrap();
957 assert!(TerminalResize::new(run.clone(), 1, 0, 24).is_err());
958 assert!(TerminalResize::new(run, 1, 80, 24).is_ok());
959 }
960
961 #[test]
962 fn guatiao_frames_validate_lifecycle_and_keep_mission_distinct() {
963 use guatiao::value::wire::channel::{Received, Receiver};
964
965 let event = LifecycleEvent {
966 operation_id: OperationId::new("station-a").unwrap(),
967 mission_id: MissionId::new("mission-17").unwrap(),
968 run_id: RunId::new("provider-run-3").unwrap(),
969 state: RunState::Working,
970 reason: None,
971 sequence: 4,
972 };
973 let (schema, value) = lifecycle_frames(&event).unwrap();
974 let mut receiver = Receiver::new();
975 assert!(matches!(
976 receiver.accept(&schema).unwrap(),
977 Received::Schema(1)
978 ));
979 let Received::Value { channel: 1, value } = receiver.accept(&value).unwrap() else {
980 panic!("lifecycle channel must carry a schema-checked value");
981 };
982 let map: &Map = value.try_as_ref().unwrap();
983 assert_eq!(
984 <&str>::try_from(map.required("mission_id").unwrap()).unwrap(),
985 "mission-17"
986 );
987 assert_eq!(
988 <&str>::try_from(map.required("run_id").unwrap()).unwrap(),
989 "provider-run-3"
990 );
991 }
992
993 #[test]
994 fn guatiao_terminal_frames_preserve_non_utf8_bytes() {
995 use guatiao::value::wire::channel::{Received, Receiver};
996
997 let event = TerminalData::new(
998 RunId::new("provider-run-3").unwrap(),
999 5,
1000 TerminalDirection::Output,
1001 vec![0xff, 0x00, 0x80],
1002 )
1003 .unwrap();
1004 let (schema, value) = terminal_frames(&event).unwrap();
1005 let mut receiver = Receiver::new();
1006 receiver.accept(&schema).unwrap();
1007 let Received::Value { channel: 2, value } = receiver.accept(&value).unwrap() else {
1008 panic!("terminal channel must carry a schema-checked value");
1009 };
1010 let map: &Map = value.try_as_ref().unwrap();
1011 let bytes: &[u8] = map.required("bytes").unwrap().try_into().unwrap();
1012 assert_eq!(bytes, [0xff, 0x00, 0x80]);
1013 }
1014
1015 #[test]
1016 fn guatiao_receiver_refuses_malformed_and_unknown_frames() {
1017 use guatiao::value::wire::channel::Receiver;
1018
1019 let mut receiver = Receiver::new();
1020 assert!(receiver.accept(&[]).is_err());
1021 assert!(receiver.accept(&[0xff]).is_err());
1022 }
1023
1024 #[test]
1025 fn protocol_receiver_decodes_lifecycle_terminal_and_resize_frames() {
1026 let event = LifecycleEvent {
1027 operation_id: OperationId::new("station-a").unwrap(),
1028 mission_id: MissionId::new("mission-17").unwrap(),
1029 run_id: RunId::new("provider-run-3").unwrap(),
1030 state: RunState::Blocked,
1031 reason: None,
1032 sequence: 9,
1033 };
1034 let terminal = TerminalData::new(
1035 event.run_id.clone(),
1036 10,
1037 TerminalDirection::Output,
1038 vec![0xff, 0x00, 0x80],
1039 )
1040 .unwrap();
1041 let resize = TerminalResize::new(event.run_id.clone(), 11, 120, 40).unwrap();
1042 let (lifecycle_schema, lifecycle_value) = lifecycle_frames(&event).unwrap();
1043 let (terminal_schema, terminal_value) = terminal_frames(&terminal).unwrap();
1044 let (resize_schema, resize_value) = resize_frames(&resize).unwrap();
1045 let mut receiver = FrameReceiver::new();
1046
1047 assert_eq!(receiver.accept(&lifecycle_schema).unwrap(), None);
1048 assert_eq!(
1049 receiver.accept(&lifecycle_value).unwrap(),
1050 Some(IncomingFrame::Lifecycle(event))
1051 );
1052 assert_eq!(receiver.accept(&terminal_schema).unwrap(), None);
1053 assert_eq!(
1054 receiver.accept(&terminal_value).unwrap(),
1055 Some(IncomingFrame::Terminal(terminal))
1056 );
1057 assert_eq!(receiver.accept(&resize_schema).unwrap(), None);
1058 assert_eq!(
1059 receiver.accept(&resize_value).unwrap(),
1060 Some(IncomingFrame::Resize(resize))
1061 );
1062 }
1063
1064 #[test]
1065 fn a_parked_run_round_trips_through_the_receiver() {
1066 let event = LifecycleEvent {
1067 operation_id: OperationId::new("station-a").unwrap(),
1068 mission_id: MissionId::new("mission-17").unwrap(),
1069 run_id: RunId::new("provider-run-3").unwrap(),
1070 state: RunState::Parked,
1071 reason: None,
1072 sequence: 4,
1073 };
1074 let (schema, value) = lifecycle_frames(&event).unwrap();
1075 let mut receiver = FrameReceiver::new();
1076 assert_eq!(receiver.accept(&schema).unwrap(), None);
1077 assert_eq!(
1078 receiver.accept(&value).unwrap(),
1079 Some(IncomingFrame::Lifecycle(event))
1080 );
1081 }
1082
1083 #[test]
1084 fn a_quarantined_run_round_trips_and_matches_its_wire_vector() {
1085 let event = LifecycleEvent {
1086 operation_id: OperationId::new("station-a").unwrap(),
1087 mission_id: MissionId::new("mission-17").unwrap(),
1088 run_id: RunId::new("provider-run-3").unwrap(),
1089 state: RunState::Quarantined,
1090 reason: None,
1091 sequence: 4,
1092 };
1093 let (schema, value) = lifecycle_frames(&event).unwrap();
1094 let mut receiver = FrameReceiver::new();
1095 assert_eq!(receiver.accept(&schema).unwrap(), None);
1096 assert_eq!(
1097 receiver.accept(&value).unwrap(),
1098 Some(IncomingFrame::Lifecycle(event))
1099 );
1100 let hex = value
1101 .iter()
1102 .map(|byte| format!("{byte:02x}"))
1103 .collect::<String>();
1104 let expected = include_str!("../tests/vectors/frames.txt")
1105 .lines()
1106 .find_map(|line| line.strip_prefix("lifecycle_value_quarantined="))
1107 .unwrap();
1108 assert_eq!(hex, expected);
1109 }
1110
1111 #[test]
1112 fn a_run_waiting_for_green_ink_carries_its_reason_and_matches_its_wire_vector() {
1113 let event = LifecycleEvent {
1114 operation_id: OperationId::new("station-a").unwrap(),
1115 mission_id: MissionId::new("mission-17").unwrap(),
1116 run_id: RunId::new("provider-run-3").unwrap(),
1117 state: RunState::Blocked,
1118 reason: Some("green-ink".to_owned()),
1119 sequence: 4,
1120 };
1121 let (schema, value) = lifecycle_frames(&event).unwrap();
1122 let mut receiver = FrameReceiver::new();
1123 assert_eq!(receiver.accept(&schema).unwrap(), None);
1124 assert_eq!(
1125 receiver.accept(&value).unwrap(),
1126 Some(IncomingFrame::Lifecycle(event.clone()))
1127 );
1128 let hex = value
1129 .iter()
1130 .map(|byte| format!("{byte:02x}"))
1131 .collect::<String>();
1132 let expected = include_str!("../tests/vectors/frames.txt")
1133 .lines()
1134 .find_map(|line| line.strip_prefix("lifecycle_value_green_ink="))
1135 .unwrap();
1136 assert_eq!(hex, expected);
1137
1138 let forged = LifecycleEvent {
1139 reason: Some("Green Ink\n".to_owned()),
1140 ..event
1141 };
1142 let (_, value) = lifecycle_frames(&forged).unwrap();
1143 assert!(receiver.accept(&value).is_err(), "a reason must be a name");
1144 assert!(!valid_reason(&"x".repeat(MAX_REASON_BYTES + 1)));
1145 }
1146
1147 fn sample_gap() -> TerminalGap {
1148 TerminalGap::new(RunId::new("provider-run-3").unwrap(), 0, 5).unwrap()
1149 }
1150
1151 #[test]
1152 fn a_gap_decodes_as_it_was_made_and_needs_a_sequence_between_its_ends() {
1153 let gap = sample_gap();
1154 assert_eq!(gap.run_id().as_str(), "provider-run-3");
1155 assert_eq!((gap.after(), gap.before()), (0, 5));
1156 let (schema, value) = gap_frames(&gap).unwrap();
1157 let mut receiver = FrameReceiver::new();
1158 assert_eq!(receiver.accept(&schema).unwrap(), None);
1159 assert_eq!(
1160 receiver.accept(&value).unwrap(),
1161 Some(IncomingFrame::Gap(gap))
1162 );
1163 let run = || RunId::new("provider-run-3").unwrap();
1164 for (after, before) in [(5, 6), (6, 5), (5, 5), (u64::MAX, u64::MAX)] {
1165 assert_eq!(
1166 TerminalGap::new(run(), after, before),
1167 Err(InvalidGap),
1168 "{after}..{before}"
1169 );
1170 }
1171 assert!(TerminalGap::new(run(), 4, 6).is_ok());
1172 }
1173
1174 fn sample_control() -> MissionControl {
1175 MissionControl::new(
1176 ControlId::new("control-1").unwrap(),
1177 OperationId::new("station-a").unwrap(),
1178 MissionId::new("mission-17").unwrap(),
1179 ControlAction::Retry,
1180 )
1181 .with_run(RunId::new("provider-run-3").unwrap())
1182 .with_agent("008")
1183 .unwrap()
1184 }
1185
1186 #[test]
1187 fn a_control_round_trips_and_its_message_stays_out_of_debug_output() {
1188 let control = sample_control();
1189 let resume = MissionControl::new(
1190 ControlId::new("control-2").unwrap(),
1191 OperationId::new("station-a").unwrap(),
1192 MissionId::new("mission-17").unwrap(),
1193 ControlAction::Resume,
1194 )
1195 .with_message("carry on with the review")
1196 .unwrap();
1197 let mut receiver = FrameReceiver::new();
1198 for expected in [control, resume.clone()] {
1199 let (schema, value) = control_frames(&expected).unwrap();
1200 assert_eq!(receiver.accept(&schema).unwrap(), None);
1201 assert_eq!(
1202 receiver.accept(&value).unwrap(),
1203 Some(IncomingFrame::Control(expected))
1204 );
1205 }
1206 let debug = format!("{resume:?}");
1207 assert!(debug.contains("[REDACTED; 24 bytes]"));
1208 assert!(!debug.contains("carry on"));
1209 }
1210
1211 #[test]
1212 fn control_fields_are_bounded() {
1213 let control = sample_control();
1214 assert!(control.clone().with_agent("").is_err());
1215 assert!(control.clone().with_agent("00\n7").is_err());
1216 assert!(control.clone().with_message(" ").is_err());
1217 assert!(
1218 control
1219 .with_message("x".repeat(MAX_CONTROL_MESSAGE_BYTES + 1))
1220 .is_err()
1221 );
1222 assert_eq!(ControlAction::parse("pause"), None);
1223 for action in ControlAction::ALL {
1224 assert_eq!(ControlAction::parse(action.as_str()), Some(action));
1225 }
1226 }
1227
1228 #[test]
1229 fn every_run_state_round_trips_its_wire_spelling() {
1230 for state in [
1231 RunState::Queued,
1232 RunState::Working,
1233 RunState::Blocked,
1234 RunState::Stalled,
1235 RunState::Parked,
1236 RunState::Quarantined,
1237 RunState::Done,
1238 RunState::Failed,
1239 RunState::Abandoned,
1240 ] {
1241 assert_eq!(RunState::parse(state.as_str()), Some(state));
1242 }
1243 assert_eq!(RunState::parse("paused"), None);
1244 }
1245
1246 #[test]
1247 fn committed_wire_vectors_match_the_rust_encoder() {
1248 let event = LifecycleEvent {
1249 operation_id: OperationId::new("station-a").unwrap(),
1250 mission_id: MissionId::new("mission-17").unwrap(),
1251 run_id: RunId::new("provider-run-3").unwrap(),
1252 state: RunState::Working,
1253 reason: None,
1254 sequence: 4,
1255 };
1256 let terminal = TerminalData::new(
1257 RunId::new("provider-run-3").unwrap(),
1258 5,
1259 TerminalDirection::Output,
1260 vec![0xff, 0x00, 0x80],
1261 )
1262 .unwrap();
1263 let resize =
1264 TerminalResize::new(RunId::new("provider-run-3").unwrap(), 6, 120, 40).unwrap();
1265 let lifecycle_frames = lifecycle_frames(&event).unwrap();
1266 let terminal_frames = terminal_frames(&terminal).unwrap();
1267 let resize_frames = resize_frames(&resize).unwrap();
1268 let control_frames = control_frames(&sample_control()).unwrap();
1269 let gap_frames = gap_frames(&sample_gap()).unwrap();
1270 let expected = include_str!("../tests/vectors/frames.txt");
1271 for line in expected.lines() {
1272 let (name, encoded) = line.split_once('=').unwrap();
1273 let actual = match name {
1274 "lifecycle_schema" => &lifecycle_frames.0,
1275 "lifecycle_value" => &lifecycle_frames.1,
1276 "terminal_schema" => &terminal_frames.0,
1277 "terminal_value" => &terminal_frames.1,
1278 "resize_schema" => &resize_frames.0,
1279 "resize_value" => &resize_frames.1,
1280 "control_schema" => &control_frames.0,
1281 "control_value" => &control_frames.1,
1282 "gap_schema" => &gap_frames.0,
1283 "gap_value" => &gap_frames.1,
1284 "lifecycle_value_quarantined" | "lifecycle_value_green_ink" => continue,
1285 _ => panic!("unknown vector name"),
1286 };
1287 let actual = actual
1288 .iter()
1289 .map(|byte| format!("{byte:02x}"))
1290 .collect::<String>();
1291 assert_eq!(actual, encoded, "{name} must match the shared vector");
1292 }
1293 }
1294}