Run cargo fmt on the whole code base (#9394)

* Run cargo fmt on the whole code base

* Second run

* Add CI check

* Fix compilation

* More unnecessary braces

* Handle weights

* Use --all

* Use correct attributes...

* Fix UI tests

* AHHHHHHHHH

* 🤦

* Docs

* Fix compilation

* 🤷

* Please stop

* 🤦 x 2

* More

* make rustfmt.toml consistent with polkadot

Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
Bastian Köcher
2021-07-21 16:32:32 +02:00
committed by GitHub
parent d451c38c1c
commit 7b56ab15b4
1010 changed files with 53339 additions and 51208 deletions
+213 -201
View File
@@ -28,16 +28,22 @@
//! actively calling any function.
use crate::api::timestamp;
use bytes::buf::ext::{Reader, BufExt};
use bytes::buf::ext::{BufExt, Reader};
use fnv::FnvHashMap;
use futures::{prelude::*, future, channel::mpsc};
use log::error;
use sp_core::offchain::{HttpRequestId, Timestamp, HttpRequestStatus, HttpError};
use std::{convert::TryFrom, fmt, io::Read as _, pin::Pin, task::{Context, Poll}};
use sp_utils::mpsc::{tracing_unbounded, TracingUnboundedSender, TracingUnboundedReceiver};
use std::sync::Arc;
use hyper::{Client as HyperClient, Body, client};
use futures::{channel::mpsc, future, prelude::*};
use hyper::{client, Body, Client as HyperClient};
use hyper_rustls::HttpsConnector;
use log::error;
use sp_core::offchain::{HttpError, HttpRequestId, HttpRequestStatus, Timestamp};
use sp_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver, TracingUnboundedSender};
use std::{
convert::TryFrom,
fmt,
io::Read as _,
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
/// Wrapper struct used for keeping the hyper_rustls client running.
#[derive(Clone)]
@@ -63,12 +69,8 @@ pub fn http(shared_client: SharedClient) -> (HttpApi, HttpWorker) {
requests: FnvHashMap::default(),
};
let engine = HttpWorker {
to_api,
from_api,
http_client: shared_client.0,
requests: Vec::new(),
};
let engine =
HttpWorker { to_api, from_api, http_client: shared_client.0, requests: Vec::new() };
(api, engine)
}
@@ -127,11 +129,7 @@ struct HttpApiRequestRp {
impl HttpApi {
/// Mimics the corresponding method in the offchain API.
pub fn request_start(
&mut self,
method: &str,
uri: &str
) -> Result<HttpRequestId, ()> {
pub fn request_start(&mut self, method: &str, uri: &str) -> Result<HttpRequestId, ()> {
// Start by building the prototype of the request.
// We do this first so that we don't touch anything in `self` if building the prototype
// fails.
@@ -146,10 +144,11 @@ impl HttpApi {
Some(new_id) => self.next_id.0 = new_id,
None => {
error!("Overflow in offchain worker HTTP request ID assignment");
return Err(());
}
return Err(())
},
};
self.requests.insert(new_id, HttpApiRequest::NotDispatched(request, body_sender));
self.requests
.insert(new_id, HttpApiRequest::NotDispatched(request, body_sender));
Ok(new_id)
}
@@ -159,11 +158,11 @@ impl HttpApi {
&mut self,
request_id: HttpRequestId,
name: &str,
value: &str
value: &str,
) -> Result<(), ()> {
let request = match self.requests.get_mut(&request_id) {
Some(&mut HttpApiRequest::NotDispatched(ref mut rq, _)) => rq,
_ => return Err(())
_ => return Err(()),
};
let name = hyper::header::HeaderName::try_from(name).map_err(drop)?;
@@ -179,7 +178,7 @@ impl HttpApi {
&mut self,
request_id: HttpRequestId,
chunk: &[u8],
deadline: Option<Timestamp>
deadline: Option<Timestamp>,
) -> Result<(), HttpError> {
// Extract the request from the list.
// Don't forget to add it back if necessary when returning.
@@ -193,76 +192,83 @@ impl HttpApi {
let mut when_ready = future::maybe_done(future::poll_fn(|cx| sender.poll_ready(cx)));
futures::executor::block_on(future::select(&mut when_ready, &mut deadline));
match when_ready {
future::MaybeDone::Done(Ok(())) => {}
future::MaybeDone::Done(Ok(())) => {},
future::MaybeDone::Done(Err(_)) => return Err(HttpError::IoError),
future::MaybeDone::Future(_) |
future::MaybeDone::Gone => {
future::MaybeDone::Future(_) | future::MaybeDone::Gone => {
debug_assert!(matches!(deadline, future::MaybeDone::Done(..)));
return Err(HttpError::DeadlineReached)
}
},
};
futures::executor::block_on(sender.send_data(hyper::body::Bytes::from(chunk.to_owned())))
.map_err(|_| {
error!("HTTP sender refused data despite being ready");
HttpError::IoError
})
futures::executor::block_on(
sender.send_data(hyper::body::Bytes::from(chunk.to_owned())),
)
.map_err(|_| {
error!("HTTP sender refused data despite being ready");
HttpError::IoError
})
};
loop {
request = match request {
HttpApiRequest::NotDispatched(request, sender) => {
// If the request is not dispatched yet, dispatch it and loop again.
let _ = self.to_worker.unbounded_send(ApiToWorker::Dispatch {
id: request_id,
request
});
let _ = self
.to_worker
.unbounded_send(ApiToWorker::Dispatch { id: request_id, request });
HttpApiRequest::Dispatched(Some(sender))
}
},
HttpApiRequest::Dispatched(Some(mut sender)) =>
if !chunk.is_empty() {
match poll_sender(&mut sender) {
Err(HttpError::IoError) => return Err(HttpError::IoError),
other => {
self.requests.insert(
request_id,
HttpApiRequest::Dispatched(Some(sender))
);
self.requests
.insert(request_id, HttpApiRequest::Dispatched(Some(sender)));
return other
}
},
}
} else {
// Writing an empty body is a hint that we should stop writing. Dropping
// the sender.
self.requests.insert(request_id, HttpApiRequest::Dispatched(None));
return Ok(())
}
},
HttpApiRequest::Response(mut response @ HttpApiRequestRp { sending_body: Some(_), .. }) =>
HttpApiRequest::Response(
mut response @ HttpApiRequestRp { sending_body: Some(_), .. },
) =>
if !chunk.is_empty() {
match poll_sender(response.sending_body.as_mut()
.expect("Can only enter this match branch if Some; qed")) {
match poll_sender(
response
.sending_body
.as_mut()
.expect("Can only enter this match branch if Some; qed"),
) {
Err(HttpError::IoError) => return Err(HttpError::IoError),
other => {
self.requests.insert(request_id, HttpApiRequest::Response(response));
self.requests
.insert(request_id, HttpApiRequest::Response(response));
return other
}
},
}
} else {
// Writing an empty body is a hint that we should stop writing. Dropping
// the sender.
self.requests.insert(request_id, HttpApiRequest::Response(HttpApiRequestRp {
sending_body: None,
..response
}));
self.requests.insert(
request_id,
HttpApiRequest::Response(HttpApiRequestRp {
sending_body: None,
..response
}),
);
return Ok(())
}
},
HttpApiRequest::Fail(_) =>
// If the request has already failed, return without putting back the request
// in the list.
// If the request has already failed, return without putting back the request
// in the list.
return Err(HttpError::IoError),
v @ HttpApiRequest::Dispatched(None) |
@@ -270,7 +276,7 @@ impl HttpApi {
// We have already finished sending this body.
self.requests.insert(request_id, v);
return Err(HttpError::Invalid)
}
},
}
}
}
@@ -279,30 +285,27 @@ impl HttpApi {
pub fn response_wait(
&mut self,
ids: &[HttpRequestId],
deadline: Option<Timestamp>
deadline: Option<Timestamp>,
) -> Vec<HttpRequestStatus> {
// First of all, dispatch all the non-dispatched requests and drop all senders so that the
// user can't write anymore data.
for id in ids {
match self.requests.get_mut(id) {
Some(HttpApiRequest::NotDispatched(_, _)) => {}
Some(HttpApiRequest::NotDispatched(_, _)) => {},
Some(HttpApiRequest::Dispatched(sending_body)) |
Some(HttpApiRequest::Response(HttpApiRequestRp { sending_body, .. })) => {
let _ = sending_body.take();
continue
}
_ => continue
},
_ => continue,
};
let (request, _sender) = match self.requests.remove(id) {
Some(HttpApiRequest::NotDispatched(rq, s)) => (rq, s),
_ => unreachable!("we checked for NotDispatched above; qed")
_ => unreachable!("we checked for NotDispatched above; qed"),
};
let _ = self.to_worker.unbounded_send(ApiToWorker::Dispatch {
id: *id,
request
});
let _ = self.to_worker.unbounded_send(ApiToWorker::Dispatch { id: *id, request });
// We also destroy the sender in order to forbid writing more data.
self.requests.insert(*id, HttpApiRequest::Dispatched(None));
@@ -319,25 +322,24 @@ impl HttpApi {
for id in ids {
output.push(match self.requests.get(id) {
None => HttpRequestStatus::Invalid,
Some(HttpApiRequest::NotDispatched(_, _)) =>
unreachable!("we replaced all the NotDispatched with Dispatched earlier; qed"),
Some(HttpApiRequest::NotDispatched(_, _)) => unreachable!(
"we replaced all the NotDispatched with Dispatched earlier; qed"
),
Some(HttpApiRequest::Dispatched(_)) => {
must_wait_more = true;
HttpRequestStatus::DeadlineReached
},
Some(HttpApiRequest::Fail(_)) => HttpRequestStatus::IoError,
Some(HttpApiRequest::Response(HttpApiRequestRp { status_code, .. })) =>
HttpRequestStatus::Finished(status_code.as_u16()),
Some(HttpApiRequest::Response(HttpApiRequestRp {
status_code, ..
})) => HttpRequestStatus::Finished(status_code.as_u16()),
});
}
debug_assert_eq!(output.len(), ids.len());
// Are we ready to call `return`?
let is_done = if let future::MaybeDone::Done(_) = deadline {
true
} else {
!must_wait_more
};
let is_done =
if let future::MaybeDone::Done(_) = deadline { true } else { !must_wait_more };
if is_done {
// Requests in "fail" mode are purged before returning.
@@ -369,47 +371,45 @@ impl HttpApi {
Some(WorkerToApi::Response { id, status_code, headers, body }) =>
match self.requests.remove(&id) {
Some(HttpApiRequest::Dispatched(sending_body)) => {
self.requests.insert(id, HttpApiRequest::Response(HttpApiRequestRp {
sending_body,
status_code,
headers,
body: body.fuse(),
current_read_chunk: None,
}));
}
None => {} // can happen if we detected an IO error when sending the body
self.requests.insert(
id,
HttpApiRequest::Response(HttpApiRequestRp {
sending_body,
status_code,
headers,
body: body.fuse(),
current_read_chunk: None,
}),
);
},
None => {}, // can happen if we detected an IO error when sending the body
_ => error!("State mismatch between the API and worker"),
}
},
Some(WorkerToApi::Fail { id, error }) =>
match self.requests.remove(&id) {
Some(HttpApiRequest::Dispatched(_)) => {
self.requests.insert(id, HttpApiRequest::Fail(error));
}
None => {} // can happen if we detected an IO error when sending the body
_ => error!("State mismatch between the API and worker"),
}
Some(WorkerToApi::Fail { id, error }) => match self.requests.remove(&id) {
Some(HttpApiRequest::Dispatched(_)) => {
self.requests.insert(id, HttpApiRequest::Fail(error));
},
None => {}, // can happen if we detected an IO error when sending the body
_ => error!("State mismatch between the API and worker"),
},
None => {
error!("Worker has crashed");
return ids.iter().map(|_| HttpRequestStatus::IoError).collect()
}
},
}
}
}
/// Mimics the corresponding method in the offchain API.
pub fn response_headers(
&mut self,
request_id: HttpRequestId
) -> Vec<(Vec<u8>, Vec<u8>)> {
pub fn response_headers(&mut self, request_id: HttpRequestId) -> Vec<(Vec<u8>, Vec<u8>)> {
// Do an implicit non-blocking wait on the request.
let _ = self.response_wait(&[request_id], Some(timestamp::now()));
let headers = match self.requests.get(&request_id) {
Some(HttpApiRequest::Response(HttpApiRequestRp { headers, .. })) => headers,
_ => return Vec::new()
_ => return Vec::new(),
};
headers
@@ -423,7 +423,7 @@ impl HttpApi {
&mut self,
request_id: HttpRequestId,
buffer: &mut [u8],
deadline: Option<Timestamp>
deadline: Option<Timestamp>,
) -> Result<usize, HttpError> {
// Do an implicit wait on the request.
let _ = self.response_wait(&[request_id], deadline);
@@ -439,14 +439,13 @@ impl HttpApi {
return Err(HttpError::DeadlineReached)
},
// The request has failed.
Some(HttpApiRequest::Fail { .. }) =>
return Err(HttpError::IoError),
Some(HttpApiRequest::Fail { .. }) => return Err(HttpError::IoError),
// Request hasn't been dispatched yet; reading the body is invalid.
Some(rq @ HttpApiRequest::NotDispatched(_, _)) => {
self.requests.insert(request_id, rq);
return Err(HttpError::Invalid)
}
None => return Err(HttpError::Invalid)
},
None => return Err(HttpError::Invalid),
};
// Convert the deadline into a `Future` that resolves when the deadline is reached.
@@ -456,19 +455,22 @@ impl HttpApi {
// First read from `current_read_chunk`.
if let Some(mut current_read_chunk) = response.current_read_chunk.take() {
match current_read_chunk.read(buffer) {
Ok(0) => {}
Ok(0) => {},
Ok(n) => {
self.requests.insert(request_id, HttpApiRequest::Response(HttpApiRequestRp {
current_read_chunk: Some(current_read_chunk),
.. response
}));
self.requests.insert(
request_id,
HttpApiRequest::Response(HttpApiRequestRp {
current_read_chunk: Some(current_read_chunk),
..response
}),
);
return Ok(n)
},
Err(err) => {
// This code should never be reached unless there's a logic error somewhere.
error!("Failed to read from current read chunk: {:?}", err);
return Err(HttpError::IoError)
}
},
}
}
@@ -482,7 +484,7 @@ impl HttpApi {
match next_body {
Some(Ok(chunk)) => response.current_read_chunk = Some(chunk.reader()),
Some(Err(_)) => return Err(HttpError::IoError),
None => return Ok(0), // eof
None => return Ok(0), // eof
}
}
@@ -496,9 +498,7 @@ impl HttpApi {
impl fmt::Debug for HttpApi {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list()
.entries(self.requests.iter())
.finish()
f.debug_list().entries(self.requests.iter()).finish()
}
}
@@ -507,12 +507,13 @@ impl fmt::Debug for HttpApiRequest {
match self {
HttpApiRequest::NotDispatched(_, _) =>
f.debug_tuple("HttpApiRequest::NotDispatched").finish(),
HttpApiRequest::Dispatched(_) =>
f.debug_tuple("HttpApiRequest::Dispatched").finish(),
HttpApiRequest::Response(HttpApiRequestRp { status_code, headers, .. }) =>
f.debug_tuple("HttpApiRequest::Response").field(status_code).field(headers).finish(),
HttpApiRequest::Fail(err) =>
f.debug_tuple("HttpApiRequest::Fail").field(err).finish(),
HttpApiRequest::Dispatched(_) => f.debug_tuple("HttpApiRequest::Dispatched").finish(),
HttpApiRequest::Response(HttpApiRequestRp { status_code, headers, .. }) => f
.debug_tuple("HttpApiRequest::Response")
.field(status_code)
.field(headers)
.finish(),
HttpApiRequest::Fail(err) => f.debug_tuple("HttpApiRequest::Fail").field(err).finish(),
}
}
}
@@ -525,7 +526,7 @@ enum ApiToWorker {
id: HttpRequestId,
/// Request to start executing.
request: hyper::Request<hyper::Body>,
}
},
}
/// Message send from the API to the worker.
@@ -605,8 +606,8 @@ impl Future for HttpWorker {
Poll::Ready(Ok(response)) => response,
Poll::Ready(Err(error)) => {
let _ = me.to_api.unbounded_send(WorkerToApi::Fail { id, error });
continue; // don't insert the request back
}
continue // don't insert the request back
},
};
// We received a response! Decompose it into its parts.
@@ -622,20 +623,20 @@ impl Future for HttpWorker {
});
me.requests.push((id, HttpWorkerRequest::ReadBody { body, tx: body_tx }));
cx.waker().wake_by_ref(); // reschedule in order to poll the new future
cx.waker().wake_by_ref(); // reschedule in order to poll the new future
continue
}
},
HttpWorkerRequest::ReadBody { mut body, mut tx } => {
// Before reading from the HTTP response, check that `tx` is ready to accept
// a new chunk.
match tx.poll_ready(cx) {
Poll::Ready(Ok(())) => {}
Poll::Ready(Err(_)) => continue, // don't insert the request back
Poll::Ready(Ok(())) => {},
Poll::Ready(Err(_)) => continue, // don't insert the request back
Poll::Pending => {
me.requests.push((id, HttpWorkerRequest::ReadBody { body, tx }));
continue
}
},
}
// `tx` is ready. Read a chunk from the socket and send it to the channel.
@@ -643,31 +644,31 @@ impl Future for HttpWorker {
Poll::Ready(Some(Ok(chunk))) => {
let _ = tx.start_send(Ok(chunk));
me.requests.push((id, HttpWorkerRequest::ReadBody { body, tx }));
cx.waker().wake_by_ref(); // reschedule in order to continue reading
}
cx.waker().wake_by_ref(); // reschedule in order to continue reading
},
Poll::Ready(Some(Err(err))) => {
let _ = tx.start_send(Err(err));
// don't insert the request back
},
Poll::Ready(None) => {} // EOF; don't insert the request back
Poll::Ready(None) => {}, // EOF; don't insert the request back
Poll::Pending => {
me.requests.push((id, HttpWorkerRequest::ReadBody { body, tx }));
},
}
}
},
}
}
// Check for messages coming from the [`HttpApi`].
match Stream::poll_next(Pin::new(&mut me.from_api), cx) {
Poll::Pending => {},
Poll::Ready(None) => return Poll::Ready(()), // stops the worker
Poll::Ready(None) => return Poll::Ready(()), // stops the worker
Poll::Ready(Some(ApiToWorker::Dispatch { id, request })) => {
let future = me.http_client.request(request);
debug_assert!(me.requests.iter().all(|(i, _)| *i != id));
me.requests.push((id, HttpWorkerRequest::Dispatched(future)));
cx.waker().wake_by_ref(); // reschedule the task to poll the request
}
cx.waker().wake_by_ref(); // reschedule the task to poll the request
},
}
Poll::Pending
@@ -676,9 +677,7 @@ impl Future for HttpWorker {
impl fmt::Debug for HttpWorker {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list()
.entries(self.requests.iter())
.finish()
f.debug_list().entries(self.requests.iter()).finish()
}
}
@@ -695,13 +694,13 @@ impl fmt::Debug for HttpWorkerRequest {
#[cfg(test)]
mod tests {
use core::convert::Infallible;
use crate::api::timestamp;
use super::{http, SharedClient};
use sp_core::offchain::{HttpError, HttpRequestId, HttpRequestStatus, Duration};
use crate::api::timestamp;
use core::convert::Infallible;
use futures::future;
use lazy_static::lazy_static;
use sp_core::offchain::{Duration, HttpError, HttpRequestId, HttpRequestStatus};
// Using lazy_static to avoid spawning lots of different SharedClients,
// as spawning a SharedClient is CPU-intensive and opens lots of fds.
lazy_static! {
@@ -720,14 +719,17 @@ mod tests {
let mut rt = tokio::runtime::Runtime::new().unwrap();
let worker = rt.spawn(worker);
let server = rt.spawn(async move {
let server = hyper::Server::bind(&"127.0.0.1:0".parse().unwrap())
.serve(hyper::service::make_service_fn(|_| { async move {
Ok::<_, Infallible>(hyper::service::service_fn(move |_req| async move {
Ok::<_, Infallible>(
hyper::Response::new(hyper::Body::from("Hello World!"))
)
}))
}}));
let server = hyper::Server::bind(&"127.0.0.1:0".parse().unwrap()).serve(
hyper::service::make_service_fn(|_| async move {
Ok::<_, Infallible>(hyper::service::service_fn(
move |_req| async move {
Ok::<_, Infallible>(hyper::Response::new(hyper::Body::from(
"Hello World!",
)))
},
))
}),
);
let _ = addr_tx.send(server.local_addr());
server.await.map_err(drop)
});
@@ -750,7 +752,7 @@ mod tests {
match api.response_wait(&[id], Some(deadline))[0] {
HttpRequestStatus::Finished(200) => {},
v => panic!("Connecting to localhost failed: {:?}", v)
v => panic!("Connecting to localhost failed: {:?}", v),
}
let headers = api.response_headers(id);
@@ -766,13 +768,13 @@ mod tests {
let (mut api, addr) = build_api_server!();
match api.request_start("\0", &format!("http://{}", addr)) {
Err(()) => {}
Ok(_) => panic!()
Err(()) => {},
Ok(_) => panic!(),
};
match api.request_start("GET", "http://\0localhost") {
Err(()) => {}
Ok(_) => panic!()
Err(()) => {},
Ok(_) => panic!(),
};
}
@@ -781,42 +783,42 @@ mod tests {
let (mut api, addr) = build_api_server!();
match api.request_add_header(HttpRequestId(0xdead), "Foo", "bar") {
Err(()) => {}
Ok(_) => panic!()
Err(()) => {},
Ok(_) => panic!(),
};
let id = api.request_start("GET", &format!("http://{}", addr)).unwrap();
match api.request_add_header(id, "\0", "bar") {
Err(()) => {}
Ok(_) => panic!()
Err(()) => {},
Ok(_) => panic!(),
};
let id = api.request_start("POST", &format!("http://{}", addr)).unwrap();
match api.request_add_header(id, "Foo", "\0") {
Err(()) => {}
Ok(_) => panic!()
Err(()) => {},
Ok(_) => panic!(),
};
let id = api.request_start("POST", &format!("http://{}", addr)).unwrap();
api.request_add_header(id, "Foo", "Bar").unwrap();
api.request_write_body(id, &[1, 2, 3, 4], None).unwrap();
match api.request_add_header(id, "Foo2", "Bar") {
Err(()) => {}
Ok(_) => panic!()
Err(()) => {},
Ok(_) => panic!(),
};
let id = api.request_start("GET", &format!("http://{}", addr)).unwrap();
api.response_headers(id);
match api.request_add_header(id, "Foo2", "Bar") {
Err(()) => {}
Ok(_) => panic!()
Err(()) => {},
Ok(_) => panic!(),
};
let id = api.request_start("GET", &format!("http://{}", addr)).unwrap();
api.response_read_body(id, &mut [], None).unwrap();
match api.request_add_header(id, "Foo2", "Bar") {
Err(()) => {}
Ok(_) => panic!()
Err(()) => {},
Ok(_) => panic!(),
};
}
@@ -825,13 +827,13 @@ mod tests {
let (mut api, addr) = build_api_server!();
match api.request_write_body(HttpRequestId(0xdead), &[1, 2, 3], None) {
Err(HttpError::Invalid) => {}
_ => panic!()
Err(HttpError::Invalid) => {},
_ => panic!(),
};
match api.request_write_body(HttpRequestId(0xdead), &[], None) {
Err(HttpError::Invalid) => {}
_ => panic!()
Err(HttpError::Invalid) => {},
_ => panic!(),
};
let id = api.request_start("POST", &format!("http://{}", addr)).unwrap();
@@ -839,8 +841,8 @@ mod tests {
api.request_write_body(id, &[1, 2, 3, 4], None).unwrap();
api.request_write_body(id, &[], None).unwrap();
match api.request_write_body(id, &[], None) {
Err(HttpError::Invalid) => {}
_ => panic!()
Err(HttpError::Invalid) => {},
_ => panic!(),
};
let id = api.request_start("POST", &format!("http://{}", addr)).unwrap();
@@ -848,52 +850,52 @@ mod tests {
api.request_write_body(id, &[1, 2, 3, 4], None).unwrap();
api.request_write_body(id, &[], None).unwrap();
match api.request_write_body(id, &[1, 2, 3, 4], None) {
Err(HttpError::Invalid) => {}
_ => panic!()
Err(HttpError::Invalid) => {},
_ => panic!(),
};
let id = api.request_start("POST", &format!("http://{}", addr)).unwrap();
api.request_write_body(id, &[1, 2, 3, 4], None).unwrap();
api.response_wait(&[id], None);
match api.request_write_body(id, &[], None) {
Err(HttpError::Invalid) => {}
_ => panic!()
Err(HttpError::Invalid) => {},
_ => panic!(),
};
let id = api.request_start("POST", &format!("http://{}", addr)).unwrap();
api.request_write_body(id, &[1, 2, 3, 4], None).unwrap();
api.response_wait(&[id], None);
match api.request_write_body(id, &[1, 2, 3, 4], None) {
Err(HttpError::Invalid) => {}
_ => panic!()
Err(HttpError::Invalid) => {},
_ => panic!(),
};
let id = api.request_start("POST", &format!("http://{}", addr)).unwrap();
api.response_headers(id);
match api.request_write_body(id, &[1, 2, 3, 4], None) {
Err(HttpError::Invalid) => {}
_ => panic!()
Err(HttpError::Invalid) => {},
_ => panic!(),
};
let id = api.request_start("GET", &format!("http://{}", addr)).unwrap();
api.response_headers(id);
match api.request_write_body(id, &[], None) {
Err(HttpError::Invalid) => {}
_ => panic!()
Err(HttpError::Invalid) => {},
_ => panic!(),
};
let id = api.request_start("POST", &format!("http://{}", addr)).unwrap();
api.response_read_body(id, &mut [], None).unwrap();
match api.request_write_body(id, &[1, 2, 3, 4], None) {
Err(HttpError::Invalid) => {}
_ => panic!()
Err(HttpError::Invalid) => {},
_ => panic!(),
};
let id = api.request_start("POST", &format!("http://{}", addr)).unwrap();
api.response_read_body(id, &mut [], None).unwrap();
match api.request_write_body(id, &[], None) {
Err(HttpError::Invalid) => {}
_ => panic!()
Err(HttpError::Invalid) => {},
_ => panic!(),
};
}
@@ -948,15 +950,15 @@ mod tests {
let mut buf = [0; 512];
match api.response_read_body(HttpRequestId(0xdead), &mut buf, None) {
Err(HttpError::Invalid) => {}
_ => panic!()
Err(HttpError::Invalid) => {},
_ => panic!(),
}
let id = api.request_start("GET", &format!("http://{}", addr)).unwrap();
while api.response_read_body(id, &mut buf, None).unwrap() != 0 {}
match api.response_read_body(id, &mut buf, None) {
Err(HttpError::Invalid) => {}
_ => panic!()
Err(HttpError::Invalid) => {},
_ => panic!(),
}
}
@@ -973,16 +975,26 @@ mod tests {
for _ in 0..250 {
match rand::random::<u8>() % 6 {
0 => { let _ = api.request_add_header(id, "Foo", "Bar"); }
1 => { let _ = api.request_write_body(id, &[1, 2, 3, 4], None); }
2 => { let _ = api.request_write_body(id, &[], None); }
3 => { let _ = api.response_wait(&[id], None); }
4 => { let _ = api.response_headers(id); }
0 => {
let _ = api.request_add_header(id, "Foo", "Bar");
},
1 => {
let _ = api.request_write_body(id, &[1, 2, 3, 4], None);
},
2 => {
let _ = api.request_write_body(id, &[], None);
},
3 => {
let _ = api.response_wait(&[id], None);
},
4 => {
let _ = api.response_headers(id);
},
5 => {
let mut buf = [0; 512];
let _ = api.response_read_body(id, &mut buf, None);
}
6 ..= 255 => unreachable!()
},
6..=255 => unreachable!(),
}
}
}
+32 -30
View File
@@ -18,8 +18,12 @@
//! Contains the same API as the `http` module, except that everything returns an error.
use sp_core::offchain::{HttpRequestId, Timestamp, HttpRequestStatus, HttpError};
use std::{future::Future, pin::Pin, task::Context, task::Poll};
use sp_core::offchain::{HttpError, HttpRequestId, HttpRequestStatus, Timestamp};
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
/// Wrapper struct (wrapping nothing in case of http_dummy) used for keeping the hyper_rustls client running.
#[derive(Clone)]
@@ -46,24 +50,17 @@ pub struct HttpWorker;
impl HttpApi {
/// Mimics the corresponding method in the offchain API.
pub fn request_start(
&mut self,
_: &str,
_: &str
) -> Result<HttpRequestId, ()> {
pub fn request_start(&mut self, _: &str, _: &str) -> Result<HttpRequestId, ()> {
/// Because this always returns an error, none of the other methods should ever be called.
Err(())
}
/// Mimics the corresponding method in the offchain API.
pub fn request_add_header(
&mut self,
_: HttpRequestId,
_: &str,
_: &str
) -> Result<(), ()> {
unreachable!("Creating a request always fails, thus this function will \
never be called; qed")
pub fn request_add_header(&mut self, _: HttpRequestId, _: &str, _: &str) -> Result<(), ()> {
unreachable!(
"Creating a request always fails, thus this function will \
never be called; qed"
)
}
/// Mimics the corresponding method in the offchain API.
@@ -71,33 +68,36 @@ impl HttpApi {
&mut self,
_: HttpRequestId,
_: &[u8],
_: Option<Timestamp>
_: Option<Timestamp>,
) -> Result<(), HttpError> {
unreachable!("Creating a request always fails, thus this function will \
never be called; qed")
unreachable!(
"Creating a request always fails, thus this function will \
never be called; qed"
)
}
/// Mimics the corresponding method in the offchain API.
pub fn response_wait(
&mut self,
requests: &[HttpRequestId],
_: Option<Timestamp>
_: Option<Timestamp>,
) -> Vec<HttpRequestStatus> {
if requests.is_empty() {
Vec::new()
} else {
unreachable!("Creating a request always fails, thus the list of requests should \
always be empty; qed")
unreachable!(
"Creating a request always fails, thus the list of requests should \
always be empty; qed"
)
}
}
/// Mimics the corresponding method in the offchain API.
pub fn response_headers(
&mut self,
_: HttpRequestId
) -> Vec<(Vec<u8>, Vec<u8>)> {
unreachable!("Creating a request always fails, thus this function will \
never be called; qed")
pub fn response_headers(&mut self, _: HttpRequestId) -> Vec<(Vec<u8>, Vec<u8>)> {
unreachable!(
"Creating a request always fails, thus this function will \
never be called; qed"
)
}
/// Mimics the corresponding method in the offchain API.
@@ -105,10 +105,12 @@ impl HttpApi {
&mut self,
_: HttpRequestId,
_: &mut [u8],
_: Option<Timestamp>
_: Option<Timestamp>,
) -> Result<usize, HttpError> {
unreachable!("Creating a request always fails, thus this function will \
never be called; qed")
unreachable!(
"Creating a request always fails, thus this function will \
never be called; qed"
)
}
}
+11 -7
View File
@@ -19,8 +19,10 @@
//! Helper methods dedicated to timestamps.
use sp_core::offchain::Timestamp;
use std::convert::TryInto;
use std::time::{SystemTime, Duration};
use std::{
convert::TryInto,
time::{Duration, SystemTime},
};
/// Returns the current time as a `Timestamp`.
pub fn now() -> Timestamp {
@@ -34,9 +36,12 @@ pub fn now() -> Timestamp {
Ok(d) => {
let duration = d.as_millis();
// Assuming overflow won't happen for a few hundred years.
Timestamp::from_unix_millis(duration.try_into()
.expect("epoch milliseconds won't overflow u64 for hundreds of years; qed"))
}
Timestamp::from_unix_millis(
duration
.try_into()
.expect("epoch milliseconds won't overflow u64 for hundreds of years; qed"),
)
},
}
}
@@ -60,7 +65,6 @@ pub fn deadline_to_future(
// Only apply delay if we need to wait a non-zero duration
Some(duration) if duration <= Duration::from_secs(0) =>
Either::Right(Either::Left(future::ready(()))),
Some(duration) =>
Either::Right(Either::Right(futures_timer::Delay::new(duration))),
Some(duration) => Either::Right(Either::Right(futures_timer::Delay::new(duration))),
})
}