r/programming • • Mar 22 '16

First Release of Silicon, a C++14 Web Framework

http://siliconframework.org/blog/silicon-0-1.html
165 Upvotes

71 comments sorted by

10

u/matthieugarrigues Mar 22 '16

Author here. Questions are welcome.

4

u/Overv Mar 22 '16

What does this offer compared to existing frameworks like crow?

12

u/matthieugarrigues Mar 22 '16

There are many differences with crow, for example:

  • Silicon is not tight to an internal http implementation so it can easily be extended with, for example, a http2 web server library.

  • It does not use hash maps but plain C objects which are much faster at runtime.

  • Dependency injection allows you to pull only the middlewares you need for a given handler. It also allow middlewares to depend on each others.

1

u/Cyttorak Mar 23 '16

Can you explain a little bit deeper that hash maps vs C objects stuff? Thanks for your framework by the way.

4

u/matthieugarrigues Mar 23 '16 edited Mar 23 '16

C and C++ framework use hashmaps to store objects from json. They retrieve json attributes by refering them with string, for example:

o = json_decode("{\"a\": 32, \"b\": 42}");
int a = o["a"].get<int>();
int b = o["b"].get<int>();

The problem with this approach is that you can easily misspell the attribute name and/or type without the compiler being able to report an error. The hashmap also have a non negligible runtime impact.

In silicon, I overcome this problem by using statically introspectable object, the equivalent of the previous example would then be:

auto o = D(_a = int(), _b = int());
json_decode(o, "{\"a\": 32, \"b\": 42}");
int a = o.a;
int b = o.b;

Here, attributes are plain C++ object member. Misspelling errors will be reported at compile time and no hash table lookup are used anymore: It is faster and safer at the same time, and the code does not look much more complicated. We are also able to generate json de/serialization that a specifically optimize for each object type. You can also not than because we do not use hash maps, json_decode does not use memory allocations. You can read more about the static introspection of silicon here: https://github.com/matt-42/iod

1

u/[deleted] Jun 08 '24

Hmmm so this is kind of like zod (a Typescript library) for C++?

2

u/xcbsmith Mar 22 '16

How would you compare it with Seastar?

3

u/matthieugarrigues Mar 22 '16

I'm not a Seatar expert but from a quick look at the doc it seems lower level than Silicon. It would be a good candidate for a new Silicon backend.

1

u/[deleted] Mar 22 '16

I can't seem to find any example of how to use Seastar as a server. How does the syntax look when describing routes? eg. server.add_route_post("/ping", callback);

1

u/xcbsmith Mar 22 '16

No HTTP stack in Seastar, so hard to have routes. I think that's the real divergence here. Silicon kind of the layer above Seastar, though perhaps you can combine the two.

2

u/not_morgana Mar 22 '16

Not to be a buzz killer and all, but what's the purpose of this framework? Do you plan on using it on production someday? Is your website using this framework?

20

u/matthieugarrigues Mar 22 '16

There is advantages (and disavantages) of using C++. There is situations where loosely typed languages may be better but there is certainly lots of case where C++ has many advantages. The problem is that today, it is pretty hard to write web APIs in C++, this is why is not widely used, despite its performances.

Hopefully, the standard finalized C++14 and I jumped on this opportunity to take advantage of those new features (lambda, auto, variadic templates,...) to write a zero-cost and robust web framework. Zero-cost because most of the framework stack goes away at compile time, and robust because its static paradigm enables the compile to detect most of the errors.

11

u/Overv Mar 22 '16 edited Mar 22 '16

I'm working on an application that uses C++ for data processing and I chose to write the web API in C++ as well so that I could reuse all my existing classes and logic.

Compared to web apps I've written in a language like Python, the amount of errors that only show up at runtime has also reduced significantly.

With modern C++14 you can also completely avoid working with pointers, so memory management is no concern. In fact I've noticed that my Python web servers also used an order of magnitude more RAM, so C++ is also a good choice for reducing memory usage. This matters to me because this can make the difference between a $10/mo and a $20/mo VPS (significant to me as a student).

