Rocket Review
Published: 2022-01-02 03:35:25

---
title: Rocket Review
published: true
date: 2022-01-01 14:28:00 UTC
tags: 
canonical_url: https://kevincox.ca/2022/01/01/rocket-review/
---

<main><p>I recently launched a web service using <a href="https://rocket.rs/">Rocket</a> (0.5.0-rc.1). After about a month, I migrated it to <a href="https://actix.rs/">actix-web</a> (although using only a small amount of the framework). I thought it would be interesting to document my rationale and thoughts about Rocket, as well as a little of how it compares to actix-web and some general ideas for web servers in Rust.</p>
<p>If you want the TL;DR, the problem that made me ditch Rocket is <a href="https://kevincox.ca/2022/01/01/rocket-review/#no-request-object">No Request Object</a>.</p>
<p>The code snippets in this article are taken from FeedMail but have been simplified to highlight the points I am making. They may have accidental errors and aren’t intended to be used as a tutorial for either Rocket or actix-web.</p>
<h2 id="rocket-pros"><a href="https://kevincox.ca/2022/01/01/rocket-review/#rocket-pros">Rocket Pros</a></h2>
<p>First, let’s talk about the things that I liked about Rocket. Overall it was a nice framework and got FeedMail off the ground quickly.</p>
<h3 id="query-routing"><a href="https://kevincox.ca/2022/01/01/rocket-review/#query-routing">Query Routing</a></h3>
<p>Rocket had something that I haven’t seen in any other framework, the ability to route based on query parameters. For example, I can have the following two routes; the first will be called if there is no <code>url</code> parameter passed and the second will be called if there is.</p>
<div><pre><code><span>#[rocket::get(</span><span>"/subscriptions"</span><span>)]</span>
<span>fn</span> <span>subscriptions</span><span>()</span> <span>{</span> <span>...</span> <span>}</span>
</code></pre></div>
<div><pre><code><span>#[rocket::get(</span><span>"/subscriptions/new?&lt;url&gt;"</span><span>)]</span>
<span>fn</span> <span>subscriptions_new_url</span><span>(</span><span>url</span><span>:</span> <span>&amp;</span><span>str</span><span>)</span> <span>{</span> <span>...</span> <span>}</span>
</code></pre></div>
<p>This is very useful when the presence or absence of a parameter dramatically changes the logic of an endpoint. Of course, Rocket still supports optional parameters, so you don’t need to use this approach if the parameter only has a minor effect on the handler.</p>
<div><pre><code><span>#[rocket::get(</span><span>"/subscriptions/new?&lt;url&gt;"</span><span>)]</span>
<span>fn</span> <span>subscriptions_new_url</span><span>(</span><span>url</span><span>:</span> <span>Option</span><span>&lt;&amp;</span><span>str</span><span>&gt;</span><span>)</span> <span>{</span> <span>...</span> <span>}</span>
</code></pre></div>
<p>While this was a really nice feature it seems to be under-developed. Rocket sometimes complains about conflicting routes where I think the precedence should be obvious. This requires adding manual ordering to resolve.</p>
<p>For example the following routes conflict and require manual ordering to resolve.</p>
<ul>
<li><code>/email/remove?&lt;proof&gt;</code></li>
<li><code>/email/remove?&lt;unsubscribe&gt;</code></li>
</ul>
<p>I assume this is because while the parameters were defined as <code>&amp;str</code> they could have been defined as <code>Option&lt;&amp;str&gt;</code> which <strong>would</strong> be a conflict. It’s a real shame that the router isn’t aware of this though and requires adding <code>rank=1</code> to one of the routes. Also, the ordering of the <code>rank</code> parameter confuses me and I always end up with them in the wrong order the first time.</p>
<h3 id="url-generation"><a href="https://kevincox.ca/2022/01/01/rocket-review/#url-generation">URL Generation</a></h3>
<p>The thing I will miss the most about Rocket is the type-safe URL generation. The following code should serve as a good example:</p>
<div><pre><code><span>#[rocket::get(</span><span>"/subscriptions/new?&lt;url&gt;"</span><span>)]</span>
<span>fn</span> <span>subscriptions_new_url</span><span>(</span><span>url</span><span>:</span> <span>&amp;</span><span>str</span><span>)</span> <span>{</span> <span>...</span> <span>}</span>

