Browse Source

format

pull/25/head
Alexey Velikiy 3 years ago
parent
commit
0d0d317c7d
  1. 12
      server/src/api.rs
  2. 1
      server/src/api/metric.rs
  3. 42
      server/src/api/segments.rs
  4. 2
      server/src/config.rs
  5. 35
      server/src/services/data_service.rs

12
server/src/api.rs

@ -15,7 +15,6 @@ use serde::Serialize;
use parking_lot::RwLock;
use std::sync::Arc;
#[derive(Debug)]
struct BadQuery;
@ -82,13 +81,12 @@ impl API<'_> {
println!("Start server on {} port", self.config.port);
// TODO: move it to "server"
let routes =
warp::path("api")
.and(
login.or(metrics).or(options))
let routes = warp::path("api")
.and(login.or(metrics).or(options))
.or(public)
.or(not_found);
warp::serve(routes).run(([127, 0, 0, 1], self.config.port)).await;
warp::serve(routes)
.run(([127, 0, 0, 1], self.config.port))
.await;
}
}

1
server/src/api/metric.rs

@ -28,7 +28,6 @@ struct QueryResponse {
message: String,
}
async fn get_query(
p: HashMap<String, String>,
ms: Arc<RwLock<metric_service::MetricService>>,

42
server/src/api/segments.rs

@ -1,17 +1,15 @@
mod filters {
use warp::Filter;
use super::models::{Db, ListOptions};
use super::handlers;
use super::models::{Db, ListOptions};
use warp::Filter;
/// The 4 REST API filters combined.
pub fn filters(
db: Db,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
list(db.clone())
.or(create(db.clone()))
// .or(update(db.clone()))
// .or(delete(db.clone()))
list(db.clone()).or(create(db.clone()))
// .or(update(db.clone()))
// .or(delete(db.clone()))
}
/// GET /segments?from=3&to=5
@ -27,50 +25,52 @@ mod filters {
/// POST /segments with JSON body
pub fn create(
db: Db
db: Db,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
warp::path!("segments")
.and(warp::post())
.and(warp::body::json())
.and(with_db(db))
.and_then(handlers::create)
.and(warp::post())
.and(warp::body::json())
.and(with_db(db))
.and_then(handlers::create)
}
fn with_db(db: Db) -> impl Filter<Extract = (Db,), Error = std::convert::Infallible> + Clone {
warp::any().map(move || db.clone())
}
}
mod handlers {
use hastic::services::data_service;
use crate::api::API;
use crate::api::BadQuery;
use super::models::ListOptions;
use super::models::Db;
use super::models::ListOptions;
use crate::api::BadQuery;
use crate::api::API;
pub async fn list(opts: ListOptions, db: Db) -> Result<impl warp::Reply, warp::Rejection> {
// Just return a JSON array of todos, applying the limit and offset.
match db.read().get_segments(opts.from, opts.to) {
Ok(segments) => Ok(API::json(&segments)),
Err(e) => Err(warp::reject::custom(BadQuery))
Err(e) => Err(warp::reject::custom(BadQuery)),
}
}
pub async fn create(segment: data_service::Segment, db: Db) -> Result<impl warp::Reply, warp::Rejection> {
pub async fn create(
segment: data_service::Segment,
db: Db,
) -> Result<impl warp::Reply, warp::Rejection> {
// Just return a JSON array of todos, applying the limit and offset.
match db.write().insert_segment(&segment) {
Ok(segments) => Ok(API::json(&segments)),
Err(e) => Err(warp::reject::custom(BadQuery))
Err(e) => Err(warp::reject::custom(BadQuery)),
}
}
}
mod models {
use serde::{Deserialize};
use hastic::services::data_service;
use parking_lot::RwLock;
use serde::Deserialize;
use std::sync::Arc;
pub type Db = Arc<RwLock<data_service::DataService>>;
@ -81,4 +81,4 @@ mod models {
pub from: u64,
pub to: u64,
}
}
}

2
server/src/config.rs

@ -1,7 +1,7 @@
pub struct Config {
pub prom_url: String,
pub query: String,
pub port: u16
pub port: u16,
}
// TODO: use actual config and env variables

35
server/src/services/data_service.rs

@ -1,10 +1,9 @@
use rusqlite::{ Connection, params };
use rusqlite::{params, Connection};
use serde::{Serialize, Deserialize};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
#[derive(Debug, Serialize, Deserialize)]
pub struct Segment {
pub id: Option<u64>,
@ -15,12 +14,10 @@ pub struct Segment {
// TODO: find a way to remove this unsafe
unsafe impl Sync for DataService {}
pub struct DataService {
connection: Arc<Mutex<Connection>>
connection: Arc<Mutex<Connection>>,
}
impl DataService {
pub fn new() -> anyhow::Result<DataService> {
let conn = Connection::open("./data.db")?;
@ -33,7 +30,9 @@ impl DataService {
[],
)?;
Ok(DataService { connection: Arc::new(Mutex::new(conn)) })
Ok(DataService {
connection: Arc::new(Mutex::new(conn)),
})
}
pub fn insert_segment(&self, segment: &Segment) -> anyhow::Result<u64> {
@ -47,17 +46,19 @@ impl DataService {
pub fn get_segments(&self, from: u64, to: u64) -> anyhow::Result<Vec<Segment>> {
let conn = self.connection.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT id, start, end FROM person WHERE ?1 < start AND end < ?2"
)?;
let mut stmt =
conn.prepare("SELECT id, start, end FROM person WHERE ?1 < start AND end < ?2")?;
let res = stmt.query_map(params![from, to], |row| {
Ok(Segment{
id: row.get(0)?,
start: row.get(1)?,
end: row.get(2)?
})
})?.map(|e| e.unwrap()).collect();
let res = stmt
.query_map(params![from, to], |row| {
Ok(Segment {
id: row.get(0)?,
start: row.get(1)?,
end: row.get(2)?,
})
})?
.map(|e| e.unwrap())
.collect();
Ok(res)
}
}

Loading…
Cancel
Save