1

u/[deleted] Jun 08 '24

Now I wonder how people who want these benefits choose between C++ and Rust

-11

u/refutingbullshit Mar 22 '16

Segfaults while doing webdev obviously.

11

u/matthieugarrigues Mar 22 '16

Segfaults is also a problem that Silicon try to solve: It allows you to write APIs without the use of any pointer, which prevents you from most of the segfaults you can have.

5

u/[deleted] Mar 22 '16

I write a lot of C and C++ code. Segfaults are almost never my problem, memory leaks are more of a problem, and in production code that's usually easy to solve, and for personal code it's something I just don't care about until it becomes a problem.

Also, a segfault in the end is no different to any other fatal error. If you're seeing them a lot in production then you're really just not a very good C/C++ programmer, or working with a poorly written codebase that you inherited. It's no different to the kind of people that whine about NPEs in Java or similar errors in C#, JS, etc.

-1

u/zicapantaneira2014 Mar 23 '16

Why two space of indentation? The source code looks so shieeett

18

u/nnevatie Mar 22 '16

Looks pretty cool. How about those underscore prefixes, though? IIRC, a single leading underscore followed by an uppercase letter would be reserved, dictated by the standard.

8

u/matthieugarrigues Mar 22 '16

It was the case when I started to write this framework but I quickly fixed the problem

2

u/Plorkyeran Mar 22 '16

Glancing through the quick tour and docs I only see single underscore followed by a lowercase letter, which is fine.

7

u/lutinmutin Mar 22 '16

I cannot understand the necessity of the DSL and the probably insane amount of operator overloading behind it.

6

u/matthieugarrigues Mar 22 '16

As long as the DSL is obvious to the user, I do not see any problem with the insanity of the code behind it, as long as it is hidden to the user.

2

u/lutinmutin Mar 22 '16

I generally disapprove of changing the original semantics of operators: / should be a division, * a multiplication(or deref), and [] for indexing. Also, I haven't had a look at the code, but "insane" code tends to be harder to debug.

6

u/matthieugarrigues Mar 22 '16

Yes changing the semantics of an operator is not something I recommend neither. But I found that in some case it really simplify the code and as long as the new semantics is coherent, the user can get used to it quickly. I could have chosen a non DSL approach, but it would have been more verbose, harder to digest, and less similar to a real URL:

DSL: GET / _hello / _world / _id[int()]

Non DSL: GET.path(_hello).path(_world).url_param(_id, int())

3

u/gct Mar 23 '16 edited Mar 23 '16

How do you match a path to an http request? I'm guessing string matching, in which case, why not specify the path as a string in the first place? Something like:

get("/hello/world/{id:int}", <handler>);

1

u/matthieugarrigues Mar 23 '16

Because I need the symbol (_id) to generate the params object pass to the handler. Note that parameters a not passed via a hashmap but via the members of a C++ object.

Having everything typed also allows to generate a faster, specialized url parser for each path.

5

u/quicknir Mar 22 '16

/ is also used by boost filesystem, and boost::filesystem will be in 17 (including the /) as far as I know. I think you're fine. The really scary ones to overload are comma, ampersand, and &&/||. Comma is just absurd, ampersand is also pretty bad; it breaks any generic code where people have not been super meticulous about using std::address instead of &. And the latter two when overloaded, don't actually provide short circuiting semantics which is highly surprising.

The others in moderation are ok, as long as it's not overused.

3

u/joelwilliamson Mar 23 '16

Unary ampersand shouldn't be overloaded, but binary ampersand is fine if you are implementing a bitmask-like class.

5

u/mus1Kk Mar 22 '16

And << should be shifting.

6

u/reddit_clone Mar 22 '16

That ship has sailed a long time ago.

Isn't that used in streams extensively ?

1

u/lutinmutin Mar 22 '16

then lets not make it worse, lets limit to << is shifting/streaming-out

2

