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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
//! Integrate a [`crate::display::SuperConsole`] into the [`tracing`] crate.

use crate::display::{SuperConsole, renderers::ConsoleOutputFeatures};
use chrono::prelude::*;
use fnv::FnvHashMap;
use serde_json::{Value as JSONValue, json};
use std::{
	error::Error as StdError,
	fmt::{Debug, Display, Formatter, Result as FmtResult},
	hash::BuildHasherDefault,
	io::Write as IoWrite,
	sync::Arc,
};
use tokio::runtime::Handle;
use tracing::{
	Event, Level, Metadata, Subscriber,
	field::{Field, Visit},
	span::{Attributes as SpanAttributes, Id as SpanId},
	subscriber::Interest,
};
use tracing_subscriber::{Layer, layer::Context, registry::LookupSpan};
use valuable::{
	Fields, NamedField, NamedValues, StructDef, Structable, Valuable, Value, Visit as ValuableVisit,
};
use valuable_serde::Serializable;

/// A connector that connects hooks up [`tracing`] to a specific [`SuperConsole`].
pub struct TracableSuperConsole<
	StdoutTy: IoWrite + ConsoleOutputFeatures + Send + 'static,
	StderrTy: IoWrite + ConsoleOutputFeatures + Send + 'static,
> {
	/// The underlying super console to log too.
	console: Arc<SuperConsole<StdoutTy, StderrTy>>,
}

impl<
	StdoutTy: IoWrite + ConsoleOutputFeatures + Send + 'static,
	StderrTy: IoWrite + ConsoleOutputFeatures + Send + 'static,
> TracableSuperConsole<StdoutTy, StderrTy>
{
	#[must_use]
	pub fn new(console: Arc<SuperConsole<StdoutTy, StderrTy>>) -> Self {
		Self { console }
	}
}

impl<
	StdoutTy: IoWrite + ConsoleOutputFeatures + Send + 'static,
	StderrTy: IoWrite + ConsoleOutputFeatures + Send + 'static,
	SubscriberTy,
> Layer<SubscriberTy> for TracableSuperConsole<StdoutTy, StderrTy>
where
	SubscriberTy: Subscriber + for<'lookup> LookupSpan<'lookup>,
{
	fn register_callsite(&self, _metadata: &'static Metadata<'static>) -> Interest {
		Interest::always()
	}

	fn on_new_span(&self, attrs: &SpanAttributes<'_>, id: &SpanId, ctx: Context<'_, SubscriberTy>) {
		let mut span_data = SuperConsoleSpanData::new();
		span_data.reserve(attrs.fields().len());
		attrs.record(&mut span_data);

		if let Some(span) = ctx.span(id) {
			span.extensions_mut().insert(span_data);
		}
	}

	fn on_event(&self, event: &Event<'_>, ctxt: Context<'_, SubscriberTy>) {
		let mut visitor = SuperConsoleLogMessage::new();

		let mut optional_span = ctxt.event_span(event);
		while let Some(current_span) = optional_span {
			if let Some(ext) = current_span.extensions().get::<SuperConsoleSpanData>() {
				visitor.visit_span(ext);
			}
			optional_span = current_span.parent();
		}

		visitor.set_level(*event.metadata().level());
		visitor.reserve_metadata_space(event.metadata().fields().len());
		event.record(&mut visitor);
		// Are we in a tokio runtime? if so we need to block in place.
		if let Ok(h) = Handle::try_current() {
			tokio::task::block_in_place(move || {
				h.block_on(async { self.console.log(visitor).await });
			});
		} else {
			_ = self.console.log_sync(visitor);
		}
	}
}

/// A structure that represents a "log message".
///
/// This is implemented through a tracing visitor that visits multiple tracing
/// [`tracing_subscriber::registry::SpanRef`]'s, and finally one
/// [`tracing::Event`] to generate a final log message.
#[allow(
	// In this case booleans are the best way to track state through
	// tracing.
	clippy::struct_excessive_bools,
)]
#[derive(Clone, Debug, PartialEq)]
pub struct SuperConsoleLogMessage {
	/// The time this event message was created at.
	at: DateTime<Utc>,
	/// An optional color code to use when rendering a terminal.
	color: Option<String>,
	/// Force combine the message + fields to render without any gutter
	/// that may exist.
	force_combine: bool,
	/// If we should hide the 'fields' values when rendering 'for humans'
	/// e.g. not in JSON.
	hide_fields_for_humans: bool,
	/// The "ID" or unique identifier for this log message.
	///
	/// Not shown in color/text, but useful for JSON where you want to key on
	/// what fields may or may not be in a message.
	id: Option<String>,
	/// The level at which the log message was produced.
	level: Level,
	/// The "name" of the subsystem that created this log message.
	subsystem: Option<String>,
	/// A way to turn off "decorations" for the color printing.
	should_decorate: bool,
	/// If we should target STDOUT, this is false by default and will head to STDERR.
	target_stdout: bool,
	/// The underlying message.
	message: Option<String>,
	/// Extra bits of metadata to render.
	metadata: FnvHashMap<&'static str, FlattenedTracingField>,
}

