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
/// Implements telemetry sending functionality.
///
/// Sends only basic anonymous usage statistics like program version, used commands and brokers.
/// No personal information will ever be sent.

use std::collections::{BTreeMap, HashSet};
use std::ops::DerefMut;
use std::sync::{Arc, Mutex, Condvar};
use std::thread::{self, JoinHandle};
use std::time::{Instant, SystemTime, Duration};

use diesel::{self, prelude::*};
use log::{trace, error};
use platforms::target::OS;
use reqwest::blocking::Client;
use serde::{Serialize, Deserialize};
use serde_json::Value;
use uuid::Uuid;

use crate::brokers::Broker;
use crate::core::{EmptyResult, GenericResult, GenericError};
use crate::db::{self, schema::{settings, telemetry}, models};
use crate::util;

#[derive(Serialize, Clone)]
pub struct TelemetryRecord {
    id: String,
    time: u64,

    os: &'static str,
    version: &'static str,
    #[serde(skip_serializing_if = "util::is_default")]
    precompiled: bool,
    #[serde(skip_serializing_if = "util::is_default")]
    container: bool,

    command: String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    brokers: Vec<String>,
}

impl TelemetryRecord {
    #[cfg(test)]
    fn mock(id: usize) -> TelemetryRecord {
        let mut record = TelemetryRecordBuilder::new().build("command-mock");
        record.id = format!("{}", id);
        record
    }
}

pub struct TelemetryRecordBuilder {
    brokers: HashSet<Broker>,
}

impl TelemetryRecordBuilder {
    pub fn new() -> TelemetryRecordBuilder {
        TelemetryRecordBuilder {
            brokers: HashSet::new(),
        }
    }

    pub fn new_with_broker(broker: Broker) -> TelemetryRecordBuilder {
        let mut record = TelemetryRecordBuilder::new();
        record.add_broker(broker);
        record
    }

    pub fn add_broker(&mut self, broker: Broker) {
        self.brokers.insert(broker);
    }

    pub fn build(self, command: &str) -> TelemetryRecord {
        let mut brokers: Vec<String> = self.brokers.iter()
            .map(|broker| broker.id().to_owned()).collect();
        brokers.sort();

        let id = Uuid::new_v4().to_string();
        let os = std::env::consts::OS;
        let time = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH).unwrap_or_default()
            .as_secs();

        TelemetryRecord {
            id, time,

            os,
            version: env!("CARGO_PKG_VERSION"),
            precompiled: option_env!("INVESTMENTS_PRECOMPILED_BINARY").is_some(),
            container: os == OS::Linux.as_str() && std::process::id() == 1,

            command: command.to_owned(),
            brokers,
        }
    }
}

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct TelemetryConfig {
    #[serde(default)]
    pub user_id: Option<Uuid>,

    #[serde(default)]
    pub disable: bool,
}

#[derive(Serialize)]
struct TelemetryRequest {
    user_id: String,
    records: Vec<Value>,
}

pub struct Telemetry {
    db: db::Connection,
    user_id: Option<String>,
    sender: Option<TelemetrySender>,
}

impl Telemetry {
    pub fn new(
        connection: db::Connection, user_id: Option<String>,
        url: &str, flush_thresholds: BTreeMap<usize, Duration>, max_records: usize,
    ) -> GenericResult<Telemetry> {
        let mut telemetry = Telemetry {
            db: connection,
            user_id,
            sender: None,
        };

        if let Some((records, last_record_id)) = telemetry.load(max_records)? {
            let user_id = telemetry.user_id()?;
            let request = TelemetryRequest {user_id, records};

            // By default we don't give any extra time to sender to complete its work. But if we
            // accumulated some records - we do.
            let mut deadline = Instant::now();
            for (&threshold, &timeout) in flush_thresholds.iter().rev() {
                if request.records.len() % threshold == 0 {
                    deadline += timeout;
                    break;
                }
            }

            telemetry.sender.replace(TelemetrySender::new(url, request, last_record_id, deadline));
        }

        Ok(telemetry)
    }

    pub fn add(&self, record: TelemetryRecord) -> EmptyResult {
        let payload = serde_json::to_string(&record)?;

        diesel::insert_into(telemetry::table)
            .values(models::NewTelemetryRecord {payload})
            .execute(self.db.borrow().deref_mut())?;

        Ok(())
    }

