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
use std::net::IpAddr;

use chrono::{DateTime, Utc};
use sqlx::{
  migrate::Migrator, types::ipnetwork::IpNetwork, ConnectOptions, FromRow,
  Pool, Postgres, QueryBuilder, Type,
};
use thiserror::Error;

use crate::*;

// TODO: check if lists are empty before sending requests

#[derive(Debug, Clone)]
pub(crate) struct Service {
  pool: Pool<Postgres>,
}

#[derive(Debug, Copy, Clone, Type, Eq, PartialEq)]
#[sqlx(type_name = "device_status", rename_all = "lowercase")]
pub(crate) enum DeviceStatus {
  Healthy,
  Unreachable,
  Inactive,
}

#[derive(Debug, Clone, FromRow)]
pub(crate) struct Device {
  pub(crate) id: String,
  pub(crate) kind: String,
  pub(crate) status: DeviceStatus,
  pub(crate) seen: DateTime<Utc>,
  pub(crate) pinged: DateTime<Utc>,
  pub(crate) address: Option<IpNetwork>,
  pub(crate) path: Option<String>,
  pub(crate) baud_rate: Option<i32>,
  pub(crate) slave: Option<i32>,
}

#[derive(Debug, Clone, FromRow)]
pub(crate) struct Measurement {
  #[allow(dead_code, reason = "needed for database functionality")]
  pub(crate) id: i64,
  pub(crate) source: String,
  pub(crate) timestamp: DateTime<Utc>,
  pub(crate) data: serde_json::Value,
}

#[derive(Debug, Clone, FromRow)]
pub(crate) struct Health {
  #[allow(dead_code, reason = "needed for database functionality")]
  pub(crate) id: i64,
  pub(crate) source: String,
  pub(crate) timestamp: DateTime<Utc>,
  pub(crate) status: DeviceStatus,
  pub(crate) data: serde_json::Value,
}

#[derive(Debug, Copy, Clone, Type, Eq, PartialEq)]
#[sqlx(type_name = "log_status", rename_all = "lowercase")]
pub(crate) enum LogStatus {
  Success,
  Failure,
}

#[derive(Debug, Copy, Clone, Type, Eq, PartialEq)]
#[sqlx(type_name = "log_kind", rename_all = "lowercase")]
pub(crate) enum LogKind {
  Push,
  Update,
}

#[derive(Debug, Clone, FromRow)]
pub(crate) struct Log {
  #[allow(dead_code, reason = "needed for database functionality")]
  pub(crate) id: i64,
  pub(crate) timestamp: DateTime<Utc>,
  pub(crate) last: Option<i64>,
  pub(crate) kind: LogKind,
  pub(crate) status: LogStatus,
  pub(crate) response: serde_json::Value,
}

#[derive(Debug, Error)]
pub(crate) enum Error {
  #[error("Sqlx error")]
  Sqlx(#[from] sqlx::Error),
}

#[derive(Debug, Error)]
pub(crate) enum MigrateError {
  #[error("Migration failed")]
  Migration(#[from] sqlx::migrate::MigrateError),
}

impl service::Service for Service {
  fn new(config: config::Values) -> Self {
    let mut options = sqlx::postgres::PgConnectOptions::new()
      .host(&config.db.domain)
      .username(&config.db.user)
      .database(&config.db.name)
      .log_slow_statements(
        log::LevelFilter::Warn,
        core::time::Duration::from_secs(5),
      )
      .options([(
        "statement_timeout",
        &config.db.timeout.num_milliseconds().to_string(),
      )]);

    if let Some(port) = config.db.port {
      options = options.port(port);
    }

    if let Some(password) = config.db.password {
      options = options.password(password.as_str());
    }

    options = options.ssl_mode(sqlx::postgres::PgSslMode::Disable);
    if config.db.ssl {
      options = options.ssl_mode(sqlx::postgres::PgSslMode::Require);
    }

    let pool = sqlx::Pool::connect_lazy_with(options);

    Self { pool }
  }
}

impl Service {
  #[tracing::instrument(skip(self))]
  pub(crate) async fn migrate(&self) -> Result<(), MigrateError> {
    let mut migration_result = MIGRATOR.run(&self.pool).await;
    let mut migration_retries = 0usize;
    while migration_result.is_err() && migration_retries < 100 {
      migration_result = MIGRATOR.run(&self.pool).await;
      migration_retries = {
        #[allow(clippy::unwrap_used, reason = "it will never pass 100")]
        let migration_retries = migration_retries.checked_add(1usize).unwrap();
        migration_retries
      };
      tracing::warn!(
        "Migration unsuccessful because\n{:?}\nRetrying in 1 second...",
        migration_result
      );
      tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
    }
    migration_result?;

    tracing::info!("Migration ran successfully");

    Ok(())
  }