impl SuperConsoleLogMessage {
	/// Create a new visitor that is capable of visiting events.
	#[must_use]
	pub(self) fn new() -> Self {
		Self {
			at: Utc::now(),
			color: None,
			id: None,
			force_combine: false,
			hide_fields_for_humans: false,
			level: Level::INFO,
			subsystem: None,
			should_decorate: true,
			target_stdout: false,
			message: None,
			metadata: FnvHashMap::with_capacity_and_hasher(0, BuildHasherDefault::default()),
		}
	}

	/// Reserve an addtional N amount of space. Used to save on re-allocs.
	pub(self) fn reserve_metadata_space(&mut self, additional: usize) {
		self.metadata.reserve(additional);
	}

	/// Get the time this log message occured at.
	#[must_use]
	pub const fn at(&self) -> &DateTime<Utc> {
		&self.at
	}

	/// Get a color to use when rendering on the terminal, if the logger
	/// chooses to use this.
	#[must_use]
	pub fn color(&self) -> Option<&str> {
		self.color.as_deref()
	}

	/// Check if we should hide fields "for humans", e.g. not in JSON.
	#[must_use]
	pub const fn should_hide_fields_for_humans(&self) -> bool {
		self.hide_fields_for_humans
	}

	/// The "ID" or unique identifier for this log message.
	///
	/// Not shown in color/text, but useful for JSON where you want to key on
	/// what fields may or may not be in a message.
	#[must_use]
	pub fn id(&self) -> Option<&str> {
		self.id.as_deref()
	}

	/// If we should force combine fields, and messages for this log message.
	#[must_use]
	pub const fn force_combine(&self) -> bool {
		self.force_combine
	}

	/// The "name" of the subsystem that created this log message.
	#[must_use]
	pub fn subsytem(&self) -> Option<&str> {
		self.subsystem.as_deref()
	}

	/// The message or 'log line'.
	#[must_use]
	pub fn message(&self) -> Option<&str> {
		self.message.as_deref()
	}

	/// Get the log level this message was produced at.
	#[must_use]
	pub const fn level(&self) -> &Level {
		&self.level
	}

	#[must_use]
	pub const fn should_decorate(&self) -> bool {
		self.should_decorate
	}

	#[must_use]
	pub const fn towards_stdout(&self) -> bool {
		self.target_stdout
	}

