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
// This file is part of Substrate.

// Copyright (C) 2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use crate::{initialize_transport, TelemetryWorker};
use futures::channel::mpsc;
use libp2p::wasm_ext::ExtTransport;
use parking_lot::Mutex;
use std::convert::TryInto;
use std::io;
use tracing::{Event, Id, Subscriber};
use tracing_subscriber::{layer::Context, registry::LookupSpan, Layer};

/// Span name used to report the telemetry.
pub const TELEMETRY_LOG_SPAN: &str = "telemetry-logger";

/// `Layer` that handles the logs for telemetries.
#[derive(Debug)]
pub struct TelemetryLayer(Mutex<mpsc::Sender<(Id, u8, String)>>);

impl TelemetryLayer {
	/// Create a new [`TelemetryLayer`] and [`TelemetryWorker`].
	///
	/// The `buffer_size` defaults to 16.
	///
	/// The [`ExtTransport`] is used in WASM contexts where we need some binding between the
	/// networking provided by the operating system or environment and libp2p.
	///
	/// > **Important**: Each individual call to `write` corresponds to one message. There is no
	/// >                internal buffering going on. In the context of WebSockets, each `write`
	/// >                must be one individual WebSockets frame.
	pub fn new(
		buffer_size: Option<usize>,
		telemetry_external_transport: Option<ExtTransport>,
	) -> io::Result<(Self, TelemetryWorker)> {
		let transport = initialize_transport(telemetry_external_transport)?;
		let worker = TelemetryWorker::new(buffer_size.unwrap_or(16), transport);
		let sender = worker.message_sender();
		Ok((Self(Mutex::new(sender)), worker))
	}
}

impl<S> Layer<S> for TelemetryLayer
where
	S: Subscriber + for<'a> LookupSpan<'a>,
{
	fn on_event(&self, event: &Event<'_>, ctx: Context<S>) {
		if event.metadata().target() != TELEMETRY_LOG_SPAN {
			return;
		}

		if let Some(span) = ctx.lookup_current() {
			let parents = span.parents();

			if let Some(span) = std::iter::once(span)
				.chain(parents)
				.find(|x| x.name() == TELEMETRY_LOG_SPAN)
			{
				let id = span.id();
				let mut attrs = TelemetryAttrs::new(id.clone());
				let mut vis = TelemetryAttrsVisitor(&mut attrs);
				event.record(&mut vis);

				if let TelemetryAttrs {
					verbosity: Some(verbosity),
					json: Some(json),
					..
				} = attrs
				{
					match self.0.lock().try_send((
						id,
						verbosity
							.try_into()
							.expect("telemetry log message verbosity are u8; qed"),
						json,
					)) {
						Err(err) if err.is_full() => eprintln!("Telemetry buffer overflowed!"),
						_ => {}
					}
				} else {
					// NOTE: logging in this function doesn't work
					eprintln!(
						"missing fields in telemetry log: {:?}. This can happen if \
						`tracing::info_span!` is (mis-)used with the telemetry target \
						directly; you should use the `telemetry!` macro.",
						event,
					);
				}
			}
		}
	}
}

#[derive(Debug)]
struct TelemetryAttrs {
	verbosity: Option<u64>,
	json: Option<String>,
	id: Id,
}

impl TelemetryAttrs {
	fn new(id: Id) -> Self {
		Self {
			verbosity: None,
			json: None,
			id,
		}
	}
}

#[derive(Debug)]
struct TelemetryAttrsVisitor<'a>(&'a mut TelemetryAttrs);

impl<'a> tracing::field::Visit for TelemetryAttrsVisitor<'a> {
	fn record_debug(&mut self, _field: &tracing::field::Field, _value: &dyn std::fmt::Debug) {
		// noop
	}

	fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
		if field.name() == "verbosity" {
			(*self.0).verbosity = Some(value);
		}
	}

	fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
		if field.name() == "json" {
			(*self.0).json = Some(format!(
				r#"{{"id":{},"ts":{:?},"payload":{}}}"#,
				self.0.id.into_u64(),
				chrono::Local::now().to_rfc3339().to_string(),
				value,
			));
		}
	}
}