525 points · by steveklabnik · 9y ago · 238 comments
Question for the more knowledgeable Rust folks: Does this code (the echo server example) not handle the situation where the port is already in use? What's the return type of the socket bind in that situation?
EDIT: Wow six responses in as many minutes. I think I've created a new objective measure of how popular a programming language will be!
My view is that sample code such as this should be as idiomatic as possible and that means providing a sample demonstrating a typical real use case. So seeing "unwrap" in this context doesn't sit well with me.
In fairness, this isn't specific to Rust. I find sample code like this in many projects regardless of language. However Rust is billing itself as a safe systems programming alternative to C and C++. It would help its marketing efforts, in my opinion, by having more robust samples than the competition. And let's be honest: given the competition is C and C++, that's a low, low bar--and this comes from a guy who's about as big a fanboy of those two languages as possible.
Edit for more disclaimer: documenting Rust code is a real pleasure. The team has done a stellar job at making documentation an easy thing to do while writing the code. It's already better in most cases than many other projects I can think of.
That is, in terms of safety, this is the same thing as explicitly handling the error and then terminating the process. Which is the only real way you're going to handle this error anyway, unless you wanted some sort of retry logic. Which you might!
It's one of the more common ways of using unwrap.
(The examples unwrap elsewhere in less known-good scenarios, I agree that we should improve there)
I've starting trying to use `if let Some/Ok(...) = ...` in examples for my projects rather than `unwrap` for pretty much this reason. I feel like it strikes a pretty good balance between providing a relatively terse example without the risk of implying that `unwrap/expect` is considered normal usage for the library.
My intermediate impression is: Basics and the whole idea behind it looks very good and suits Rusts general concepts. However from a productivity point of view it yet can't match the ergonomics of Go or C# with TPL and async/await for IO tasks. But I think the rust contributors are well aware of this and working on some things (async/await like sugar and that impl trait thing which might fix my composition problems).
More likely, you'll be using something like this: https://tokio.rs/docs/getting-started/simple-server/.
Perhaps something like that should also be on the homepage to show that, while you can do low-level, it has already scaled up to a higher abstraction for you.
The result of parse().unwrap() is of type F, which means addr is of type 'F'. afterwards when we call `let sock = TcpListener::bind(&addr, &handle).unwrap();` the compiler can infer from the signature of `TcpListener::bind`[2] what F has to be, namely `std::net::SocketAddr`
[1] https://doc.rust-lang.org/std/primitive.str.html [2] https://tokio-rs.github.io/tokio-core/tokio_core/net/struct....
Due to the resulting thread, I feel legitimately excited to sit down and learn a new-to-me language for the first time in ages :)
The TCPListener::bind call returns a Result enum, which can have the values Ok(SomeType) or Err(SomeError). The compiler forces you to decide how you want to handle that, for the sake of brevity the example code calls unwrap() which assumes the result is Ok and will either return SomeType or else panic.
> Does this code
So
let sock = TcpListener::bind(&addr, &handle).unwrap();
Here, the bind method [1] will return an error if it can't bind to the port. unwrap will cause a panic to happen.1: https://docs.rs/tokio-core/0.1.3/tokio_core/net/struct.TcpLi...
This line tries to bind the port and returns a `Result` type which is then unwraped, which will cause a panic when the port already is in use.
It's generally considered bad form to use unwrap() (and by extension panic) in production code, but for examples where you just want to show something it's fine.
bind would either return a Option type or a Result type, unwrap is defined for both.
edit: Others have looked through the docs and confirmed it's a Result
TcpListener::bind(&addr, &handle).unwrap()
Rather than raising exceptions, the paradigm in Rust is to return a Response item, which has an Ok and an Err subtype. unwrap() here assumes that the response is Ok and just gives that back the data returned, or crashes if its an error.
> It won't crash. It's a "clean" shutdown.
:+1:
let addr = "127.0.0.1:12345".parse().unwrap();
Is Rust like Ruby in that devs and library authors can add methods to and redefine built-ins? And that merely including a library can alter the definition of those objects everywhere in your project's code?I'm not trying to start a language war, but IMO that's too bad: this feature is, in my experience, the single largest source for difficult-to-detect errors that characterize the Ruby programming experience, e.g. anything that uses Rails. It also contributes to deep stack traces which are essentially useless, because the departure point from your actual code is some 20+ frames above the site of the error.
In this case, both of those methods are in the standard library.
From reading the docs, something provides a method called `FromStr` and the `str.parse` method does some magic to figure out which `FromStr` of all the registered traits is the one which we want? So then, it's not arbitrary monkey-patching, but using a defined protocol for defining and extending string parsing?
It's closer to refinements than monkey-patching, that is, you can, but you must bring the trait into scope for it to work.
> And that merely including a library can alter the definition of those objects everywhere in your project's code?
No, based on the above rule. We don't want that.
It was announced roughly in August, so yeah, five months. Though some work had to happen for that initial release, of course. There was a joke though, about this rapid development. Someone said something like "That they keep re-writing tokio is really annoying as a user, but I guess if Rust is so productive that you can throw out huge chunks and re-build it that quickly, well, that says good things about the language." Of course, as the post says, things will be more stable now.
#[derive(Aws!("s3/2006-03-01/service-2.json"))]
struct S3;
Becomes up-to-date with the latest changes from Amazon the moment they're released (recompile required).Procedural macros are really exciting with regard to writing/consuming APIs as they enable both the client and the server interface to be implemented in an API specification language (Amazon uses custom JSON, but Swagger/RAML could work too) instead of Rust with zero performance penalty (gotta love those zero-cost abstractions :-)
We're tracking the missing services: https://github.com/rusoto/rusoto/issues/436 . There's plenty of work to do and we're concentrating on getting them implemented. Sometimes progress is slow since it's a side project, but it's still moving forward.
If we can make the derive statements work as your code snippet shows, I'd be really happy. We'll take a look at how we can improve codegen when new features are available. Some of our codegen is dated, using what was available when it was written.
It seems like many things are in flux. There's a new `rest_xml` codegen thing that just got implemented which will allow AWS API to be supported. They're also moving from Hyper to Reqwests. From what I saw, Async stuff is planned for after 1.0 by adding new AsyncClient impls backwards-compatibly.
We also have a crate that's designed to provide higher level abstractions. Rusoto is analogous to botocore and rusoto_helpers (https://github.com/rusoto/rusoto/tree/master/helpers) will be closer to boto3. It's on the back burner as we focus on completing the core functionality.
Async support is still an open question. If requested we can make that happen before 1.0. Feel free to weigh in: https://github.com/rusoto/rusoto/issues/318 .
Overall I was super happy. I finished the feature I was working on in maybe a day or two without any issues in the rusoto library. Can't ask for more than that.
One of the core premises of tokio is that this compiles down to the state machine you'd have to write by hand if you wanted to do asynchronous stuff. So yes, this is very much intended as a zero-cost abstraction.
Then stuff like spinning up 1 OS-thread for every CPU core and scheduling requests in round-robin (?) style, and then wrap it all up into a developer-ergonomic thing.
Since you probably have a way better insight into rust-dev and the ecosystem, can we stay tuned that this eventually will happen or are there still showstoppers somewhere?
You could see how that match block functions as a router...
I was literally playing around with this last night. There's a lot of experimentation going on in the server-side Rust web framework space right now, and I expect it to heat up even more now that tokio has had a release.
> once Macros 1.1 land in stable, right?
So to be clear, macros 1.1 gets you custom Derive, which is Serde/Diesel. It'll be stable in the next release in ~3 weeks. It won't get you the full ability to use any custom attribute, like https://rocket.rs/ uses.
> Then stuff like spinning up 1 OS-thread for every CPU core
This is not implemented in tokio yet, but in my understanding, it's coming.
I enjoyed visiting Tokio (Tokyo) the city and I liked the
"io" suffix and how it plays w/ Mio as well. I don't
know... naming is hard so I didn't spend too much time
thinking about it.
[0]https://www.reddit.com/r/rust/comments/4vzomj/announcing_tok...(.rs being TLD of Republic of Serbia)
とうきょう 「漢字:東京」 is the capital. 「ときょ」is gibberish and doesn't exist.
Romanization is a way of unambigously encoding Japanese into the roman alphabet. One method gives us "toukyou". Another system uses diacritics for long vowels.
"Tokio" is a different word.
tokio -- ときお (to ki o)
toukyou -- とうきょう (tō kyō: this is Tokyo)
tokyo -- ときょ (to kyo)
Note that ō loses an orthographic nuance, since it can denote either おう or おお.
Edit: By the way, your idea of "unambiguously" encoding Japanese doesn't hold water. Written Japanese is written in a mixture of kanji and kana, and no romanization system does round-trip the kanji. You could say that (good) romanization systems unambiguously encode the pronunciation, but that isn't true either: in addition to the fact that encoding "pronunciation" of written language is problematic in principle, there are the pitch accents that aren't captured by kana. But we're digressing.
If you give up the "unambiguous", "tokyo" is a perfectly good romanization for 東京.
If you're going to be strict with respect to romanization and use accents, isn't the circumflex used to indicate long vowels, at least in Kunrei? So, Tôkyô? Or in Hepburn, the macron? Tōkyō? I've never come across acute being used for this.
And by cheap I mean cheaper than OS threads. The reactor pattern still adds a lot of CPU overhead to each I/O operation.
What's interesting is that Rust had green threads at one point. They implemented that by making std::io async-capable under the hood. But they didn't like it: too much abstraction cost, and it was preventing to add more native i/o features easily.
So they ditched it and now they are doing exactly the same thing to I/O, just in user space, and without green threads.
You need to pay for concurrency one way or another, there is always going to be some bookkeeping overhead. Whether you pay the price in your language's runtime (like Go) or in a library doesn't mean you're getting for free. However, it looks like the design of Rust's futures will let it reach very throughput.
I've measured "zero-cost abstraction" that weren't quite so when profiled.
What it really means is "if the inlining goes like the programmer expects, then it should have no cost". The term expresses hope.
But inlining is best left to the compiler, and hope is of little value until measurement is done with a profiler.
But you don't necessarily want to do that since you may not make the most efficient use of the CPU cache.
[1] https://doc.rust-lang.org/reference.html#inline-attributes
It was cool and trendy when libevent and Nodejs came out, but now we should all have the experience and knowledge that tell us to stop doing asynchronous I/O.
Go, Hakell, or Erlang do a great job at concurrency, without the async i/o craziness.
I couldn't tell the same thing about Nodejs, for instance, which is why I tried Go in the first place.
Incidentally my code is much easier to understand, too.
nodejs use to be pretty annoying when dealing with complex workflow in term of code legibility when it was fully callback-based, but with async/await you get the best of both world IMHO.
Being a green thread with a growing stack is an implementation detail for the developer writing Go code.
In async, every single function must be async (or be super fast and i/o-free).
Like with a lot of Rust development at the moment, these libraries are building blocks, they're not the end of the story.
I can appreciate a polemic, but I also appreciate substance ;)
Async code can not use synchronous code because this would block it, and prevent it from returning to the event loop.
This is a tedious task, and you end up with less tested, less complete code (at least during the first few years) compared to the sync libraries provided by vendors and std libs.
Event Nodejs still doesn't have ported the world to async yet, and still uses a thread pool under the hood for a number of things (e.g. name resolving), which defeats the promises of async I/O.
Synchronous code can not use asyn code either because, well, in order to get anything from async code you have to be async yourself.
Async code is also more difficult to reason about compared to classical blocking code.
The idea behind async code is to avoid the cost of context switches and the memory usage of OS threads. But they are not the only way to avoid these costs. Go, Erlang, Haskell do a great job at this, without forcing the world into async.
And since this guy is way better than me at writing, I'm going to leave this url here : http://journal.stuffwithstuff.com/2015/02/01/what-color-is-y...
You're not avoiding the cost, you're just moving the runtime and language/code complexity costs around. Each of the techniques used by Go, Erlang, and Haskell to implement coroutines have trade-offs and there is two that Rust simply cannot make and still fulfill its goals: lose low overhead bidirectional C interop and add a language runtime.
Performant coroutine implementations (AFAIK) all require moving the stack pointer around which makes it very expensive to have code call FFI functions. C makes certain assumptions about the stack and invariants need to be upheld, especially when the foreign library takes a function pointer from the host language. These features require a runtime which is out of the question for a low level language.
We're definitely aware of all of this. Tokio is made by two Rust core team members and the person who wrote the most widely used async io tool; it's virtually all but provided by Rust itself. And the ecosystem is aware of this too; the other people who were working on AIO have backed tokio as well, and the Rust community in general is interested in not having this split.
> Synchronous code can not use asyn code either because, well, in order to get anything from async code you have to be async yourself.
This is solvable through a threadpool, which tokio provides. In other words, it lets you make a blue function red.
> But they are not the only way to avoid these costs
These do not avoid all costs. For example, they pay the overhead of green threads, which means that you can't interoperate with C code at zero cost. That's a price a language like Rust cannot pay.
This sounds like a JS-specific issue, where you're not allowed to spawn new threads for historical/implementation reasons? Even in Python and Ruby, where the GILs prevent threads from really running in parallel most of the time, you can still use them to unblock an event loop around a long-running function.
There is just no need for async I/O. Just bring "zero-cost" multi tasking / coroutines to your language, and you don't need async anymore.
So you have to rewrite every single library and network client in asynchronous mode.
It would be great to have every I/O library use OS specific polling mechanisms but that places a significant burden on library developers to not only know their domain, but have experience with each platforms quirks and limitations.
Until you exhaust the thread pool, in which case everything relying on the thread pool will be much longer than usual to complete.
Nodejs does this for name resolving, and it's a nightmare. Basically, with the default pool of 4 threads, it suffices of 4 slow resolves to DoS everything that needs to do a name resolve in the same process.
I hope that Rust will not have the same problem when mixing async and thread pools.
If the thread pool is not limited in size, you avoid this problem, but you lose all the benefits of async.