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
|
#[macro_use]
extern crate rocket;
use futures::{future::TryFutureExt, stream::TryStreamExt};
use rocket::fairing::{self, AdHoc};
use rocket::response::status::NotFound;
use rocket::serde::json::Json;
use rocket::{futures, Build, Rocket};
use rocket_db_pools::{sqlx, Connection, Database};
use utoipa::OpenApi;
use utoipa_swagger_ui::SwaggerUi;
mod api_model;
mod auth;
use auth::AuthApiAddon;
#[derive(Database)]
#[database("eyeballs")]
struct Db(sqlx::MySqlPool);
#[derive(OpenApi)]
#[openapi(
paths(projects, project, reviews, review,),
modifiers(&AuthApiAddon),
)]
pub struct MainApi;
enum Role {
Reviewer,
Watcher,
}
struct UserRole {
user: api_model::User,
role: Role,
}
impl TryFrom<u8> for Role {
type Error = &'static str;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(Role::Reviewer),
1 => Ok(Role::Watcher),
_ => Err("Invalid role"),
}
}
}
impl TryFrom<u8> for api_model::ReviewState {
type Error = &'static str;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(api_model::ReviewState::Draft),
1 => Ok(api_model::ReviewState::Open),
2 => Ok(api_model::ReviewState::Dropped),
3 => Ok(api_model::ReviewState::Closed),
_ => Err("Invalid review state"),
}
}
}
#[utoipa::path(
responses(
(status = 200, description = "Get all projects", body = api_model::Projects),
),
security(
("session" = []),
),
)]
#[get("/projects?<limit>&<offset>")]
async fn projects<'r>(
mut db: Connection<Db>,
_session: auth::Session,
limit: Option<u32>,
offset: Option<u32>,
) -> Json<api_model::Projects> {
let uw_offset = offset.unwrap_or(0);
let uw_limit = limit.unwrap_or(10);
let entries = sqlx::query!(
"SELECT id,title FROM projects ORDER BY title,id LIMIT ? OFFSET ?",
uw_limit,
uw_offset
)
.fetch(&mut **db)
.map_ok(|r| api_model::ProjectEntry {
id: r.id,
title: r.title,
})
.try_collect::<Vec<_>>()
.await
.unwrap();
let count = sqlx::query!("SELECT COUNT(id) AS count FROM projects")
.fetch_one(&mut **db)
.map_ok(|r| r.count)
.await
.unwrap();
let u32_count = u32::try_from(count).unwrap();
Json(api_model::Projects {
offset: uw_offset,
limit: uw_limit,
total_count: u32_count,
more: uw_offset + uw_limit < u32_count,
projects: entries,
})
}
#[utoipa::path(
responses(
(status = 200, description = "Get project", body = api_model::Project),
(status = 404, description = "No such project"),
),
security(
("session" = []),
),
)]
#[get("/project/<projectid>")]
async fn project<'r>(
mut db: Connection<Db>,
_session: auth::Session,
projectid: u64,
) -> Result<Json<api_model::Project>, NotFound<&'static str>> {
let members = sqlx::query!(
"SELECT id, username, name, active FROM users JOIN project_users ON project_users.user=users.id WHERE project_users.project=?",
projectid)
.fetch(&mut **db)
.map_ok(|r| api_model::User {
id: r.id,
username: r.username,
name: r.name,
active: r.active != 0,
})
.try_collect::<Vec<_>>()
.await
.unwrap();
let project = sqlx::query!(
"SELECT id,title,description FROM projects WHERE id=?",
projectid
)
.fetch_one(&mut **db)
.map_ok(|r| api_model::Project {
id: r.id,
title: r.title,
description: r.description,
members: members,
})
.map_err(|_| NotFound("No such project"))
.await?;
Ok(Json(project))
}
#[utoipa::path(
responses(
(status = 200, description = "Get all reviews for project", body = api_model::Reviews),
),
security(
("session" = []),
),
)]
#[get("/project/<projectid>/reviews?<limit>&<offset>")]
async fn reviews<'r>(
mut db: Connection<Db>,
_session: auth::Session,
projectid: u64,
limit: Option<u32>,
offset: Option<u32>,
) -> Json<api_model::Reviews> {
let uw_offset = offset.unwrap_or(0);
let uw_limit = limit.unwrap_or(10);
let entries = sqlx::query!(
"SELECT reviews.id AS id,title,state,progress,users.id AS user_id,users.username AS username,users.name AS name,users.active AS user_active FROM reviews JOIN users ON users.id=owner WHERE project=? ORDER BY id DESC LIMIT ? OFFSET ?",
projectid, uw_limit, uw_offset)
.fetch(&mut **db)
.map_ok(|r| api_model::ReviewEntry {
id: r.id,
title: r.title,
owner: api_model::User {
id: r.user_id,
username: r.username,
name: r.name,
active: r.user_active != 0,
},
state: api_model::ReviewState::try_from(r.state).unwrap(),
progress: r.progress,
})
.try_collect::<Vec<_>>()
.await
.unwrap();
let count = sqlx::query!(
"SELECT COUNT(id) AS count FROM reviews WHERE project=?",
projectid
)
.fetch_one(&mut **db)
.map_ok(|r| r.count)
.await
.unwrap();
let u32_count = u32::try_from(count).unwrap();
Json(api_model::Reviews {
offset: uw_offset,
limit: uw_limit,
total_count: u32_count,
more: uw_offset + uw_limit < u32_count,
reviews: entries,
})
}
#[utoipa::path(
responses(
(status = 200, description = "Get review", body = api_model::Review),
(status = 404, description = "No such review"),
),
security(
("session" = []),
),
)]
#[get("/review/<reviewid>")]
async fn review<'r>(
mut db: Connection<Db>,
_session: auth::Session,
reviewid: u64,
) -> Result<Json<api_model::Review>, NotFound<&'static str>> {
let mut users = sqlx::query!(
"SELECT id,username,name,active,review_users.role AS role FROM users JOIN review_users ON review_users.user=id WHERE review_users.review=? ORDER BY role,username,id",
reviewid)
.fetch(&mut **db)
.map_ok(|r| UserRole {
user: api_model::User {
id: r.id,
username: r.username,
name: r.name,
active: r.active != 0,
},
role: Role::try_from(r.role).unwrap(),
})
.try_collect::<Vec<_>>()
.await
.unwrap();
let first_reviewer = users
.iter()
.position(|u| matches!(u.role, Role::Reviewer))
.unwrap_or(users.len());
let mut reviewers: Vec<api_model::User> = Vec::with_capacity(first_reviewer);
for user_role in users.drain(0..first_reviewer) {
reviewers.push(user_role.user);
}
let mut watchers: Vec<api_model::User> = Vec::with_capacity(users.len());
for user_role in users.drain(0..) {
watchers.push(user_role.user);
}
let review = sqlx::query!(
"SELECT reviews.id AS id,title,description,state,progress,users.id AS user_id,users.username AS username,users.name AS name,users.active AS user_active FROM reviews JOIN users ON users.id=owner WHERE reviews.id=?",
reviewid)
.fetch_one(&mut **db)
.map_ok(|r| api_model::Review {
id: r.id,
title: r.title,
description: r.description,
owner: api_model::User {
id: r.user_id,
username: r.username,
name: r.name,
active: r.user_active != 0,
},
reviewers: reviewers,
watchers: watchers,
state: api_model::ReviewState::try_from(r.state).unwrap(),
progress: r.progress,
})
.map_err(|_| NotFound("No such review"))
.await?;
Ok(Json(review))
}
async fn run_migrations(rocket: Rocket<Build>) -> fairing::Result {
match Db::fetch(&rocket) {
Some(db) => match sqlx::migrate!("./migrations").run(&**db).await {
Ok(_) => Ok(rocket),
Err(e) => {
error!("Failed to initialize database: {}", e);
Err(rocket)
}
},
None => Err(rocket),
}
}
#[rocket::main]
async fn main() -> Result<(), rocket::Error> {
let basepath = "/api/v1";
let mut api = MainApi::openapi();
api.merge(auth::AuthApi::openapi());
api.servers = Some(vec![utoipa::openapi::ServerBuilder::new()
.url(basepath)
.build()]);
let _rocket = rocket::build()
.attach(Db::init())
.attach(AdHoc::try_on_ignite("Database Migrations", run_migrations))
.mount(basepath, routes![projects, project, reviews, review])
.mount(
"/",
SwaggerUi::new("/openapi/ui/<_..>").url("/openapi/openapi.json", api),
)
.attach(auth::stage(basepath))
.launch()
.await?;
Ok(())
}
|