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 - fragment request server listener #55

Merged
merged 20 commits into from
Jan 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
7b729c2
feat(server): binding listener on fragment request
jabibamman Nov 24, 2023
1641059
doc: add rustdoc to server messages
jabibamman Nov 24, 2023
529e093
chore(types): add Serialize and deserialize serde to all types
jabibamman Nov 25, 2023
1774d84
chore: remove whitespace in write.rs
jabibamman Nov 25, 2023
63176e2
feat(server): server write fragment task to the client
jabibamman Nov 25, 2023
13f9255
feat(logger): implement env_logger and server logger usage
jabibamman Dec 3, 2023
1e73f83
feat(logger): implement client logger usage
jabibamman Dec 3, 2023
8df131b
chore: delete unused utils
jabibamman Dec 3, 2023
70f57b3
chore(handler): update handler logger
jabibamman Dec 3, 2023
73e4c6a
doc(serialization): update serialization doc
jabibamman Dec 3, 2023
9275866
Merge branch 'develop' into feat/server/fragment-request
jabibamman Dec 19, 2023
95f24e7
Merge branch 'develop' into feat/server/fragment-request
jabibamman Dec 25, 2023
c264f52
fix(server): update serialization using ronan func
jabibamman Dec 25, 2023
b8155a3
chore(parser): Add optional flags for verbose, debug, and open
jabibamman Dec 25, 2023
88abbc8
fix(handler): enhance message handling to read json size from stream
jabibamman Dec 26, 2023
d9b64af
Merge branch 'develop' into feat/server/fragment-request
jabibamman Jan 6, 2024
cf82e97
refacto: delete panic clean code
jabibamman Jan 6, 2024
44ea824
Restyled by rustfmt
restyled-commits Jan 6, 2024
19c7c74
Restyled by whitespace
restyled-commits Jan 6, 2024
94cd521
Merge pull request #56 from jabibamman/restyled/feat/server/fragment-…
jabibamman Jan 6, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,34 @@ To run the server with CLI, use the following command:
cargo run -p server -- -h
```

## Using debug log level

To use the debug log level, use the following command:

### Unix/Linux/MacOS

```bash
RUST_LOG=debug cargo run -p client
RUST_LOG=debug cargo run -p server
```

### Windows

#### CMD

```bash
set RUST_LOG=debug
cargo run -p client
cargo run -p server
```

#### PowerShell

```bash
$env:RUST_LOG="debug"; cargo run -p client
$env:RUST_LOG="debug"; cargo run -p server
```

## Documentation

To generate documentation for all packages without including dependencies (recommended):
Expand Down
62 changes: 18 additions & 44 deletions cli/src/operation.rs
Original file line number Diff line number Diff line change
@@ -1,69 +1,43 @@
use crate::parser::CliArgs;

/// Parses `CliArgs` to create a formatted address string.
///
/// This function takes an instance of `CliArgs` and returns a string representing an address.
/// It supports both client and server arguments. The address format is "hostname:port".
///
/// ## Parameters
/// - `cli_args`: An instance of `CliArgs`, which can be either `CliClientArgs` or `CliServerArgs`.
///
/// ## Returns
/// A `String` that represents the address in the format "hostname:port".
///
/// ## Examples
/// Assuming `CliArgs::Client` variant is used with hostname "192.168.1.0" and port 8787:
/// ```rust
/// use cli::{parser::{CliClientArgs, Parser, CliArgs}, operation::parse_to_address};
///
/// let client_args = CliArgs::Client(CliClientArgs {
/// hostname: "192.168.1.0".to_string(),
/// port: 8787,
/// worker_name: "worker".to_string(),
/// });
///
/// let address = parse_to_address(client_args);
/// assert_eq!(address, "192.168.1.0:8787");
/// ```
/// Similarly, you can create an instance of `CliArgs::Server` and pass it to this function.
pub fn parse_to_address(cli_args: CliArgs) -> String {
match cli_args {
CliArgs::Client(args) => format!("{}:{}", args.hostname, args.port),
CliArgs::Server(args) => format!("{}:{}", args.hostname, args.port),
}
}