	/// Any extra set of fields folks have attached.
	///
	/// NOTE: structured fields here through valuable will be rendered as
	/// their keys being: "key.innerkey"="value" here.
	#[must_use]
	pub const fn metadata(&self) -> &FnvHashMap<&'static str, FlattenedTracingField> {
		&self.metadata
	}

	/// Set the log level for this even.
	pub(self) fn set_level(&mut self, level: Level) {
		self.level = level;
	}

	/// Visit a span data and append all information from the spans into
	/// our context.
	///
	/// This expects to be called repeatedly (one for each span), and should be
	/// visited in the order of current span first, followed by it's parent, etc.
	pub(self) fn visit_span(&mut self, ext: &SuperConsoleSpanData) {
		for (key, value) in ext.fields() {
			match *key {
				"id" => {
					if self.id.is_none() {
						_ = self.id.insert(Self::get_field_as_string(value));
					}
				}
				"lisa.force_combine_fields" => {
					self.force_combine = Self::get_field_as_bool(value);
				}
				"lisa.hide_fields_for_humans" => {
					self.hide_fields_for_humans = Self::get_field_as_bool(value);
				}
				"lisa.subsystem" => {
					if self.subsystem.is_none() {
						_ = self.subsystem.insert(Self::get_field_as_string(value));
					}
				}
				"lisa.stdout" => {
					self.target_stdout = Self::get_field_as_bool(value);
				}
				"lisa.decorate" => {
					self.should_decorate = Self::get_field_as_bool(value);
				}
				key_value => {
					if !self.metadata.contains_key(key_value) {
						self.metadata.insert(key_value, value.clone());
					}
				}
			}
		}
	}

	/// Get a field as a boolean.
	fn get_field_as_bool(value: &FlattenedTracingField) -> bool {
		match value {
			FlattenedTracingField::Null => false,
			FlattenedTracingField::Boolean(val) => *val,
			FlattenedTracingField::Bytes(val) => !val.is_empty() && val[0] > 0,
			FlattenedTracingField::Float(val) => *val > 0.0,
			FlattenedTracingField::Int(val) => *val > 0,
			FlattenedTracingField::IntLarge(val) => *val > 0,
			FlattenedTracingField::Str(val) => val.eq_ignore_ascii_case("true") || val == "1",
			FlattenedTracingField::UnsignedInt(val) => *val > 0,
			FlattenedTracingField::UnsignedIntLarge(val) => *val > 0,
			FlattenedTracingField::List(val) => !val.is_empty(),
			FlattenedTracingField::Object(val) => !val.is_empty(),
		}
	}

	/// Get a field as an owned string.
	fn get_field_as_string(value: &FlattenedTracingField) -> String {
		match value {
			FlattenedTracingField::Null => String::with_capacity(0),
			FlattenedTracingField::Boolean(val) => format!("{val}"),
			FlattenedTracingField::Float(val) => format!("{val}"),
			FlattenedTracingField::Int(val) => format!("{val}"),
			FlattenedTracingField::IntLarge(val) => format!("{val}"),
			FlattenedTracingField::UnsignedInt(val) => format!("{val}"),
			FlattenedTracingField::UnsignedIntLarge(val) => format!("{val}"),
			FlattenedTracingField::Str(val) => val.clone(),
			FlattenedTracingField::Bytes(val) => format!("{val:02x?}"),
			FlattenedTracingField::List(_) | FlattenedTracingField::Object(_) => {
				format!("{value}")
			}
		}
	}

	fn do_field_visit(&mut self, field: &Field, value: FlattenedTracingField) {
		match field.name() {
			"id" => {
				_ = self.id.insert(Self::get_field_as_string(&value));
			}
			"lisa.subsystem" => {
				_ = self.subsystem.insert(Self::get_field_as_string(&value));
			}
			"lisa.stdout" => {
				self.target_stdout = Self::get_field_as_bool(&value);
			}
			"lisa.decorate" => {
				self.should_decorate = Self::get_field_as_bool(&value);
			}
			"lisa.force_combine_fields" => {
				self.force_combine = Self::get_field_as_bool(&value);
			}
			"lisa.hide_fields_for_humans" => {
				self.hide_fields_for_humans = Self::get_field_as_bool(&value);
			}
			"message" => {
				_ = self.message.insert(Self::get_field_as_string(&value));
			}
			key_value => {
				self.metadata.insert(key_value, value);
			}
		}
	}
}

impl Visit for SuperConsoleLogMessage {
	fn record_f64(&mut self, field: &Field, value: f64) {
		self.do_field_visit(field, FlattenedTracingField::Float(value));
	}

	fn record_i64(&mut self, field: &Field, value: i64) {
		self.do_field_visit(field, FlattenedTracingField::Int(value));
	}

	fn record_u64(&mut self, field: &Field, value: u64) {
		self.do_field_visit(field, FlattenedTracingField::UnsignedInt(value));
	}

	fn record_i128(&mut self, field: &Field, value: i128) {
		self.do_field_visit(field, FlattenedTracingField::IntLarge(value));
	}

	fn record_u128(&mut self, field: &Field, value: u128) {
		self.do_field_visit(field, FlattenedTracingField::UnsignedIntLarge(value));
	}

	fn record_bool(&mut self, field: &Field, value: bool) {
		self.do_field_visit(field, FlattenedTracingField::Boolean(value));
	}

	fn record_str(&mut self, field: &Field, value: &str) {
		self.do_field_visit(field, FlattenedTracingField::Str(value.to_owned()));
	}

	fn record_bytes(&mut self, field: &Field, value: &[u8]) {
		self.do_field_visit(field, FlattenedTracingField::Bytes(Vec::from(value)));
	}