    fn load(&self, max_records: usize) -> GenericResult<Option<(Vec<Value>, i64)>> {
        let records = telemetry::table
            .select((telemetry::id, telemetry::payload))
            .order_by(telemetry::id.asc())
            .load::<(i64, String)>(self.db.borrow().deref_mut())?;

        let mut records: &[_] = &records;
        if records.len() > max_records {
            let count = records.len() - max_records;
            trace!("Dropping {} telemetry records.", count);
            self.delete(records[count - 1].0)?;
            records = &records[count..];
        }

        let mut payloads = Vec::with_capacity(records.len());
        for record in records {
            let payload = serde_json::from_str(&record.1).map_err(|e| format!(
                "Failed to parse telemetry record: {}", e))?;
            payloads.push(payload);
        }

        Ok(records.last().map(|record| (payloads, record.0)))
    }

    fn delete(&self, last_record_id: i64) -> EmptyResult {
        diesel::delete(telemetry::table.filter(telemetry::id.le(last_record_id)))
            .execute(self.db.borrow().deref_mut())?;
        Ok(())
    }

    fn user_id(&self) -> GenericResult<String> {
        self.db.borrow().transaction::<_, GenericError, _>(|db| {
            let name = models::SETTING_USER_ID;
            let user_id = settings::table
                .select(settings::value)
                .filter(settings::name.eq(name))
                .get_result::<String>(db).optional()?;

            Ok(match (user_id, self.user_id.clone()) {
                (Some(user_id), None) => user_id,
                (Some(user_id), Some(configured_user_id)) if user_id == configured_user_id => user_id,
                (_, configured_user_id) => {
                    let user_id = configured_user_id.unwrap_or_else(|| Uuid::new_v4().to_string());

                    diesel::replace_into(settings::table)
                        .values(&models::NewSetting {name, value: &user_id})
                        .execute(db)?;

                    user_id
                },
            })
        })
    }

    #[cfg(test)]
    fn close(mut self) -> EmptyResult {
        self.close_impl()
    }

    fn close_impl(&mut self) -> EmptyResult {
        if let Some(sender) = self.sender.take() {
            if let Some(last_record_id) = sender.wait() {
                self.delete(last_record_id).map_err(|e| format!(
                    "Failed to delete telemetry records: {}", e))?;
            }
        }
        Ok(())
    }
}

impl Drop for Telemetry {
    fn drop(&mut self) {
        if let Err(err) = self.close_impl() {
            error!("{}.", err)
        }
    }
}

struct TelemetrySender {
    thread: JoinHandle<()>,
    result: Arc<(Mutex<Option<Option<i64>>>, Condvar)>,
    deadline: Instant,
}

impl TelemetrySender {
    fn new(url: &str, request: TelemetryRequest, last_record_id: i64, deadline: Instant) -> TelemetrySender {
        let result = Arc::new((Mutex::new(None), Condvar::new()));

        let thread = {
            let url = url.to_owned();
            let result = result.clone();
            thread::spawn(move || {
                let ok = TelemetrySender::send(&url, request);

                let (lock, cond) = result.as_ref();
                let mut result = lock.lock().unwrap();

                result.replace(if ok {
                    Some(last_record_id)
                } else {
                    None
                });
                cond.notify_one();
            })
        };

        TelemetrySender {thread, result, deadline}
    }

    fn wait(self) -> Option<i64> {
        let result = {
            let (lock, cond) = self.result.as_ref();

            let guard = lock.lock().unwrap();
            let timeout = self.deadline.checked_duration_since(Instant::now()).unwrap_or_default();

            let (mut result, _) = cond.wait_timeout_while(
                guard, timeout, |result| result.is_none(),
            ).unwrap();

            result.take().unwrap_or_default()
        };

        if cfg!(test) {
            // Join the thread in test mode to not introduce any side effects, but do it after
            // result acquiring to not change the behaviour.
            self.thread.join().unwrap();
        } else {
            // We mustn't delay program execution or shutdown because of telemetry server or network
            // unavailability, so just forget about the thread - it will die on program exit.
        }

        result
    }

