rm-lisa 0.3.2

A logging library for rem-verse, with support for inputs, tasks, and more.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//! [`SuperConsole`]; The Structure that renders everything.
//!
//! This directory contains the base implementation for [`SuperConsole`] the
//! main type that handles displaying all the information we get fed from
//! various sources. It also contains supporting types for the console such
//! as the throttler that ensures we don't eat up all your CPU time with
//! printing to the console too often.
//!
//! Chances are if you're looking to want to do anything with the actual
//! displaying of log lines. This is the place to be.
//!
//! ## Throttling
//!
//! When printing to standard-out, and standard-error we can cause severe
//! CPU contention when we print _too often_ to these channels. As such we
//! apply throttling (think like a buffered writer) to how often we update.
//!
//! There are a couple ways around this:
//!
//! 1. Manually create a super console with [`SuperConsole::new_with_outputs`],
//!    and set the parameter `should_throttle` to false. You can still specify
//!    standard-out/standard-error. ***this will fully disable throttling, and
//!    as a result CPU can go out of control.***
//! 2. Store a reference to [`SuperConsole`], and call [`SuperConsole::tick`]
//!    once the throttling limit has surpassed. You can call tick as many times
//!    as you want, and it will _always_ be safe.

pub mod render_state;
pub mod renderers;
pub mod tracing;

use crate::{
	app_name_to_prefix,
	display::{
		render_state::UnlockedRendererState,
		renderers::{
			ColorConsoleRenderer, ConsoleOutputFeatures, ConsoleRenderer, JSONConsoleRenderer,
			TextConsoleRenderer,
		},
		tracing::SuperConsoleLogMessage,
	},
	errors::LisaError,
	input::InputProvider,
	tasks::TaskEventLogProvider,
};
use parking_lot::{Mutex, RawMutex, lock_api::MutexGuard};
use std::{
	io::{Stderr, Stdout, Write as IoWrite, stderr as get_stderr, stdout as get_stdout},
	sync::Arc,
	time::Duration,
};
use tokio::{
	signal::ctrl_c,
	sync::{
		Mutex as AsyncMutex,
		mpsc::{Receiver as BoundedReceiver, Sender as BoundedSender, channel as bounded_channel},
	},
	task::Builder as TaskBuilder,
	time::sleep,
};

/// How many logs can be queued (this gets flushed every ~15ms, so doesn't need to be too large).
const LOG_CHANNEL_SIZE: usize = 64_usize;

/// Effectively the console "renderer".
///
/// [`SuperConsole`] is responsible for keeping track of the 'rendering'
/// state, and managing it effectively. This crucially does not handle any of
/// the input tracking or any of the other console related bits.
///
/// It is called [`SuperConsole`] as it's output is heavily inspired by the
/// Buck1 renderer also with the name [`SuperConsole`]. Buck2 also has a
/// concept of a [`SuperConsole`], but I don't like it's output at all. So
/// don't confuse it with the rust library 'superconsole', or it's buck2
/// counterpart.
pub struct SuperConsole<
	StdoutTy: ConsoleOutputFeatures + IoWrite + Send + 'static,
	StderrTy: ConsoleOutputFeatures + IoWrite + Send + 'static,
> {
	/// Queue a flush off the underlying messages.
	flush_sender: BoundedSender<()>,
	/// Used to signal that a flush _has_ occured.
	did_do_flush: AsyncMutex<BoundedReceiver<()>>,
	/// The messages to actually log to the screen.
	log_messages: BoundedSender<SuperConsoleLogMessage>,
	/// The underlying renderer that actually prints to stdout, and stderr.
	state: Arc<Mutex<UnlockedRendererState<StdoutTy, StderrTy>>>,
	/// A channel used to stop tick tasking.
	stop_tick_task: BoundedSender<()>,
}