u/dallbee Mar 22 '16

Why would it be anything else?

hides among a collection of C books

7

u/reddit_clone Mar 22 '16
// Read a record.
int age; std::string name;
c("SELECT name, age from users LIMIT 1")() >> std::tie(name, age);

This is amazing !

5

u/j0hnGa1t Mar 22 '16

sqlpp11 is amazing. Get your SQL queries and types verified at compile time. In your // Read a record, let's hope there's no typos in your text string. That there's no null values, that name & age are the correct types etc.

auto row = db(select(users.name, users.age).from(users)).front()

row is a struct having .name & .age elements of the correct type.

6

u/matthieugarrigues Mar 23 '16

The typos, null values, etc.. will be spoted and reported (via an exception that will generate an internal server error) by the framework at runtime.

I will not say that one is better than another. I actually started to write something similar to sqlpp11, but stopped to concentrate my time on the framework. Both have drawbacks:

Silicon way is not typesafe but I does not limit you to a subset of sql, it is also much easier to use since it does not use c++ types.

sqlpp11 is typesafe and garanties that the request is valid but it probably do not cover the full SQL language, it is also a much bigger library (vs the 400 lines of the silicon middleware).

FInally, if you prefer sqlpp11, one could easily write a sqlpp11 middleware.

2

u/j0hnGa1t Mar 23 '16

+1 for writing your own framework, open sourcing it and promoting it on reddit for public criticism.

1

u/reddit_clone Mar 23 '16

Yep. I didn't expect this kind of typesafe extraction in C++. Perhaps in haskell.

Normally it is mucking about in a dictionary with string keys, with the risk of a typo killing your function.

2

u/[deleted] Mar 22 '16

I don't have much time to look through. Templating? Or does someone have a good templating suggestion?

Maybe good isn't the right word. One that they like I suppose.

2

u/matthieugarrigues Mar 22 '16

Templating is not provided by silicon but it does not prevent you to use one. However, I'll better use javascript to generate the DOM than sever side templating.

0

u/[deleted] Mar 22 '16 edited Mar 22 '16

You'll have to excuse my ignorance. My main Web experience is in big application servers.

I'll research the subject a bit more. So far all I come up with is include jquery and include this and include that.

My goal is to get in to today's Web without 150 megs of javascript.

In more searching client vs server side rendering seems like a big battle between everyone.

edit

I am still lost at why I wouldn't want a little of each. Not everyone writes or wants single page applications. Some basic templating to reduce payload in multipage apps doesn't seem terribly abnormal. I will definitely give this thing a go tonight though. Thanks.

2

u/raziel2p Mar 22 '16

I think the main point is, if you don't want to write just a JSON API, you probably shouldn't pick a C++ web framework. Right tool for the job etc.

The 150 megs of javascript comment is absurd. Javascript frameworks made for writing fully javascript apps (i.e. no server-side HTML rendering, just fetching data from an API) range from 10kb (Mithril) to 1-3MB (Angular, depending on how many extra dependencies you pull in). You can pull in jQuery on top of that for extra bloat, but it's rarely needed.

Server vs client side rendering is hardly a battle. Each has its own use case, and you can even combine them if you're clever.

The biggest challenge with JS dev is the tools. You have to know how to use npm and something like webpack to competently work with modern frameworks/libraries.

1

u/[deleted] Mar 23 '16

Dude, stick with client-side rendering but keep the HTML that you're rendering as lean and efficient as possible.

Client-side rendering is nice if you use a framework like what we use, Ampersand.js which can be used and tested on our end, w/o a browser.

Uglifcation and minification tools also help.

3

u/[deleted] Mar 22 '16

Last year I was surprised/happy to learn that c++ now supports heredoc, like this:

const char* htmlTemplate = R"htmlHeredoc(
<h1>World Peace</h1>
)htmlHeredoc";

I use it for templating. I think it was introduced in c++11.

21

u/losvedir Mar 22 '16

