-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathdelimited_area.rs
929 lines (873 loc) · 32 KB
/
delimited_area.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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
use crate::error::Result;
use crate::infra_cache::{Graph, InfraCache};
use crate::models::Infra;
use crate::views::infra::{InfraApiError, InfraIdParam};
use crate::views::{AuthenticationExt, AuthorizationError};
use crate::AppState;
use crate::Retrieve;
use axum::extract::{Path, State};
use axum::{Extension, Json};
use editoast_authz::BuiltinRole;
use editoast_derive::EditoastError;
use editoast_schemas::{
infra::{Direction, DirectionalTrackRange, Endpoint, Sign, TrackEndpoint},
primitives::Identifier,
};
use itertools::{Either, Itertools};
use serde::{Deserialize, Serialize};
use std::{
cmp::Ordering,
collections::{HashMap, HashSet},
result::Result as StdResult,
};
use thiserror::Error;
use utoipa::ToSchema;
crate::routes! {
"/delimited_area" => delimited_area,
}
editoast_common::schemas! {
DelimitedAreaResponse,
DirectedLocation,
InputError,
}
// Maximum distance the graph can be explored from a speed limit execution signal
// without finding any legitimate ending to the speed limit before it is considered
// there is not valid limit on the portion of the graph that is being explored.
// TODO Magic number for now. Make it configurable ?
const MAXIMUM_DISTANCE: f64 = 5000.;
#[derive(Deserialize, ToSchema)]
struct DelimitedAreaForm {
#[schema(inline)]
entries: Vec<DirectedLocation>,
#[schema(inline)]
exits: Vec<DirectedLocation>,
}
#[derive(Deserialize, Serialize, ToSchema)]
struct DelimitedAreaResponse {
track_ranges: Vec<DirectionalTrackRange>,
}
#[derive(Debug, Deserialize, Serialize, ToSchema)]
struct DirectedLocation {
#[schema(inline)]
track: Identifier,
position: f64,
direction: Direction,
}
#[derive(Debug, Error, Serialize, Deserialize, EditoastError)]
#[editoast_error(base_id = "delimited_area")]
enum DelimitedAreaError {
#[error("Some locations were invalid")]
#[editoast_error(status = 400)]
InvalidLocations {
invalid_locations: Vec<(DirectedLocation, InputError)>,
},
}
#[derive(Debug, Error, Serialize, Deserialize, ToSchema)]
enum InputError {
#[error("Track '{0}' does not exist")]
TrackDoesNotExist(String),
#[error("Invalid input position '{position}' on track '{track}' of length '{track_length}'")]
LocationOutOfBounds {
track: String,
position: f64,
track_length: f64,
},
}
#[derive(Debug, Error, Serialize, Deserialize)]
enum TrackRangeConstructionError {
#[error("Track identifiers do not match")]
TrackIdentifierMissmatch,
#[error(
"The input directions or locations on track do not allow to build a valid track range"
)]
InvalidRelativeLocations,
#[error("The location is not on track")]
LocationNotOnTrack,
}
impl From<Sign> for DirectedLocation {
fn from(value: Sign) -> Self {
let Sign {
track,
position,
direction,
..
} = value;
DirectedLocation {
track,
position,
direction,
}
}
}
#[utoipa::path(
get, path = "",
tag = "delimited_area",
params(InfraIdParam),
request_body = inline(DelimitedAreaResponse),
responses(
(status = 200, body = inline(DelimitedAreaResponse), description = "The track ranges between a list entries and exits." ),
)
)]
/// Computes all tracks between a set of `entries` locations and a set of `exits` locations
///
/// Returns any track between one of the `entries` and one of the `exits`, i.e. any track that can
/// be reached from an entry before reaching an exit.
/// To prevent a missing exit to cause the graph traversal to never stop exploring, the exploration
/// stops when a maximum distance is reached and no exit has been found.
async fn delimited_area(
Extension(auth): AuthenticationExt,
State(AppState {
infra_caches,
db_pool,
..
}): State<AppState>,
Path(InfraIdParam { infra_id }): Path<InfraIdParam>,
Json(DelimitedAreaForm { entries, exits }): Json<DelimitedAreaForm>,
) -> Result<Json<DelimitedAreaResponse>> {
// TODO in case of a missing exit, return an empty list of track ranges instead of returning all
// the track ranges explored until the stopping condition ?
let authorized = auth
.check_roles([BuiltinRole::InfraWrite].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
// Retrieve the infra
let conn = &mut db_pool.get().await?;
let infra =
Infra::retrieve_or_fail(conn, infra_id, || InfraApiError::NotFound { infra_id }).await?;
let infra_cache = InfraCache::get_or_load(conn, &infra_caches, &infra).await?;
let graph = Graph::load(&infra_cache);
// Validate user input
let (valid_entries, invalid_entries): (Vec<_>, Vec<_>) =
entries
.into_iter()
.partition_map(|entry| match validate_location(&entry, &infra_cache) {
Ok(_) => Either::Left(entry),
Err(e) => Either::Right((entry, e)),
});
let (valid_exits, invalid_exits): (Vec<_>, Vec<_>) =
exits
.into_iter()
.partition_map(|exit| match validate_location(&exit, &infra_cache) {
Ok(_) => Either::Left(exit),
Err(e) => Either::Right((exit, e)),
});
if !(invalid_exits.is_empty() && invalid_entries.is_empty()) {
let invalid_locations = invalid_entries
.into_iter()
.chain(invalid_exits.into_iter())
.collect::<Vec<_>>();
return Err(DelimitedAreaError::InvalidLocations { invalid_locations }.into());
}
// Retrieve the track ranges
Ok(Json(DelimitedAreaResponse {
track_ranges: track_ranges_from_locations(valid_entries, valid_exits, &graph, &infra_cache),
}))
}
/// Check whether a location is valid on a given infra cache, i.e. if it matches a track on the infra
/// and if it is within bounds.
fn validate_location(
location: &DirectedLocation,
infra_cache: &InfraCache,
) -> StdResult<(), InputError> {
// Check if the location track exists on the infra
let track_length = infra_cache
.track_sections()
.get(&location.track.0)
.ok_or(InputError::TrackDoesNotExist(location.track.0.clone()))?
.unwrap_track_section()
.length;
// Check if the location is within bounds on the track
if location.position < 0. || track_length < location.position {
Err(InputError::LocationOutOfBounds {
track: location.track.0.clone(),
position: location.position,
track_length,
})
} else {
Ok(())
}
}
fn track_ranges_from_locations(
entries: Vec<DirectedLocation>,
exits: Vec<DirectedLocation>,
graph: &Graph,
infra_cache: &InfraCache,
) -> Vec<DirectionalTrackRange> {
entries
.iter()
.flat_map(|entry| {
impacted_tracks(
entry,
exits.iter().collect::<Vec<&DirectedLocation>>(),
graph,
infra_cache,
MAXIMUM_DISTANCE,
)
})
.collect::<Vec<_>>()
}
fn impacted_tracks(
entry: &DirectedLocation,
exits: Vec<&DirectedLocation>,
graph: &Graph,
infra_cache: &InfraCache,
max_distance: f64,
) -> Vec<DirectionalTrackRange> {
// Map track identifiers to their list of associated exits:
let exits = {
let mut tracks_to_exits: HashMap<&Identifier, Vec<&DirectedLocation>> = HashMap::new();
for exit in exits {
tracks_to_exits.entry(&exit.track).or_default().push(exit);
}
tracks_to_exits
};
// Directional track ranges reachable from `entry` during the graph exploration.
let mut related_track_ranges: Vec<DirectionalTrackRange> = Vec::new();
// TrackEndpoint right after the entry location (in the correct direction):
let first_track_endpoint = TrackEndpoint {
endpoint: match entry.direction {
Direction::StartToStop => Endpoint::End,
Direction::StopToStart => Endpoint::Begin,
},
track: entry.track.clone(),
};
if let Some(immediate_exit) = closest_exit_from_entry(entry, exits.get(&entry.track)) {
let only_track_range = track_range_between_two_locations(entry, immediate_exit)
.expect("Failed to build track range");
return vec![only_track_range];
} else {
let first_track_length = infra_cache
.track_sections()
.get(&first_track_endpoint.track.0)
.expect("Error while retrieving a track range from the infra cache")
.unwrap_track_section()
.length;
let first_track_range = track_range_between_endpoint_and_location(
entry,
&first_track_endpoint,
first_track_length,
true,
)
.expect("Failed to build track range");
related_track_ranges.push(first_track_range);
};
// Identifiers of the track sections that have already been reached and should be ignored:
let mut visited_tracks: HashSet<&TrackEndpoint> = HashSet::new();
// Neighbors of the explored tracks, i.e. the tracks that should be visited next:
let mut next_tracks: Vec<(&TrackEndpoint, f64)> = Vec::new();
let remaining_distance =
max_distance - (related_track_ranges[0].end - related_track_ranges[0].begin);
if 0. < remaining_distance {
let neighbours = graph
.get_all_neighbours(&first_track_endpoint)
.into_iter()
.map(|neighbour| (neighbour, remaining_distance))
.collect::<Vec<_>>();
next_tracks.extend(neighbours);
}
while let Some((curr_track_endpoint, remaining_distance)) = next_tracks.pop() {
let curr_track_id = &curr_track_endpoint.track;
if !visited_tracks.insert(curr_track_endpoint) {
// Track already visited
continue;
}
let track_length = infra_cache
.track_sections()
.get(&curr_track_endpoint.track.0)
.expect("Error while retrieving a track range from the infra cache")
.unwrap_track_section()
.length;
// Check if there is an exit location on that track range
if let Some(exit) =
closest_exit_from_endpoint(curr_track_endpoint, exits.get(&curr_track_id))
{
// End the search on that track, add the current track with the correct offset
let track_range = track_range_between_endpoint_and_location(
exit,
curr_track_endpoint,
track_length,
false,
)
.expect("Failed to build track range");
related_track_ranges.push(track_range);
} else {
let track_range =
track_range_from_endpoint(curr_track_endpoint, remaining_distance, track_length)
.expect("Failed to build track range");
let neighbours_remaining_distance =
remaining_distance - (track_range.end - track_range.begin);
related_track_ranges.push(track_range);
if 0. < neighbours_remaining_distance {
let opposite_track_endpoint = TrackEndpoint {
endpoint: match curr_track_endpoint.endpoint {
Endpoint::Begin => Endpoint::End,
Endpoint::End => Endpoint::Begin,
},
track: curr_track_endpoint.track.clone(),
};
let neighbours = graph
.get_all_neighbours(&opposite_track_endpoint)
.into_iter()
.map(|neighbour| (neighbour, neighbours_remaining_distance))
.collect::<Vec<_>>();
next_tracks.extend(neighbours);
}
}
}
related_track_ranges
}
/// Return the closest exit that applies on a track from a starting endpoint.
/// To be applicable, an exit must be in the correct direction.
fn closest_exit_from_endpoint<'a>(
track_endpoint: &TrackEndpoint,
exits: Option<&'a Vec<&DirectedLocation>>,
) -> Option<&'a DirectedLocation> {
exits.map(|exits| {
exits
.iter()
.filter(|exit| exit.track == track_endpoint.track)
.filter(|exit| match track_endpoint.endpoint {
Endpoint::Begin => exit.direction == Direction::StartToStop,
Endpoint::End => exit.direction == Direction::StopToStart,
})
.sorted_by(
|e_1, e_2| match (track_endpoint.endpoint, e_1.position < e_2.position) {
(Endpoint::Begin, true) | (Endpoint::End, false) => Ordering::Less,
(Endpoint::Begin, false) | (Endpoint::End, true) => Ordering::Greater,
},
)
.map(|exit| &**exit)
.next()
})?
}
/// Return the closest applicable exit that is on the same track as the `entry`, or `None`.
/// if there is none.
fn closest_exit_from_entry<'a>(
entry: &DirectedLocation,
exits: Option<&'a Vec<&DirectedLocation>>,
) -> Option<&'a DirectedLocation> {
exits.map(|exits| {
exits
.iter()
.filter(|exit| exit.track == entry.track)
.filter(|exit| entry.direction == exit.direction)
.filter(|exit| match entry.direction {
Direction::StartToStop => entry.position < exit.position,
Direction::StopToStart => exit.position < entry.position,
})
.sorted_by(
|e_1, e_2| match (entry.direction, e_1.position < e_2.position) {
(Direction::StartToStop, true) | (Direction::StopToStart, false) => {
Ordering::Less
}
(Direction::StartToStop, false) | (Direction::StopToStart, true) => {
Ordering::Greater
}
},
)
.map(|exit| &**exit)
.next()
})?
}
/// Return the directional track range starting at `entry` finishing at `exit`, or an error
/// if no track range can be built from them.
fn track_range_between_two_locations(
entry: &DirectedLocation,
exit: &DirectedLocation,
) -> StdResult<DirectionalTrackRange, TrackRangeConstructionError> {
let exit_before_entry = match entry.direction {
Direction::StartToStop => exit.position < entry.position,
Direction::StopToStart => entry.position < exit.position,
};
if entry.direction != exit.direction || exit_before_entry {
Err(TrackRangeConstructionError::InvalidRelativeLocations)
} else if entry.track != exit.track {
Err(TrackRangeConstructionError::TrackIdentifierMissmatch)
} else {
Ok(DirectionalTrackRange {
track: entry.track.clone(),
begin: f64::min(entry.position, exit.position),
end: f64::max(entry.position, exit.position),
direction: entry.direction,
})
}
}
/// Return the directional track range delimited by a location and a track endpoint.
/// Panics a valid track range on `infra_cache` cannot be built from `location` and `endpoint`.
fn track_range_between_endpoint_and_location(
location: &DirectedLocation,
endpoint: &TrackEndpoint,
track_length: f64,
entry: bool,
) -> StdResult<DirectionalTrackRange, TrackRangeConstructionError> {
let mut location_on_correct_direction = !matches!(
(location.direction, endpoint.endpoint),
(Direction::StartToStop, Endpoint::End) | (Direction::StopToStart, Endpoint::Begin)
);
if entry {
location_on_correct_direction = !location_on_correct_direction;
}
let same_track = location.track == endpoint.track;
let location_inside_track = 0. <= location.position && location.position <= track_length;
if !location_on_correct_direction {
Err(TrackRangeConstructionError::InvalidRelativeLocations)
} else if !same_track {
Err(TrackRangeConstructionError::TrackIdentifierMissmatch)
} else if !location_inside_track {
Err(TrackRangeConstructionError::LocationNotOnTrack)
} else {
let (begin_offset, end_offset) = match endpoint.endpoint {
Endpoint::Begin => (0., location.position),
Endpoint::End => (location.position, track_length),
};
let track_range = DirectionalTrackRange {
track: location.track.clone(),
begin: begin_offset,
end: end_offset,
direction: location.direction,
};
Ok(track_range)
}
}
/// Build a directional track range starting at `track_endpoint` and stopping at the end of the track
/// range if it is shorter than `remaining_distance`, or at `remaining_distance` from `track_endpoint`
/// otherwise. Returns: the built track range or `None` if the track does not exist in `infra_cache`.
fn track_range_from_endpoint(
track_endpoint: &TrackEndpoint,
remaining_distance: f64,
track_length: f64,
) -> StdResult<DirectionalTrackRange, TrackRangeConstructionError> {
let direction = match track_endpoint.endpoint {
Endpoint::Begin => Direction::StartToStop,
Endpoint::End => Direction::StopToStart,
};
let track_range_length = if track_length < remaining_distance {
track_length
} else {
remaining_distance
};
let (begin_offset, end_offset) = match direction {
Direction::StartToStop => (0., track_range_length),
Direction::StopToStart => (track_length - track_range_length, track_length),
};
Ok(DirectionalTrackRange {
track: track_endpoint.track.clone(),
begin: begin_offset,
end: end_offset,
direction,
})
}
#[cfg(test)]
mod tests {
use crate::models::fixtures::create_small_infra;
use crate::models::Infra;
use crate::views::infra::delimited_area::DelimitedAreaResponse;
use crate::views::test_app::TestAppBuilder;
use axum::http::StatusCode;
use editoast_schemas::infra::{Direction, DirectionalTrackRange};
use rstest::rstest;
use serde_json::json;
use super::DirectedLocation;
/// Create a temporary speed limit through with a given signal list and `small_infra` id through
/// the creation endpoint, then retrieve from the database the persisted track sections for that
/// speed limit.
async fn get_track_ranges_request(
entries: Vec<DirectedLocation>,
exits: Vec<DirectedLocation>,
) -> Vec<DirectionalTrackRange> {
let app = TestAppBuilder::default_app();
let pool = app.db_pool();
let Infra { id: infra_id, .. } = create_small_infra(&mut pool.get_ok()).await;
let request = app
.get(&format!("/infra/{infra_id}/delimited_area"))
.json(&json!({
"infra_id": infra_id,
"entries": entries,
"exits": exits,
}
));
let DelimitedAreaResponse { track_ranges } =
app.fetch(request).assert_status(StatusCode::OK).json_into();
track_ranges
}
#[rstest]
async fn same_track_start_to_stop() {
let entries = vec![DirectedLocation {
track: "TH1".into(),
position: 100.,
direction: Direction::StartToStop,
}];
let exits = vec![DirectedLocation {
track: "TH1".into(),
position: 200.,
direction: Direction::StartToStop,
}];
let retrieved_track_ranges = get_track_ranges_request(entries, exits).await;
let expected_track_ranges = vec![DirectionalTrackRange {
track: "TH1".into(),
begin: 100.,
end: 200.,
direction: Direction::StartToStop,
}];
assert_eq!(expected_track_ranges, retrieved_track_ranges);
}
#[rstest]
async fn same_track_stop_to_start() {
let entries = vec![DirectedLocation {
track: "TH1".into(),
position: 200.,
direction: Direction::StopToStart,
}];
let exits = vec![DirectedLocation {
track: "TH1".into(),
position: 100.,
direction: Direction::StopToStart,
}];
let retrieved_track_ranges = get_track_ranges_request(entries, exits).await;
let expected_track_ranges = vec![DirectionalTrackRange {
track: "TH1".into(),
begin: 100.,
end: 200.,
direction: Direction::StopToStart,
}];
assert_eq!(expected_track_ranges, retrieved_track_ranges);
}
#[rstest]
async fn tunnel_on_two_tracks() {
let entries = vec![DirectedLocation {
track: "TF1".into(),
position: 100.,
direction: Direction::StopToStart,
}];
let exits = vec![DirectedLocation {
track: "TF0".into(),
position: 2.,
direction: Direction::StopToStart,
}];
let retrieved_track_ranges = get_track_ranges_request(entries, exits).await;
let expected_track_ranges = vec![
DirectionalTrackRange {
track: "TF1".into(),
begin: 0.,
end: 100.,
direction: Direction::StopToStart,
},
DirectionalTrackRange {
track: "TF0".into(),
begin: 2.,
end: 3.,
direction: Direction::StopToStart,
},
];
assert_eq!(expected_track_ranges, retrieved_track_ranges);
}
#[rstest]
async fn both_point_switch_directions_get_explored() {
let entries = vec![DirectedLocation {
track: "TG1".into(),
position: 100.,
direction: Direction::StartToStop,
}];
let exits = vec![
DirectedLocation {
track: "TG3".into(),
position: 50.,
direction: Direction::StartToStop,
},
DirectedLocation {
track: "TG4".into(),
position: 150.,
direction: Direction::StartToStop,
},
];
let mut retrieved_track_ranges = get_track_ranges_request(entries, exits).await;
let mut expected_track_ranges = vec![
DirectionalTrackRange {
track: "TG1".into(),
begin: 100.,
end: 4000.,
direction: Direction::StartToStop,
},
DirectionalTrackRange {
track: "TG3".into(),
begin: 0.,
end: 50.,
direction: Direction::StartToStop,
},
DirectionalTrackRange {
track: "TG4".into(),
begin: 0.,
end: 150.,
direction: Direction::StartToStop,
},
];
expected_track_ranges.sort_by(|lhs, rhs| lhs.track.0.cmp(&rhs.track.0));
retrieved_track_ranges.sort_by(|lhs, rhs| lhs.track.0.cmp(&rhs.track.0));
assert_eq!(expected_track_ranges, retrieved_track_ranges);
}
#[rstest]
async fn multiple_isolated_entry_signals() {
let entries = vec![
DirectedLocation {
track: "TF1".into(),
position: 100.,
direction: Direction::StopToStart,
},
DirectedLocation {
track: "TG1".into(),
position: 100.,
direction: Direction::StartToStop,
},
];
let exits = vec![
DirectedLocation {
track: "TF0".into(),
position: 2.,
direction: Direction::StopToStart,
},
DirectedLocation {
track: "TG3".into(),
position: 50.,
direction: Direction::StartToStop,
},
DirectedLocation {
track: "TG4".into(),
position: 150.,
direction: Direction::StartToStop,
},
];
let mut retrieved_track_ranges = get_track_ranges_request(entries, exits).await;
let mut expected_track_ranges = vec![
DirectionalTrackRange {
track: "TF1".into(),
begin: 0.,
end: 100.,
direction: Direction::StopToStart,
},
DirectionalTrackRange {
track: "TF0".into(),
begin: 2.,
end: 3.,
direction: Direction::StopToStart,
},
DirectionalTrackRange {
track: "TG1".into(),
begin: 100.,
end: 4000.,
direction: Direction::StartToStop,
},
DirectionalTrackRange {
track: "TG3".into(),
begin: 0.,
end: 50.,
direction: Direction::StartToStop,
},
DirectionalTrackRange {
track: "TG4".into(),
begin: 0.,
end: 150.,
direction: Direction::StartToStop,
},
];
expected_track_ranges.sort_by(|lhs, rhs| lhs.track.0.cmp(&rhs.track.0));
retrieved_track_ranges.sort_by(|lhs, rhs| lhs.track.0.cmp(&rhs.track.0));
assert_eq!(expected_track_ranges, retrieved_track_ranges);
}
#[rstest]
async fn signals_facing_opposite_direction_are_ignored() {
let entries = vec![DirectedLocation {
track: "TF1".into(),
position: 100.,
direction: Direction::StopToStart,
}];
let exits = vec![
DirectedLocation {
track: "TF0".into(),
position: 2.,
direction: Direction::StartToStop,
},
DirectedLocation {
track: "TF0".into(),
position: 1.,
direction: Direction::StopToStart,
},
];
let retrieved_track_ranges = get_track_ranges_request(entries, exits).await;
let expected_track_ranges = vec![
DirectionalTrackRange {
track: "TF1".into(),
begin: 0.,
end: 100.,
direction: Direction::StopToStart,
},
DirectionalTrackRange {
track: "TF0".into(),
begin: 1.,
end: 3.,
direction: Direction::StopToStart,
},
];
assert_eq!(expected_track_ranges, retrieved_track_ranges);
}
#[rstest]
async fn track_range_is_built_from_the_closest_exit() {
let entries = vec![DirectedLocation {
track: "TF1".into(),
position: 100.,
direction: Direction::StopToStart,
}];
let exits = vec![
DirectedLocation {
track: "TF0".into(),
position: 2.,
direction: Direction::StopToStart,
},
DirectedLocation {
track: "TF0".into(),
position: 1.,
direction: Direction::StopToStart,
},
];
let retrieved_track_ranges = get_track_ranges_request(entries, exits).await;
let expected_track_ranges = vec![
DirectionalTrackRange {
track: "TF1".into(),
begin: 0.,
end: 100.,
direction: Direction::StopToStart,
},
DirectionalTrackRange {
track: "TF0".into(),
begin: 2.,
end: 3.,
direction: Direction::StopToStart,
},
];
assert_eq!(expected_track_ranges, retrieved_track_ranges);
}
#[rstest]
async fn exit_before_entry_is_ignored() {
// The graph exploration should not stop if there is an exit signal on the same track
// as the entry signal when the exit signal is behind the entry signal.
let entries = vec![DirectedLocation {
track: "TF1".into(),
position: 100.,
direction: Direction::StopToStart,
}];
let exits = vec![
DirectedLocation {
track: "TF1".into(),
position: 150.,
direction: Direction::StopToStart,
},
DirectedLocation {
track: "TF0".into(),
position: 2.,
direction: Direction::StopToStart,
},
];
let retrieved_track_ranges = get_track_ranges_request(entries, exits).await;
let expected_track_ranges = vec![
DirectionalTrackRange {
track: "TF1".into(),
begin: 0.,
end: 100.,
direction: Direction::StopToStart,
},
DirectionalTrackRange {
track: "TF0".into(),
begin: 2.,
end: 3.,
direction: Direction::StopToStart,
},
];
assert_eq!(expected_track_ranges, retrieved_track_ranges);
}
#[rstest]
async fn closest_exit_ignores_exits_before_entry() {
// If the LTV is a single track range, it should ignore the signals behind it when
// checking which one is the closest.
let entries = vec![DirectedLocation {
track: "TF1".into(),
position: 400.,
direction: Direction::StopToStart,
}];
let exits = vec![
DirectedLocation {
track: "TF1".into(),
position: 500.,
direction: Direction::StopToStart,
},
DirectedLocation {
track: "TF1".into(),
position: 100.,
direction: Direction::StopToStart,
},
];
let retrieved_track_ranges = get_track_ranges_request(entries, exits).await;
let expected_track_ranges = vec![DirectionalTrackRange {
track: "TF1".into(),
begin: 100.,
end: 400.,
direction: Direction::StopToStart,
}];
assert_eq!(expected_track_ranges, retrieved_track_ranges);
}
#[rstest]
async fn exploration_stops_when_resume_signal_is_missing_and_maximum_distance_is_reached() {
let entries = vec![DirectedLocation {
track: "TE0".into(),
position: 500.,
direction: Direction::StartToStop,
}];
let mut retrieved_track_ranges = get_track_ranges_request(entries, vec![]).await;
let mut expected_track_ranges = vec![
DirectionalTrackRange {
track: "TE0".into(),
begin: 500.,
end: 1500.,
direction: Direction::StartToStop,
},
DirectionalTrackRange {
track: "TF0".into(),
begin: 0.,
end: 3.,
direction: Direction::StartToStop,
},
DirectionalTrackRange {
track: "TF1".into(),
begin: 0.,
end: 3997.,
direction: Direction::StartToStop,
},
];
expected_track_ranges.sort_by(|lhs, rhs| lhs.track.0.cmp(&rhs.track.0));
retrieved_track_ranges.sort_by(|lhs, rhs| lhs.track.0.cmp(&rhs.track.0));
assert_eq!(expected_track_ranges, retrieved_track_ranges);
}
#[rstest]
#[ignore]
async fn track_section_can_be_explored_in_both_directions() {
// TODO find a way to test it on small_infra or make a specific infra for this test
todo!()
}
#[rstest]
#[ignore]
async fn adjacent_track_ranges_are_merged() {
// If two directional track ranges are adjacent and have the same direction,
// they should be merged into a single bigger directional track range.
// N.B. This is mostly a performance issue.
unimplemented!();
}
#[rstest]
#[ignore]
async fn request_with_invalid_locations_is_rejected() {
// Invalid locations (invalid track number, location position not on the track...)
// get rejected with a 400 error code and the response contains context about
// which locations were invalid and how they were invalid.
todo!()
}
}