	fn record_error(&mut self, field: &Field, value: &(dyn StdError + 'static)) {
		self.do_field_visit(field, FlattenedTracingField::Str(format!("{value}")));
	}

	fn record_debug(&mut self, field: &Field, value: &dyn Debug) {
		self.do_field_visit(field, FlattenedTracingField::Str(format!("{value:?}")));
	}

	fn record_value(&mut self, field: &Field, value: Value<'_>) {
		self.do_field_visit(field, valuable_to_flattened(value));
	}
}

const SUPER_CONSOLE_LOG_MESSAGE_FIELDS: &[NamedField<'static>] = &[
	NamedField::new("id"),
	NamedField::new("level"),
	NamedField::new("subsystem"),
	NamedField::new("should_decorate"),
	NamedField::new("target_stdout"),
	NamedField::new("metadata"),
];

impl Structable for SuperConsoleLogMessage {
	fn definition(&self) -> StructDef<'_> {
		StructDef::new_static(
			"SuperConsoleLogMessage",
			Fields::Named(SUPER_CONSOLE_LOG_MESSAGE_FIELDS),
		)
	}
}

impl Valuable for SuperConsoleLogMessage {
	fn as_value(&self) -> Value<'_> {
		Value::Structable(self)
	}

	fn visit(&self, visitor: &mut dyn ValuableVisit) {
		visitor.visit_named_fields(&NamedValues::new(
			SUPER_CONSOLE_LOG_MESSAGE_FIELDS,
			&[
				Valuable::as_value(&self.id),
				Valuable::as_value(&format!("{}", self.level())),
				Valuable::as_value(&self.subsystem),
				Valuable::as_value(&self.should_decorate),
				Valuable::as_value(&self.target_stdout),
				Valuable::as_value(&self.metadata),
			],
		));
	}
}

/// A field that gets stored on a tracing span, or event.
///
/// We keep track of tracing fields in this structured format. Specifically
/// all fields are stored 'flattened' so `{event: {key: 10}}` gets stored as a
/// single key/value: `event.key=10`.
///
/// They are stored to match 1:1 with the tracing types that generate them, so
/// it's easy to format in various types of serialization formats. The only two
/// formats that don't get a specific value are:
///
/// - `Error`: because of lifetime issues we will render it as it's Display trait.
/// - `Debug`: because of limetime issues we will render it as it's Debug trait.
#[derive(Clone, PartialEq, Valuable)]
pub enum FlattenedTracingField {
	Null,
	Float(f64),
	Int(i64),
	UnsignedInt(u64),
	IntLarge(i128),
	UnsignedIntLarge(u128),
	Boolean(bool),
	Str(String),
	Bytes(Vec<u8>),
	List(Vec<FlattenedTracingField>),
	Object(FnvHashMap<String, FlattenedTracingField>),
}

impl FlattenedTracingField {
	/// Get the total count of inner fields that will be rendered.
	#[must_use]
	pub fn field_count(&self) -> usize {
		match self {
			FlattenedTracingField::Boolean(_)
			| FlattenedTracingField::Bytes(_)
			| FlattenedTracingField::Float(_)
			| FlattenedTracingField::Int(_)
			| FlattenedTracingField::IntLarge(_)
			| FlattenedTracingField::Null
			| FlattenedTracingField::Str(_)
			| FlattenedTracingField::UnsignedInt(_)
			| FlattenedTracingField::UnsignedIntLarge(_) => 1,
			FlattenedTracingField::List(list) => {
				list.iter().map(FlattenedTracingField::field_count).sum()
			}
			FlattenedTracingField::Object(obj) => {
				obj.values().map(FlattenedTracingField::field_count).sum()
			}
		}
	}
}

impl Display for FlattenedTracingField {
	fn fmt(&self, fmt: &mut Formatter<'_>) -> FmtResult {
		match self {
			Self::Null => write!(fmt, ""),
			Self::Boolean(value) => write!(fmt, "{value}"),
			Self::Bytes(value) => write!(fmt, "{value:02x?}"),
			Self::Float(value) => write!(fmt, "{value}"),
			Self::Int(value) => write!(fmt, "{value}"),
			Self::IntLarge(value) => write!(fmt, "{value}"),
			Self::Str(value) => write!(fmt, "{value}"),
			Self::UnsignedInt(value) => write!(fmt, "{value}"),
			Self::UnsignedIntLarge(value) => write!(fmt, "{value}"),
			Self::List(value) => {
				for (idx, val) in value.iter().enumerate() {
					if idx != 0 {
						write!(fmt, ",")?;
					}
					write!(fmt, "{val}")?;
				}
				Ok(())
			}
			Self::Object(value) => {
				write!(fmt, "{{")?;
				let mut written_once = false;
				for (key, val) in value {
					if written_once {
						write!(fmt, ",")?;
					}
					written_once = true;
					write!(fmt, "{key}={val}")?;
				}
				write!(fmt, "}}")
			}
		}
	}
}

