-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathstdcm_search_env_commands.rs
455 lines (393 loc) · 14.5 KB
/
stdcm_search_env_commands.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
use crate::models::electrical_profiles::ElectricalProfileSet;
use crate::models::stdcm_search_environment::StdcmSearchEnvironment;
use crate::models::timetable::Timetable;
use crate::models::work_schedules::WorkScheduleGroup;
use crate::models::Create;
use crate::models::Infra;
use crate::models::Scenario;
use crate::CliError;
use crate::Exists;
use crate::Model;
use crate::Retrieve;
use chrono::DateTime;
use chrono::Duration;
use chrono::Utc;
use clap::Args;
use clap::Subcommand;
use editoast_models::DbConnection;
use editoast_models::DbConnectionPoolV2;
use std::error::Error;
#[derive(Subcommand, Debug)]
pub enum StdcmSearchEnvCommands {
SetFromScenario(SetSTDCMSearchEnvFromScenarioArgs),
SetFromScratch(SetSTDCMSearchEnvFromScratchArgs),
Show,
}
pub async fn handle_stdcm_search_env_command(
command: StdcmSearchEnvCommands,
db_pool: DbConnectionPoolV2,
) -> Result<(), Box<dyn Error + Send + Sync>> {
let conn = &mut db_pool.get().await?;
match command {
StdcmSearchEnvCommands::SetFromScenario(args) => {
set_stdcm_search_env_from_scenario(args, conn).await
}
StdcmSearchEnvCommands::SetFromScratch(args) => {
set_stdcm_search_env_from_scratch(args, conn).await
}
StdcmSearchEnvCommands::Show => show_stdcm_search_env(conn).await,
}
}
async fn check_exists<T: Exists<i64>>(
conn: &mut DbConnection,
object_id: i64,
readable_name: &str,
) -> Result<(), Box<dyn Error + Send + Sync>> {
if !T::exists(conn, object_id).await? {
let err_msg = format!("❌ {0} not found, id: {1}", readable_name, object_id);
return Err(Box::new(CliError::new(1, err_msg)));
}
Ok(())
}
#[derive(Args, Debug)]
#[command(
about,
long_about = "Set the current STDCM search env by copying most data from a scenario"
)]
pub struct SetSTDCMSearchEnvFromScenarioArgs {
pub scenario_id: i64,
#[arg(long)]
pub work_schedule_group_id: Option<i64>,
/// If omitted, set to the earliest train start time in the timetable
#[arg(long)]
pub search_window_begin: Option<DateTime<Utc>>,
/// If omitted, set to the latest train start time in the timetable plus one day
#[arg(long)]
pub search_window_end: Option<DateTime<Utc>>,
}
async fn set_stdcm_search_env_from_scenario(
args: SetSTDCMSearchEnvFromScenarioArgs,
conn: &mut DbConnection,
) -> Result<(), Box<dyn Error + Send + Sync>> {
if let Some(work_schedule_group_id) = args.work_schedule_group_id {
check_exists::<WorkScheduleGroup>(conn, work_schedule_group_id, "Work Schedule Group")
.await?;
}
let scenario_option = Scenario::retrieve(conn, args.scenario_id).await?;
let scenario = scenario_option.ok_or_else(|| {
let error = CliError::new(
1,
format!("❌ Scenario not found, id: {0}", args.scenario_id),
);
Box::new(error)
})?;
let (begin, end) = resolve_search_window(
scenario.timetable_id,
args.search_window_begin,
args.search_window_end,
conn,
)
.await?;
StdcmSearchEnvironment::changeset()
.infra_id(scenario.infra_id)
.electrical_profile_set_id(scenario.electrical_profile_set_id)
.work_schedule_group_id(args.work_schedule_group_id)
.timetable_id(scenario.timetable_id)
.search_window_begin(begin)
.search_window_end(end)
.enabled_from(Utc::now())
.enabled_until(Utc::now() + Duration::days(1000))
.create(conn)
.await?;
println!("✅ STDCM search environment set up successfully");
Ok(())
}
#[derive(Args, Debug)]
#[command(
about,
long_about = "Set the current STDCM search env by specifying each attribute"
)]
pub struct SetSTDCMSearchEnvFromScratchArgs {
#[arg(long)]
pub infra_id: i64,
#[arg(long)]
pub electrical_profile_set_id: Option<i64>,
#[arg(long)]
pub work_schedule_group_id: Option<i64>,
#[arg(long)]
pub timetable_id: i64,
#[arg(long)]
/// If omitted, set to the earliest train start time in the timetable
#[arg(long)]
pub search_window_begin: Option<DateTime<Utc>>,
/// If omitted, set to the latest train start time in the timetable plus one day
#[arg(long)]
pub search_window_end: Option<DateTime<Utc>>,
}
async fn set_stdcm_search_env_from_scratch(
args: SetSTDCMSearchEnvFromScratchArgs,
conn: &mut DbConnection,
) -> Result<(), Box<dyn Error + Send + Sync>> {
check_exists::<Timetable>(conn, args.timetable_id, "Timetable").await?;
check_exists::<Infra>(conn, args.infra_id, "Infra").await?;
if let Some(electrical_profile_set_id) = args.electrical_profile_set_id {
check_exists::<ElectricalProfileSet>(
conn,
electrical_profile_set_id,
"Electrical Profile Set",
)
.await?;
}
if let Some(work_schedule_group_id) = args.work_schedule_group_id {
check_exists::<WorkScheduleGroup>(conn, work_schedule_group_id, "Work Schedule Group")
.await?;
}
let (begin, end) = resolve_search_window(
args.timetable_id,
args.search_window_begin,
args.search_window_end,
conn,
)
.await?;
StdcmSearchEnvironment::changeset()
.infra_id(args.infra_id)
.electrical_profile_set_id(args.electrical_profile_set_id)
.work_schedule_group_id(args.work_schedule_group_id)
.timetable_id(args.timetable_id)
.search_window_begin(begin)
.search_window_end(end)
.enabled_from(Utc::now())
.enabled_until(Utc::now() + Duration::days(1000))
.create(conn)
.await?;
println!("✅ STDCM search environment set up successfully");
Ok(())
}
async fn resolve_search_window(
timetable_id: i64,
search_window_begin: Option<DateTime<Utc>>,
search_window_end: Option<DateTime<Utc>>,
conn: &mut DbConnection,
) -> Result<(DateTime<Utc>, DateTime<Utc>), Box<dyn Error + Send + Sync>> {
let (begin, end) = if let (Some(begin), Some(end)) = (search_window_begin, search_window_end) {
(begin, end)
} else {
let start_times = Timetable::gather_start_times(timetable_id, conn).await?;
let (Some(min), Some(max)) = (start_times.iter().min(), start_times.iter().max()) else {
let error_msg =
"❌ Timetable specified contains no train. Please fully specify search window.";
return Err(Box::new(CliError::new(1, error_msg)));
};
let begin = search_window_begin.unwrap_or(*min);
let end = search_window_end.unwrap_or(*max + Duration::days(1));
(begin, end)
};
if begin >= end {
let error_msg = format!(
"❌ Resolved window is empty: begin ({0}) >= end ({1})",
begin, end
);
return Err(Box::new(CliError::new(1, error_msg)));
}
Ok((begin, end))
}
async fn show_stdcm_search_env(
conn: &mut DbConnection,
) -> Result<(), Box<dyn Error + Send + Sync>> {
let search_env = StdcmSearchEnvironment::retrieve_latest_enabled(conn).await;
if let Some(search_env) = search_env {
println!("{search_env:#?}");
let n_trains = Timetable::trains_count(search_env.timetable_id, conn).await?;
println!("🚆 Number of trains in timetable: {0}", n_trains);
} else {
println!("🔎 No STDCM search environment has been set up yet")
};
Ok(())
}
#[cfg(test)]
mod tests {
use crate::{
models::fixtures::{
create_electrical_profile_set, create_empty_infra, create_scenario_fixtures_set,
create_timetable, create_work_schedule_group, simple_train_schedule_changeset,
},
Create,
};
use super::*;
use chrono::DateTime;
use chrono::Utc;
use editoast_models::{DbConnection, DbConnectionPoolV2};
use rstest::rstest;
fn make_datetime(s: &str) -> DateTime<Utc> {
DateTime::parse_from_rfc3339(s).unwrap().to_utc()
}
async fn create_train_schedules_from_start_times(
start_times: Vec<DateTime<Utc>>,
timetable_id: i64,
conn: &mut DbConnection,
) {
for start_time in start_times {
simple_train_schedule_changeset(timetable_id)
.start_time(start_time)
.create(conn)
.await
.expect("Should be able to create train schedules");
}
}
#[rstest]
#[case::both_none(
None,
None,
make_datetime("2000-01-01 11:59:59Z"),
make_datetime("2000-02-03 00:00:01Z")
)]
#[case::begin_none(
None,
Some(make_datetime("2000-02-01 00:00:00Z")),
make_datetime("2000-01-01 11:59:59Z"),
make_datetime("2000-02-01 00:00:00Z")
)]
#[case::end_none(
Some(make_datetime("2000-02-01 08:00:00Z")),
None,
make_datetime("2000-02-01 08:00:00Z"),
make_datetime("2000-02-03 00:00:01Z")
)]
#[case::both_some(
Some(make_datetime("2000-02-01 08:00:00Z")),
Some(make_datetime("2000-05-22 09:00:50Z")),
make_datetime("2000-02-01 08:00:00Z"),
make_datetime("2000-05-22 09:00:50Z")
)]
async fn test_resolve_search_window(
#[case] search_window_begin: Option<DateTime<Utc>>,
#[case] search_window_end: Option<DateTime<Utc>>,
#[case] expected_begin: DateTime<Utc>,
#[case] expected_end: DateTime<Utc>,
) {
let db_pool = DbConnectionPoolV2::for_tests();
let conn = &mut db_pool.get_ok();
let timetable = create_timetable(conn).await;
let start_times = vec![
make_datetime("2000-01-01 12:00:00Z"),
make_datetime("2000-02-02 00:00:00Z"),
make_datetime("2000-01-01 11:59:59Z"), // earliest
make_datetime("2000-01-15 08:59:59Z"),
make_datetime("2000-02-02 00:00:01Z"), // latest
make_datetime("2000-01-19 17:00:00Z"),
];
create_train_schedules_from_start_times(start_times, timetable.id, conn).await;
let (begin, end) =
resolve_search_window(timetable.id, search_window_begin, search_window_end, conn)
.await
.unwrap();
assert_eq!(begin, expected_begin);
assert_eq!(end, expected_end);
}
#[rstest]
async fn fail_resolve_search_window_on_empty_timetable() {
let db_pool = DbConnectionPoolV2::for_tests();
let conn = &mut db_pool.get_ok();
let timetable = create_timetable(conn).await;
assert!(resolve_search_window(timetable.id, None, None, conn)
.await
.is_err());
}
#[rstest]
#[case::both_some(
Some(make_datetime("2000-02-01 08:00:00Z")),
Some(make_datetime("2000-02-01 00:00:00Z"))
)]
#[case::end_none(Some(make_datetime("2000-03-01 00:00:00Z")), None)]
#[case::begin_none(None, Some(make_datetime("2000-01-01 08:00:00Z")))]
async fn test_resolve_search_window_incompatible_dates(
#[case] search_window_begin: Option<DateTime<Utc>>,
#[case] search_window_end: Option<DateTime<Utc>>,
) {
let db_pool = DbConnectionPoolV2::for_tests();
let conn = &mut db_pool.get_ok();
let timetable = create_timetable(conn).await;
let start_times = vec![
make_datetime("2000-01-01 12:00:00Z"),
make_datetime("2000-02-02 00:00:01Z"),
];
create_train_schedules_from_start_times(start_times, timetable.id, conn).await;
assert!(
resolve_search_window(timetable.id, search_window_begin, search_window_end, conn)
.await
.is_err()
);
}
#[rstest]
async fn test_stdcm_set_search_env_from_scenario() {
let db_pool = DbConnectionPoolV2::for_tests();
let conn = &mut db_pool.get_ok();
let scenario_fixture_set =
create_scenario_fixtures_set(conn, "test_stdcm_set_search_env_from_scenario").await;
let work_schedule_group = create_work_schedule_group(conn).await;
let start_times = vec![
make_datetime("2000-01-01 12:00:00Z"),
make_datetime("2000-02-02 08:00:00Z"),
];
create_train_schedules_from_start_times(
start_times,
scenario_fixture_set.timetable.id,
conn,
)
.await;
let args = SetSTDCMSearchEnvFromScenarioArgs {
scenario_id: scenario_fixture_set.scenario.id,
work_schedule_group_id: Some(work_schedule_group.id),
search_window_begin: None,
search_window_end: None,
};
let result = set_stdcm_search_env_from_scenario(args, conn).await;
assert!(result.is_ok());
let search_env = StdcmSearchEnvironment::retrieve_latest_enabled(conn).await;
assert!(search_env.is_some());
let search_env = search_env.unwrap();
assert_eq!(
search_env.search_window_begin,
make_datetime("2000-01-01 12:00:00Z")
);
assert_eq!(
search_env.search_window_end,
make_datetime("2000-02-03 08:00:00Z")
);
}
#[rstest]
async fn test_set_stdcm_search_env_from_scratch() {
let db_pool = DbConnectionPoolV2::for_tests();
let conn = &mut db_pool.get_ok();
let timetable = create_timetable(conn).await;
let infra = create_empty_infra(conn).await;
let work_schedule_group = create_work_schedule_group(conn).await;
let electrical_profile_set = create_electrical_profile_set(conn).await;
let start_times = vec![
make_datetime("2000-01-01 12:00:00Z"),
make_datetime("2000-02-02 08:00:00Z"),
];
create_train_schedules_from_start_times(start_times, timetable.id, conn).await;
let args = SetSTDCMSearchEnvFromScratchArgs {
infra_id: infra.id,
electrical_profile_set_id: Some(electrical_profile_set.id),
work_schedule_group_id: Some(work_schedule_group.id),
timetable_id: timetable.id,
search_window_begin: None,
search_window_end: None,
};
let result = set_stdcm_search_env_from_scratch(args, conn).await;
assert!(result.is_ok());
let search_env = StdcmSearchEnvironment::retrieve_latest_enabled(conn).await;
assert!(search_env.is_some());
let search_env = search_env.unwrap();
assert_eq!(
search_env.search_window_begin,
make_datetime("2000-01-01 12:00:00Z")
);
assert_eq!(
search_env.search_window_end,
make_datetime("2000-02-03 08:00:00Z")
);
}
}