pop_telemetry/
lib.rs

1// SPDX-License-Identifier: GPL-3.0
2
3#![doc = include_str!("../README.md")]
4
5use reqwest::Client;
6use serde::{de::DeserializeOwned, Deserialize, Serialize};
7use serde_json::{json, Value};
8use std::{
9	env,
10	fs::{create_dir_all, File},
11	io,
12	io::{Read, Write},
13	path::PathBuf,
14};
15use thiserror::Error;
16
17const ENDPOINT: &str = "https://insights.onpop.io/api/send";
18const WEBSITE_ID: &str = "0cbea0ba-4752-45aa-b3cd-8fd11fa722f7";
19const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
20
21/// A telemetry error.
22#[derive(Error, Debug)]
23pub enum TelemetryError {
24	/// A network error occurred.
25	#[error("a reqwest error occurred: {0}")]
26	NetworkError(reqwest::Error),
27	/// An IO error occurred.
28	#[error("io error occurred: {0}")]
29	IO(io::Error),
30	/// The user has opted out and metrics cannot be reported.
31	#[error("opt-out has been set, can not report metrics")]
32	OptedOut,
33	/// The configuration file cannot be found.
34	#[error("unable to find config file")]
35	ConfigFileNotFound,
36	/// The configuration could not be serialized.
37	#[error("serialization failed: {0}")]
38	SerializeFailed(String),
39}
40
41/// A result that represents either success ([`Ok`]) or failure ([`TelemetryError`]).
42pub type Result<T> = std::result::Result<T, TelemetryError>;
43
44/// Anonymous collection of usage metrics.
45#[derive(Debug, Clone)]
46pub struct Telemetry {
47	// Endpoint to the telemetry API.
48	// This should include the domain and api path (e.g. localhost:3000/api/send)
49	endpoint: String,
50	// Has the user opted-out to anonymous telemetry
51	opt_out: bool,
52	// Reqwest client
53	client: Client,
54}
55
56impl Telemetry {
57	/// Create a new [Telemetry] instance.
58	///
59	/// parameters:
60	/// `config_path`: the path to the configuration file (used for opt-out checks)
61	pub fn new(config_path: &PathBuf) -> Self {
62		Self::init(ENDPOINT.to_string(), config_path)
63	}
64
65	/// Initialize a new [Telemetry] instance with parameters.
66	/// Can be used in tests to provide mock endpoints.
67	/// parameters:
68	/// `endpoint`: the API endpoint that telemetry will call
69	/// `config_path`: the path to the configuration file (used for opt-out checks)
70	fn init(endpoint: String, config_path: &PathBuf) -> Self {
71		let opt_out = Self::is_opt_out(config_path);
72
73		Telemetry { endpoint, opt_out, client: Client::new() }
74	}
75
76	fn is_opt_out_from_config(config_file_path: &PathBuf) -> bool {
77		let config: Config = match read_json_file(config_file_path) {
78			Ok(config) => config,
79			Err(err) => {
80				log::debug!("{:?}", err.to_string());
81				return false;
82			},
83		};
84
85		// if the version is empty, then the user has not opted out
86		!config.opt_out.version.is_empty()
87	}
88
89	// Checks two env variables, CI & DO_NOT_TRACK. If either are set to true, disable telemetry
90	fn is_opt_out_from_env() -> bool {
91		// CI first as it is more likely to be set
92		let ci = env::var("CI").unwrap_or_default();
93		let do_not_track = env::var("DO_NOT_TRACK").unwrap_or_default();
94		ci == "true" || ci == "1" || do_not_track == "true" || do_not_track == "1"
95	}
96
97	/// Check if the user has opted out of telemetry through two methods:
98	/// 1. Check environment variable DO_NOT_TRACK. If not set check...
99	/// 2. Configuration file
100	fn is_opt_out(config_file_path: &PathBuf) -> bool {
101		Self::is_opt_out_from_env() || Self::is_opt_out_from_config(config_file_path)
102	}
103
104	/// Send JSON payload to saved api endpoint.
105	/// Returns error and will not send anything if opt-out is true.
106	/// Returns error from reqwest if the sending fails.
107	/// It sends message only once as "best effort". There is no retry on error
108	/// in order to keep overhead to a minimal.
109	async fn send_json(&self, payload: Value) -> Result<()> {
110		if self.opt_out {
111			return Err(TelemetryError::OptedOut);
112		}
113
114		let request_builder = self.client.post(&self.endpoint);
115
116		request_builder
117			.json(&payload)
118			.send()
119			.await
120			.map_err(TelemetryError::NetworkError)?;
121
122		Ok(())
123	}
124}
125
126/// Generically reports that the CLI was used to the telemetry endpoint.
127/// There is explicitly no reqwest retries on failure to ensure overhead
128/// stays to a minimum.
129pub async fn record_cli_used(tel: Telemetry) -> Result<()> {
130	let payload = generate_payload("", "");
131
132	let res = tel.send_json(payload).await;
133	log::debug!("send_cli_used result: {:?}", res);
134
135	res
136}
137
138/// Reports what CLI command was called to telemetry.
139///
140/// parameters:
141/// `event`: the name of the event to record (new, up, build, etc)
142/// `data`: additional data to record.
143pub async fn record_cli_command(tel: Telemetry, event: &str, data: &str) -> Result<()> {
144	let payload = generate_payload(event, data);
145
146	let res = tel.send_json(payload).await;
147	log::debug!("send_cli_used result: {:?}", res);
148
149	res
150}
151
152#[derive(PartialEq, Serialize, Deserialize, Debug)]
153struct OptOut {
154	// what telemetry version did they opt-out for
155	version: String,
156}
157
158/// Type to represent pop cli configuration.
159/// This will be written as json to a config.json file.
160#[derive(PartialEq, Serialize, Deserialize, Debug)]
161pub struct Config {
162	opt_out: OptOut,
163}
164
165/// Returns the configuration file path based on OS's default config directory.
166pub fn config_file_path() -> Result<PathBuf> {
167	let config_path = dirs::config_dir().ok_or(TelemetryError::ConfigFileNotFound)?.join("pop");
168	// Creates pop dir if needed
169	create_dir_all(config_path.as_path()).map_err(TelemetryError::IO)?;
170	Ok(config_path.join("config.json"))
171}
172
173/// Writes opt-out to the configuration file at the specified path.
174/// opt-out is currently the only config type. Hence, if the file exists, it will be overwritten.
175///
176/// parameters:
177/// `config_path`: the path to write the config file to
178pub fn write_config_opt_out(config_path: &PathBuf) -> Result<()> {
179	let config = Config { opt_out: OptOut { version: CARGO_PKG_VERSION.to_string() } };
180
181	let config_json = serde_json::to_string_pretty(&config)
182		.map_err(|err| TelemetryError::SerializeFailed(err.to_string()))?;
183
184	// overwrites file if it exists
185	let mut file = File::create(config_path).map_err(TelemetryError::IO)?;
186	file.write_all(config_json.as_bytes()).map_err(TelemetryError::IO)?;
187
188	Ok(())
189}
190
191fn read_json_file<T>(file_path: &PathBuf) -> std::result::Result<T, io::Error>
192where
193	T: DeserializeOwned,
194{
195	let mut file = File::open(file_path)?;
196
197	let mut json = String::new();
198	file.read_to_string(&mut json)?;
199
200	let deserialized: T = serde_json::from_str(&json)?;
201
202	Ok(deserialized)
203}
204
205fn generate_payload(event: &str, data: &str) -> Value {
206	json!({
207		"payload": {
208			"hostname": "cli",
209			"language": "en-US",
210			"referrer": "",
211			"screen": "1920x1080",
212			"title": CARGO_PKG_VERSION,
213			"url": "/",
214			"website": WEBSITE_ID,
215			"name": event,
216			"data": data
217		},
218		"type": "event"
219	})
220}
221
222#[cfg(test)]
223mod tests {
224
225	use super::*;
226	use mockito::{Matcher, Mock, Server};
227	use tempfile::TempDir;
228
229	fn create_temp_config(temp_dir: &TempDir) -> Result<PathBuf> {
230		let config_path = temp_dir.path().join("config.json");
231		write_config_opt_out(&config_path)?;
232		Ok(config_path)
233	}
234	async fn default_mock(mock_server: &mut Server, payload: String) -> Mock {
235		mock_server
236			.mock("POST", "/api/send")
237			.match_header("content-type", "application/json")
238			.match_header("accept", "*/*")
239			.match_body(Matcher::JsonString(payload.clone()))
240			.match_header("content-length", payload.len().to_string().as_str())
241			.match_header("host", mock_server.host_with_port().trim())
242			.create_async()
243			.await
244	}
245
246	#[tokio::test]
247	async fn write_config_opt_out_works() -> Result<()> {
248		// Mock config file path function to return a temporary path
249		let temp_dir = TempDir::new().unwrap();
250		let config_path = create_temp_config(&temp_dir)?;
251
252		let actual_config: Config = read_json_file(&config_path).unwrap();
253		let expected_config = Config { opt_out: OptOut { version: CARGO_PKG_VERSION.to_string() } };
254
255		assert_eq!(actual_config, expected_config);
256		Ok(())
257	}
258
259	#[tokio::test]
260	async fn new_telemetry_works() -> Result<()> {
261		let _ = env_logger::try_init();
262
263		// Mock config file path function to return a temporary path
264		let temp_dir = TempDir::new().unwrap();
265		// write a config file with opt-out set
266		let config_path = create_temp_config(&temp_dir)?;
267
268		let _: Config = read_json_file(&config_path).unwrap();
269
270		let tel = Telemetry::init("127.0.0.1".to_string(), &config_path);
271		let expected_telemetry = Telemetry {
272			endpoint: "127.0.0.1".to_string(),
273			opt_out: true,
274			client: Default::default(),
275		};
276
277		assert_eq!(tel.endpoint, expected_telemetry.endpoint);
278		assert_eq!(tel.opt_out, expected_telemetry.opt_out);
279
280		let tel = Telemetry::new(&config_path);
281
282		let expected_telemetry =
283			Telemetry { endpoint: ENDPOINT.to_string(), opt_out: true, client: Default::default() };
284
285		assert_eq!(tel.endpoint, expected_telemetry.endpoint);
286		assert_eq!(tel.opt_out, expected_telemetry.opt_out);
287		Ok(())
288	}
289
290	#[test]
291	fn new_telemetry_env_vars_works() {
292		let _ = env_logger::try_init();
293
294		// assert that no config file, and env vars not existing sets opt-out to false
295		env::remove_var("DO_NOT_TRACK");
296		env::set_var("CI", "false");
297		assert!(!Telemetry::init("".to_string(), &PathBuf::new()).opt_out);
298
299		// assert that if DO_NOT_TRACK env var is set, opt-out is true
300		env::set_var("DO_NOT_TRACK", "true");
301		assert!(Telemetry::init("".to_string(), &PathBuf::new()).opt_out);
302		env::remove_var("DO_NOT_TRACK");
303
304		// assert that if CI env var is set, opt-out is true
305		env::set_var("CI", "true");
306		assert!(Telemetry::init("".to_string(), &PathBuf::new()).opt_out);
307		env::remove_var("CI");
308	}
309
310	#[tokio::test]
311	async fn test_record_cli_used() -> Result<()> {
312		let _ = env_logger::try_init();
313		let mut mock_server = Server::new_async().await;
314
315		let mut endpoint = mock_server.url();
316		endpoint.push_str("/api/send");
317
318		// Mock config file path function to return a temporary path
319		let temp_dir = TempDir::new().unwrap();
320		let config_path = temp_dir.path().join("config.json");
321
322		let expected_payload = generate_payload("", "").to_string();
323
324		let mock = default_mock(&mut mock_server, expected_payload).await;
325
326		let mut tel = Telemetry::init(endpoint.clone(), &config_path);
327		tel.opt_out = false; // override as endpoint is mocked
328
329		record_cli_used(tel).await?;
330		mock.assert_async().await;
331		Ok(())
332	}
333
334	#[tokio::test]
335	async fn test_record_cli_command() -> Result<()> {
336		let _ = env_logger::try_init();
337		let mut mock_server = Server::new_async().await;
338
339		let mut endpoint = mock_server.url();
340		endpoint.push_str("/api/send");
341
342		// Mock config file path function to return a temporary path
343		let temp_dir = TempDir::new().unwrap();
344
345		let config_path = temp_dir.path().join("config.json");
346
347		let expected_payload = generate_payload("new", "parachain").to_string();
348
349		let mock = default_mock(&mut mock_server, expected_payload).await;
350
351		let mut tel = Telemetry::init(endpoint.clone(), &config_path);
352		tel.opt_out = false; // override as endpoint is mocked
353
354		record_cli_command(tel, "new", "parachain").await?;
355		mock.assert_async().await;
356		Ok(())
357	}
358
359	#[tokio::test]
360	async fn opt_out_set_fails() {
361		let _ = env_logger::try_init();
362		let mut mock_server = Server::new_async().await;
363
364		let endpoint = mock_server.url();
365
366		let mock = mock_server.mock("POST", "/").create_async().await;
367		let mock = mock.expect_at_most(0);
368
369		let mut tel = Telemetry::init(endpoint.clone(), &PathBuf::new());
370		tel.opt_out = true;
371
372		assert!(matches!(tel.send_json(Value::Null).await, Err(TelemetryError::OptedOut)));
373		assert!(matches!(record_cli_used(tel.clone()).await, Err(TelemetryError::OptedOut)));
374		assert!(matches!(
375			record_cli_command(tel.clone(), "foo", "").await,
376			Err(TelemetryError::OptedOut)
377		));
378		mock.assert_async().await;
379	}
380}