1 //! The session state machine.2 //!3 //! This is protocol.md section 6 as a table, with no I/O. The SDK owns the4 //! socket; this owns the rule about which frame may follow which.5 //!6 //! A phase is the last milestone that both peers agree on. `HELLO` means "the7 //! caller's hello is on the wire". `WELCOMED` means "the server's welcome is8 //! on the wire". Sending and receiving therefore advance the same phase, and9 //! the two sides cannot drift.10 11 use std::fmt;12 13 use crate::frame::Kind;14 15 /// Which end of the connection this is.16 #[derive(Clone, Copy, PartialEq, Eq, Debug)]17 pub enum Role {18 /// The core. Allocates stream ids and owns the jobs.19 Caller,20 /// The plugin. Answers and never allocates a stream id.21 Server,22 }23 24 /// How far the session has got.25 #[derive(Clone, Copy, PartialEq, Eq, Debug)]26 pub enum Phase {27 New,28 Hello,29 Welcomed,30 Catalogued,31 Loading,32 Ready,33 Draining,34 Closed,35 }36 37 /// A frame that the lifecycle does not allow here.38 #[derive(Clone, Copy, PartialEq, Eq, Debug)]39 pub struct OutOfOrder {40 pub role: Role,41 pub phase: Phase,42 pub kind: Kind,43 pub sent: bool,44 }45 46 /// Whether a frame moves the session table of protocol.md section 6.47 ///48 /// Job frames are not phases. A caller that fed a `done` to the session would49 /// move it out of `READY` and refuse every later `open`.50 pub const fn is_session(kind: Kind) -> bool {51 matches!(52 kind,53 Kind::Hello54 | Kind::Welcome55 | Kind::Catalogue56 | Kind::Grant57 | Kind::Ready58 | Kind::Open59 | Kind::Bye60 | Kind::Fatal61 )62 }63 64 impl fmt::Display for OutOfOrder {65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {66 let side = if self.sent { "send" } else { "receive" };67 write!(68 f,69 "cannot {side} {:?} in {:?} as {:?}",70 self.kind, self.phase, self.role71 )72 }73 }74 75 /// The lifecycle of one connection.76 #[derive(Clone, Copy, Debug)]77 pub struct Session {78 role: Role,79 phase: Phase,80 streams: u32,81 }82 83 impl Session {84 pub fn new(role: Role) -> Session {85 Session {86 role,87 phase: Phase::New,88 streams: 0,89 }90 }91 92 pub fn phase(self) -> Phase {93 self.phase94 }95 96 pub fn role(self) -> Role {97 self.role98 }99 100 /// How many job streams are open. `bye` drains these before the close.101 pub fn streams(self) -> u32 {102 self.streams103 }104 105 pub fn is_closed(self) -> bool {106 self.phase == Phase::Closed107 }108 109 /// Records a frame that this side is about to send.110 pub fn send(&mut self, kind: Kind) -> Result<(), OutOfOrder> {111 let next = match (self.role, self.phase, kind) {112 (_, _, Kind::Fatal) => Phase::Closed,113 114 (Role::Caller, Phase::New, Kind::Hello) => Phase::Hello,115 (Role::Caller, Phase::Catalogued, Kind::Grant) => Phase::Loading,116 (Role::Caller, Phase::Ready, Kind::Open) => Phase::Ready,117 (Role::Caller, Phase::Ready, Kind::Bye) => Phase::Draining,118 119 (Role::Server, Phase::Hello, Kind::Welcome) => Phase::Welcomed,120 (Role::Server, Phase::Welcomed, Kind::Catalogue) => Phase::Catalogued,121 // A server that needs nothing loads and answers at once, so `ready`122 // is legal from `CATALOGUED` as well as from `LOADING`.123 (Role::Server, Phase::Catalogued | Phase::Loading, Kind::Ready) => Phase::Ready,124 125 _ => return Err(self.refuse(kind, true)),126 };127 128 if kind == Kind::Open {129 self.streams += 1;130 }131 self.phase = next;132 self.close_if_drained(kind);133 Ok(())134 }135 136 /// Records a frame that this side has received.137 pub fn recv(&mut self, kind: Kind) -> Result<(), OutOfOrder> {138 let next = match (self.role, self.phase, kind) {139 (_, _, Kind::Fatal) => Phase::Closed,140 141 (Role::Server, Phase::New, Kind::Hello) => Phase::Hello,142 (Role::Server, Phase::Catalogued, Kind::Grant) => Phase::Loading,143 (Role::Server, Phase::Ready, Kind::Open) => Phase::Ready,144 (Role::Server, Phase::Ready, Kind::Bye) => Phase::Draining,145 146 (Role::Caller, Phase::Hello, Kind::Welcome) => Phase::Welcomed,147 (Role::Caller, Phase::Welcomed, Kind::Catalogue) => Phase::Catalogued,148 (Role::Caller, Phase::Catalogued | Phase::Loading, Kind::Ready) => Phase::Ready,149 150 _ => return Err(self.refuse(kind, false)),151 };152 153 if kind == Kind::Open {154 self.streams += 1;155 }156 self.phase = next;157 self.close_if_drained(kind);158 Ok(())159 }160 161 /// Takes back the count of an `open` whose frame never left.162 ///163 /// `send` counts the open before the write, so a failed write must undo164 /// that count. The phase does not move: an `open` never leaves `READY`.165 pub fn withdraw_stream(&mut self) {166 self.streams = self.streams.saturating_sub(1);167 }168 169 /// Leaves `DRAINING` at once when no job is open.170 fn close_if_drained(&mut self, kind: Kind) {171 if kind == Kind::Bye && self.streams == 0 {172 self.phase = Phase::Closed;173 }174 }175 176 /// Records the terminal frame that ends one stream.177 ///178 /// The session closes when the last open stream ends after `bye`.179 pub fn finish_stream(&mut self) {180 self.streams = self.streams.saturating_sub(1);181 if self.phase == Phase::Draining && self.streams == 0 {182 self.phase = Phase::Closed;183 }184 }185 186 fn refuse(self, kind: Kind, sent: bool) -> OutOfOrder {187 OutOfOrder {188 role: self.role,189 phase: self.phase,190 kind,191 sent,192 }193 }194 }