Hi rustaecans!
I've been making my own self-hostable chat server and client in rust for a few months. And now that I have added tls encryption, I want to know what I can improve about my code, but also what is already good about my code.
Here is the repo: https://github.com/Cheese-Space/8080_msg.
There are already some things which I could improve which I'm aware of like more comments and some functions in the library. The README could also be more detailed.
Have you used SI ever? Major benefit of using SI, it puts exceeding comments in the generated code. For example, you obtain arguments, and then immediately call next(). Why ? What if there are no arguments at all? Why didn't you use clap or simcli. So I recommend to start documenting own code, and then reviewing it will be a full pleasure.
A satisfying degree of code documentation always helps enthusiastic people contribute more effectively to code reviews. But when comments are sparse, the review process becomes somewhat challenging, especially in larger codebases. Personally, I find that more fun ![]()
Are you talking about Artificial Inteligence there? I have never seen anyone use "SI" for that before. Had me scratching my head for a while.
Why would I use ai only for the code comments? I think I would understand my own code better then the ai so shouldn’t I be the one writing comments?
Alright, I had a look. I'm glad to give code review to a human!
So the up front problems:
- I'm not sure how to generate certificates with your program. It's unclear to me from reading the code whether this would need a certificate from an actual CA (the tty_8080 src starts with an empty root store)? and there's no client auth enabled, so I'm not sure why the client needs one
- The code needs to be split up in to multiple functions, in one file I saw up to 10 indent levels and the file went off my screen in both directions. It's really hard to keep all of this in my head for review
- I'm not really sure how I feel about having a 'prelude' file that has all your includes, ideally that will change once you split things up
- There's quite a few typos. Having a spell checker on is helpful. The main reason I bring this up is it makes grepping/searching a codebase easier
I'm sure you're already aware of most of this, especially as you have split things up already in to a crate for some of it. If you need help figuring out how to do this or don't know where to start, it would be good to ask here ![]()
Looking at the design after a bit of spelunking, I'm not liking the approach you have of multiple async threads sharing a lot of data and using locks to figure things out. The first reason is that it's very, very hard to reason about whether this is correct. The second is that there doesn't seem to be a total order of events.
So for example, what happens if two clients kick each other? Ideally we would acknowledge that one user wins the race to kick and the other's kick is ignored. But here it's unclear at the conceptual level, which means it's up to whatever the code does. Something like revoking privileges also means your code could run with privileges set for a few lines then unset for another, or vice-versa.
I think it would be better to have some architecture where you get a packet from the client and that gets sent to a server 'thread' that has sole access to the state and runs things in order one packet after another. This is easier to think about and doesn't run the risks of locks causing issues.
Some other small notes:
- There's no packet version or anything that would allow old clients to connect to new servers or vice versa
- I'm not sure if Username being the same as a user identifier of some sort is a great idea. Usually services separate display name and user credentials, or assign IDs
- SHA256 hashes should be their own type
- Erroring about an upload already existing leaks the existing filename
- Special casing Option in SetPrivilege seems unnecessary to me?
- It seems like you can SetPrivilege yourself with any privilege you want if you send None, bypassing the 'you can't set your own privilege' or 'you must be admin' checks
- For the server you have two loops per connection, one that handles some packets and another that reads other packets?
- Breaking up file sends/receives in to chunks might be good for big files, unless you want to use multiple streams like in QUIC
There's definitely more things but I think that's enough for now.
On to the positives:
- I think the protocol architecture is good using TLS, JSON and a packet format in Rust. Not reinventing the wheel and using standard formats is great!
- You seem to have a good focus on error handling and edge cases which is good attention to detail
- Sharing code between the client and server is good
- Shipping something that works is a win in itself
- Publishing code and asking for feedback is great too
- The comments you have are really good, I'm not sure what other comments you would need without getting in to boilerplate territory
Sorry if I'm bad at giving positive feedback, maybe you could reply telling me where you are at skill-wise? The code doesn't look incorrect, but that's most code I read so there's a bit of a bias there.
Thanks for the feedback! You're also certainly NOT bad at giving positive feedback. I would say that I'm an intermediate rust dev. I know the basics, and a bit about async, but I am certainly NOT an expert.
The code for the certificate handling was (almost) directly taken from the rustls example, if I'm being honest I don't really understand how it works
, I'll look more into the docs.
The typos are because English isn't my first language, but I'll try to spell things correctly for the future. Are there spell checkers available for IDE's? (specifically zed)
I myself also struggle to find some things because of the indent levels, but I never really considered splitting code. The crate is more for shared types and functions between the server and client.
The prelude is because I personally didn't like all the use statements, so I moved them to a prelude which I personally thought looked a bit cleaner.
As for the threads, I did actually in the very early stages have multiple readers yet one writer, but I thought one writer would slow things down so I replaced it with multiple writers. My only question is if I went back to the one writer thread model, how would that one thread know which TCP-stream to write to?
I was also considering adding some form of protocol version for when I try to write my own protocol.
And are the comments really enough? I thought I had put too few comments as most of my previous projects were more for myself.
If there are no arguments we return an Err
. It is more a temporary solution, as I would like to move it to a config file.
I'm glad my feedback can be helpful.
I looked up spellchecker for Zed and found this: GitHub - blopker/codebook: An unholy spell checker for code · GitHub
I use Vim to write code and text documents so I have the spellchecker that comes with that. Your spelling is good enough to get the point across which is what I personally care about
But I do worry that typos can confuse people who aren't native speakers or rely on assistive technology like text to speech. I'm a native speaker but I still struggle with typos all the time.
Splitting up the codebase should help with this. It does look cleaner but seems like it would make the code harder to change, and might also make it harder for linting tools like cargo fmt or cargo clippy to give help.
I looked online for examples and found this one: Channels | Tokio - An asynchronous Rust runtime
As psuedocode (not Rust!) for how I imagine this would work
struct ServerCommand {
packet: Packet,
responseChannel: oneshot from tokio
}
fn main() {
command_queue = new mpsc from tokio
server_socket = create socket
server_state = db, users, etc
loop {
select! {
new connection => spawn_client(connection, &command_queue),
new command => run_command(command, server_state)
}
}
spawn_client(connection, command_queue) {
new task {
loop {
data = connection.recv()
response = new oneshot
command_queue.send(ServerCommand { data, response })
server_response = response.read()
connection.write(response)
}
}
}
run_command(command, server_state) {
resp = command.responseChannel
resp.write("invalid command")
}
As a disclaimer: I haven't actually done anything like this, this is just reading documentation, but I think this is what you would want.
Regarding things being slower, it may be slower. There's always faster ways to do tasks and it always costs something. It's up to you to find a goal to set to decide what you're willing to pay. For a chat application where people usually expect a bit of network and 'processing' delay I think you'd struggle to tell the difference here.
This is a good idea! I don't know enough about versioning protocols, but I have seen chat clients that didn't do this break compatibility in really weird ways and cause real world upset. Even if you only have a few users, it really pays off to make things not break overnight. This is why you also might want to look at existing extensible protocols like XMPP or IRCv3 and see how they figured out adding or removing new features without breaking compatibility with older clients.
(Though this might be a little less important nowadays when security updates force people to update all the time)
I think I should qualify that these are enough comments for me specifically, because I am familiar with reading through large codebases that lack documentation and writing down my own notes. Reading code in other projects is a good exercise for the brain. But this is most likely not everyone's experience or desire.
In my opinion (and this is only my opinion, if you ask a few dozen developers you'll get more opinions) the only thing you should be commenting are things that you can't specify using the language. Most of the comments you've written are things that I can't learn from reading the source code, such as why something is the way it is. Such as this:
Packet::Msg(_) | Packet::FileMsg { .. } => {
let msg = packet.as_ref();
if msg
.get_inner_msg()
.expect("should contain a message")
.get_username()
== user.read().await.get_username()
{
// the client is responsible for displaying its own messages
continue;
}
let _ = msg.send_async(&mut writer).await;
}
Packet::File(_) => (), /*handeled in reader thread*/
Without these two comments here I would have no idea why your code is seemingly discarding packets or ignoring them. They are vital to the codebase.
There are some more comments like // init the logger which aren't as helpful and state the obvious. But sometimes people use comments to break up what long functions do to make it easier to read. Arguably you should be making your functions smaller, but there's diminishing returns and you don't want to end up structuring your codebase to avoid comments. Otherwise you just put the comments in your function and variable names.
Another reason you would want comments is for things like API and function documentation for your crate. I'm not sure I would classify this as a 'comment' as much as out of band data read by other programs stashed in a comment.
I do find over-commenting a little tedious, a bit like visual noise. It means I'm reading duplicate information. For example (not real Rust code):
fn sha256sum(in: &[u8]) -> [u8; 32] {
hash_crate::hash(HashType::SHA256, in)
}
versus
// Hashes a series of bytes using the SHA256 algorithm
//
// Arguments:
// - in: A slice of bytes (any size), no padding needed
//
// Returns:
// - An array containing the binary hash in bytes
//
// Notes:
// - This function is just a wrapper around the
// hash_crate wrapper
fn sha256sum(in: &[u8]) -> [u8; 32] {
hash_crate::hash(HashType::SHA256, in)
}
I don't want to cast shade on anyone or anything, but a lot of code these days has comments like that. Maybe it helps the bots think or save tokens by skipping reading the function implementation? I'm not sure. But for me as a human I find it noisy and one more thing to keep up to date.
But again, you would likely want something verbose for a public API you are exporting as a crate where you want to make human to human guarantees about the behaviour of a function's behaviour and stability promises.
After using the spell checker you suggested, I was shocked at how many spelling mistaktes I made! I'll try to incorporate your other suggestions and I'll post something in this thread again when I have made an improvement. Thanks again for the feedback!
I was thinking about si measurements when he said si
. Didn't understand what he was talking about until you said ai :).
Hi! Maybe a bit late to say, but you mostly gave feedback on the server, would really appreciate it if you also reviewed the client :).
Oh hey, it's never too late for me ![]()
I neglected to mention the client code because while it does exhibit a lot of the problems I explained with the other code base, it's also (in comparison) not that much code and fairly straightforward.
I haven't been able to run the program yet, it would be good if you added some instructions for using self-signed certificates to run the program for testing.