<span>#[rocket::get(</span><span>"/subscriptions/&lt;id&gt;"</span><span>)]</span>
<span>fn</span> <span>subscriptions_get</span><span>(</span><span>id</span><span>:</span> <span>i64</span><span>)</span> <span>{</span> <span>...</span> <span>}</span>

<span>fn</span> <span>test</span><span>()</span> <span>{</span>
	<span>assert</span><span>!</span><span>(</span>
		<span>rocket</span><span>::</span><span>uri!</span><span>(</span><span>subscriptions_new</span><span>(</span><span>url</span><span>=</span><span>"https://kevincox.ca"</span><span>))</span><span>.to_string</span><span>(),</span>
		<span>"/subscriptions/new?url=https%3A%2F%2Fkevincox.ca"</span><span>)</span>
	<span>assert</span><span>!</span><span>(</span>
		<span>rocket</span><span>::</span><span>uri!</span><span>(</span><span>subscriptions_get</span><span>(</span><span>id</span><span>=</span><span>5</span><span>))</span><span>.to_string</span><span>(),</span>
		<span>"/subscriptions/5"</span><span>)</span>
<span>}</span>
</code></pre></div>
<p>It seems trivial but there are huge benefits. For example:</p>
<ul>
<li>Changes to URLs or parameters are automatically synced between routing and generation.</li>
<li>Removing parameters or routes raises errors in code that tries to use them.</li>
<li>Typos are caught by the compiler rather than producing wrong URLs.</li>
<li>URL-escaping handled automatically.</li>
</ul>
<p>Even if changing paths and parameters should be a rare operation, the last couple of points are useful for ongoing development and make broken URLs incredibly rare.</p>
<p>It is also easy to generate absolute URLs. This is useful for generating email and other non-web content.</p>
<div><pre><code><span>rocket</span><span>::</span><span>uri!</span><span>(</span>
	<span>global</span><span>.config.host</span><span>.clone</span><span>(),</span>
	<span>crate</span><span>::</span><span>subscriptions_get</span><span>(</span><span>id</span><span>=</span><span>subscription</span><span>))</span>
</code></pre></div>
<p>My only real complaint is that due to the heavy type-inference it can be quite noisy at times. But while a handful to type or read, the code is still quite simple. So overall, I am happy with the API and wish it was available in other frameworks.</p>
<div><pre><code><span>rocket</span><span>::</span><span>uri!</span><span>(</span>
	<span>// This needs to be cloned.</span>
	<span>global</span><span>.config.host</span><span>.clone</span><span>(),</span>
	<span>login_reset_password</span><span>(</span>
		<span>// These type hints are necessary.</span>
		<span>email</span><span>=</span><span>None</span><span>::</span><span>&lt;&amp;</span><span>str</span><span>&gt;</span><span>,</span>
		<span>err</span><span>=</span><span>None</span><span>::</span><span>&lt;&amp;</span><span>str</span><span>&gt;</span><span>))</span>