Huh. Last year I would have thought writing a web app in C++ would be madness, but after seeing the progress the rust community is making in web development with a very low level language, maybe there's something to it... Certainly the performance for small APIs would be beneficial.

One word of advice to the author: they seem to think the routing DSL is intuitive enough that it's practically self documenting. To me, at least, it's not. I checked the "quick tour" link, too, because I didn't quite get it from the blog post. Are the underscores part of the route? Is it how you specify string literals? It would go a long way to have a comment giving an example route that it matches, and what values are pulled out.

edit: Oh, the home page does have what I was looking for. It indicates GET / _hello / _world matches /hello/world. It was just in the paragraph above the example and I glossed over it.

8

u/KayEss Mar 22 '16

I've been doing webdev in C++ for years now -- it's pretty good (and I prefer doing it in C++ over Python really), and as you surmise the speed of the APIs can be insane. The server side is still a good deal simpler than having to write C++, though thankfully we don't have to do so much of this these days given the excellent CSS frameworks.

5

u/CookieOfFortune Mar 22 '16

What framework do you use?

3

u/awaitsV Mar 22 '16

can you give details on the stack that you use?

4

u/KayEss Mar 23 '16

It's largely based around this stuff found in here https://github.com/KayEss/fost-meta and is mostly doing JSON APIs for use in things like angularjs applications.

0

u/weberc2 Mar 22 '16

I would not consider Python to be a good language for web development, as someone who writes Python web things professionally. Go is my standard for a good web language.

7

u/AaronOpfer Mar 22 '16

As someone who also writes Python web things professionally, I find python to be an excellent language for web development. What exactly about Python do you think is weak for web development?

1

u/weberc2 Mar 23 '16

Hi, I replied to another commenter here. I wrote it up quickly; it only focuses on the things I dislike about Python, so please don't read it as a rant. :)

1

u/havacore Mar 22 '16

We've been doing webdev in both python and go. Python is great for like, 90% of what you need to do on the web. We write a little bit of Go for anything that requires some really heavy lifting, but you just can't beat python when it comes to development speed and maintainability.

Still interested in why you would think python is bad for web development

4

u/weberc2 Mar 23 '16

Still interested in why you would think python is bad for web development

