diff --git a/editoast/editoast_derive/src/model.rs b/editoast/editoast_derive/src/model.rs index 495f766c4f0..7704c434fab 100644 --- a/editoast/editoast_derive/src/model.rs +++ b/editoast/editoast_derive/src/model.rs @@ -92,7 +92,7 @@ fn create_functions(config: &Config) -> TokenStream { } #[doc = #documentation] - async fn create(self, db_pool: actix_web::web::Data) -> crate::error::Result { + async fn create(self, db_pool: std::sync::Arc) -> crate::error::Result { let mut conn = db_pool.get().await?; self.create_conn(&mut conn).await } @@ -142,7 +142,7 @@ fn retrieve_functions(config: &Config) -> TokenStream { } #[doc = #retrieve_documentation] - async fn retrieve(db_pool: actix_web::web::Data, id: i64) -> crate::error::Result> { + async fn retrieve(db_pool: std::sync::Arc, id: i64) -> crate::error::Result> { let mut conn = db_pool.get().await?; Self::retrieve_conn(&mut conn, id).await } @@ -188,7 +188,7 @@ fn delete_functions(config: &Config) -> TokenStream { } #[doc = #documentation] - async fn delete(db_pool: actix_web::web::Data, id: i64) -> crate::error::Result { + async fn delete(db_pool: std::sync::Arc, id: i64) -> crate::error::Result { let mut conn = db_pool.get().await?; Self::delete_conn(&mut conn, id).await } diff --git a/editoast/src/fixtures.rs b/editoast/src/fixtures.rs index f187875bcd2..93fe0f9c563 100644 --- a/editoast/src/fixtures.rs +++ b/editoast/src/fixtures.rs @@ -2,6 +2,7 @@ pub mod tests { use std::io::Cursor; use std::ops::{Deref, DerefMut}; + use std::sync::Arc; use crate::modelsv2::connection_pool::DbConnectionConfig; use crate::modelsv2::connection_pool::DbConnectionPool; @@ -25,7 +26,6 @@ pub mod tests { }, }; - use actix_web::web::Data; use chrono::Utc; use editoast_schemas::infra::ElectricalProfile; use editoast_schemas::infra::ElectricalProfileSetData; @@ -40,7 +40,7 @@ pub mod tests { pub struct TestFixture + Identifiable + Send> { pub model: T, - pub db_pool: Data, + pub db_pool: Arc, pub infra: Option, } @@ -57,7 +57,7 @@ pub mod tests { self.model.get_id() } - pub fn new(model: T, db_pool: Data) -> Self { + pub fn new(model: T, db_pool: Arc) -> Self { TestFixture { model, db_pool, @@ -67,7 +67,7 @@ pub mod tests { } impl + models::Create + Identifiable + Send> TestFixture { - pub async fn create_legacy(model: T, db_pool: Data) -> Self { + pub async fn create_legacy(model: T, db_pool: Arc) -> Self { TestFixture { model: model.create(db_pool.clone()).await.unwrap(), db_pool, @@ -81,7 +81,7 @@ pub mod tests { T: modelsv2::Model + modelsv2::DeleteStatic + Identifiable + Send, T::Changeset: modelsv2::Create + Send, { - pub async fn create(cs: T::Changeset, db_pool: Data) -> Self { + pub async fn create(cs: T::Changeset, db_pool: Arc) -> Self { use modelsv2::Create; let conn = &mut db_pool.get().await.unwrap(); TestFixture { @@ -111,7 +111,7 @@ pub mod tests { } pub trait IntoFixture: modelsv2::DeleteStatic + Identifiable + Send { - fn into_fixture(self, db_pool: Data) -> TestFixture { + fn into_fixture(self, db_pool: Arc) -> TestFixture { TestFixture::new(self, db_pool) } } @@ -139,13 +139,13 @@ pub mod tests { } #[fixture] - pub fn db_pool() -> Data { + pub fn db_pool() -> Arc { let pg_config_url = PostgresConfig::default() .url() .expect("cannot get postgres config url"); let config = DbConnectionConfig::new(pg_config_url); let pool = DbConnectionPool::builder(config).build().unwrap(); - Data::new(pool) + Arc::new(pool) } pub fn get_fast_rolling_stock_form(name: &str) -> RollingStockForm { @@ -166,7 +166,7 @@ pub mod tests { pub async fn named_fast_rolling_stock( name: &str, - db_pool: Data, + db_pool: Arc, ) -> TestFixture { let mut rs: Changeset = get_fast_rolling_stock_form(name).into(); rs = rs.version(0); @@ -188,7 +188,7 @@ pub mod tests { pub async fn named_other_rolling_stock( name: &str, - db_pool: Data, + db_pool: Arc, ) -> TestFixture { let mut rs: Changeset = get_other_rolling_stock_form(name).into(); rs = rs.version(0); @@ -196,7 +196,7 @@ pub mod tests { } async fn make_train_schedule( - db_pool: Data, + db_pool: Arc, path_id: i64, timetable_id: i64, rolling_stock_id: i64, @@ -221,7 +221,7 @@ pub mod tests { #[fixture] pub async fn train_schedule_v2( #[future] timetable_v2: TestFixture, - db_pool: Data, + db_pool: Arc, ) -> TrainScheduleV2FixtureSet { let timetable = timetable_v2.await; let train_schedule = make_simple_train_schedule_v2(timetable.id(), db_pool).await; @@ -234,7 +234,7 @@ pub mod tests { pub async fn make_simple_train_schedule_v2( timetable_id: i64, - db_pool: Data, + db_pool: Arc, ) -> TestFixture { let train_schedule_base: TrainScheduleBase = serde_json::from_str(include_str!("./tests/train_schedules/simple.json")) @@ -331,7 +331,7 @@ pub mod tests { #[fixture] pub async fn study_fixture_set( - db_pool: Data, + db_pool: Arc, #[future] project: TestFixture, ) -> StudyFixtureSet { let project = project.await; @@ -351,7 +351,7 @@ pub mod tests { } #[fixture] - pub async fn project(db_pool: Data) -> TestFixture { + pub async fn project(db_pool: Arc) -> TestFixture { let project_model = Project::changeset() .name("test_project".to_owned()) .budget(Some(0)) @@ -362,7 +362,7 @@ pub mod tests { } #[fixture] - pub async fn timetable(db_pool: Data) -> TestFixture { + pub async fn timetable(db_pool: Arc) -> TestFixture { let timetable_model = Timetable { id: None, name: Some(String::from("with_electrical_profiles")), @@ -371,7 +371,7 @@ pub mod tests { } #[fixture] - pub async fn timetable_v2(db_pool: Data) -> TestFixture { + pub async fn timetable_v2(db_pool: Arc) -> TestFixture { TestFixture::create( TimetableV2::changeset().electrical_profile_set_id(None), db_pool, @@ -389,7 +389,7 @@ pub mod tests { #[fixture] pub async fn scenario_v2_fixture_set( - db_pool: Data, + db_pool: Arc, #[future] timetable_v2: TestFixture, #[future] project: TestFixture, ) -> ScenarioV2FixtureSet { @@ -416,7 +416,7 @@ pub mod tests { } #[fixture] - pub async fn document_example(db_pool: Data) -> TestFixture { + pub async fn document_example(db_pool: Arc) -> TestFixture { let img = image::open("src/tests/example_rolling_stock_image_1.gif").unwrap(); let mut img_bytes: Vec = Vec::new(); assert!(img @@ -438,7 +438,7 @@ pub mod tests { pub async fn rolling_stock_livery( name: &str, - db_pool: Data, + db_pool: Arc, ) -> RollingStockLiveryFixture { let mut rs_name = "fast_rolling_stock_".to_string(); rs_name.push_str(name); @@ -459,7 +459,7 @@ pub mod tests { #[fixture] pub async fn electrical_profile_set( - db_pool: Data, + db_pool: Arc, ) -> TestFixture { TestFixture::create( serde_json::from_str::>(include_str!( @@ -473,7 +473,7 @@ pub mod tests { #[fixture] pub async fn dummy_electrical_profile_set( - db_pool: Data, + db_pool: Arc, ) -> TestFixture { let ep_set_data = ElectricalProfileSetData { levels: vec![ElectricalProfile { @@ -490,7 +490,7 @@ pub mod tests { } #[fixture] - pub async fn empty_infra(db_pool: Data) -> TestFixture { + pub async fn empty_infra(db_pool: Arc) -> TestFixture { TestFixture::create( Infra::changeset() .name("test_infra".to_owned()) @@ -500,7 +500,7 @@ pub mod tests { .await } - async fn make_small_infra(db_pool: Data) -> Infra { + async fn make_small_infra(db_pool: Arc) -> Infra { let railjson: RailJson = serde_json::from_str(include_str!( "../../tests/data/infras/small_infra/infra.json" )) @@ -524,12 +524,12 @@ pub mod tests { /// is made, the `editoast/tests/small_infra/small_infra.json` file should be updated /// to the latest infra description. #[fixture] - pub async fn small_infra(db_pool: Data) -> TestFixture { + pub async fn small_infra(db_pool: Arc) -> TestFixture { TestFixture::new(make_small_infra(db_pool.clone()).await, db_pool) } #[fixture] - pub async fn pathfinding(db_pool: Data) -> TestFixture { + pub async fn pathfinding(db_pool: Arc) -> TestFixture { let small_infra = make_small_infra(db_pool.clone()).await; let pf_cs = PathfindingChangeset { infra_id: Some(small_infra.id), @@ -571,7 +571,7 @@ pub mod tests { pub async fn train_with_simulation_output_fixture_set( name: &str, - db_pool: Data, + db_pool: Arc, ) -> TrainScheduleWithSimulationOutputFixtureSet { let ScenarioFixtureSet { project, diff --git a/editoast/src/generated_data/mod.rs b/editoast/src/generated_data/mod.rs index d7dfb1f2ae0..10e72a7e434 100644 --- a/editoast/src/generated_data/mod.rs +++ b/editoast/src/generated_data/mod.rs @@ -30,6 +30,7 @@ use operational_point::OperationalPointLayer; use psl_sign::PSLSignLayer; use signal::SignalLayer; use speed_section::SpeedSectionLayer; +use std::sync::Arc; use switch::SwitchLayer; use tracing::debug; use track_section::TrackSectionLayer; @@ -63,7 +64,7 @@ pub trait GeneratedData { } async fn refresh_pool( - pool: crate::Data, + pool: Arc, infra: i64, infra_cache: &InfraCache, ) -> Result<()> { @@ -82,7 +83,7 @@ pub trait GeneratedData { /// Refresh all the generated data of a given infra pub async fn refresh_all( - db_pool: crate::Data, + db_pool: Arc, infra: i64, infra_cache: &InfraCache, ) -> Result<()> { diff --git a/editoast/src/main.rs b/editoast/src/main.rs index 6802a5ff2e3..05972f9b9ea 100644 --- a/editoast/src/main.rs +++ b/editoast/src/main.rs @@ -66,6 +66,7 @@ use std::error::Error; use std::fs::File; use std::io::{BufReader, IsTerminal}; use std::process::exit; +use std::sync::Arc; use std::{env, fs}; use thiserror::Error; use tracing::{error, info, warn}; @@ -193,7 +194,9 @@ async fn run() -> Result<(), Box> { match client.command { Commands::Runserver(args) => runserver(args, create_db_pool()?, redis_config).await, - Commands::ImportRollingStock(args) => import_rolling_stock(args, create_db_pool()?).await, + Commands::ImportRollingStock(args) => { + import_rolling_stock(args, create_db_pool()?.into_inner()).await + } Commands::OsmToRailjson(args) => { osm_to_railjson::osm_to_railjson(args.osm_pbf_in, args.railjson_out) } @@ -203,13 +206,13 @@ async fn run() -> Result<(), Box> { } Commands::ElectricalProfiles(subcommand) => match subcommand { ElectricalProfilesCommands::Import(args) => { - electrical_profile_set_import(args, create_db_pool()?).await + electrical_profile_set_import(args, create_db_pool()?.into_inner()).await } ElectricalProfilesCommands::List(args) => { - electrical_profile_set_list(args, create_db_pool()?).await + electrical_profile_set_list(args, create_db_pool()?.into_inner()).await } ElectricalProfilesCommands::Delete(args) => { - electrical_profile_set_delete(args, create_db_pool()?).await + electrical_profile_set_delete(args, create_db_pool()?.into_inner()).await } }, Commands::Search(subcommand) => match subcommand { @@ -218,26 +221,36 @@ async fn run() -> Result<(), Box> { Ok(()) } SearchCommands::MakeMigration(args) => make_search_migration(args), - SearchCommands::Refresh(args) => refresh_search_tables(args, create_db_pool()?).await, + SearchCommands::Refresh(args) => { + refresh_search_tables(args, create_db_pool()?.into_inner()).await + } }, Commands::Infra(subcommand) => match subcommand { - InfraCommands::Clone(args) => clone_infra(args, create_db_pool()?).await, - InfraCommands::Clear(args) => clear_infra(args, create_db_pool()?, redis_config).await, + InfraCommands::Clone(args) => clone_infra(args, create_db_pool()?.into_inner()).await, + InfraCommands::Clear(args) => { + clear_infra(args, create_db_pool()?.into_inner(), redis_config).await + } InfraCommands::Generate(args) => { - generate_infra(args, create_db_pool()?, redis_config).await + generate_infra(args, create_db_pool()?.into_inner(), redis_config).await + } + InfraCommands::ImportRailjson(args) => { + import_railjson(args, create_db_pool()?.into_inner()).await } - InfraCommands::ImportRailjson(args) => import_railjson(args, create_db_pool()?).await, }, Commands::Timetables(subcommand) => match subcommand { - TimetablesCommands::Import(args) => trains_import(args, create_db_pool()?).await, - TimetablesCommands::Export(args) => trains_export(args, create_db_pool()?).await, + TimetablesCommands::Import(args) => { + trains_import(args, create_db_pool()?.into_inner()).await + } + TimetablesCommands::Export(args) => { + trains_export(args, create_db_pool()?.into_inner()).await + } }, } } async fn trains_export( args: ExportTimetableArgs, - db_pool: Data, + db_pool: Arc, ) -> Result<(), Box> { let conn = &mut db_pool.get().await?; let train_ids = match TimetableWithTrains::retrieve(conn, args.id).await? { @@ -271,7 +284,7 @@ async fn trains_export( async fn trains_import( args: ImportTimetableArgs, - db_pool: Data, + db_pool: Arc, ) -> Result<(), Box> { let train_file = match File::open(args.path.clone()) { Ok(file) => file, @@ -495,7 +508,7 @@ async fn batch_retrieve_infras( /// This command refresh all infra given as input (if no infra given then refresh all of them) async fn generate_infra( args: GenerateArgs, - db_pool: Data, + db_pool: Arc, redis_config: RedisConfig, ) -> Result<(), Box> { let mut conn = db_pool.get().await?; @@ -539,7 +552,7 @@ async fn generate_infra( async fn import_rolling_stock( args: ImportRollingStockArgs, - db_pool: Data, + db_pool: Arc, ) -> Result<(), Box> { for rolling_stock_path in args.rolling_stock_path { let rolling_stock_file = File::open(rolling_stock_path)?; @@ -589,7 +602,7 @@ async fn import_rolling_stock( async fn clone_infra( infra_args: InfraCloneArgs, - db_pool: Data, + db_pool: Arc, ) -> Result<(), Box> { let conn = &mut db_pool.get().await?; let infra = Infra::retrieve(conn, infra_args.id as i64) @@ -613,7 +626,7 @@ async fn clone_infra( async fn import_railjson( args: ImportRailjsonArgs, - db_pool: Data, + db_pool: Arc, ) -> Result<(), Box> { let railjson_file = match File::open(args.railjson_path.clone()) { Ok(file) => file, @@ -660,7 +673,7 @@ async fn import_railjson( async fn electrical_profile_set_import( args: ImportProfileSetArgs, - db_pool: Data, + db_pool: Arc, ) -> Result<(), Box> { let electrical_profile_set_file = File::open(args.electrical_profile_set_path)?; @@ -678,7 +691,7 @@ async fn electrical_profile_set_import( async fn electrical_profile_set_list( args: ListProfileSetArgs, - db_pool: Data, + db_pool: Arc, ) -> Result<(), Box> { let mut conn = db_pool.get().await?; let electrical_profile_sets = ElectricalProfileSet::list_light(&mut conn).await.unwrap(); @@ -696,7 +709,7 @@ async fn electrical_profile_set_list( async fn electrical_profile_set_delete( args: DeleteProfileSetArgs, - db_pool: Data, + db_pool: Arc, ) -> Result<(), Box> { for profile_set_id in args.profile_set_ids { let conn = &mut db_pool.get().await?; @@ -716,7 +729,7 @@ async fn electrical_profile_set_delete( /// This command clear all generated data for the given infra async fn clear_infra( args: ClearArgs, - db_pool: Data, + db_pool: Arc, redis_config: RedisConfig, ) -> Result<(), Box> { let mut conn = db_pool.get().await?; @@ -824,7 +837,7 @@ fn make_search_migration(args: MakeMigrationArgs) -> Result<(), Box, + db_pool: Arc, ) -> Result<(), Box> { let objects = if args.objects.is_empty() { SearchConfigFinder::all() @@ -899,10 +912,11 @@ mod tests { use rstest::rstest; use serde::Serialize; use std::io::Write; + use std::sync::Arc; use tempfile::NamedTempFile; #[rstest] - async fn import_export_timetable_schedule_v2(db_pool: Data) { + async fn import_export_timetable_schedule_v2(db_pool: Arc) { let conn = &mut db_pool.get().await.unwrap(); let changeset = Timetable::changeset(); @@ -941,7 +955,7 @@ mod tests { } #[rstest] - async fn import_rolling_stock_ko_file_not_found(db_pool: Data) { + async fn import_rolling_stock_ko_file_not_found(db_pool: Arc) { // GIVEN let args = ImportRollingStockArgs { rolling_stock_path: vec!["non/existing/railjson/file/location".into()], @@ -956,7 +970,7 @@ mod tests { #[rstest] async fn import_non_electric_rs_without_startup_and_panto_values( - db_pool: Data, + db_pool: Arc, ) { // GIVEN let rolling_stock_name = @@ -987,7 +1001,7 @@ mod tests { } #[rstest] - async fn import_non_electric_rs_with_startup_and_panto_values(db_pool: Data) { + async fn import_non_electric_rs_with_startup_and_panto_values(db_pool: Arc) { // GIVEN let rolling_stock_name = "fast_rolling_stock_import_non_electric_rs_with_startup_and_panto_values"; @@ -1021,7 +1035,7 @@ mod tests { } #[rstest] - async fn import_electric_rs_without_startup_and_panto_values(db_pool: Data) { + async fn import_electric_rs_without_startup_and_panto_values(db_pool: Arc) { // GIVEN let rolling_stock_name = "fast_rolling_stock_import_electric_rs_without_startup_and_panto_values"; @@ -1050,7 +1064,7 @@ mod tests { } #[rstest] - async fn import_electric_rs_with_startup_and_panto_values(db_pool: Data) { + async fn import_electric_rs_with_startup_and_panto_values(db_pool: Arc) { // GIVEN let rolling_stock_name = "fast_rolling_stock_import_electric_rs_with_startup_and_panto_values"; @@ -1088,7 +1102,7 @@ mod tests { } #[rstest] - async fn import_railjson_ko_file_not_found(db_pool: Data) { + async fn import_railjson_ko_file_not_found(db_pool: Arc) { // GIVEN let railjson_path = "non/existing/railjson/file/location"; let args: ImportRailjsonArgs = ImportRailjsonArgs { @@ -1113,7 +1127,7 @@ mod tests { } #[rstest] - async fn import_railjson_ok(db_pool: Data) { + async fn import_railjson_ok(db_pool: Arc) { // GIVEN let railjson = Default::default(); let file = generate_temp_file::(&railjson); @@ -1154,7 +1168,7 @@ mod tests { #[rstest] async fn test_electrical_profile_set_delete( #[future] electrical_profile_set: TestFixture, - db_pool: Data, + db_pool: Arc, ) { // GIVEN let electrical_profile_set = electrical_profile_set.await; @@ -1181,7 +1195,7 @@ mod tests { #[rstest] async fn test_electrical_profile_set_list_doesnt_fail( #[future] electrical_profile_set: TestFixture, - db_pool: Data, + db_pool: Arc, ) { let _electrical_profile_set = electrical_profile_set.await; for quiet in [true, false] { diff --git a/editoast/src/models/mod.rs b/editoast/src/models/mod.rs index ea247dcf049..1e42c6a7fbc 100644 --- a/editoast/src/models/mod.rs +++ b/editoast/src/models/mod.rs @@ -4,11 +4,11 @@ mod text_array; mod timetable; pub mod train_schedule; -use actix_web::web::Data; use async_trait::async_trait; pub use scenario::Scenario; pub use scenario::ScenarioWithCountTrains; pub use scenario::ScenarioWithDetails; +use std::sync::Arc; pub use text_array::TextArray; pub use timetable::check_train_validity; pub use timetable::Timetable; @@ -84,7 +84,7 @@ pub trait Create: Sized + 'static { /// let created_obj = obj.create(db_pool).await?; /// let obj_id = created_obj.id.unwrap(); /// ``` - async fn create(self, db_pool: Data) -> Result { + async fn create(self, db_pool: Arc) -> Result { let mut conn = db_pool.get().await?; Self::create_conn(self, &mut conn).await } @@ -108,7 +108,7 @@ pub trait Delete { /// ``` /// assert!(Model::delete(db_pool, 42).await?); /// ``` - async fn delete(db_pool: Data, id: i64) -> Result { + async fn delete(db_pool: Arc, id: i64) -> Result { let mut conn = db_pool.get().await?; Self::delete_conn(&mut conn, id).await } @@ -134,7 +134,7 @@ pub trait Retrieve: Sized + 'static { /// // do something with obj /// } /// ``` - async fn retrieve(db_pool: Data, id: i64) -> Result> { + async fn retrieve(db_pool: Arc, id: i64) -> Result> { let mut conn = db_pool.get().await?; Self::retrieve_conn(&mut conn, id).await } @@ -185,7 +185,7 @@ pub trait List: Sized + 'static { /// let new_obj = patch_model.update(db_pool).await?.expect("Object not found"); /// ``` async fn list( - db_pool: Data, + db_pool: Arc, page: i64, page_size: i64, params: T, diff --git a/editoast/src/models/pathfinding.rs b/editoast/src/models/pathfinding.rs index 58ac058c334..dd706d10f93 100644 --- a/editoast/src/models/pathfinding.rs +++ b/editoast/src/models/pathfinding.rs @@ -250,7 +250,7 @@ impl Identifiable for Pathfinding { #[cfg(test)] pub mod tests { - use actix_web::web::Data; + use std::sync::Arc; use super::*; use crate::fixtures::tests::TestFixture; @@ -310,7 +310,7 @@ pub mod tests { pub async fn simple_pathfinding_fixture( infra_id: i64, - db_pool: Data, + db_pool: Arc, ) -> TestFixture { let pathfinding = simple_pathfinding(infra_id); let mut changeset = PathfindingChangeset::from(pathfinding); diff --git a/editoast/src/models/scenario.rs b/editoast/src/models/scenario.rs index 6ae08974900..86cf4d1c0a7 100644 --- a/editoast/src/models/scenario.rs +++ b/editoast/src/models/scenario.rs @@ -1,4 +1,3 @@ -use actix_web::web::Data; use async_trait::async_trait; use chrono::NaiveDateTime; use chrono::Utc; @@ -16,6 +15,7 @@ use diesel_async::RunQueryDsl; use editoast_derive::Model; use serde::Deserialize; use serde::Serialize; +use std::sync::Arc; use utoipa::ToSchema; use super::List; @@ -117,10 +117,7 @@ pub struct ScenarioWithCountTrains { } impl Scenario { - pub async fn with_details( - self, - db_pool: Data, - ) -> Result { + pub async fn with_details(self, db_pool: Arc) -> Result { let mut conn = db_pool.get().await?; self.with_details_conn(&mut conn).await } @@ -223,6 +220,7 @@ impl List<(i64, Ordering)> for ScenarioWithCountTrains { #[cfg(test)] pub mod test { use rstest::rstest; + use std::sync::Arc; use super::*; use crate::fixtures::tests::db_pool; @@ -236,7 +234,7 @@ pub mod test { use crate::modelsv2::Ordering; #[rstest] - async fn create_delete_scenario(db_pool: Data) { + async fn create_delete_scenario(db_pool: Arc) { let ScenarioFixtureSet { scenario, .. } = scenario_fixture_set().await; // Delete the scenario @@ -251,7 +249,7 @@ pub mod test { } #[rstest] - async fn get_study(db_pool: Data) { + async fn get_study(db_pool: Arc) { let ScenarioFixtureSet { study, .. } = scenario_fixture_set().await; // Get a scenario @@ -269,7 +267,7 @@ pub mod test { } #[rstest] - async fn sort_scenario(db_pool: Data) { + async fn sort_scenario(db_pool: Arc) { let ScenarioFixtureSet { scenario, study, diff --git a/editoast/src/models/timetable.rs b/editoast/src/models/timetable.rs index 446df619634..739e15ea5a8 100644 --- a/editoast/src/models/timetable.rs +++ b/editoast/src/models/timetable.rs @@ -1,6 +1,3 @@ -use std::collections::HashMap; - -use actix_web::web::Data; use derivative::Derivative; use diesel::prelude::*; use diesel::result::Error as DieselError; @@ -9,6 +6,8 @@ use editoast_derive::Model; use futures::future::try_join_all; use serde::Deserialize; use serde::Serialize; +use std::collections::HashMap; +use std::sync::Arc; use utoipa::ToSchema; use super::train_schedule::TrainScheduleValidation; @@ -80,7 +79,7 @@ impl Timetable { /// some information about the simulation result pub async fn with_detailed_train_schedules( self, - db_pool: Data, + db_pool: Arc, ) -> Result { use crate::tables::infra::dsl as infra_dsl; use crate::tables::scenario::dsl as scenario_dsl; @@ -162,13 +161,13 @@ impl Timetable { /// Retrieves the associated train schedules pub async fn get_train_schedules( &self, - db_pool: Data, + db_pool: Arc, ) -> Result> { get_timetable_train_schedules(self.id.unwrap(), db_pool).await } /// Get infra_version from timetable - pub async fn infra_version_from_timetable(&self, db_pool: Data) -> String { + pub async fn infra_version_from_timetable(&self, db_pool: Arc) -> String { use crate::tables::infra::dsl as infra_dsl; use crate::tables::scenario::dsl as scenario_dsl; let timetable_id = self.id.unwrap(); @@ -198,7 +197,7 @@ impl Timetable { } /// Retrieve the associated scenario - pub async fn get_scenario(&self, db_pool: Data) -> Result { + pub async fn get_scenario(&self, db_pool: Arc) -> Result { let mut conn = db_pool.get().await.unwrap(); self.get_scenario_conn(&mut conn).await } @@ -206,7 +205,7 @@ impl Timetable { pub async fn get_timetable_train_schedules( timetable_id: i64, - db_pool: Data, + db_pool: Arc, ) -> Result> { use crate::tables::train_schedule; let mut conn = db_pool.get().await?; @@ -219,7 +218,7 @@ pub async fn get_timetable_train_schedules( pub async fn get_timetable_train_schedules_with_simulations( timetable_id: i64, - db_pool: Data, + db_pool: Arc, ) -> Result> { let train_schedules = get_timetable_train_schedules(timetable_id, db_pool.clone()).await?; diff --git a/editoast/src/models/train_schedule.rs b/editoast/src/models/train_schedule.rs index 2129ec8dc91..844470123a2 100644 --- a/editoast/src/models/train_schedule.rs +++ b/editoast/src/models/train_schedule.rs @@ -1,6 +1,5 @@ use std::collections::HashMap; -use actix_web::web::Data; use derivative::Derivative; use diesel::result::Error as DieselError; use diesel::ExpressionMethods; @@ -11,6 +10,7 @@ use editoast_schemas::train_schedule::Allowance; use editoast_schemas::train_schedule::RjsPowerRestrictionRange; use serde::Deserialize; use serde::Serialize; +use std::sync::Arc; use utoipa::ToSchema; use super::check_train_validity; @@ -477,7 +477,7 @@ pub struct ScheduledPoint { } pub async fn filter_invalid_trains( - db_pool: Data, + db_pool: Arc, schedules: Vec, infra_version: String, ) -> Result<(Vec, Vec)> { diff --git a/editoast/src/modelsv2/electrical_profiles.rs b/editoast/src/modelsv2/electrical_profiles.rs index a3e6aabbead..67fa4a7dca7 100644 --- a/editoast/src/modelsv2/electrical_profiles.rs +++ b/editoast/src/modelsv2/electrical_profiles.rs @@ -37,8 +37,8 @@ pub struct LightElectricalProfileSet { #[cfg(test)] mod tests { - use actix_web::web::Data; use rstest::rstest; + use std::sync::Arc; use super::*; use crate::fixtures::tests::db_pool; @@ -49,7 +49,7 @@ mod tests { #[rstest] async fn test_list_light( - db_pool: Data, + db_pool: Arc, #[future] electrical_profile_set: TestFixture, #[future] dummy_electrical_profile_set: TestFixture, ) { diff --git a/editoast/src/modelsv2/infra.rs b/editoast/src/modelsv2/infra.rs index 03f223b2ee8..02cc4237071 100644 --- a/editoast/src/modelsv2/infra.rs +++ b/editoast/src/modelsv2/infra.rs @@ -1,6 +1,5 @@ use std::pin::Pin; -use actix_web::web::Data; use async_trait::async_trait; use chrono::NaiveDateTime; use chrono::Utc; @@ -14,6 +13,7 @@ use futures::future::try_join_all; use futures::Future; use serde::Deserialize; use serde::Serialize; +use std::sync::Arc; use strum::IntoEnumIterator; use tracing::debug; use tracing::error; @@ -66,13 +66,13 @@ impl InfraChangeset { pub async fn persist( self, railjson: RailJson, - db_pool: Data, + db_pool: Arc, ) -> Result { let conn = &mut db_pool.get().await?; let infra = self.create(conn).await?; // TODO: lock infra for update debug!("🛤 Begin importing all railjson objects"); - if let Err(e) = persist_railjson(db_pool.into_inner(), infra.id, railjson).await { + if let Err(e) = persist_railjson(db_pool, infra.id, railjson).await { error!("Could not import infrastructure {}. Rolling back", infra.id); infra.delete(conn).await?; return Err(e); @@ -115,7 +115,7 @@ impl Infra { pub async fn clone( &self, - db_pool: Data, + db_pool: Arc, new_name: Option, ) -> Result { // Duplicate infra shell @@ -185,7 +185,7 @@ impl Infra { /// If refreshed you need to call `invalidate_after_refresh` to invalidate layer cache pub async fn refresh( &mut self, - db_pool: Data, + db_pool: Arc, force: bool, infra_cache: &InfraCache, ) -> Result { diff --git a/editoast/src/modelsv2/light_rolling_stock.rs b/editoast/src/modelsv2/light_rolling_stock.rs index 8ead8bf8d3f..e83a580c609 100644 --- a/editoast/src/modelsv2/light_rolling_stock.rs +++ b/editoast/src/modelsv2/light_rolling_stock.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; +use std::sync::Arc; -use actix_web::web::Data; use diesel::sql_query; use diesel::ExpressionMethods; use diesel::QueryDsl; @@ -68,7 +68,7 @@ pub struct LightRollingStockModel { impl LightRollingStockModel { pub async fn with_liveries( self, - db_pool: Data, + db_pool: Arc, ) -> Result { use crate::tables::rolling_stock_livery::dsl as livery_dsl; let mut conn = db_pool.get().await?; @@ -85,7 +85,7 @@ impl LightRollingStockModel { /// List the rolling stocks with their simplified effort curves pub async fn list( - db_pool: Data, + db_pool: Arc, page: i64, per_page: i64, ) -> Result> { @@ -152,8 +152,8 @@ pub struct LightRollingStockWithLiveriesModel { #[cfg(test)] pub mod tests { - use actix_web::web::Data; use rstest::*; + use std::sync::Arc; use super::LightRollingStockModel; use crate::fixtures::tests::db_pool; @@ -162,7 +162,7 @@ pub mod tests { use crate::modelsv2::Retrieve; #[rstest] - async fn get_light_rolling_stock(db_pool: Data) { + async fn get_light_rolling_stock(db_pool: Arc) { // GIVEN let rolling_stock = named_fast_rolling_stock( "fast_rolling_stock_get_light_rolling_stock", @@ -179,7 +179,7 @@ pub mod tests { } #[rstest] - async fn list_light_rolling_stock(db_pool: Data) { + async fn list_light_rolling_stock(db_pool: Arc) { // GIVEN let rolling_stock = named_fast_rolling_stock( "fast_rolling_stock_list_light_rolling_stock", diff --git a/editoast/src/modelsv2/projects.rs b/editoast/src/modelsv2/projects.rs index 20648455639..9d0ba070a1f 100644 --- a/editoast/src/modelsv2/projects.rs +++ b/editoast/src/modelsv2/projects.rs @@ -1,4 +1,3 @@ -use actix_web::web::Data; use async_trait::async_trait; use chrono::NaiveDateTime; use chrono::Utc; @@ -9,6 +8,7 @@ use diesel_async::RunQueryDsl; use editoast_derive::ModelV2; use serde::Deserialize; use serde::Serialize; +use std::sync::Arc; use utoipa::ToSchema; use crate::error::Result; @@ -103,7 +103,7 @@ impl Project { Ok(()) } - pub async fn studies_count(&self, db_pool: Data) -> Result { + pub async fn studies_count(&self, db_pool: Arc) -> Result { use crate::tables::study::dsl as study_dsl; let conn = &mut db_pool.get().await?; let studies_count = study_dsl::study @@ -186,8 +186,8 @@ impl List for Project { #[cfg(test)] pub mod test { - use actix_web::web::Data; use rstest::rstest; + use std::sync::Arc; use super::*; use crate::fixtures::tests::db_pool; @@ -202,7 +202,7 @@ pub mod test { #[rstest] async fn create_delete_project( #[future] project: TestFixture, - db_pool: Data, + db_pool: Arc, ) { let project = project.await; let conn = &mut db_pool.get().await.unwrap(); @@ -213,7 +213,7 @@ pub mod test { } #[rstest] - async fn get_project(#[future] project: TestFixture, db_pool: Data) { + async fn get_project(#[future] project: TestFixture, db_pool: Arc) { let fixture_project = &project.await.model; let conn = &mut db_pool.get().await.unwrap(); @@ -231,10 +231,7 @@ pub mod test { } #[rstest] - async fn sort_project( - #[future] project: TestFixture, - db_pool: Data, - ) { + async fn sort_project(#[future] project: TestFixture, db_pool: Arc) { let project = project.await; let project_2 = project .model @@ -259,7 +256,7 @@ pub mod test { #[rstest] async fn update_project( #[future] project: TestFixture, - db_pool: Data, + db_pool: Arc, ) { let project_fixture = project.await; let conn = &mut db_pool.get().await.unwrap(); diff --git a/editoast/src/modelsv2/rolling_stock_livery.rs b/editoast/src/modelsv2/rolling_stock_livery.rs index 888dec93e88..ea09b23968d 100644 --- a/editoast/src/modelsv2/rolling_stock_livery.rs +++ b/editoast/src/modelsv2/rolling_stock_livery.rs @@ -82,8 +82,8 @@ impl From for RollingStockLiveryMetadata { #[cfg(test)] pub mod tests { - use actix_web::web::Data; use rstest::*; + use std::sync::Arc; use super::RollingStockLiveryModel; use crate::fixtures::tests::db_pool; @@ -92,7 +92,7 @@ pub mod tests { use crate::modelsv2::Document; #[rstest] - async fn create_get_delete_rolling_stock_livery(db_pool: Data) { + async fn create_get_delete_rolling_stock_livery(db_pool: Arc) { use crate::modelsv2::prelude::*; let mut conn = db_pool.get().await.unwrap(); let rolling_stock_livery = rolling_stock_livery("", db_pool.clone()).await; diff --git a/editoast/src/modelsv2/rolling_stock_model.rs b/editoast/src/modelsv2/rolling_stock_model.rs index 075f479a640..72b965d0583 100644 --- a/editoast/src/modelsv2/rolling_stock_model.rs +++ b/editoast/src/modelsv2/rolling_stock_model.rs @@ -1,6 +1,5 @@ use std::collections::HashMap; -use actix_web::web::Data; use diesel::ExpressionMethods; use diesel::QueryDsl; use diesel::SelectableHelper; @@ -16,6 +15,7 @@ use editoast_schemas::rolling_stock::RollingStockMetadata; use editoast_schemas::rolling_stock::RollingStockSupportedSignalingSystems; use serde::Deserialize; use serde::Serialize; +use std::sync::Arc; use utoipa::ToSchema; use validator::Validate; use validator::ValidationError; @@ -78,7 +78,7 @@ pub struct RollingStockModel { impl RollingStockModel { pub async fn with_liveries( self, - db_pool: Data, + db_pool: Arc, ) -> Result { use crate::tables::rolling_stock_livery::dsl as livery_dsl; let mut conn = db_pool.get().await?; @@ -214,9 +214,9 @@ impl From for RollingStockModelChangeset { #[cfg(test)] pub mod tests { - use actix_web::web::Data; use rstest::*; use serde_json::to_value; + use std::sync::Arc; use super::RollingStockModel; use crate::error::InternalError; @@ -234,7 +234,7 @@ pub mod tests { } #[rstest] - async fn create_delete_rolling_stock(db_pool: Data) { + async fn create_delete_rolling_stock(db_pool: Arc) { use crate::modelsv2::Retrieve; let mut db_conn = db_pool.get().await.expect("Failed to get db connection"); let name = "fast_rolling_stock_create_delete_rolling_stock"; @@ -253,7 +253,7 @@ pub mod tests { } #[rstest] - async fn update_rolling_stock(db_pool: Data) { + async fn update_rolling_stock(db_pool: Arc) { use crate::modelsv2::Update; let mut db_conn = db_pool.get().await.expect("Failed to get db connection"); // GIVEN @@ -279,7 +279,7 @@ pub mod tests { } #[rstest] - async fn update_rolling_stock_failure_name_already_used(db_pool: Data) { + async fn update_rolling_stock_failure_name_already_used(db_pool: Arc) { use crate::modelsv2::*; let mut db_conn = db_pool.get().await.expect("Failed to get db connection"); // GIVEN diff --git a/editoast/src/modelsv2/study.rs b/editoast/src/modelsv2/study.rs index 937e3e3c6cd..b56aab897e7 100644 --- a/editoast/src/modelsv2/study.rs +++ b/editoast/src/modelsv2/study.rs @@ -1,4 +1,3 @@ -use actix_web::web::Data; use async_trait::async_trait; use chrono::NaiveDate; use chrono::NaiveDateTime; @@ -11,6 +10,7 @@ use diesel_async::RunQueryDsl; use editoast_derive::ModelV2; use serde::Deserialize; use serde::Serialize; +use std::sync::Arc; use utoipa::ToSchema; use crate::error::Result; @@ -54,7 +54,7 @@ impl Study { Ok(()) } - pub async fn scenarios_count(&self, db_pool: Data) -> Result { + pub async fn scenarios_count(&self, db_pool: Arc) -> Result { use crate::tables::scenario::dsl as scenario_dsl; let conn = &mut db_pool.get().await?; let scenarios_count = scenario_dsl::scenario @@ -117,6 +117,7 @@ impl List<(i64, Ordering)> for Study { #[cfg(test)] pub mod test { use rstest::rstest; + use std::sync::Arc; use super::*; use crate::fixtures::tests::db_pool; @@ -132,7 +133,7 @@ pub mod test { #[rstest] async fn create_delete_study( #[future] study_fixture_set: StudyFixtureSet, - db_pool: Data, + db_pool: Arc, ) { let StudyFixtureSet { study, .. } = study_fixture_set.await; @@ -147,7 +148,7 @@ pub mod test { #[rstest] async fn get_study( #[future] study_fixture_set: StudyFixtureSet, - db_pool: Data, + db_pool: Arc, ) { let StudyFixtureSet { study, project } = study_fixture_set.await; @@ -167,7 +168,7 @@ pub mod test { #[rstest] async fn sort_study( #[future] study_fixture_set: StudyFixtureSet, - db_pool: Data, + db_pool: Arc, ) { let StudyFixtureSet { study, project } = study_fixture_set.await; diff --git a/editoast/src/views/documents.rs b/editoast/src/views/documents.rs index 79548609a71..9a6107233b7 100644 --- a/editoast/src/views/documents.rs +++ b/editoast/src/views/documents.rs @@ -129,6 +129,7 @@ mod tests { use actix_web::test::TestRequest; use rstest::rstest; use serde::Deserialize; + use std::sync::Arc; use super::*; use crate::fixtures::tests::db_pool; @@ -139,7 +140,7 @@ mod tests { #[rstest] async fn get_document( #[future] document_example: TestFixture, - db_pool: Data, + db_pool: Arc, ) { let service = create_test_service().await; let doc = document_example.await; @@ -171,7 +172,7 @@ mod tests { } #[rstest] - async fn document_post(db_pool: Data) { + async fn document_post(db_pool: Arc) { let service = create_test_service().await; // Insert document diff --git a/editoast/src/views/electrical_profiles.rs b/editoast/src/views/electrical_profiles.rs index 5849fc4a6da..e8bfcca7a28 100644 --- a/editoast/src/views/electrical_profiles.rs +++ b/editoast/src/views/electrical_profiles.rs @@ -187,6 +187,7 @@ mod tests { use actix_web::test::read_body_json; use actix_web::test::TestRequest; use rstest::rstest; + use std::sync::Arc; use super::*; use crate::fixtures::tests::db_pool; @@ -306,7 +307,7 @@ mod tests { } #[rstest] - async fn test_post(db_pool: Data) { + async fn test_post(db_pool: Arc) { let app = create_test_service().await; let ep_set = ElectricalProfileSetData { levels: vec![ElectricalProfile { diff --git a/editoast/src/views/infra/mod.rs b/editoast/src/views/infra/mod.rs index 8563a471e3a..ac885d03c4a 100644 --- a/editoast/src/views/infra/mod.rs +++ b/editoast/src/views/infra/mod.rs @@ -192,6 +192,7 @@ async fn refresh( }; // Refresh each infras + let db_pool = db_pool.into_inner(); let mut infra_refreshed = vec![]; for mut infra in infras_list { @@ -225,6 +226,7 @@ async fn list( .validate(1000)? .warn_page_size(100) .unpack(); + let db_pool = db_pool.into_inner(); let infras = Infra::list(db_pool.clone(), page, per_page, NoParams).await?; let infra_state = call_core_infra_state(None, db_pool, core).await?; let infras_with_state: Vec = infras @@ -291,7 +293,7 @@ async fn get( let conn = &mut db_pool.get().await?; let infra = Infra::retrieve_or_fail(conn, infra_id, || InfraApiError::NotFound { infra_id }).await?; - let infra_state = call_core_infra_state(Some(infra_id), db_pool, core).await?; + let infra_state = call_core_infra_state(Some(infra_id), db_pool.into_inner(), core).await?; let state = infra_state .get(&infra_id.to_string()) .unwrap_or(&InfraStateResponse::default()) @@ -326,7 +328,7 @@ async fn clone( infra_id: infra_id.into_inner(), }) .await?; - let cloned_infra = infra.clone(db_pool.clone(), name).await?; + let cloned_infra = infra.clone(db_pool.into_inner(), name).await?; Ok(Json(cloned_infra.id)) } @@ -568,7 +570,7 @@ async fn load( /// Builds a Core cache_status request, runs it pub async fn call_core_infra_state( infra_id: Option, - db_pool: Data, + db_pool: Arc, core: Data, ) -> Result> { if let Some(infra_id) = infra_id { @@ -593,7 +595,9 @@ async fn cache_status( Either::Right(_) => Default::default(), }; let infra_id = payload.infra; - Ok(Json(call_core_infra_state(infra_id, db_pool, core).await?)) + Ok(Json( + call_core_infra_state(infra_id, db_pool.into_inner(), core).await?, + )) } #[cfg(test)] @@ -608,6 +612,7 @@ pub mod tests { use diesel_async::RunQueryDsl; use rstest::*; use serde_json::json; + use std::sync::Arc; use strum::IntoEnumIterator; use super::*; @@ -648,7 +653,7 @@ pub mod tests { } #[rstest] - async fn infra_clone_empty(db_pool: Data) { + async fn infra_clone_empty(db_pool: Arc) { let conn = &mut db_pool.get().await.unwrap(); let infra = empty_infra(db_pool.clone()).await; let app = create_test_service().await; @@ -672,7 +677,7 @@ pub mod tests { } #[rstest] // Slow test - async fn infra_clone(db_pool: Data) { + async fn infra_clone(db_pool: Arc) { let app = create_test_service().await; let small_infra = small_infra(db_pool.clone()).await; let small_infra_id = small_infra.id; @@ -777,7 +782,7 @@ pub mod tests { } #[rstest] - async fn default_infra_create(db_pool: Data) { + async fn default_infra_create(db_pool: Arc) { let app = create_test_service().await; let req = TestRequest::post() .uri("/infra") @@ -796,7 +801,7 @@ pub mod tests { } #[rstest] - async fn infra_get(#[future] empty_infra: TestFixture, db_pool: Data) { + async fn infra_get(#[future] empty_infra: TestFixture, db_pool: Arc) { let empty_infra = empty_infra.await; let mut core = MockingClient::new(); core.stub("/cache_status") diff --git a/editoast/src/views/infra/railjson.rs b/editoast/src/views/infra/railjson.rs index 98e57bb74b6..79c153eacd0 100644 --- a/editoast/src/views/infra/railjson.rs +++ b/editoast/src/views/infra/railjson.rs @@ -185,6 +185,7 @@ async fn post_railjson( } let railjson = railjson.into_inner(); + let db_pool = db_pool.into_inner(); let mut infra = Infra::changeset() .name(params.name.clone()) .last_railjson_version() @@ -212,6 +213,7 @@ mod tests { use actix_web::test::call_service; use actix_web::test::read_body_json; use rstest::*; + use std::sync::Arc; use super::*; use crate::fixtures::tests::db_pool; @@ -243,7 +245,7 @@ mod tests { #[rstest] #[serial_test::serial] - async fn test_post_railjson(db_pool: Data) { + async fn test_post_railjson(db_pool: Arc) { let app = create_test_service().await; let railjson = RailJson { diff --git a/editoast/src/views/light_rolling_stocks.rs b/editoast/src/views/light_rolling_stocks.rs index 596cc0b7a02..a3873e3952b 100644 --- a/editoast/src/views/light_rolling_stocks.rs +++ b/editoast/src/views/light_rolling_stocks.rs @@ -54,7 +54,7 @@ async fn list( page_settings: Query, ) -> Result>> { let (page, per_page) = page_settings.validate(1000)?.warn_page_size(100).unpack(); - let result = LightRollingStockModel::list(db_pool, page, per_page).await?; + let result = LightRollingStockModel::list(db_pool.into_inner(), page, per_page).await?; let results: Vec = result.results.into_iter().map(|l| l.into()).collect(); @@ -90,8 +90,10 @@ async fn get( } }) .await?; - let rollig_stock_with_liveries: LightRollingStockWithLiveries = - rolling_stock.with_liveries(db_pool).await?.into(); + let rollig_stock_with_liveries: LightRollingStockWithLiveries = rolling_stock + .with_liveries(db_pool.into_inner()) + .await? + .into(); Ok(Json(rollig_stock_with_liveries)) } @@ -117,8 +119,10 @@ async fn get_by_name( } }) .await?; - let rollig_stock_with_liveries: LightRollingStockWithLiveries = - rolling_stock.with_liveries(db_pool).await?.into(); + let rollig_stock_with_liveries: LightRollingStockWithLiveries = rolling_stock + .with_liveries(db_pool.into_inner()) + .await? + .into(); Ok(Json(rollig_stock_with_liveries)) } @@ -130,8 +134,8 @@ mod tests { use actix_web::test as actix_test; use actix_web::test::call_service; use actix_web::test::TestRequest; - use actix_web::web::Data; use rstest::*; + use std::sync::Arc; use super::LightRollingStockWithLiveries; use crate::assert_response_error_type_match; @@ -153,7 +157,7 @@ mod tests { } #[rstest] - async fn get_light_rolling_stock(db_pool: Data) { + async fn get_light_rolling_stock(db_pool: Arc) { // GIVEN let app = create_test_service().await; let rolling_stock = named_fast_rolling_stock( @@ -174,7 +178,7 @@ mod tests { } #[rstest] - async fn get_light_rolling_stock_by_name(db_pool: Data) { + async fn get_light_rolling_stock_by_name(db_pool: Arc) { // GIVEN let app = create_test_service().await; let rolling_stock = named_fast_rolling_stock( @@ -215,7 +219,7 @@ mod tests { } #[rstest] - async fn list_light_rolling_stock_increasing_ids(db_pool: Data) { + async fn list_light_rolling_stock_increasing_ids(db_pool: Arc) { // Generate some rolling stocks let vec_fixtures = (0..10) .map(|x| { diff --git a/editoast/src/views/pathfinding/electrical_profiles.rs b/editoast/src/views/pathfinding/electrical_profiles.rs index 75c62714d78..4a384b934d2 100644 --- a/editoast/src/views/pathfinding/electrical_profiles.rs +++ b/editoast/src/views/pathfinding/electrical_profiles.rs @@ -99,6 +99,7 @@ async fn electrical_profiles_on_path( request: Query, db_pool: Data, ) -> Result> { + let db_pool = db_pool.into_inner(); let pathfinding_id = params.pathfinding_id; let pathfinding = match Pathfinding::retrieve(db_pool.clone(), pathfinding_id).await? { Some(pf) => pf, @@ -143,6 +144,7 @@ mod tests { use actix_web::test::TestRequest; use editoast_common::range_map; use rstest::*; + use std::sync::Arc; use super::*; use crate::fixtures::tests::db_pool; @@ -158,7 +160,7 @@ mod tests { #[fixture] async fn electrical_profile_set( - db_pool: Data, + db_pool: Arc, ) -> TestFixture { let ep_data = ElectricalProfileSetData { levels: vec![ @@ -253,7 +255,7 @@ mod tests { #[rstest] #[serial_test::serial] async fn test_view_electrical_profiles_on_path( - db_pool: Data, + db_pool: Arc, #[future] empty_infra: TestFixture, #[future] electrical_profile_set: TestFixture, ) { diff --git a/editoast/src/views/pathfinding/electrifications.rs b/editoast/src/views/pathfinding/electrifications.rs index 2f89c20e9d6..305ae03ffee 100644 --- a/editoast/src/views/pathfinding/electrifications.rs +++ b/editoast/src/views/pathfinding/electrifications.rs @@ -141,6 +141,7 @@ pub mod tests { use editoast_common::range_map; use rstest::*; use serde_json::from_value; + use std::sync::Arc; use ApplicableDirections::*; use super::*; @@ -175,7 +176,7 @@ pub mod tests { #[fixture] async fn infra_with_electrifications( - db_pool: Data, + db_pool: Arc, #[future] empty_infra: TestFixture, ) -> TestFixture { let infra = empty_infra.await; @@ -218,7 +219,7 @@ pub mod tests { #[rstest] async fn test_map_electrification_modes( - db_pool: Data, + db_pool: Arc, #[future] infra_with_electrifications: TestFixture, simple_mode_map: TrackMap, ) { @@ -240,7 +241,7 @@ pub mod tests { #[rstest] async fn test_map_electrification_modes_with_warnings( - db_pool: Data, + db_pool: Arc, #[future] infra_with_electrifications: TestFixture, ) { let mut conn = db_pool.get().await.unwrap(); @@ -300,7 +301,7 @@ pub mod tests { #[rstest] async fn test_view_electrifications_on_path( - db_pool: Data, + db_pool: Arc, #[future] infra_with_electrifications: TestFixture, ) { let infra_with_electrifications = infra_with_electrifications.await; diff --git a/editoast/src/views/pathfinding/mod.rs b/editoast/src/views/pathfinding/mod.rs index a2af47d1b6a..0a8462d96c4 100644 --- a/editoast/src/views/pathfinding/mod.rs +++ b/editoast/src/views/pathfinding/mod.rs @@ -558,7 +558,7 @@ async fn get_pf( db_pool: Data, ) -> Result> { let pathfinding_id = params.pathfinding_id; - match Pathfinding::retrieve(db_pool, pathfinding_id).await? { + match Pathfinding::retrieve(db_pool.into_inner(), pathfinding_id).await? { Some(pf) => Ok(Json(pf.into())), None => Err(PathfindingError::NotFound { pathfinding_id }.into()), } @@ -578,7 +578,7 @@ async fn del_pf( db_pool: Data, ) -> Result { let pathfinding_id = params.pathfinding_id; - if Pathfinding::delete(db_pool, pathfinding_id).await? { + if Pathfinding::delete(db_pool.into_inner(), pathfinding_id).await? { Ok(HttpResponse::NoContent()) } else { Err(PathfindingError::NotFound { pathfinding_id }.into()) diff --git a/editoast/src/views/projects.rs b/editoast/src/views/projects.rs index b62f0357f19..ec4ee51a075 100644 --- a/editoast/src/views/projects.rs +++ b/editoast/src/views/projects.rs @@ -187,6 +187,7 @@ async fn list( .warn_page_size(100) .unpack(); let ordering = params.ordering.clone(); + let db_pool = db_pool.into_inner(); let projects = Project::list(db_pool.clone(), page, per_page, ordering).await?; let mut results = Vec::new(); for project in projects.results.into_iter() { @@ -229,7 +230,7 @@ async fn get( let project = Project::retrieve_or_fail(conn, project_id, || ProjectError::NotFound { project_id }) .await?; - let studies_count = project.studies_count(db_pool).await?; + let studies_count = project.studies_count(db_pool.into_inner()).await?; Ok(Json(ProjectWithStudies::new_from_project( project, studies_count, @@ -314,7 +315,7 @@ async fn patch( let project_changeset: Changeset = data.into(); let conn = &mut db_pool.get().await?; let project = Project::update_and_prune_document(conn, project_changeset, project_id).await?; - let studies_count = project.studies_count(db_pool).await?; + let studies_count = project.studies_count(db_pool.into_inner()).await?; Ok(Json(ProjectWithStudies::new_from_project( project, studies_count, @@ -331,6 +332,7 @@ pub mod test { use actix_web::test::TestRequest; use rstest::rstest; use serde_json::json; + use std::sync::Arc; use super::*; use crate::fixtures::tests::db_pool; @@ -346,7 +348,7 @@ pub mod test { } #[rstest] - async fn project_create_delete(db_pool: Data) { + async fn project_create_delete(db_pool: Arc) { let app = create_test_service().await; let req = TestRequest::post() .uri("/projects") diff --git a/editoast/src/views/rolling_stocks/mod.rs b/editoast/src/views/rolling_stocks/mod.rs index dbe263d3016..be2235f580f 100644 --- a/editoast/src/views/rolling_stocks/mod.rs +++ b/editoast/src/views/rolling_stocks/mod.rs @@ -4,6 +4,7 @@ pub mod rolling_stock_form; use std::io::BufReader; use std::io::Cursor; use std::io::Read; +use std::sync::Arc; use actix_multipart::form::tempfile::TempFile; use actix_multipart::form::text::Text; @@ -168,7 +169,7 @@ async fn get( let rolling_stock = retrieve_existing_rolling_stock(&db_pool, RollingStockKey::Id(rolling_stock_id)).await?; - let rolling_stock_with_liveries = rolling_stock.with_liveries(db_pool).await?; + let rolling_stock_with_liveries = rolling_stock.with_liveries(db_pool.into_inner()).await?; Ok(Json(rolling_stock_with_liveries)) } @@ -189,7 +190,7 @@ async fn get_by_name( let rolling_stock = retrieve_existing_rolling_stock(&db_pool, RollingStockKey::Name(rolling_stock_name)) .await?; - let rolling_stock_with_liveries = rolling_stock.with_liveries(db_pool).await?; + let rolling_stock_with_liveries = rolling_stock.with_liveries(db_pool.into_inner()).await?; Ok(Json(rolling_stock_with_liveries)) } @@ -302,7 +303,11 @@ async fn update( .map_err(|err| map_diesel_error(err, name))?; } - Ok(Json(new_rolling_stock.with_liveries(db_pool).await?)) + Ok(Json( + new_rolling_stock + .with_liveries(db_pool.into_inner()) + .await?, + )) } #[derive(Deserialize, IntoParams, ToSchema)] @@ -498,7 +503,7 @@ async fn create_livery( /// Retrieve a rolling stock by id or by name pub async fn retrieve_existing_rolling_stock( - db_pool: &Data, + db_pool: &Arc, rolling_stock_key: RollingStockKey, ) -> Result { let mut db_conn = db_pool.get().await?; @@ -619,9 +624,9 @@ pub mod tests { use actix_web::test::call_service; use actix_web::test::read_body_json; use actix_web::test::TestRequest; - use actix_web::web::Data; use rstest::rstest; use serde_json::json; + use std::sync::Arc; use super::retrieve_existing_rolling_stock; use super::RollingStockError; @@ -643,7 +648,7 @@ pub mod tests { use crate::views::tests::create_test_service; #[rstest] - async fn get_returns_corresponding_rolling_stock(db_pool: Data) { + async fn get_returns_corresponding_rolling_stock(db_pool: Arc) { // GIVEN let name = "fast_rolling_stock_get_returns_corresponding_rolling_stock"; let app = create_test_service().await; @@ -660,7 +665,7 @@ pub mod tests { } #[rstest] - async fn get_returns_corresponding_rolling_stock_by_name(db_pool: Data) { + async fn get_returns_corresponding_rolling_stock_by_name(db_pool: Arc) { // GIVEN let name = "fast_rolling_stock_get_returns_corresponding_rolling_stock_by_name"; let app = create_test_service().await; @@ -738,7 +743,7 @@ pub mod tests { assert_eq!(get_response.status(), StatusCode::NOT_FOUND); } - async fn check_create_gave_400(db_pool: Data, response: ServiceResponse) { + async fn check_create_gave_400(db_pool: Arc, response: ServiceResponse) { let mut db_conn = db_pool.get().await.expect("Failed to get db connection"); if response.status() == StatusCode::OK { let rolling_stock: RollingStockModel = read_body_json(response).await; @@ -755,7 +760,7 @@ pub mod tests { } #[rstest] - async fn create_rolling_stock_with_base_power_class_empty(db_pool: Data) { + async fn create_rolling_stock_with_base_power_class_empty(db_pool: Arc) { // GIVEN let app = create_test_service().await; let mut rolling_stock_form = get_fast_rolling_stock_form( @@ -778,7 +783,7 @@ pub mod tests { } #[rstest] - async fn create_rolling_stock_with_duplicate_name(db_pool: Data) { + async fn create_rolling_stock_with_duplicate_name(db_pool: Arc) { // GIVEN let name = "fast_rolling_stock_create_rolling_stock_with_duplicate_name"; let fast_rolling_stock = named_fast_rolling_stock(name, db_pool.clone()).await; @@ -803,7 +808,7 @@ pub mod tests { } #[rstest] - async fn update_and_delete_locked_rolling_stock_fails(db_pool: Data) { + async fn update_and_delete_locked_rolling_stock_fails(db_pool: Arc) { let mut db_conn = db_pool.get().await.expect("Failed to get db connection"); // GIVEN let app = create_test_service().await; @@ -913,7 +918,7 @@ pub mod tests { } #[rstest] - async fn update_unlocked_rolling_stock(db_pool: Data) { + async fn update_unlocked_rolling_stock(db_pool: Arc) { // GIVEN let app = create_test_service().await; let fast_rolling_stock = named_fast_rolling_stock( @@ -948,7 +953,7 @@ pub mod tests { } #[rstest] - async fn update_rolling_stock_failure_name_already_used(db_pool: Data) { + async fn update_rolling_stock_failure_name_already_used(db_pool: Arc) { // GIVEN let other_rs_name = "other_rolling_stock_update_rolling_stock_failure_name_already_used"; let app = create_test_service().await; @@ -984,7 +989,7 @@ pub mod tests { } #[rstest] - async fn update_locked_successfully(db_pool: Data) { + async fn update_locked_successfully(db_pool: Arc) { // GIVEN let app = create_test_service().await; let rolling_stock_form = @@ -1095,7 +1100,7 @@ pub mod tests { } #[rstest] - async fn get_power_restrictions_list(db_pool: Data) { + async fn get_power_restrictions_list(db_pool: Arc) { // GIVEN let app = create_test_service().await; let rolling_stock = diff --git a/editoast/src/views/scenario.rs b/editoast/src/views/scenario.rs index b84651dfc04..20b5cb0c6da 100644 --- a/editoast/src/views/scenario.rs +++ b/editoast/src/views/scenario.rs @@ -14,6 +14,7 @@ use diesel_async::AsyncConnection; use editoast_derive::EditoastError; use serde::Deserialize; use serde::Serialize; +use std::sync::Arc; use thiserror::Error; use utoipa::IntoParams; use utoipa::ToSchema; @@ -138,7 +139,7 @@ impl ScenarioResponse { /// Check if project and study exist given a study ID and a project ID pub async fn check_project_study( - db_pool: Data, + db_pool: Arc, project_id: i64, study_id: i64, ) -> Result<(Project, Study)> { @@ -185,6 +186,7 @@ async fn create( // Check if the project and the study exist let (mut project, mut study) = check_project_study_conn(&mut conn, project_id, study_id).await?; + let db_pool = db_pool.into_inner(); let (project, study, scenarios_with_details) = conn .transaction::<_, InternalError, _>(|conn| { async { @@ -198,7 +200,7 @@ async fn create( // Create Scenario let scenario: Scenario = data.into_inner().into_scenario(study_id, timetable_id); - let scenario = scenario.create(db_pool.clone()).await?; + let scenario = scenario.create(db_pool).await?; // Update study last_modification field study.update_last_modified(conn).await?; @@ -239,6 +241,7 @@ async fn delete( ) -> Result { let (project_id, study_id, scenario_id) = path.into_inner(); + let db_pool = db_pool.into_inner(); // Check if the project and the study exist let (mut project, mut study) = check_project_study(db_pool.clone(), project_id, study_id) .await @@ -341,6 +344,7 @@ async fn get( path: Path<(i64, i64, i64)>, ) -> Result> { let (project_id, study_id, scenario_id) = path.into_inner(); + let db_pool = db_pool.into_inner(); let (project, study) = check_project_study(db_pool.clone(), project_id, study_id).await?; // Return the scenarios @@ -383,6 +387,7 @@ async fn list( .warn_page_size(100) .unpack(); let (project_id, study_id) = path.into_inner(); + let db_pool = db_pool.into_inner(); let _ = check_project_study(db_pool.clone(), project_id, study_id).await?; let ordering = params.ordering.clone(); let scenarios = @@ -400,6 +405,7 @@ mod test { use actix_web::test::TestRequest; use rstest::rstest; use serde_json::json; + use std::sync::Arc; use super::*; use crate::fixtures::tests::db_pool; @@ -436,7 +442,7 @@ mod test { #[rstest] async fn scenario_create( - db_pool: Data, + db_pool: Arc, #[future] study_fixture_set: StudyFixtureSet, #[future] empty_infra: TestFixture, ) { diff --git a/editoast/src/views/single_simulation.rs b/editoast/src/views/single_simulation.rs index f0069b3ebf9..96245ef08fe 100644 --- a/editoast/src/views/single_simulation.rs +++ b/editoast/src/views/single_simulation.rs @@ -165,6 +165,7 @@ async fn standalone_simulation( }) .await?; + let db_pool = db_pool.into_inner(); let path_id = request.path_id; let pathfinding = Pathfinding::retrieve(db_pool.clone(), path_id).await?; let pathfinding = match pathfinding { @@ -205,6 +206,7 @@ mod tests { use reqwest::Method; use rstest::rstest; use serde_json::json; + use std::sync::Arc; use super::*; use crate::assert_response_error_type_match; @@ -241,7 +243,7 @@ mod tests { #[case::invalid_path_id(Some(SingleSimulationError::PathNotFound { path_id: -666 }), "case_3")] #[case::invalid_ep_set_id(Some(SingleSimulationError::ElectricalProfileSetNotFound { electrical_profile_set_id: -666 }), "case_4")] async fn test_single_simulation( - db_pool: Data, + db_pool: Arc, #[case] expected_error: Option, #[case] case_id: &str, ) { @@ -316,7 +318,7 @@ mod tests { } #[rstest] - async fn test_single_simulation_bare_minimum_payload(db_pool: Data) { + async fn test_single_simulation_bare_minimum_payload(db_pool: Arc) { // GIVEN let (core_client, mock_response) = create_core_client(); let app = create_test_service_with_core_client(core_client).await; diff --git a/editoast/src/views/stdcm/mod.rs b/editoast/src/views/stdcm/mod.rs index 7f631cf1a20..aab73fc1c1c 100644 --- a/editoast/src/views/stdcm/mod.rs +++ b/editoast/src/views/stdcm/mod.rs @@ -1,3 +1,5 @@ +use std::sync::Arc; + use actix_web::post; use actix_web::web::Data; use actix_web::web::Json; @@ -135,12 +137,12 @@ async fn create( core: Data, data: Json, ) -> Result { - let stdcm_response = compute_stdcm(db_pool, core, data).await?; + let stdcm_response = compute_stdcm(db_pool.into_inner(), core, data).await?; Ok(HttpResponse::Created().json(stdcm_response)) } async fn compute_stdcm( - db_pool: Data, + db_pool: Arc, core: Data, data: Json, ) -> Result { @@ -152,7 +154,7 @@ async fn compute_stdcm( } async fn call_core_stdcm( - db_pool: Data, + db_pool: Arc, core: &Data, data: &Json, ) -> Result { @@ -194,7 +196,7 @@ async fn call_core_stdcm( /// create steps from track_map and waypoints async fn parse_stdcm_steps( - db_pool: Data, + db_pool: Arc, data: &Json, infra: &Infra, ) -> Result> { @@ -217,7 +219,7 @@ async fn parse_stdcm_steps( /// Create route occupancies, adjusted by simulation departure time. /// uses base_simulation by default, or eco_simulation if given async fn make_spacing_requirements( - db_pool: Data, + db_pool: Arc, timetable_id: i64, ) -> Result> { let (schedules, simulations) = @@ -247,7 +249,7 @@ async fn make_spacing_requirements( /// Creates a Pathfinding using the same function used with core /pathfinding response async fn create_path_from_core_response( - db_pool: Data, + db_pool: Arc, core_output: &STDCMCoreResponse, data: &Json, ) -> Result { @@ -273,7 +275,7 @@ async fn create_path_from_core_response( /// processes the stdcm simulation and create a simulation report async fn create_simulation_from_core_response( - db_pool: Data, + db_pool: Arc, core: &Data, data: &Json, core_output: &STDCMCoreResponse, @@ -297,7 +299,7 @@ async fn create_simulation_from_core_response( &projection, &path.payload, simulation_output[0].clone(), - db_pool.clone(), + db_pool, core, ) .await diff --git a/editoast/src/views/study.rs b/editoast/src/views/study.rs index 1d4b465543d..c7e1de1c218 100644 --- a/editoast/src/views/study.rs +++ b/editoast/src/views/study.rs @@ -260,6 +260,7 @@ async fn list( .unpack(); let project = project.into_inner(); let ordering = params.ordering.clone(); + let db_pool = db_pool.into_inner(); let studies = Study::list(db_pool.clone(), page, per_page, (project, ordering)).await?; let mut results = Vec::new(); @@ -308,7 +309,7 @@ async fn get( return Err(StudyError::NotFound { study_id }.into()); } - let scenarios_count = study.scenarios_count(db_pool.clone()).await?; + let scenarios_count = study.scenarios_count(db_pool.into_inner()).await?; let study_scenarios = StudyWithScenarios::new(study, scenarios_count); let study_response = StudyResponse::new(study_scenarios, project); Ok(Json(study_response)) @@ -387,7 +388,7 @@ async fn patch( .into_study_changeset()? .update_or_fail(conn, study_id, || StudyError::NotFound { study_id }) .await?; - let scenarios_count = study.scenarios_count(db_pool.clone()).await?; + let scenarios_count = study.scenarios_count(db_pool.into_inner()).await?; let study_scenarios = StudyWithScenarios::new(study, scenarios_count); // Update project last_modification field @@ -411,6 +412,7 @@ pub mod test { use actix_web::test::TestRequest; use rstest::rstest; use serde_json::json; + use std::sync::Arc; use super::*; use crate::fixtures::tests::db_pool; @@ -450,10 +452,7 @@ pub mod test { } #[rstest] - async fn study_create( - #[future] project: TestFixture, - db_pool: Data, - ) { + async fn study_create(#[future] project: TestFixture, db_pool: Arc) { let app = create_test_service().await; let project = project.await; let req = TestRequest::post() @@ -502,7 +501,7 @@ pub mod test { #[rstest] async fn study_get( #[future] study_fixture_set: StudyFixtureSet, - db_pool: Data, + db_pool: Arc, ) { let app = create_test_service().await; let study_fixture_set = study_fixture_set.await; diff --git a/editoast/src/views/timetable.rs b/editoast/src/views/timetable.rs index b1bd2f98885..98c1d9ec318 100644 --- a/editoast/src/views/timetable.rs +++ b/editoast/src/views/timetable.rs @@ -1,4 +1,5 @@ use std::collections::HashMap; +use std::sync::Arc; use actix_web::get; use actix_web::web::Data; @@ -70,6 +71,7 @@ async fn get( let timetable_id = timetable_id.into_inner(); // Return the timetable + let db_pool = db_pool.into_inner(); let timetable = match Timetable::retrieve(db_pool.clone(), timetable_id).await? { Some(timetable) => timetable, None => return Err(TimetableError::NotFound { timetable_id }.into()), @@ -90,7 +92,7 @@ struct Conflict { pub async fn get_simulated_schedules_from_timetable( timetable_id: i64, - db_pool: Data, + db_pool: Arc, ) -> Result<(Vec, Vec)> { let mut conn = db_pool.get().await?; use diesel::BelongingToDsl; @@ -146,7 +148,7 @@ async fn get_conflicts( let timetable_id = timetable_id.into_inner(); let (schedules, simulations) = - get_simulated_schedules_from_timetable(timetable_id, db_pool).await?; + get_simulated_schedules_from_timetable(timetable_id, db_pool.into_inner()).await?; let mut id_to_name = HashMap::new(); let mut trains_requirements = Vec::new(); diff --git a/editoast/src/views/timetable/import.rs b/editoast/src/views/timetable/import.rs index 5b0592524ee..34d09b3326f 100644 --- a/editoast/src/views/timetable/import.rs +++ b/editoast/src/views/timetable/import.rs @@ -1,5 +1,6 @@ use std::cmp::Ordering; use std::collections::HashMap; +use std::sync::Arc; use actix_web::post; use actix_web::web::Data; @@ -206,6 +207,7 @@ pub async fn post_timetable( .await?; // Check infra is loaded + let db_pool = db_pool.into_inner(); let mut infra_state = call_core_infra_state(Some(infra_id), db_pool.clone(), core_client.clone()).await?; let infra_status = infra_state @@ -249,7 +251,7 @@ macro_rules! time_execution { async fn import_item( infra_id: i64, infra_version: &str, - db_pool: Data, + db_pool: Arc, import_item: TimetableImportItem, timetable_id: i64, core_client: &CoreClient, diff --git a/editoast/src/views/train_schedule/mod.rs b/editoast/src/views/train_schedule/mod.rs index 8cccdbce6a9..1a1aaf2d7a5 100644 --- a/editoast/src/views/train_schedule/mod.rs +++ b/editoast/src/views/train_schedule/mod.rs @@ -3,6 +3,7 @@ pub mod simulation_report; use std::collections::HashMap; use std::collections::HashSet; +use std::sync::Arc; use actix_web::delete; use actix_web::get; @@ -142,10 +143,11 @@ async fn get( let train_schedule_id = train_schedule_id.into_inner(); // Return the timetable - let train_schedule = match TrainSchedule::retrieve(db_pool.clone(), train_schedule_id).await? { - Some(train_schedule) => train_schedule, - None => return Err(TrainScheduleError::NotFound { train_schedule_id }.into()), - }; + let train_schedule = + match TrainSchedule::retrieve(db_pool.into_inner(), train_schedule_id).await? { + Some(train_schedule) => train_schedule, + None => return Err(TrainScheduleError::NotFound { train_schedule_id }.into()), + }; Ok(Json(train_schedule)) } @@ -163,7 +165,7 @@ async fn delete( train_schedule_id: Path, ) -> Result { let train_schedule_id = train_schedule_id.into_inner(); - if !TrainSchedule::delete(db_pool.clone(), train_schedule_id).await? { + if !TrainSchedule::delete(db_pool.into_inner(), train_schedule_id).await? { return Err(TrainScheduleError::NotFound { train_schedule_id }.into()); } @@ -261,6 +263,7 @@ async fn patch_multiple( } let mut conn = db_pool.get().await?; + let db_pool = db_pool.into_inner(); conn.transaction::<_, InternalError, _>(|conn| { async { let mut train_schedules = Vec::new(); @@ -373,6 +376,7 @@ async fn get_result( core: Data, ) -> Result> { let train_schedule_id = id.into_inner(); + let db_pool = db_pool.into_inner(); let train_schedule = match TrainSchedule::retrieve(db_pool.clone(), train_schedule_id).await? { Some(train_schedule) => train_schedule, None => return Err(TrainScheduleError::NotFound { train_schedule_id }.into()), @@ -475,6 +479,7 @@ async fn get_results( return Err(TrainScheduleError::BatchShouldHaveSameTimetable.into()); } + let db_pool = db_pool.into_inner(); let timetable = Timetable::retrieve(db_pool.clone(), timetable_id) .await? .ok_or(TrainScheduleError::TimetableNotFound { timetable_id })?; @@ -612,6 +617,7 @@ async fn standalone_simulation( return Err(TrainScheduleError::NoTrainSchedules.into()); } + let db_pool = db_pool.into_inner(); let timetable = Timetable::retrieve(db_pool.clone(), id_timetable) .await? .ok_or(TrainScheduleError::TimetableNotFound { @@ -670,7 +676,7 @@ async fn standalone_simulation( async fn create_backend_request_payload( train_schedules: &[TrainSchedule], scenario: &Scenario, - db_pool: Data, + db_pool: Arc, ) -> Result { let mut db_conn = db_pool.get().await?; diff --git a/editoast/src/views/train_schedule/simulation_report.rs b/editoast/src/views/train_schedule/simulation_report.rs index 51bef73fe25..d0f74e65270 100644 --- a/editoast/src/views/train_schedule/simulation_report.rs +++ b/editoast/src/views/train_schedule/simulation_report.rs @@ -1,4 +1,5 @@ -use actix_web::web::Data; +use std::sync::Arc; + use diesel::ExpressionMethods; use diesel::QueryDsl; use diesel_async::RunQueryDsl; @@ -91,7 +92,7 @@ pub async fn create_simulation_report( projection: &Projection, projection_path_payload: &PathfindingPayload, simulation_output_cs: SimulationOutputChangeset, - db_pool: Data, + db_pool: Arc, core: &CoreClient, ) -> error::Result { let train_path = Pathfinding::retrieve(db_pool.clone(), train_schedule.path_id) @@ -99,7 +100,7 @@ pub async fn create_simulation_report( .expect("Train Schedule should have a path"); let train_path_payload = train_path.payload; use crate::modelsv2::Retrieve; - let mut db_conn = db_pool.get().await?; + let mut db_conn = db_pool.clone().get().await?; let rolling_stock = RollingStockModel::retrieve(&mut db_conn, train_schedule.rolling_stock_id) .await? .expect("Train Schedule should have a rolling stock"); @@ -162,7 +163,7 @@ pub async fn create_simulation_report( pub async fn fetch_simulation_output( train_schedule: &TrainSchedule, - db_pool: Data, + db_pool: Arc, ) -> error::Result { use crate::tables::simulation_output::dsl::*; let ts_id = train_schedule.id.unwrap(); @@ -191,7 +192,7 @@ async fn project_simulation_results( departure_time: f64, train_length: f64, core: &CoreClient, - db_pool: Data, + db_pool: Arc, ) -> error::Result { let arrival_time = simulation_result .head_positions @@ -243,7 +244,7 @@ async fn add_stops_additional_information( stops: Vec, infra_id: i64, path_waypoints: Vec, - db_pool: Data, + db_pool: Arc, ) -> error::Result> { let mut conn = db_pool.get().await?; let track_sections_map = make_track_map( diff --git a/editoast/src/views/v2/scenario.rs b/editoast/src/views/v2/scenario.rs index 1f6354877f6..7297d96a18e 100644 --- a/editoast/src/views/v2/scenario.rs +++ b/editoast/src/views/v2/scenario.rs @@ -229,6 +229,7 @@ async fn delete( } = path.into_inner(); let mut tx = db_pool.get().await?; + let db_pool = db_pool.into_inner(); tx.transaction::<_, InternalError, _>(|conn| { async { // Check if the project and the study exist @@ -367,6 +368,7 @@ async fn get( scenario_id, } = path.into_inner(); + let db_pool = db_pool.into_inner(); let (project, study) = check_project_study(db_pool.clone(), project_id, study_id).await?; let conn = &mut db_pool.get().await?; // Return the scenarios @@ -412,10 +414,11 @@ async fn list( .unpack(); let (project_id, study_id) = path.into_inner(); + let db_pool = db_pool.into_inner(); let _ = check_project_study(db_pool.clone(), project_id, study_id).await?; let ordering = params.ordering.clone(); let scenarios = - ScenarioWithDetails::list(db_pool.clone(), page, per_page, (study_id, ordering)).await?; + ScenarioWithDetails::list(db_pool, page, per_page, (study_id, ordering)).await?; Ok(Json(scenarios)) } @@ -427,6 +430,7 @@ mod tests { use actix_web::test::TestRequest; use rstest::rstest; use serde_json::json; + use std::sync::Arc; use super::*; use crate::fixtures::tests::db_pool; @@ -511,7 +515,7 @@ mod tests { async fn post_scenario( #[future] scenario_v2_fixture_set: ScenarioV2FixtureSet, #[future] timetable_v2: TestFixture, - db_pool: Data, + db_pool: Arc, ) { let service = create_test_service().await; let fixtures = scenario_v2_fixture_set.await; diff --git a/editoast/src/views/v2/timetable.rs b/editoast/src/views/v2/timetable.rs index 7a2aace4094..a3fa01879c2 100644 --- a/editoast/src/views/v2/timetable.rs +++ b/editoast/src/views/v2/timetable.rs @@ -384,6 +384,7 @@ mod tests { use actix_web::test::TestRequest; use rstest::rstest; use serde_json::json; + use std::sync::Arc; use super::*; use crate::fixtures::tests::db_pool; @@ -395,7 +396,7 @@ mod tests { #[rstest] async fn get_timetable( #[future] timetable_v2: TestFixture, - db_pool: Data, + db_pool: Arc, ) { let service = create_test_service().await; let timetable = timetable_v2.await; @@ -421,7 +422,7 @@ mod tests { } #[rstest] - async fn timetable_post(db_pool: Data) { + async fn timetable_post(db_pool: Arc) { let service = create_test_service().await; // Insert timetable diff --git a/editoast/src/views/v2/train_schedule.rs b/editoast/src/views/v2/train_schedule.rs index 2a6a8960078..d88a92199d1 100644 --- a/editoast/src/views/v2/train_schedule.rs +++ b/editoast/src/views/v2/train_schedule.rs @@ -666,6 +666,7 @@ mod tests { use actix_web::test::TestRequest; use rstest::rstest; use serde_json::json; + use std::sync::Arc; use super::*; use crate::fixtures::tests::db_pool; @@ -685,7 +686,7 @@ mod tests { #[rstest] async fn get_trainschedule( #[future] train_schedule_v2: TrainScheduleV2FixtureSet, - db_pool: Data, + db_pool: Arc, ) { let service = create_test_service().await; let fixture = train_schedule_v2.await; @@ -713,7 +714,7 @@ mod tests { #[rstest] async fn get_batch_trainschedule( #[future] timetable_v2: TestFixture, - db_pool: Data, + db_pool: Arc, ) { let service = create_test_service().await; let timetable = timetable_v2.await; @@ -747,7 +748,7 @@ mod tests { #[rstest] async fn train_schedule_post( #[future] timetable_v2: TestFixture, - db_pool: Data, + db_pool: Arc, ) { let service = create_test_service().await; @@ -823,7 +824,7 @@ mod tests { async fn train_schedule_simulation( #[future] timetable_v2: TestFixture, #[future] small_infra: TestFixture, - db_pool: Data, + db_pool: Arc, ) { let timetable = timetable_v2.await; let infra = small_infra.await; @@ -869,7 +870,7 @@ mod tests { async fn train_schedule_simulation_summary( #[future] timetable_v2: TestFixture, #[future] small_infra: TestFixture, - db_pool: Data, + db_pool: Arc, ) { let timetable = timetable_v2.await; let infra = small_infra.await; diff --git a/editoast/src/views/work_schedules.rs b/editoast/src/views/work_schedules.rs index 72ab4b21afc..ae374457b2f 100644 --- a/editoast/src/views/work_schedules.rs +++ b/editoast/src/views/work_schedules.rs @@ -173,6 +173,7 @@ pub mod test { use actix_web::test::{call_service, read_body_json, TestRequest}; use rstest::rstest; use serde_json::json; + use std::sync::Arc; use super::*; use crate::assert_response_error_type_match; @@ -181,7 +182,7 @@ pub mod test { use crate::views::tests::create_test_service; async fn create_work_schedule_group_fixture( - db_pool: Data, + db_pool: Arc, work_schedule_response: WorkScheduleCreateResponse, ) -> TestFixture { let mut conn = db_pool.get().await.unwrap(); @@ -194,7 +195,7 @@ pub mod test { } #[rstest] - async fn work_schedule_create(db_pool: Data) { + async fn work_schedule_create(db_pool: Arc) { // GIVEN let app = create_test_service().await; let req = TestRequest::post() @@ -247,7 +248,7 @@ pub mod test { } #[rstest] - async fn work_schedule_create_fail_name_already_used(db_pool: Data) { + async fn work_schedule_create_fail_name_already_used(db_pool: Arc) { // GIVEN let app = create_test_service().await; let payload = json!({