  #[tracing::instrument(skip(self))]
  pub(crate) async fn get_devices(&self) -> Result<Vec<Device>, Error> {
    #[allow(clippy::panic, reason = "sqlx thing")]
    let devices = sqlx::query_as!(
      Device,
      r#"
        select id, kind, status as "status: DeviceStatus", seen, pinged, address, path, baud_rate, slave
        from devices
      "#,
    )
    .fetch_all(&self.pool)
    .await?;

    tracing::trace!("Fetched {:?} devices", devices.len());

    Ok(devices)
  }

  #[tracing::instrument(skip(self))]
  pub(crate) async fn get_device(
    &self,
    id: &str,
  ) -> Result<Option<Device>, Error> {
    #[allow(clippy::panic, reason = "sqlx thing")]
    let device = sqlx::query_as!(
      Device,
      r#"
        select id, kind, status as "status: DeviceStatus", seen, pinged, address, path, baud_rate, slave
        from devices
        where id = $1
      "#,
      id
    )
    .fetch_optional(&self.pool)
    .await?;

    tracing::trace!("Fetched device");

    Ok(device)
  }

  #[tracing::instrument(skip(self))]
  pub(crate) async fn insert_device(
    &self,
    device: Device,
  ) -> Result<(), Error> {
    #[allow(clippy::panic, reason = "sqlx thing")]
    sqlx::query!(
      r#"
        insert into devices (id, kind, status, seen, pinged, address, path, baud_rate, slave)
        values ($1, $2, $3, $4, $5, $6, $7, $8, $9)
      "#,
      device.id,
      device.kind,
      device.status as DeviceStatus,
      device.seen,
      device.pinged,
      device.address,
      device.path,
      device.baud_rate,
      device.slave
    )
    .execute(&self.pool)
    .await?;

    tracing::trace!("Inserted device");

    Ok(())
  }

  #[tracing::instrument(skip(self))]
  pub(crate) async fn delete_device(&self, id: &str) -> Result<(), Error> {
    #[allow(clippy::panic, reason = "sqlx thing")]
    sqlx::query!(
      r#"
        delete from devices
        where id = $1
      "#,
      id,
    )
    .execute(&self.pool)
    .await?;

    tracing::trace!("Deleted device");

    Ok(())
  }

  #[tracing::instrument(skip(self))]
  pub(crate) async fn update_device_status(
    &self,
    id: &str,
    status: DeviceStatus,
    seen: DateTime<Utc>,
    pinged: DateTime<Utc>,
  ) -> Result<(), Error> {
    #[allow(clippy::panic, reason = "sqlx thing")]
    sqlx::query!(
      r#"
        update devices
        set status = $2::device_status, seen = $3, pinged = $4
        where id = $1
      "#,
      id,
      status as DeviceStatus,
      seen,
      pinged
    )
    .execute(&self.pool)
    .await?;

    tracing::trace!("Updated device status");

    Ok(())
  }

  #[allow(
    clippy::too_many_arguments,
    reason = "needed for database functionality"
  )]
  #[tracing::instrument(skip(self))]
  pub(crate) async fn update_device_destination(
    &self,
    id: &str,
    address: Option<IpNetwork>,
    path: Option<String>,
    baud_rate: Option<i32>,
    slave: Option<i32>,
    seen: DateTime<Utc>,
    pinged: DateTime<Utc>,
  ) -> Result<(), Error> {
    #[allow(clippy::panic, reason = "sqlx thing")]
    sqlx::query!(
      r#"
        update devices
        set address = $2, path = $3, baud_rate = $4, slave = $5, seen = $6, pinged = $7
        where id = $1
      "#,
      id,
      address,
      path,
      baud_rate,
      slave,
      seen,
      pinged
    )
    .execute(&self.pool)
    .await?;

    tracing::trace!("Updated device destination");

    Ok(())
  }

  #[tracing::instrument(skip(self))]
  pub(crate) async fn insert_measurement(
    &self,
    measurement: Measurement,
  ) -> Result<(), Error> {
    #[allow(clippy::panic, reason = "sqlx thing")]
    sqlx::query!(
      r#"
        insert into measurements (source, timestamp, data)
        values ($1, $2, $3)
      "#,
      measurement.source,
      measurement.timestamp,
      measurement.data
    )
    .execute(&self.pool)
    .await?;

    tracing::trace!("Inserted measurement");

    Ok(())
  }

  #[tracing::instrument(skip_all, fields(count = measurements.len()))]
  pub(crate) async fn insert_measurements(
    &self,
    measurements: Vec<Measurement>,
  ) -> Result<(), Error> {
    QueryBuilder::new("insert into measurements (source, timestamp, data)")
      .push_values(measurements, |mut binder, measurement| {
        binder
          .push_bind(measurement.source)
          .push_bind(measurement.timestamp)
          .push_bind(measurement.data);
      })
      .build()
      .execute(&self.pool)
      .await?;

    tracing::trace!("Inserted measurements");

    Ok(())
  }

