crates/run/core/src/jobs.rs 9.3 KiB 298 lines Raw
1 //! The job table: what is running, what it is doing, and how to stop it.2 //!3 //! A job is identified here, not on the wire: the stream id is unique only4 //! inside one peer, and a client must be able to cancel a job without knowing5 //! which plugin serves it. The table is the answer to `GET /jobs`, `GET6 //! /jobs/{id}`, and `DELETE /jobs/{id}`.7 //!8 //! The entry is made before the plugin is asked to start, so a cancel that9 //! arrives during the handshake has a row to find. A job leaves `Running` once,10 //! and the terminal state is never rewritten.11 12 use std::collections::BTreeMap;13 use std::sync::atomic::{AtomicU64, Ordering};14 use std::sync::{Mutex, MutexGuard};15 use std::time::{Duration, Instant};16 17 use crate::refusal::RefusalCode;18 use inf3r_proto::client::Handle;19 20 /// The state of one job.21 #[derive(Clone, PartialEq, Eq, Debug)]22 pub enum JobState {23     /// Accepted and not finished.24     Running,25     /// The plugin finished the stream.26     Done {27         /// `completed`, `cancelled`, `failed`, or `timeout`.28         outcome: String,29     },30     /// The job failed with a refusal.31     Failed {32         /// The core code of the failure.33         code: RefusalCode,34         /// One sentence for a human.35         message: String,36     },37 }38 39 impl JobState {40     /// The word that a caller sees.41     pub fn as_str(&self) -> &str {42         match self {43             JobState::Running => "running",44             JobState::Done { outcome } => outcome,45             JobState::Failed { code, .. } => code.as_str(),46         }47     }48 }49 50 /// One row of the table, as a caller sees it.51 #[derive(Clone, PartialEq, Eq, Debug)]52 pub struct JobStatus {53     /// The identifier that the core made.54     pub id: String,55     /// The served name.56     pub model: String,57     /// The capability.58     pub capability: String,59     /// The identifier that the client sent.60     pub request_id: String,61     /// What the job is doing.62     pub state: JobState,63     /// Milliseconds from acceptance to now, or to the end.64     pub elapsed_ms: u64,65 }66 67 struct Row {68     plugin: String,69     model: String,70     capability: String,71     request_id: String,72     started: Instant,73     state: JobState,74     ended: Option<Instant>,75     stream: u16,76     handle: Option<Handle>,77 }78 79 /// The jobs of one core.80 pub struct JobTable {81     rows: Mutex<BTreeMap<String, Row>>,82     next: AtomicU64,83 }84 85 impl Default for JobTable {86     fn default() -> JobTable {87         JobTable::new()88     }89 }90 91 impl JobTable {92     /// An empty table.93     pub fn new() -> JobTable {94         JobTable {95             rows: Mutex::new(BTreeMap::new()),96             next: AtomicU64::new(1),97         }98     }99 100     /// Makes a row and returns the identifier that the caller uses.101     pub fn open(&self, plugin: &str, model: &str, capability: &str, request_id: &str) -> String {102         let id = format!("j-{:08x}", self.next.fetch_add(1, Ordering::Relaxed));103         lock(&self.rows).insert(104             id.clone(),105             Row {106                 plugin: plugin.to_string(),107                 model: model.to_string(),108                 capability: capability.to_string(),109                 request_id: request_id.to_string(),110                 started: Instant::now(),111                 state: JobState::Running,112                 ended: None,113                 stream: 0,114                 handle: None,115             },116         );117         id118     }119 120     /// Records the stream and the handle of a row that is now running.121     ///122     /// A row that a cancel ended between `open` and this call stays ended:123     /// `attach` returns false, and the submit path cancels the stream at once124     /// rather than stream to a reader that will never read it.125     pub fn attach(&self, id: &str, stream: u16, handle: Handle) -> bool {126         let mut rows = lock(&self.rows);127         match rows.get_mut(id) {128             Some(row) if row.state == JobState::Running => {129                 row.stream = stream;130                 row.handle = Some(handle);131                 true132             }133             _ => false,134         }135     }136 137     /// Ends a row with the outcome that the plugin sent.138     pub fn finish(&self, id: &str, state: JobState) {139         let mut rows = lock(&self.rows);140         if let Some(row) = rows.get_mut(id)141             && row.state == JobState::Running142         {143             row.state = state;144             row.ended = Some(Instant::now());145         }146     }147 148     /// Fails every running job of one plugin.149     ///150     /// A peer that died owns every stream on it. The table is the caller's151     /// view, so it must show the same failure that the readers see, and it must152     /// happen before a later request can reuse the name.153     pub fn fail_plugin(&self, plugin: &str, message: &str) -> usize {154         let mut rows = lock(&self.rows);155         let now = Instant::now();156         let mut failed = 0;157         for row in rows.values_mut() {158             if row.plugin == plugin && row.state == JobState::Running {159                 row.state = JobState::Failed {160                     code: RefusalCode::PluginCrashed,161                     message: message.to_string(),162                 };163                 row.ended = Some(now);164                 failed += 1;165             }166         }167         failed168     }169 170     /// Ends a row whose stream ended without a terminal frame.171     pub fn lost(&self, id: &str) {172         self.finish(173             id,174             JobState::Failed {175                 code: RefusalCode::PluginCrashed,176                 message: "the stream ended without a terminal frame".to_string(),177             },178         );179     }180 181     /// Every row, oldest first.182     pub fn list(&self) -> Vec<JobStatus> {183         let rows = lock(&self.rows);184         let now = Instant::now();185         rows.iter().map(|(id, row)| status(id, row, now)).collect()186     }187 188     /// One row.189     pub fn get(&self, id: &str) -> Option<JobStatus> {190         let rows = lock(&self.rows);191         let now = Instant::now();192         rows.get(id).map(|row| status(id, row, now))193     }194 195     /// Asks the plugin to stop one job. Idempotent: a job that already ended is196     /// not asked twice, and the answer is the same.197     pub fn cancel(&self, id: &str) -> Option<JobStatus> {198         let (handle, stream) = {199             let mut rows = lock(&self.rows);200             match rows.get_mut(id) {201                 Some(row) if row.state == JobState::Running => {202                     match (&row.handle, row.stream) {203                         (Some(handle), stream) if stream != 0 => (Some(handle.clone()), stream),204                         // The row exists but the stream has not been attached.205                         // Mark it ended now; `attach` will see a non-running206                         // row and the submit path will cancel the stream as207                         // soon as it has one.208                         _ => {209                             row.state = JobState::Done {210                                 outcome: "cancelled".to_string(),211                             };212                             row.ended = Some(Instant::now());213                             (None, 0)214                         }215                     }216                 }217                 _ => (None, 0),218             }219         };220         if let Some(handle) = handle {221             let _ = handle.cancel(stream);222         }223         self.get(id)224     }225 226     /// Removes the rows that ended before `keep` ago.227     pub fn sweep(&self, keep: Duration) -> usize {228         let mut rows = lock(&self.rows);229         let now = Instant::now();230         let before = rows.len();231         rows.retain(|_, row| match row.ended {232             Some(ended) => now.duration_since(ended) < keep,233             None => true,234         });235         before - rows.len()236     }237 238     /// The number of rows that are still running.239     pub fn running(&self) -> usize {240         lock(&self.rows)241             .values()242             .filter(|row| row.state == JobState::Running)243             .count()244     }245 }246 247 fn status(id: &str, row: &Row, now: Instant) -> JobStatus {248     let end = row.ended.unwrap_or(now);249     JobStatus {250         id: id.to_string(),251         model: row.model.clone(),252         capability: row.capability.clone(),253         request_id: row.request_id.clone(),254         state: row.state.clone(),255         elapsed_ms: end.duration_since(row.started).as_millis() as u64,256     }257 }258 259 fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {260     m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())261 }262 263 #[cfg(test)]264 mod tests {265     use super::*;266 267     #[test]268     fn an_early_cancel_ends_the_row_before_the_stream_is_attached() {269         let table = JobTable::new();270         let id = table.open("p", "m", "chat", "r");271         let status = table.cancel(&id).expect("the row");272         assert_eq!(273             status.state,274             JobState::Done {275                 outcome: "cancelled".to_string()276             }277         );278         // A late terminal frame must not rewrite the cancellation.279         table.finish(280             &id,281             JobState::Done {282                 outcome: "completed".to_string(),283             },284         );285         assert_eq!(table.get(&id).expect("the row").state, status.state);286     }287 288     #[test]289     fn a_sweep_keeps_running_rows_and_removes_ended_ones() {290         let table = JobTable::new();291         let running = table.open("p", "running", "chat", "r1");292         let ended = table.open("p", "ended", "chat", "r2");293         table.cancel(&ended);294         assert_eq!(table.sweep(Duration::ZERO), 1);295         assert!(table.get(&running).is_some());296         assert!(table.get(&ended).is_none());297     }298 }