crates/edge/proto/src/client.rs 43.4 KiB 1281 lines Raw
1 //! The caller half of the wire.2 //!3 //! One reader thread owns the socket and routes frames to the inbox of their4 //! stream. A caller therefore never waits for a frame that the server is5 //! waiting to send: the reader is always reading. Protocol.md section 8, rule 2.6 //!7 //! The caller is synchronous. `next` blocks the thread that reads one job, and8 //! a pool of those threads is the whole concurrency model of the core.9 10 use std::collections::{BTreeSet, HashMap, VecDeque};11 use std::io;12 use std::os::fd::{AsFd, BorrowedFd, OwnedFd};13 use std::os::unix::net::UnixStream;14 use std::sync::{Arc, Condvar, Mutex, MutexGuard};15 use std::thread::{self, JoinHandle};16 use std::time::{Duration, Instant};17 18 use crate::body::{self, Body, Catalogue, Grant, Ready, Refusal, Welcome};19 use crate::fd::{recv_frame, send_frame};20 use crate::frame::{Header, Kind};21 use crate::session::{Role, Session};22 23 /// The highest version this build speaks; Wire 1 peers still negotiate down.24 const PROTOCOL_VERSION: u32 = 2;25 const MIN_PROTOCOL_VERSION: u32 = 1;26 27 /// One frame that a job can see.28 #[derive(Debug)]29 pub enum Item {30     /// The server accepted the job.31     Accepted(Option<u32>),32     /// One chunk of a channel.33     Event {34         /// Channel name, as the capability declares it.35         ch: String,36         /// MIME type of this chunk.37         mime: String,38         /// The bytes.39         data: Vec<u8>,40     },41     /// The job ended. Descriptors are the ones the terminal frame carried.42     Done(body::Done, Vec<OwnedFd>),43     /// The server refused the job before it spent anything.44     Reject(Refusal),45 }46 47 /// A file that a cache lookup returned. The core keeps the read lease; this is48 /// a duplicate for the plugin to restore.49 pub struct CacheFile {50     pub key: [u8; 32],51     pub lease_id: u64,52     pub bytes: u64,53     pub crc32c: u32,54     pub token_count: u64,55     pub tier: String,56     pub file: OwnedFd,57 }58 59 /// A writable temp file that a cache reserve granted.60 pub struct CacheWrite {61     pub lease_id: u64,62     pub max_bytes: u64,63     pub tier: String,64     pub file: OwnedFd,65 }66 67 /// The core's cache handler. It lives outside this leaf crate so the wire68 /// remains independent of the storage engine.69 pub trait CacheHost: Send + Sync {70     fn lookup(71         &self,72         session: u64,73         request: &body::CacheLookup,74     ) -> Result<Option<CacheFile>, String>;75 76     fn release(&self, session: u64, request: &body::CacheRelease);77 78     fn reserve(&self, session: u64, request: &body::CacheReserve) -> Result<CacheWrite, String>;79 80     fn commit(&self, session: u64, request: &body::CacheCommit);81 82     /// The binding is going away, with or without a cooperative close. A host83     /// that keeps leases outside the wire must drop them here.84     fn closed(&self, _session: u64) {}85 }86 87 /// A peer that this process started. Every frame it sends is one `open`.88 pub struct Peer {89     inner: Arc<Inner>,90     reader: Option<JoinHandle<io::Result<()>>>,91 }92 93 struct Inner {94     out: Mutex<UnixStream>,95     /// The socket as the owner saw it. A drop shuts it down through this96     /// handle, because the reader thread holds the only other reference and97     /// cannot see an end that its own descriptor keeps open.98     halt: UnixStream,99     streams: Mutex<Streams>,100     shared: Mutex<Shared>,101     wake: Condvar,102     cache: Mutex<Option<CacheBinding>>,103     cache_flushed: Mutex<Option<body::CacheFlushed>>,104 }105 106 /// The open streams, and the allocator that names them.107 ///108 /// One mutex covers both because an identifier is only reusable once its109 /// stream has left the map. Splitting them would let a reader retire an id110 /// between the allocator's choice and the map's insert.111 struct Streams {112     open: HashMap<u16, Arc<Inbox>>,113     ids: Ids,114 }115 116 /// Stream identifiers: one pass through the whole range, then reuse.117 ///118 /// Zero is the session and is never handed out. A job's id returns to `free`119 /// only when its terminal frame has been received, so a resident model does120 /// not have to reconnect after 65,535 jobs.121 struct Ids {122     next: u32,123     free: BTreeSet<u16>,124 }125 126 impl Ids {127     fn new() -> Ids {128         Ids {129             next: 1,130             free: BTreeSet::new(),131         }132     }133 134     /// The next id, or an error when every id is open.135     fn take(&mut self) -> io::Result<u16> {136         if self.next <= u32::from(u16::MAX) {137             let id = u16::try_from(self.next).unwrap_or(u16::MAX);138             self.next += 1;139             return Ok(id);140         }141         self.free142             .pop_first()143             .ok_or_else(|| io::Error::other("every stream id is open"))144     }145 146     /// Makes an id available again.147     ///148     /// A terminal frame was received, or the open never reached the wire.149     /// Both mean that no frame can arrive for this id from this point on.150     fn release(&mut self, id: u16) {151         if id != 0 {152             self.free.insert(id);153         }154     }155 }156 157 /// A handle to the session, for a caller that must reach a stream that another158 /// thread owns.159 ///160 /// Cancelling a job is a frame, not a call on the job object: the thread that161 /// streams a job blocks on `next`, and the thread that wants it to stop is a162 /// different one.163 #[derive(Clone)]164 pub struct Handle {165     inner: Arc<Inner>,166 }167 168 struct CacheBinding {169     session: u64,170     host: Arc<dyn CacheHost>,171 }172 173 impl Drop for CacheBinding {174     fn drop(&mut self) {175         self.host.closed(self.session);176     }177 }178 179 /// The state that the handshake fills in.180 struct Shared {181     session: Session,182     welcome: Option<Welcome>,183     catalogue: Option<Catalogue>,184     ready: Option<Ready>,185     fatal: Option<Refusal>,186 }187 188 /// Cache frames are legal only after a Wire 2 welcome and a declared cache.189 fn cache_allowed(shared: &Shared) -> bool {190     shared.welcome.is_some_and(|welcome| welcome.v == 2)191         && shared192             .catalogue193             .as_ref()194             .is_some_and(|catalogue| catalogue.cache.is_some())195 }196 197 /// Where one job is in `open -> (accept | reject) -> done`.198 #[derive(Clone, Copy, PartialEq, Eq, Debug)]199 enum JobPhase {200     Open,201     Active,202     Ended,203 }204 205 /// What one job has seen but not yet consumed.206 struct Queue {207     items: VecDeque<Item>,208     phase: JobPhase,209     ended: bool,210     /// Total bytes of `event` bodies seen, which is the caller's credit base.211     received: u64,212     /// The absolute watermark that this stream may reach. An `event` that213     /// crosses it is a credit violation and ends the stream.214     window: u64,215 }216 217 impl Drop for Peer {218     /// Ends the session when the owner drops the peer without `close`.219     ///220     /// The reader thread owns the socket it reads. Without this shutdown, the221     /// descriptor count never reaches zero and the plugin waits for an end222     /// that the caller already intends: a shutdown becomes a grace-period223     /// timeout instead of a close.224     fn drop(&mut self) {225         let _ = self.inner.halt.shutdown(std::net::Shutdown::Both);226         if let Some(reader) = self.reader.take() {227             let _ = reader.join();228         }229     }230 }231 232 impl Peer {233     /// Starts the reader and performs the handshake.234     ///235     /// `wait` is the whole handshake deadline. It is a parameter because the236     /// core decides it from the model's intent, and the wire crate has no237     /// policy.238     pub fn connect(socket: UnixStream, id: &str, wait: Duration) -> io::Result<Peer> {239         let inner = Arc::new(Inner {240             out: Mutex::new(socket.try_clone()?),241             halt: socket.try_clone()?,242             streams: Mutex::new(Streams {243                 open: HashMap::new(),244                 ids: Ids::new(),245             }),246             shared: Mutex::new(Shared {247                 session: Session::new(Role::Caller),248                 welcome: None,249                 catalogue: None,250                 ready: None,251                 fatal: None,252             }),253             wake: Condvar::new(),254             cache: Mutex::new(None),255             cache_flushed: Mutex::new(None),256         });257 258         let hello = Body::Hello(body::Hello {259             v: body::VersionRange {260                 min: MIN_PROTOCOL_VERSION,261                 max: PROTOCOL_VERSION,262             },263             role: body::Role::Call,264             id: id.to_string(),265         });266         write_body(&inner, 0, &hello, &[])?;267         lock(&inner.shared)268             .session269             .send(Kind::Hello)270             .map_err(out_of_order)?;271 272         let reading = inner.clone();273         let reader = thread::spawn(move || {274             read_loop(&socket, &reading);275             Ok::<(), io::Error>(())276         });277 278         let peer = Peer {279             inner,280             reader: Some(reader),281         };282         // A welcome with another version cannot be followed by a catalogue283         // that this caller understands. Stop waiting as soon as it arrives so284         // the core can classify the failure instead of spending the whole285         // handshake budget on it.286         peer.wait_until(wait, |shared| {287             shared.catalogue.is_some()288                 || shared.welcome.is_some_and(|welcome| {289                     !(MIN_PROTOCOL_VERSION..=PROTOCOL_VERSION).contains(&welcome.v)290                 })291         })?;292         Ok(peer)293     }294 295     /// Whether the server welcomed the one version this build speaks.296     pub fn compatible(&self) -> bool {297         self.welcome()298             .is_some_and(|welcome| (MIN_PROTOCOL_VERSION..=PROTOCOL_VERSION).contains(&welcome.v))299     }300 301     /// The negotiated wire version. Cache frames are legal only at 2.302     pub fn version(&self) -> Option<u32> {303         self.welcome().map(|welcome| welcome.v)304     }305 306     /// The version and the limit that the server reported.307     ///308     /// `None` only before the handshake finishes, which `connect` waits for.309     pub fn welcome(&self) -> Option<Welcome> {310         lock(&self.inner.shared).welcome311     }312 313     /// Installs the one cache handler for this peer. Called before `grant`.314     pub fn install_cache(&self, session: u64, host: Arc<dyn CacheHost>) {315         *lock(&self.inner.cache) = Some(CacheBinding { session, host });316     }317 318     /// Removes the cache binding and lets its `closed` hook retire the leases.319     /// A conformance runner uses this before it deletes its temporary store.320     pub fn uninstall_cache(&self) {321         *lock(&self.inner.cache) = None;322     }323 324     /// Sends `cache_flush` and waits for the plugin's answer.325     pub fn flush_cache(&self, budget: Duration) -> io::Result<body::CacheFlushed> {326         if self.version() != Some(2)327             || !self328                 .catalogue()329                 .is_some_and(|catalogue| catalogue.cache.is_some())330         {331             return Err(io::Error::other("the peer did not declare a Wire 2 cache"));332         }333         *lock(&self.inner.cache_flushed) = None;334         let request_id = 1;335         write_body(336             &self.inner,337             0,338             &Body::CacheFlush(body::CacheFlush {339                 req_id: request_id,340                 budget_ms: u32::try_from(budget.as_millis()).unwrap_or(u32::MAX),341             }),342             &[],343         )?;344         let deadline = Instant::now() + budget.max(Duration::from_millis(1));345         loop {346             if let Some(flushed) = *lock(&self.inner.cache_flushed) {347                 return Ok(flushed);348             }349             if let Some(refusal) = self.refusal() {350                 return Err(refused(&refusal));351             }352             let now = Instant::now();353             if now >= deadline {354                 return Err(io::Error::new(355                     io::ErrorKind::TimedOut,356                     "cache_flush timed out",357                 ));358             }359             let guard = lock(&self.inner.cache_flushed);360             let _ = wait_timeout(&self.inner.wake, guard, deadline - now);361         }362     }363 364     /// The models and capabilities of the server.365     pub fn catalogue(&self) -> Option<Catalogue> {366         lock(&self.inner.shared).catalogue.clone()367     }368 369     /// The load time and cache fingerprint that the server reported.370     pub fn ready(&self) -> Option<Ready> {371         lock(&self.inner.shared).ready372     }373 374     /// The refusal that ended the session, with the detail the server sent.375     ///376     /// A load or a handshake reports its reason here, so a caller that needs to377     /// show why can read the words instead of parsing an io error.378     pub fn refusal(&self) -> Option<Refusal> {379         lock(&self.inner.shared).fatal.clone()380     }381 382     /// Grants a load and waits for the server to report it.383     pub fn load(&self, grant: &Grant, wait: Duration) -> io::Result<Ready> {384         self.load_fds(grant, &[], wait)385     }386 387     /// Grants a load with the descriptors that the grant names.388     ///389     /// Only the first frame of a message carries descriptors, so the grant390     /// frame is the only place that a weight file can cross the socket. The391     /// caller keeps them open until this call returns; the peer does not store392     /// them.393     pub fn load_fds(394         &self,395         grant: &Grant,396         fds: &[BorrowedFd<'_>],397         wait: Duration,398     ) -> io::Result<Ready> {399         // The session moves before the frame leaves. A plugin that answers at400         // once would otherwise reach the reader before this thread records what401         // it sent, and the reader would see `ready` in `catalogued`.402         lock(&self.inner.shared)403             .session404             .send(Kind::Grant)405             .map_err(out_of_order)?;406         write_body(&self.inner, 0, &Body::Grant(grant.clone()), fds)?;407         self.wait_until(wait, |shared| {408             shared.ready.is_some() || shared.fatal.is_some()409         })?;410         let shared = lock(&self.inner.shared);411         match (&shared.ready, &shared.fatal) {412             (Some(ready), _) => Ok(*ready),413             (None, Some(refusal)) => Err(refused(refusal)),414             (None, None) => Err(io::Error::new(io::ErrorKind::TimedOut, "no ready")),415         }416     }417 418     /// Opens one job and returns the handle that reads it.419     pub fn open(&self, open: body::Open, fds: &[BorrowedFd<'_>]) -> io::Result<Job> {420         let inbox = Arc::new(Inbox {421             queue: Mutex::new(Queue {422                 items: VecDeque::new(),423                 phase: JobPhase::Open,424                 ended: false,425                 received: 0,426                 window: open.credit,427             }),428             wake: Condvar::new(),429         });430         // The inbox is visible before the frame leaves, so a server that431         // answers at once finds a stream to answer on.432         let id = {433             let mut streams = lock(&self.inner.streams);434             let id = streams.ids.take()?;435             streams.open.insert(id, inbox.clone());436             id437         };438 439         // The session counts the open before the wire carries it. The reader440         // must never see a terminal frame for a stream that the session has441         // not counted, or the `bye` drain waits forever.442         let counted = lock(&self.inner.shared).session.send(Kind::Open);443         if let Err(why) = counted {444             self.withdraw(id, &inbox);445             return Err(out_of_order(why));446         }447         if let Err(why) = write_body(&self.inner, id, &Body::Open(open), fds) {448             self.withdraw(id, &inbox);449             lock(&self.inner.shared).session.withdraw_stream();450             return Err(why);451         }452         Ok(Job {453             id,454             inbox,455             inner: self.inner.clone(),456         })457     }458 459     /// Removes an inbox that no frame can reach, and frees its id.460     fn withdraw(&self, id: u16, inbox: &Arc<Inbox>) {461         let mut streams = lock(&self.inner.streams);462         let current = streams463             .open464             .get(&id)465             .is_some_and(|open| Arc::ptr_eq(open, inbox));466         if current {467             streams.open.remove(&id);468         }469         streams.ids.release(id);470     }471 472     /// Ends the session and waits for the reader to see the end.473     ///474     /// A caller that has open jobs waits for them first; this is the drain.475     /// Shuts the socket down without dropping the peer.476     ///477     /// The core uses this before it stops a child: the child sees EOF and can478     /// exit inside the supervisor's grace instead of waiting for the kill. The479     /// peer stays in the map so a failed stop can still name the reservation.480     pub fn shutdown(&self) -> io::Result<()> {481         self.inner.halt.shutdown(std::net::Shutdown::Both)482     }483 484     pub fn close(mut self) -> io::Result<()> {485         let body = Body::Bye(body::Bye {486             reason: String::new(),487         });488         lock(&self.inner.shared)489             .session490             .send(Kind::Bye)491             .map_err(out_of_order)?;492         let sent = write_body(&self.inner, 0, &body, &[]);493         let reader = self.reader.take();494         let joined = match reader {495             Some(handle) => handle496                 .join()497                 .map_err(|_| io::Error::other("the reader thread panicked"))?,498             None => Ok(()),499         };500         sent?;501         joined502     }503 504     fn wait_until(&self, wait: Duration, done: impl Fn(&Shared) -> bool) -> io::Result<()> {505         let deadline = Instant::now() + wait;506         let mut shared = lock(&self.inner.shared);507         while !done(&shared) {508             if shared.fatal.is_some() {509                 let refusal = shared.fatal.clone().unwrap_or(Refusal {510                     code: body::ErrorCode::Internal,511                     detail: None,512                 });513                 return Err(refused(&refusal));514             }515             let now = Instant::now();516             if now >= deadline {517                 return Err(io::Error::new(518                     io::ErrorKind::TimedOut,519                     "the handshake timed out",520                 ));521             }522             // The deadline is fixed when the wait starts. A wakeup must not523             // start a fresh full wait.524             shared = wait_timeout(&self.inner.wake, shared, deadline - now).0;525         }526         Ok(())527     }528 }529 530 /// One job that the caller opened.531 pub struct Job {532     id: u16,533     inbox: Arc<Inbox>,534     inner: Arc<Inner>,535 }536 537 impl Job {538     /// A handle that another thread may use to cancel this job.539     pub fn handle(&self) -> Handle {540         Handle {541             inner: Arc::clone(&self.inner),542         }543     }544 545     /// The stream identifier on the wire.546     pub fn id(&self) -> u16 {547         self.id548     }549 550     /// Blocks until the job produces the next item.551     ///552     /// `Ok(None)` is the end of the stream: a terminal frame was consumed, or553     /// the session ended. The name is deliberate: one call, one item, the same554     /// move as an iterator but with an error and a blocking step.555     #[allow(clippy::should_implement_trait)]556     pub fn next(&mut self) -> io::Result<Option<Item>> {557         self.next_inner(None)558     }559 560     /// Blocks until the next item or `deadline`, whichever comes first.561     ///562     /// A terminal frame that the reader already queued wins over the deadline:563     /// a job that finished in time is not failed because the caller was slow to564     /// drain it. `Ok(None)` has the same meaning as in `next`. A deadline that565     /// passes while the job is still running is `TimedOut`.566     pub fn next_deadline(&mut self, deadline: Instant) -> io::Result<Option<Item>> {567         self.next_inner(Some(deadline))568     }569 570     fn next_inner(&mut self, deadline: Option<Instant>) -> io::Result<Option<Item>> {571         let mut queue = lock(&self.inbox.queue);572         loop {573             // The receipt path already counted an event. Consuming it must not574             // count it again, or a stream fails at half of its credit.575             if let Some(item) = queue.items.pop_front() {576                 // A bounded caller gets its terminal frame even if it reads577                 // late: the plugin did finish. An event after the deadline is578                 // not delivered, because a plugin that keeps streaming must579                 // not defeat the budget by never blocking.580                 if let Some(deadline) = deadline581                     && Instant::now() >= deadline582                     && !matches!(item, Item::Done(..) | Item::Reject(_))583                 {584                     return Err(io::Error::new(585                         io::ErrorKind::TimedOut,586                         "the job deadline passed",587                     ));588                 }589                 return Ok(Some(item));590             }591             if let Some(refusal) = lock(&self.inner.shared).fatal.clone() {592                 return Err(refused(&refusal));593             }594             if queue.ended {595                 return Ok(None);596             }597             match deadline {598                 Some(deadline) => {599                     let now = Instant::now();600                     let left = deadline.saturating_duration_since(now);601                     if left.is_zero() {602                         return Err(io::Error::new(603                             io::ErrorKind::TimedOut,604                             "the job deadline passed",605                         ));606                     }607                     queue = wait_timeout(&self.inbox.wake, queue, left).0;608                 }609                 None => queue = wait(&self.inbox.wake, queue),610             }611         }612     }613 614     /// Raises the credit watermark of this stream to `watermark`.615     ///616     /// The caller raises it after it consumes bytes. A watermark is absolute617     /// and monotonic, so a lower value is refused here rather than sent and618     /// refused by the plugin. The queue lock is held across the write so two619     /// threads cannot grant out of order.620     pub fn grant(&self, watermark: u64) -> io::Result<()> {621         grant_stream(&self.inner, self.id, watermark)622     }623 624     /// Total bytes of `event` bodies that this job received.625     pub fn received(&self) -> u64 {626         lock(&self.inbox.queue).received627     }628 629     /// Asks the server to stop. The job ends with `cancelled`.630     ///631     /// A job that already ended is not asked twice, and the answer is `Ok`:632     /// cancellation is best effort and the terminal frame is the truth.633     pub fn cancel(&self) -> io::Result<()> {634         let queue = lock(&self.inbox.queue);635         if queue.ended {636             return Ok(());637         }638         let body = Body::Cancel(body::CancelJob {639             reason: String::new(),640         });641         write_body(&self.inner, self.id, &body, &[])642     }643 }644 645 impl Handle {646     /// Sends `cancel` on one stream. The caller does not have to own the job.647     ///648     /// A stream that already ended is a no-op, so a cancel that races the649     /// terminal frame does not become an error at the caller.650     pub fn cancel(&self, stream: u16) -> io::Result<()> {651         let inbox = lock(&self.inner.streams).open.get(&stream).cloned();652         let Some(inbox) = inbox else {653             return Ok(());654         };655         let queue = lock(&inbox.queue);656         if queue.ended {657             return Ok(());658         }659         let body = Body::Cancel(body::CancelJob {660             reason: String::new(),661         });662         write_body(&self.inner, stream, &body, &[])663     }664 665     /// Raises the watermark of a stream that another thread reads.666     ///667     /// The worker that consumes events is usually not the thread that decides668     /// how much it may consume. This is the same operation as [`Job::grant`],669     /// for exactly that split.670     pub fn grant(&self, stream: u16, watermark: u64) -> io::Result<()> {671         grant_stream(&self.inner, stream, watermark)672     }673 674     /// Sends one frame in the extension range on a stream.675     ///676     /// An extension is optional by design: the receiver reads it and drops it.677     /// A gate uses this to prove that a binding keeps a job alive when an678     /// extension crosses it.679     pub fn extension(&self, stream: u16, payload: &[u8]) -> io::Result<()> {680         write_extension(&self.inner, stream, payload)681     }682 }683 684 impl Drop for Job {685     fn drop(&mut self) {686         // A dropped job is not a stream that never existed. Its terminal frame687         // may already be in flight, and removing the inbox here would make the688         // reader call that frame an unknown stream and fail the whole session.689         // Ask the server to end it instead; the terminal frame retires the id.690         let ended = lock(&self.inbox.queue).ended;691         if !ended {692             let _ = self.cancel();693         }694     }695 }696 697 /// The inbox of one stream.698 struct Inbox {699     queue: Mutex<Queue>,700     wake: Condvar,701 }702 703 fn read_loop(socket: &UnixStream, inner: &Arc<Inner>) {704     loop {705         let frame = match recv_frame(socket) {706             Ok(Some(frame)) => frame,707             Ok(None) => break,708             Err(_) => break,709         };710         let (frame, fds) = frame;711         let kind = frame.header.kind;712         let stream = frame.header.stream;713 714         // An extension frame is read and dropped. A receiver that does not know715         // a type must not fail a job over it (requirement R26).716         if matches!(kind, Kind::Extension(_)) {717             continue;718         }719 720         let body = match Body::decode(kind, &frame.payload) {721             Ok(body) => body,722             Err(_) => {723                 refuse(inner, body::ErrorCode::Frame, "a frame is out of order");724                 break;725             }726         };727 728         if crate::session::is_session(kind) {729             let mut shared = lock(&inner.shared);730             let legal = shared.session.recv(kind).is_ok();731             drop(shared);732             if !legal {733                 refuse(inner, body::ErrorCode::Frame, "a frame is out of order");734                 break;735             }736         }737         let mut shared = lock(&inner.shared);738 739         match body {740             Body::Welcome(welcome) => {741                 shared.welcome = Some(welcome);742             }743             Body::Catalogue(catalogue) => {744                 shared.catalogue = Some(catalogue);745                 drop(shared);746                 inner.wake.notify_all();747             }748             Body::Ready(ready) => {749                 shared.ready = Some(ready);750                 drop(shared);751                 inner.wake.notify_all();752             }753             Body::Accept(accepted) => {754                 drop(shared);755                 if let Err(why) = accept(inner, stream, accepted.est_ms) {756                     faulted(inner, stream, why);757                     break;758                 }759             }760             Body::Event(chunk) => {761                 drop(shared);762                 if let Err(why) = event(inner, stream, chunk) {763                     faulted(inner, stream, why);764                     break;765                 }766             }767             Body::Done(done) => {768                 drop(shared);769                 if let Err(why) = end(inner, stream, Item::Done(done, fds), JobPhase::Active) {770                     faulted(inner, stream, why);771                     break;772                 }773             }774             Body::Reject(refusal) => {775                 drop(shared);776                 if let Err(why) = end(inner, stream, Item::Reject(refusal), JobPhase::Open) {777                     faulted(inner, stream, why);778                     break;779                 }780             }781             Body::Fatal(refusal) => {782                 shared.fatal = Some(refusal);783                 shared.session.recv(Kind::Fatal).ok();784                 drop(shared);785                 inner.wake.notify_all();786                 break;787             }788             Body::Pong(_) => {789                 drop(shared);790                 if stream != 0 {791                     refuse(inner, body::ErrorCode::Frame, "pong on a job stream");792                     break;793                 }794             }795             Body::Ping(tick) => {796                 drop(shared);797                 if stream != 0 {798                     refuse(inner, body::ErrorCode::Frame, "ping on a job stream");799                     break;800                 }801                 // Ping is bidirectional. A server that asks for liveness gets802                 // the same time back on the session stream.803                 if write_body(inner, 0, &Body::Pong(tick), &[]).is_err() {804                     break;805                 }806             }807             Body::CacheLookup(request) => {808                 if !cache_allowed(&shared) {809                     drop(shared);810                     refuse(inner, body::ErrorCode::Frame, "cache frame outside Wire 2");811                     break;812                 }813                 drop(shared);814                 if stream != 0 {815                     refuse(inner, body::ErrorCode::Frame, "cache frame on a job stream");816                     break;817                 }818                 let binding = lock(&inner.cache)819                     .as_ref()820                     .map(|cache| (cache.session, Arc::clone(&cache.host)));821                 if let Some((session, host)) = binding {822                     match host.lookup(session, &request) {823                         Ok(Some(file)) => {824                             let reply = body::CacheLookupRes {825                                 req_id: request.req_id,826                                 hit: Some(body::CacheHit {827                                     key: file.key,828                                     lease_id: file.lease_id,829                                     bytes: file.bytes,830                                     crc32c: file.crc32c,831                                     token_count: file.token_count,832                                     tier: file.tier,833                                     fd: 0,834                                 }),835                             };836                             if write_body(837                                 inner,838                                 0,839                                 &Body::CacheLookupRes(reply),840                                 &[file.file.as_fd()],841                             )842                             .is_err()843                             {844                                 break;845                             }846                             continue;847                         }848                         Ok(None) => {}849                         Err(why) => eprintln!("cache lookup: {why}"),850                     }851                 }852                 let reply = body::CacheLookupRes {853                     req_id: request.req_id,854                     hit: None,855                 };856                 if write_body(inner, 0, &Body::CacheLookupRes(reply), &[]).is_err() {857                     break;858                 }859             }860             Body::CacheReserve(request) => {861                 if !cache_allowed(&shared) {862                     drop(shared);863                     refuse(inner, body::ErrorCode::Frame, "cache frame outside Wire 2");864                     break;865                 }866                 drop(shared);867                 if stream != 0 {868                     refuse(inner, body::ErrorCode::Frame, "cache frame on a job stream");869                     break;870                 }871                 let binding = lock(&inner.cache)872                     .as_ref()873                     .map(|cache| (cache.session, Arc::clone(&cache.host)));874                 let (grant, fds, reason) = match binding {875                     Some((session, host)) => match host.reserve(session, &request) {876                         Ok(file) => (877                             Some(body::CacheWriteGrant {878                                 lease_id: file.lease_id,879                                 max_bytes: file.max_bytes,880                                 tier: file.tier,881                                 fd: 0,882                             }),883                             Some(file.file),884                             None,885                         ),886                         Err(why) => (None, None, Some(why)),887                     },888                     None => (None, None, Some("the core has no cache host".to_string())),889                 };890                 let reply = body::CacheGrant {891                     req_id: request.req_id,892                     grant,893                     reason,894                 };895                 let borrowed: Vec<BorrowedFd<'_>> = fds.iter().map(AsFd::as_fd).collect();896                 if write_body(inner, 0, &Body::CacheGrant(reply), &borrowed).is_err() {897                     break;898                 }899             }900             Body::CacheRelease(request) => {901                 if !cache_allowed(&shared) {902                     drop(shared);903                     refuse(inner, body::ErrorCode::Frame, "cache frame outside Wire 2");904                     break;905                 }906                 drop(shared);907                 if stream != 0 {908                     refuse(inner, body::ErrorCode::Frame, "cache frame on a job stream");909                     break;910                 }911                 if let Some(cache) = lock(&inner.cache).as_ref() {912                     cache.host.release(cache.session, &request);913                 }914             }915             Body::CacheCommit(request) => {916                 if !cache_allowed(&shared) {917                     drop(shared);918                     refuse(inner, body::ErrorCode::Frame, "cache frame outside Wire 2");919                     break;920                 }921                 drop(shared);922                 if stream != 0 {923                     refuse(inner, body::ErrorCode::Frame, "cache frame on a job stream");924                     break;925                 }926                 if let Some(cache) = lock(&inner.cache).as_ref() {927                     cache.host.commit(cache.session, &request);928                 }929             }930             Body::CacheFlushed(flushed) => {931                 if !cache_allowed(&shared) {932                     drop(shared);933                     refuse(inner, body::ErrorCode::Frame, "cache frame outside Wire 2");934                     break;935                 }936                 drop(shared);937                 *lock(&inner.cache_flushed) = Some(flushed);938                 inner.wake.notify_all();939             }940             Body::CacheLookupRes(_) | Body::CacheGrant(_) | Body::CacheFlush(_) => {941                 drop(shared);942                 refuse(943                     inner,944                     body::ErrorCode::Frame,945                     "a core cache frame arrived at the core",946                 );947                 break;948             }949             Body::Hello(_)950             | Body::Grant(_)951             | Body::Window(_)952             | Body::Cancel(_)953             | Body::Open(_)954             | Body::Bye(_) => {955                 drop(shared);956                 refuse(957                     inner,958                     body::ErrorCode::Frame,959                     "a caller frame arrived at the caller",960                 );961                 break;962             }963         }964     }965 966     // A reader that ends leaves every waiter without an answer. The callers967     // must be woken with a refusal, not with a timeout five seconds later.968     {969         let mut shared = lock(&inner.shared);970         if shared.fatal.is_none() {971             shared.fatal = Some(body::Refusal {972                 code: body::ErrorCode::Internal,973                 detail: Some("the socket closed".to_string()),974             });975         }976     }977 978     let mut streams = lock(&inner.streams);979     for (_, inbox) in streams.open.drain() {980         let mut queue = lock(&inbox.queue);981         queue.ended = true;982         drop(queue);983         inbox.wake.notify_all();984     }985     drop(streams);986     inner.wake.notify_all();987 }988 989 /// A frame that the caller cannot route.990 #[derive(Clone, Copy)]991 enum Fault {992     /// No stream with this id is open.993     Unknown,994     /// The frame is not legal in the stream's phase.995     Phase,996     /// The stream passed its credit watermark.997     Credit,998 }999 1000 /// Answer a fault with `fatal`, then let the loop end.1001 fn faulted(inner: &Arc<Inner>, stream: u16, why: Fault) {1002     match why {1003         Fault::Unknown => refuse(1004             inner,1005             body::ErrorCode::Stream,1006             format!("stream {stream} is not open"),1007         ),1008         Fault::Phase => refuse(1009             inner,1010             body::ErrorCode::Frame,1011             format!("a job frame is out of order on stream {stream}"),1012         ),1013         Fault::Credit => refuse(1014             inner,1015             body::ErrorCode::Credit,1016             format!("stream {stream} passed its credit window"),1017         ),1018     }1019 }1020 1021 /// Records `accept` on a stream that is open.1022 fn accept(inner: &Arc<Inner>, stream: u16, est_ms: Option<u32>) -> Result<(), Fault> {1023     let inbox = lock(&inner.streams)1024         .open1025         .get(&stream)1026         .cloned()1027         .ok_or(Fault::Unknown)?;1028     let mut queue = lock(&inbox.queue);1029     if queue.phase != JobPhase::Open {1030         return Err(Fault::Phase);1031     }1032     queue.phase = JobPhase::Active;1033     queue.items.push_back(Item::Accepted(est_ms));1034     drop(queue);1035     inbox.wake.notify_all();1036     Ok(())1037 }1038 1039 /// Counts and queues one event on a stream that is active.1040 fn event(inner: &Arc<Inner>, stream: u16, event: body::Event) -> Result<(), Fault> {1041     let inbox = lock(&inner.streams)1042         .open1043         .get(&stream)1044         .cloned()1045         .ok_or(Fault::Unknown)?;1046     let mut queue = lock(&inbox.queue);1047     if queue.phase != JobPhase::Active {1048         return Err(Fault::Phase);1049     }1050     // Credit is an absolute watermark, and the receiver is the one that can1051     // prove it was passed.1052     queue.received = queue.received.saturating_add(event.data.len() as u64);1053     if queue.received > queue.window {1054         return Err(Fault::Credit);1055     }1056     queue.items.push_back(Item::Event {1057         ch: event.ch,1058         mime: event.mime,1059         data: event.data,1060     });1061     drop(queue);1062     inbox.wake.notify_all();1063     Ok(())1064 }1065 1066 /// Ends one stream with its terminal frame.1067 fn end(inner: &Arc<Inner>, stream: u16, item: Item, expected: JobPhase) -> Result<(), Fault> {1068     let mut streams = lock(&inner.streams);1069     let Some(inbox) = streams.open.get(&stream).cloned() else {1070         return Err(Fault::Unknown);1071     };1072     let mut queue = lock(&inbox.queue);1073     if queue.phase != expected {1074         return Err(Fault::Phase);1075     }1076     queue.phase = JobPhase::Ended;1077     queue.ended = true;1078     queue.items.push_back(item);1079     streams.open.remove(&stream);1080     streams.ids.release(stream);1081     drop(queue);1082     drop(streams);1083     inbox.wake.notify_all();1084     lock(&inner.shared).session.finish_stream();1085     Ok(())1086 }1087 1088 /// Marks the session as failed, tells the server, and closes the write side.1089 ///1090 /// The first fault wins. A second one has no frame to send: the server already1091 /// knows that the session is over.1092 fn refuse(inner: &Arc<Inner>, code: body::ErrorCode, detail: impl Into<String>) {1093     let refusal = Refusal {1094         code,1095         detail: Some(detail.into()),1096     };1097     let first = {1098         let mut shared = lock(&inner.shared);1099         if shared.fatal.is_some() {1100             false1101         } else {1102             shared.fatal = Some(refusal.clone());1103             shared.session.recv(Kind::Fatal).ok();1104             true1105         }1106     };1107     inner.wake.notify_all();1108     if first {1109         let _ = write_body(inner, 0, &Body::Fatal(refusal), &[]);1110         let _ = inner.halt.shutdown(std::net::Shutdown::Write);1111     }1112 }1113 1114 /// The first type in the extension range.1115 const EXTENSION: u8 = 0x40;1116 1117 /// Applies one absolute watermark to the inbox of a stream.1118 fn grant_stream(inner: &Arc<Inner>, stream: u16, watermark: u64) -> io::Result<()> {1119     let inbox = lock(&inner.streams).open.get(&stream).cloned();1120     let Some(inbox) = inbox else {1121         return Err(io::Error::new(1122             io::ErrorKind::BrokenPipe,1123             "the job has ended",1124         ));1125     };1126     let mut queue = lock(&inbox.queue);1127     if queue.ended {1128         return Err(io::Error::new(1129             io::ErrorKind::BrokenPipe,1130             "the job has ended",1131         ));1132     }1133     if watermark < queue.window {1134         return Err(io::Error::new(1135             io::ErrorKind::InvalidInput,1136             format!(1137                 "watermark {watermark} is below the granted window {}",1138                 queue.window1139             ),1140         ));1141     }1142     if watermark == queue.window {1143         return Ok(());1144     }1145     let body = Body::Window(body::Window { credit: watermark });1146     write_body(inner, stream, &body, &[])?;1147     queue.window = watermark;1148     Ok(())1149 }1150 1151 /// Writes one extension frame. The payload is opaque and carries no body.1152 fn write_extension(inner: &Arc<Inner>, stream: u16, payload: &[u8]) -> io::Result<()> {1153     let length = u32::try_from(payload.len())1154         .map_err(|_| io::Error::other("the payload does not fit the header"))?;1155     let header = Header::new(Kind::Extension(EXTENSION), stream, length);1156     let out = lock(&inner.out);1157     send_frame(&out, header, payload, &[]).map_err(|e| match e {1158         crate::Error::Io(e) => e,1159         other => io::Error::other(other.to_string()),1160     })1161 }1162 1163 fn write_body(1164     inner: &Arc<Inner>,1165     stream: u16,1166     body: &Body,1167     fds: &[BorrowedFd<'_>],1168 ) -> io::Result<()> {1169     let payload = body.encode();1170     let length = match u32::try_from(payload.len()) {1171         Ok(length) => length,1172         Err(_) => return Err(io::Error::other("the payload does not fit the header")),1173     };1174     let header = Header::new(body.kind(), stream, length);1175     let out = lock(&inner.out);1176     send_frame(&out, header, &payload, fds).map_err(|e| match e {1177         crate::Error::Io(e) => e,1178         other => io::Error::other(other.to_string()),1179     })1180 }1181 1182 /// A phase refusal is a protocol error, not a transport one.1183 fn out_of_order(why: crate::session::OutOfOrder) -> io::Error {1184     io::Error::other(why.to_string())1185 }1186 1187 fn refused(refusal: &Refusal) -> io::Error {1188     match &refusal.detail {1189         Some(detail) => io::Error::other(format!("{refusal:?}: {detail}")),1190         None => io::Error::other(format!("{refusal:?}")),1191     }1192 }1193 1194 fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {1195     m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())1196 }1197 1198 fn wait<'a, T>(cv: &Condvar, guard: MutexGuard<'a, T>) -> MutexGuard<'a, T> {1199     cv.wait(guard)1200         .unwrap_or_else(|poisoned| poisoned.into_inner())1201 }1202 1203 fn wait_timeout<'a, T>(1204     cv: &Condvar,1205     guard: MutexGuard<'a, T>,1206     at: Duration,1207 ) -> (MutexGuard<'a, T>, std::sync::WaitTimeoutResult) {1208     cv.wait_timeout(guard, at)1209         .unwrap_or_else(|poisoned| poisoned.into_inner())1210 }1211 1212 #[cfg(test)]1213 mod deadline {1214     use super::*;1215     use std::sync::atomic::{AtomicBool, Ordering};1216 1217     #[test]1218     fn a_wakeup_does_not_restart_the_wait() {1219         let pair = UnixStream::pair();1220         assert!(pair.is_ok(), "socketpair");1221         let Ok((socket, other)) = pair else {1222             return;1223         };1224         let out = socket.try_clone();1225         assert!(out.is_ok(), "clone the writer");1226         let Ok(out) = out else {1227             return;1228         };1229         let halt = socket.try_clone();1230         assert!(halt.is_ok(), "clone the socket");1231         let Ok(halt) = halt else {1232             return;1233         };1234         let inner = Arc::new(Inner {1235             out: Mutex::new(out),1236             halt,1237             streams: Mutex::new(Streams {1238                 open: HashMap::new(),1239                 ids: Ids::new(),1240             }),1241             shared: Mutex::new(Shared {1242                 session: Session::new(Role::Caller),1243                 welcome: None,1244                 catalogue: None,1245                 ready: None,1246                 fatal: None,1247             }),1248             wake: Condvar::new(),1249             cache: Mutex::new(None),1250             cache_flushed: Mutex::new(None),1251         });1252         let peer = Peer {1253             inner: Arc::clone(&inner),1254             reader: None,1255         };1256 1257         let stop = Arc::new(AtomicBool::new(false));1258         let beating = Arc::clone(&stop);1259         let beat = thread::spawn(move || {1260             while !beating.load(Ordering::SeqCst) {1261                 thread::sleep(Duration::from_millis(5));1262                 inner.wake.notify_all();1263             }1264         });1265 1266         let (send, recv) = std::sync::mpsc::channel();1267         let waiter = thread::spawn(move || {1268             let _ = send.send(peer.wait_until(Duration::from_millis(100), |_| false));1269         });1270         let result = recv.recv_timeout(Duration::from_secs(2));1271         stop.store(true, Ordering::SeqCst);1272         let _ = beat.join();1273         let _ = waiter.join();1274 1275         assert!(1276             matches!(&result, Ok(Err(error)) if error.kind() == io::ErrorKind::TimedOut),1277             "the wait must time out once: {result:?}"1278         );1279         drop(other);1280     }1281 }