Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(#17): register_user, Storage redesigned to struct #61

Merged
merged 10 commits into from
Jul 11, 2024
2 changes: 2 additions & 0 deletions server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,11 @@ path = "src/lib.rs"
openapi = { path = "../github-mirror" }
anyhow = "1.0.86"
serde = { version = "1.0.203", features = ["derive"] }
serde-xml-rs = "0.6.0"
serde_json = "1.0.117"
tokio = { version = "1.0.0", features = ["rt", "rt-multi-thread", "macros", "fs"] }
axum = "0.7.5"
log = { version = "0.4.21", features = [] }
env_logger = "0.11.3"
tempdir = "0.3.7"
tracing-subscriber = "0.3.18"
13 changes: 9 additions & 4 deletions server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,15 @@
use std::io;

use anyhow::Result;
use axum::routing::get;
use axum::routing::{get, post};
use axum::Router;
use tokio::net::TcpListener;

use crate::routes::home;
use crate::xml::storage::touch_storage;
use crate::routes::register_user::register_user;
use crate::xml::storage::Storage;

mod objects;
pub mod report;
mod routes;
mod xml;
Expand All @@ -46,8 +48,11 @@ impl Server {

impl Server {
pub async fn start(self) -> Result<()> {
touch_storage(Some("fakehub.xml"));
let app: Router = Router::new().route("/", get(home::home));
tracing_subscriber::fmt::init();
Storage::new(Some("fakehub.xml"));
let app: Router = Router::new()
.route("/", get(home::home))
.route("/users", post(register_user));
let addr: String = format!("0.0.0.0:{}", self.port);
let started: io::Result<TcpListener> = TcpListener::bind(addr.clone()).await;
match started {
Expand Down
22 changes: 22 additions & 0 deletions server/src/objects/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// The MIT License (MIT)
//
// Copyright (c) 2024 Aliaksei Bialiauski
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pub mod user;
70 changes: 70 additions & 0 deletions server/src/objects/user.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// The MIT License (MIT)
//
// Copyright (c) 2024 Aliaksei Bialiauski
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use anyhow::Result;
use log::{debug, info};
use serde::{Deserialize, Serialize};
use serde_xml_rs::to_string;

#[derive(Debug, Serialize, Deserialize)]
pub struct User {
pub(crate) username: String,
}

impl User {
pub fn new(username: String) -> User {
User { username }
}
}

// @todo #17:40min Apply XMLed user to the <users/> node in storage.
// We should apply XMLed user to the <users> XML node in storage. First we
// need to check that user with provided name does not exist, and only then
// apply it to the storage. Keep in mind that application function in the
// storage should be thread-safe (as well as #xml function). Don't forget to
// create unit tests that prove that.
impl User {
pub async fn save(self) -> Result<()> {

Check warning on line 45 in server/src/objects/user.rs

View check run for this annotation

Codecov / codecov/patch

server/src/objects/user.rs#L45

Added line #L45 was not covered by tests
info!("registering user @{}", self.username);
let xml = to_string(&self).unwrap();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's avoid such #unwrap calls, can you set clippy or create puzzle for it?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@l3r8yJ I will create one

debug!("XMLed user: {}", xml);
Ok(())
}
}

#[cfg(test)]
mod tests {
use anyhow::Result;

use crate::objects::user::User;

#[test]
fn returns_username() -> Result<()> {
let expected = "jeff";
let jeff = User::new(String::from(expected));
assert_eq!(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@h1alexbel might be we should add hamcrest to project?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@l3r8yJ good idea. Let's try it

jeff.username, expected,
"Username {} from user: {:?} does not match with expected {}",
jeff.username, jeff, expected
);
Ok(())
}
}
1 change: 1 addition & 0 deletions server/src/routes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pub mod home;
pub mod register_user;
pub mod rs_err;
33 changes: 33 additions & 0 deletions server/src/routes/register_user.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// The MIT License (MIT)
//
// Copyright (c) 2024 Aliaksei Bialiauski
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use axum::http::StatusCode;
use axum::Json;

use crate::objects::user::User;

pub async fn register_user(Json(payload): Json<User>) -> Result<StatusCode, String> {

Check warning on line 27 in server/src/routes/register_user.rs

View check run for this annotation

Codecov / codecov/patch

server/src/routes/register_user.rs#L27

Added line #L27 was not covered by tests
let user = User::new(payload.username.clone());
match user.save().await {
Ok(_) => Ok(StatusCode::CREATED),
Err(e) => Err(format!("Can't register {}: {}", payload.username, e)),
}
}
75 changes: 61 additions & 14 deletions server/src/xml/storage.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
use std::fs::File;
use std::io::Write;

// The MIT License (MIT)
//
// Copyright (c) 2024 Aliaksei Bialiauski
Expand All @@ -19,37 +22,66 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use std::fs::File;

use anyhow::Result;
use log::info;

pub fn touch_storage(path: Option<&str>) -> File {
let location = path.unwrap_or("fakehub.xml");
info!("Initializing XML storage: {location}");
match File::create(location) {
Ok(file) => {
info!("'{location}' initialized");
file
#[derive(Default)]
#[allow(dead_code)]
pub struct Storage {
pub(crate) path: String,
}

impl Storage {
pub fn new(path: Option<&str>) -> Storage {
let location = path.unwrap_or("fakehub.xml");
info!("Initializing XML storage: {location}");
let mut file = match File::create(location) {
Ok(file) => file,
Err(err) => {
panic!("fakehub storage failed to initialize in '{location}': {err}");

Check warning on line 41 in server/src/xml/storage.rs

View check run for this annotation

Codecov / codecov/patch

server/src/xml/storage.rs#L40-L41

Added lines #L40 - L41 were not covered by tests
}
};
if let Err(err) = file.write_all(
"<root>\
<github><users/></github>\
</root>"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@h1alexbel i think we can move it to some constant

.as_bytes(),
) {
panic!("Failed to write initial content to '{}': {}", location, err);

Check warning on line 50 in server/src/xml/storage.rs

View check run for this annotation

Codecov / codecov/patch

server/src/xml/storage.rs#L50

Added line #L50 was not covered by tests
}
Err(err) => {
panic!("fakehub storage failed to initialize in '{location}': {err}")
info!("'{}' initialized", location);
Storage {
path: String::from(location),
}
}
}

// @todo #17:35min Implement #xml function in Storage.
// This function should return full XML storage has at the moment. #xml
// function should be thread-safe, as it intended to be used concurrently.
// Don't forget to create a unit tests related to #xml function.
impl Storage {
#[allow(dead_code)]
pub fn xml() -> Result<()> {
Ok(())

Check warning on line 66 in server/src/xml/storage.rs

View check run for this annotation

Codecov / codecov/patch

server/src/xml/storage.rs#L66

Added line #L66 was not covered by tests
}
}

#[cfg(test)]
mod tests {
use std::fs;

use anyhow::Result;
use tempdir::TempDir;

use crate::xml::storage::touch_storage;
use crate::xml::storage::Storage;

#[test]
fn creates_xml_storage() -> Result<()> {
let temp = TempDir::new("temp")?;
let path = temp.path().join("fakehub.xml");
let storage = path.to_str();
touch_storage(storage);
Storage::new(storage);
assert!(
path.exists(),
"storage file {:?} was not created, but should be",
Expand All @@ -58,12 +90,27 @@
Ok(())
}

#[test]
fn reads_initial_content() -> Result<()> {
let temp = TempDir::new("temp")?;
let path = temp.path().join("fakehub.xml");
Storage::new(path.to_str());
let xml = fs::read_to_string(path).unwrap();
let expected = "<root><github><users/></github></root>";
assert_eq!(
xml, expected,
"Received initial XML {} does not match with expected {}",
xml, expected
);
Ok(())
}

#[test]
fn creates_xml_storage_with_different_name() -> Result<()> {
let temp = TempDir::new("temp")?;
let path = temp.path().join("test.xml");
let storage = path.to_str();
touch_storage(storage);
Storage::new(storage);
assert!(
path.exists(),
"storage file {:?} was not created, but should be",
Expand Down
Loading