Skip to content

Commit

Permalink
refactor: rustfmt [skip ci]
Browse files Browse the repository at this point in the history
  • Loading branch information
pyro-kitchen committed Apr 20, 2024
1 parent 8ecc62a commit 09250b5
Show file tree
Hide file tree
Showing 14 changed files with 73 additions and 69 deletions.
2 changes: 1 addition & 1 deletion crates/alerion_core/src/filesystem.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use anyhow::Context;
use directories::ProjectDirs;

pub async fn setup_directories() -> anyhow::Result<ProjectDirs> {
pub async fn setup_directories() -> anyhow::Result<ProjectDirs> {
let project_dirs = ProjectDirs::from("host", "pyro", "alerion")
.context("couldn't determine a home directory for your operating system")?;

Expand Down
7 changes: 1 addition & 6 deletions crates/alerion_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,7 @@ pub async fn alerion_main() -> anyhow::Result<()> {
let project_dirs = setup_directories().await?;
let config = AlerionConfig::load(&project_dirs)?;

let server_pool = Arc::new(
ServerPool::builder(&config)?
.fetch_servers()
.await?
.build()
);
let server_pool = Arc::new(ServerPool::builder(&config)?.fetch_servers().await?.build());

//server_pool.create_server("0e4059ca-d79b-46a5-8ec4-95bd0736d150".try_into().unwrap()).await;

Expand Down
29 changes: 19 additions & 10 deletions crates/alerion_core/src/servers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@ use std::sync::Arc;
use std::time::Instant;

use actix_web::HttpResponse;
use alerion_datamodel::websocket::{PerformanceStatisics, NetworkStatistics, ServerStatus};
use alerion_datamodel::remote::server::{ContainerConfig, ServerSettings};
use alerion_datamodel::websocket::{NetworkStatistics, PerformanceStatisics, ServerStatus};
use bollard::container::{Config, CreateContainerOptions};
use bollard::Docker;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tokio::sync::mpsc::{channel, Receiver, Sender};
use tokio::sync::RwLock;
use uuid::Uuid;
use bollard::Docker;
use bollard::container::{Config, CreateContainerOptions};
use thiserror::Error;
use serde::{Serialize, Deserialize};

use crate::config::AlerionConfig;
use crate::websocket::conn::{ConnectionAddr , PanelMessage, ServerMessage};
use crate::websocket::conn::{ConnectionAddr, PanelMessage, ServerMessage};
use crate::websocket::relay::{AuthTracker, ClientConnection, ServerConnection};

pub struct ServerPoolBuilder {
Expand Down Expand Up @@ -50,7 +50,8 @@ impl ServerPoolBuilder {
info,
Arc::clone(&self.remote_api),
Arc::clone(&self.docker),
).await?;
)
.await?;
self.servers.insert(uuid, server);
}

Expand Down Expand Up @@ -183,7 +184,10 @@ impl Server {
}

async fn create_docker_container(&self) -> Result<(), ServerError> {
log::info!("Creating docker container for server {}", self.uuid.as_hyphenated());
log::info!(
"Creating docker container for server {}",
self.uuid.as_hyphenated()
);

let opts = CreateContainerOptions {
name: self.container_name.clone(),
Expand All @@ -204,7 +208,10 @@ impl Server {
Ok(())
}

pub async fn setup_new_websocket<F>(&self, start_websocket: F) -> actix_web::Result<HttpResponse>
pub async fn setup_new_websocket<F>(
&self,
start_websocket: F,
) -> actix_web::Result<HttpResponse>
where
F: FnOnce(ServerConnection) -> actix_web::Result<(ConnectionAddr, HttpResponse)>,
{
Expand Down Expand Up @@ -257,7 +264,9 @@ async fn monitor_performance_metrics(server: Arc<Server>) {
disk_bytes: 100,
};

server.send_to_available_websockets(ServerMessage::Stats(stats)).await;
server
.send_to_available_websockets(ServerMessage::Stats(stats))
.await;
}
}

Expand Down
58 changes: 28 additions & 30 deletions crates/alerion_core/src/servers/remote.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
use std::mem;

use alerion_datamodel::remote::server::{
PostServerInstallByUuidRequest,
GetServerInstallByUuidResponse,
GetServerByUuidResponse,
GetServersResponse,
ServerData,
GetServerByUuidResponse, GetServerInstallByUuidResponse, GetServersResponse, PostServerInstallByUuidRequest, ServerData
};
use reqwest::header::{self, HeaderMap};
use reqwest::StatusCode;
Expand Down Expand Up @@ -47,8 +43,9 @@ impl RemoteClient {

headers.insert(header::AUTHORIZATION, authorization);


let accept = "application/vnd.pterodactyl.v1+json".parse().expect("valid header value");
let accept = "application/vnd.pterodactyl.v1+json"
.parse()
.expect("valid header value");

headers.insert(header::ACCEPT, accept);

Expand All @@ -74,7 +71,11 @@ impl RemoteClient {
reinstall,
};

let url = format!("{}/api/remote/servers/{}/install", self.remote, uuid.as_hyphenated());
let url = format!(
"{}/api/remote/servers/{}/install",
self.remote,
uuid.as_hyphenated()
);

log::debug!("remote: POST {url}");

Expand All @@ -96,15 +97,15 @@ impl RemoteClient {
&self,
uuid: Uuid,
) -> Result<GetServerInstallByUuidResponse, ResponseError> {
let url = format!("{}/api/remote/servers/{}/install", self.remote, uuid.as_hyphenated());

let url = format!(
"{}/api/remote/servers/{}/install",
self.remote,
uuid.as_hyphenated()
);

log::debug!("remote: GET {url}");

let resp = self
.http
.get(url)
.send()
.await?;
let resp = self.http.get(url).send().await?;

match resp.status() {
StatusCode::NOT_FOUND => Err(ResponseError::NotFound(uuid)),
Expand All @@ -124,15 +125,15 @@ impl RemoteClient {
&self,
uuid: Uuid,
) -> Result<GetServerByUuidResponse, ResponseError> {
let url = format!("{}/api/remote/servers/{}", self.remote, uuid.as_hyphenated());
let url = format!(
"{}/api/remote/servers/{}",
self.remote,
uuid.as_hyphenated()
);

log::debug!("remote: GET {url}");

let resp = self
.http
.get(url)
.send()
.await?;
let resp = self.http.get(url).send().await?;

match resp.status() {
StatusCode::NOT_FOUND => Err(ResponseError::NotFound(uuid)),
Expand All @@ -153,15 +154,14 @@ impl RemoteClient {
let mut page = 1;

loop {
let url = format!("{}/api/remote/servers?page={}&per_page=2", self.remote, page);
let url = format!(
"{}/api/remote/servers?page={}&per_page=2",
self.remote, page
);

log::debug!("remote: GET {url}");

let resp = self
.http
.get(url)
.send()
.await?;
let resp = self.http.get(url).send().await?;

let parsed = match resp.status() {
StatusCode::UNAUTHORIZED => Err(ResponseError::Unauthorized),
Expand Down Expand Up @@ -194,9 +194,7 @@ impl RemoteClient {
});

if parsed.meta.current_page == parsed.meta.last_page {
return Ok(unsafe {
servers.unwrap_unchecked()
});
return Ok(unsafe { servers.unwrap_unchecked() });
}

page += 1;
Expand Down
5 changes: 1 addition & 4 deletions crates/alerion_core/src/webserver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,7 @@ impl Webserver {
.wrap(BearerAuth::new(token.clone()))
.to(api::update_post),
)
.service(
web::scope("/servers/{id}")
.route("ws", web::get().to(api::ws)),
)
.service(web::scope("/servers/{id}").route("ws", web::get().to(api::ws)))
})
});

Expand Down
7 changes: 3 additions & 4 deletions crates/alerion_core/src/webserver/router/api.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use std::sync::Arc;

use actix_web::{web, HttpResponse, HttpRequest, Responder};
use alerion_datamodel::webserver::CreateServerRequest;
use actix_web::{web, HttpRequest, HttpResponse, Responder};
use alerion_datamodel::webserver::update::{ConfigUpdateRequest, ConfigUpdateResponse};
use alerion_datamodel::webserver::CreateServerRequest;
use uuid::Uuid;

use crate::config::AlerionConfig;
use crate::servers::ServerPool;
use crate::webserver::SystemOptions;
use crate::config::AlerionConfig;

pub async fn servers_post(
opts: web::Json<CreateServerRequest>,
Expand Down Expand Up @@ -52,4 +52,3 @@ pub async fn ws(
Ok(HttpResponse::NotImplemented().into())
}
}

6 changes: 3 additions & 3 deletions crates/alerion_core/src/websocket/conn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ use actix_web_actors::ws;
use alerion_datamodel::websocket::*;
use uuid::Uuid;

use crate::config::AlerionConfig;

use super::auth::Auth;
use super::relay::ServerConnection;
use crate::config::AlerionConfig;

#[derive(Debug, Clone)]
pub enum ServerMessage {
Expand Down Expand Up @@ -59,7 +58,8 @@ impl Handler<ServerMessage> for WebsocketConnectionImpl {
}

ServerMessage::Stats(stats) => {
let str = serde_json::to_string(&stats).expect("JSON serialization should not fail");
let str =
serde_json::to_string(&stats).expect("JSON serialization should not fail");
ctx.text(RawMessage::new(EventType::Stats, str))
}
}
Expand Down
8 changes: 6 additions & 2 deletions crates/alerion_core/src/websocket/relay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ pub struct ServerConnection {
}

impl ServerConnection {
pub fn new(auth_tracker: Arc<AuthTracker>, sender: Sender<(u32, PanelMessage)>, id: u32) -> Self {
pub fn new(
auth_tracker: Arc<AuthTracker>,
sender: Sender<(u32, PanelMessage)>,
id: u32,
) -> Self {
ServerConnection {
auth_tracker,
sender,
Expand Down Expand Up @@ -59,7 +63,7 @@ impl ClientConnection {

pub fn send_if_authenticated<F>(&self, msg: F)
where
F: FnOnce() -> ServerMessage
F: FnOnce() -> ServerMessage,
{
if self.auth_tracker.get_auth() {
let m = msg();
Expand Down
4 changes: 2 additions & 2 deletions crates/alerion_datamodel/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![deny(clippy::unwrap_used)]
#![allow(dead_code)]

pub mod websocket;
pub mod webserver;
pub mod remote;
pub mod webserver;
pub mod websocket;
1 change: 0 additions & 1 deletion crates/alerion_datamodel/src/remote.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@

pub mod server;
3 changes: 2 additions & 1 deletion crates/alerion_datamodel/src/remote/server.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::collections::HashMap;

use serde::{Serialize, Deserialize, de::IgnoredAny};
use serde::de::IgnoredAny;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use smallvec::SmallVec;
use uuid::Uuid;
Expand Down
2 changes: 1 addition & 1 deletion crates/alerion_datamodel/src/webserver.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use serde::{Serialize, Deserialize};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[derive(Serialize, Deserialize)]
Expand Down
3 changes: 1 addition & 2 deletions crates/alerion_datamodel/src/webserver/update.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::net::IpAddr;

use serde::{Serialize, Deserialize};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[derive(Debug, Deserialize)]
Expand Down Expand Up @@ -48,4 +48,3 @@ pub struct ConfigUpdateRequest {
pub struct ConfigUpdateResponse {
pub applied: bool,
}

7 changes: 5 additions & 2 deletions crates/alerion_datamodel/src/websocket.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use serde::{Serialize, Deserialize};
use bytestring::ByteString;
use serde::{Deserialize, Serialize};
use smallvec::{smallvec, SmallVec};

#[derive(Copy, Clone, Debug, Serialize, PartialEq, Eq)]
Expand Down Expand Up @@ -84,7 +84,10 @@ impl RawMessage {
}

pub fn new(event: EventType, args: String) -> Self {
Self { event, args: Some(smallvec![serde_json::Value::String(args)]) }
Self {
event,
args: Some(smallvec![serde_json::Value::String(args)]),
}
}

pub fn into_first_arg(self) -> Option<String> {
Expand Down

0 comments on commit 09250b5

Please sign in to comment.