-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathmod.rs
1240 lines (1098 loc) · 37.4 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 attached;
mod auto_fixes;
mod delimited_area;
mod edition;
mod errors;
mod lines;
mod objects;
mod pathfinding;
mod railjson;
mod routes;
use axum::extract::Json;
use axum::extract::Path;
use axum::extract::Query;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::Extension;
use editoast_authz::BuiltinRole;
use editoast_derive::EditoastError;
use editoast_osrdyne_client::OsrdyneClient;
use itertools::Itertools;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
use thiserror::Error;
use utoipa::IntoParams;
use utoipa::ToSchema;
use super::pagination::PaginationStats;
use super::params::List;
use super::AuthenticationExt;
use crate::core::infra_loading::InfraLoadRequest;
use crate::core::AsCoreRequest;
use crate::error::Result;
use crate::infra_cache::InfraCache;
use crate::infra_cache::ObjectCache;
use crate::map;
use crate::models::prelude::*;
use crate::models::Infra;
use crate::views::pagination::PaginatedList as _;
use crate::views::pagination::PaginationQueryParams;
use crate::views::AuthorizationError;
use crate::AppState;
use editoast_models::DbConnectionPoolV2;
use editoast_schemas::infra::SwitchType;
crate::routes! {
"/infra" => {
list,
create,
"/refresh" => refresh,
"/voltages" => get_all_voltages,
&railjson,
"/{infra_id}" => {
&objects,
&routes,
&lines,
&auto_fixes,
&pathfinding,
&attached,
&edition,
&errors,
&delimited_area,
get,
"/load" => load,
delete,
put,
"/clone" => clone,
"/lock" => lock,
"/unlock" => unlock,
"/speed_limit_tags" => get_speed_limit_tags,
"/voltages" => get_voltages,
"/switch_types" => get_switch_types,
},
},
}
editoast_common::schemas! {
pathfinding::schemas(),
delimited_area::schemas(),
InfraState,
InfraWithState,
}
#[derive(Debug, Error, EditoastError)]
#[editoast_error(base_id = "infra")]
pub enum InfraApiError {
/// Couldn't find the infra with the given id
#[error("Infra '{infra_id}', could not be found")]
#[editoast_error(status = 404)]
NotFound { infra_id: i64 },
}
#[derive(Debug, Deserialize, IntoParams)]
#[into_params(parameter_in = Query)]
struct RefreshQueryParams {
#[serde(default)]
force: bool,
/// A comma-separated list of infra IDs to refresh
///
/// If not provided, all available infras will be refreshed.
#[serde(default)]
#[param(value_type = Vec<u64>)]
infras: List<i64>,
}
#[derive(Debug, Serialize, ToSchema)]
struct RefreshResponse {
/// The list of infras that were refreshed successfully
infra_refreshed: Vec<i64>,
}
/// Refresh infra generated geographic layers
#[utoipa::path(
post, path = "",
tag = "infra",
params(RefreshQueryParams),
responses(
(status = 200, body = inline(RefreshResponse)),
(status = 404, description = "Invalid infra ID query parameters"),
)
)]
async fn refresh(
State(AppState {
db_pool,
valkey: valkey_client,
infra_caches,
map_layers,
..
}): State<AppState>,
Extension(auth): AuthenticationExt,
Query(query_params): Query<RefreshQueryParams>,
) -> Result<Json<RefreshResponse>> {
let authorized = auth
.check_roles([BuiltinRole::InfraWrite].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
// Use a transaction to give scope to infra list lock
let RefreshQueryParams {
force,
infras: List(infras),
} = query_params;
let infras_list = if infras.is_empty() {
// Retrieve all available infra
Infra::all(&mut db_pool.get().await?).await
} else {
// Retrieve given infras
Infra::retrieve_batch_or_fail(&mut db_pool.get().await?, infras, |missing| {
InfraApiError::NotFound {
infra_id: missing.into_iter().next().unwrap(),
}
})
.await?
};
// Refresh each infras
let mut infra_refreshed = vec![];
for mut infra in infras_list {
let infra_cache =
InfraCache::get_or_load(&mut db_pool.get().await?, &infra_caches, &infra).await?;
if infra.refresh(db_pool.clone(), force, &infra_cache).await? {
infra_refreshed.push(infra.id);
}
}
let mut conn = valkey_client.get_connection().await?;
for infra_id in infra_refreshed.iter() {
map::invalidate_all(
&mut conn,
&map_layers.layers.keys().cloned().collect(),
*infra_id,
)
.await?;
}
Ok(Json(RefreshResponse { infra_refreshed }))
}
#[derive(Serialize, ToSchema)]
struct InfraListResponse {
#[serde(flatten)]
stats: PaginationStats,
results: Vec<InfraWithState>,
}
/// Lists all infras along with their current loading state in Core
#[utoipa::path(
get, path = "",
tag = "infra",
params(PaginationQueryParams),
responses(
(status = 200, description = "All infras, paginated", body = inline(InfraListResponse))
),
)]
async fn list(
State(AppState {
db_pool,
osrdyne_client,
..
}): State<AppState>,
Extension(auth): AuthenticationExt,
Query(pagination_params): Query<PaginationQueryParams>,
) -> Result<Json<InfraListResponse>> {
let authorized = auth
.check_roles([BuiltinRole::InfraRead].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
let settings = pagination_params
.validate(1000)?
.warn_page_size(100)
.into_selection_settings();
let (infras, stats) = {
let conn = &mut db_pool.get().await?;
Infra::list_paginated(conn, settings).await?
};
let infra_states = fetch_all_infra_states(&infras, osrdyne_client.as_ref()).await?;
let response = InfraListResponse {
stats,
results: infras
.into_iter()
.map(|infra| {
let state = infra_states
.get(&infra.id.to_string())
.cloned()
.unwrap_or(InfraState::NotLoaded);
InfraWithState { infra, state }
})
.collect(),
};
Ok(Json(response))
}
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq, Serialize, ToSchema)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum InfraState {
#[default]
NotLoaded,
Initializing,
Downloading,
ParsingJson,
ParsingInfra,
LoadingSignals,
BuildingBlocks,
Cached,
TransientError,
Error,
}
impl From<editoast_osrdyne_client::WorkerStatus> for InfraState {
fn from(status: editoast_osrdyne_client::WorkerStatus) -> Self {
match status {
editoast_osrdyne_client::WorkerStatus::Unscheduled => InfraState::NotLoaded,
editoast_osrdyne_client::WorkerStatus::Started => InfraState::Initializing,
editoast_osrdyne_client::WorkerStatus::Ready => InfraState::Cached,
editoast_osrdyne_client::WorkerStatus::Error => InfraState::Error,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
struct InfraWithState {
#[serde(flatten)]
pub infra: Infra,
pub state: InfraState,
}
#[derive(IntoParams, Deserialize)]
#[allow(unused)]
struct InfraIdParam {
/// An existing infra ID
infra_id: i64,
}
/// Retrieve a specific infra
#[utoipa::path(
get, path = "",
tag = "infra",
params(InfraIdParam),
responses(
(status = 200, description = "The infra", body = InfraWithState),
(status = 404, description = "Infra ID not found"),
),
)]
async fn get(
State(AppState {
db_pool,
osrdyne_client,
..
}): State<AppState>,
Extension(auth): AuthenticationExt,
Path(infra): Path<InfraIdParam>,
) -> Result<Json<InfraWithState>> {
let authorized = auth
.check_roles([BuiltinRole::InfraRead].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
let infra_id = infra.infra_id;
let infra = Infra::retrieve_or_fail(&mut db_pool.get().await?, infra_id, || {
InfraApiError::NotFound { infra_id }
})
.await?;
let state = fetch_infra_state(infra.id, osrdyne_client.as_ref()).await?;
Ok(Json(InfraWithState { infra, state }))
}
#[derive(Debug, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct InfraCreateForm {
/// The name to give to the new infra
pub name: String,
}
impl From<InfraCreateForm> for Changeset<Infra> {
fn from(infra: InfraCreateForm) -> Self {
Self::default().name(infra.name).last_railjson_version()
}
}
/// Creates an empty infra
///
/// The infra may be edited by batch later via the `POST /infra/ID` or `POST /infra/ID/railjson` endpoints.
#[utoipa::path(
post, path = "",
tag = "infra",
request_body = inline(InfraCreateForm),
responses(
(status = 201, description = "The created infra", body = Infra),
),
)]
async fn create(
State(db_pool): State<DbConnectionPoolV2>,
Extension(auth): AuthenticationExt,
Json(infra_form): Json<InfraCreateForm>,
) -> Result<impl IntoResponse> {
let authorized = auth
.check_roles([BuiltinRole::InfraWrite].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
let infra: Changeset<Infra> = infra_form.into();
let infra = infra.create(&mut db_pool.get().await?).await?;
Ok((StatusCode::CREATED, Json(infra)))
}
#[derive(Deserialize, IntoParams)]
#[into_params(parameter_in = Query)]
struct CloneQuery {
/// The name of the new infra
name: String,
}
/// Duplicate an infra
#[utoipa::path(
post, path = "",
tag = "infra",
params(InfraIdParam, CloneQuery),
responses(
(status = 200, description = "The new infra ID", body = u64),
(status = 404, description = "Infra ID not found"),
),
)]
async fn clone(
Extension(auth): AuthenticationExt,
Path(params): Path<InfraIdParam>,
State(db_pool): State<DbConnectionPoolV2>,
Query(CloneQuery { name }): Query<CloneQuery>,
) -> Result<Json<i64>> {
let authorized = auth
.check_roles([BuiltinRole::InfraWrite].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
let conn = &mut db_pool.get().await?;
let infra = Infra::retrieve_or_fail(conn, params.infra_id, || InfraApiError::NotFound {
infra_id: params.infra_id,
})
.await?;
let cloned_infra = infra.clone(conn, name).await?;
Ok(Json(cloned_infra.id))
}
/// Delete an infra and all entities linked to it.
///
/// This operation cannot be undone.
///
/// So beware.
///
/// You've been warned.
///
/// This operation may take a while to complete.
#[utoipa::path(
delete, path = "",
tag = "infra",
params(InfraIdParam),
responses(
(status = 204, description = "The infra has been deleted"),
(status = 404, description = "Infra ID not found"),
),
)]
async fn delete(
State(AppState {
db_pool,
infra_caches,
..
}): State<AppState>,
Extension(auth): AuthenticationExt,
Path(InfraIdParam { infra_id }): Path<InfraIdParam>,
) -> Result<impl IntoResponse> {
let authorized = auth
.check_roles([BuiltinRole::InfraWrite].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
if Infra::fast_delete_static(db_pool.get().await?, infra_id).await? {
infra_caches.remove(&infra_id);
Ok(StatusCode::NO_CONTENT)
} else {
Ok(StatusCode::NOT_FOUND)
}
}
#[derive(Serialize, Deserialize, ToSchema)]
struct InfraPatchForm {
/// The new name to give the infra
pub name: String,
}
impl From<InfraPatchForm> for Changeset<Infra> {
fn from(patch: InfraPatchForm) -> Self {
Infra::changeset().name(patch.name)
}
}
/// Rename an infra
#[utoipa::path(
put, path = "",
tag = "infra",
params(InfraIdParam),
request_body = inline(InfraPatchForm),
responses(
(status = 200, description = "The infra has been renamed", body = Infra),
(status = 404, description = "Infra ID not found"),
),
)]
async fn put(
State(db_pool): State<DbConnectionPoolV2>,
Extension(auth): AuthenticationExt,
Path(infra): Path<i64>,
Json(patch): Json<InfraPatchForm>,
) -> Result<Json<Infra>> {
let authorized = auth
.check_roles([BuiltinRole::InfraWrite].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
let infra_cs: Changeset<Infra> = patch.into();
let infra = infra_cs
.update_or_fail(&mut db_pool.get().await?, infra, || {
InfraApiError::NotFound { infra_id: infra }
})
.await?;
Ok(Json(infra))
}
/// Return the railjson list of switch types
#[utoipa::path(
get, path = "",
tag = "infra",
params(InfraIdParam),
responses(
(status = 200, description = "A list of switch types", body = Vec<SwitchType>),
(status = 404, description = "The infra was not found"),
)
)]
async fn get_switch_types(
State(AppState {
db_pool,
infra_caches,
..
}): State<AppState>,
Extension(auth): AuthenticationExt,
Path(infra): Path<InfraIdParam>,
) -> Result<Json<Vec<SwitchType>>> {
let authorized = auth
.check_roles([BuiltinRole::InfraRead].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
let conn = &mut db_pool.get().await?;
let infra = Infra::retrieve_or_fail(conn, infra.infra_id, || InfraApiError::NotFound {
infra_id: infra.infra_id,
})
.await?;
let infra = InfraCache::get_or_load(conn, &infra_caches, &infra).await?;
Ok(Json(
infra
.switch_types()
.values()
.map(ObjectCache::unwrap_switch_type)
.cloned()
.collect(),
))
}
/// Returns the set of speed limit tags for a given infra
#[utoipa::path(
get, path = "",
tag = "infra",
params(InfraIdParam),
responses(
(status = 200, description = "List all speed limit tags", body = Vec<String>, example = json!(["freight", "heavy_load"])),
(status = 404, description = "The infra was not found"),
)
)]
async fn get_speed_limit_tags(
Extension(auth): AuthenticationExt,
Path(infra): Path<InfraIdParam>,
State(db_pool): State<DbConnectionPoolV2>,
) -> Result<Json<Vec<String>>> {
let authorized = auth
.check_roles([BuiltinRole::InfraRead].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
let conn = &mut db_pool.get().await?;
let infra = Infra::retrieve_or_fail(conn, infra.infra_id, || InfraApiError::NotFound {
infra_id: infra.infra_id,
})
.await?;
let speed_limits_tags = infra.get_speed_limit_tags(conn).await?;
Ok(Json(
speed_limits_tags.into_iter().map(|el| (el.tag)).collect(),
))
}
#[derive(Debug, Clone, Deserialize, IntoParams)]
#[into_params(parameter_in = Query)]
struct GetVoltagesQueryParams {
#[serde(default)]
include_rolling_stock_modes: bool,
}
/// Returns the set of voltages for a given infra and/or rolling_stocks modes.
/// If include_rolling_stocks_modes is true, it returns also rolling_stocks modes.
#[utoipa::path(
get, path = "",
tag = "infra",
params(InfraIdParam, GetVoltagesQueryParams),
responses(
(status = 200, description = "Voltages list", body = Vec<String>, example = json!(["750V", "1500V", "2500.5V"])),
(status = 404, description = "The infra was not found",),
)
)]
async fn get_voltages(
Extension(auth): AuthenticationExt,
Path(infra): Path<InfraIdParam>,
Query(param): Query<GetVoltagesQueryParams>,
State(db_pool): State<DbConnectionPoolV2>,
) -> Result<Json<Vec<String>>> {
let authorized = auth
.check_roles([BuiltinRole::InfraRead].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
let include_rolling_stock_modes = param.include_rolling_stock_modes;
let infra = Infra::retrieve_or_fail(&mut db_pool.get().await?, infra.infra_id, || {
InfraApiError::NotFound {
infra_id: infra.infra_id,
}
})
.await?;
let voltages = infra
.get_voltages(&mut db_pool.get().await?, include_rolling_stock_modes)
.await?;
Ok(Json(voltages.into_iter().map(|el| (el.voltage)).collect()))
}
/// Returns the set of voltages for all infras and rolling_stocks modes.
#[utoipa::path(
get, path = "",
tag = "infra,rolling_stock",
responses(
(status = 200, description = "Voltages list", body = Vec<String>, example = json!(["750V", "1500V", "2500.5V"])),
(status = 404, description = "The infra was not found",),
)
)]
async fn get_all_voltages(
State(db_pool): State<DbConnectionPoolV2>,
Extension(auth): AuthenticationExt,
) -> Result<Json<Vec<String>>> {
let authorized = auth
.check_roles([BuiltinRole::InfraRead].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
let voltages = Infra::get_all_voltages(&mut db_pool.get().await?).await?;
Ok(Json(voltages.into_iter().map(|el| (el.voltage)).collect()))
}
async fn set_locked(infra_id: i64, locked: bool, db_pool: DbConnectionPoolV2) -> Result<()> {
let mut infra = Infra::retrieve_or_fail(&mut db_pool.get().await?, infra_id, || {
InfraApiError::NotFound { infra_id }
})
.await?;
infra.locked = locked;
infra.save(&mut db_pool.get().await?).await
}
/// Lock an infra
#[utoipa::path(
post, path = "",
tag = "infra",
params(InfraIdParam),
responses(
(status = 204, description = "The infra was locked successfully"),
(status = 404, description = "The infra was not found",),
)
)]
async fn lock(
Extension(auth): AuthenticationExt,
Path(infra): Path<InfraIdParam>,
State(db_pool): State<DbConnectionPoolV2>,
) -> Result<impl IntoResponse> {
let authorized = auth
.check_roles([BuiltinRole::InfraWrite].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
set_locked(infra.infra_id, true, db_pool).await?;
Ok(StatusCode::NO_CONTENT)
}
/// Unlock an infra
#[utoipa::path(
post, path = "",
tag = "infra",
params(InfraIdParam),
responses(
(status = 204, description = "The infra was unlocked successfully"),
(status = 404, description = "The infra was not found",),
)
)]
async fn unlock(
Extension(auth): AuthenticationExt,
Path(infra): Path<InfraIdParam>,
State(db_pool): State<DbConnectionPoolV2>,
) -> Result<impl IntoResponse> {
let authorized = auth
.check_roles([BuiltinRole::InfraWrite].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
set_locked(infra.infra_id, false, db_pool).await?;
Ok(StatusCode::NO_CONTENT)
}
/// Instructs Core to load an infra
#[utoipa::path(
post, path = "",
tag = "infra",
params(InfraIdParam),
responses(
(status = 204, description = "The infra was loaded successfully"),
(status = 404, description = "The infra was not found"),
)
)]
async fn load(
State(AppState {
db_pool,
core_client,
..
}): State<AppState>,
Extension(auth): AuthenticationExt,
Path(path): Path<InfraIdParam>,
) -> Result<impl IntoResponse> {
let authorized = auth
.check_roles([BuiltinRole::InfraRead].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
let infra_id = path.infra_id;
let infra = Infra::retrieve_or_fail(&mut db_pool.get().await?, infra_id, || {
InfraApiError::NotFound { infra_id }
})
.await?;
let infra_request = InfraLoadRequest {
infra: infra.id,
expected_version: infra.version,
};
infra_request.fetch(core_client.as_ref()).await?;
Ok(StatusCode::NO_CONTENT)
}
#[derive(Debug, Error, EditoastError)]
#[editoast_error(base_id = "infra_state")]
pub enum InfraStateError {
#[error("Failed to fetch infra state: {0}")]
#[editoast_error(status = 500)]
FetchError(#[from] editoast_osrdyne_client::Error),
}
pub async fn fetch_infra_state(infra_id: i64, osrdyne: &OsrdyneClient) -> Result<InfraState> {
let status = osrdyne
.get_worker_status(&infra_id.to_string())
.await
.map_err(InfraStateError::FetchError)?;
Ok(status.into())
}
pub async fn fetch_all_infra_states(
infras: &[Infra],
osrdyne: &OsrdyneClient,
) -> Result<HashMap<String, InfraState>> {
let ids = infras
.iter()
.map(|infra| infra.id.to_string())
.collect_vec();
let statuses = osrdyne
.get_workers_statuses(&ids)
.await
.map_err(InfraStateError::FetchError)?;
Ok(statuses
.into_iter()
.map(|(id, status)| (id, status.into()))
.collect())
}
#[cfg(test)]
pub mod tests {
use axum::http::StatusCode;
use diesel::sql_query;
use diesel::sql_types::BigInt;
use diesel_async::RunQueryDsl;
use editoast_osrdyne_client::WorkerStatus;
use pretty_assertions::assert_eq;
use rstest::rstest;
use serde_json::json;
use std::ops::DerefMut;
use strum::IntoEnumIterator;
use super::*;
use crate::core::mocking::MockingClient;
use crate::core::CoreClient;
use crate::generated_data;
use crate::infra_cache::operation::create::apply_create_operation;
use crate::models::fixtures::create_empty_infra;
use crate::models::fixtures::create_rolling_stock_with_energy_sources;
use crate::models::fixtures::create_small_infra;
use crate::models::get_geometry_layer_table;
use crate::models::get_table;
use crate::models::infra::DEFAULT_INFRA_VERSION;
use crate::views::test_app::TestApp;
use crate::views::test_app::TestAppBuilder;
use editoast_osrdyne_client::OsrdyneClient;
use editoast_schemas::infra::Electrification;
use editoast_schemas::infra::Speed;
use editoast_schemas::infra::SpeedSection;
use editoast_schemas::infra::SwitchType;
use editoast_schemas::infra::RAILJSON_VERSION;
use editoast_schemas::primitives::ObjectType;
impl TestApp {
fn delete_infra_request(&self, infra_id: i64) -> axum_test::TestRequest {
self.delete(format!("/infra/{infra_id}").as_str())
}
}
#[rstest]
#[serial_test::serial]
async fn infra_clone_empty() {
let app = TestAppBuilder::default_app();
let db_pool = app.db_pool();
let empty_infra = create_empty_infra(&mut db_pool.get_ok()).await;
let request =
app.post(format!("/infra/{}/clone/?name=cloned_infra", empty_infra.id).as_str());
let cloned_infra_id: i64 = app.fetch(request).assert_status(StatusCode::OK).json_into();
let cloned_infra = Infra::retrieve(&mut db_pool.get_ok(), cloned_infra_id)
.await
.unwrap()
.expect("infra was not cloned");
assert_eq!(cloned_infra.name, "cloned_infra");
}
#[derive(QueryableByName)]
struct Count {
#[diesel(sql_type = BigInt)]
nb: i64,
}
#[rstest] // Slow test
#[serial_test::serial]
async fn infra_clone() {
let app = TestAppBuilder::default_app();
let db_pool = app.db_pool();
let small_infra = create_small_infra(&mut db_pool.get_ok()).await;
let small_infra_id = small_infra.id;
let infra_cache = InfraCache::load(&mut db_pool.get_ok(), &small_infra)
.await
.unwrap();
generated_data::refresh_all(db_pool.clone(), small_infra_id, &infra_cache)
.await
.unwrap();
let switch_type = SwitchType {
id: "test_switch_type".into(),
..Default::default()
}
.into();
apply_create_operation(&switch_type, small_infra_id, &mut db_pool.get_ok())
.await
.expect("Failed to create switch_type object");
let req_clone =
app.post(format!("/infra/{}/clone/?name=cloned_infra", small_infra_id).as_str());
let cloned_infra_id: i64 = app
.fetch(req_clone)
.assert_status(StatusCode::OK)
.json_into();
let _cloned_infra = Infra::retrieve(&mut db_pool.get_ok(), cloned_infra_id)
.await
.unwrap()
.expect("infra was not cloned");
let mut tables = vec!["infra_layer_error"];
for object in ObjectType::iter() {
tables.push(get_table(&object));
if let Some(layer_table) = get_geometry_layer_table(&object) {
tables.push(layer_table);
}
}
let mut table_content = HashMap::new();
for table in tables {
for inf_id in [small_infra_id, cloned_infra_id] {
let count_object = sql_query(format!(
"SELECT COUNT (*) as nb from {} where infra_id = $1",
table
))
.bind::<BigInt, _>(inf_id)
.get_result::<Count>(&mut db_pool.get_ok().write().await.deref_mut())
.await
.unwrap();
table_content
.entry(table)
.or_insert_with(Vec::new)
.push(count_object.nb);
}
}
for val in table_content.values() {
// check that with have values for small infra and values for the cloned infra
assert_eq!(val.len(), 2);
// check that we have at least one object in each table to ensure we have something to clone for each table
assert!(val[0] > 0);
// check that we have the same number of objects in each table for both infras
assert_eq!(val[0], val[1]);
}
}
#[rstest]
async fn infra_delete() {
let pool = DbConnectionPoolV2::for_tests_no_transaction();
let app = TestAppBuilder::new()
.db_pool(pool)
.core_client(CoreClient::Mocked(MockingClient::default()))
.build();
let db_pool = app.db_pool();
let empty_infra = create_empty_infra(&mut db_pool.get_ok()).await;
app.fetch(app.delete_infra_request(empty_infra.id))
.assert_status(StatusCode::NO_CONTENT);
app.fetch(app.delete_infra_request(empty_infra.id))
.assert_status(StatusCode::NOT_FOUND);
}
#[rstest]
async fn infra_list() {
let app = TestAppBuilder::default_app();
let request = app.get("/infra/");
app.fetch(request).assert_status(StatusCode::OK);
}
#[rstest]
async fn default_infra_create() {
let app = TestAppBuilder::default_app();
let request = app
.post("/infra")
.json(&json!({ "name": "create_infra_test" }));
let infra: Infra = app
.fetch(request)
.assert_status(StatusCode::CREATED)
.json_into();
assert_eq!(infra.name, "create_infra_test");
assert_eq!(infra.railjson_version, RAILJSON_VERSION);
assert_eq!(infra.version, DEFAULT_INFRA_VERSION);
assert_eq!(infra.generated_version, None);
assert!(!infra.locked);
}
#[rstest]
async fn infra_get() {
let db_pool = DbConnectionPoolV2::for_tests();
let core_client = CoreClient::Mocked(MockingClient::default());
let app = TestAppBuilder::new()
.db_pool(db_pool.clone())
.core_client(core_client)
.build();
let empty_infra = create_empty_infra(&mut db_pool.get_ok()).await;
let req = app.get(format!("/infra/{}", empty_infra.id).as_str());
app.fetch(req).assert_status(StatusCode::OK);
empty_infra.delete(&mut db_pool.get_ok()).await.unwrap();
let req = app.get(format!("/infra/{}", empty_infra.id).as_str());
app.fetch(req).assert_status(StatusCode::NOT_FOUND);
}
#[rstest]
async fn infra_rename() {
let app = TestAppBuilder::default_app();
let db_pool = app.db_pool();
let empty_infra = create_empty_infra(&mut db_pool.get_ok()).await;
let req = app
.put(format!("/infra/{}", empty_infra.id).as_str())
.json(&json!({"name": "rename_test"}));
let infra: Infra = app.fetch(req).assert_status(StatusCode::OK).json_into();