rust_hello_world's People
rust_hello_world's Issues
Feedback:)
let address = chat::Address::parse_arguments();
Very nice:) Good exercise, and minimalistic. Most apps do this via clap or a similar library (I like argh)
lazy_static! {
static ref REGISTRY: Registry = Registry::new();
static ref MESSAGE_COUNTER: Counter =
Counter::new("message_counter", "counts number of messages send")
.expect("Counter metrics init failed!");
static ref USER_COUNTER: Gauge = Gauge::new("user_counter", "counts number of connected users")
.expect("Gauge metrics init failed!");
}
Good use of lazy_static for initializing Prometheus metrics! I am personally quite partial to lazy_static because I was "classically trained", but soon, we will have tools for this in standard library:
- once_cell was merged into std not long ago
- LazyCell and LazyLock should be merged in Rust 1.80 :)
fn log_broadcasting(
message: &Message,
sender_addr: &std::net::SocketAddr,
receiver_addr: &std::net::SocketAddr,
) {
if log_enabled!(Level::Debug) {
debug!(
"Broadcasting message from client {:?} to client {:?} ({:?}).",
sender_addr, receiver_addr, message
);
} else {
info!(
"Broadcasting message from client {:?} to client {:?}.",
sender_addr, receiver_addr
);
};
}
This logging function is well-structured, but you could simplify it using the log
macro's built-in conditional compilation:
log::debug!(
"Broadcasting message from client {:?} to client {:?} ({:?}).",
sender_addr, receiver_addr, message
);
log::info!(
"Broadcasting message from client {:?} to client {:?}.",
sender_addr, receiver_addr
);
With the correct Cargo features set for the log library:
e.g.
[dependencies]
log = { version = "0.4", features = ["max_level_debug", "release_max_level_warn"] }
===
async fn run_server() -> Result<()> {
// ...
loop {
let Ok((stream, addr)) = listener.accept().await else {
error!("Failed to accept connection!");
continue;
};
// ...
}
}
Good use of the let-else
pattern for error handling. It's the most readable solution imo.:)
async fn init_db() -> Result<SqlitePool> {
if !Sqlite::database_exists(DB).await.unwrap_or(false) {
info!("Creating database: {}", DB);
Sqlite::create_database(DB)
.await
.context("Creating database error!")?;
}
// ...
}
Your usage of database is quite elegant. One thing I would like to note is that if you are writing pure Rocket apps, there are two tools you can use:
State
to keep track of database connections for databases Rocket does not have native support for- https://api.rocket.rs/v0.5/rocket_db_pools/ for the ones that Rocket does support natively (which is quite a few)
The meow() function should be async, and it should use tokio sleep, roughly:
async fn reading_loop(mut stream: OwnedReadHalf) -> Result<()> {
loop {
let message = chat::Message::read(&mut stream).await?;
if let Err(err_msg) = handle_message(message).await {
eprintln!("Message handling error: {:?}", err_msg);
};
tokio::spawn(async {
meow().await.unwrap_or_else(|err_msg| eprintln!("Sound error {:?}", err_msg))
});
}
}
async fn meow() -> Result<()> {
let (_stream, stream_handle) = OutputStream::try_default()?;
let file = std::fs::File::open(SOUND_FILE)?; // should also replace with tokio::fs::File
let source = Decoder::new(std::io::BufReader::new(file))?;
stream_handle.play_raw(source.convert_samples())?;
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
Ok(())
}
It does not matter in such as small application, but this function will actually block the tokio scheduler on this thread for two seconds + time taken to read the wav, which would impact performance in bigger applications
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. ๐๐๐
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google โค๏ธ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.