impl SuperConsole<Stdout, Stderr> {
	/// Create a new super console that will print to the programs STDOUT/STDERR.
	///
	/// This will dynamically choose a renderer to use based off the default
	/// renderers that are present in lisa (color, json, and text).
	///
	/// ## Errors
	///
	/// If we could not identify a renderer to use, If we cannot spawn a
	/// background task to render inputs.
	pub fn new(app_name: &'static str) -> Result<Self, LisaError> {
		let stdout_sink = get_stdout();
		let stderr_sink = get_stderr();

		let environment_prefix = app_name_to_prefix(app_name);
		let stdout_renderer = Self::choose_default_renderer(&stdout_sink, &environment_prefix)
			.ok_or(LisaError::NoRendererFound)?;
		let stderr_renderer = Self::choose_default_renderer(&stderr_sink, &environment_prefix)
			.ok_or(LisaError::NoRendererFound)?;

		let (log_messages, log_receiver) = bounded_channel(LOG_CHANNEL_SIZE);
		let (flush_sender, flush_receiver) = bounded_channel(1);
		let (flush_completed_sender, flush_completed_receiver) = bounded_channel(1);
		let (stop_tick_sender, stop_tick_receiver) = bounded_channel(1);

		let state = Arc::new(Mutex::new(UnlockedRendererState::new(
			app_name,
			&environment_prefix,
			(stdout_sink, stderr_sink),
			(stdout_renderer, stderr_renderer),
			log_receiver,
		)));
		Self::spawn_tick_task(
			flush_completed_sender,
			flush_receiver,
			stop_tick_receiver,
			state.clone(),
		)?;

		Ok(Self {
			did_do_flush: AsyncMutex::new(flush_completed_receiver),
			flush_sender,
			log_messages,
			state,
			stop_tick_task: stop_tick_sender,
		})
	}

	/// Create a new super console that will print to the programs STDOUT/STDERR.
	///
	/// In this case the renderers are explicitly passed in allowing for fully
	/// custom rendering. It is the callers job to make sure that they have
	/// respected all and any user preferences for _which_ renderer they want to
	/// use.
	///
	/// ## Errors
	///
	/// If we cannot spawn a background task to render inputs.
	pub fn new_preselected_renderers(
		app_name: &'static str,
		stdout_renderer: Box<dyn ConsoleRenderer>,
		stderr_renderer: Box<dyn ConsoleRenderer>,
	) -> Result<Self, LisaError> {
		let stdout_sink = get_stdout();
		let stderr_sink = get_stderr();

		let environment_prefix = app_name_to_prefix(app_name);
		let (log_messages, log_receiver) = bounded_channel(LOG_CHANNEL_SIZE);
		let (flush_sender, flush_receiver) = bounded_channel(1);
		let (flush_completed_sender, flush_completed_receiver) = bounded_channel(1);
		let (stop_tick_sender, stop_tick_receiver) = bounded_channel(1);

		let state = Arc::new(Mutex::new(UnlockedRendererState::new(
			app_name,
			&environment_prefix,
			(stdout_sink, stderr_sink),
			(stdout_renderer, stderr_renderer),
			log_receiver,
		)));
		Self::spawn_tick_task(
			flush_completed_sender,
			flush_receiver,
			stop_tick_receiver,
			state.clone(),
		)?;

		Ok(Self {
			did_do_flush: AsyncMutex::new(flush_completed_receiver),
			flush_sender,
			log_messages,
			state,
			stop_tick_task: stop_tick_sender,
		})
	}
}

impl<
	StdoutTy: ConsoleOutputFeatures + IoWrite + Send + 'static,
	StderrTy: ConsoleOutputFeatures + IoWrite + Send + 'static,
