Skip to content

Commit b3b52c5

Browse files
Merge pull request #1029 from tgnottingham/server-cleanup
Miscellaneous `site` crate cleanups
2 parents bdac6bd + 32cdb8e commit b3b52c5

File tree

7 files changed

+170
-224
lines changed

7 files changed

+170
-224
lines changed

site/src/api.rs

Lines changed: 32 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -4,32 +4,8 @@
44
//!
55
//! The responses are calculated in the server.rs file.
66
7-
use database::Benchmark;
8-
use serde::{Deserialize, Serialize};
9-
use std::fmt;
107
use std::result::Result as StdResult;
118

12-
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
13-
pub struct StyledBenchmarkName {
14-
pub name: Benchmark,
15-
pub profile: crate::db::Profile,
16-
}
17-
18-
impl fmt::Display for StyledBenchmarkName {
19-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20-
write!(f, "{}-{}", self.name, self.profile)
21-
}
22-
}
23-
24-
impl Serialize for StyledBenchmarkName {
25-
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
26-
where
27-
S: serde::ser::Serializer,
28-
{
29-
serializer.collect_str(&self)
30-
}
31-
}
32-
339
pub type ServerResult<T> = StdResult<T, String>;
3410

3511
pub mod info {
@@ -65,11 +41,6 @@ pub mod dashboard {
6541
}
6642
}
6743

68-
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
69-
pub struct CommitResponse {
70-
pub commit: Option<String>,
71-
}
72-
7344
pub mod graph {
7445
use collector::Bound;
7546
use serde::{Deserialize, Serialize};
@@ -263,7 +234,38 @@ pub mod self_profile_raw {
263234
pub cids: Vec<i32>,
264235
pub cid: i32,
265236
pub url: String,
266-
pub is_tarball: bool,
237+
}
238+
}
239+
240+
pub mod self_profile_processed {
241+
use serde::{Deserialize, Serialize};
242+
243+
#[derive(Debug, PartialEq, Copy, Clone, Serialize, Deserialize)]
244+
#[serde(rename_all = "lowercase")]
245+
pub enum ProcessorType {
246+
#[serde(rename = "codegen-schedule")]
247+
CodegenSchedule,
248+
Crox,
249+
Flamegraph,
250+
}
251+
252+
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
253+
pub struct Request {
254+
pub commit: String,
255+
pub benchmark: String,
256+
pub run_name: String,
257+
pub cid: Option<i32>,
258+
#[serde(rename = "type")]
259+
pub processor_type: ProcessorType,
260+
#[serde(default, flatten)]
261+
pub params: std::collections::HashMap<String, String>,
262+
}
263+
264+
#[derive(Debug, Clone, Serialize)]
265+
pub struct Response {
266+
pub cids: Vec<i32>,
267+
pub cid: i32,
268+
pub url: String,
267269
}
268270
}
269271

@@ -277,7 +279,6 @@ pub mod self_profile {
277279
pub base_commit: Option<String>,
278280
pub benchmark: String,
279281
pub run_name: String,
280-
281282
pub sort_idx: String,
282283
}
283284