impl Debug for FlattenedTracingField {
	fn fmt(&self, fmt: &mut Formatter<'_>) -> FmtResult {
		match self {
			Self::Null => write!(fmt, ""),
			Self::Boolean(value) => write!(fmt, "{value:?}"),
			Self::Bytes(value) => write!(fmt, "{value:02x?}"),
			Self::Float(value) => write!(fmt, "{value:?}"),
			Self::Int(value) => write!(fmt, "{value:?}"),
			Self::IntLarge(value) => write!(fmt, "{value:?}"),
			Self::Str(value) => write!(fmt, "{value:?}"),
			Self::UnsignedInt(value) => write!(fmt, "{value:?}"),
			Self::UnsignedIntLarge(value) => write!(fmt, "{value:?}"),
			Self::List(value) => {
				let mut has_written = false;
				for val in value {
					if has_written {
						write!(fmt, ",")?;
					} else {
						has_written = true;
					}
					write!(fmt, "{val:?}")?;
				}
				Ok(())
			}
			Self::Object(value) => {
				write!(fmt, "{{")?;
				let mut written_once = false;
				for (key, val) in value {
					if written_once {
						write!(fmt, ",")?;
					}
					written_once = true;
					write!(fmt, "{key}={val:?}")?;
				}
				write!(fmt, "}}")
			}
		}
	}
}

/// [`tracing_subscriber::registry::SpanRef`]'s don't store the actual values.
///
/// This is to support cases like embedded where keeping the span data is too
/// expensive. Luckily for us! Lisa doesn't need to support embedded data, and
/// won't have too!
///
/// This means we can just keep a map of the fields around in memory.
#[derive(Clone, Debug, PartialEq, Valuable)]
struct SuperConsoleSpanData {
	/// Fields that are recorded as part of this span.
	fields: FnvHashMap<&'static str, FlattenedTracingField>,
}

impl SuperConsoleSpanData {
	#[must_use]
	pub fn new() -> Self {
		Self {
			fields: FnvHashMap::with_capacity_and_hasher(0, BuildHasherDefault::default()),
		}
	}

	/// Reserve an addtional N amount of space. Used to save on re-allocs.
	pub fn reserve(&mut self, additional: usize) {
		self.fields.reserve(additional);
	}

	#[must_use]
	pub fn fields(&self) -> &FnvHashMap<&'static str, FlattenedTracingField> {
		&self.fields
	}
}

impl Visit for SuperConsoleSpanData {
	fn record_f64(&mut self, field: &Field, value: f64) {
		self.fields
			.insert(field.name(), FlattenedTracingField::Float(value));
	}

	fn record_i64(&mut self, field: &Field, value: i64) {
		self.fields
			.insert(field.name(), FlattenedTracingField::Int(value));
	}

	fn record_u64(&mut self, field: &Field, value: u64) {
		self.fields
			.insert(field.name(), FlattenedTracingField::UnsignedInt(value));
	}

	fn record_i128(&mut self, field: &Field, value: i128) {
		self.fields
			.insert(field.name(), FlattenedTracingField::IntLarge(value));
	}

	fn record_u128(&mut self, field: &Field, value: u128) {
		self.fields
			.insert(field.name(), FlattenedTracingField::UnsignedIntLarge(value));
	}

	fn record_bool(&mut self, field: &Field, value: bool) {
		self.fields
			.insert(field.name(), FlattenedTracingField::Boolean(value));
	}

	fn record_str(&mut self, field: &Field, value: &str) {
		self.fields
			.insert(field.name(), FlattenedTracingField::Str(value.to_owned()));
	}

	fn record_bytes(&mut self, field: &Field, value: &[u8]) {
		self.fields
			.insert(field.name(), FlattenedTracingField::Bytes(Vec::from(value)));
	}

