265 points · by blacksmythe · 8y ago · 125 comments
> Immutability (const) by default
The author clearly knows this, but others may not, so: immutability and "const" aren't the same thing. Const typically prevents name rebinding (as the type system permits). Immutability is the presumption that the whole data structure can't be mutated by default (though there are usually ways to mutate cheaply--without bulk copying, that is--provided by most immutable data APIs).
Const works like this:
not_const int[] foo = [123, 456]
const int[] bar = [456,789]
foo = [1,2,3] // no problem; rebinding is allowed if it meets the 'int' type constraint.
bar = [1,2,3] // compile error!
Immutability, as typically defined (there's a bit of a semantic debate here sometimes) prevents changes to the contents of complex data structures: mut int[] foo = [123, 456]
not_mut int[] bar = [456,789]
foo[0] = 789 // no problem; mutation is allowed so long as it's with valid types.
bar[0] = 123 // compile error!
Edit: missed a space.In C++ you can only call `const` methods through a const binding. `const` methods mark `this` const, so such methods cannot modify member variables. (Minus all escape hatches, such as `const_cast`.)
The author clearly knows this, [...] Immutability is the presumption that the whole data structure can't be mutated by default
The situation in Rust is a bit more complex. Rust distinguishes between interior and exterior mutability.
`let mut` bindings and `&mut` references exhibit exterior mutability - you can call methods that borrow `self` mutably (`&mut self`). Whereas `let` bindings and `&` references cannot. By the way, you can simply use moves to introduce exterior mutability for data that you own:
let a = Vec::new();
// Not allowed: a.push(1);
// Move the vector.
let mut b = a;
b.push(1);
Even even if a data type uses an immutable binding or reference, it could still mutate that data structure if it has interior mutability (you just can't call methods that use self mutably). See the following small example, which uses an immutable binding to call a method that mutates the internal state of the struct.https://play.rust-lang.org/?gist=6816dc9a03aca1e779f08443224...
The downside of interior mutability is that borrowing rules are enforced at run-time rather than compile-time.
let bar = [456, 789]; // const binding to owned data
let mut bar = bar; // allowed if nobody else can see `bar`
bar[0] = 123; // OK!
Immutability in Rust is not property of the data, but the way you access it.You cannot get around that behavior by assigning the reference to a non-const copy. That isn't allowed.
That difference severely weakens the meaning of the const property in C++.
C++'s const is your "immutability".
struct X {
const int i{123};
const int j;
X(int j_) : j{j_} {}
};
// non-const object; x.i == 123; x.j == 111
X x{111};
x.i = 222; // compilation error
x.j = 333; // compilation errorSo, a const value cannot be mutated locally or globally. So if you make something const and expose it, it cannot be changed.
Huh? That's a CRUD app. A "microservice" is a service which is a component of a larger service. Usually a service run by the same organization. Many microservices don't speak HTTP; they use Google protocol buffers or something similarly efficient. Serving a Facebook page involves about a hundred microservices, and they don't talk HTTP to each other.
Is it? Isn't it a purely organizational paradigm where each teams are responsible for a specific service and clear API boundaries are defined between teams? rather than the "size" of an application? (which is hard to quantify, if my app does AI and needs 100,000 line of code for a single endpoint, is it still micro?).
That's why I believe "micro" is an unfortunate qualifier what is essentially basic SOA.
It may be useful to some people, as we've most of the feature you find in a "real life" service
* database connection
* schema creation
* json handling
* pagination
* some endpoints are non-json
* support for CORS
* automated isolation test (i.e we test the service as a blackbox)
* generation of a minimal bin-only docker image that with travis-ci
* self-contained dev environment (vagrant up and you're good to go)
https://github.com/allan-simon/sentence-aligner-rustIf you're going to use Rocket, I recommend pinning the Rocket version in a Cargo.lock, and setting a specific version of nightly with rustup override.
In case you're not familiar with Swagger/OpenAPI, it's a format for specifying (generally REST-ful) HTTP APIs. The key benefit over just writing your API directly in Rocket is that you specify your API once and then generate client and server implementations that join up - even if they're in different languages.
(I did a lot of the development work on the "rust-server" Swagger codegen, and blogged on it at https://www.metaswitch.com/blog/metaswitch-swagger-codegen-f...)
https://github.com/modern-project/modern-ruby
IMO it's a smarter framework than Grape for the tasks I've set out to tackle--JSON-based RESTful APIs (though, as it's an OpenAPI-first service, there's no reason you can't handle binary data or XML or whatever you want) that leverage tools like dry-types to unambiguously define OpenAPI schema--and it addresses a lot of my pet peeves with stuff like weirdly stateful and mutable DSLs during the definition step.
The reason I mention it is because there are three languages I've been using regularly: Ruby, Node, and Rust. I intend to, next time I need a service in Node or Rust, write a Modern equivalent there. =)
Someday I will finish my Express port...
1. write the service specification in Thrift.
2. Generate the server and client stub with the framework.
3. Write the service functions.
4. Most probably you'd need to include some database/cache libraries. Poco project does a fairly good job.
5. Add some more logging and metric libraries.
6. General tools/libs are available in poco and folly.
7. If you are messing with REST, Microsoft Rest SDK and Facebook Proxygen is already providing a very solid foundation. High performance servers are already written. You just need to fill the call backs and configure the thread pools.
Why do you consider this more difficult than doing the same in Go? You just need some intermediate C++ knowledge for above tasks. No need to touch template programming, manually managing threads, ...
The cleanest asynchronous io model that I have ever seen.
Simple serialization by default.
Did I mention the blazing fast compile times? Just that would make it way more “faster” to build your service in Go :)
And above all the language is simple with robust idioms.
Okay, I admit it is somewhat too simple, cough generics. And you won’t get C like performances for sure.
I like how grpc/protobuf work. And generating the code saving it in a repo and using it, is fine. for RPC-like stuff.
However, generating code with a compiler can actually suck. Like having your database layer (jooq like) generated while compiling so the code does not get checked in anywhere.
I think it's good that other languages are evolving that are safer, make it easier to do concurrency, have an idiomatic style and still are performant whilst removing legacy cruft. It's the natural evolution of things. Every C++ team I've been on debates every feature usage (e.g. auto/lambdas/etc) where one team's good code is another's bad idea due to sheer amount of legacy features vs new ways, what language constructs are good vs completely bad ideas (everyone has completely different opinions), how should I import libraries, what build tool to use, etc.
Any complex language that gets wide market adoption evolves into "complex beast that due to its age has quite a number of disadvantages and no two codebases I've seen are the same".
Even something like C.
That's in no way a fair characterization of the parent poster.
well yeah, and if you then ask these people to debate instead the use of $LANG instead of C++ you will get 100 times more debate.
It doesn’t seem to be an advertisement for C++ or a condemnation of Rust.
It's because it's written using a low level library. Here's the first two sections (the http handling part) in Rocket:
#![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
use rocket::request::Form;
#[derive(FromForm, Debug)]
struct NewMessage {
username: String,
message: String,
}
#[derive(FromForm, Debug)]
struct TimeRange {
before: Option<i64>,
after: Option<i64>,
}
#[post("/", data="<message>")]
fn message_create(message: Form<NewMessage>) -> String {
format!("{:?}", message)
}
#[get("/?<times>")]
fn message_query(times: TimeRange) -> String {
format!("{:?}", times)
}
fn main() {
rocket::ignite()
.mount("/", routes![message_create, message_query])
.launch();
}A Python equivalent using the typing module:
@app.get("/<times>")
def message_query(times: TimeRange) -> str:
return format("{:?}", times)I really think people need to get over syntax. I don't find rust particularly good looking either, but I get over that because I like the semantics and it sits in a nice place in the ecosystem of programming languages. Likewise i don't like how C# uses PascalCase everywhere, or puts opening braces on its own line - yet when I program in C#, I adhere to those conventions.
Syntax is incredibly subjective, and also superficial. If you think the semantics of a language suck or are not a fit for what you are doing - that's a reasonable conversation. But you really shouldn't limit your language choice based on non-alphanumeric characters or whatever your objection is.
Compared to what? Compared to Python, JS, Go, etc, yes, those are different tools for projects with different requirements, that allow for a leaner syntax. Compared to other languages of it's category (non garbage collected, manual memory management), Rust looks alright, IMHO.
You should check out Rocket or Actix-Web or Gotham for something a bit more higher-level. Also know that it's Rust we're talking about - it's an expressive languages, but it's also a systems language, if you want something you can toss in a breakpoint and start introspecting or experimenting you'll probably want Ruby or Elixir.
extern crate actix_web;
use actix_web::*;
fn index(req: HttpRequest) -> String {
format!("Hello {}!", &req.match_info()["name"])
}
fn main() {
HttpServer::new(
|| Application::new()
.resource("/{name}", |r| r.f(index)))
.bind("127.0.0.1:8080").unwrap()
.run();
}I'm a big fan of Rust, and I don't deny that it's possible for it to be faster, but my understanding of where Rocket's async story is that it isn't there yet.
You're also using reqwest::Client inside your handlers, which is synchronous.
I'd just find it hard to believe that could beat an async JVM or Go implementation.
Since language ergonomics and productivity are inferior over e.g. Kotlin, it would be pointless to pick where it not for technical advantages such req/s, memory usage or latency.
Type inference, explicit non-nullabililty, first class functions, function types, extension methods, etc.
Eveyone I know who's used Kotlin would not willingly go back to Java.
- Java's GC is highly customizable?
- It's one of top contenders in most web related benchmarks (see: https://www.techempower.com/benchmarks/#section=data-r15&hw=...)
I have a thing that listens as root and serves as a user dictated by their id.
so it's
as root:
on connect fork:
forked process:
read request to determine ID
drop privileges to UID and GID of ID
process request
Because of the root component I want it to do as little as possible while being root, which c is good for. but it's also probably riddled with holes, only some of which I am aware.It has node bits there but they aren't necessary for the basic static serving. If it gets a WebSocket connection it punts it on to node.
This looks like something right out of a CTF. I'm pretty sure you can overflow that buffer and smash the stack. It's also vulnerable to a path traversal attack. What happens if the filename is '../../../etc/passwd'?
You should also pass -fstack-protector in your Makefile.
Also: Cookie:../../../<filename>
Where <filename> is a file starting with a value that's interpreted as a valid uid by atoi(). You're saved by a NULL pointer deref when the unchecked getpwuid() fails if the resulting uid is >0 but invalid (unless you're running it on a system where NULL is mapped to readable memory).
Another thing, in a make_post_response stub function I think it's better to use StatusCode::NotImplemented instead of NotFound (when trying this code I thought the match did not work correctly as everything returned NotFound).
Made more amazing by the fact that only one ad shows on the entire page.
I wonder why the author chose hyper instead of iron though...
Using hyper directly definitely gives you a better idea how everything fits together and it is much more helpful for understanding how Futures work.
You could fix this by passing a `&futures_cpupool::CpuPool` into your database functions and wrapping the post's function bodies in `pool.spawn_fn(|| { ... })` so that they execute on a different thread and return a future of their result.
To have a global IO pool that you pass into fns, you can store it in the Service struct:
struct Microservice { io_pool: CpuPool }
Now you can access it in your service's handler (the call() fn) with `self.io_pool`.(I mean - why futures, if the call was blocking and presumably have a real result to return?)