I wouldn't say Python is bad for web development; it's just not the gold standard. Python has a lot of good parts--I especially like its comprehensions, iterators, and generator expressions. It makes it quite easy for a team of experienced, disciplined developers to crank out code quickly (so long as the code doesn't need to be parallel).

However, I disagree with you that Python excels at development speed and maintainability. Here are some grievances I have with Python regarding development speed and maintainability, in no particular order:

  • Python's "fast development" is an illusion achieved mostly by removing static analysis tools from the loop or otherwise making it very hard for static analysis tools to do their jobs. You're only kicking bugs down the road where they're more expensive to find and fix.

  • Python encourages lots of bad programming practices by making the bad thing easy (no language prevents bad code, but Python actively tempts developers to write it). For examples:

    • Why inject your dependencies when you can just mock.patch() to "validate" your spaghetti code?

    • Why design interfaces when you can just isinstance(x, T)?

    • Why define classes with structure when you can just pass around dicts and tack on whatever you think someone else might need down the road?

  • And then there are other misfeatures that it includes just to trip up beginners:

    • inheritance

    • decorators

    • default arguments (def func(arg=[]))

  • Style

    • Not enforced

    • Standard library mixes conventions (assertEqual() isn't snake case)

    • PEP8 is the first and only style guideline I've ever felt makes code less readable. This is obviously subjective, so I won't discuss it further.

  • Setuptools suck. Pip sucks. Easy_install sucks. I don't think anyone disagrees with this, but it doesn't make development more pleasant.

  • Python completely ignores it's own Zen. By coincidence, Go seems to respect Python's Zen more than Python does.

Basically, Python makes collaboration harder than it needs to be. Of course, these criticisms are general--not specific to web development. My grievances with Python's web development story are:

  • You need an external web server to handle requests in parallel with decent performance

  • I've not yet encountered a decent web framework. Certainly nothing as straightforward as Go's HTTP library.

  • Parallelism is hard in Python. This isn't a super common case, but it's not an edge case either. And it really sucks when you start a project in Python thinking you won't need parallelism, only to find out you really do need it.

  • Deploying Python sucks (lots of runtime dependencies)

Like I said, I still think Python is a fun, useful language; I enjoy writing it, I just think Go beats it at many of its own strengths.

1

u/DigitalDolt Mar 22 '16

What is the advantage of using something like this over Go?

For the vast majority of applications Go is Fast EnoughTM, but it's also way easier to write, read, test, and deploy.

9

u/matthieugarrigues Mar 22 '16

You'll prefer C++ when performance is the #1 priority. But you're right, most of the websites don't handle more than 10req/s and the web framework they use will never be a bottleneck.

1

u/yelnatz Mar 23 '16

If the main point of choosing your framework is performance, you should post some benchmarks front and center.

2

u/matthieugarrigues Mar 23 '16

I added this first release to the techempower benchmark. It should be published soon.

1

u/dallbee Mar 23 '16

I'll prefer C, personally

3

u/matthieugarrigues Mar 23 '16

I respect your choice. C is better than C++ in some ways, and both also have drawbacks. This framework does not aim to be the univeral web framework. I do not want to convince anybody to use C++ instead of their preferred language. Silicon mainly targets peoples who already made (or are open to) the C++ choice.

1

u/dallbee Mar 28 '16

Have an up vote.

2

u/[deleted] Mar 23 '16

This is largely true. But C++ would be a welcome contender into the arena so I really appreciate efforts like Silicon.

I was curious because I haven't read HTTP specs but are all the verbs supported like PUT, PATCH, DELETE, HEAD, OPTIONS, um... I know there are some other weird ones...

I'm kind of at the point now where if I see a verb in a url I basically have a rage-aneurysm.

1

u/[deleted] Mar 22 '16

Do you spawn a sqlite instance per thread?

Any plans for http2 ?

I'm currently working on a c++ web thing myself. I didn't use a framework. I used nginx+fcgi and sqlite+sqlitecpp and rapidjson. Getting rid of nginx and fcgi would be awesome.

2

u/matthieugarrigues Mar 22 '16

One sqlite connection per thread is something I'll implement soon. It is done with mySQL but for now, the sqlite_connection middleware only use one connection with the serialized mode: https://sqlite.org/threadsafe.html

Silicon does not implement neither HTTP or HTTP2. Instead, it relies on external libraries. Today, only HTTP1 libraries are wraped but I'll probably add a HTTP2-compliant one later.

If you have any question regarding your project feel free to post it here: https://groups.google.com/forum/?fromgroups=#!forum/siliconframework

-7

u/deus_lemmus Mar 22 '16

Ouch my eyes.

0

u/[deleted] Mar 22 '16

[deleted]

10

u/matthieugarrigues Mar 22 '16

I could add a boost::asio backend but it was quicker to first rely on simple C library providing a HTTP server implementation.

Thanks for noticing about auto/const auto. I'll update it.

4

u/lolomfgkthxbai Mar 22 '16

Does adding const add any value, besides making the variable constant? Also, doesn't the cargo-cult say that you should make it a reference:

for (const auto &foo : bar) {...}

7

u/matthieugarrigues Mar 22 '16

It is true that it make less sense to make a value const than making a reference const. To me, it is just to make explicit the fact that this variable wont be modified, making the code a bit more readable.

Adding the reference is more a performance optimization to avoid copying every vector elements. I could also add it, but if it would not make much difference in the whole framework running-time since it does not involves performance-critical code.

1

u/vincentk Mar 23 '16

If you can't make it a const, then how can you treat foo and &foo as equivalent?

1

u/j0hnGa1t Mar 22 '16

Meh. Value loop, not a reference loop. Short {...}. Wish there was a way to make const default. There were a few rejected proposals to be able to write just for(foo:bar){...}