	fn record_error(&mut self, field: &Field, value: &(dyn StdError + 'static)) {
		self.fields
			.insert(field.name(), FlattenedTracingField::Str(format!("{value}")));
	}

	fn record_debug(&mut self, field: &Field, value: &dyn Debug) {
		self.fields.insert(
			field.name(),
			FlattenedTracingField::Str(format!("{value:?}")),
		);
	}

	fn record_value(&mut self, field: &Field, value: Value<'_>) {
		self.fields
			.insert(field.name(), valuable_to_flattened(value));
	}
}

/// Convert a valuable type into a Flattened tracing field.
///
/// This backs off of [`valuable_serde::Serializable`] to provide the actual
/// implementation of converting to a serde set of types. Then we take those
/// serde types and turn them into a tracing field.
#[must_use]
fn valuable_to_flattened(value: Value<'_>) -> FlattenedTracingField {
	json_value_to_flattened(json!(Serializable::new(value)))
}

/// Convert a json value into a Flattened tracing field.
#[must_use]
fn json_value_to_flattened(as_json_value: JSONValue) -> FlattenedTracingField {
	match as_json_value {
		JSONValue::Null => FlattenedTracingField::Null,
		JSONValue::Bool(val) => FlattenedTracingField::Boolean(val),
		JSONValue::Number(val) => {
			if let Some(float) = val.as_f64() {
				FlattenedTracingField::Float(float)
			} else if let Some(uint) = val.as_u64() {
				FlattenedTracingField::UnsignedInt(uint)
			} else if let Some(int) = val.as_i64() {
				FlattenedTracingField::Int(int)
			} else if let Some(uint) = val.as_u128() {
				FlattenedTracingField::UnsignedIntLarge(uint)
			} else if let Some(int) = val.as_i128() {
				FlattenedTracingField::IntLarge(int)
			} else {
				FlattenedTracingField::Null
			}
		}
		JSONValue::String(val) => FlattenedTracingField::Str(val.clone()),
		JSONValue::Array(val) => {
			let mut list = Vec::with_capacity(val.len());
			for item in val {
				list.push(json_value_to_flattened(item));
			}
			FlattenedTracingField::List(list)
		}
		JSONValue::Object(val) => {
			let mut obj =
				FnvHashMap::with_capacity_and_hasher(val.len(), BuildHasherDefault::default());
			for (key, value) in val {
				obj.insert(key, json_value_to_flattened(value));
			}
			FlattenedTracingField::Object(obj)
		}
	}
}

#[cfg(test)]
mod unit_tests {
	use super::*;
	use serde_json::{Value as JSONValue, json};

	#[test]
	pub fn super_console_span_data_reservation() {
		let mut span = SuperConsoleSpanData::new();
		assert_eq!(
			span.fields().capacity(),
			0,
			"SuperConsoleSpanData new should start with a 0 capacity item!",
		);
		span.reserve(10);
		assert!(
			span.fields().capacity() >= 10,
			"SuperConsoleSpanData did not our first 10 items: {}",
			span.fields.capacity(),
		);
	}

	#[test]
	pub fn valuable_to_flattened_simple_conversion() {
		#[derive(Valuable)]
		struct InnerObject {
			array: Vec<u64>,
		}
		#[derive(Valuable)]
		struct SimpleObject {
			null: Option<bool>,
			bool: bool,
			real: u64,
			float: f64,
			str: String,
			array: Vec<String>,
			inner_obj: InnerObject,
		}

		let serializable = SimpleObject {
			null: None,
			bool: true,
			real: 10,
			float: 10.5,
			str: "hello".to_owned(),
			array: vec!["oh".to_owned(), "hello".to_owned(), "there".to_owned()],
			inner_obj: InnerObject {
				array: vec![10, 11, 12],
			},
		};

		let mut global_object = FnvHashMap::default();
		global_object.insert("null".to_owned(), FlattenedTracingField::Null);
		global_object.insert("bool".to_owned(), FlattenedTracingField::Boolean(true));
		global_object.insert("real".to_owned(), FlattenedTracingField::Float(10.0));
		global_object.insert("float".to_owned(), FlattenedTracingField::Float(10.5));
		global_object.insert(
			"str".to_owned(),
			FlattenedTracingField::Str("hello".to_owned()),
		);
		global_object.insert(
			"array".to_owned(),
			FlattenedTracingField::List(vec![
				FlattenedTracingField::Str("oh".to_owned()),
				FlattenedTracingField::Str("hello".to_owned()),
				FlattenedTracingField::Str("there".to_owned()),
			]),
		);

		let mut inner_object = FnvHashMap::default();
		inner_object.insert(
			"array".to_owned(),
			FlattenedTracingField::List(vec![
				FlattenedTracingField::Float(10.0),
				FlattenedTracingField::Float(11.0),
				FlattenedTracingField::Float(12.0),
			]),
		);
		global_object.insert(
			"inner_obj".to_owned(),
			FlattenedTracingField::Object(inner_object),
		);

		assert_eq!(
			valuable_to_flattened(serializable.as_value()),
			FlattenedTracingField::Object(global_object),
			"Valuable to flattened differed: {:?}",
			valuable_to_flattened(serializable.as_value()),
		);
	}