  #[tracing::instrument(skip(self))]
  pub(crate) async fn get_measurements(
    &self,
    from: i64,
    limit: i64,
  ) -> Result<Vec<Measurement>, Error> {
    #[allow(clippy::panic, reason = "sqlx thing")]
    let measurements = sqlx::query_as!(
      Measurement,
      r#"
        select id, source, timestamp, data
        from measurements
        where measurements.id > $1
        order by measurements.id asc
        limit $2
      "#,
      from,
      limit
    )
    .fetch_all(&self.pool)
    .await?;

    tracing::trace!("Fetched {:?} measurements", measurements.len());

    Ok(measurements)
  }

  #[tracing::instrument(skip(self))]
  pub(crate) async fn insert_health(
    &self,
    health: Health,
  ) -> Result<(), Error> {
    #[allow(clippy::panic, reason = "sqlx thing")]
    sqlx::query!(
      r#"
        insert into health (source, timestamp, status, data)
        values ($1, $2, $3, $4)
      "#,
      health.source,
      health.timestamp,
      health.status as DeviceStatus,
      health.data
    )
    .execute(&self.pool)
    .await?;

    tracing::trace!(
      "Inserted health for {:?} at {:?}",
      health.source,
      health.timestamp
    );

    Ok(())
  }

  #[tracing::instrument(skip_all, fields(count = healths.len()))]
  pub(crate) async fn insert_healths(
    &self,
    healths: Vec<Health>,
  ) -> Result<(), Error> {
    QueryBuilder::new("insert into health (source, timestamp, status, data)")
      .push_values(healths, |mut binder, health| {
        binder
          .push_bind(health.source)
          .push_bind(health.timestamp)
          .push_bind(health.status)
          .push_bind(health.data);
      })
      .build()
      .execute(&self.pool)
      .await?;

    tracing::trace!("Inserted healths");

    Ok(())
  }

  #[tracing::instrument(skip(self))]
  pub(crate) async fn get_health(
    &self,
    from: i64,
    limit: i64,
  ) -> Result<Vec<Health>, Error> {
    #[allow(clippy::panic, reason = "sqlx thing")]
    let healths = sqlx::query_as!(
      Health,
      r#"
        select id, source, timestamp, status as "status: DeviceStatus", data
        from health
        where health.id > $1
        limit $2
      "#,
      from,
      limit
    )
    .fetch_all(&self.pool)
    .await?;

    tracing::trace!("Fetched {:?} healths", healths.len());

    Ok(healths)
  }

  #[tracing::instrument(skip(self))]
  pub(crate) async fn insert_log(&self, log: Log) -> Result<(), Error> {
    #[allow(clippy::panic, reason = "sqlx thing")]
    sqlx::query!(
      r#"
        insert into logs (timestamp, last, status, kind, response)
        values ($1, $2, $3, $4, $5)
      "#,
      log.timestamp,
      log.last,
      log.status as LogStatus,
      log.kind as LogKind,
      log.response
    )
    .execute(&self.pool)
    .await?;

    tracing::trace!(
      "Inserted {:?} {:?} log at {:?}",
      log.status,
      log.kind,
      log.timestamp
    );

    Ok(())
  }

  #[tracing::instrument(skip(self))]
  pub(crate) async fn get_last_successful_push_log(
    &self,
  ) -> Result<Option<Log>, Error> {
    #[allow(clippy::panic, reason = "sqlx thing")]
    let log = sqlx::query_as!(
      Log,
      r#"
        select id, timestamp, last, kind as "kind: LogKind", status as "status: LogStatus", response
        from logs
        where status = 'success'::log_status and kind = 'push'::log_kind and last is not null
        order by timestamp desc
        limit 1
      "#
    )
    .fetch_optional(&self.pool)
    .await?;

    tracing::trace!(
      "Fetched last successful push log at {:?}",
      log.as_ref().map(|log| log.timestamp)
    );

    Ok(log)
  }

  #[tracing::instrument(skip(self))]
  pub(crate) async fn get_last_successful_update_log(
    &self,
  ) -> Result<Option<Log>, Error> {
    #[allow(clippy::panic, reason = "sqlx thing")]
    let log = sqlx::query_as!(
      Log,
      r#"
        select id, timestamp, last, kind as "kind: LogKind", status as "status: LogStatus", response
        from logs
        where status = 'success'::log_status and kind = 'update'::log_kind and last is not null
        order by timestamp desc
        limit 1
      "#
    )
    .fetch_optional(&self.pool)
    .await?;

    tracing::trace!(
      "Fetched last successful update log at {:?}",
      log.as_ref().map(|log| log.timestamp)
    );

    Ok(log)
  }
}

pub(crate) fn to_db_address(address: IpAddr) -> IpNetwork {
  #[allow(clippy::unwrap_used, reason = "24 is valid for ipv4")]
  IpNetwork::new(address, 24).unwrap()
}

pub(crate) fn to_db_slave(slave: Option<u8>) -> Option<i32> {
  slave.map(|slave| slave as i32)
}

pub(crate) fn to_address(db_address: IpNetwork) -> IpAddr {
  db_address.ip()
}

pub(crate) fn to_slave(db_slave: Option<i32>) -> Option<u8> {
  db_slave.map(|slave| slave as u8)
}

static MIGRATOR: Migrator = sqlx::migrate!("./migrations");