1
Fork 0
mirror of https://github.com/Steffo99/todocolors.git synced 2024-11-22 00:04:18 +00:00

Setup editor config in server and reformat everything

This commit is contained in:
Steffo 2023-07-30 02:31:48 +02:00
parent 66384988db
commit a705e73803
Signed by: steffo
GPG key ID: 2A24051445686895
9 changed files with 170 additions and 156 deletions

View file

@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state>
</component>

9
todored/.editorconfig Normal file
View file

@ -0,0 +1,9 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = tab
insert_final_newline = true
tab_width = 4

View file

@ -1,43 +1,43 @@
use std::str::FromStr;
use axum::routing::{get, post};
pub mod task; pub mod task;
pub(crate) mod op; pub(crate) mod op;
mod config; mod config;
mod routes; mod routes;
mod utils; mod utils;
use std::str::FromStr;
use axum::routing::{get, post};
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
pretty_env_logger::init(); pretty_env_logger::init();
log::debug!("Logging initialized!"); log::debug!("Logging initialized!");
let rclient = redis::Client::open(&**config::REDIS_CONN) let rclient = redis::Client::open(&**config::REDIS_CONN)
.expect("to be able to connect to Redis"); .expect("to be able to connect to Redis");
let router = axum::Router::new() let router = axum::Router::new()
.route("/", get(routes::root::version)) .route("/", get(routes::root::version))
.route("/version", get(routes::root::version)) .route("/version", get(routes::root::version))
.route("/", post(routes::root::healthcheck)) .route("/", post(routes::root::healthcheck))
.route("/healthcheck", post(routes::root::healthcheck)) .route("/healthcheck", post(routes::root::healthcheck))
.route("/board/:board/ws", get(routes::board::websocket)) .route("/board/:board/ws", get(routes::board::websocket))
.layer(axum::Extension(rclient)) .layer(axum::Extension(rclient))
.layer(tower_http::cors::CorsLayer::new() .layer(tower_http::cors::CorsLayer::new()
.allow_origin( .allow_origin(
tower_http::cors::Any tower_http::cors::Any
) )
.allow_headers([ .allow_headers([
axum::http::header::AUTHORIZATION, axum::http::header::AUTHORIZATION,
axum::http::header::CONTENT_TYPE, axum::http::header::CONTENT_TYPE,
]) ])
.allow_methods( .allow_methods(
tower_http::cors::Any tower_http::cors::Any
) )
); );
axum::Server::bind(&std::net::SocketAddr::from_str(&**config::AXUM_HOST).expect("AXUM_HOST to be a valid SocketAddr")) axum::Server::bind(&std::net::SocketAddr::from_str(&**config::AXUM_HOST).expect("AXUM_HOST to be a valid SocketAddr"))
.serve(router.into_make_service()) .serve(router.into_make_service())
.await .await
.expect("to be able to run the Axum server"); .expect("to be able to run the Axum server");
} }

View file

@ -1,21 +1,22 @@
use serde::{Serialize, Deserialize}; use serde::{Deserialize, Serialize};
use uuid::Uuid; use uuid::Uuid;
use super::task::Task; use super::task::Task;
/// An operation sent from the client to the server. /// An operation sent from the client to the server.
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ClientOperation { pub enum ClientOperation {
/// Set the board's title. /// Set the board's title.
Title(String), Title(String),
/// Create a new [`Task`], or update or delete the task with the given [`Uuid`]. /// Create a new [`Task`], or update or delete the task with the given [`Uuid`].
Task(Option<Uuid>, Option<Task>) Task(Option<Uuid>, Option<Task>),
} }
/// An operation sent from the server to the clients, and stored on the database. /// An operation sent from the server to the clients, and stored on the database.
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ServerOperation { pub enum ServerOperation {
/// Set the board's title. /// Set the board's title.
Title(String), Title(String),
/// Create, update, or delete the [`Task`] with the given [`Uuid`]. /// Create, update, or delete the [`Task`] with the given [`Uuid`].
Task(Uuid, Option<Task>), Task(Uuid, Option<Task>),
} }

View file