</code></pre></div>
<h2 id="rocket-cons"><a href="https://kevincox.ca/2022/01/01/rocket-review/#rocket-cons">Rocket Cons</a></h2>
<h3 id="no-request-object"><a href="https://kevincox.ca/2022/01/01/rocket-review/#no-request-object">No Request Object</a></h3>
<p>This is the reason that I ultimately left Rocket. Instead of giving you a “Request” object in handlers to access information such as the URL, query parameters and headers; Rocket forces you to use their <a href="https://docs.rs/rocket/0.5.0-rc.1/rocket/request/trait.FromRequest.html">FromRequest API</a> inside handlers. While the API is convenient for a lot of cases, I found that it was too limiting to build reusable APIs upon and didn’t allow easy composition of helpers in handlers.</p>
<h4 id="good-example"><a href="https://kevincox.ca/2022/01/01/rocket-review/#good-example">Good Example</a></h4>
<p>One place where this worked really well was for user login. I could write a “guard” that checked a user was logged in and extracted session information.</p>
<div><pre><code><span>#[rocket::get(</span><span>"/subscriptions"</span><span>)]</span>
<span>fn</span> <span>subscriptions_list</span><span>(</span><span>user</span><span>:</span> <span>crate</span><span>::</span><span>User</span><span>)</span> <span>-&gt;</span> <span>String</span> <span>{</span>
	<span>format!</span><span>(</span><span>"User {} is logged in!"</span><span>,</span> <span>user</span><span>.id</span><span>)</span>
<span>}</span>
</code></pre></div>
<p>This works quite well, and using the <code>FromRequest</code> API I was allowed to respond with a “401 Forbidden” response code if the user was not logged in. Then I could use a “catcher” to redirect to the login page which would redirect the user back to the original page after being logged in.</p>
<h4 id="ok-example"><a href="https://kevincox.ca/2022/01/01/rocket-review/#ok-example">Ok Example</a></h4>
<p>The other major guard I used was to prevent against <a href="https://owasp.org/www-community/attacks/csrf">CSRF</a> requests. For mutating endpoints I would check that the request was same-origin. Using the guard was a bit more involved and looked like this:</p>
<div><pre><code><span>#[rocket::post(</span><span>"/subscriptions/new"</span><span>,</span> <span>data=</span><span>"&lt;subscription&gt;"</span><span>)]</span>
<span>pub</span> <span>async</span> <span>fn</span> <span>subscriptions_new_post</span><span>(</span>
	<span>sameorigin</span><span>:</span> <span>Result</span><span>&lt;</span><span>crate</span><span>::</span><span>SameOrigin</span><span>,</span> <span>&amp;</span><span>str</span><span>&gt;</span><span>,</span>
	<span>body</span><span>:</span> <span>rocket</span><span>::</span><span>form</span><span>::</span><span>Form</span><span>&lt;</span><span>SubscribtionNewForm</span><span>&lt;</span><span>'_</span><span>&gt;&gt;</span><span>,</span>
<span>)</span> <span>{</span>
	<span>if</span> <span>let</span> <span>Err</span><span>(</span><span>err</span><span>)</span> <span>=</span> <span>sameorigin</span> <span>{</span>
		<span>return</span> <span>crate</span><span>::</span><span>redirect</span><span>(</span>
			<span>err</span><span>,</span>
			<span>rocket</span><span>::</span><span>uri!</span><span>(</span><span>subscriptions_new_url</span><span>(</span><span>url</span><span>=</span><span>body</span><span>.url</span><span>)))</span>
	<span>}</span>
<span>}</span>
</code></pre></div>
<p>The <code>SameOrigin</code> guard checks that a request is actually same origin otherwise returns an error. However, due to the limited <code>FromRequest</code> API, all I can do is return an arbitrary error—which is usually ignored—and a status code. If I just rely on the status code I need no “error” handling in the handler itself and can install a catcher to manage that. But as far as I am aware, the catcher has no way of knowing which guard failed. This makes it impossible to redirect to a helpful URL or other clever logic (unless I abuse status codes to identify the source guard or particular error condition). So instead you need to manually handle the “error” value here (which in the example is just a <code>&amp;str</code>) so I can more flexibly handle the error.</p>
<p>This starts to make me question the utility of this guard pattern. The hidden “error” path has incredibly limited response capabilities and there is very little customisability as all of the customization needs to be done at the type level. It seems for anything moderately complex you need to force the route to handle the error. So what have you gained from the special guard API?</p>
<p>After migration to actix-web the same “guard” looks like this:</p>
<div><pre><code><span>if</span> <span>let</span> <span>Err</span><span>(</span><span>err</span><span>)</span> <span>=</span> <span>crate</span><span>::</span><span>same_origin</span><span>(</span><span>req</span><span>)</span> <span>{</span>
	<span>return</span> <span>crate</span><span>::</span><span>redirect</span><span>(</span>
		<span>err</span><span>,</span>
		<span>// My new URL generation.</span>
		<span>crate</span><span>::</span><span>SubscriptionsNewQuery</span><span>::</span><span>err</span><span>(</span><span>body</span><span>.url</span><span>.to_string</span><span>(),</span> <span>None</span><span>)</span><span>.to_url</span><span>())</span>
<span>}</span>
</code></pre></div>
<p>This is a fairly straight-forward conversion of the old guard but keeps the whole thing in code rather than messing with the <code>FromRequest</code> trait. This also means that I can do much more complex things such passing runtime parameters. For example, Rocket has built-in request size limiting, but this is static by “category” such as bytes, form bodies and file uploads. If implemented in the request body it would be easy to customize the limit for different routes or even different users (for example different subscription levels could have different limits).</p>
<h3 id="bad-example"><a href="https://kevincox.ca/2022/01/01/rocket-review/#bad-example">Bad Example</a></h3>
<p>Using Rocket I failed to implement <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag">ETag</a>s on a bunch of static pages. I was hoping that I could implement it with a guard. However, this was not possible. Even if implemented with a helper function in the handler it would be very difficult.</p>
<p>I did manage to add ETags for my static assets because they were managed by a macro. But looking at the macro it is clear why it is not worth adding this to other routes.</p>
<div><pre><code><span>macro_rules!</span> <span>static_file</span> <span>{</span>
	<span>(</span> <span>$path:expr</span><span>,</span> <span>$n:ident</span><span>,</span> <span>$ext:literal</span><span>,</span> <span>$type:expr</span> <span>)</span> <span>=&gt;</span> <span>{</span>
		<span>#[rocket::get(</span><span>$</span><span>path)]</span>
		<span>pub</span> <span>fn</span> <span>$n</span><span>(</span>
			<span>global</span><span>:</span> <span>&amp;</span><span>rocket</span><span>::</span><span>State</span><span>&lt;&amp;</span><span>crate</span><span>::</span><span>Global</span><span>&gt;</span><span>,</span>
			<span>headers</span><span>:</span> <span>crate</span><span>::</span><span>guards</span><span>::</span><span>Headers</span><span>,</span>
		<span>)</span> <span>-&gt;</span> <span>rocket</span><span>::</span><span>Response</span> <span>{</span>
			<span>let</span> <span>body</span> <span>=</span> <span>std</span><span>::</span><span>include_bytes!</span><span>(</span>
				<span>std</span><span>::</span><span>concat!</span><span>(</span><span>"../static/"</span><span>,</span> <span>std</span><span>::</span><span>stringify!</span><span>(</span><span>$n</span><span>),</span> <span>$ext</span><span>));</span>

			<span>let</span> <span>mut</span> <span>r</span> <span>=</span> <span>rocket</span><span>::</span><span>Response</span><span>::</span><span>build</span><span>();</span>
			<span>r</span><span>.raw_header</span><span>(</span><span>"cache-control"</span><span>,</span> <span>"max-age=600"</span><span>);</span>

			<span>if</span> <span>let</span> <span>Some</span><span>(</span><span>etag</span><span>)</span> <span>=</span> <span>&amp;</span><span>global</span><span>.etag</span> <span>{</span>
				<span>r</span><span>.raw_header</span><span>(</span><span>"etag"</span><span>,</span> <span>etag</span><span>);</span>
				<span>if</span> <span>headers</span><span>.get_one</span><span>(</span><span>"if-none-match"</span><span>)</span> <span>==</span> <span>Some</span><span>(</span><span>etag</span><span>)</span> <span>{</span>
					<span>r</span><span>.status</span><span>(</span><span>rocket</span><span>::</span><span>http</span><span>::</span><span>Status</span><span>::</span><span>NotModified</span><span>);</span>
					<span>return</span> <span>r</span><span>.finalize</span><span>()</span>
				<span>}</span>
			<span>}</span>

			<span>r</span><span>.header</span><span>(</span><span>$type</span><span>);</span>
			<span>r</span><span>.sized_body</span><span>(</span><span>body</span><span>.len</span><span>(),</span> <span>std</span><span>::</span><span>io</span><span>::</span><span>Cursor</span><span>::</span><span>new</span><span>(</span><span>body</span><span>));</span>
			<span>r</span><span>.finalize</span><span>()</span>
		<span>}</span>
	<span>}</span>
<span>}</span>

