Skip to content

Commit

Permalink
feat: combining graph query to keep nodes and edges consistent
Browse files Browse the repository at this point in the history
  • Loading branch information
112batuhan committed Nov 28, 2024
1 parent 9db6ba2 commit 2f81b76
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 33 deletions.
33 changes: 19 additions & 14 deletions src/database/graph_vizualizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,19 @@ pub struct GraphInfluence {
influence_type: u8,
}

#[derive(Serialize, JsonSchema, Clone)]
pub struct GraphData {
pub nodes: Vec<GraphUser>,
pub links: Vec<GraphInfluence>,
}

impl DatabaseClient {
pub async fn get_users_for_graph(&self) -> Result<Vec<GraphUser>, AppError> {
let graph_users: Vec<GraphUser> = self
/// These two select queries are combined into one. The goal is to keep the data consistent
/// with each other to avoid errors in graphs. It's an edge case but can happen if load is
/// high. And since we cache the results, the error will stay on UI for the duration of the
/// cache. Not optimal. If it happens regardless, then use transactions.
pub async fn get_graph_data(&self) -> Result<GraphData, AppError> {
let mut query_result = self
.db
.query(
"
Expand All @@ -37,19 +47,14 @@ impl DatabaseClient {
WHERE
count(<-influenced_by) > 0
OR count(->influenced_by) > 0;
SELECT meta::id(in) AS source, meta::id(out) AS target, influence_type FROM influenced_by;
",
)
.await?
.take(0)?;
Ok(graph_users)
}

pub async fn get_influences_for_graph(&self) -> Result<Vec<GraphInfluence>, AppError> {
let graph_influences: Vec<GraphInfluence> = self
.db
.query("SELECT meta::id(in) AS source, meta::id(out) AS target, influence_type FROM influenced_by;")
.await?
.take(0)?;
Ok(graph_influences)
.await?;
Ok(GraphData {
nodes: query_result.take(0)?,
links: query_result.take(1)?,
})
}
}
21 changes: 2 additions & 19 deletions src/handlers/graph_vizualizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,8 @@ use std::{
};

use axum::{extract::State, Json};
use futures::try_join;
use schemars::JsonSchema;
use serde::Serialize;

use crate::{
database::graph_vizualizer::{GraphInfluence, GraphUser},
error::AppError,
AppState,
};

#[derive(Serialize, JsonSchema, Clone)]
pub struct GraphData {
pub nodes: Vec<GraphUser>,
pub links: Vec<GraphInfluence>,
}
use crate::{database::graph_vizualizer::GraphData, error::AppError, AppState};

pub struct GraphCacheInner {
pub data: Option<GraphData>,
Expand Down Expand Up @@ -65,11 +52,7 @@ pub async fn get_graph_data(
return Ok(Json(cached_graph));
}

let (nodes, links) = try_join!(
state.db.get_users_for_graph(),
state.db.get_influences_for_graph()
)?;
let graph_data = GraphData { nodes, links };
let graph_data = state.db.get_graph_data().await?;
state.graph_cache.update(graph_data.clone())?;

Ok(Json(graph_data))
Expand Down

0 comments on commit 2f81b76

Please sign in to comment.