#[cfg(test)]
mod operation_tests {
use super::*;
use crate::parser::{CliArgs, CliClientArgs, CliServerArgs};
use crate::parser::{CliClientArgs, CliServerArgs};

pub fn initialize() -> CliServerArgs {
CliServerArgs {
hostname: "127.0.0.1".to_string(),
port: 8787,
verbose: false,
debug: false,
}
}

#[test]
fn test_parse_client_to_address() {
let args = initialize();
let client_args = CliArgs::Client(CliClientArgs {
hostname: args.hostname,
port: args.port,
let client_args: CliClientArgs = CliClientArgs {
hostname: args.hostname.clone(),
port: args.port.clone(),
worker_name: "worker".to_string(),
});
verbose: args.verbose.clone(),
debug: args.debug.clone(),
open: false,
};

let address = parse_to_address(client_args);
let address = format!("{}:{}", client_args.hostname, client_args.port);
assert_eq!(address, "127.0.0.1:8787");
}

#[test]
fn test_parse_server_to_address() {
let args = initialize();
let server_args = CliArgs::Server(args);
let server_args: CliServerArgs = CliServerArgs {
hostname: args.hostname.clone(),
port: args.port.clone(),
verbose: args.verbose.clone(),
debug: args.debug.clone(),
};

let address = parse_to_address(server_args);
let address = format!("{}:{}", server_args.hostname, server_args.port);
assert_eq!(address, "127.0.0.1:8787");
}
}
31 changes: 28 additions & 3 deletions cli/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,35 @@ pub use clap::Parser;
/// ```
#[derive(Parser, Debug, Clone)]
pub struct CliClientArgs {
/// The hostname of the client.
/// Optional: The hostname of the client.
/// Default: "localhost"
#[clap(short = 'H', long = "hostname", default_value = "localhost")]
pub hostname: String,

/// The port number to connect on.
/// Optional: The port number to connect on.
/// Default: 8787
#[clap(short = 'P', long = "port", default_value = "8787")]
pub port: u16,

/// The name of the worker.
/// Optional: The name of the worker.
/// Default: "worker"
#[clap(short = 'N', long = "name", default_value = "worker")]
pub worker_name: String,

/// Optional: Add a flag to enable/disable logging.
/// Default: false
#[clap(short = 'v', long = "verbose", default_value = "false")]
pub verbose: bool,

/// Optional: Add a flag to enable/disable debug mode.
/// Default: false
#[clap(short = 'd', long = "debug", default_value = "false")]
pub debug: bool,

/// Optional: Add a flag to enable/disable opening the browser.
/// Default: false
#[clap(short = 'o', long = "open", default_value = "false")]
pub open: bool,
}

/// Represents command line arguments for a server in a CLI application.
Expand Down Expand Up @@ -58,6 +73,16 @@ pub struct CliServerArgs {
/// Default: 8787
#[clap(short = 'P', long = "port", default_value = "8787")]
pub port: u16,

/// Optional: Add a flag to enable/disable logging.
/// Default: false
#[clap(short = 'v', long = "verbose", default_value = "false")]
pub verbose: bool,

/// Optional: Add a flag to enable/disable debug mode.
/// Default: false
#[clap(short = 'd', long = "debug", default_value = "false")]
pub debug: bool,
}

/// An enumeration representing the possible types of command line arguments.
Expand Down
1 change: 1 addition & 0 deletions client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ edition = "2021"

