-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathattached.rs
162 lines (145 loc) · 4.71 KB
/
attached.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
use std::collections::HashMap;
use axum::extract::Json;
use axum::extract::Path;
use axum::extract::State;
use axum::Extension;
use editoast_authz::BuiltinRole;
use editoast_derive::EditoastError;
use serde::Deserialize;
use thiserror::Error;
use crate::error::Result;
use crate::infra_cache::InfraCache;
use crate::models::prelude::*;
use crate::models::Infra;
use crate::views::infra::InfraApiError;
use crate::views::AuthenticationExt;
use crate::views::AuthorizationError;
use crate::AppState;
use editoast_schemas::primitives::ObjectType;
crate::routes! {
"/attached/{track_id}" => attached,
}
/// Objects types that can be attached to a track
const ATTACHED_OBJECTS_TYPES: &[ObjectType] = &[
ObjectType::Signal,
ObjectType::SpeedSection,
ObjectType::Detector,
ObjectType::Switch,
ObjectType::BufferStop,
ObjectType::OperationalPoint,
ObjectType::Electrification,
];
#[derive(Debug, Error, EditoastError)]
#[editoast_error(base_id = "attached")]
enum AttachedError {
#[error("Track '{track_id}' not found")]
#[editoast_error(status = 404)]
TrackNotFound { track_id: String },
}
#[derive(utoipa::IntoParams, Deserialize)]
struct InfraAttachedParams {
/// An infra ID
infra_id: i64,
/// A track section ID
track_id: String,
}
/// Retrieve all objects attached to a given track
#[utoipa::path(
get, path = "",
tag = "infra",
params(InfraAttachedParams),
responses(
(
status = 200,
body = inline(HashMap<ObjectType, Vec<String>>),
description = "All objects attached to the given track (arranged by types)"
),
),
)]
async fn attached(
Path(InfraAttachedParams { infra_id, track_id }): Path<InfraAttachedParams>,
State(AppState {
infra_caches,
db_pool,
..
}): State<AppState>,
Extension(auth): AuthenticationExt,
) -> Result<Json<HashMap<ObjectType, Vec<String>>>> {
let authorized = auth
.check_roles([BuiltinRole::InfraRead].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Forbidden.into());
}
let mut conn = db_pool.get().await?;
// TODO: lock for share
let infra =
Infra::retrieve_or_fail(&mut conn, infra_id, || InfraApiError::NotFound { infra_id })
.await?;
let infra_cache = InfraCache::get_or_load(&mut conn, &infra_caches, &infra).await?;
// Check track existence
if !infra_cache.track_sections().contains_key(&track_id) {
return Err(AttachedError::TrackNotFound {
track_id: track_id.clone(),
}
.into());
}
// Get attached objects
let res: HashMap<_, Vec<_>> = ATTACHED_OBJECTS_TYPES
.iter()
.map(|obj_type| {
(
*obj_type,
infra_cache
.get_track_refs_type(&track_id, *obj_type)
.into_iter()
.map(|obj_ref| obj_ref.obj_id.clone())
.collect(),
)
})
.collect();
Ok(Json(res))
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use rstest::rstest;
use crate::infra_cache::operation::create::apply_create_operation;
use crate::models::prelude::*;
use crate::models::Infra;
use crate::views::test_app::TestAppBuilder;
use editoast_schemas::infra::Detector;
use editoast_schemas::infra::TrackSection;
use editoast_schemas::primitives::OSRDIdentified;
use editoast_schemas::primitives::ObjectType;
#[rstest]
async fn get_attached_detector() {
let app = TestAppBuilder::default_app();
let pool = app.db_pool();
// Create empty infra
let empty_infra = Infra::changeset()
.name("test_infra".to_owned())
.last_railjson_version()
.create(&mut pool.get_ok())
.await
.expect("Failed to create infra");
// Create a track and a detector on it
let track = TrackSection::default().into();
apply_create_operation(&track, empty_infra.id, &mut pool.get_ok())
.await
.expect("Failed to create track object");
let detector = Detector {
track: track.get_id().clone().into(),
..Default::default()
}
.into();
apply_create_operation(&detector, empty_infra.id, &mut pool.get_ok())
.await
.expect("Failed to create detector object");
let req =
app.get(format!("/infra/{}/attached/{}/", empty_infra.id, track.get_id()).as_str());
let response: HashMap<ObjectType, Vec<String>> = app.fetch(req).json_into();
assert_eq!(response.get(&ObjectType::Detector).unwrap().len(), 1);
}
}