Skip to content

Commit

Permalink
Housekeeping
Browse files Browse the repository at this point in the history
- Update dependencies
- Remove explicit http status code from status endpoint
- Remove unnecessary code
  • Loading branch information
koarlchen committed Dec 26, 2024
1 parent 82ebe48 commit f5ebc54
Show file tree
Hide file tree
Showing 6 changed files with 75 additions and 109 deletions.
74 changes: 47 additions & 27 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 7 additions & 7 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ keywords = ["spaceapi", "hackspace", "k4cg"]
[dependencies]
spaceapi = "0.9.0"
influxdb = "0.7.2"
serde = "1.0.214"
serde_json = "1.0.132"
axum = "0.7.7"
tokio = { version = "1.41.0", features = ["rt-multi-thread", "fs", "sync"] }
chrono = "0.4.38"
thiserror = "1.0.65"
serde = "1.0.216"
serde_json = "1.0.134"
axum = "0.7.9"
tokio = { version = "1.42.0", features = ["rt-multi-thread", "fs", "sync"] }
chrono = "0.4.39"
thiserror = "2.0.9"
log = "0.4.22"
simple_logger = { version = "5.0.0", default-features = false, features = ["timestamps"] }
clap = { version = "4.5.20", features = ["derive", "env"] }
clap = { version = "4.5.23", features = ["derive", "env"] }
70 changes: 14 additions & 56 deletions src/database.rs
Original file line number Diff line number Diff line change
@@ -1,40 +1,18 @@
use crate::{configuration, StatusError};
use chrono::{DateTime, Utc};
use serde::Deserialize;
use std::vec::Vec;

#[derive(Clone)]
pub struct Database {
client: influxdb::Client,
}

#[derive(Debug)]
#[derive(Deserialize, Clone)]
pub struct TimeValue {
pub time: DateTime<Utc>,
pub value: f64,
}

#[derive(Deserialize, Clone)]
struct QueryResults {
pub results: Vec<QueryResult>,
}

#[derive(Deserialize, Clone)]
struct QueryResult {
#[allow(dead_code)]
pub statement_id: u64,
pub series: Option<Vec<QuerySeries>>,
}

#[derive(Deserialize, Clone)]
struct QuerySeries {
#[allow(dead_code)]
pub name: String,
#[allow(dead_code)]
pub columns: Vec<String>,
pub values: Vec<(String, f64)>,
}

impl Database {
pub fn new(config: &configuration::Database) -> Self {
let client = influxdb::Client::new(&config.connection, &config.database)
Expand All @@ -57,52 +35,32 @@ impl Database {
unit: &str,
validity: DateTime<Utc>,
) -> Result<TimeValue, StatusError> {
let time = validity
.timestamp_nanos_opt()
.ok_or(StatusError::Database("DateTime out of range".into()))?;

let query = influxdb::ReadQuery::new(format!(
r#"SELECT time, value FROM "{}" WHERE (entity_id = '{}' AND time > {}) ORDER BY time DESC LIMIT 1"#,
unit, name, time
r#"SELECT time, value FROM "{}" WHERE (entity_id = '{}' AND time > '{}') ORDER BY time DESC LIMIT 1"#,
unit,
name,
validity.to_rfc3339()
));

let results_raw = self
let mut result = self
.client
.query(query)
.json_query(query)
.await
.map_err(|e| StatusError::Database(e.to_string()))?;

let results: QueryResults = serde_json::from_str(&results_raw)
.map_err(|e| StatusError::Database(format!("serde '{}'", e)))?;

let values = results
.results
.first()
.ok_or(StatusError::Database(
"unexpected response, no results".into(),
))?
result
.deserialize_next::<TimeValue>()
.map_err(|e| StatusError::Database(format!("unexpected response: {:?}", e)))?
.series
.as_ref()
.ok_or(StatusError::Database(
"unexpected response, statements result does not contain any data".into(),
))?
.first()
.ok_or(StatusError::Database(
"unexpected response, no series".into(),
"unexpected response: no series".into(),
))?
.values
.first()
.ok_or(StatusError::Database(
"unexpected response, no values".into(),
))?;

let time: DateTime<Utc> = DateTime::parse_from_rfc3339(&values.0)
.map(|e| e.into())
.map_err(|e| StatusError::Database(e.to_string()))?;

Ok(TimeValue {
time,
value: values.1,
})
"unexpected response: no values".into(),
))
.cloned()
}
}
8 changes: 1 addition & 7 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,5 @@ async fn main() -> Result<(), StatusError> {
.init()
.expect("Logger already initialized");

match app().await {
Ok(_) => panic!(),
Err(err) => {
log::error!("{}", err);
Err(err)
}
}
app().await
}
4 changes: 1 addition & 3 deletions src/server/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,5 @@ pub async fn run(

axum::serve(listener, app)
.await
.map_err(|e| StatusError::Server(format!("Failed to start server ({})", e)))?;

Ok(())
.map_err(|e| StatusError::Server(format!("Failed to start server ({})", e)))
}
14 changes: 5 additions & 9 deletions src/server/routes/status.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use axum::{extract::State, http, Json};
use axum::{extract::State, Json};
use chrono::{DateTime, TimeZone, Utc};
use spaceapi::{sensors, Status as SpaceStatus};
use std::sync::Arc;
Expand All @@ -23,17 +23,13 @@ impl StateStatus {
}
}

pub async fn get_status(
State(state): State<Arc<AppState>>,
) -> (http::StatusCode, Json<SpaceStatus>) {
pub async fn get_status(State(state): State<Arc<AppState>>) -> Json<SpaceStatus> {
log::info!("GET /status.json");

(http::StatusCode::OK, Json(update_template(&state).await))
Json(update_template(&state).await)
}

pub async fn get_status_cache(
State(state): State<Arc<AppState>>,
) -> (http::StatusCode, Json<SpaceStatus>) {
pub async fn get_status_cache(State(state): State<Arc<AppState>>) -> Json<SpaceStatus> {
log::info!("GET /status.json");

let status = {
Expand All @@ -46,7 +42,7 @@ pub async fn get_status_cache(
current.status.clone()
};

(http::StatusCode::OK, Json(status))
Json(status)
}

async fn update_template(appstate: &Arc<AppState>) -> SpaceStatus {
Expand Down

0 comments on commit f5ebc54

Please sign in to comment.