-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathmod.rs
1628 lines (1459 loc) · 57 KB
/
mod.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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
mod graph;
pub mod object_cache;
pub mod operation;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::collections::HashSet;
use chashmap::CHashMap;
use chashmap::ReadGuard;
use chashmap::WriteGuard;
use diesel::sql_query;
use diesel::sql_types::BigInt;
use diesel::sql_types::Double;
use diesel::sql_types::Integer;
use diesel::sql_types::Nullable;
use diesel::sql_types::Text;
use diesel::QueryableByName;
use diesel_async::AsyncPgConnection as PgConnection;
use diesel_async::RunQueryDsl;
use editoast_derive::EditoastError;
use editoast_schemas::infra::Crossing;
use editoast_schemas::infra::Direction;
use editoast_schemas::infra::DirectionalTrackRange;
use editoast_schemas::infra::DoubleSlipSwitch;
use editoast_schemas::infra::Electrification;
use editoast_schemas::infra::Endpoint;
use editoast_schemas::infra::Link;
use editoast_schemas::infra::OperationalPointPart;
use editoast_schemas::infra::PointSwitch;
use editoast_schemas::infra::Route;
use editoast_schemas::infra::RoutePath;
use editoast_schemas::infra::SingleSlipSwitch;
use editoast_schemas::infra::SpeedSection;
use editoast_schemas::infra::SwitchType;
use editoast_schemas::infra::TrackEndpoint;
use editoast_schemas::infra::Waypoint;
use editoast_schemas::primitives::OSRDIdentified;
use editoast_schemas::primitives::OSRDObject;
use editoast_schemas::primitives::ObjectRef;
use editoast_schemas::primitives::ObjectType;
use enum_map::EnumMap;
use geos::geojson::Geometry;
pub use graph::Graph;
use itertools::Itertools as _;
use thiserror::Error;
use crate::error::Result;
use crate::infra_cache::object_cache::BufferStopCache;
use crate::infra_cache::object_cache::DetectorCache;
use crate::infra_cache::object_cache::OperationalPointCache;
use crate::infra_cache::object_cache::SignalCache;
use crate::infra_cache::object_cache::SwitchCache;
use crate::infra_cache::object_cache::TrackSectionCache;
use crate::infra_cache::operation::CacheOperation;
use crate::infra_cache::operation::RailjsonObject;
use crate::map::BoundingBox;
use crate::modelsv2::railjson::find_all_schemas;
use crate::modelsv2::Infra;
/// Contains infra cached data used to generate layers and errors
#[derive(Debug, Default, Clone)]
pub struct InfraCache {
/// Map track section id to the list of objects that depend on it
/// Contains all referenced track sections (not only existing ones)
pub track_sections_refs: HashMap<String, HashSet<ObjectRef>>,
/// Map reference to their cache object
objects: EnumMap<ObjectType, HashMap<String, ObjectCache>>,
}
pub trait Cache: OSRDObject {
/// Return the list of track section ids referenced by the object
fn get_track_referenced_id(&self) -> Vec<&String>;
/// Build and return the cache object
fn get_object_cache(&self) -> ObjectCache;
}
#[derive(Debug, Clone)]
pub enum ObjectCache {
TrackSection(TrackSectionCache),
Signal(SignalCache),
SpeedSection(SpeedSection),
Switch(SwitchCache),
Detector(DetectorCache),
BufferStop(BufferStopCache),
Route(Route),
OperationalPoint(OperationalPointCache),
SwitchType(SwitchType),
Electrification(Electrification),
}
impl From<RailjsonObject> for ObjectCache {
fn from(railjson: RailjsonObject) -> Self {
match railjson {
RailjsonObject::TrackSection { railjson } => ObjectCache::TrackSection(railjson.into()),
RailjsonObject::Signal { railjson } => ObjectCache::Signal(railjson.into()),
RailjsonObject::NeutralSection { .. } => unimplemented!(),
RailjsonObject::SpeedSection { railjson } => ObjectCache::SpeedSection(railjson),
RailjsonObject::Switch { railjson } => ObjectCache::Switch(railjson.into()),
RailjsonObject::SwitchType { railjson } => ObjectCache::SwitchType(railjson),
RailjsonObject::Detector { railjson } => ObjectCache::Detector(railjson.into()),
RailjsonObject::BufferStop { railjson } => ObjectCache::BufferStop(railjson.into()),
RailjsonObject::Route { railjson } => ObjectCache::Route(railjson),
RailjsonObject::OperationalPoint { railjson } => {
ObjectCache::OperationalPoint(railjson.into())
}
RailjsonObject::Electrification { railjson } => ObjectCache::Electrification(railjson),
}
}
}
impl<T: Cache> From<T> for ObjectCache {
fn from(cache: T) -> Self {
cache.get_object_cache()
}
}
impl OSRDIdentified for ObjectCache {
fn get_id(&self) -> &String {
match self {
ObjectCache::TrackSection(obj) => obj.get_id(),
ObjectCache::Signal(obj) => obj.get_id(),
ObjectCache::SpeedSection(obj) => obj.get_id(),
ObjectCache::Switch(obj) => obj.get_id(),
ObjectCache::Detector(obj) => obj.get_id(),
ObjectCache::BufferStop(obj) => obj.get_id(),
ObjectCache::Route(obj) => obj.get_id(),
ObjectCache::OperationalPoint(obj) => obj.get_id(),
ObjectCache::SwitchType(obj) => obj.get_id(),
ObjectCache::Electrification(obj) => obj.get_id(),
}
}
}
impl OSRDObject for ObjectCache {
fn get_type(&self) -> ObjectType {
match self {
ObjectCache::TrackSection(_) => ObjectType::TrackSection,
ObjectCache::Signal(_) => ObjectType::Signal,
ObjectCache::SpeedSection(_) => ObjectType::SpeedSection,
ObjectCache::Switch(_) => ObjectType::Switch,
ObjectCache::Detector(_) => ObjectType::Detector,
ObjectCache::BufferStop(_) => ObjectType::BufferStop,
ObjectCache::Route(_) => ObjectType::Route,
ObjectCache::OperationalPoint(_) => ObjectType::OperationalPoint,
ObjectCache::SwitchType(_) => ObjectType::SwitchType,
ObjectCache::Electrification(_) => ObjectType::Electrification,
}
}
}
impl ObjectCache {
fn get_track_referenced_id(&self) -> Vec<&String> {
match self {
ObjectCache::TrackSection(track) => track.get_track_referenced_id(),
ObjectCache::Signal(signal) => signal.get_track_referenced_id(),
ObjectCache::SpeedSection(speed) => speed.get_track_referenced_id(),
ObjectCache::Switch(switch) => switch.get_track_referenced_id(),
ObjectCache::Detector(detector) => detector.get_track_referenced_id(),
ObjectCache::BufferStop(buffer_stop) => buffer_stop.get_track_referenced_id(),
ObjectCache::Route(route) => route.get_track_referenced_id(),
ObjectCache::OperationalPoint(op) => op.get_track_referenced_id(),
ObjectCache::SwitchType(switch_type) => switch_type.get_track_referenced_id(),
ObjectCache::Electrification(electrification) => {
electrification.get_track_referenced_id()
}
}
}
/// Unwrap a track section from the object cache
pub fn unwrap_track_section(&self) -> &TrackSectionCache {
match self {
ObjectCache::TrackSection(track) => track,
_ => panic!("ObjectCache is not a TrackSection"),
}
}
/// Unwrap a signal from the object cache
pub fn unwrap_signal(&self) -> &SignalCache {
match self {
ObjectCache::Signal(signal) => signal,
_ => panic!("ObjectCache is not a Signal"),
}
}
/// Unwrap a speed section from the object cache
pub fn unwrap_speed_section(&self) -> &SpeedSection {
match self {
ObjectCache::SpeedSection(speed) => speed,
_ => panic!("ObjectCache is not a SpeedSection"),
}
}
/// Unwrap a switch from the object cache
pub fn unwrap_switch(&self) -> &SwitchCache {
match self {
ObjectCache::Switch(switch) => switch,
_ => panic!("ObjectCache is not a Switch"),
}
}
/// Unwrap a detector from the object cache
pub fn unwrap_detector(&self) -> &DetectorCache {
match self {
ObjectCache::Detector(detector) => detector,
_ => panic!("ObjectCache is not a Detector"),
}
}
/// Unwrap a buffer stop from the object cache
pub fn unwrap_buffer_stop(&self) -> &BufferStopCache {
match self {
ObjectCache::BufferStop(buffer_stop) => buffer_stop,
_ => panic!("ObjectCache is not a BufferStop"),
}
}
/// Unwrap a route from the object cache
pub fn unwrap_route(&self) -> &Route {
match self {
ObjectCache::Route(route) => route,
_ => panic!("ObjectCache is not a Route"),
}
}
/// Unwrap an operational point from the object cache
pub fn unwrap_operational_point(&self) -> &OperationalPointCache {
match self {
ObjectCache::OperationalPoint(op) => op,
_ => panic!("ObjectCache is not a OperationalPoint"),
}
}
/// Unwrap a switch type from the object cache
pub fn unwrap_switch_type(&self) -> &SwitchType {
match self {
ObjectCache::SwitchType(switch_type) => switch_type,
_ => panic!("ObjectCache is not a SwitchType"),
}
}
/// Unwrap a electrification from the object cache
pub fn unwrap_electrification(&self) -> &Electrification {
match self {
ObjectCache::Electrification(electrification) => electrification,
_ => panic!("ObjectCache is not a Electrification"),
}
}
}
#[derive(QueryableByName, Debug, Clone)]
pub struct TrackQueryable {
#[diesel(sql_type = Text)]
pub obj_id: String,
#[diesel(sql_type = Nullable<Integer>)]
pub line_code: Option<i32>,
#[diesel(sql_type = Double)]
pub length: f64,
#[diesel(sql_type = Text)]
pub curves: String,
#[diesel(sql_type = Text)]
pub slopes: String,
#[diesel(sql_type = Text)]
pub geo: String,
#[diesel(sql_type = Text)]
pub sch: String,
}
impl From<TrackQueryable> for TrackSectionCache {
fn from(track: TrackQueryable) -> Self {
let geo: Geometry =
serde_json::from_str(&track.geo).expect("invalid track section geometry");
let sch: Geometry =
serde_json::from_str(&track.sch).expect("invalid track section geometry");
Self {
obj_id: track.obj_id,
length: track.length,
curves: serde_json::from_str(&track.curves).unwrap(),
slopes: serde_json::from_str(&track.slopes).unwrap(),
line_code: track.line_code,
bbox_geo: BoundingBox::from_geometry(geo)
.expect("tracksections' geometry must be LineStrings"),
bbox_sch: BoundingBox::from_geometry(sch)
.expect("tracksections' geometry must be LineStrings"),
}
}
}
#[derive(QueryableByName, Debug, Clone)]
pub struct SwitchQueryable {
#[diesel(sql_type = Text)]
pub obj_id: String,
#[diesel(sql_type = Text)]
pub switch_type: String,
#[diesel(sql_type = Text)]
pub ports: String,
}
impl From<SwitchQueryable> for SwitchCache {
fn from(switch: SwitchQueryable) -> Self {
Self {
obj_id: switch.obj_id,
switch_type: switch.switch_type,
ports: serde_json::from_str(&switch.ports).unwrap(),
}
}
}
#[derive(QueryableByName, Debug, Clone)]
pub struct OperationalPointQueryable {
#[diesel(sql_type = Text)]
pub obj_id: String,
#[diesel(sql_type = Text)]
pub parts: String,
}
impl From<OperationalPointQueryable> for OperationalPointCache {
fn from(op: OperationalPointQueryable) -> Self {
let parts: Vec<OperationalPointPart> = serde_json::from_str(&op.parts).unwrap();
Self {
obj_id: op.obj_id,
parts: parts.into_iter().map_into().collect(),
}
}
}
impl InfraCache {
/// Add an object to the cache.
/// If the object already exists, it will fail (without inserting).
pub fn add<T: Cache>(&mut self, obj: T) -> Result<()> {
for track_id in obj.get_track_referenced_id() {
self.track_sections_refs
.entry(track_id.clone())
.or_default()
.insert(obj.get_ref());
}
let entry = self.objects[obj.get_type()].entry(obj.get_id().clone());
match entry {
Entry::Occupied(_) => Err(CacheOperationError::DuplicateIdsProvided {
obj_type: obj.get_type().to_string(),
obj_id: obj.get_id().clone(),
}
.into()),
Entry::Vacant(v) => {
v.insert(obj.get_object_cache());
Ok(())
}
}
}
/// Retrieve the cache of track sections
pub fn track_sections(&self) -> &HashMap<String, ObjectCache> {
&self.objects[ObjectType::TrackSection]
}
/// Retrieve the cache of detectors
pub fn detectors(&self) -> &HashMap<String, ObjectCache> {
&self.objects[ObjectType::Detector]
}
/// Retrieve the cache of buffer stops
pub fn buffer_stops(&self) -> &HashMap<String, ObjectCache> {
&self.objects[ObjectType::BufferStop]
}
/// Retrieve the cache of signals
pub fn signals(&self) -> &HashMap<String, ObjectCache> {
&self.objects[ObjectType::Signal]
}
/// Retrieve the cache of speed sections
pub fn speed_sections(&self) -> &HashMap<String, ObjectCache> {
&self.objects[ObjectType::SpeedSection]
}
/// Retrieve the cache of routes
pub fn routes(&self) -> &HashMap<String, ObjectCache> {
&self.objects[ObjectType::Route]
}
/// Retrieve the cache of switches
pub fn switches(&self) -> &HashMap<String, ObjectCache> {
&self.objects[ObjectType::Switch]
}
/// Retrieve the cache of switch types
pub fn switch_types(&self) -> &HashMap<String, ObjectCache> {
&self.objects[ObjectType::SwitchType]
}
/// Retrieve the cache of operational points
pub fn operational_points(&self) -> &HashMap<String, ObjectCache> {
&self.objects[ObjectType::OperationalPoint]
}
/// Retrieve the cache of electrifications
pub fn electrifications(&self) -> &HashMap<String, ObjectCache> {
&self.objects[ObjectType::Electrification]
}
pub fn get_objects_by_type(&self, object_type: ObjectType) -> &HashMap<String, ObjectCache> {
&self.objects[object_type]
}
/// Given an infra id load infra cache from database
pub async fn load(conn: &mut PgConnection, infra: &Infra) -> Result<InfraCache> {
let infra_id = infra.id;
let mut infra_cache = Self::default();
// Load track sections list
sql_query(
"SELECT
obj_id,
(data->'extensions'->'sncf'->>'line_code')::integer as line_code,
(data->>'length')::float as length,
data->>'curves' as curves,
data->>'slopes' as slopes,
data->>'geo' as geo,
data->>'sch' as sch
FROM infra_object_track_section WHERE infra_id = $1",
)
.bind::<BigInt, _>(infra_id)
.load::<TrackQueryable>(conn)
.await?
.into_iter()
.try_for_each(|track| infra_cache.add::<TrackSectionCache>(track.into()))?;
// Load signal tracks references
sql_query(
"SELECT obj_id, data->>'track' AS track, (data->>'position')::float AS position, data->'logical_signals' as logical_signals FROM infra_object_signal WHERE infra_id = $1")
.bind::<BigInt, _>(infra_id)
.load::<SignalCache>(conn).await?.into_iter().try_for_each(|signal|
infra_cache.add(signal)
)?;
// Load speed sections tracks references
find_all_schemas::<SpeedSection, Vec<_>>(conn, infra_id)
.await?
.into_iter()
.try_for_each(|speed| infra_cache.add(speed))?;
// Load routes tracks references
find_all_schemas::<_, Vec<Route>>(conn, infra_id)
.await?
.into_iter()
.try_for_each(|route| infra_cache.add(route))?;
// Load operational points tracks references
sql_query(
"SELECT obj_id, data->>'parts' AS parts FROM infra_object_operational_point WHERE infra_id = $1")
.bind::<BigInt, _>(infra_id)
.load::<OperationalPointQueryable>(conn).await?.into_iter().try_for_each(|op|
infra_cache.add::<OperationalPointCache>(op.into())
)?;
// Load switch tracks references
sql_query(
"SELECT obj_id, data->>'switch_type' AS switch_type, data->>'ports' AS ports FROM infra_object_switch WHERE infra_id = $1")
.bind::<BigInt, _>(infra_id)
.load::<SwitchQueryable>(conn).await?.into_iter().try_for_each(|switch|
infra_cache.add::<SwitchCache>(switch.into())
)?;
// Load switch types references
find_all_schemas::<_, Vec<SwitchType>>(conn, infra_id)
.await?
.into_iter()
.try_for_each(|switch_type| infra_cache.add::<SwitchType>(switch_type))?;
// Add builtin switch nodes
infra_cache.add::<SwitchType>(Link.into())?;
infra_cache.add::<SwitchType>(PointSwitch.into())?;
infra_cache.add::<SwitchType>(Crossing.into())?;
infra_cache.add::<SwitchType>(SingleSlipSwitch.into())?;
infra_cache.add::<SwitchType>(DoubleSlipSwitch.into())?;
// Load detector tracks references
sql_query(
"SELECT obj_id, data->>'track' AS track, (data->>'position')::float AS position FROM infra_object_detector WHERE infra_id = $1")
.bind::<BigInt, _>(infra_id)
.load::<DetectorCache>(conn).await?.into_iter().try_for_each(|detector|
infra_cache.add(detector)
)?;
// Load buffer stop tracks references
sql_query(
"SELECT obj_id, data->>'track' AS track, (data->>'position')::float AS position FROM infra_object_buffer_stop WHERE infra_id = $1")
.bind::<BigInt, _>(infra_id)
.load::<BufferStopCache>(conn).await?.into_iter().try_for_each(|buffer_stop|
infra_cache.add(buffer_stop)
)?;
// Load electrification tracks references
find_all_schemas::<_, Vec<Electrification>>(conn, infra_id)
.await?
.into_iter()
.try_for_each(|electrification| infra_cache.add::<Electrification>(electrification))?;
Ok(infra_cache)
}
/// This function tries to get the infra from the cache, if it fails, it loads it from the database
/// If the infra is not found in the database, it returns `None`
pub async fn get_or_load<'a>(
conn: &mut PgConnection,
infra_caches: &'a CHashMap<i64, InfraCache>,
infra: &Infra,
) -> Result<ReadGuard<'a, i64, InfraCache>> {
// Cache hit
if let Some(infra_cache) = infra_caches.get(&infra.id) {
return Ok(infra_cache);
}
// Cache miss
infra_caches.insert_new(infra.id, InfraCache::load(conn, infra).await?);
Ok(infra_caches.get(&infra.id).unwrap())
}
/// This function tries to get the infra from the cache, if it fails, it loads it from the database
/// If the infra is not found in the database, it returns `None`
pub async fn get_or_load_mut<'a>(
conn: &mut PgConnection,
infra_caches: &'a CHashMap<i64, InfraCache>,
infra: &Infra,
) -> Result<WriteGuard<'a, i64, InfraCache>> {
// Cache hit
if let Some(infra_cache) = infra_caches.get_mut(&infra.id) {
return Ok(infra_cache);
}
// Cache miss
infra_caches.insert_new(infra.id, InfraCache::load(conn, infra).await?);
Ok(infra_caches.get_mut(&infra.id).unwrap())
}
/// Get all track sections references of a given track and type
/// If the track is not found, it returns an empty vector
pub fn get_track_refs_type(&self, track_id: &String, obj_type: ObjectType) -> Vec<&ObjectRef> {
self.track_sections_refs
.get(track_id)
.map(|set| {
set.iter()
.filter(|obj_ref| obj_ref.obj_type == obj_type)
.collect()
})
.unwrap_or_default()
}
/// Apply delete operation to the infra cache
pub fn apply_delete(&mut self, object_ref: &ObjectRef) -> Result<()> {
let obj_cache = self.objects[object_ref.obj_type]
.remove(&object_ref.obj_id)
.ok_or_else(|| CacheOperationError::ObjectNotFound {
obj_type: object_ref.obj_type.to_string(),
obj_id: object_ref.obj_id.clone(),
})?;
for track_id in obj_cache.get_track_referenced_id() {
self.track_sections_refs
.get_mut(track_id)
.ok_or_else(|| CacheOperationError::ObjectNotFound {
obj_type: object_ref.obj_type.to_string(),
obj_id: object_ref.obj_id.clone(),
})?
.remove(object_ref);
}
Ok(())
}
/// Apply update operation to the infra cache
fn apply_update(&mut self, object_cache: ObjectCache) -> Result<()> {
self.apply_delete(&object_cache.get_ref())?;
self.apply_create(object_cache)?;
Ok(())
}
/// Apply create operation to the infra cache
fn apply_create(&mut self, object_cache: ObjectCache) -> Result<()> {
match object_cache {
ObjectCache::TrackSection(track_section) => {
self.add::<TrackSectionCache>(track_section)?;
}
ObjectCache::Signal(signal) => self.add::<SignalCache>(signal)?,
ObjectCache::SpeedSection(speed_section) => self.add(speed_section)?,
ObjectCache::Switch(switch) => self.add::<SwitchCache>(switch)?,
ObjectCache::SwitchType(switch_type) => self.add::<SwitchType>(switch_type)?,
ObjectCache::Detector(detector) => self.add::<DetectorCache>(detector)?,
ObjectCache::BufferStop(buffer_stop) => self.add::<BufferStopCache>(buffer_stop)?,
ObjectCache::Route(route) => self.add::<Route>(route)?,
ObjectCache::OperationalPoint(operational_point) => {
self.add::<OperationalPointCache>(operational_point)?;
}
ObjectCache::Electrification(electrification) => {
self.add::<Electrification>(electrification)?
}
}
Ok(())
}
/// Apply an operation to the infra cache
pub fn apply_operations(&mut self, operations: &[CacheOperation]) -> Result<()> {
for op_res in operations {
match op_res {
CacheOperation::Delete(obj_ref) => self.apply_delete(obj_ref)?,
CacheOperation::Update(object_cache) => self.apply_update(object_cache.clone())?,
CacheOperation::Create(object_cache) => self.apply_create(object_cache.clone())?,
}
}
Ok(())
}
pub fn get_track_section(&self, track_section_id: &str) -> Result<&TrackSectionCache> {
Ok(self
.track_sections()
.get(track_section_id)
.ok_or_else(|| InfraCacheEditoastError::ObjectNotFound {
obj_type: ObjectType::TrackSection.to_string(),
obj_id: track_section_id.to_string(),
})?
.unwrap_track_section())
}
pub fn get_signal(&self, signal_id: &str) -> Result<&SignalCache> {
Ok(self
.signals()
.get(signal_id)
.ok_or_else(|| InfraCacheEditoastError::ObjectNotFound {
obj_type: ObjectType::Signal.to_string(),
obj_id: signal_id.to_string(),
})?
.unwrap_signal())
}
pub fn get_speed_section(&self, speed_section_id: &str) -> Result<&SpeedSection> {
Ok(self
.speed_sections()
.get(speed_section_id)
.ok_or_else(|| InfraCacheEditoastError::ObjectNotFound {
obj_type: ObjectType::SpeedSection.to_string(),
obj_id: speed_section_id.to_string(),
})?
.unwrap_speed_section())
}
pub fn get_detector(&self, detector_id: &str) -> Result<&DetectorCache> {
Ok(self
.detectors()
.get(detector_id)
.ok_or_else(|| InfraCacheEditoastError::ObjectNotFound {
obj_type: ObjectType::Detector.to_string(),
obj_id: detector_id.to_string(),
})?
.unwrap_detector())
}
pub fn get_switch(&self, switch_id: &str) -> Result<&SwitchCache> {
Ok(self
.switches()
.get(switch_id)
.ok_or_else(|| InfraCacheEditoastError::ObjectNotFound {
obj_type: ObjectType::Switch.to_string(),
obj_id: switch_id.to_string(),
})?
.unwrap_switch())
}
pub fn get_switch_type(&self, switch_type_id: &str) -> Result<&SwitchType> {
Ok(self
.switch_types()
.get(switch_type_id)
.ok_or_else(|| InfraCacheEditoastError::ObjectNotFound {
obj_type: ObjectType::SwitchType.to_string(),
obj_id: switch_type_id.to_string(),
})?
.unwrap_switch_type())
}
pub fn get_buffer_stop(&self, buffer_stop_id: &str) -> Result<&BufferStopCache> {
Ok(self
.buffer_stops()
.get(buffer_stop_id)
.ok_or_else(|| InfraCacheEditoastError::ObjectNotFound {
obj_type: ObjectType::BufferStop.to_string(),
obj_id: buffer_stop_id.to_string(),
})?
.unwrap_buffer_stop())
}
pub fn get_route(&self, route_id: &str) -> Result<&Route> {
Ok(self
.routes()
.get(route_id)
.ok_or_else(|| InfraCacheEditoastError::ObjectNotFound {
obj_type: ObjectType::Route.to_string(),
obj_id: route_id.to_string(),
})?
.unwrap_route())
}
pub fn get_operational_point(
&self,
operational_point_id: &str,
) -> Result<&OperationalPointCache> {
Ok(self
.operational_points()
.get(operational_point_id)
.ok_or_else(|| InfraCacheEditoastError::ObjectNotFound {
obj_type: ObjectType::OperationalPoint.to_string(),
obj_id: operational_point_id.to_string(),
})?
.unwrap_operational_point())
}
pub fn get_electrification(&self, electrification_id: &str) -> Result<&Electrification> {
Ok(self
.electrifications()
.get(electrification_id)
.ok_or_else(|| InfraCacheEditoastError::ObjectNotFound {
obj_type: ObjectType::Electrification.to_string(),
obj_id: electrification_id.to_string(),
})?
.unwrap_electrification())
}
/// Return the track and position of a waypoint
fn get_waypoint_location(&self, waypoint: &Waypoint) -> Option<(&String, f64)> {
if waypoint.is_detector() {
let detector = self.detectors().get(waypoint.get_id())?;
let detector = detector.unwrap_detector();
Some((&detector.track, detector.position))
} else {
let bs = self.buffer_stops().get(waypoint.get_id())?;
let bs = bs.unwrap_buffer_stop();
Some((&bs.track, bs.position))
}
}
/// Compute the track ranges through which the route passes.
/// If the path cannot be computed (e.g. invalid topology), returns None.
pub fn compute_track_ranges_on_route(&self, route: &Route, graph: &Graph) -> Option<RoutePath> {
// Check if entry and exit points are the same
if route.entry_point == route.exit_point {
return None;
}
let mut cur_dir = route.entry_point_direction;
let (cur_track, mut cur_offset) = self.get_waypoint_location(&route.entry_point)?;
let (exit_track, exit_offset) = self.get_waypoint_location(&route.exit_point)?;
// Check that the track exists
let mut cur_track = self.track_sections().get(cur_track)?.unwrap_track_section();
// Save track ranges and used switches
let mut track_ranges = vec![];
let mut used_switches = HashMap::new();
// Check path validity
loop {
let cur_track_id = cur_track.get_id();
// Add track range
let end_offset = if cur_track_id == exit_track {
exit_offset
} else if cur_dir == Direction::StartToStop {
cur_track.length
} else {
0.
};
track_ranges.push(DirectionalTrackRange::new(
cur_track_id.clone(),
cur_offset.min(end_offset),
cur_offset.max(end_offset),
cur_dir,
));
// Search for the exit_point
if cur_track_id == exit_track {
if (cur_dir == Direction::StartToStop && cur_offset > exit_offset)
|| (cur_dir == Direction::StopToStart && cur_offset < exit_offset)
{
return None;
}
break;
}
// Search for the next track section
let endpoint = TrackEndpoint::from_track_and_direction(cur_track_id, cur_dir);
// No neighbour found
if !graph.has_neighbour(&endpoint) {
return None;
}
let switch = graph.get_switch(&endpoint)?;
let switch_id = switch.get_id();
// Check we found the switch in the route
let group = route.switches_directions.get(&switch_id.clone().into())?;
used_switches.insert(switch_id.clone().into(), group.clone());
let next_endpoint = graph.get_neighbour(&endpoint, group)?;
// Update current track section, offset and direction
cur_track = self
.track_sections()
.get(&next_endpoint.track.0)?
.unwrap_track_section();
(cur_dir, cur_offset) = match next_endpoint.endpoint {
Endpoint::Begin => (Direction::StartToStop, 0.),
Endpoint::End => (Direction::StopToStart, cur_track.length),
};
}
Some(RoutePath {
track_ranges,
switches_directions: used_switches,
})
}
}
#[derive(Debug, Error, EditoastError)]
#[editoast_error(base_id = "cache_operation")]
pub enum CacheOperationError {
#[error("{obj_type} '{obj_id}', could not be found everywhere in the infrastructure cache")]
#[editoast_error(status = 404)]
ObjectNotFound { obj_type: String, obj_id: String },
#[error("{obj_type} '{obj_id}', a duplicate already exists")]
#[editoast_error(status = 404)]
DuplicateIdsProvided { obj_type: String, obj_id: String },
}
#[derive(Debug, Error, EditoastError)]
#[editoast_error(base_id = "infra_cache")]
pub enum InfraCacheEditoastError {
#[error("{obj_type} '{obj_id}', could not be found in the infrastructure cache")]
#[editoast_error(status = 404)]
ObjectNotFound { obj_type: String, obj_id: String },
}
#[cfg(test)]
pub mod tests {
use std::collections::HashMap;
use actix_web::test as actix_test;
use chashmap::CHashMap;
use diesel_async::scoped_futures::ScopedFutureExt;
use editoast_schemas::infra::Waypoint;
use super::OperationalPointCache;
use crate::infra_cache::object_cache::BufferStopCache;
use crate::infra_cache::object_cache::DetectorCache;
use crate::infra_cache::object_cache::OperationalPointPartCache;
use crate::infra_cache::object_cache::SignalCache;
use crate::infra_cache::object_cache::TrackSectionCache;
use crate::infra_cache::operation::create::tests::create_buffer_stop;
use crate::infra_cache::operation::create::tests::create_detector;
use crate::infra_cache::operation::create::tests::create_electrification;
use crate::infra_cache::operation::create::tests::create_op;
use crate::infra_cache::operation::create::tests::create_route;
use crate::infra_cache::operation::create::tests::create_signal;
use crate::infra_cache::operation::create::tests::create_speed;
use crate::infra_cache::operation::create::tests::create_switch;
use crate::infra_cache::operation::create::tests::create_switch_type;
use crate::infra_cache::operation::create::tests::create_track;
use crate::infra_cache::InfraCache;
use crate::infra_cache::SwitchCache;
use crate::map::BoundingBox;
use crate::modelsv2::infra::tests::test_infra_transaction;
use editoast_common::Identifier;
use editoast_common::NonBlankString;
use editoast_schemas::infra::ApplicableDirections;
use editoast_schemas::infra::ApplicableDirectionsTrackRange;
use editoast_schemas::infra::Direction;
use editoast_schemas::infra::Electrification;
use editoast_schemas::infra::Endpoint;
use editoast_schemas::infra::OperationalPoint;
use editoast_schemas::infra::Route;
use editoast_schemas::infra::SpeedSection;
use editoast_schemas::infra::Switch;
use editoast_schemas::infra::SwitchPortConnection;
use editoast_schemas::infra::SwitchType;
use editoast_schemas::infra::TrackEndpoint;
use editoast_schemas::primitives::OSRDIdentified;
#[actix_test]
async fn load_track_section() {
test_infra_transaction(|conn, infra| {
async move {
let track = create_track(conn, infra.id, Default::default()).await;
let infra_cache = InfraCache::load(conn, &infra).await.unwrap();
assert_eq!(infra_cache.track_sections().len(), 1);
assert!(infra_cache.track_sections().contains_key(track.get_id()));
}
.scope_boxed()
})
.await;
}
#[actix_test]
async fn load_signal() {
test_infra_transaction(|conn, infra| {
{
async move {
let signal = create_signal(conn, infra.id, Default::default()).await;
let infra_cache = InfraCache::load(conn, &infra).await.unwrap();
assert!(infra_cache.signals().contains_key(signal.get_id()));
let refs = infra_cache.track_sections_refs;
assert_eq!(refs.get("InvalidRef").unwrap().len(), 1);
}
}
.scope_boxed()
})
.await;
}
#[actix_test]
async fn load_speed_section() {
test_infra_transaction(|conn, infra| {
async move {
let speed = create_speed(
conn,
infra.id,
SpeedSection {
track_ranges: vec![Default::default()],
..Default::default()
},
)
.await;
let infra_cache = InfraCache::load(conn, &infra).await.unwrap();
assert!(infra_cache.speed_sections().contains_key(speed.get_id()));
let refs = infra_cache.track_sections_refs;
assert_eq!(refs.get("InvalidRef").unwrap().len(), 1);
}
.scope_boxed()
})
.await;
}
#[actix_test]
async fn load_route() {
test_infra_transaction(|conn, infra| {
async move {
let route = create_route(conn, infra.id, Default::default()).await;
let infra_cache = InfraCache::load(conn, &infra).await.unwrap();
assert!(infra_cache.routes().contains_key(route.get_id()));
}
.scope_boxed()
})
.await;
}
#[actix_test]
async fn load_operational_point() {
test_infra_transaction(|conn, infra| {
async move {
let op = create_op(
conn,
infra.id,
OperationalPoint {
parts: vec![Default::default()],
..Default::default()
},
)
.await;
let infra_cache = InfraCache::load(conn, &infra).await.unwrap();
assert!(infra_cache.operational_points().contains_key(op.get_id()));
let refs = infra_cache.track_sections_refs;
assert_eq!(refs.get("InvalidRef").unwrap().len(), 1);
}
.scope_boxed()
})
.await;
}
#[actix_test]
async fn load_switch() {
test_infra_transaction(|conn, infra| {
async move {
let switch = create_switch(
conn,
infra.id,
Switch {
ports: HashMap::from([("port".into(), Default::default())]),
..Default::default()
},
)
.await;
let infra_cache = InfraCache::load(conn, &infra).await.unwrap();
assert!(infra_cache.switches().contains_key(switch.get_id()));
}
.scope_boxed()
})
.await;
}
#[actix_test]
async fn load_switch_type() {
test_infra_transaction(|conn, infra| {
async move {
let s_type = create_switch_type(conn, infra.id, Default::default()).await;
let infra_cache = InfraCache::load(conn, &infra).await.unwrap();