Skip to content
This repository has been archived by the owner on Nov 6, 2020. It is now read-only.

Commit

Permalink
purge unwrap from dapps server
Browse files Browse the repository at this point in the history
  • Loading branch information
rphmeier committed Oct 20, 2016
1 parent 2a3487b commit 3af2a67
Show file tree
Hide file tree
Showing 12 changed files with 62 additions and 30 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions dapps/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ ethcore-util = { path = "../util" }
fetch = { path = "../util/fetch" }
parity-ui = { path = "./ui" }
parity-dapps-glue = { path = "./js-glue" }
mime = "0.2"
### DEPRECATED
parity-dapps = { git = "https://github.com/ethcore/parity-ui.git", version = "1.4" }
parity-dapps-home = { git = "https://github.com/ethcore/parity-ui.git", version = "1.4" }
Expand Down
1 change: 1 addition & 0 deletions dapps/js-glue/src/lib.rs.in
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ use std::default::Default;
pub struct File {
pub path: &'static str,
pub content: &'static [u8],
// TODO: use strongly-typed MIME.
pub content_type: &'static str,
}

Expand Down
12 changes: 8 additions & 4 deletions dapps/src/api/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,16 @@ use serde_json;
use endpoint::Handler;
use handlers::{ContentHandler, EchoHandler};

