Skip to content

Commit

Permalink
minor refactoring and fixes: dev module (#373)
Browse files Browse the repository at this point in the history
  • Loading branch information
AnthonyMichaelTDM authored May 12, 2024
1 parent da47e0f commit 5d1a0cb
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 15 deletions.
19 changes: 9 additions & 10 deletions create-rust-app/src/dev/controller.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::Database;
use anyhow::{bail, Result};
use diesel::{
migration::{Migration, MigrationSource},
query_dsl::RunQueryDsl,
Expand Down Expand Up @@ -43,12 +44,11 @@ pub fn query_db(db: &Database, body: &MySqlQuery) -> Result<String, diesel::resu
}

/// /db/is-connected
///
/// # Panics
/// * cannot connect to the database
#[must_use]
pub fn is_connected(db: &Database) -> bool {
let mut db = db.pool.clone().get().unwrap();
let Ok(mut db) = db.pool.clone().get() else {
return false;
};
let is_connected = sql_query("SELECT 1;").execute(&mut db);
is_connected.is_err()
}
Expand Down Expand Up @@ -136,25 +136,24 @@ pub fn needs_migration(db: &Database) -> bool {
/// * cannot find the migrations directory
/// * cannot run the migrations
///
/// TODO: return a Result instead of a tuple (bool, Option<String>), this is Rust, not Go
#[must_use]
pub fn migrate_db(db: &Database) -> (bool, /* error message: */ Option<String>) {
/// TODO: Propagate more of these errors instead of panicking
pub fn migrate_db(db: &Database) -> Result<()> {
let mut db = db.pool.clone().get().unwrap();

let source = FileBasedMigrations::find_migrations_directory().unwrap();
let has_pending_migrations =
MigrationHarness::has_pending_migration(&mut db, source.clone()).unwrap();

if !has_pending_migrations {
return (true, None);
return Ok(());
}

let op = MigrationHarness::run_pending_migrations(&mut db, source);
match op {
Ok(_) => (true, None),
Ok(_) => Ok(()),
Err(err) => {
println!("{err:#?}");
(false, Some(err.to_string()))
bail!(err)
}
}
}
Expand Down
8 changes: 6 additions & 2 deletions create-rust-app/src/dev/dev_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ async fn handle_socket(stream: WebSocket, state: Arc<AppState>) {
}
DevServerEvent::CompileMessages(messages) => {
let mut s = state2.dev.lock().unwrap();
s.compiler_messages = messages.clone();
s.compiler_messages.clone_from(&messages);
}
DevServerEvent::SHUTDOWN => {
let mut s = state2.dev.lock().unwrap();
Expand Down Expand Up @@ -300,7 +300,11 @@ async fn handle_socket(stream: WebSocket, state: Arc<AppState>) {
println!("📝 Could not open file `{file_name}`");
});
} else if t.eq_ignore_ascii_case("migrate") {
let (success, error_message) = controller::migrate_db(&state3.db);
let (success, error_message) =
match controller::migrate_db(&state3.db) {
Ok(_) => (true, None),
Err(e) => (false, Some(e.to_string())),
};

state3
.tx
Expand Down
9 changes: 6 additions & 3 deletions create-rust-app/src/dev/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,11 +305,14 @@ fn check_exit(state: &DevState) {

async fn listen_for_signals(signal_tx: tokio::sync::broadcast::Sender<DevServerEvent>) {
let (event_sender, event_receiver) = priority::bounded::<Event, Priority>(1024);
let (er_s, mut er_r) = tokio::sync::mpsc::channel(64);
let (error_sender, mut error_receiver) = tokio::sync::mpsc::channel(64);

// panic on errors
tokio::spawn(async move {
while let Some(error) = er_r.recv().await {
// we panic on the first error we receive, so we only need to recv once
// if, in the future, we change the error handling to be more robust (not panic), we'll need to loop here
// like `while let Some(error) = error_receiver.recv().await { ... }`
if let Some(error) = error_receiver.recv().await {
panic!(
"Error handling process signal:\n==============================\n{:#?}",
error
Expand All @@ -328,5 +331,5 @@ async fn listen_for_signals(signal_tx: tokio::sync::broadcast::Sender<DevServerE
}
});

worker(er_s, event_sender).await.unwrap();
worker(error_sender, event_sender).await.unwrap();
}

0 comments on commit 5d1a0cb

Please sign in to comment.