1
Fork 0
mirror of https://github.com/Steffo99/todocolors.git synced 2024-10-16 07:17:28 +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,4 +1,4 @@
use micronfig::required;
required!(REDIS_CONN, String);
required!(AXUM_HOST, String); // FIXME: Use SocketAddr when possible
required!(AXUM_HOST, String); // FIXME: Use SocketAddr when possible

View file

@ -1,43 +1,43 @@
use std::str::FromStr;
use axum::routing::{get, post};
pub mod task;
pub(crate) mod op;
mod config;
mod routes;
mod utils;
use std::str::FromStr;
use axum::routing::{get, post};
#[tokio::main]
async fn main() {
pretty_env_logger::init();
log::debug!("Logging initialized!");
pretty_env_logger::init();
log::debug!("Logging initialized!");
let rclient = redis::Client::open(&**config::REDIS_CONN)
.expect("to be able to connect to Redis");
let rclient = redis::Client::open(&**config::REDIS_CONN)
.expect("to be able to connect to Redis");
let router = axum::Router::new()
.route("/", get(routes::root::version))
.route("/version", get(routes::root::version))
.route("/", post(routes::root::healthcheck))
.route("/healthcheck", post(routes::root::healthcheck))
.route("/board/:board/ws", get(routes::board::websocket))
.layer(axum::Extension(rclient))
.layer(tower_http::cors::CorsLayer::new()
.allow_origin(
tower_http::cors::Any
)
.allow_headers([
axum::http::header::AUTHORIZATION,
axum::http::header::CONTENT_TYPE,
])
.allow_methods(
tower_http::cors::Any
)
);
let router = axum::Router::new()
.route("/", get(routes::root::version))
.route("/version", get(routes::root::version))
.route("/", post(routes::root::healthcheck))
.route("/healthcheck", post(routes::root::healthcheck))
.route("/board/:board/ws", get(routes::board::websocket))
.layer(axum::Extension(rclient))
.layer(tower_http::cors::CorsLayer::new()
.allow_origin(
tower_http::cors::Any
)
.allow_headers([
axum::http::header::AUTHORIZATION,
axum::http::header::CONTENT_TYPE,
])
.allow_methods(
tower_http::cors::Any
)
);
axum::Server::bind(&std::net::SocketAddr::from_str(&**config::AXUM_HOST).expect("AXUM_HOST to be a valid SocketAddr"))
.serve(router.into_make_service())
.await
.expect("to be able to run the Axum server");
axum::Server::bind(&std::net::SocketAddr::from_str(&**config::AXUM_HOST).expect("AXUM_HOST to be a valid SocketAddr"))
.serve(router.into_make_service())
.await
.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 super::task::Task;
/// An operation sent from the client to the server.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ClientOperation {
/// Set the board's title.
Title(String),
/// Create a new [`Task`], or update or delete the task with the given [`Uuid`].
Task(Option<Uuid>, Option<Task>)
/// Set the board's title.
Title(String),
/// Create a new [`Task`], or update or delete the task with the given [`Uuid`].
Task(Option<Uuid>, Option<Task>),
}
/// An operation sent from the server to the clients, and stored on the database.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ServerOperation {
/// Set the board's title.
Title(String),
/// Create, update, or delete the [`Task`] with the given [`Uuid`].
Task(Uuid, Option<Task>),
/// Set the board's title.
Title(String),
/// Create, update, or delete the [`Task`] with the given [`Uuid`].
Task(Uuid, Option<Task>),
}

View file

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

View file

@ -1,37 +1,35 @@
use axum::{Extension, Json};
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 MINOR: u32 = pkg_version::pkg_version_minor!();
const PATCH: u32 = pkg_version::pkg_version_patch!();
fn compose_version() -> String {
format!("{}.{}.{}", MAJOR, MINOR, PATCH)
format!("{}.{}.{}", MAJOR, MINOR, PATCH)
}
pub async fn version(
) -> Json<String> {
Json(compose_version())
pub async fn version() -> Json<String> {
Json(compose_version())
}
pub async fn healthcheck(
Extension(rclient): Extension<redis::Client>
Extension(rclient): Extension<redis::Client>
) -> 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...");
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);
log::trace!("Sent PING and received: {:?}", response);
match response == "PONG" {
false => Err(StatusCode::INTERNAL_SERVER_ERROR),
true => Ok(Json(compose_version())),
}
match response == "PONG" {
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.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Task {
pub text: String,
pub icon: TaskIcon,
pub importance: TaskImportance,
pub priority: TaskPriority,
pub status: TaskStatus,
pub text: String,
pub icon: TaskIcon,
pub importance: TaskImportance,
pub priority: TaskPriority,
pub status: TaskStatus,
}
/// Possible icons for a [`Task`].
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum TaskIcon {
User,
Image,
Envelope,
Star,
Heart,
Comment,
FaceSmile,
File,
Bell,
Bookmark,
Eye,
Hand,
PaperPlane,
Handshake,
Sun,
Clock,
Circle,
Square,
Building,
Flag,
Moon,
User,
Image,
Envelope,
Star,
Heart,
Comment,
FaceSmile,
File,
Bell,
Bookmark,
Eye,
Hand,
PaperPlane,
Handshake,
Sun,
Clock,
Circle,
Square,
Building,
Flag,
Moon,
}
/// The importance of a [`Task`] (how much it matters).
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub enum TaskImportance {
Highest,
High,
Normal,
Low,
Lowest,
Highest,
High,
Normal,
Low,
Lowest,
}
/// The priority of a [`Task`] (how soon it should be completed).
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub enum TaskPriority {
Highest,
High,
Normal,
Low,
Lowest,
Highest,
High,
Normal,
Low,
Lowest,
}
/// The status a [`Task`] is currently in.
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub enum TaskStatus {
Unfinished,
InProgress,
Complete,
Unfinished,
InProgress,
Complete,
}

View file

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