@ -1,68 +1,67 @@
use axum::Extension; use axum::Extension;
use axum::extract::{Path, WebSocketUpgrade}; use axum::extract::{Path, WebSocketUpgrade};
use axum::extract::ws::{Message, WebSocket}; use axum::extract::ws::{Message, WebSocket};
use futures_util::{SinkExt, stream::{StreamExt, SplitSink, SplitStream}};
use axum::response::Response; use axum::response::Response;
use futures_util::{SinkExt, stream::{SplitSink, SplitStream, StreamExt}};
pub(crate) async fn websocket( pub(crate) async fn websocket(
Path(board): Path<String>, Path(board): Path<String>,
Extension(rclient): Extension<redis::Client>, Extension(rclient): Extension<redis::Client>,
ws: WebSocketUpgrade, ws: WebSocketUpgrade,
) -> Response { ) -> Response {
log::trace!("Received websocket request, upgrading..."); log::trace!("Received websocket request, upgrading...");
ws.on_upgrade(|socket| splitter(socket, rclient, board)) ws.on_upgrade(|socket| splitter(socket, rclient, board))
} }
async fn splitter( async fn splitter(
socket: WebSocket, socket: WebSocket,
rclient: redis::Client, rclient: redis::Client,
board: String, board: String,
) { ) {
log::trace!("Splitting socket into two separate pipes..."); log::trace!("Splitting socket into two separate pipes...");
let (mut sender, receiver) = socket.split(); let (mut sender, receiver) = socket.split();
log::trace!("Creating Redis connection for the reader thread..."); log::trace!("Creating Redis connection for the reader thread...");
let reader_redis = rclient.get_async_connection().await; let reader_redis = rclient.get_async_connection().await;
if reader_redis.is_err() { if reader_redis.is_err() {
log::error!("Could not open Redis connection for the reader thread."); log::error!("Could not open Redis connection for the reader thread.");
let _ = sender.close().await; let _ = sender.close().await;
return; return;
} }
let reader_redis = reader_redis.unwrap(); let reader_redis = reader_redis.unwrap();
log::trace!("Created Redis connection for the reader thread!"); log::trace!("Created Redis connection for the reader thread!");
log::trace!("Creating Redis connection for the writer thread..."); log::trace!("Creating Redis connection for the writer thread...");
let writer_redis = rclient.get_async_connection().await; let writer_redis = rclient.get_async_connection().await;
if writer_redis.is_err() { if writer_redis.is_err() {
log::error!("Could not open Redis connection for the writer thread."); log::error!("Could not open Redis connection for the writer thread.");
let _ = sender.close().await; let _ = sender.close().await;
return; return;
} }
let writer_redis = writer_redis.unwrap(); let writer_redis = writer_redis.unwrap();
log::trace!("Created Redis connection for the writer thread!"); log::trace!("Created Redis connection for the writer thread!");
let reader_thread = tokio::spawn(reader(receiver, reader_redis)); let reader_thread = tokio::spawn(reader(receiver, reader_redis));
let writer_thread = tokio::spawn(writer(sender, writer_redis)); let writer_thread = tokio::spawn(writer(sender, writer_redis));
} }
async fn reader( async fn reader(
receiver: SplitStream<WebSocket>, receiver: SplitStream<WebSocket>,
reader_redis: redis::aio::Connection, reader_redis: redis::aio::Connection,
) -> SplitStream<WebSocket> { ) -> SplitStream<WebSocket> {
log::trace!("Reader thread spawned successfully!"); log::trace!("Reader thread spawned successfully!");
todo!() todo!()
} }
async fn writer( async fn writer(
mut sender: SplitSink<WebSocket, Message>, mut sender: SplitSink<WebSocket, Message>,
writer_redis: redis::aio::Connection, writer_redis: redis::aio::Connection,
) -> SplitSink<WebSocket, Message> { ) -> SplitSink<WebSocket, Message> {
log::trace!("Writer thread spawned successfully!"); log::trace!("Writer thread spawned successfully!");
log::trace!("Sending test message..."); log::trace!("Sending test message...");
let _ = sender.send(Message::Text("\"Garasauto\"".to_string())).await; let _ = sender.send(Message::Text("\"Garasauto\"".to_string())).await;
log::trace!("Sent test message!"); log::trace!("Sent test message!");
todo!() todo!()
} }

View file

@ -1,37 +1,35 @@
use axum::{Extension, Json}; use axum::{Extension, Json};
use axum::http::StatusCode; use axum::http::StatusCode;
use crate::utils::{RedisConnectOr500, RedisUnwrapOr500, Result};
use crate::utils::{RedisConnectOr500, RedisUnwrapOr500, Result};
const MAJOR: u32 = pkg_version::pkg_version_major!(); const MAJOR: u32 = pkg_version::pkg_version_major!();
const MINOR: u32 = pkg_version::pkg_version_minor!(); const MINOR: u32 = pkg_version::pkg_version_minor!();
const PATCH: u32 = pkg_version::pkg_version_patch!(); const PATCH: u32 = pkg_version::pkg_version_patch!();
fn compose_version() -> String { fn compose_version() -> String {
format!("{}.{}.{}", MAJOR, MINOR, PATCH) format!("{}.{}.{}", MAJOR, MINOR, PATCH)
} }
pub async fn version( pub async fn version() -> Json<String> {
) -> Json<String> { Json(compose_version())
Json(compose_version())
} }
pub async fn healthcheck( pub async fn healthcheck(
Extension(rclient): Extension<redis::Client> Extension(rclient): Extension<redis::Client>
) -> Result<Json<String>> { ) -> Result<Json<String>> {
let mut rconn = rclient.get_connection_or_500().await?;
let mut rconn = rclient.get_connection_or_500().await?; log::trace!("Sending PING...");
let response = redis::cmd("PING")
.query_async::<redis::aio::Connection, String>(&mut rconn).await
.unwrap_or_500_and_log()?;
log::trace!("Sending PING..."); log::trace!("Sent PING and received: {:?}", response);
let response = redis::cmd("PING")
.query_async::<redis::aio::Connection, String>(&mut rconn).await
.unwrap_or_500_and_log()?;
log::trace!("Sent PING and received: {:?}", response); match response == "PONG" {
false => Err(StatusCode::INTERNAL_SERVER_ERROR),
match response == "PONG" { true => Ok(Json(compose_version())),
false => Err(StatusCode::INTERNAL_SERVER_ERROR), }
true => Ok(Json(compose_version())),
}
} }