site/src/comparison.rs

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,13 @@ type BoxedError = Box<dyn Error + Send + Sync>;
2222
pub async fn handle_triage(
2323
body: api::triage::Request,
2424
ctxt: &SiteCtxt,
25-
) -> Result<api::triage::Response, BoxedError> {
25+
) -> api::ServerResult<api::triage::Response> {
26+
log::info!("handle_triage({:?})", body);
2627
let start = body.start;
2728
let end = body.end;
28-
let master_commits = collector::master_commits().await?;
29+
let master_commits = collector::master_commits()
30+
.await
31+
.map_err(|e| format!("error retrieving master commit list: {}", e))?;
2932

3033
let start_artifact = ctxt
3134
.artifact_id_for_bound(start.clone(), true)
@@ -47,7 +50,8 @@ pub async fn handle_triage(
4750
&master_commits,
4851
body.calcNewSig.unwrap_or(false),
4952
)
50-
.await?
53+
.await
54+
.map_err(|e| format!("error comparing commits: {}", e))?
5155
{
5256
Some(c) => c,
5357
None => {
@@ -87,8 +91,11 @@ pub async fn handle_triage(
8791
pub async fn handle_compare(
8892
body: api::comparison::Request,
8993
ctxt: &SiteCtxt,
90-
) -> Result<api::comparison::Response, BoxedError> {
91-
let master_commits = collector::master_commits().await?;
94+
) -> api::ServerResult<api::comparison::Response> {
95+
log::info!("handle_compare({:?})", body);
96+
let master_commits = collector::master_commits()
97+
.await
98+
.map_err(|e| format!("error retrieving master commit list: {}", e))?;
9299
let end = body.end;
93100
let comparison = compare_given_commits(
94101
body.start,
@@ -98,7 +105,8 @@ pub async fn handle_compare(
98105
&master_commits,
99106
body.calcNewSig.unwrap_or(false),
100107
)
101-
.await?
108+
.await
109+
.map_err(|e| format!("error comparing commits: {}", e))?
102110
.ok_or_else(|| format!("could not find end commit for bound {:?}", end))?;
103111

104112
let conn = ctxt.conn().await;

site/src/request_handlers.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ pub use github::handle_github;
1212
pub use graph::{handle_graph, handle_graph_new};
1313
pub use next_commit::handle_next_commit;
1414
pub use self_profile::{
15-
get_self_profile_raw, handle_self_profile, handle_self_profile_processed_download,
16-
handle_self_profile_raw, handle_self_profile_raw_download,
15+
handle_self_profile, handle_self_profile_processed_download, handle_self_profile_raw,
16+
handle_self_profile_raw_download,
1717
};
1818
pub use status_page::handle_status_page;
1919

site/src/request_handlers/github.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ pub async fn handle_github(
2424
request: github::Request,
2525
ctxt: Arc<SiteCtxt>,
2626
) -> ServerResult<github::Response> {
27+
log::info!("handle_github({:?})", request);
2728
if request.comment.body.contains(" homu: ") {
2829
if let Some(sha) = parse_homu_comment(&request.comment.body).await {
2930
enqueue_sha(request.issue, &ctxt, sha).await?;

site/src/request_handlers/self_profile.rs

Lines changed: 36 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,30 @@
1-
use std::collections::{HashMap, HashSet};
1+
use std::collections::HashSet;
22
use std::io::Read;
33
use std::sync::Arc;
44
use std::time::{Duration, Instant};
55

66
use bytes::Buf;
77
use headers::{ContentType, Header};
88
use hyper::StatusCode;
9-
use log::error;
109

11-
use crate::api::{self_profile, self_profile_raw, ServerResult};
10+
use crate::api::{self_profile, self_profile_processed, self_profile_raw, ServerResult};
1211
use crate::db::ArtifactId;
1312
use crate::load::SiteCtxt;
1413
use crate::selector::{self, Tag};
15-
use crate::server::{Request, Response, ResponseHeaders};
14+
use crate::server::{Response, ResponseHeaders};
1615

1716
pub async fn handle_self_profile_processed_download(
18-
body: self_profile_raw::Request,
19-
mut params: HashMap<String, String>,
17+
body: self_profile_processed::Request,
2018
ctxt: &SiteCtxt,
2119
) -> http::Response<hyper::Body> {
20+
log::info!("handle_self_profile_processed_download({:?})", body);
21+
let mut params = body.params.clone();
2222
let diff_against = params.remove("base_commit");
23-
if params
24-
.get("type")
25-
.map_or(false, |t| t != "codegen-schedule")
23+
24+
if body.processor_type != self_profile_processed::ProcessorType::CodegenSchedule
2625
&& diff_against.is_some()
2726
{
28-
let mut resp = Response::new("Only codegen_schedule supports diffing right now.".into());
27+
let mut resp = Response::new("Only codegen-schedule supports diffing right now.".into());
2928
*resp.status_mut() = StatusCode::BAD_REQUEST;
3029
return resp;
3130
}
@@ -75,7 +74,17 @@ pub async fn handle_self_profile_processed_download(
7574
None
7675
};
7776

78-
let data = match handle_self_profile_raw(body, ctxt).await {
77+
let data = match handle_self_profile_raw(
78+
self_profile_raw::Request {
79+
commit: body.commit,
80+
benchmark: body.benchmark.clone(),
81+
run_name: body.run_name.clone(),
82+
cid: body.cid,
83+
},
84+
ctxt,
85+
)
86+
.await
87+
{
7988
Ok(v) => match get_self_profile_raw_data(&v.url).await {
8089
Ok(v) => v,
8190
Err(e) => return e,
@@ -89,15 +98,16 @@ pub async fn handle_self_profile_processed_download(
8998

9099
log::trace!("got data in {:?}", start.elapsed());
91100

92-
let output = match crate::self_profile::generate(&title, base_data, data, params) {
93-
Ok(c) => c,
94-
Err(e) => {
95-
log::error!("Failed to generate json {:?}", e);
96-
let mut resp = http::Response::new(format!("{:?}", e).into());
97-
*resp.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
98-
return resp;
99-
}
100-
};
101+
let output =
102+
match crate::self_profile::generate(&title, body.processor_type, base_data, data, params) {
103+
Ok(c) => c,
104+
Err(e) => {
105+
log::error!("Failed to generate json {:?}", e);
106+
let mut resp = http::Response::new(format!("{:?}", e).into());
107+
*resp.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
108+
return resp;
109+
}
110+
};
101111
let mut builder = http::Response::builder()
102112
.header_typed(if output.filename.ends_with("json") {
103113
ContentType::json()
@@ -390,9 +400,9 @@ pub async fn handle_self_profile_raw_download(
390400
body: self_profile_raw::Request,
391401
ctxt: &SiteCtxt,
392402
) -> http::Response<hyper::Body> {
393-
let res = handle_self_profile_raw(body, ctxt).await;
394-
let (url, is_tarball) = match res {
395-
Ok(v) => (v.url, v.is_tarball),
403+
log::info!("handle_self_profile_raw_download({:?})", body);
404+
let url = match handle_self_profile_raw(body, ctxt).await {
405+
Ok(v) => v.url,
396406
Err(e) => {
397407
let mut resp = http::Response::new(e.into());
398408
*resp.status_mut() = StatusCode::BAD_REQUEST;
@@ -427,75 +437,16 @@ pub async fn handle_self_profile_raw_download(
427437
.insert(hyper::header::CONTENT_TYPE, header.pop().unwrap());
428438
server_resp.headers_mut().insert(
429439
hyper::header::CONTENT_DISPOSITION,
430-
hyper::header::HeaderValue::from_maybe_shared(format!(
431-
"attachment; filename=\"{}\"",
432-
if is_tarball {
433-
"self-profile.tar"
434-
} else {
435-
"self-profile.mm_profdata"
436-
}
437-
))
440+
hyper::header::HeaderValue::from_maybe_shared(
441+
"attachment; filename=\"self-profile.mm_profdata\"",
442+
)
438443
.expect("valid header"),
439444
);
440445
*server_resp.status_mut() = StatusCode::OK;
441446
tokio::spawn(tarball(resp, sender));
442447
server_resp
443448
}
444449

445-
pub fn get_self_profile_raw(
446-
req: &Request,
447-
) -> Result<(HashMap<String, String>, self_profile_raw::Request), http::Response<hyper::Body>> {
448-
// FIXME: how should this look?
449-
let url = match url::Url::parse(&format!("http://example.com{}", req.uri())) {
450-
Ok(v) => v,
451-
Err(e) => {
452-
error!("failed to parse url {}: {:?}", req.uri(), e);
453-
return Err(http::Response::builder()
454-
.header_typed(ContentType::text_utf8())
455-
.status(StatusCode::BAD_REQUEST)
456-
.body(hyper::Body::from(format!(
457-
"failed to parse url {}: {:?}",
458-
req.uri(),
459-
e
460-
)))
461-
.unwrap());
462-
}
463-
};
464-
let mut parts = url
465-
.query_pairs()
466-
.into_owned()
467-
.collect::<HashMap<String, String>>();
468-
macro_rules! key_or_error {
469-
($ident:ident) => {
470-
if let Some(v) = parts.remove(stringify!($ident)) {
471-
v
472-
} else {
473-
error!(
474-
"failed to deserialize request {}: missing {} in query string",
475-
req.uri(),
476-
stringify!($ident)
477-
);
478-
return Err(http::Response::builder()
479-
.header_typed(ContentType::text_utf8())
480-
.status(StatusCode::BAD_REQUEST)
481-
.body(hyper::Body::from(format!(
482-
"failed to deserialize request {}: missing {} in query string",
483-
req.uri(),
484-
stringify!($ident)
485-
)))
486-
.unwrap());
487-
}
488-
};
489-
}
490-
let request = self_profile_raw::Request {
491-
commit: key_or_error!(commit),
492-
benchmark: key_or_error!(benchmark),
493-
run_name: key_or_error!(run_name),
494-
cid: None,
495-
};
496-
return Ok((parts, request));
497-
}
498-
499450
async fn tarball(resp: reqwest::Response, mut sender: hyper::body::Sender) {
500451
// Ideally, we would stream the response though the snappy decoding, but
501452
// snappy doesn't support that AFAICT -- we'd need it to implement AsyncRead
@@ -615,7 +566,6 @@ pub async fn handle_self_profile_raw(
615566
cids: cids.to_vec(),
616567
cid,
617568
url,
618-
is_tarball: false,
619569
})
620570
}
621571
}

site/src/self_profile.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ mod codegen_schedule;
88
pub mod crox;
99
pub mod flamegraph;
1010

11+
pub type ProcessorType = crate::api::self_profile_processed::ProcessorType;
12+
1113
pub struct Output {
1214
pub data: Vec<u8>,
1315
pub filename: &'static str,
@@ -16,13 +18,13 @@ pub struct Output {
1618

1719
pub fn generate(
1820
title: &str,
21+
processor_type: ProcessorType,
1922
self_profile_base_data: Option<Vec<u8>>,
2023
self_profile_data: Vec<u8>,
21-
mut params: HashMap<String, String>,
24+
params: HashMap<String, String>,
2225
) -> anyhow::Result<Output> {
23-
let removed = params.remove("type");
24-
match removed.as_deref() {
25-
Some("crox") => {
26+
match processor_type {
27+
ProcessorType::Crox => {
2628
let opt = serde_json::from_str(&serde_json::to_string(&params).unwrap())
2729
.context("crox opts")?;
2830
Ok(Output {
@@ -31,7 +33,7 @@ pub fn generate(
3133
is_download: true,
3234
})
3335
}
34-
Some("flamegraph") => {
36+
ProcessorType::Flamegraph => {
3537
let opt = serde_json::from_str(&serde_json::to_string(&params).unwrap())
3638
.context("flame opts")?;
3739
Ok(Output {
@@ -40,7 +42,7 @@ pub fn generate(
4042
is_download: false,
4143
})
4244
}
43-
Some("codegen-schedule") => {
45+
ProcessorType::CodegenSchedule => {
4446
let opt =
4547
serde_json::from_str(&serde_json::to_string(&params).unwrap()).context("params")?;
4648
Ok(Output {

0 commit comments

Comments
 (0)