	/// Do a basic JSON -> FlattenedTracingField conversion.
	///
	/// Right now we haven't had bugs here so this is mostly just a simple check
	/// of each type of things.
	#[test]
	pub fn json_to_flattened_simple_conversion() {
		let json_nul = JSONValue::Null;
		let json_bool = json!(true);
		let json_real = json!(100);
		let json_flot = json!(10.5);
		let json_strg = json!("hello world!");
		let json_arry = json!(["oh no", "why did", "we do this"]);
		let json_objc = json!({
			"a": false,
			"b": 10,
			"c": 10.2,
			"d": "hello world",
			"e": ["a", "b", "c"],
			"f": {
				"g": [10, 11, 12],
			},
		});

		assert_eq!(
			json_value_to_flattened(json_nul.clone()),
			FlattenedTracingField::Null,
			"Converting JSON NULL did not produce FTF Null: {}",
			json_value_to_flattened(json_nul),
		);
		assert_eq!(
			json_value_to_flattened(json_bool.clone()),
			FlattenedTracingField::Boolean(true),
			"Converting JSON BOOL did not produce FTF Bool: {}",
			json_value_to_flattened(json_bool),
		);
		assert_eq!(
			json_value_to_flattened(json_real.clone()),
			FlattenedTracingField::Float(100.0),
			"Converting JSON REAL did not produce FTF UnsignedInt: {}",
			json_value_to_flattened(json_real),
		);
		assert_eq!(
			json_value_to_flattened(json_flot.clone()),
			FlattenedTracingField::Float(10.5),
			"Converting JSON Float did not produce FTF Float: {}",
			json_value_to_flattened(json_flot),
		);
		assert_eq!(
			json_value_to_flattened(json_strg.clone()),
			FlattenedTracingField::Str("hello world!".to_owned()),
			"Converting JSON String did not produce FTF String: {}",
			json_value_to_flattened(json_strg),
		);
		assert_eq!(
			json_value_to_flattened(json_arry.clone()),
			FlattenedTracingField::List(vec![
				FlattenedTracingField::Str("oh no".to_owned()),
				FlattenedTracingField::Str("why did".to_owned()),
				FlattenedTracingField::Str("we do this".to_owned()),
			]),
			"Converting JSON List did not produce FTF List: {}",
			json_value_to_flattened(json_arry),
		);

		let mut f_object = FnvHashMap::default();
		f_object.insert(
			"g".to_owned(),
			FlattenedTracingField::List(vec![
				FlattenedTracingField::Float(10.0),
				FlattenedTracingField::Float(11.0),
				FlattenedTracingField::Float(12.0),
			]),
		);
		let mut global_object = FnvHashMap::default();
		global_object.insert("a".to_owned(), FlattenedTracingField::Boolean(false));
		global_object.insert("b".to_owned(), FlattenedTracingField::Float(10.0));
		global_object.insert("c".to_owned(), FlattenedTracingField::Float(10.2));
		global_object.insert(
			"d".to_owned(),
			FlattenedTracingField::Str("hello world".to_owned()),
		);
		global_object.insert(
			"e".to_owned(),
			FlattenedTracingField::List(vec![
				FlattenedTracingField::Str("a".to_owned()),
				FlattenedTracingField::Str("b".to_owned()),
				FlattenedTracingField::Str("c".to_owned()),
			]),
		);
		global_object.insert("f".to_owned(), FlattenedTracingField::Object(f_object));
		assert_eq!(
			json_value_to_flattened(json_objc.clone()),
			FlattenedTracingField::Object(global_object),
			"Converting JSON List did not produce FTF Object: {}",
			json_value_to_flattened(json_objc),
		);
	}
}