<span>static_file!</span><span>(</span><span>"/a/logo.png"</span><span>,</span> <span>logo</span><span>,</span> <span>".png"</span><span>,</span> <span>rocket</span><span>::</span><span>http</span><span>::</span><span>ContentType</span><span>::</span><span>PNG</span><span>);</span>
</code></pre></div>
<p>I have a number of problems with this approach:</p>
<ol>
<li>Every route that needs this needs to add the (custom) <code>Headers</code> guard/extractor to their arguments list. In fact if I was doing the “the rocket way” I would have made a more targeted <code>IfNoneMatch</code> guard since you are <a href="https://github.com/SergioBenitez/Rocket/pull/675#issuecomment-400333243">supposed to extract small bits of the request</a>. But this leads to an explosion of parameters once you add a couple of guards.</li>
<li>You need to set the same headers on the “full” response and the “Not Modified” response (for example <code>Cache-Control</code>). This is difficult when the response object is generated after you do the ETag check.</li>
</ol>
<p>So while this was worth implementing for the simple case of static files, it wasn’t worth adding to other endpoints.</p>
<p>I find that guards work well for simple cases but fail for more complex cases. For more complex cases you need guards to pull the data from the request, then you pass it to an in-code “guard”. But at this point what is the benefit? You are just repeating yourself twice, once to acquire the values and once to pass them to the “guard”.</p>
<p>It seems like guards are cute and save a tiny amount of typing at best. But since they can’t handle more complex cases I don’t find they justify their complexity. My code on actix-web now just uses regular Rust code which I find both simpler and more flexible.</p>
<div><pre><code> fn subscriptions_list(
 	...
<span>-	user: crate::guards::User,
</span> ) -&gt; crate::Response {
<span>+	let user = crate::guards::user(req)?;
</span></code></pre></div>
<p>To be fair instead of having the guard in the handler parameters I do need to have a <code>Request</code> object passed in. But that is passed in once for all of the guards and for the handler itself. In Rocket I needed to keep adding new arguments that are copy-pasted into the arguments list of every handler that used an in-code “guard”. While you can argue that this is a violation of functions taking exactly the values they depend on, I would argue that the caller shouldn’t need to know what data each specific guard depends on. For example if I decide that you can authenticate with an <code>Authorization</code> header rather than passing a <code>Cookie</code> I don’t feel like I should need to update the callers.</p>
<p>Now ETag checks look like the following and I can easily apply it to all static routes.</p>
<div><pre><code><span>// Set headers that need to be on 304 Not Modified responses.</span>
<span>crate</span><span>::</span><span>ui</span><span>::</span><span>set_cache</span><span>(</span><span>res</span><span>,</span> <span>"max-age=600"</span><span>);</span>

<span>// Check if the request is conditional and either early return or just set the response header.</span>
<span>crate</span><span>::</span><span>guards</span><span>::</span><span>version_etag</span><span>(</span><span>global</span><span>,</span> <span>req</span><span>,</span> <span>res</span><span>)</span><span>?</span><span>;</span>

<span>// Generate page.</span>
<span>crate</span><span>::</span><span>ui</span><span>::</span><span>page</span><span>(</span><span>res</span><span>,</span> <span>...</span><span>)</span>
</code></pre></div>
<p>I just need to add a single function call for ETag handling! The things that make this work are:</p>
<ol>
<li>The ability to set headers before the check.</li>
<li>The ability to return arbitrary responses from the “guard”.</li>
<li>The ability to set response headers.</li>
</ol>
<p>None of these could readily be done with Rocket’s <code>FromRequest</code> framework.</p>
<h3 id="macro-route-error-reporting"><a href="https://kevincox.ca/2022/01/01/rocket-review/#macro-route-error-reporting">Macro Route Error Reporting</a></h3>
<p>In Rocket a minor issue is that you define your Routes using an attribute macro. Unfortunately the Rust complier handles syntax errors very poorly in this case. If the function has a syntax error the syntax macro doesn’t run and you get a ton of errors about the function not existing. This isn’t really Rocket’s fault (it is mostly the fact that <a href="https://github.com/rust-lang/rust/issues/27189">the Rust compiler can’t stop on the first error</a> and tends to snowball a lot of errors that don’t really exist because of what it assumed about your code) but it does make development a bit annoying.</p>
<h3 id="405-method-not-allowed-handled-incorrectly"><a href="https://kevincox.ca/2022/01/01/rocket-review/#405-method-not-allowed-handled-incorrectly">405 Method Not Allowed handled incorrectly.</a></h3>
<p>Another minor complaint is that if I declare a route for one method other methods should return <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405">405 Method Not Allowed</a>. Like most Rust frameworks Rocket doesn’t handle this correctly but instead returns a 404. This isn’t a big deal and is mostly just pedantry.</p>
<h2 id="my-own-framework">My Own “framework”</h2>
<p>As I mentioned at the beginning I’m not using all of actix-web, instead I have created a bit of my own framework inside of it. In fact the main setup of my <code>actix_web::HttpServer</code> shows how little of the framework I’m using. I’m not using multiple “services” instead just using a default and doing routing myself.</p>
<div><pre><code><span>actix_web</span><span>::</span><span>HttpServer</span><span>::</span><span>new</span><span>(</span>
		<span>move</span> <span>||</span> <span>actix_web</span><span>::</span><span>App</span><span>::</span><span>new</span><span>()</span>
			<span>.app_data</span><span>(</span><span>actix_web</span><span>::</span><span>web</span><span>::</span><span>PayloadConfig</span><span>::</span><span>new</span><span>(</span><span>128</span> <span>*</span> <span>1024</span> <span>*</span> <span>1024</span><span>))</span>
			<span>.default_service</span><span>(</span><span>actix_web</span><span>::</span><span>web</span><span>::</span><span>to</span><span>(</span><span>handle_request</span><span>)))</span>
	<span>.bind</span><span>(</span><span>std</span><span>::</span><span>env</span><span>::</span><span>var</span><span>(</span><span>"FEEDMAIL_BIND"</span><span>)</span><span>.as_deref</span><span>()</span>
		<span>.unwrap_or</span><span>(</span><span>"127.0.0.1:8000"</span><span>))</span><span>.unwrap</span><span>()</span>
	<span>.shutdown_timeout</span><span>(</span><span>if</span> <span>cfg!</span><span>(</span><span>dbg</span><span>)</span> <span>{</span> <span>0</span> <span>}</span> <span>else</span> <span>{</span> <span>600</span> <span>})</span>
	<span>.run</span><span>()</span>
</code></pre></div>
<p>I made a couple of interesting decisions in my implementation and thought I would show some examples of what the code looks like.</p>
<h3 id="passed-in-response-object"><a href="https://kevincox.ca/2022/01/01/rocket-review/#passed-in-response-object">Passed in Response Object</a></h3>
<p>Most frameworks I saw let you respond with any object that implemented some “Responder” trait. This seemed like a good idea at first, but I found that it was too limiting. Instead, I found it best to pass in an “out parameter” <code>&amp;mut Response</code> that could be updated with the response.</p>
<p>Here are some issues that I had with the other approach:</p>
<h4 id="all-returns-must-be-the-same-type"><a href="https://kevincox.ca/2022/01/01/rocket-review/#all-returns-must-be-the-same-type">All Returns Must Be the Same Type</a></h4>
<p>If you had early returns for things like errors or failed “guards” you had to respond with the same type. This was very limiting, so I ended up using a “type erased” object such as <code>rocket::Response</code>. This was such a frequent issue that I just switched to using the same type of response object everywhere. This means that the flexible “Responder” trait was not being used anyway.</p>
<h4 id="setting-headers-is-awkward"><a href="https://kevincox.ca/2022/01/01/rocket-review/#setting-headers-is-awkward">Setting Headers is Awkward</a></h4>
<p>In this case I found that I was frequently doing code like this.</p>
<div><pre><code><span>let</span> <span>mut</span> <span>r</span> <span>=</span> <span>render_page</span><span>(</span><span>...</span><span>)</span><span>?</span><span>;</span>
<span>r</span><span>.set_header</span><span>(</span><span>CacheControl</span><span>::</span><span>IMMUTABLE</span><span>);</span>
<span>Ok</span><span>(</span><span>r</span><span>)</span>
</code></pre></div>
<p>With a passed in response I could just do:</p>
<div><pre><code><span>res</span><span>.set_header</span><span>(</span><span>CacheControl</span><span>::</span><span>IMMUTABLE</span><span>);</span>
<span>render_page</span><span>(</span><span>res</span><span>,</span> <span>...</span><span>)</span>
</code></pre></div>
<h4 id="etag-generation-is-very-awkward"><a href="https://kevincox.ca/2022/01/01/rocket-review/#etag-generation-is-very-awkward">ETag Generation is Very Awkward</a></h4>
<p>When responding <code>304 Not Modified</code> you need to include the <code>Cache-Control</code> header even if you don’t generate the response. If you want to avoid actually generating the page this can be quite difficult. With a response out-parameter you can just set the cache header first, then check for conditional request headers, then generate the response.</p>
<p>One downside here is you need to be careful about setting a cache header before running code that may return a transient error. You might end up with your error being cached when you didn’t want it to be, especially if you issue an <code>ETag</code> based on code version! This could result in an error being stuck in your cache for an extended period of time! When the error handlers generate “fresh” responses this issue naturally doesn’t occur.</p>
<h4 id="setting-cookies-requires-special-logic"><a href="https://kevincox.ca/2022/01/01/rocket-review/#setting-cookies-requires-special-logic">Setting Cookies Requires Special Logic</a></h4>
<p>Often when setting cookies they aren’t specifically related to any particular response, you want to return them to the client no matter what else happens whether that is a redirect, error or successful response. Rocket and other frameworks handle this by providing a way to access a “cookie jar” which you can add cookies to, those are then automatically attached to whatever response ends up being returned. With the “out parameter” response you can just set the cookie with no special API. Of course, you can also do this for any other header without needing to roll your own solution.</p>
<h3 id="using-result-for-control-flow"><a href="https://kevincox.ca/2022/01/01/rocket-review/#using-result-for-control-flow">Using Result for control flow.</a></h3>
<p>Rust has a fantastic <code>?</code> (try) operator which can simplify error handling. In the future <a href="https://github.com/rust-lang/rust/issues/84277">this operator will be usable on custom types</a> but for now it is only available on <code>std::result::Result</code> and <code>std::option::Option</code>. I had to get a bit creative to make everything work well and ended up with this API for handlers:</p>
<div><pre><code><span>/// Marker that the response body has been filled.</span>
<span>struct</span> <span>BodySet</span><span>;</span>

<span>/// Marker that the Result is not actually an error but the response is filled properly.</span>
<span>struct</span> <span>EarlyReturn</span><span>;</span> <span>// Implements std::error::Error.</span>

<span>type</span> <span>Response</span> <span>=</span> <span>Result</span><span>&lt;</span><span>BodySet</span><span>,</span> <span>anyhow</span><span>::</span><span>Error</span><span>&gt;</span><span>;</span>
</code></pre></div>
<p>All of my handlers and most of my helper functions return a <code>crate::Response</code> which allows a number of things:</p>
<ul>
<li>
<code>BodySet</code> is just a marker to ensure that someone remembered to set the body. It trickles down from a helper which sets the body, so handler code barely needs to remember it exists.</li>
<li>
<code>?</code> can be used on any <code>Result&lt;_, impl std::error::Error + 'static&gt;</code> in the handler to log the error and return a generic 500.</li>
<li>Returning <code>Err(EarlyReturn.into())</code> can be used from helpers to short-circuit request handling. This isn’t truly an error and the top-level dispatch will use the response instead of generating a generic error page. This is a bit of a hack but very nicely allows early-return with arbitrary responses.</li>
</ul>
<p>Here is some code examples to show how this works.</p>
<div><pre><code><span>fn</span> <span>handle_request</span><span>(</span><span>req</span><span>:</span> <span>actix_web</span><span>::</span><span>HttpRequest</span><span>)</span> <span>-&gt;</span> <span>actix_web</span><span>::</span><span>HttpResponse</span> <span>{</span>
	<span>let</span> <span>mut</span> <span>res</span> <span>=</span> <span>actix_web</span><span>::</span><span>HttpResponse</span><span>::</span><span>new</span><span>(</span><span>http</span><span>::</span><span>StatusCode</span><span>::</span><span>OK</span><span>);</span>
	<span>match</span> <span>route_request</span><span>(</span><span>&amp;</span><span>req</span><span>,</span> <span>&amp;</span><span>mut</span> <span>res</span><span>)</span> <span>{</span>
		<span>Ok</span><span>(</span><span>BodySet</span><span>)</span> <span>=&gt;</span> <span>{}</span>
		<span>Err</span><span>(</span><span>e</span><span>)</span> <span>=&gt;</span> <span>if</span> <span>e</span><span>.root_cause</span><span>()</span><span>.is</span><span>::</span><span>&lt;</span><span>EarlyExit</span><span>&gt;</span><span>()</span> <span>{</span>
			<span>// Do nothing, response was generated by whoever returned the EarlyExit.</span>
		<span>}</span> <span>else</span> <span>{</span>
			<span>log</span><span>(</span><span>e</span><span>);</span>
			<span>// Generate generic error page.</span>
			<span>render_internal_error</span><span>(</span><span>&amp;</span><span>mut</span> <span>res</span><span>)</span>
				<span>.expect</span><span>(</span><span>"error generating error page"</span><span>);</span>
		<span>}</span>
	<span>}</span>
	<span>res</span>
<span>}</span>

<span>fn</span> <span>require_user</span><span>(</span>
	<span>req</span><span>:</span> <span>&amp;</span><span>actix_web</span><span>::</span><span>HttpRequest</span><span>,</span>
	<span>res</span><span>:</span> <span>&amp;</span><span>mut</span> <span>actix_web</span><span>::</span><span>HttpResponse</span><span>,</span>
<span>)</span> <span>-&gt;</span> <span>anyhow</span><span>::</span><span>Result</span><span>&lt;</span><span>User</span><span>&gt;</span> <span>{</span>
	<span>try_user</span><span>(</span><span>req</span><span>,</span> <span>res</span><span>)</span>
		<span>.or_else</span><span>(|</span><span>msg</span><span>|</span> <span>{</span>
			<span>crate</span><span>::</span><span>ui</span><span>::</span><span>redirect</span><span>(</span>
				<span>res</span><span>,</span>
				<span>msg</span><span>,</span>
				<span>crate</span><span>::</span><span>LoginQuery</span><span>::</span><span>msg</span><span>(</span><span>msg</span><span>.into</span><span>()))</span><span>?</span><span>;</span>
			<span>Err</span><span>(</span><span>crate</span><span>::</span><span>EarlyReturn</span><span>.into</span><span>())</span>
		<span>})</span>
<span>}</span>

<span>fn</span> <span>account</span><span>(</span>
	<span>req</span><span>:</span> <span>&amp;</span><span>actix_web</span><span>::</span><span>HttpRequest</span><span>,</span>
	<span>res</span><span>:</span> <span>&amp;</span><span>mut</span> <span>actix_web</span><span>::</span><span>HttpResponse</span><span>,</span>
<span>)</span> <span>-&gt;</span> <span>crate</span><span>::</span><span>Response</span> <span>{</span>
	<span>let</span> <span>user</span> <span>=</span> <span>require_user</span><span>(</span><span>req</span><span>,</span> <span>res</span><span>)</span><span>?</span><span>;</span>
	<span>html</span><span>(</span><span>res</span><span>,</span> <span>format!</span><span>(</span><span>"&lt;p&gt;Hello user {}&lt;/p&gt;"</span><span>,</span> <span>user</span><span>.id</span><span>))</span>
<span>}</span>
</code></pre></div>
<p>I think this code looks quite nice. <code>handle_request</code> is the main handler which calls the router and handles the response. <code>require_user</code> is an example “guard”. It is easy to write, can accept any runtime parameters to customize its behaviour and can return an arbitrary “error” response.</p>
<p>I think once “try_trait” stabilizes I will update this to a custom type but for now it is working really well. The only “ugly” code is in <code>handle_request</code> which exists only once in the whole codebase, the guards are not super pretty but fairly good and the routes which are the most frequent are very nice looking.</p>
<h2 id="conclusion"><a href="https://kevincox.ca/2022/01/01/rocket-review/#conclusion">Conclusion</a></h2>
<p>I’m very happy with the current state of the codebase on actix-web. I’ll probably continue to work on routing and URL generation to tie them together in a type-safe way, but it isn’t urgent. Simple line counts suggest that there is a slight line-count increase after migrating from Rocket to actix-web. The biggest sources of extra code are URL-generation, more manual routing and form body handling. I suspect that the current code somewhat reflects a direct translation of the “Rocket style” code with <code>FromRequest</code> guards turned into regular function calls. As I refactor I think the line count will become very similar for either version.</p></main>