-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathedition.rs
1116 lines (1059 loc) · 43.7 KB
/
edition.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
use axum::extract::Json;
use axum::extract::Path;
use axum::extract::State;
use axum::Extension;
use editoast_authz::BuiltinRole;
use editoast_derive::EditoastError;
use editoast_schemas::infra::ApplicableDirectionsTrackRange;
use editoast_schemas::infra::DirectionalTrackRange;
use editoast_schemas::infra::Endpoint;
use editoast_schemas::infra::Sign;
use editoast_schemas::infra::Switch;
use editoast_schemas::infra::TrackEndpoint;
use editoast_schemas::infra::TrackOffset;
use editoast_schemas::infra::TrackSection;
use editoast_schemas::primitives::Identifier;
use editoast_schemas::primitives::OSRDIdentified;
use editoast_schemas::primitives::ObjectType;
use itertools::Itertools;
use json_patch::{AddOperation, Patch, PatchOperation, RemoveOperation, ReplaceOperation};
use serde_json::json;
use std::collections::HashMap;
use thiserror::Error;
use tracing::error;
use tracing::info;
use uuid::Uuid;
use crate::error::Result;
use crate::generated_data;
use crate::infra_cache::object_cache::OperationalPointPartCache;
use crate::infra_cache::operation::CacheOperation;
use crate::infra_cache::operation::DeleteOperation;
use crate::infra_cache::operation::Operation;
use crate::infra_cache::operation::UpdateOperation;
use crate::infra_cache::InfraCache;
use crate::infra_cache::ObjectCache;
use crate::map;
use crate::models::prelude::*;
use crate::models::Infra;
use crate::views::infra::InfraApiError;
use crate::views::infra::InfraIdParam;
use crate::views::AuthenticationExt;
use crate::views::AuthorizationError;
use crate::AppState;
use editoast_models::DbConnection;
use editoast_schemas::infra::InfraObject;
crate::routes! {
edit,
"/split_track_section" => split_track_section,
}
/// Edit the content of an infrastructure
///
/// Takes a batch of operations. An operation is a JSON patch document that will
/// be applied to the RailJSON description of the appropriate infra object.
///
/// The consistency of the patch with the RailJSON schema is checked. If a patch
/// is erroneous, the whole batch is rejected.
///
/// After editing the object, the generated cartographic layers are invalidated and
/// regenerated. The edition step fails if the regeneration fails.
#[utoipa::path(
post, path = "",
tag = "infra",
params(InfraIdParam),
request_body = Vec<Operation>,
responses(
(status = 200, body = Vec<InfraObject>, description = "The result of the operations")
)
)]
async fn edit<'a>(
Path(InfraIdParam { infra_id }): Path<InfraIdParam>,
State(AppState {
db_pool,
infra_caches,
valkey,
map_layers,
..
}): State<AppState>,
Extension(auth): AuthenticationExt,
Json(operations): Json<Vec<Operation>>,
) -> Result<Json<Vec<InfraObject>>> {
let authorized = auth
.check_roles([BuiltinRole::InfraWrite].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
// TODO: lock for update
let mut infra = Infra::retrieve_or_fail(&mut db_pool.get().await?, infra_id, || {
InfraApiError::NotFound { infra_id }
})
.await?;
let mut infra_cache =
InfraCache::get_or_load_mut(&mut db_pool.get().await?, &infra_caches, &infra).await?;
let operation_results = apply_edit(
&mut db_pool.get().await?,
&mut infra,
&operations,
&mut infra_cache,
)
.await?;
let mut conn = valkey.get_connection().await?;
map::invalidate_all(
&mut conn,
&map_layers.layers.keys().cloned().collect(),
infra_id,
)
.await?;
Ok(Json(operation_results))
}
#[utoipa::path(
post, path = "",
tag = "infra",
params(InfraIdParam),
request_body = TrackOffset,
responses(
(status = 200, body = inline(Vec<String>), description = "ID of the trackSections created")
),
)]
pub async fn split_track_section<'a>(
Path(InfraIdParam { infra_id }): Path<InfraIdParam>,
State(AppState {
db_pool,
infra_caches,
valkey,
map_layers,
..
}): State<AppState>,
Extension(auth): AuthenticationExt,
Json(payload): Json<TrackOffset>,
) -> Result<Json<Vec<String>>> {
let authorized = auth
.check_roles([BuiltinRole::InfraWrite].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
info!(
track_id = payload.track.as_str(),
offset = payload.offset,
"Splitting track section"
);
// Check the infra
let mut infra = Infra::retrieve_or_fail(&mut db_pool.get().await?, infra_id, || {
InfraApiError::NotFound { infra_id }
})
.await?;
let mut infra_cache =
InfraCache::get_or_load_mut(&mut db_pool.get().await?, &infra_caches, &infra).await?;
// Get tracks cache if it exists
let tracksection_cached = infra_cache.get_track_section(&payload.track)?.clone();
// Check if the distance is compatible with the length of the TrackSection
let distance = payload.offset as f64 / 1000.0;
let distance_fraction = distance / tracksection_cached.length;
if distance <= 0.0 || distance >= tracksection_cached.length {
return Err(EditionError::SplitTrackSectionBadOffset {
infra_id,
tracksection_id: payload.track.to_string(),
tracksection_length: tracksection_cached.length,
}
.into());
}
// Calling the DB to get the full object and also the split geo
let result = infra
.get_split_track_section_with_data(
&mut db_pool.get().await?,
payload.track.clone(),
distance_fraction,
)
.await?;
let tracksection_data = result.expect("Failed to retrieve split track section data. Ensure the track ID and distance fraction are valid.").clone();
let tracksection = tracksection_data.railjson.as_ref().clone();
// Building the two newly tracksections from the split one
// ~~~~~~~~~~~~~~~
// left
let left_tracksection_id = Uuid::new_v4();
let left_tracksection = TrackSection {
id: Identifier::from(left_tracksection_id),
length: distance,
geo: tracksection_data.left_geo.as_ref().clone(),
slopes: tracksection
.slopes
.iter()
.filter(|e| e.begin <= distance)
.map(|e| {
let mut item = e.clone();
if item.end > distance {
item.end = distance;
}
item
})
.collect_vec(),
curves: tracksection
.curves
.iter()
.filter(|e| e.begin <= distance)
.map(|e| {
let mut item = e.clone();
if item.end > distance {
item.end = distance;
}
item
})
.collect_vec(),
loading_gauge_limits: tracksection
.loading_gauge_limits
.iter()
.filter(|e| e.begin <= distance)
.map(|e| {
let mut item = e.clone();
if item.end > distance {
item.end = distance;
}
item
})
.collect_vec(),
..tracksection.clone()
};
// right
let right_tracksection_id = Uuid::new_v4();
let right_tracksection = TrackSection {
id: Identifier::from(right_tracksection_id),
length: tracksection.length - distance,
geo: tracksection_data.right_geo.as_ref().clone(),
slopes: tracksection
.slopes
.iter()
.filter(|e| e.end >= distance)
.map(|e| {
let mut item = e.clone();
item.begin = (item.begin - distance).max(0.0);
item.end -= distance;
item
})
.collect_vec(),
curves: tracksection
.curves
.iter()
.filter(|e| e.end >= distance)
.map(|e| {
let mut item = e.clone();
item.begin = (item.begin - distance).max(0.0);
item.end -= distance;
item
})
.collect_vec(),
loading_gauge_limits: tracksection
.loading_gauge_limits
.iter()
.filter(|e| e.end >= distance)
.map(|e| {
let mut item = e.clone();
item.begin = (item.begin - distance).max(0.0);
item.end -= distance;
item
})
.collect_vec(),
..tracksection.clone()
};
// track link
let mut ports = HashMap::new();
ports.insert(
"A".into(),
TrackEndpoint {
track: Identifier::from(left_tracksection_id),
endpoint: Endpoint::End,
},
);
ports.insert(
"B".into(),
TrackEndpoint {
track: Identifier::from(right_tracksection_id),
endpoint: Endpoint::Begin,
},
);
let track_link = Switch {
id: Identifier::from(Uuid::new_v4()),
switch_type: Identifier::from("link"),
group_change_delay: 0.0,
ports,
..Switch::default()
};
// Compute operations
// ~~~~~~~~~~~~~~~~~~~~~~~
// Firstly, we create the two newly tracks
let mut operations: Vec<Operation> = [
Operation::Create(Box::new(InfraObject::TrackSection {
railjson: left_tracksection,
})),
Operation::Create(Box::new(InfraObject::TrackSection {
railjson: right_tracksection,
})),
Operation::Create(Box::new(InfraObject::Switch {
railjson: track_link,
})),
]
.to_vec();
operations.extend(get_split_operations_for_impacted(
&mut infra_cache,
&tracksection,
distance,
left_tracksection_id,
right_tracksection_id,
));
// last operation, we delete the given track
operations.push(Operation::Delete(DeleteOperation {
obj_type: ObjectType::TrackSection,
obj_id: payload.track.to_string(),
}));
// Apply operations
apply_edit(
&mut db_pool.get().await?,
&mut infra,
&operations,
&mut infra_cache,
)
.await?;
let mut conn = valkey.get_connection().await?;
map::invalidate_all(
&mut conn,
&map_layers.layers.keys().cloned().collect(),
infra_id,
)
.await?;
// Return the result
Ok(Json(
[
left_tracksection_id.to_string(),
right_tracksection_id.to_string(),
]
.to_vec(),
))
}
/// Function used while splitting a track section.
/// It compute the impacted list of operations in the DB to do, following the split of the tracksection.
///
/// # Example
/// * On Switch, we change the ports ref
/// * On electrification, we change the track ranges
/// * On Detector, BufferStop : we change the track and possibly its position
/// * ....
///
/// # Arguments
/// * `tracksection_id` - ID of the original track (the split one)
/// * `distance` - Distance (in meters) where the tracksection is split
/// * `left_tracksection_id` - ID of the newly "left" tracksection
/// * `tracksection_id` - ID of the newly "right" tracksection
/// * `path` - JSON path for the operation
/// * `sign` - Sign to check
fn get_split_operations_for_impacted(
infra_cache: &mut InfraCache,
tracksection: &TrackSection,
distance: f64,
left_tracksection_id: Uuid,
right_tracksection_id: Uuid,
) -> Vec<Operation> {
let mut operations: Vec<Operation> = Vec::<Operation>::new();
let impacted = infra_cache.track_sections_refs.get(tracksection.get_id());
let Some(objs) = impacted else {
return vec![];
};
for obj in objs {
match obj.obj_type {
ObjectType::Signal => {
let ponctual_item = infra_cache.get_signal(&obj.obj_id).unwrap();
operations.push(Operation::Update(UpdateOperation {
obj_type: obj.obj_type,
obj_id: obj.obj_id.to_string(),
railjson_patch: Patch(vec![
PatchOperation::Replace(ReplaceOperation {
path: "/track".to_string().parse().unwrap(),
value: if ponctual_item.position <= distance {
json!(Identifier::from(left_tracksection_id))
} else {
json!(Identifier::from(right_tracksection_id))
},
}),
PatchOperation::Replace(ReplaceOperation {
path: "/position".to_string().parse().unwrap(),
value: if ponctual_item.position <= distance {
json!(ponctual_item.position)
} else {
json!(ponctual_item.position - distance)
},
}),
]),
}));
}
ObjectType::BufferStop => {
let ponctual_item = infra_cache.get_buffer_stop(&obj.obj_id).unwrap();
operations.push(Operation::Update(UpdateOperation {
obj_type: obj.obj_type,
obj_id: obj.obj_id.to_string(),
railjson_patch: Patch(vec![
PatchOperation::Replace(ReplaceOperation {
path: "/track".to_string().parse().unwrap(),
value: if ponctual_item.position <= distance {
json!(Identifier::from(left_tracksection_id))
} else {
json!(Identifier::from(right_tracksection_id))
},
}),
PatchOperation::Replace(ReplaceOperation {
path: "/position".to_string().parse().unwrap(),
value: if ponctual_item.position <= distance {
json!(ponctual_item.position)
} else {
json!(ponctual_item.position - distance)
},
}),
]),
}));
}
ObjectType::Detector => {
let ponctual_item = infra_cache.get_detector(&obj.obj_id).unwrap();
operations.push(Operation::Update(UpdateOperation {
obj_type: obj.obj_type,
obj_id: obj.obj_id.to_string(),
railjson_patch: Patch(vec![
PatchOperation::Replace(ReplaceOperation {
path: "/track".to_string().parse().unwrap(),
value: if ponctual_item.position <= distance {
json!(Identifier::from(left_tracksection_id))
} else {
json!(Identifier::from(right_tracksection_id))
},
}),
PatchOperation::Replace(ReplaceOperation {
path: "/position".to_string().parse().unwrap(),
value: if ponctual_item.position <= distance {
json!(ponctual_item.position)
} else {
json!(ponctual_item.position - distance)
},
}),
]),
}));
}
ObjectType::Switch => {
let switch = infra_cache.get_switch(&obj.obj_id).unwrap();
let mut patch_operations: Vec<PatchOperation> = Vec::<PatchOperation>::new();
// Check ports ref
for (key, value) in switch.ports.iter() {
if value.track == tracksection.id {
patch_operations.push(PatchOperation::Replace(ReplaceOperation {
path: format!("/ports/{}/track", key).parse().unwrap(),
value: if value.endpoint == Endpoint::Begin {
json!(Identifier::from(left_tracksection_id))
} else {
json!(Identifier::from(right_tracksection_id))
},
}));
}
}
operations.push(Operation::Update(UpdateOperation {
obj_type: obj.obj_type,
obj_id: obj.obj_id.to_string(),
railjson_patch: Patch(patch_operations),
}));
}
ObjectType::Electrification => {
let electrification = infra_cache.get_electrification(&obj.obj_id).unwrap();
// Check track ranges
operations.push(Operation::Update(UpdateOperation {
obj_type: obj.obj_type,
obj_id: obj.obj_id.to_string(),
railjson_patch: Patch(get_split_patch_operations_for_applicable_ranges(
tracksection.id.clone(),
distance,
left_tracksection_id,
right_tracksection_id,
"/track_ranges".to_string(),
&electrification.track_ranges,
)),
}));
}
ObjectType::SpeedSection => {
let speedsection = infra_cache.get_speed_section(&obj.obj_id).unwrap();
let mut patch_operations: Vec<PatchOperation> = Vec::<PatchOperation>::new();
// Check track ranges
patch_operations.extend(get_split_patch_operations_for_applicable_ranges(
tracksection.id.clone(),
distance,
left_tracksection_id,
right_tracksection_id,
"/track_ranges".to_string(),
&speedsection.track_ranges,
));
// Check extensions for signs in extensions
if let Some(psl) = &speedsection.extensions.psl_sncf {
// check for `z``
patch_operations.extend(get_split_patch_operations_for_sign(
tracksection.id.clone(),
distance,
left_tracksection_id,
right_tracksection_id,
"/extensions/psl_sncf/z".to_string(),
psl.z(),
));
// check for `announcement`
for (index, sign) in psl.announcement().iter().enumerate() {
patch_operations.extend(get_split_patch_operations_for_sign(
tracksection.id.clone(),
distance,
left_tracksection_id,
right_tracksection_id,
format!("/extensions/psl_sncf/announcement/{}", index),
sign,
));
}
// check for `r`
for (index, sign) in psl.r().iter().enumerate() {
patch_operations.extend(get_split_patch_operations_for_sign(
tracksection.id.clone(),
distance,
left_tracksection_id,
right_tracksection_id,
format!("/extensions/psl_sncf/r/{}", index),
sign,
));
}
}
operations.push(Operation::Update(UpdateOperation {
obj_type: obj.obj_type,
obj_id: obj.obj_id.to_string(),
railjson_patch: Patch(patch_operations),
}));
}
ObjectType::OperationalPoint => {
let operationalpoint = infra_cache.get_operational_point(&obj.obj_id).unwrap();
let mut patch_operations: Vec<PatchOperation> = Vec::<PatchOperation>::new();
for (index, part) in operationalpoint.parts.iter().enumerate() {
if part.track == tracksection.id {
if part.position <= distance {
patch_operations.push(PatchOperation::Replace(ReplaceOperation {
path: format!("/parts/{}/track", index).parse().unwrap(),
value: json!(Identifier::from(left_tracksection_id)),
}));
} else {
patch_operations.push(PatchOperation::Replace(ReplaceOperation {
path: format!("/parts/{}", index).parse().unwrap(),
value: json!(OperationalPointPartCache {
track: Identifier::from(right_tracksection_id),
position: part.position - distance,
}),
}));
}
}
}
operations.push(Operation::Update(UpdateOperation {
obj_type: obj.obj_type,
obj_id: obj.obj_id.to_string(),
railjson_patch: Patch(patch_operations),
}));
}
ObjectType::NeutralSection => {
let neutralsection = infra_cache.get_neutral_section(&obj.obj_id).unwrap();
let mut patch_operations: Vec<PatchOperation> = Vec::<PatchOperation>::new();
// Check track ranges
patch_operations.extend(get_split_patch_operations_for_ranges(
tracksection.id.clone(),
distance,
left_tracksection_id,
right_tracksection_id,
"/track_ranges".to_string(),
&neutralsection.track_ranges,
));
// Check extensions for signs in extensions
if let Some(neutral) = &neutralsection.extensions.neutral_sncf {
// Check for `z``
patch_operations.extend(get_split_patch_operations_for_sign(
tracksection.id.clone(),
distance,
left_tracksection_id,
right_tracksection_id,
"/extensions/neutral_sncf/exe".to_string(),
&neutral.exe,
));
// check for `announcement`
for (index, sign) in neutral.announcement.iter().enumerate() {
patch_operations.extend(get_split_patch_operations_for_sign(
tracksection.id.clone(),
distance,
left_tracksection_id,
right_tracksection_id,
format!("/extensions/neutral_sncf/announcement/{}", index),
sign,
));
}
// check for `end`
for (index, sign) in neutral.end.iter().enumerate() {
patch_operations.extend(get_split_patch_operations_for_sign(
tracksection.id.clone(),
distance,
left_tracksection_id,
right_tracksection_id,
format!("/extensions/neutral_sncf/end/{}", index),
sign,
));
}
// check for `rev`
for (index, sign) in neutral.rev.iter().enumerate() {
patch_operations.extend(get_split_patch_operations_for_sign(
tracksection.id.clone(),
distance,
left_tracksection_id,
right_tracksection_id,
format!("/extensions/neutral_sncf/rev/{}", index),
sign,
));
}
}
operations.push(Operation::Update(UpdateOperation {
obj_type: obj.obj_type,
obj_id: obj.obj_id.to_string(),
railjson_patch: Patch(patch_operations),
}));
}
// TODO: route
ObjectType::Route => (),
// TrackSection doesn't depend on track
ObjectType::TrackSection => (),
// Switch type doesn't depend on track
ObjectType::SwitchType => (),
}
}
operations
}
/// Function used while splitting a track section.
/// It helps to generate a JSON patch operation for a `Sign`.
///
/// # Arguments
/// * `tracksection_id` - ID of the original track (the split one)
/// * `distance` - Distance (in meters) where the tracksection is split
/// * `left_tracksection_id` - ID of the newly "left" tracksection
/// * `tracksection_id` - ID of the newly "right" tracksection
/// * `path` - JSON path for the operation
/// * `sign` - Sign to check
fn get_split_patch_operations_for_sign(
tracksection_id: Identifier,
distance: f64,
left_tracksection_id: Uuid,
right_tracksection_id: Uuid,
path: String,
sign: &Sign,
) -> Vec<PatchOperation> {
let mut patch_operations: Vec<PatchOperation> = Vec::<PatchOperation>::new();
if sign.track == tracksection_id {
if sign.position <= distance {
patch_operations.push(PatchOperation::Replace(ReplaceOperation {
path: format!("{}/track", path).parse().unwrap(),
value: json!(Identifier::from(left_tracksection_id)),
}));
} else {
patch_operations.push(PatchOperation::Replace(ReplaceOperation {
path: format!("{}/track", path).parse().unwrap(),
value: json!(Identifier::from(right_tracksection_id)),
}));
patch_operations.push(PatchOperation::Replace(ReplaceOperation {
path: format!("{}/position", path).parse().unwrap(),
value: json!(sign.position - distance),
}));
}
}
patch_operations
}
/// Function used while splitting a track section.
/// It helps to generate a JSON patch operation for a `Vec<ApplicableDirectionsTrackRange>`.
///
/// # Arguments
/// * `tracksection_id` - ID of the original track (the split one)
/// * `distance` - Distance (in meters) where the tracksection is split
/// * `left_tracksection_id` - ID of the newly "left" tracksection
/// * `right_tracksection_id` - ID of the newly "right" tracksection
/// * `path` - JSON path for the operation
/// * `ranges` - List of track section ranges
fn get_split_patch_operations_for_applicable_ranges(
tracksection_id: Identifier,
distance: f64,
left_tracksection_id: Uuid,
right_tracksection_id: Uuid,
path: String,
ranges: &[ApplicableDirectionsTrackRange],
) -> Vec<PatchOperation> {
let mut patch_operations: Vec<PatchOperation> = Vec::<PatchOperation>::new();
for (index, range) in ranges.iter().enumerate() {
if range.track == tracksection_id {
// Case where the range is fully on left side
// so we just need to change the track
if range.end <= distance {
patch_operations.push(PatchOperation::Replace(ReplaceOperation {
path: format!("{}/{}/track", path, index).parse().unwrap(),
value: json!(Identifier::from(left_tracksection_id)),
}));
} else {
// Case where the range is fully on right side
// so we need to change the track and to substract the distance on begin & end
if range.begin >= distance {
patch_operations.push(PatchOperation::Replace(ReplaceOperation {
path: format!("{}/{}/track", path, index).parse().unwrap(),
value: json!(Identifier::from(right_tracksection_id)),
}));
patch_operations.push(PatchOperation::Replace(ReplaceOperation {
path: format!("{}/{}/begin", path, index).parse().unwrap(),
value: json!(range.begin - distance),
}));
patch_operations.push(PatchOperation::Replace(ReplaceOperation {
path: format!("{}/{}/end", path, index).parse().unwrap(),
value: json!(range.end - distance),
}));
}
// Case where the range is on left AND right side
else {
patch_operations.push(PatchOperation::Remove(RemoveOperation {
path: format!("{}/{}", path, index).parse().unwrap(),
}));
patch_operations.push(PatchOperation::Add(AddOperation {
path: format!("{}/-", path).parse().unwrap(),
value: json!(ApplicableDirectionsTrackRange {
track: Identifier::from(left_tracksection_id),
end: distance,
..range.clone()
}),
}));
patch_operations.push(PatchOperation::Add(AddOperation {
path: format!("{}/-", path).parse().unwrap(),
value: json!(ApplicableDirectionsTrackRange {
track: Identifier::from(right_tracksection_id),
begin: 0.0,
end: range.end - distance,
..range.clone()
}),
}));
}
}
}
}
patch_operations
}
/// Function used while splitting a track section.
/// It helps to generate a JSON patch operation for a `Vec<DirectionalTrackRange>`.
/// /!\ It's the same function than the one above, but for `DirectionalTrackRange`` instead of `ApplicableDirectionsTrackRange``.
///
/// # Arguments
/// * `tracksection_id` - ID of the original track (the split one)
/// * `distance` - Distance (in meters) where the tracksection is split
/// * `left_tracksection_id` - ID of the newly "left" tracksection
/// * `right_tracksection_id` - ID of the newly "right" tracksection
/// * `path` - JSON path for the operation
/// * `ranges` - List of track section ranges
fn get_split_patch_operations_for_ranges(
tracksection_id: Identifier,
distance: f64,
left_tracksection_id: Uuid,
right_tracksection_id: Uuid,
path: String,
ranges: &[DirectionalTrackRange],
) -> Vec<PatchOperation> {
let mut patch_operations: Vec<PatchOperation> = Vec::<PatchOperation>::new();
for (index, range) in ranges.iter().enumerate() {
if range.track == tracksection_id {
// Case where the range is fully on left side
// so we just need to change the track
if range.end <= distance {
patch_operations.push(PatchOperation::Replace(ReplaceOperation {
path: format!("{}/{}/track", path, index).parse().unwrap(),
value: json!(Identifier::from(left_tracksection_id)),
}));
} else {
// Case where the range is fully on right side
// so we need to change the track and to substract the distance on begin & end
if range.begin >= distance {
patch_operations.push(PatchOperation::Replace(ReplaceOperation {
path: format!("{}/{}/track", path, index).parse().unwrap(),
value: json!(Identifier::from(right_tracksection_id)),
}));
patch_operations.push(PatchOperation::Replace(ReplaceOperation {
path: format!("{}/{}/begin", path, index).parse().unwrap(),
value: json!(range.begin - distance),
}));
patch_operations.push(PatchOperation::Replace(ReplaceOperation {
path: format!("{}/{}/end", path, index).parse().unwrap(),
value: json!(range.end - distance),
}));
}
// Case where the range is on left AND right side
else {
patch_operations.push(PatchOperation::Remove(RemoveOperation {
path: format!("{}/{}", path, index).parse().unwrap(),
}));
patch_operations.push(PatchOperation::Add(AddOperation {
path: format!("{}/-", path).parse().unwrap(),
value: json!(DirectionalTrackRange {
track: Identifier::from(left_tracksection_id),
end: distance,
..range.clone()
}),
}));
patch_operations.push(PatchOperation::Add(AddOperation {
path: format!("{}/-", path).parse().unwrap(),
value: json!(DirectionalTrackRange {
track: Identifier::from(right_tracksection_id),
begin: 0.0,
end: range.end - distance,
..range.clone()
}),
}));
}
}
}
}
patch_operations
}
async fn apply_edit(
connection: &mut DbConnection,
infra: &mut Infra,
operations: &[Operation],
infra_cache: &mut InfraCache,
) -> Result<Vec<InfraObject>> {
let infra_id = infra.id;
// Check if the infra is locked
if infra.locked {
return Err(EditionError::InfraIsLocked { infra_id }.into());
}
// Apply modifications in one transaction
connection
.clone()
.transaction(|conn| {
Box::pin(async move {
let mut railjsons = vec![];
let mut cache_operations = vec![];
for operation in operations {
let railjson = operation.apply(infra_id, &mut conn.clone()).await?;
match (operation, railjson) {
(Operation::Create(_), Some(railjson)) => {
railjsons.push(railjson.clone());
cache_operations
.push(CacheOperation::Create(ObjectCache::from(railjson)));
}
(Operation::Update(_), Some(railjson)) => {
railjsons.push(railjson.clone());
cache_operations
.push(CacheOperation::Update(ObjectCache::from(railjson)));
}
(Operation::Delete(delete_operation), _) => {
cache_operations
.push(CacheOperation::Delete(delete_operation.clone().into()));
}
_ => unreachable!("CREATE and UPDATE always produce a RailJSON"),
}
}
// Bump version
infra.bump_version(&mut conn.clone()).await?;
// Apply operations to infra cache
infra_cache.apply_operations(&cache_operations)?;
// Refresh layers if needed
generated_data::update_all(
&mut conn.clone(),
infra_id,
&cache_operations,
infra_cache,
)
.await
.expect("Update generated data failed");
// Bump infra generated version to the infra version
infra.bump_generated_version(&mut conn.clone()).await?;
Ok(railjsons)
})
})
.await
}
#[derive(Debug, Clone, Error, EditoastError)]
#[editoast_error(base_id = "infra:edition")]
enum EditionError {
#[error("Infra {infra_id} is locked")]
InfraIsLocked { infra_id: i64 },
#[error("Invalid split offset for track section '{tracksection_id}' in infra '{infra_id}'. Expected a value between 0 and {tracksection_length} meters")]
#[editoast_error(status = 400)]
SplitTrackSectionBadOffset {
infra_id: i64,
tracksection_id: String,
tracksection_length: f64,
},
}
#[cfg(test)]
pub mod tests {
use axum::http::StatusCode;
use pretty_assertions::assert_eq;
use rstest::rstest;
use super::*;
use crate::generated_data::infra_error::InfraError;
use crate::generated_data::infra_error::InfraErrorType;
use crate::models::fixtures::create_small_infra;
use crate::models::infra::ObjectQueryable;
use crate::views::infra::errors::query_errors;
use crate::views::test_app::TestAppBuilder;
#[rstest]
async fn split_track_section_should_return_404_with_bad_infra() {
// Init
let app = TestAppBuilder::default_app();
// Make a call with a bad infra ID
let request = app
.post("/infra/123456789/split_track_section/")
.json(&json!({
"track": String::from("INVALID-ID"),
"offset": 1,
}));
// Check that we receive a 404
app.fetch(request).assert_status(StatusCode::NOT_FOUND);
}
#[rstest]
async fn split_track_section_should_return_404_with_bad_id() {
// Init
let app = TestAppBuilder::default_app();
let db_pool = app.db_pool();
let small_infra = create_small_infra(&mut db_pool.get_ok()).await;
// Make a call with a bad ID
let request = app
.post(format!("/infra/{}/split_track_section", small_infra.id).as_str())
.json(&json!({
"track":"INVALID-ID",
"offset": 1,
}));
// Check that we receive a 404
app.fetch(request).assert_status(StatusCode::NOT_FOUND);
}
#[rstest]
async fn split_track_section_should_fail_with_bad_distance() {
// Init
let app = TestAppBuilder::default_app();
let db_pool = app.db_pool();
let small_infra = create_small_infra(&mut db_pool.get_ok()).await;
// Make a call with a bad distance
let request = app
.post(format!("/infra/{}/split_track_section", small_infra.id).as_str())
.json(&json!({
"track": "TA0",
"offset": 5000000,
}));
// Check that we receive an error
app.fetch(request).assert_status(StatusCode::BAD_REQUEST);
}
#[rstest]
#[case("TA0", 1000000)]
#[case("TD1", 15500000)]
async fn split_track_section_should_work(#[case] track: &str, #[case] offset: u64) {
// Init
let app = TestAppBuilder::default_app();
let db_pool = app.db_pool();
let small_infra = create_small_infra(&mut db_pool.get_ok()).await;
// Refresh the infra to get the good number of infra errors
let req_refresh =
app.post(format!("/infra/refresh/?infras={}&force=true", small_infra.id).as_str());
app.fetch(req_refresh).assert_status(StatusCode::OK);