[dependencies]
image = { version = "0.24.7", features = [] }
log = "0.4.20"
complex = { path = "../complex" }
shared = { path = "../shared" }
server = { path = "../server" }
Expand Down
2 changes: 2 additions & 0 deletions client/src/fractal_generation.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use complex::complex_operations::ComplexOperations;
use complex::fractal_operations::FractalOperations;
use image::{ImageBuffer, Rgb};
use log::info;
use shared::types::color::{HSL, RGB};
use shared::types::complex::Complex;
use shared::types::fractal_descriptor::FractalType::{
Expand Down Expand Up @@ -37,6 +38,7 @@ pub fn generate_fractal_set(fragment_task: FragmentTask) -> ImageBuffer<Rgb<u8>,

let mut img = ImageBuffer::new(resolution.nx.into(), resolution.ny.into());

info!("Generating fractal set...");
for (x, y, pixel) in img.enumerate_pixels_mut() {
let scaled_x = x as f64 * scale_x + range.min.x;
let scaled_y = y as f64 * scale_y + range.min.y;
Expand Down
61 changes: 34 additions & 27 deletions client/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use shared::types::complex::Complex;
use shared::utils::fragment_request_impl::FragmentRequestOperation;

mod fractal_generation;
Expand All @@ -9,10 +10,11 @@ use crate::fractal_generation::generate_fractal_set;
use crate::image::open_image;

use cli::parser::{CliClientArgs, Parser};
use log::{debug, error, info};
use server::services::{connect::connect, reader::get_response, write::write};
use shared::types::filesystem::FileExtension;
use shared::types::fractal_descriptor::FractalType::NewtonRaphsonZ4;
use shared::types::fractal_descriptor::{FractalDescriptor, NewtonRaphsonZ4Descriptor};
use shared::types::fractal_descriptor::FractalType::Julia;
use shared::types::fractal_descriptor::{FractalDescriptor, JuliaDescriptor};
use shared::types::messages::{FragmentRequest, FragmentTask};
use shared::types::point::Point;
use shared::types::range::Range;
Expand All @@ -21,31 +23,33 @@ use shared::types::u8data::U8Data;
use shared::utils::filesystem::{get_dir_path_buf, get_extension_str, get_file_path};

fn main() -> io::Result<()> {
shared::logger::init_logger();

let cli_args: CliClientArgs = CliClientArgs::parse();
let fragment_request = FragmentRequest::new(cli_args.worker_name, 100);
let fragment_request = FragmentRequest::new(cli_args.worker_name, 1000);
let serialized_request = fragment_request.serialize()?;
let connection_result = connect(format!("{}:{}", cli_args.hostname, cli_args.port).as_str());

if let Ok(mut stream) = connection_result {
println!("Connected to the server!");

info!("Connected to the server!");
debug!("Sending message: {}", serialized_request);
match write(&mut stream, serialized_request.as_str()) {
Ok(_) => println!("Message sent!"),
Err(error) => println!("Failed to send message: {}", error),
Ok(_) => info!("Message sent!"),
Err(error) => error!("Failed to send message, {}", error),
}

let response = get_response(&mut stream)?;
println!("Response received: {:?}", response);
debug!("Response received: {:?}", response);
} else if let Err(e) = connection_result {
println!("Failed to connect: {}", e);
error!("Failed to connect to the server: {}", e);
}

let img_path = match get_dir_path_buf() {
Ok(dir_path_buf) => {
match get_file_path("z4", dir_path_buf, get_extension_str(FileExtension::PNG)) {
match get_file_path("julia", dir_path_buf, get_extension_str(FileExtension::PNG)) {
Ok(img_path) => img_path,
Err(e) => {
eprintln!(
error!(
"Erreur lors de la récupération du chemin du fichier : {}",
e
);
Expand All @@ -54,7 +58,7 @@ fn main() -> io::Result<()> {
}
}
Err(e) => {
eprintln!("Erreur lors de la récupération du répertoire : {}", e);
error!("Erreur lors de la récupération du répertoire : {}", e);
return Ok(());
}
};
Expand All @@ -65,8 +69,9 @@ fn main() -> io::Result<()> {
count: 16,
},
fractal: FractalDescriptor {
fractal_type: NewtonRaphsonZ4(NewtonRaphsonZ4Descriptor{
//c: Complex { re: 0.2, im: 1.0 },
fractal_type: Julia(JuliaDescriptor {
c: Complex { re: 0.2, im: 1.0 },
divergence_threshold_square: 4.0,
}),
},
max_iteration: 64,
Expand All @@ -81,24 +86,26 @@ fn main() -> io::Result<()> {
};

match generate_fractal_set(fragment_task).save(img_path.clone().as_str()) {
Ok(_) => println!("L'image de la fractale a été sauvegardée !"),
Err(e) => println!(
Ok(_) => info!("L'image de la fractale a été sauvegardée !"),
Err(e) => error!(
"Erreur lors de la sauvegarde de l'image de la fractale : {}",
e
),
}

match open_image(img_path.as_str()) {
Ok(_) => {
println!("L'image de la fractale a été ouverte !");
Ok(())
}
Err(e) => {
println!(
"Erreur lors de l'ouverture de l'image de la fractale : {}",
e
);
Err(e)
if cli_args.open {
match open_image(img_path.as_str()) {
Ok(_) => {
info!("L'image de la fractale a été ouverte !");
}
Err(e) => {
error!(
"Erreur lors de l'ouverture de l'image de la fractale: {}",
e
);
}
}
}

Ok(())
}
20 changes: 14 additions & 6 deletions complex/src/newtonraphsonz_descriptor_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ impl FractalOperations for NewtonRaphsonZ3Descriptor {
let mut iterations = 0;

while iterations < max_iteration {
let next_z = newton_raphson_step(&z, 3);
let next_z = match newton_raphson_step(&z, 3) {
Ok(z) => z,
Err(_) => break,
};

if (next_z.sub(&z)).magnitude_squared() < 1e-6 {
break;
}
Expand Down Expand Up @@ -78,7 +82,11 @@ impl FractalOperations for NewtonRaphsonZ4Descriptor {
let mut iterations = 0;

while iterations < max_iteration {
let next_z = newton_raphson_step(&z, 4);
let next_z = match newton_raphson_step(&z, 4) {
Ok(z) => z,
Err(_) => break,
};

if (next_z.sub(&z)).magnitude_squared() < 1e-6 {
break;
}
Expand All @@ -103,20 +111,20 @@ impl FractalOperations for NewtonRaphsonZ4Descriptor {
/// # Returns
///
/// Le prochain point complexe dans l'itération pour NewtonRaphsonZ3.
fn newton_raphson_step(z: &Complex, degree: u32) -> Complex {
fn newton_raphson_step(z: &Complex, degree: u32) -> Result<Complex, &'static str> {
match degree {
3 => {
// p(z) = z^3 - 1 et p'(z) = 3z^2
let pz = z.square().mul(z).sub(&Complex::new(1.0, 0.0));
let dpz = z.square().mul(&Complex::new(3.0, 0.0));
z.sub(&pz.div(dpz))
Ok(z.sub(&pz.div(dpz)))
}
4 => {
// p(z) = z^4 - 1 et p'(z) = 4z^3
let pz = z.square().square().sub(&Complex::new(1.0, 0.0));
let dpz = z.square().mul(z).mul(&Complex::new(4.0, 0.0));
z.sub(&pz.div(dpz))
Ok(z.sub(&pz.div(dpz)))
}
_ => panic!("Unsupported polynomial degree"),
_ => Err("Degree must be 3 or 4"),
}
}
3 changes: 3 additions & 0 deletions server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ edition = "2021"
complex = { path = "../complex" }
shared = { path = "../shared" }
cli = { path = "../cli" }
serde = { version = "1.0.193", features = ["derive"] }
serde_json ="1.0.108"
log = "0.4.20"

[lib]
path = "src/lib.rs"
Loading