> SuperConsole<StdoutTy, StderrTy>
{
	/// Create a new super console where outputs go somewhere specific (may not be
	/// stdout/stderr).
	///
	/// ## Errors
	///
	/// If we cannot find a renderer for your given stdout/stderr types, or cannot
	/// spawn a background task to progress the input.
	pub fn new_with_outputs(
		app_name: &'static str,
		stdout: StdoutTy,
		stderr: StderrTy,
	) -> Result<Self, LisaError> {
		let environment_prefix = app_name_to_prefix(app_name);
		let stdout_renderer = Self::choose_default_renderer(&stdout, &environment_prefix)
			.ok_or(LisaError::NoRendererFound)?;
		let stderr_renderer = Self::choose_default_renderer(&stderr, &environment_prefix)
			.ok_or(LisaError::NoRendererFound)?;

		let (log_messages, log_receiver) = bounded_channel(LOG_CHANNEL_SIZE);
		let (flush_sender, flush_receiver) = bounded_channel(1);
		let (flush_completed_sender, flush_completed_receiver) = bounded_channel(1);
		let (stop_tick_sender, stop_tick_receiver) = bounded_channel(1);

		let state = Arc::new(Mutex::new(UnlockedRendererState::new(
			app_name,
			&environment_prefix,
			(stdout, stderr),
			(stdout_renderer, stderr_renderer),
			log_receiver,
		)));
		Self::spawn_tick_task(
			flush_completed_sender,
			flush_receiver,
			stop_tick_receiver,
			state.clone(),
		)?;

		Ok(Self {
			did_do_flush: AsyncMutex::new(flush_completed_receiver),
			flush_sender,
			log_messages,
			state,
			stop_tick_task: stop_tick_sender,
		})
	}

	/// Create a new console outputting to specific places, with specific
	/// renderers.
	///
	/// It is up to the caller to inherit all user preferences for the renderers.
	///
	/// ## Errors
	///
	/// If we cannot spawn a task to tick along the console.
	pub fn new_with_outputs_and_preselected_renderers(
		app_name: &'static str,
		stdout: StdoutTy,
		stderr: StderrTy,
		stdout_renderer: Box<dyn ConsoleRenderer>,
		stderr_renderer: Box<dyn ConsoleRenderer>,
	) -> Result<Self, LisaError> {
		let environment_prefix = app_name_to_prefix(app_name);
		let (log_messages, log_receiver) = bounded_channel(LOG_CHANNEL_SIZE);
		let (flush_sender, flush_receiver) = bounded_channel(1);
		let (flush_completed_sender, flush_completed_receiver) = bounded_channel(1);
		let (stop_tick_sender, stop_tick_receiver) = bounded_channel(1);

		let state = Arc::new(Mutex::new(UnlockedRendererState::new(
			app_name,
			&environment_prefix,
			(stdout, stderr),
			(stdout_renderer, stderr_renderer),
			log_receiver,
		)));
		Self::spawn_tick_task(
			flush_completed_sender,
			flush_receiver,
			stop_tick_receiver,
			state.clone(),
		)?;

		Ok(Self {
			did_do_flush: AsyncMutex::new(flush_completed_receiver),
			flush_sender,
			log_messages,
			state,
			stop_tick_task: stop_tick_sender,
		})
	}

	/// Request this console immediately working on flushing it's contents.
	///
	/// THIS WILL NOT RETURN UNTIL THE FLUSH HAS BEEN COMPLETED.
	pub async fn flush(&self) {
		let mut did_do_flush_lock = self.did_do_flush.lock().await;
		_ = self.flush_sender.send(()).await;
		_ = did_do_flush_lock.recv().await;
	}

	/// Get the current render state.
	///
	/// *NOTE: WHILE HOLDING TO THIS YOU WILL BE LOCKING LOGS FROM RENDERING*.
	pub fn get_render_state(
		&self,
	) -> MutexGuard<'_, RawMutex, UnlockedRendererState<StdoutTy, StderrTy>> {
		self.state.lock()
	}

	/// Set the current input provider.
	pub fn set_input_provider<Ty: InputProvider + Sized + 'static>(&self, provider: Ty) {
		self.state.lock().set_input_provider(Box::new(provider));
	}

	/// Set the current event log task provider.
	pub fn set_task_provider<Ty: TaskEventLogProvider + Sized + 'static>(&self, provider: Ty) {
		self.state.lock().set_task_provider(Box::new(provider));
	}

	/// Set a channel to receive inputs on rather than needing to call
	/// [`Self::get_unprocessed_inputs`].
	pub fn set_input_channel(&self, channel: BoundedSender<String>) {
		self.state.lock().set_completed_input_channel(channel);
	}

	/// Mark the current input as active.
	///
	/// ## Errors
	///
	/// If the input provider errors trying to be marked as active.
	pub fn set_input_active(&self, active: bool) -> Result<(), LisaError> {
		self.state.lock().set_input_active(active)
	}

	/// Get a series of unprocessed inputs from the input provider.
	///
	/// In general prefer using [`Self::set_input_channel`] which gives you a
	/// channel you can poll for inputs with locking this like with poll for
	/// inputs, and rendering.
	pub fn get_unprocessed_inputs(&self) -> Vec<String> {
		self.state.lock().get_unprocessed_inputs()
	}

	/// Look at all the default renderers, and return whichever one is
	/// compatible if any are.
	#[must_use]
	pub fn choose_default_renderer(
		features: &dyn ConsoleOutputFeatures,
		environment_prefix: &str,
	) -> Option<Box<dyn ConsoleRenderer>> {
		let color = ColorConsoleRenderer::new();
		if color.should_use_renderer(features, environment_prefix) {
			return Some(Box::new(color));
		}
		std::mem::drop(color);

		let json = JSONConsoleRenderer::new();
		if json.should_use_renderer(features, environment_prefix) {
			return Some(Box::new(json));
		}
		std::mem::drop(json);

		let text = TextConsoleRenderer::new();
		if text.should_use_renderer(features, environment_prefix) {
			return Some(Box::new(text));
		}
		std::mem::drop(text);

		None
	}

	/// Cross OS wrapper for getting the current terminal height & width.
	///
	/// This backs off of `termios` on many non-windows OS, and then
	/// `GetConsoleScreenBufferInfo` on windows. This will look at standard
	/// in file descriptor (as standard out/standard error can be individually
	/// redirected).
	#[allow(
		// Dependent on OS...
		unreachable_code,
	)]
	#[must_use]
	pub fn terminal_height_and_width() -> Option<(u16, u16)> {
		#[cfg(any(
			target_os = "aix",
			target_os = "linux",
			target_os = "android",
			target_os = "macos",
			target_os = "ios",
			target_os = "freebsd",
			target_os = "openbsd",
			target_os = "netbsd",
			target_os = "dragonfly",
			target_os = "solaris",
			target_os = "illumos",
			target_os = "haiku",
		))]
		{
			use crate::termios::tcgetwinsize;
			let winsize = tcgetwinsize(0).ok()?;
			return Some((winsize.ws_row, winsize.ws_col));
		}

		#[cfg(target_os = "windows")]
		{
			use windows::Win32::System::Console::{
				CONSOLE_SCREEN_BUFFER_INFO, GetConsoleScreenBufferInfo, GetStdHandle,
				STD_INPUT_HANDLE,
			};

			let mut buffer_info = CONSOLE_SCREEN_BUFFER_INFO::default();
			let handle = unsafe { GetStdHandle(STD_INPUT_HANDLE) }.ok()?;
			unsafe { GetConsoleScreenBufferInfo(handle, &raw mut buffer_info).ok()? };
			return Some((
				u16::try_from(buffer_info.dwSize.Y).unwrap_or(u16::MIN),
				u16::try_from(buffer_info.dwSize.X).unwrap_or(u16::MIN),
			));
		}

		None
	}

	/// Cross OS wrapper for getting the current terminal height.
	///
	/// This backs off of `termios` on many non-windows OS, and then
	/// `GetConsoleScreenBufferInfo` on windows. This will look at standard
	/// in file descriptor (as standard out/standard error can be individually
	/// redirected).
	#[must_use]
	pub fn terminal_height() -> Option<u16> {
		Self::terminal_height_and_width().map(|tuple| tuple.0)
	}

	/// Cross OS wrapper for getting the current terminal width.
	///
	/// This backs off of `termios` on many non-windows OS, and then
	/// `GetConsoleScreenBufferInfo` on windows. This will look at standard
	/// in file descriptor (as standard out/standard error can be individually
	/// redirected).
	#[must_use]
	pub fn terminal_width() -> Option<u16> {
		Self::terminal_height_and_width().map(|tuple| tuple.1)
	}

	/// The function that is used to actually queue a log message.
	///
	/// This is what gets called by tracing and queues a message to be
	/// rendered. Called when a tokio runtime _does_ exist on the thread.
	pub(crate) async fn log(&self, log_message: SuperConsoleLogMessage) {
		_ = self.log_messages.send(log_message).await;
	}

	/// The function that is used to actually queue a log message.
	///
	/// This is what gets called by tracing and queues a message to be rendered,
	/// when a tokio runtime is not present on the thread.
	pub(crate) async fn log_sync(&self, log_message: SuperConsoleLogMessage) {
		_ = self.log_messages.send(log_message).await;
	}

	fn spawn_tick_task(
		flush_completed_sender: BoundedSender<()>,
		mut flush_recveiver: BoundedReceiver<()>,
		mut receiver: BoundedReceiver<()>,
		state: Arc<Mutex<UnlockedRendererState<StdoutTy, StderrTy>>>,
	) -> Result<(), LisaError> {
		TaskBuilder::new()
			.name("lisa::display::SuperConsole::tick")
			.spawn(async move {
				loop {
					let mut flush_queued = false;

					tokio::select! {
						() = sleep(Duration::from_millis(12)) => {}
						_ = flush_recveiver.recv() => {
							flush_queued = true;
						}
						_ = receiver.recv() => {
							break;
						}
						_ = ctrl_c() => {
							break;
						}
					}

					_ = state.lock().render_if_needed();
					if flush_queued {
						_ = flush_completed_sender.send(()).await;
					}
				}
			})?;

		Ok(())
	}
}

