12 ms·
Rust async-await status report 2
- deleted 7y ago[deleted]
- ngrilly 7y agoI really appreciate the progress here! But I'm wondering if the return type of the function in the code example is not introducing too much complexity for a Rust novice trying to develop a simple highly concurrent HTTP service: async fn process(data: TcpStream) -> Result<(), Box<dyn Error>> Update: I read that one can simplify this using for example the Hyper library: async fn serve_req(_req: Request<Body>) -> Result<Response<Body>, hyper::Error>
- tiniuclx 7y agoWould a novice to the language implement a highly concurrent HTTP service as their first ever task? I don't think so, most people start with "Hello world" programs. To understand the entirety of that first signature you need to grasp is: 1. The Result type, which returns the result of a successful computation or an error. 2. The Box container, which is basically just a safe pointer to some memory 3. Rust's way of doing polymorphism. These are indeed some complex topics but I doubt most people start at that level. Sure, an absolute beginner would be dumbfounded by this, but working through even the first few chapters of the Rust book gives you enough knowledge of Result and Box to let you figure out what is going on.
- ngrilly 7y agoThanks!
- jedisct1 7y ago> Would a novice to the language implement a highly concurrent HTTP service as their first ever task? Why not? With Node or Go, this is trivial.
- empath75 7y agoNothing is trivial with rust.
- Dowwie 7y agoMany things aren't trivial, but some things are! For instance, the following is a program that uses a well-defined, user-friendly api for regex pattern matching. extern crate regex; // 1.1.8 fn main() { let pattern = regex::Regex::new("(?i)resource not found").unwrap(); let msg = "resource not found".to_string(); // didn't have to convert to String as &str suffices if pattern.is_match(&msg) { println!("found pattern in msg"); } else { println!("did not find pattern in msg"); } } Clearly, this is an easy example and when used in the wild, you'll have to account for error handling. However, whatever isn't trivial exists for a good reason. Trivial comes at a cost. One thing I like about Rust is that it lets a programmer decide what costs to assume.
- hu3 7y agoPerhaps we have different definitions of trivial but I don't find it trivial to cast a string to a string in variable declarations: let msg = "resource not found".to_string(); Is it necessary?
- steveklabnik 7y agoYou're not casting a string to a string, you're casting a &str to a String. > Is it necessary? In this code, it's not actually necessary, your parent converts it back to a &str later, when passing it to is_match. In other cases, it's very necessary; they're two different types, with different properties.
- hu3 7y agoThanks for explaining steve. I guess these things become second nature with practice.
- enlyth 7y agoI don't see why not, making a simple HTTP server is fun and interactive, doesn't take much time and you can learn a lot if you don't know much about the language yet. Seeing that function signature, I can imagine why a lot of people avoid Rust just based on first impressions.
- steveklabnik 7y agoNot to mention, you wouldn't even have to see a signature like that in the first place. Many of Rust's frameworks can accept a variety of signatures for handlers, so for example, with actix-web: use actix_web::{web, App, HttpRequest, HttpServer}; async fn index(req: HttpRequest) -> &'static str { println!("REQ: {:?}", req); "Hello world!" } fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() .service(web::resource("/").to_async(index)) }) .bind("127.0.0.1:7879")? .run() } Five small notes: Actix runs on stable Rust, and so does not support async/await directly yet; this is what it will look like when it does. You need to write a bit more code to map between the 0.1 futures and stdlib futures to use it today. This will go away once async/await is stable. The async/await is not needed for something that simply returns a string, of course, but to keep it as close to the original example as possible... The `'static` is a bit unfortunate, but if you just write &str, the compiler will tell you to insert it. A small speedbump but shouldn't stop a newbie in their tracks entirely. This is an infallible handler, since we're just returning a string. You can use Results and such as well, when your handlers need it, but it doesn't have to come into play for the simplest of things, which reduces the overall burden. A lot of web frameworks in Rust let you return non-Strings too, which is actually a hard requirement or else you can't serve things like images. It's just that "hello world" is a string... It didn't make it on HN, but the latest Techempower benchmarks show Actix starting to run away with the competition: https://news.ycombinator.com/item?id=20399773 https://news.ycombinator.com/item?id=20399773
- tiniuclx 7y agoThank you for your reply, that was exactly what I was trying to show when I linked the Actix Web example in one of the child comments below!
- 0815test 7y ago> To understand the entirety of that first signature you need to grasp is: ... ...4. The unit type (), which is basically a 0-tuple, i.e. a type that carries no information, and generally replaces the use of `void` in C-like languages. (Rust also has a proper void type, i.e. a type for something that cannot occur, but that's denoted by ! and is quite different from the unit type.) It's not a hard concept, but it may be a bit unfamiliar if you havent worked with functionalish languages before.
- lmm 7y agoI'd argue that hiding what's going on for the sake of "simplicity" ends up confusing a novice more when it means the function ends up behaving inconsistently. E.g. in many languages a novice might see a function that returns just "Response", but when they call it it actually "throws" an "exception", which is a whole different concept that you have to understand and that completely destroys the simple "function evaluates to its return value" model. Result has the advantage of being a plain old datatype that's just written in normal code - it follows all the normal rules of the language, and the user can probably click through and read its implementation for themselves.
- ngrilly 7y agoI think the Result type is quite easy to understand, and it's central to Rust error handling strategy. The main difficulty is we also have to understand the purpose of the dyn keyword and why the Error must be boxed. Anyone writing serious Rust will have to learn this sooner or later, but maybe this is a lot to learn "upfront" :-)
- 0815test 7y ago> The main difficulty is we also have to understand the purpose of the dyn keyword and why the Error must be boxed. Box<dyn Trait> is just an owning opaque pointer to something that implements the Trait interface. This kind of stuff is done all the time in C/C++ because it's just so darn useful, even though it requires a bunch of boilerplate code to make it work properly. (It's also arguably implied in the semantics of other languages, even though it's not directly marked in the code.) In Rust, it's just a line of code and the compiler provides checks that ensure you're writing something reasonable. (And of course you can dispense with the whole boxing mechanism when it's not needed, same as in C.)
- Dowwie 7y agoIt's a great milestone, and hopefully async methods not far behind in the pipeline. I might be able to port my work to async-await syntax with the first release to stable in ~1.38 but I may wait longer until async methods are addressed. I want to encapsulate state with async behavior. Updated (as per Steve): inherent methods will be avail and may address my reqs
- steveklabnik 7y agoNote that async inherent methods will be part of the MVP; it's trait methods that are much harder and won't. Not sure if that fits your requirements or not!
- Dowwie 7y agooh in that case, it might!
- spinningslate 7y agoGenuine question: can anyone comment on which alternatives to async/await were considered? And if so why they were rejected? It’s proliferation puzzles me: c#, python, node, rust and no doubt others. Yet it seems like a poor abstraction. 1. The cognitive overhead. Whilst the example might be intended to show off power, that function signature is not at all easy to parse mentally. Even allowing for generics it’s still a lot more difficult to think of a function that returns a future that will return the result at some point (as opposed to a function that returns a result synchronously). 2. It’s declared at the call site - not by the caller. As the writer of a function, how am I supposed to know whether the majority of callers will get sufficient benefit to offset the increased cognitive overhead? It can also have viral tendencies: a function that calls an async function is async itself, and so on. (Not sure if that’s mandatory in all language implementations). I’ve seen more than one code base where async was like a virulent rash. Personally I find Actor model concurrency so much easier to deal with (e.g. Erlang). The rules seem significantly more straightforward and easier to deal with mentally. Data flow concurrency (e.g. FRP) also seems much easier to reason about. Async/await by comparison seems like a poor substitute. So I’m puzzled but intrigued by its growing popularity. I can imagine it’s easier to implement in the language (compiler/runtime), which might be key for rust. I can also see that it’s an incremental step for procedural languages. But then surely it’s a wise investment to build good abstractions in the language - even if it’s (a lot) harder - rather than burden the programmer with more complexity? What am I missing?
- steveklabnik 7y agoEverything was considered. This has been the most discussed Rust feature to date, but a serious margin. I'll try to give you some answers from my perspective; I am not on the language team, nor have I done any of this work myself, but this is what I remember, and see from the outside. The short answer is: it's the only way to accomplish the task that fits into Rust's requirements. The top relevant ones are speed, lack of required runtime for non-async code, and zero-cost C interoperability. It sounds to me like you're coming at this from a "what is the simplest thing for a programmer to use" angle. That's a totally valid angle, but Rust is focused on ease of use only within the context of other requirements. Notably, Erlang's model, while it has excellent properties, falls down on all three of these other requirements. That's totally okay in the context of Erlang, but is not acceptable in the context of Rust.
- krircc 7y agohttps://news.ycombinator.com/item?id=20402082 https://news.ycombinator.com/item?id=20402082
- samirm 7y agoThanks for the update, but why do you have to repeat yourself so much in the post? :/
- randyrand 7y agoThis has been asked already, but what are the benefits to declaring async in the function definition and not at the call site?
- steveklabnik 7y agoI'm not sure why you would do it that way. How would you know which functions can be async and which ones cannot?