1 //! inf3r-sched — the queue in front of each peer.2 //!3 //! Admission has three parts and this crate owns all three: a bound on how many4 //! jobs a peer runs, a bound on how many wait, and the rule for which waiter5 //! runs next. The rule is the whole reason the crate exists: a background job6 //! that arrived first must not hold a slot while an interactive job waits, and7 //! a job whose deadline has passed must not take a slot that a live job can use.8 //!9 //! The clock is a parameter. Every method takes the instant that the caller10 //! read, so a test can age a job without sleeping and the crate has no thread.11 12 use std::collections::BTreeMap;13 use std::sync::{Arc, Condvar, Mutex, MutexGuard};14 use std::time::{Duration, Instant};15 16 /// How long a background job waits before it is treated as interactive.17 ///18 /// Priority alone starves a background job when interactive requests keep19 /// arriving: every newcomer has the same class and a later arrival number, so20 /// the old background waiter never becomes the best. Aging gives the older21 /// waiter the interactive class after this window, and its lower arrival22 /// number then puts it first.23 pub const BACKGROUND_AGING: Duration = Duration::from_secs(1);24 25 /// Who a job is for.26 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]27 pub enum Priority {28 /// A person is waiting.29 Interactive,30 /// Nobody is waiting. It runs when no interactive job wants the slot.31 Background,32 }33 34 /// One job that waits for a slot.35 #[derive(Clone, Copy, PartialEq, Eq, Debug)]36 pub struct Waiter {37 /// The order it arrived in, which breaks a tie inside one class.38 pub seq: u64,39 /// Who it is for.40 pub priority: Priority,41 /// When the caller stops waiting.42 pub deadline: Instant,43 /// When it entered the queue. This is what ages a background job.44 pub since: Instant,45 }46 47 /// Why a job did not get a slot.48 #[derive(Clone, Copy, PartialEq, Eq, Debug)]49 pub enum SchedError {50 /// The name is not registered.51 Unknown,52 /// Every slot is busy and every queue place is taken.53 QueueFull,54 /// The deadline passed before a slot was free.55 Timeout,56 /// The job's own budget ended before it started. It would be refused by the57 /// deadline rule anyway, so it must not take a place in a queue.58 Expired,59 }60 61 impl std::fmt::Display for SchedError {62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {63 match self {64 SchedError::Unknown => write!(f, "no such peer"),65 SchedError::QueueFull => write!(f, "the queue is full"),66 SchedError::Timeout => write!(f, "the deadline passed before a slot was free"),67 SchedError::Expired => write!(f, "the deadline had already passed"),68 }69 }70 }71 72 impl std::error::Error for SchedError {}73 74 /// The queue of one peer.75 struct Peer {76 /// Slots in use.77 busy: u16,78 /// Slots that exist.79 slots: u16,80 /// Waiters, in arrival order. A short vector is the right shape: a peer81 /// that runs one job rarely has more than a handful of waiters, and the82 /// scan is what makes the priority rule simple enough to read.83 waiters: Vec<Waiter>,84 /// The most waiters that this queue may hold. A queue without a bound is a85 /// memory leak that a client controls.86 capacity: u16,87 /// The next arrival number.88 seq: u64,89 }90 91 /// The schedule of every peer on this host.92 pub struct Sched {93 peers: Mutex<BTreeMap<String, Peer>>,94 wake: Condvar,95 }96 97 impl Default for Sched {98 fn default() -> Sched {99 Sched::new()100 }101 }102 103 impl Sched {104 /// A schedule with no peer.105 pub fn new() -> Sched {106 Sched {107 peers: Mutex::new(BTreeMap::new()),108 wake: Condvar::new(),109 }110 }111 112 /// Adds or replaces the bounds of one plugin.113 ///114 /// The key is the plugin, not a served name: every name that one bundle115 /// serves shares the same slots. A second registration keeps the slots in116 /// use, so a plugin that restarts does not free a slot that a live job117 /// still holds.118 pub fn register(&self, plugin: &str, slots: u16, capacity: u16) {119 let mut peers = lock(&self.peers);120 let peer = peers.entry(plugin.to_string()).or_insert(Peer {121 busy: 0,122 slots,123 waiters: Vec::new(),124 capacity,125 seq: 0,126 });127 peer.slots = slots;128 peer.capacity = capacity;129 }130 131 /// Takes a slot, waiting until `deadline` if every slot is busy.132 ///133 /// `now` is the caller's reading of the clock, so a caller that keeps one134 /// instant for a whole admission uses the same instant here and in its own135 /// deadline check.136 pub fn acquire(137 self: &Arc<Self>,138 plugin: &str,139 priority: Priority,140 now: Instant,141 deadline: Instant,142 ) -> Result<Lease, SchedError> {143 let mut guard = lock(&self.peers);144 let peer = guard.get_mut(plugin).ok_or(SchedError::Unknown)?;145 if deadline <= now {146 return Err(SchedError::Expired);147 }148 if peer.busy < peer.slots && peer.waiters.is_empty() {149 peer.busy += 1;150 return Ok(Lease {151 sched: Arc::clone(self),152 plugin: plugin.to_string(),153 });154 }155 if peer.waiters.len() >= usize::from(peer.capacity) {156 return Err(SchedError::QueueFull);157 }158 peer.seq += 1;159 let me = peer.seq;160 peer.waiters.push(Waiter {161 seq: me,162 priority,163 deadline,164 since: now,165 });166 167 loop {168 let peer = guard.get_mut(plugin).ok_or(SchedError::Unknown)?;169 // The best waiter is the highest priority and, inside one class,170 // the one that arrived first. A background waiter that has waited171 // long enough competes as interactive, so a stream of new172 // interactive arrivals cannot keep it out forever.173 let at = Instant::now();174 // A deadline that passed while this thread was asleep removes the175 // waiter before it can take a slot. The same pass removes every176 // other expired waiter, so an old row cannot keep the queue full.177 let before = peer.waiters.len();178 peer.waiters.retain(|waiter| at < waiter.deadline);179 if peer.waiters.len() != before {180 self.wake.notify_all();181 }182 if !peer.waiters.iter().any(|waiter| waiter.seq == me) {183 return Err(SchedError::Timeout);184 }185 let best = peer186 .waiters187 .iter()188 .min_by_key(|waiter| rank(waiter, at))189 .map(|waiter| waiter.seq);190 if best == Some(me) && peer.busy < peer.slots {191 peer.busy += 1;192 peer.waiters.retain(|waiter| waiter.seq != me);193 drop(guard);194 self.wake.notify_all();195 return Ok(Lease {196 sched: Arc::clone(self),197 plugin: plugin.to_string(),198 });199 }200 let left = deadline.saturating_duration_since(at);201 if left.is_zero() {202 peer.waiters.retain(|waiter| waiter.seq != me);203 self.wake.notify_all();204 return Err(SchedError::Timeout);205 }206 let (next, _) = self207 .wake208 .wait_timeout(guard, left)209 .unwrap_or_else(|poisoned| poisoned.into_inner());210 guard = next;211 }212 }213 214 /// Forgets one plugin. A switch removes the child that stopped; a cold215 /// bind is registered again when the next child starts.216 pub fn remove(&self, plugin: &str) {217 lock(&self.peers).remove(plugin);218 self.wake.notify_all();219 }220 221 /// Slots in use by one peer.222 pub fn in_flight(&self, plugin: &str) -> u16 {223 lock(&self.peers)224 .get(plugin)225 .map(|peer| peer.busy)226 .unwrap_or(0)227 }228 229 /// The jobs that wait for one peer.230 pub fn queued(&self, plugin: &str) -> usize {231 lock(&self.peers)232 .get(plugin)233 .map(|peer| peer.waiters.len())234 .unwrap_or(0)235 }236 237 /// Every peer with its slots, its busy count, and its queue.238 pub fn snapshot(&self) -> Vec<(String, u16, u16, usize)> {239 lock(&self.peers)240 .iter()241 .map(|(plugin, peer)| (plugin.clone(), peer.busy, peer.slots, peer.waiters.len()))242 .collect()243 }244 245 fn release(&self, plugin: &str) {246 let mut peers = lock(&self.peers);247 if let Some(peer) = peers.get_mut(plugin) {248 peer.busy = peer.busy.saturating_sub(1);249 }250 drop(peers);251 self.wake.notify_all();252 }253 }254 255 /// One slot, given back when the job ends.256 pub struct Lease {257 sched: Arc<Sched>,258 plugin: String,259 }260 261 impl Lease {262 /// The plugin that this slot belongs to.263 pub fn plugin(&self) -> &str {264 &self.plugin265 }266 }267 268 impl Drop for Lease {269 fn drop(&mut self) {270 self.sched.release(&self.plugin);271 }272 }273 274 fn rank(waiter: &Waiter, now: Instant) -> (Priority, u64) {275 let priority = if waiter.priority == Priority::Background276 && now.saturating_duration_since(waiter.since) >= BACKGROUND_AGING277 {278 Priority::Interactive279 } else {280 waiter.priority281 };282 (priority, waiter.seq)283 }284 285 fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {286 m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())287 }