Skip to content

Commit

Permalink
Fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
brokad committed Jun 22, 2022
1 parent 6aaebd1 commit 4310259
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 54 deletions.
133 changes: 83 additions & 50 deletions gateway/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,24 @@ use std::pin::Pin;
use std::str::FromStr;

use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::response::{
IntoResponse,
Response
};
use axum::Json;
use bollard::Docker;
use convert_case::{Case, Casing};
use convert_case::{
Case,
Casing
};
use futures::prelude::*;
use lazy_static::lazy_static;
use regex::Regex;
use serde::{Deserialize, Deserializer, Serialize};
use serde::{
Deserialize,
Deserializer,
Serialize
};
use serde_json::json;

use crate::args::Args;
Expand Down Expand Up @@ -53,7 +63,7 @@ pub enum ErrorKind {
ProjectUnavailable,
InvalidOperation,
Internal,
NotReady,
NotReady
}

impl std::fmt::Display for ErrorKind {
Expand All @@ -74,14 +84,14 @@ impl std::fmt::Display for ErrorKind {
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
source: Option<Box<dyn StdError + Sync + Send + 'static>>,
source: Option<Box<dyn StdError + Sync + Send + 'static>>
}

impl Error {
pub fn source<E: StdError + Sync + Send + 'static>(kind: ErrorKind, err: E) -> Self {
Self {
kind,
source: Some(Box::new(err)),
source: Some(Box::new(err))
}
}

Expand All @@ -90,8 +100,8 @@ impl Error {
kind,
source: Some(Box::new(io::Error::new(
io::ErrorKind::Other,
message.as_ref().to_string(),
))),
message.as_ref().to_string()
)))
}
}