    fn send(base_url: &str, request: TelemetryRequest) -> bool {
        let url = format!("{}/telemetry", base_url);

        trace!("Sending telemetry ({} records)...", request.records.len());
        match Client::new().post(url).json(&request).send() {
            Ok(response) => {
                let status = response.status();
                if status.is_success() {
                    // Consume body in test mode to block on unreachable server emulation
                    if cfg!(test) {
                        let _ = response.bytes();
                    }
                    trace!("Telemetry has been successfully sent.");
                    true
                } else {
                    trace!("Telemetry server returned an error: {}.", status);
                    false
                }
            },
            Err(e) => {
                trace!("Failed to send telemetry: {}.", e);
                false
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use mockito::{Server, Mock};

    #[test]
    fn telemetry() {
        let mut server = Server::new();

        let url = server.url();
        let (_database, connection) = db::new_temporary();

        let new_telemetry = || {
            Telemetry::new(connection.clone(), None, &url, btreemap!{
                1 => Duration::from_millis(10),
            }, 5).unwrap()
        };

        let mut expected = vec![];
        let mut mock = broken_server(&mut server).expect(0);

        // Broken server, nothing to drop, nothing to send
        let user_id = {
            let telemetry = new_telemetry();
            let user_id = telemetry.user_id().unwrap();

            for id in 0..4 {
                let record = TelemetryRecord::mock(id);
                telemetry.add(record.clone()).unwrap();
                expected.push(record);
            }

            telemetry.close().unwrap();
            user_id
        };
        mock.assert();
        compare(connection.clone(), &expected); // 4 records

        // Broken server, nothing to drop, trying to send
        {
            let telemetry = new_telemetry();

            for id in 4..8 {
                let record = TelemetryRecord::mock(id);
                telemetry.add(record.clone()).unwrap();
                expected.push(record);
            }

            telemetry.close().unwrap();
        }
        mock = mock.expect(1);
        mock.assert();
        compare(connection.clone(), &expected); // 8 records

        // Broken server, dropping records, trying to send
        {
            let telemetry = new_telemetry();
            expected.drain(..3);

            for id in 8..12 {
                let record = TelemetryRecord::mock(id);
                telemetry.add(record.clone()).unwrap();
                expected.push(record);
            }

            telemetry.close().unwrap();
        }
        mock = mock.expect(2);
        mock.assert();
        compare(connection.clone(), &expected); // 9 records

        // Healthy server, dropping records, sending remaining
        expected.drain(..4);
        mock = healthy_server(&mut server, &user_id, &expected); // 5 records
        {
            let telemetry = new_telemetry();

            for id in 12..16 {
                let record = TelemetryRecord::mock(id);
                telemetry.add(record.clone()).unwrap();
                expected.push(record);
            }

            telemetry.close().unwrap();
        }
        mock.assert();
        expected.drain(..5);
        compare(connection.clone(), &expected); // 4 records

        // Unreachable server, nothing to drop, trying to send
        mock = unreachable_server(&mut server);
        {
            let telemetry = new_telemetry();

            let record = TelemetryRecord::mock(16);
            telemetry.add(record.clone()).unwrap();
            expected.push(record);

            telemetry.close().unwrap();
        }
        mock.assert();
        compare(connection.clone(), &expected); // 5 records

        // Healthy server, nothing to drop, sending all records
        mock = healthy_server(&mut server, &user_id, &expected);
        {
            let telemetry = new_telemetry();

            let record = TelemetryRecord::mock(17);
            telemetry.add(record.clone()).unwrap();
            expected.push(record);

            telemetry.close().unwrap();
        }
        mock.assert();
        expected.drain(..5);
        compare(connection.clone(), &expected); // 1 record
    }

    fn broken_server(server: &mut Server, ) -> Mock {
        server.mock("POST", "/telemetry")
            .with_status(500)
            .create()
    }

    fn healthy_server(server: &mut Server, user_id: &str, expected: &[TelemetryRecord]) -> Mock {
        let expected_request = TelemetryRequest {
            user_id: user_id.to_owned(),
            records: expected.iter().map(|record| {
                serde_json::to_value(record).unwrap()
            }).collect(),
        };
        let expected_body = serde_json::to_string(&expected_request).unwrap();

        server.mock("POST", "/telemetry")
            .match_header("content-type", "application/json")
            .match_body(expected_body.as_str())
            .with_status(200)
            .create()
    }

    fn unreachable_server(server: &mut Server, ) -> Mock {
        server.mock("POST", "/telemetry")
            .with_status(200)
            .with_chunked_body(|_| {
                thread::sleep(Duration::from_millis(100));
                Ok(())
            })
            .create()
    }

    fn compare(connection: db::Connection, expected: &[TelemetryRecord]) {
        let actual = telemetry::table
            .select(telemetry::payload)
            .order_by(telemetry::id.asc())
            .load::<String>(connection.borrow().deref_mut()).unwrap();

        let expected: Vec<String> = expected.iter()
            .map(|record| serde_json::to_string(record).unwrap())
            .collect();

        assert_eq!(actual, expected);
    }
}