| 1 | use std::collections::VecDeque; |
| 2 | use std::fmt::{Debug, Write as _}; |
| 3 | use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; |
| 4 | use std::time::{Duration, SystemTime, UNIX_EPOCH}; |
| 5 | |
| 6 | use forge_ci::proto::{RUNNER_LOG_MAX_TEXT, RunnerLogBatch, RunnerLogLine, truncate_text}; |
| 7 | use reqwest::StatusCode; |
| 8 | use tokio_util::sync::CancellationToken; |
| 9 | use tracing::field::{Field, Visit}; |
| 10 | use tracing::{Event, Level, Subscriber}; |
| 11 | use tracing_subscriber::Layer; |
| 12 | use tracing_subscriber::layer::Context; |
| 13 | |
| 14 | use crate::client::{ClientError, ForgeClient}; |
| 15 | |
| 16 | pub const CAPACITY: usize = 2000; |
| 17 | pub const BATCH: usize = 500; |
| 18 | const EVERY: Duration = Duration::from_secs(2); |
| 19 | const SKIP_TARGETS: [&str; 4] = ["reqwest", "hyper", "h2", "rustls"]; |
| 20 | |
| 21 | static RING: OnceLock<Arc<Ring>> = OnceLock::new(); |
| 22 | |
| 23 | pub fn ring() -> Arc<Ring> { |
| 24 | RING.get_or_init(|| Arc::new(Ring::new(CAPACITY))).clone() |
| 25 | } |
| 26 | |
| 27 | pub fn layer() -> SelfLog { |
| 28 | SelfLog { ring: ring() } |
| 29 | } |
| 30 | |
| 31 | pub struct Ring { |
| 32 | capacity: usize, |
| 33 | state: Mutex<State>, |
| 34 | } |
| 35 | |
| 36 | #[derive(Default)] |
| 37 | struct State { |
| 38 | lines: VecDeque<RunnerLogLine>, |
| 39 | next: u64, |
| 40 | } |
| 41 | |
| 42 | impl Ring { |
| 43 | pub fn new(capacity: usize) -> Self { |
| 44 | Self { |
| 45 | capacity, |
| 46 | state: Mutex::new(State::default()), |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | fn lock(&self) -> MutexGuard<'_, State> { |
| 51 | self.state.lock().unwrap_or_else(PoisonError::into_inner) |
| 52 | } |
| 53 | |
| 54 | pub fn push(&self, line: RunnerLogLine) { |
| 55 | let mut state = self.lock(); |
| 56 | if state.lines.len() >= self.capacity { |
| 57 | state.lines.pop_front(); |
| 58 | } |
| 59 | state.lines.push_back(line); |
| 60 | state.next += 1; |
| 61 | } |
| 62 | |
| 63 | pub fn batch(&self, from: u64, max: usize) -> (u64, Vec<RunnerLogLine>) { |
| 64 | let state = self.lock(); |
| 65 | let oldest = state.next - state.lines.len() as u64; |
| 66 | let first = from.max(oldest); |
| 67 | if first >= state.next { |
| 68 | return (first, Vec::new()); |
| 69 | } |
| 70 | let skip = (first - oldest) as usize; |
| 71 | let lines = state.lines.iter().skip(skip).take(max).cloned().collect(); |
| 72 | (first, lines) |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | pub struct SelfLog { |
| 77 | ring: Arc<Ring>, |
| 78 | } |
| 79 | |
| 80 | impl<S: Subscriber> Layer<S> for SelfLog { |
| 81 | fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) { |
| 82 | let meta = event.metadata(); |
| 83 | if *meta.level() > Level::INFO { |
| 84 | return; |
| 85 | } |
| 86 | if SKIP_TARGETS |
| 87 | .iter() |
| 88 | .any(|prefix| meta.target().starts_with(prefix)) |
| 89 | { |
| 90 | return; |
| 91 | } |
| 92 | let mut text = Text::default(); |
| 93 | event.record(&mut text); |
| 94 | self.ring.push(RunnerLogLine { |
| 95 | at_ms: now_ms(), |
| 96 | level: level_name(*meta.level()).to_owned(), |
| 97 | text: truncate_text(&text.finish(), RUNNER_LOG_MAX_TEXT).to_owned(), |
| 98 | }); |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | #[derive(Default)] |
| 103 | struct Text { |
| 104 | message: String, |
| 105 | fields: String, |
| 106 | } |
| 107 | |
| 108 | impl Text { |
| 109 | fn finish(self) -> String { |
| 110 | match (self.message.is_empty(), self.fields.is_empty()) { |
| 111 | (_, true) => self.message, |
| 112 | (true, false) => self.fields.trim_start().to_owned(), |
| 113 | (false, false) => format!("{}{}", self.message, self.fields), |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | impl Visit for Text { |
| 119 | fn record_str(&mut self, field: &Field, value: &str) { |
| 120 | if field.name() == "message" { |
| 121 | self.message.push_str(value); |
| 122 | } else { |
| 123 | let _ = write!(self.fields, " {}={value}", field.name()); |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | fn record_debug(&mut self, field: &Field, value: &dyn Debug) { |
| 128 | if field.name() == "message" { |
| 129 | let _ = write!(self.message, "{value:?}"); |
| 130 | } else { |
| 131 | let _ = write!(self.fields, " {}={value:?}", field.name()); |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | fn level_name(level: Level) -> &'static str { |
| 137 | match level { |
| 138 | Level::ERROR => "error", |
| 139 | Level::WARN => "warn", |
| 140 | Level::INFO => "info", |
| 141 | Level::DEBUG => "debug", |
| 142 | _ => "trace", |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | pub(crate) fn now_ms() -> i64 { |
| 147 | SystemTime::now() |
| 148 | .duration_since(UNIX_EPOCH) |
| 149 | .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX)) |
| 150 | } |
| 151 | |
| 152 | pub async fn ship(client: ForgeClient, runner_secret: String, stop: CancellationToken) { |
| 153 | let ring = ring(); |
| 154 | let boot_id = crate::restart::boot_id(); |
| 155 | let mut next_seq = 0_u64; |
| 156 | let mut ticker = tokio::time::interval(EVERY); |
| 157 | loop { |
| 158 | let stopping = tokio::select! { |
| 159 | _ = ticker.tick() => false, |
| 160 | () = stop.cancelled() => true, |
| 161 | }; |
| 162 | loop { |
| 163 | let (first_seq, lines) = ring.batch(next_seq, BATCH); |
| 164 | if lines.is_empty() { |
| 165 | break; |
| 166 | } |
| 167 | let batch = RunnerLogBatch { |
| 168 | boot_id: boot_id.to_owned(), |
| 169 | first_seq, |
| 170 | lines, |
| 171 | }; |
| 172 | match client.post_runner_log(&runner_secret, &batch).await { |
| 173 | Ok(ack) => { |
| 174 | let moved = ack.next_seq != next_seq; |
| 175 | next_seq = ack.next_seq; |
| 176 | if !stopping || !moved { |
| 177 | break; |
| 178 | } |
| 179 | } |
| 180 | Err(ClientError::Status { |
| 181 | status: StatusCode::NOT_FOUND, |
| 182 | .. |
| 183 | }) => return, |
| 184 | Err(e) => { |
| 185 | tracing::debug!(error = %e, "cannot ship the runner log, retrying"); |
| 186 | break; |
| 187 | } |
| 188 | } |
| 189 | } |
| 190 | if stopping { |
| 191 | return; |
| 192 | } |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | #[cfg(test)] |
| 197 | mod tests { |
| 198 | use super::*; |
| 199 | |
| 200 | fn line(text: &str) -> RunnerLogLine { |
| 201 | RunnerLogLine { |
| 202 | at_ms: 0, |
| 203 | level: "info".into(), |
| 204 | text: text.into(), |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | #[test] |
| 209 | fn ring_drops_the_oldest_lines() { |
| 210 | let ring = Ring::new(3); |
| 211 | for i in 0..5 { |
| 212 | ring.push(line(&i.to_string())); |
| 213 | } |
| 214 | assert_eq!(ring.batch(5, 10).0, 5); |
| 215 | let (first, lines) = ring.batch(0, 10); |
| 216 | assert_eq!(first, 2); |
| 217 | let texts: Vec<_> = lines.iter().map(|l| l.text.as_str()).collect(); |
| 218 | assert_eq!(texts, ["2", "3", "4"]); |
| 219 | } |
| 220 | |
| 221 | #[test] |
| 222 | fn sequence_numbers_follow_the_request() { |
| 223 | let ring = Ring::new(10); |
| 224 | for i in 0..4 { |
| 225 | ring.push(line(&i.to_string())); |
| 226 | } |
| 227 | let (first, lines) = ring.batch(1, 2); |
| 228 | assert_eq!(first, 1); |
| 229 | assert_eq!(lines.len(), 2); |
| 230 | assert_eq!(lines[0].text, "1"); |
| 231 | assert!(ring.batch(4, 10).1.is_empty()); |
| 232 | } |
| 233 | |
| 234 | #[test] |
| 235 | fn long_text_is_cut_on_a_char_boundary() { |
| 236 | let text = "é".repeat(RUNNER_LOG_MAX_TEXT); |
| 237 | let cut = truncate_text(&text, RUNNER_LOG_MAX_TEXT); |
| 238 | assert!(cut.len() <= RUNNER_LOG_MAX_TEXT); |
| 239 | assert!(cut.ends_with('é')); |
| 240 | } |
| 241 | } |