impl<
	StdoutTy: ConsoleOutputFeatures + IoWrite + Send,
	StderrTy: ConsoleOutputFeatures + IoWrite + Send,
> Drop for SuperConsole<StdoutTy, StderrTy>
{
	fn drop(&mut self) {
		let cloned_flush_sender = self.flush_sender.clone();
		let cloned_stop_tick_task = self.stop_tick_task.clone();

		_ = TaskBuilder::new()
			.name("lisa::display::SuperConsole::flush_drop")
			.spawn(async move {
				_ = cloned_flush_sender.send(()).await;
				_ = cloned_stop_tick_task.send(()).await;
			});
	}
}

#[cfg(test)]
mod unit_tests {
	use super::*;

	#[test]
	pub fn is_send_sync() {
		fn accepts_send_sync<Ty: Send + Sync>() {}

		accepts_send_sync::<SuperConsole<Stdout, Stderr>>();
	}

	#[test]
	pub fn term_size_matches_terminal_size_crate() {
		assert_eq!(
			SuperConsole::<Stdout, Stderr>::terminal_width(),
			terminal_size::terminal_size().map(|item| item.0.0),
			"{:?} != {:?}, (us == term_size) [WIDTH]",
			SuperConsole::<Stdout, Stderr>::terminal_width()
				.expect("Failed to query terminal width"),
			terminal_size::terminal_size().map(|item| item.0.0)
		);

		assert_eq!(
			SuperConsole::<Stdout, Stderr>::terminal_height(),
			terminal_size::terminal_size().map(|item| item.1.0),
			"{:?} != {:?}, (us == term_size) [HEIGHT]",
			SuperConsole::<Stdout, Stderr>::terminal_width()
				.expect("Failed to query terminal height"),
			terminal_size::terminal_size().map(|item| item.1.0)
		);
	}
}