View file

@ -1,65 +1,65 @@
use serde::{Serialize, Deserialize}; use serde::{Deserialize, Serialize};
/// A task that can be displayed on the board. /// A task that can be displayed on the board.
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Task { pub struct Task {
pub text: String, pub text: String,
pub icon: TaskIcon, pub icon: TaskIcon,
pub importance: TaskImportance, pub importance: TaskImportance,
pub priority: TaskPriority, pub priority: TaskPriority,
pub status: TaskStatus, pub status: TaskStatus,
} }
/// Possible icons for a [`Task`]. /// Possible icons for a [`Task`].
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub enum TaskIcon { pub enum TaskIcon {
User, User,
Image, Image,
Envelope, Envelope,
Star, Star,
Heart, Heart,
Comment, Comment,
FaceSmile, FaceSmile,
File, File,
Bell, Bell,
Bookmark, Bookmark,
Eye, Eye,
Hand, Hand,
PaperPlane, PaperPlane,
Handshake, Handshake,
Sun, Sun,
Clock, Clock,
Circle, Circle,
Square, Square,
Building, Building,
Flag, Flag,
Moon, Moon,
} }
/// The importance of a [`Task`] (how much it matters). /// The importance of a [`Task`] (how much it matters).
#[derive(Copy, Clone, Debug, Serialize, Deserialize)] #[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub enum TaskImportance { pub enum TaskImportance {
Highest, Highest,
High, High,
Normal, Normal,
Low, Low,
Lowest, Lowest,
} }
/// The priority of a [`Task`] (how soon it should be completed). /// The priority of a [`Task`] (how soon it should be completed).
#[derive(Copy, Clone, Debug, Serialize, Deserialize)] #[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub enum TaskPriority { pub enum TaskPriority {
Highest, Highest,
High, High,
Normal, Normal,
Low, Low,
Lowest, Lowest,
} }
/// The status a [`Task`] is currently in. /// The status a [`Task`] is currently in.
#[derive(Copy, Clone, Debug, Serialize, Deserialize)] #[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub enum TaskStatus { pub enum TaskStatus {
Unfinished, Unfinished,
InProgress, InProgress,
Complete, Complete,
} }

View file

@ -1,35 +1,37 @@
use async_trait::async_trait; use async_trait::async_trait;
use axum::http::StatusCode; use axum::http::StatusCode;
pub type Result<T> = std::result::Result<T, StatusCode>; pub type Result<T> = std::result::Result<T, StatusCode>;
pub(crate) trait RedisUnwrapOr500<T> { pub(crate) trait RedisUnwrapOr500<T> {
fn unwrap_or_500_and_log(self) -> Result<T>; fn unwrap_or_500_and_log(self) -> Result<T>;
} }
impl<T> RedisUnwrapOr500<T> for redis::RedisResult<T> { impl<T> RedisUnwrapOr500<T> for redis::RedisResult<T> {
fn unwrap_or_500_and_log(self) -> Result<T> { fn unwrap_or_500_and_log(self) -> Result<T> {
self self
.map_err(|e| { log::error!("{e:#?}"); e }) .map_err(|e| {
.or(Err(StatusCode::INTERNAL_SERVER_ERROR)) log::error!("{e:#?}");
} e
})
.or(Err(StatusCode::INTERNAL_SERVER_ERROR))
}
} }
#[async_trait] #[async_trait]
pub(crate) trait RedisConnectOr500 { pub(crate) trait RedisConnectOr500 {
async fn get_connection_or_500(&self) -> Result<redis::aio::Connection>; async fn get_connection_or_500(&self) -> Result<redis::aio::Connection>;
} }
#[async_trait] #[async_trait]
impl RedisConnectOr500 for redis::Client { impl RedisConnectOr500 for redis::Client {
async fn get_connection_or_500(&self) -> Result<redis::aio::Connection> { async fn get_connection_or_500(&self) -> Result<redis::aio::Connection> {
log::trace!("Connecting to Redis..."); log::trace!("Connecting to Redis...");
let rconn = self.get_async_connection().await let rconn = self.get_async_connection().await
.unwrap_or_500_and_log()?; .unwrap_or_500_and_log()?;
log::trace!("Connection successful!"); log::trace!("Connection successful!");
Ok(rconn) Ok(rconn)
} }
} }