Expand Down Expand Up @@ -127,15 +137,15 @@ impl IntoResponse for Error {
ErrorKind::InvalidProjectName => (StatusCode::BAD_REQUEST, "invalid project name"),
ErrorKind::InvalidOperation => (
StatusCode::BAD_REQUEST,
"the requested operation is invalid",
"the requested operation is invalid"
),
ErrorKind::ProjectAlreadyExists => (
StatusCode::BAD_REQUEST,
"a project with the same name already exists",
"a project with the same name already exists"
),
ErrorKind::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized"),
ErrorKind::Forbidden => (StatusCode::FORBIDDEN, "forbidden"),
ErrorKind::NotReady => (StatusCode::INTERNAL_SERVER_ERROR, "not ready yet"),
ErrorKind::NotReady => (StatusCode::INTERNAL_SERVER_ERROR, "not ready yet")
};
(status, Json(json!({ "error": error_message }))).into_response()
}
Expand All @@ -161,7 +171,7 @@ pub struct ProjectName(pub String);
impl<'de> Deserialize<'de> for ProjectName {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
D: Deserializer<'de>
{
String::deserialize(deserializer)?
.parse()
Expand Down Expand Up @@ -208,7 +218,7 @@ impl std::fmt::Display for AccountName {
impl<'de> Deserialize<'de> for AccountName {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
D: Deserializer<'de>
{
String::deserialize(deserializer)?
.parse()
Expand Down Expand Up @@ -252,7 +262,7 @@ pub trait State<'c>: Send + Sized + Clone {
/// failures
pub trait EndState<'c>
where
Self: State<'c, Error = Infallible, Next = Self>,
Self: State<'c, Error = Infallible, Next = Self>
{
type ErrorVariant;

Expand All @@ -271,7 +281,7 @@ pub trait EndStateExt<'c>: EndState<'c> {
fn into_stream<Ctx>(self, ctx: Ctx) -> StateTryStream<'c, Self, Self::ErrorVariant>
where
Self: 'c,
Ctx: 'c + Context<'c>,
Ctx: 'c + Context<'c>
{
Box::pin(stream::try_unfold((self, ctx), |(state, ctx)| async move {
state
Expand All @@ -288,14 +298,14 @@ impl<'c, S> EndStateExt<'c> for S where S: EndState<'c> {}

pub trait IntoEndState<'c, E>
where
E: EndState<'c>,
E: EndState<'c>
{
fn into_end_state(self) -> Result<E, Infallible>;
}

impl<'c, E, S, Err> IntoEndState<'c, E> for Result<S, Err>
where
E: EndState<'c> + From<S> + From<Err>,
E: EndState<'c> + From<S> + From<Err>
{
fn into_end_state(self) -> Result<E, Infallible> {
self.map(|s| E::from(s)).or_else(|err| Ok(E::from(err)))
Expand All @@ -311,35 +321,53 @@ pub trait Refresh: Sized {

#[cfg(test)]
pub mod tests {
use crate::api::make_api;
use crate::args::Args;
use crate::auth::User;
use crate::project::Project;
use crate::proxy::make_proxy;
use crate::service::GatewayService;
use crate::worker::Worker;
use crate::Context;
use anyhow::{anyhow, Context as AnyhowContext};
use std::env;
use std::io::Read;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;

use anyhow::{
anyhow,
Context as AnyhowContext
};
use axum::headers::Authorization;
use bollard::network::ListNetworksOptions;
use bollard::Docker;
use futures::prelude::*;
use hyper::client::HttpConnector;
use hyper::http::uri::Scheme;
use hyper::http::Uri;
use hyper::StatusCode;
use hyper::{Body, Client as HyperClient, Request, Response};
use hyper::{
Body,
Client as HyperClient,
Request,
Response,
StatusCode
};
use log::info;
use rand::distributions::{Alphanumeric, DistString, Distribution, Uniform};
use shuttle_common::{DeploymentMeta, DeploymentStateMeta};
use std::env;
use std::io::Read;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use rand::distributions::{
Alphanumeric,
DistString,
Distribution,
Uniform
};
use shuttle_common::{
DeploymentMeta,
DeploymentStateMeta
};
use tempfile::NamedTempFile;
use tokio::sync::mpsc::channel;

use crate::api::make_api;
use crate::args::Args;
use crate::auth::User;
use crate::project::Project;
use crate::proxy::make_proxy;
use crate::service::GatewayService;
use crate::worker::Worker;
use crate::Context;

macro_rules! value_block_helper {
($next:ident, $block:block) => {
$block
Expand Down Expand Up @@ -437,7 +465,12 @@ pub mod tests {
}};
}

pub(crate) use {assert_err_kind, assert_matches, assert_stream_matches, value_block_helper};
pub(crate) use {
assert_err_kind,
assert_matches,
assert_stream_matches,
value_block_helper
};

mod request_builder_ext {
pub trait Sealed {}
Expand Down Expand Up @@ -478,14 +511,14 @@ pub mod tests {

pub struct Client<C = HttpConnector, B = Body> {
target: SocketAddr,
hyper: Option<HyperClient<C, B>>,
hyper: Option<HyperClient<C, B>>
}

impl<C, B> Client<C, B> {
pub fn new<A: Into<SocketAddr>>(target: A) -> Self {
Self {
target: target.into(),
hyper: None,
hyper: None
}
}

Expand All @@ -498,7 +531,7 @@ pub mod tests {
impl Client<HttpConnector, Body> {
pub async fn request(
&self,
mut req: Request<Body>,
mut req: Request<Body>
) -> Result<Response<Vec<u8>>, hyper::Error> {
if req.uri().authority().is_none() {
let mut uri = req.uri().clone().into_parts();
Expand Down Expand Up @@ -529,14 +562,14 @@ pub mod tests {
_state: NamedTempFile,
docker: Docker,
args: Args,
hyper: HyperClient<HttpConnector, Body>,
hyper: HyperClient<HttpConnector, Body>
}

#[derive(Clone, Copy)]
pub struct WorldContext<'c> {
pub docker: &'c Docker,
pub args: &'c Args,
pub hyper: &'c HyperClient<HttpConnector, Body>,
pub hyper: &'c HyperClient<HttpConnector, Body>
}

impl World {
Expand Down Expand Up @@ -572,7 +605,7 @@ pub mod tests {
.list_networks(Some(ListNetworksOptions {
filters: vec![("id", vec![network_id.as_str()])]
.into_iter()
.collect(),
.collect()
}))
.await
.context("can't list docker networks")
Expand All @@ -593,7 +626,7 @@ pub mod tests {
prefix,
provisioner_host,
network_id,
state: state.path().to_str().unwrap().to_string(),
state: state.path().to_str().unwrap().to_string()
};

let hyper = HyperClient::builder().build(HttpConnector::new());
Expand All @@ -602,7 +635,7 @@ pub mod tests {
_state: state,
docker,
args,
hyper,
hyper
})
}

Expand All @@ -616,7 +649,7 @@ pub mod tests {
WorldContext {
docker: &self.docker,
args: &self.args,
hyper: &self.hyper,
hyper: &self.hyper
}
}
}
Expand Down Expand Up @@ -686,7 +719,7 @@ pub mod tests {
Request::post("/users/trinity")
.with_header(&Authorization::basic("", key.as_str()))
.body(Body::empty())
.unwrap(),
.unwrap()
)
.map_ok(|resp| {
assert_eq!(resp.status(), StatusCode::OK);
Expand All @@ -702,7 +735,7 @@ pub mod tests {
Request::post("/projects/matrix")
.with_header(&authorization)
.body(Body::empty())
.unwrap(),
.unwrap()
)
.map_ok(|resp| {
assert_eq!(resp.status(), StatusCode::OK);
Expand Down Expand Up @@ -738,7 +771,7 @@ pub mod tests {
Request::get("/projects/matrix/status")
.with_header(&authorization)
.body(Body::empty())
.unwrap(),
.unwrap()
)
.map_ok(|resp| assert_eq!(resp.status(), StatusCode::OK))
.await
Expand Down Expand Up @@ -783,7 +816,7 @@ pub mod tests {
Request::get("/hello")
.header("Host", "matrix.shuttleapp.rs")
.body(Body::empty())
.unwrap(),
.unwrap()
)
.map_ok(|resp| {
assert_eq!(resp.status(), StatusCode::OK);
Expand All @@ -801,7 +834,7 @@ pub mod tests {
Request::delete("/projects/matrix")
.with_header(&authorization)
.body(Body::empty())
.unwrap(),
.unwrap()
)
.map_ok(|resp| assert_eq!(resp.status(), StatusCode::OK))
.await
Expand Down
4 changes: 2 additions & 2 deletions gateway/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -720,12 +720,12 @@ pub mod tests {
};

use super::*;
use crate::EndStateExt;
use crate::tests::World;
use crate::tests::{
assert_matches,
assert_stream_matches,
World
};
use crate::EndStateExt;

#[tokio::test]
async fn create_start_stop_destroy_project() -> anyhow::Result<()> {
Expand Down
6 changes: 4 additions & 2 deletions gateway/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -480,8 +480,10 @@ pub mod tests {
use tokio::task::JoinHandle;

use super::*;
use crate::tests::assert_err_kind;
use crate::tests::World;
use crate::tests::{
assert_err_kind,
World
};

#[tokio::test]
async fn service_create_find_user() -> anyhow::Result<()> {
Expand Down

0 comments on commit 4310259

Please sign in to comment.