1use std::io::{IsTerminal as _, Write};
28use std::sync::atomic::AtomicU64;
29use std::sync::{Arc, Mutex};
30use std::time::Instant;
31
32use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
33use tracing::{Event, Level, Subscriber};
34use tracing_subscriber::layer::Context;
35
36pub const POOL_TARGET: &str = "degenbot::ingest";
38
39pub const AAVE_TARGET: &str = "degenbot::aave";
41
42#[must_use]
47pub fn stderr_opt() -> Option<ProgressDrawTarget> {
48 std::io::stderr()
49 .is_terminal()
50 .then(ProgressDrawTarget::stderr)
51}
52
53struct Record {
58 out: Mutex<Box<dyn Write + Send>>,
59 start: Instant,
60 chunks: AtomicU64,
61}
62
63impl Record {
64 fn line(&self, percent: u64, cursor: Option<u64>, message: &str) {
65 let chunks = self
66 .chunks
67 .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
68 + 1;
69 let elapsed = self.start.elapsed().as_secs();
70 let line = match cursor {
71 Some(cursor) => format!(
72 "{message} cursor={cursor} chunks={chunks} elapsed={elapsed}s pct={percent}%"
73 ),
74 None => format!("{message} chunks={chunks} elapsed={elapsed}s pct={percent}%"),
75 };
76 if let Ok(mut out) = self.out.lock() {
77 let _ = writeln!(out, "{line}");
78 let _ = out.flush();
79 }
80 }
81}
82
83pub struct Painter {
85 bar: Option<ProgressBar>,
86 record: Option<Record>,
87}
88
89impl std::fmt::Debug for Painter {
90 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 f.debug_struct("Painter")
92 .field("bar", &self.bar)
93 .field("record", &self.record.is_some())
94 .finish()
95 }
96}
97
98impl Painter {
99 #[must_use]
103 pub fn from_draw_target(target: Option<ProgressDrawTarget>) -> Self {
104 let bar = target.map(|target| {
105 let bar = ProgressBar::with_draw_target(Some(100), target);
106 let style = ProgressStyle::with_template("{msg} [{bar:40}] {pos:>3}%")
107 .unwrap_or_else(|_| ProgressStyle::default_bar());
108 bar.set_style(style);
109 bar
110 });
111 Self { bar, record: None }
112 }
113
114 #[must_use]
117 pub fn console() -> Self {
118 if std::io::stderr().is_terminal() {
119 return Self::from_draw_target(Some(ProgressDrawTarget::stderr()));
120 }
121 Self {
122 bar: None,
123 record: (!std::io::stdout().is_terminal()).then(|| Record {
124 out: Mutex::new(Box::new(std::io::stdout())),
125 start: Instant::now(),
126 chunks: AtomicU64::new(0),
127 }),
128 }
129 }
130
131 #[cfg(test)]
133 fn with_record(out: Box<dyn Write + Send>) -> Self {
134 Self {
135 bar: None,
136 record: Some(Record {
137 out: Mutex::new(out),
138 start: Instant::now(),
139 chunks: AtomicU64::new(0),
140 }),
141 }
142 }
143
144 #[must_use]
147 pub const fn is_active(&self) -> bool {
148 self.bar.is_some() || self.record.is_some()
149 }
150
151 pub fn paint(&self, percent: u64, message: &str) {
154 if let Some(bar) = &self.bar {
155 bar.set_length(100);
156 bar.set_position(percent.min(100));
157 bar.set_message(message.to_string());
158 }
159 }
160
161 pub fn chunk(&self, percent: u64, cursor: Option<u64>, message: Option<&str>) {
164 if self.bar.is_some() {
165 self.paint(percent, message.unwrap_or("update"));
166 } else if let Some(record) = &self.record {
167 record.line(percent, cursor, message.unwrap_or("update"));
168 }
169 }
170
171 #[must_use]
173 pub fn position(&self) -> Option<u64> {
174 self.bar.as_ref().map(ProgressBar::position)
175 }
176
177 #[must_use]
179 pub fn message(&self) -> Option<String> {
180 self.bar.as_ref().map(ProgressBar::message)
181 }
182
183 pub fn finish(&self) {
185 if let Some(bar) = &self.bar {
186 bar.finish_and_clear();
187 }
188 }
189}
190
191#[derive(Debug)]
194pub struct Layer {
195 painter: Arc<Painter>,
196}
197
198impl Layer {
199 #[must_use]
201 pub fn new(painter: Arc<Painter>) -> Self {
202 Self { painter }
203 }
204}
205
206impl<S: Subscriber> tracing_subscriber::Layer<S> for Layer {
207 fn on_event(&self, event: &Event<'_>, _context: Context<'_, S>) {
208 let metadata = event.metadata();
209 if metadata.target() != POOL_TARGET && metadata.target() != AAVE_TARGET {
210 return;
211 }
212 if *metadata.level() != Level::INFO {
213 return;
214 }
215 let mut fields = Fields::default();
216 event.record(&mut fields);
217 if let Some(percent) = fields.progress_pct {
218 self.painter
219 .chunk(percent, fields.chunk_end, fields.message.as_deref());
220 }
221 }
222}
223
224#[derive(Debug, Default)]
226struct Fields {
227 progress_pct: Option<u64>,
228 chunk_end: Option<u64>,
229 message: Option<String>,
230}
231
232impl tracing::field::Visit for Fields {
233 fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
234 match field.name() {
235 "progress_pct" => self.progress_pct = Some(value),
236 "chunk_end" => self.chunk_end = Some(value),
237 _ => {}
238 }
239 }
240
241 fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
242 if field.name() == "message" {
243 self.message = Some(value.to_string());
244 }
245 }
246
247 fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
248 if field.name() == "message" && self.message.is_none() {
249 self.message = Some(format!("{value:?}"));
250 }
251 }
252}
253
254#[cfg(test)]
255mod tests {
256 #![expect(clippy::unwrap_used)]
257
258 use std::io::Write;
259 use std::sync::{Arc, Mutex};
260
261 use indicatif::ProgressDrawTarget;
262 use tracing_subscriber::layer::SubscriberExt as _;
263
264 use super::{Layer, Painter, AAVE_TARGET, POOL_TARGET};
265
266 struct CaptureSink(Arc<Mutex<Vec<u8>>>);
268
269 impl Write for CaptureSink {
270 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
271 self.0.lock().unwrap().extend_from_slice(buf);
272 Ok(buf.len())
273 }
274
275 fn flush(&mut self) -> std::io::Result<()> {
276 Ok(())
277 }
278 }
279
280 #[test]
281 fn no_draw_target_means_no_painter_and_no_write() {
282 let painter = Painter::from_draw_target(None);
283 assert!(!painter.is_active());
284 painter.paint(100, "pool update: chunk committed");
285 assert_eq!(painter.position(), None);
286 assert_eq!(painter.message(), None);
287 painter.finish();
288 }
289
290 #[test]
291 fn progress_layer_paints_from_the_core_progress_event() {
292 let painter = Arc::new(Painter::from_draw_target(
293 Some(ProgressDrawTarget::hidden()),
294 ));
295 assert!(painter.is_active());
296 let subscriber = tracing_subscriber::registry().with(Layer::new(Arc::clone(&painter)));
297 tracing::subscriber::with_default(subscriber, || {
298 tracing::info!(
299 target: POOL_TARGET,
300 chain_id = 8453i64,
301 chunk_start = 1u64,
302 chunk_end = 500u64,
303 progress_pct = 42u64,
304 "pool update: chunk committed"
305 );
306 });
307 assert_eq!(painter.position(), Some(42));
308 assert_eq!(
309 painter.message().as_deref(),
310 Some("pool update: chunk committed")
311 );
312 painter.finish();
313 }
314
315 #[test]
316 fn unrelated_events_do_not_paint() {
317 let painter = Arc::new(Painter::from_draw_target(
318 Some(ProgressDrawTarget::hidden()),
319 ));
320 let subscriber = tracing_subscriber::registry().with(Layer::new(Arc::clone(&painter)));
321 tracing::subscriber::with_default(subscriber, || {
322 tracing::info!(target: "degenbot::rpc", progress_pct = 99u64, "not a chunk");
323 });
324 assert_eq!(painter.position(), Some(0));
325 painter.finish();
326 }
327
328 #[test]
329 fn non_tty_run_records_one_line_per_chunk() {
330 let captured = Arc::new(Mutex::new(Vec::<u8>::new()));
331 let painter = Arc::new(Painter::with_record(Box::new(CaptureSink(Arc::clone(
332 &captured,
333 )))));
334 let subscriber = tracing_subscriber::registry().with(Layer::new(Arc::clone(&painter)));
335 tracing::subscriber::with_default(subscriber, || {
336 tracing::info!(
337 target: AAVE_TARGET,
338 chain_id = 8453i64,
339 chunk_start = 1u64,
340 chunk_end = 500u64,
341 chunks_committed = 1u64,
342 progress_pct = 42u64,
343 "aave update: chunk committed"
344 );
345 tracing::info!(
346 target: AAVE_TARGET,
347 chunk_end = 1000u64,
348 chunks_committed = 2u64,
349 progress_pct = 84u64,
350 "aave update: chunk committed"
351 );
352 });
353 let text = String::from_utf8(captured.lock().unwrap().clone()).unwrap();
354 let mut lines = text.lines();
355 let first = lines.next().unwrap();
356 assert!(
357 first.starts_with("aave update: chunk committed cursor=500 chunks=1 elapsed="),
358 "unexpected first record: {first}"
359 );
360 assert!(
361 first.ends_with("pct=42%"),
362 "unexpected first record: {first}"
363 );
364 let second = lines.next().unwrap();
365 assert!(
366 second.contains("cursor=1000 chunks=2 ") && second.ends_with("pct=84%"),
367 "unexpected second record: {second}"
368 );
369 assert!(
370 lines.next().is_none(),
371 "one line per committed chunk: {text}"
372 );
373 }
374}