Skip to content

Commit

Permalink
webapi: Create shared DB connection logic
Browse files Browse the repository at this point in the history
  • Loading branch information
mrozycki committed Dec 18, 2024
1 parent 14ef137 commit d87009c
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 26 deletions.
5 changes: 3 additions & 2 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions webapi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ toml = "0.8.19"
log = "0.4.17"
env_logger = "0.10.0"
thiserror = "2.0.7"
anyhow = "1.0.94"

[features]
default = ["midi", "audio"]
Expand Down
30 changes: 30 additions & 0 deletions webapi/src/db.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use std::{str::FromStr, sync::Arc};

use sqlx::{sqlite::SqliteConnectOptions, ConnectOptions, SqliteConnection};
use tokio::sync::{Mutex, MutexGuard};

use crate::config::RustmasConfig;

#[derive(Debug, Clone)]
pub struct SharedDbConnection {
inner: Arc<Mutex<SqliteConnection>>,
}

impl SharedDbConnection {
pub async fn from_config(config: &RustmasConfig) -> anyhow::Result<Self> {
let mut conn = SqliteConnectOptions::from_str(&config.database_path.to_string_lossy())?
.disable_statement_logging()
.connect()
.await?;

sqlx::migrate!("../migrations").run(&mut conn).await?;

Ok(Self {
inner: Arc::new(Mutex::new(conn)),
})
}

pub async fn lock(&self) -> MutexGuard<'_, SqliteConnection> {
self.inner.lock().await
}
}
5 changes: 4 additions & 1 deletion webapi/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
mod animations;
mod config;
mod db;
mod events;
mod parameters;
mod visualizer;

use ::config::Config;
use actix_cors::Cors;
use config::RustmasConfig;
use db::SharedDbConnection;
use log::info;
use std::error::Error;
use tokio::sync::{mpsc, Mutex};
Expand All @@ -28,7 +30,8 @@ async fn main() -> Result<(), Box<dyn Error>> {
.try_deserialize::<RustmasConfig>()?;

info!("Setting up database");
let parameters = web::Data::new(parameters::Logic::from(&config).await?);
let shared_db = SharedDbConnection::from_config(&config).await?;
let parameters = web::Data::new(parameters::Logic::from(shared_db));
let animations = web::Data::new(animations::Logic::new());

let (sender, receiver) = mpsc::channel::<lightfx::Frame>(1);
Expand Down
15 changes: 7 additions & 8 deletions webapi/src/parameters/logic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::collections::HashMap;
use log::warn;
use webapi_model::{Configuration, ConfigurationSchema, ParameterValue, ValueSchema};

use crate::config::RustmasConfig;
use crate::db::SharedDbConnection;
use crate::parameters;

#[derive(Debug, thiserror::Error)]
Expand All @@ -24,13 +24,6 @@ impl Logic {
Self { storage }
}

pub async fn from(config: &RustmasConfig) -> Result<Self, LogicError> {
let parameters_storage = parameters::Storage::new(&config.database_path.to_string_lossy())
.await
.map_err(|e| LogicError::InternalError(e.to_string()))?;
Ok(Self::new(parameters_storage))
}

pub async fn restore_from_db(
&self,
controller: &mut rustmas_animator::Controller,
Expand Down Expand Up @@ -107,6 +100,12 @@ impl Logic {
}
}

impl From<SharedDbConnection> for Logic {
fn from(value: SharedDbConnection) -> Self {
Self::new(parameters::Storage::new(value))
}
}

fn reconcile_parameters(
defaults: HashMap<String, ParameterValue>,
mut values: HashMap<String, ParameterValue>,
Expand Down
22 changes: 7 additions & 15 deletions webapi/src/parameters/storage.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,18 @@
use std::{collections::HashMap, error::Error, str::FromStr, sync::Arc};
use std::{collections::HashMap, error::Error};

use sqlx::{sqlite::SqliteConnectOptions, ConnectOptions, Executor, Row, SqliteConnection};
use tokio::sync::Mutex;
use sqlx::{Executor, Row};
use webapi_model::ParameterValue;

use crate::db::SharedDbConnection;

#[derive(Debug, Clone)]
pub struct Storage {
conn: Arc<Mutex<SqliteConnection>>,
conn: SharedDbConnection,
}

impl Storage {
pub async fn new(path: &str) -> Result<Self, Box<dyn Error>> {
let mut conn = SqliteConnectOptions::from_str(path)?
.disable_statement_logging()
.connect()
.await?;

sqlx::migrate!("../migrations").run(&mut conn).await?;

Ok(Self {
conn: Arc::new(Mutex::new(conn)),
})
pub fn new(conn: SharedDbConnection) -> Self {
Self { conn }
}

pub async fn save(
Expand Down

0 comments on commit d87009c

Please sign in to comment.