pub fn as_json<T : Serialize>(val: &T) -> Box<Handler> {
Box::new(ContentHandler::ok(serde_json::to_string(val).unwrap(), "application/json".to_owned()))
pub fn as_json<T: Serialize>(val: &T) -> Box<Handler> {
let json = serde_json::to_string(val)
.expect("serialization to string is infallible; qed");
Box::new(ContentHandler::ok(json, mime!(Application/Json)))
}

pub fn as_json_error<T : Serialize>(val: &T) -> Box<Handler> {
Box::new(ContentHandler::not_found(serde_json::to_string(val).unwrap(), "application/json".to_owned()))
pub fn as_json_error<T: Serialize>(val: &T) -> Box<Handler> {
let json = serde_json::to_string(val)
.expect("serialization to string is infallible; qed");
Box::new(ContentHandler::not_found(json, mime!(Application/Json)))
}

pub fn ping_response(local_domain: &str) -> Box<Handler> {
Expand Down
7 changes: 4 additions & 3 deletions dapps/src/apps/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,10 @@ impl ContentCache {
}

let mut removed = Vec::with_capacity(len - expected_size);
while len > expected_size {
let entry = self.cache.pop_front().unwrap();

while self.cache.len() > expected_size {
let entry = self.cache.pop_front().expect("expected_size bounded at 0, len is greater; qed");

match entry.1 {
ContentStatus::Fetching(ref fetch) => {
trace!(target: "dapps", "Aborting {} because of limit.", entry.0);
Expand All @@ -73,7 +75,6 @@ impl ContentCache {
}

removed.push(entry);
len -= 1;
}
removed
}
Expand Down
6 changes: 3 additions & 3 deletions dapps/src/apps/urlhint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,9 @@ impl URLHintContract {
}

let mut it = vec.into_iter();
let account_slash_repo = it.next().unwrap();
let commit = it.next().unwrap();
let owner = it.next().unwrap();
let account_slash_repo = it.next().expect("element 0 of 3-len vector known to exist; qed");
let commit = it.next().expect("element 1 of 3-len vector known to exist; qed");
let owner = it.next().expect("element 2 of 3-len vector known to exist qed");

match (account_slash_repo, commit, owner) {
(Token::String(account_slash_repo), Token::FixedBytes(commit), Token::Address(owner)) => {
Expand Down
15 changes: 8 additions & 7 deletions dapps/src/handlers/content.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use std::io::Write;
use hyper::{header, server, Decoder, Encoder, Next};
use hyper::net::HttpStream;
use hyper::mime::Mime;
use hyper::status::StatusCode;

use util::version;
Expand All @@ -29,22 +30,22 @@ use handlers::add_security_headers;
pub struct ContentHandler {
code: StatusCode,
content: String,
mimetype: String,
mimetype: Mime,
write_pos: usize,
safe_to_embed_at_port: Option<u16>,
}

impl ContentHandler {
pub fn ok(content: String, mimetype: String) -> Self {
pub fn ok(content: String, mimetype: Mime) -> Self {
Self::new(StatusCode::Ok, content, mimetype)
}

pub fn not_found(content: String, mimetype: String) -> Self {
pub fn not_found(content: String, mimetype: Mime) -> Self {
Self::new(StatusCode::NotFound, content, mimetype)
}

pub fn html(code: StatusCode, content: String, embeddable_at: Option<u16>) -> Self {
Self::new_embeddable(code, content, "text/html".into(), embeddable_at)
Self::new_embeddable(code, content, mime!(Text/Html), embeddable_at)
}

pub fn error(code: StatusCode, title: &str, message: &str, details: Option<&str>) -> Self {
Expand All @@ -61,11 +62,11 @@ impl ContentHandler {
), embeddable_at)
}

pub fn new(code: StatusCode, content: String, mimetype: String) -> Self {
pub fn new(code: StatusCode, content: String, mimetype: Mime) -> Self {
Self::new_embeddable(code, content, mimetype, None)
}

pub fn new_embeddable(code: StatusCode, content: String, mimetype: String, embeddable_at: Option<u16>) -> Self {
pub fn new_embeddable(code: StatusCode, content: String, mimetype: Mime, embeddable_at: Option<u16>) -> Self {
ContentHandler {
code: code,
content: content,
Expand All @@ -87,7 +88,7 @@ impl server::Handler<HttpStream> for ContentHandler {

fn on_response(&mut self, res: &mut server::Response) -> Next {
res.set_status(self.code);
res.headers_mut().set(header::ContentType(self.mimetype.parse().unwrap()));
res.headers_mut().set(header::ContentType(self.mimetype.clone()));
add_security_headers(&mut res.headers_mut(), self.safe_to_embed_at_port.clone());
Next::write()
}
Expand Down
12 changes: 8 additions & 4 deletions dapps/src/handlers/echo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ impl server::Handler<HttpStream> for EchoHandler {

// Don't even read the payload if origin is forbidden!
if let Cors::Forbidden = self.cors {
self.handler = Some(ContentHandler::ok(String::new(), "text/plain".into()));
self.handler = Some(ContentHandler::ok(String::new(), mime!(Text/Plain)));
Next::write()
} else {
Next::read()
Expand All @@ -92,7 +92,7 @@ impl server::Handler<HttpStream> for EchoHandler {
fn on_request_readable(&mut self, decoder: &mut Decoder<HttpStream>) -> Next {
match decoder.read_to_string(&mut self.content) {
Ok(0) => {
self.handler = Some(ContentHandler::ok(self.content.clone(), "application/json".into()));
self.handler = Some(ContentHandler::ok(self.content.clone(), mime!(Application/Json)));
Next::write()
},
Ok(_) => Next::read(),
Expand All @@ -114,11 +114,15 @@ impl server::Handler<HttpStream> for EchoHandler {
]));
headers.set(header::AccessControlAllowOrigin::Value(domain.clone()));
}
self.handler.as_mut().unwrap().on_response(res)
self.handler.as_mut()
.expect("handler always set in on_request, which is before now; qed")
.on_response(res)
}

fn on_response_writable(&mut self, encoder: &mut Encoder<HttpStream>) -> Next {
self.handler.as_mut().unwrap().on_response_writable(encoder)
self.handler.as_mut()
.expect("handler always set in on_request, which is before now; qed")
.on_response_writable(encoder)
}
}

Expand Down
11 changes: 8 additions & 3 deletions dapps/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,8 @@
#![warn(missing_docs)]
#![cfg_attr(feature="nightly", plugin(clippy))]

#[macro_use]
extern crate log;
extern crate url as url_lib;
extern crate hyper;
extern crate url as url_lib;
extern crate unicase;
extern crate serde;
extern crate serde_json;
Expand All @@ -61,6 +59,13 @@ extern crate ethcore_rpc;
extern crate ethcore_util as util;
extern crate linked_hash_map;
extern crate fetch;

#[macro_use]
extern crate log;

#[macro_use]
extern crate mime;

#[cfg(test)]
extern crate ethcore_devtools as devtools;

Expand Down
8 changes: 7 additions & 1 deletion dapps/src/page/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,13 @@ impl<T: Dapp> server::Handler<HttpStream> for PageHandler<T> {
match self.file {
ServedFile::File(ref f) => {
res.set_status(StatusCode::Ok);
res.headers_mut().set(header::ContentType(f.content_type().parse().unwrap()));


match f.content_type().parse() {
Ok(mime) => res.headers_mut().set(header::ContentType(mime)),
Err(()) => debug!(target: "page_handler", "invalid MIME type: {}", f.content_type()),
}

// Security headers:
add_security_headers(&mut res.headers_mut(), self.safe_to_embed_at_port);
Next::write()
Expand Down
2 changes: 1 addition & 1 deletion dapps/src/proxypac.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ function FindProxyForURL(url, host) {{
}}
"#,
DAPPS_DOMAIN, path.host, path.port);
Box::new(ContentHandler::ok(content, "application/javascript".to_owned()))
Box::new(ContentHandler::ok(content, mime!(Application/Javascript)))
}
}

Expand Down
16 changes: 12 additions & 4 deletions dapps/src/router/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,15 @@ impl<A: Authorization + 'static> server::Handler<HttpStream> for Router<A> {
self.handler = match endpoint {
// First check special endpoints
(ref path, ref endpoint) if self.special.contains_key(endpoint) => {
self.special.get(endpoint).unwrap().to_async_handler(path.clone().unwrap_or_default(), control)
self.special.get(endpoint)
.expect("special known to contain key; qed")
.to_async_handler(path.clone().unwrap_or_default(), control)
},
// Then delegate to dapp
(Some(ref path), _) if self.endpoints.contains_key(&path.app_id) => {
self.endpoints.get(&path.app_id).unwrap().to_async_handler(path.clone(), control)
self.endpoints.get(&path.app_id)
.expect("special known to contain key; qed")
.to_async_handler(path.clone(), control)
},
// Try to resolve and fetch the dapp
(Some(ref path), _) if self.fetch.contains(&path.app_id) => {
Expand All @@ -108,7 +112,9 @@ impl<A: Authorization + 'static> server::Handler<HttpStream> for Router<A> {
},
// RPC by default
_ => {
self.special.get(&SpecialEndpoint::Rpc).unwrap().to_async_handler(EndpointPath::default(), control)
self.special.get(&SpecialEndpoint::Rpc)
.expect("RPC endpoint always stored; qed")
.to_async_handler(EndpointPath::default(), control)
}
};

Expand Down Expand Up @@ -143,7 +149,9 @@ impl<A: Authorization> Router<A> {
allowed_hosts: Option<Vec<String>>,
) -> Self {

let handler = special.get(&SpecialEndpoint::Utils).unwrap().to_handler(EndpointPath::default());
let handler = special.get(&SpecialEndpoint::Utils)
.expect("Utils endpoint always stored; qed")
.to_handler(EndpointPath::default());
Router {
control: Some(control),
main_page: main_page,
Expand Down

0 comments on commit 3af2a67

Please sign in to comment.