16 ms·
Writing a website in Rust
- eigenrick 11y agoThanks for the detailed write-up. You are a pioneer in the rust webdev space and have created a map (with the dragons labeled) for others :)
- viraptor 11y agoHaha, I didn't intend to go for detailed :) I'm pretty sure there's a lot more to tell about the details. I just wanted to at least list all the modules I've been looking for / using in this webapp. Thank you for the feedback. I intend to write another post with some very basic skeleton / hello-world of a new Iron application using database with connection pooling, templates, logger, parameter parsing. But that's for another day.
- anonbanker 11y agoPlease do so, and tell HN. Many of us are paying attention.
- deleted 11y ago[deleted]
- neverminder 11y ago> Actually the compiler checks cover most of the things I’d normally unit-test, so this is probably the only non-trivial project I wrote without checks and I’m OK with that. This is interesting. First time I read about Rust I had this gut feeling that it's design might reduce the number of unit testing cases. Someone care to comment on that?
- viraptor 11y agoJust to add some context, here are the tests which I didn't write, but would in Python/Flask usually: - Proper behaviour if I don't pass a parameter. Not needed, because it's an explicit `Option<>` which I have to handle. - Is results list constructed properly / what's the None-vs-empty behaviour. Not needed, `Vec<>` is verified at type level and None is not possible. - What happens if various database functions don't find a result. Not needed, because type signatures force either a returned `Entity` (if it's not there, it's an implementation bug: panic + 500), or `Option<Entity>` which again needs to be explicitly handled. But these are only unit tests. If it was a critical app, I'd still write functional / logic tests to make sure the right data goes all the way to the database and back in known scenarios. Types can't guarantee that. One kind of tests I'm tempted to write is for templates rendering properly, because handlebars-iron takes parameters as Json - all type guarantees go out of the window there. But it may be the same amount of effort to migrate to some type-safe templating like Maud.
- s_kilk 11y agoI've had a similar experience writing web-apps in Scala. The Option type alone handles so many cases which would otherwise require unit-tests in Python or another unityped language.
- Cyph0n 11y agoI'm a Python/Flask dev who has knowledge of the basics of Scala. Which web framework and ORM would you recommend to develop a (potentially) non-trivial web app?
- neverminder 11y agoIf you want to use Scala, Play Framework 2.4 + Slick 3.0 would be the deadliest combination in my opinion.
- s_kilk 11y agoSecond, I'd certainly recommend play framework.
- jfoutz 11y agoI've dabbled with rust, but did quite a bit of stuff in haskell. A lot of unit testing is verifying failure modes. What happens if they pass in null? What happens if they ask for a value i don't know about? stuff like that. Haskell (and rust) give you a lot more control over what a function is willing to accept at compile time. You could spend your time writing a test to ensure null is handled gracefully. With rust, you have a bit more power, and you can simply ensure the function can't be called with null. It's more general than just null checking, but that's the flavor of what happens.
- neverminder 11y agoThat's my general feeling as well. Coming from Scala transition into "dabbling" with Rust was actually quite smooth. I try to stick to functional style where possible, exhaustive pattern matching, everything wrapped in Result/Option, etc - eliminates the need of unit testing in many cases.
- Manishearth 11y agoThis is true IME. There are a lot of things you don't need to check for. Some guaranteed by Rust. Others guaranteed by the APIs themselves; Rust gives you a lot of powerful tools for designing APIs with static checks. For example, if you return a Result<T>, you don't need to check if the programmer forgot to handle a failure mode in your tests. The mode will be handled, or there will be an explicit panic. Rust is harder to get to compile, but a lot of your boilerplate testcases go away. And if you design your API right, even higher-level guarantees can be provided statically. A lot of times when writing Rust code in Servo I'll just ensure that stuff compiles, and then run the tests once before making a pull request. When contributing to python codebases I generally make smaller, incremental changes and run tests. Edit: Just to clarify, this doesn't mean you should go all #yolo and abandon testing entirely. But (a) you can do so temporarily without adverse effects, and (b) once you start, you'll find that you only need to focus on the higher level tests.
- ilaksh 11y agoHere's something that most of you will probably learn the hard way: popularity and merit are not the same thing. Rust is very popular now. That doesn't mean it has a great design. One of the very first design decision/belief they made was "no code can perform with garbage collection". Well, garbage collection does cause quite a few performance problems, but that doesn't mean it can't work if you engineer it right. Personally I think Go and Nim are better languages as a general statement, both for applications and systems programming. I know I am going out on a limb making a negative statement like that, and previously Nim developers have tried to discourage me from saying negative things about Rust. Those guys are smart and have social skills and they realize they should be careful to be nice to Rust developers because sophisticated developers looking for things like performance, type safety, etc. with a C or C++ background are really going to benefit from Nim if they give it a chance and Rust developers are prime candidates for Nim conversion. So let me just say clearly that I don't associate with the main Nim community, the core developers, or anyone really. Nothing I say here reflects on them I hope. I literally have no friends in fact. I don't understand people, or pay much attention to them, or interact with them very much. When I do interact I say what I really think, not what people want to hear. What I DO understand is technology. From a very early age I have been programming in everything from different types of assembly language to C to C++ to Ruby, Javascript/CoffeeScript/ES7, different variants of SQL, Rust, Forth, OCaml, etc. Mozilla is a leading technology organization with many contributors. Rust is a new technology with quite a few people innovating on it. Unfortunately, Rust starts with a bad design decision and never really recovers from that design decision. The values and perspective are lacking a modern, contemporary perspective. The Rust worldview is trapped in the C++ era. I have been primarily a JavaScript developer both on the front and back end for many years now. Why? Because I like to make useful applications and I am sane and paying attention. But in a world where people were better informed and had better judgement and the best things won out rather than the most popular, Rust would be an obscure language being toyed with by a few academics for (perhaps?) implementing certain parts of kernels, the new browser from Mozilla would be fully peer-to-peer capable (using IPFS/gittorrent/swarm/ndn etc), written in Nim of course, use JIT/VM/something Nim for scripting, and have thrown out JavaScript/ES6/ES7 AND CSS for good. Of course, in this ideal world there would be no google monopolizing all advertizing and capturing most good engineering talent, since semantic markup and p2p query would also be be built in to this browser, making google irrelevant. The default mode for the browser would be virtual reality, with the ability to render 2d operating systems or markdown/images on arbitrary 3d surfaces. But instead we have the world we have. All advertising must follow the dictates of a giant all-powerful global corporation. Mozilla is trapped in a pseudo-C++ mindset and spending most of its efforts trying to reproduce the intractable mess of decades of CSS hacks, in the time the engineers have left after going through in excruciating detail all of the possible ways to 'borrow' memory. CSS, a brilliant system that is a pain the in the ass not only for programmers but also designers, so complex that only two computer programs in the world are known to do a reasonable job of rendering it accurately. Its time to stop dragging the old tools, mindsets, and technical debt forward. Stop judging things on the basis of momentum or authority (Google/Mozilla/Microsoft) and start using your brain to select things rationally. Mozilla as an organization is not going to be capable of admitting they made a mistake with Servo/Rust and recoding it in Nim. Just like the world is not going to accept that we should throw out CSS and use any other simple system that can reproduce graphic designs. And we are not getting rid of JavaScript with its horrible threading model and garbage collection anytime. But we should. In a sane world we would learn from our mistakes and throw all of that out.
- kybernetyk 11y agoWell, IMHO, "the right hammer for the right nail". Rust is a great systems language (besides the lack of bitfields) but I wouldn't use it as a web language. Just as much as I wouldn't use C++ to develop webapps. Sure you can do it but then again there are far easier ways to achieve your goal.
- mangeletti 11y agoOut of curiosity (I've never done systems programming), what are some of the things that make a language more suited to systems programming rather than web (other than libraries and community support - I'm more interested in the intrinsic qualities of the language)?
- Thaxll 11y agoStandard library, look at PHP it's all about web!
- supster 11y agoSuper fast, type safe (and thread safe in Rust), compiled, low/no cost abstractions
- pecan_xt 11y agoSuper fast? More like Java ballpark: http://benchmarksgame.alioth.debian.org/u64q/compare.php?lang=rust&lang2=java http://benchmarksgame.alioth.debian.org/u64q/compare.php?lan...
- steveklabnik 11y agoWe've been focused more on language semantics than the Benchmarks Game for a while now. A few months ago, iirc, we were faster than C on some of them.
- jamii 11y agoIt looks like the worst offenders (vs C) are regex-dna (which is a young regex + unicode vs pcre + ascii) and fasta (where the rust version is still single-core). The others are at 1-2x cpu and on par for memory. I suspect most of them could be on par or better with a little effort - only regex looks hard.
- malandrew 11y agoThe tooling for the web written in JavaScript is excellent, so I was curious, are there any options there are for calling JavaScript from Rust code? I know there is the ffi module for NodeJS that allows you to call Rust from JavaScript, but I was wondering if there is something that works well in the other direction.
- kibwen 11y agoIt's an interesting question. You can embed V8 in Node, so theoretically you could also embed the entirety of V8 in a Rust program just as you could embed Lua or Python in a Rust program. But just because it's possible doesn't necessarily mean that it's easy... it would be a fascinating project for someone adventurous. :)
- aselzer 11y agoEmbedding JS in Rust by using V8 (as kibwen has mentioned) would be no problem, but using node.js modules might not be so easy. It's like calling ruby gems from C. What do you mean by "tooling for the web"? If it's preprocessors like LESS (that are written in JS), you could run the JS in V8 to transform the CSS efficiently, but maybe the compiler "binary" (script) is enough. In this case it's the best approach, since performance will be good, and you don't have to reinvent everything. But if it's something like express.js, it's probably not worth it. It's surely possible somehow, but in a pretty hacky way and at the cost of high overhead and complexity caused by calling from a static language to a dynamic one.
- barosl 11y agoI once experimented this, and it worked. I wanted to do this because I needed a decent and fast CommonMark library, but Rust didn't have one. (Yes, I tried to embed JavaScript in Rust just to parse some MarkDown text!) There are two libraries that embed V8 in Rust, but all of them seem to be abandoned for now. However if there become enough interests, a new project will arise I think. (FWIW, I ended up calling CommonMark library written in Python from Rust, because embedding CPython was easier than embedding V8. Unfortunately CPython's performance is worse than V8, but as I know Python better than JavaScript it was a reasonable choice.)
- ffn 11y agoHey OP, have you tried the other "future" languages like go or Elixir? If so, how does it compare with your experiences in rust?
- viraptor 11y agoNo, sorry. I did some erlang (directly, not elixir), but not for websites. I really missed strict types and compiler validation there. I know there's dializer and others, but it's just not the same level of comfort. I've done one website in C however and can tell you that Rust is way more predictable ;-)
- bliti 11y agoVery nice write up. As a Go programmer, Rust is really interesting. Can't wait until you can build web APIs with it.
- steveklabnik 11y agoCrates.io is built this way: Rust serving JSON on the back end, Ember consuming it on the front end.
- mwcampbell 11y agoWhat kind of database does crates.io use?
- steveklabnik 11y agoPostgres: https://github.com/rust-lang/crates.io https://github.com/rust-lang/crates.io It also stores the index via git and S3...
- bliti 11y agoHow mature could this setup be considered? Thanks for pointing it out.
- steveklabnik 11y agoAs mature as anything for a language which just hit 1.0. Alex, the main developer, said he likes it a lot. https://m.reddit.com/r/rust/comments/2v1fe3/hows_rust_working_out_as_the_backend_for_cratesio/ https://m.reddit.com/r/rust/comments/2v1fe3/hows_rust_workin... I think it's a pretty good architecture overall. We'll see how it all shakes out.
- deleted 11y ago[deleted]
- chachalarue 11y agoI've been using typed racket for backends https://www.classes.cs.uchicago.edu/archive/2014/fall/15100-1/guide.html https://www.classes.cs.uchicago.edu/archive/2014/fall/15100-... Recently where I work we switched to Golang for any network facing daemons and it's been awesome. Rust was decided as 'too alpha' to try yet.
- bliti 11y agoVery nice write up. As a Go programmer, Rust is really interesting. Can't wait until you can build web APIs with it.
- Manishearth 11y agoRegarding compile time, you can track the passes with `-Z time-passes` and wait for borrowck/lints to get over (or just typeck if you're only worried about types). There also was [this plugin](http://www.reddit.com/r/rust/comments/2krdbu/rest_easy_a_lint_to_tell_you_when_compilation/ http://www.reddit.com/r/rust/comments/2krdbu/rest_easy_a_lin...), but it's outdated at the moment (I can upgrade it later). Regarding imports, `use foo::bar::*` works.
- viraptor 11y agoFor use, I meant that there are so many packages you just take space just listing them. For basic iron you need: iron::prelude::*, iron::status, staticfile, logger, router, handlebars_iron, and more. And these are all from different crates.
- Jweb_Guru 11y agoThis is the same in even many dynamic languages, though, isn't it?
- viraptor 11y agoAlmost. In Rust to use a trait, you have to explicitly import it. That means if you want to run `.to_json()` on something, you need to import trait `ToJson`. Then again if you want to force a type of something (for example an empty hashmap) you need to import the types which are included. So what in a dynamic language could be: a.to_json() if a else {}.to_json() In rust will start with: use rustc_serialize::json::{ToJson,Json}; use std::collections::BTreeMap; ...
- filsmick 11y agoI'd love something similar to be part of Cargo, maybe as an option in the manifest. Like the author, I've learned to guess when the codegen starts, but having this information displayed would be useful.
- 11y ago
- bishop_mandible 11y ago63 dependency crates? That's insane.
- steveklabnik 11y agoLast I checked, a 'rails new' gives you over 40 dependencies off the bat.
- mrcwinn 11y agoLet's please not look to Rails to determine the way forward for web development.
- bishop_mandible 11y agoYes, the Rails and Node communities are known for insanity.
- AgentME 11y agoI put all node functions I might want to re-use in other projects on NPM by themselves (though this also usually pushes me to make a lot of unit tests for each of them, which is a nice benefit). I'm not really clear on what's insane about re-using a lot of small modular parts. This is way better than copying and pasting functions between codebases, and then trying to keep them (and their tests) all in sync.
- MichaelGG 11y agoNode/npm is terrible. Look at Popcorn Time. This client app has over 4000 files in npm_modules. Most of them totally unneeded, and many of them tiny and for things that should be in a stdlib or rolled with others. I think it's the same kind of folks that create a huge Java object model, always one file per type. Gives the feeling of being big and doing real work, even when you're not.
- kibwen 11y agoCargo makes it trivial to add dependencies to a project (which themselves may have their own dependencies), and Rust has been designed with versioning in mind from the start so that even incompatible versions of the same dependencies can exist in your dependency tree without any problems whatsoever. 63 dependency crates isn't insanity when your tools take 100% care of them for you. To me, a large collection of dependencies represents a proper and fine-grained separation of concerns.
- CyberShadow 11y agoI think D has shown that you can get a nice web stack in a compiled systems programming language: http://vibed.org/ http://vibed.org/ Lots of packages for it on code.dlang.org as well.
- barosl 11y agoWhenever someone writes bad things™ about some language, one of the language's fanboys shows up and starts nitpicking! Yes, now is the time! > Another bad part is Rust’s JSON handling. It badly needs macros which make things easier. Actually this is not the end of the world. As you mentioned, Rust's JSON library supports `ToJson` for primitive types, but also provides compile-time code generation for arbitrary `struct`s. Quoting the code from my project:[1] #[derive(RustcDecodable, RustcEncodable)] struct Msg { cmd: String, id: i32, x: Option<i32>, y: Option<i32>, speed: Option<i32>, } What the mystical `#[derive]` thing does is to direct the compiler to create the boilerplate for converting the `struct` to/from a string automatically. So, now you can do this: // Decoding a JSON string let text = r#"{"cmd": "move", "x": 5, "y": 10, "speed": 200}"#; let decoded: Msg = json::decode(text); // Encoding a Msg object to JSON let msg = Msg { cmd: "new", x: 10, y: 20 }; let encoded = json::encode(msg); The `Msg` struct is full of `Option`s because my project allowed many fields to be missing, but if the JSON messages in your protocol are in fairly similar format, you can eliminate most of them. One more benefit of this approach is that it type checks. If the JSON you received is missing some fields that are not defined as `Option`, the decoding process produces an error! So you can be certain that you're handling a valid JSON after the decoding stage. This is analogous to schemaless vs. schema-enforced database design. > Compared to many static languages, the handlers look tidy. Compared to dynamic languages, they’re terrible. This is the property of the Iron framework, not of the Rust language itself! Another web framework for Rust, namely Nickel.rs[2], provides much simpler APIs. I believe the author of Iron is trying to establish essential things first, and build more "user friendly" APIs on top of them. (FWIW, the Rust project itself follows the similar strategy.) [1] https://github.com/barosl/pgr21-online-server/blob/master/src/server.rs https://github.com/barosl/pgr21-online-server/blob/master/sr... [2] http://nickel.rs/ http://nickel.rs/
- tomjakubowski 11y ago> Actually this is not the end of the world. As you mentioned, Rust's JSON library supports `ToJson` for primitive types, but also provides compile-time code generation for arbitrary `struct`s. Quoting the code from my project:[1] Pardon my self-promotion: if you just need some one-off JSON and are willing to use the nightly compiler, I wrote a compiler plugin that expands JSON-like literals into an expression that expands to the tedious way of building up a JSON object. https://github.com/tomjakubowski/json_macros https://github.com/tomjakubowski/json_macros I find it's super handy for testing libraries or applications that emit JSON meant to go across some well-specified protocol. Some day I'll get around to expanding the library to support pattern matching with JSON literals as well (pull requests very welcome!).
- nickpsecurity 11y agoInteresting project. If Rust is to replace C++, then we need to see it exercised in all domains C++ has succeeded in. As I told another commenter, C++ with good frameworks does very well in web applications albeit with fewer libraries & utilities. A team of Rust programmers could catch Rust up to one of the C++ web frameworks and do a shootout between the two on realistic web apps. The results in terms of efficiency, productivity, and maintainability for each should tell us plenty about Rust's success in terms of its objectives. That experiment among others, of course.